Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(compiler-core): improve the isMemberExpression function #3675

Merged
merged 1 commit into from
May 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion packages/compiler-core/__tests__/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { Position } from '../src/ast'
import { getInnerRange, advancePositionWithClone } from '../src/utils'
import {
getInnerRange,
advancePositionWithClone,
isMemberExpression
} from '../src/utils'

function p(line: number, column: number, offset: number): Position {
return { column, line, offset }
Expand Down Expand Up @@ -67,3 +71,19 @@ describe('getInnerRange', () => {
expect(loc2.end.offset).toBe(7)
})
})

test('isMemberExpression', () => {
// should work
expect(isMemberExpression('obj.foo')).toBe(true)
expect(isMemberExpression('obj[foo]')).toBe(true)
expect(isMemberExpression('obj[arr[0]]')).toBe(true)
expect(isMemberExpression('obj[arr[ret.bar]]')).toBe(true)
expect(isMemberExpression('obj[arr[ret[bar]]]')).toBe(true)
expect(isMemberExpression('obj[arr[ret[bar]]].baz')).toBe(true)
expect(isMemberExpression('obj[1 + 1]')).toBe(true)
// should warning
expect(isMemberExpression('obj[foo')).toBe(false)
expect(isMemberExpression('objfoo]')).toBe(false)
expect(isMemberExpression('obj[arr[0]')).toBe(false)
expect(isMemberExpression('obj[arr0]]')).toBe(false)
})
8 changes: 6 additions & 2 deletions packages/compiler-core/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,14 @@ const nonIdentifierRE = /^\d|[^\$\w]/
export const isSimpleIdentifier = (name: string): boolean =>
!nonIdentifierRE.test(name)

const memberExpRE = /^[A-Za-z_$\xA0-\uFFFF][\w$\xA0-\uFFFF]*(?:\s*\.\s*[A-Za-z_$\xA0-\uFFFF][\w$\xA0-\uFFFF]*|\[[^\]]+\])*$/
const memberExpRE = /^[A-Za-z_$\xA0-\uFFFF][\w$\xA0-\uFFFF]*(?:\s*\.\s*[A-Za-z_$\xA0-\uFFFF][\w$\xA0-\uFFFF]*|\[(.+)\])*$/
export const isMemberExpression = (path: string): boolean => {
if (!path) return false
return memberExpRE.test(path.trim())
const matched = memberExpRE.exec(path.trim())
if (!matched) return false
if (!matched[1]) return true
if (!/[\[\]]/.test(matched[1])) return true
return isMemberExpression(matched[1].trim())
}

export function getInnerRange(
Expand Down