diff --git a/src/check.ts b/src/check.ts index 39c2115..d187f2c 100644 --- a/src/check.ts +++ b/src/check.ts @@ -86,7 +86,7 @@ export function isIdentifierOf( node: t.Node | undefined | null, test: string | string[] | ((id: string) => boolean), ): node is t.Identifier { - return !!node && node.type === 'Identifier' && match(node.name, test) + return isIdentifier(node) && match(node.name, test) } /** @@ -388,4 +388,100 @@ export function isReferenced( return true } +export function isIdentifier( + node?: t.Node | undefined | null, +): node is t.Identifier { + return !!node && (node.type === 'Identifier' || node.type === 'JSXIdentifier') +} + +export function isStaticProperty( + node?: t.Node | undefined | null, +): node is t.ObjectProperty { + return ( + !!node && + (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') && + !node.computed + ) +} + +export function isStaticPropertyKey(node: t.Node, parent: t.Node): boolean { + return isStaticProperty(parent) && parent.key === node +} + +export function isForStatement( + stmt: t.Node, +): stmt is t.ForStatement | t.ForOfStatement | t.ForInStatement { + return ( + stmt.type === 'ForOfStatement' || + stmt.type === 'ForInStatement' || + stmt.type === 'ForStatement' + ) +} + +export function isReferencedIdentifier( + id: t.Identifier, + parent: t.Node | null | undefined, + parentStack: t.Node[], +): boolean { + if (!parent) { + return true + } + + // is a special keyword but parsed as identifier + if (id.name === 'arguments') { + return false + } + + if (isReferenced(id, parent)) { + return true + } + + // babel's isReferenced check returns false for ids being assigned to, so we + // need to cover those cases here + switch (parent.type) { + case 'AssignmentExpression': + case 'AssignmentPattern': + return true + case 'ObjectPattern': + case 'ArrayPattern': + return isInDestructureAssignment(parent, parentStack) + } + + return false +} + +export function isInDestructureAssignment( + parent: t.Node, + parentStack: t.Node[], +): boolean { + if ( + parent && + (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern') + ) { + let i = parentStack.length + while (i--) { + const p = parentStack[i] + if (p.type === 'AssignmentExpression') { + return true + } else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) { + break + } + } + } + return false +} + +export function isInNewExpression(parentStack: t.Node[]): boolean { + let i = parentStack.length + while (i--) { + const p = parentStack[i] + if (p.type === 'NewExpression') { + return true + } else if (p.type !== 'MemberExpression') { + break + } + } + return false +} + /* v8 ignore end */ diff --git a/src/extract.ts b/src/extract.ts index c60a762..059ee20 100644 --- a/src/extract.ts +++ b/src/extract.ts @@ -12,10 +12,12 @@ export function extractIdentifiers( ): t.Identifier[] { switch (node.type) { case 'Identifier': - identifiers.push(node) + case 'JSXIdentifier': + identifiers.push(node as t.Identifier) break - case 'MemberExpression': { + case 'MemberExpression': + case 'JSXMemberExpression': { let object: any = node while (object.type === 'MemberExpression') { object = object.object diff --git a/src/walk.ts b/src/walk.ts index adab988..fe0f37f 100644 --- a/src/walk.ts +++ b/src/walk.ts @@ -1,6 +1,14 @@ import { asyncWalk, walk } from 'estree-walker' -import { isExpressionType } from './check' +import { + isExpressionType, + isForStatement, + isFunctionType, + isIdentifier, + isReferencedIdentifier, +} from './check' +import { extractIdentifiers } from './extract' import { resolveString } from './resolve' +import { TS_NODE_TYPES } from './utils' import type { LiteralUnion } from './types' import type * as t from '@babel/types' @@ -219,3 +227,178 @@ export function walkExportDeclaration( setExport() } + +/** + * Modified from https://github.com/vuejs/core/blob/main/packages/compiler-core/src/babelUtils.ts + * To support browser environments and JSX. + * + * https://github.com/vuejs/core/blob/main/LICENSE + */ + +/** + * Return value indicates whether the AST walked can be a constant + */ +export function walkIdentifiers( + root: t.Node, + onIdentifier: ( + node: t.Identifier, + parent: t.Node | null | undefined, + parentStack: t.Node[], + isReference: boolean, + isLocal: boolean, + ) => void, + includeAll = false, + parentStack: t.Node[] = [], + knownIds: Record = Object.create(null), +): void { + const rootExp = + root.type === 'Program' + ? root.body[0].type === 'ExpressionStatement' && root.body[0].expression + : root + + walkAST(root, { + enter(node: t.Node & { scopeIds?: Set }, parent) { + parent && parentStack.push(parent) + if ( + parent && + parent.type.startsWith('TS') && + !TS_NODE_TYPES.includes(parent.type as any) + ) { + return this.skip() + } + if (isIdentifier(node)) { + const isLocal = !!knownIds[node.name] + const isRefed = isReferencedIdentifier(node, parent, parentStack) + if (includeAll || (isRefed && !isLocal)) { + onIdentifier(node, parent, parentStack, isRefed, isLocal) + } + } else if ( + node.type === 'ObjectProperty' && + parent?.type === 'ObjectPattern' + ) { + // mark property in destructure pattern + ;(node as any).inPattern = true + } else if (isFunctionType(node)) { + /* v8 ignore start */ + if (node.scopeIds) { + node.scopeIds.forEach((id) => markKnownIds(id, knownIds)) + /* v8 ignore end */ + } else { + // walk function expressions and add its arguments to known identifiers + // so that we don't prefix them + walkFunctionParams(node, (id) => + markScopeIdentifier(node, id, knownIds), + ) + } + } else if (node.type === 'BlockStatement') { + /* v8 ignore start */ + if (node.scopeIds) { + node.scopeIds.forEach((id) => markKnownIds(id, knownIds)) + /* v8 ignore end */ + } else { + // #3445 record block-level local variables + walkBlockDeclarations(node, (id) => + markScopeIdentifier(node, id, knownIds), + ) + } + } else if (node.type === 'CatchClause' && node.param) { + for (const id of extractIdentifiers(node.param)) { + markScopeIdentifier(node, id, knownIds) + } + } else if (isForStatement(node)) { + walkForStatement(node, false, (id) => + markScopeIdentifier(node, id, knownIds), + ) + } + }, + leave(node: t.Node & { scopeIds?: Set }, parent) { + parent && parentStack.pop() + if (node !== rootExp && node.scopeIds) { + for (const id of node.scopeIds) { + knownIds[id]-- + if (knownIds[id] === 0) { + delete knownIds[id] + } + } + } + }, + }) +} + +export function walkFunctionParams( + node: t.Function, + onIdent: (id: t.Identifier) => void, +): void { + for (const p of node.params) { + for (const id of extractIdentifiers(p)) { + onIdent(id) + } + } +} + +export function walkBlockDeclarations( + block: t.BlockStatement | t.Program, + onIdent: (node: t.Identifier) => void, +): void { + for (const stmt of block.body) { + if (stmt.type === 'VariableDeclaration') { + if (stmt.declare) continue + for (const decl of stmt.declarations) { + for (const id of extractIdentifiers(decl.id)) { + onIdent(id) + } + } + } else if ( + stmt.type === 'FunctionDeclaration' || + stmt.type === 'ClassDeclaration' + ) { + /* v8 ignore next */ + if (stmt.declare || !stmt.id) continue + onIdent(stmt.id) + } else if (isForStatement(stmt)) { + walkForStatement(stmt, true, onIdent) + } + } +} + +function walkForStatement( + stmt: t.ForStatement | t.ForOfStatement | t.ForInStatement, + isVar: boolean, + onIdent: (id: t.Identifier) => void, +) { + const variable = stmt.type === 'ForStatement' ? stmt.init : stmt.left + if ( + variable && + variable.type === 'VariableDeclaration' && + (variable.kind === 'var' ? isVar : !isVar) + ) { + for (const decl of variable.declarations) { + for (const id of extractIdentifiers(decl.id)) { + onIdent(id) + } + } + } +} + +function markKnownIds(name: string, knownIds: Record) { + if (name in knownIds) { + knownIds[name]++ + } else { + knownIds[name] = 1 + } +} + +function markScopeIdentifier( + node: t.Node & { scopeIds?: Set }, + child: t.Identifier, + knownIds: Record, +) { + const { name } = child + /* v8 ignore start */ + if (node.scopeIds && node.scopeIds.has(name)) { + return + } + /* v8 ignore end */ + markKnownIds(name, knownIds) + ;(node.scopeIds || (node.scopeIds = new Set())).add(name) +} diff --git a/tests/check.test.ts b/tests/check.test.ts index 3246ee3..5fef123 100644 --- a/tests/check.test.ts +++ b/tests/check.test.ts @@ -1,14 +1,19 @@ import { describe, expect, test } from 'vitest' import { + babelParse, isCallOf, isDeclarationType, isExpressionType, isFunctionType, isIdentifierOf, + isInDestructureAssignment, + isInNewExpression, isLiteralType, isReferenced, + isReferencedIdentifier, isTaggedFunctionCallOf, isTypeOf, + walkIdentifiers, } from '../src' import { parse as _parse } from './_utils' import type * as t from '@babel/types' @@ -177,4 +182,183 @@ describe('utils', () => { expect(isReferenced(node2.superClass!, node2)) //.toBe(true) }) }) + + describe('isReferencedIdentifier', () => { + test('identifier is referenced in a variable declaration', () => { + expect.assertions(1) + const ast = babelParse(`const a = b`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'b') { + expect(isReferencedIdentifier(node, parent, parentStack)).toBe(true) + } + }) + }) + + test('identifier is referenced in a function call', () => { + expect.assertions(1) + const ast = babelParse(`foo(bar)`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'bar') { + expect(isReferencedIdentifier(node, parent, parentStack)).toBe(true) + } + }) + }) + + test('identifier is referenced in a member expression', () => { + expect.assertions(1) + const ast = babelParse(`obj.prop`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'obj') { + expect(isReferencedIdentifier(node, parent, parentStack)).toBe(true) + } + }) + }) + + test('identifier is referenced in an assignment expression', () => { + expect.assertions(1) + const ast = babelParse(`a = b`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'b') { + expect(isReferencedIdentifier(node, parent, parentStack)).toBe(true) + } + }) + }) + + test('identifier is referenced in a return statement', () => { + expect.assertions(1) + const ast = babelParse(`function foo() { return bar }`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'bar') { + expect(isReferencedIdentifier(node, parent, parentStack)).toBe(true) + } + }) + }) + + test('identifier is referenced in a conditional expression', () => { + expect.assertions(2) + const ast = babelParse(`a ? b : c`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if ( + node.type === 'Identifier' && + (node.name === 'b' || node.name === 'c') + ) { + expect(isReferencedIdentifier(node, parent, parentStack)).toBe(true) + } + }) + }) + }) + + describe('isInNewExpression', () => { + test('identifier in NewExpression', () => { + expect.assertions(1) + const ast = babelParse(`new Foo()`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'Foo') { + expect(isInNewExpression(parentStack)).toBe(true) + } + }) + }) + + test('identifier not in NewExpression', () => { + expect.assertions(1) + const ast = babelParse(`Foo()`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'Foo') { + expect(isInNewExpression(parentStack)).toBe(false) + } + }) + }) + + test('identifier in nested MemberExpression within NewExpression', () => { + expect.assertions(1) + const ast = babelParse(`new Foo.Bar()`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'Foo') { + expect(isInNewExpression(parentStack)).toBe(true) + } + }) + }) + + test('identifier in deeply nested MemberExpression within NewExpression', () => { + expect.assertions(1) + const ast = babelParse(`new Foo.Bar.Baz()`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'Foo') { + expect(isInNewExpression(parentStack)).toBe(true) + } + }) + }) + + test('identifier in MemberExpression not in NewExpression', () => { + expect.assertions(1) + const ast = babelParse(`Foo.Bar()`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'Foo') { + expect(isInNewExpression(parentStack)).toBe(false) + } + }) + }) + }) + + describe('isInDestructureAssignment', () => { + test('identifier in object destructure assignment', () => { + expect.assertions(1) + const ast = babelParse(`({ a: c } = obj)`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'c') { + expect(isInDestructureAssignment(parent!, parentStack)).toBe(true) + } + }) + }) + + test('identifier in array destructure assignment', () => { + expect.assertions(1) + const ast = babelParse(`[a, b] = arr`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'a') { + expect(isInDestructureAssignment(parent!, parentStack)).toBe(true) + } + }) + }) + + test('identifier in nested object destructure assignment', () => { + expect.assertions(1) + const ast = babelParse(`({ a: { b: c } } = obj)`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'c') { + expect(isInDestructureAssignment(parent!, parentStack)).toBe(true) + } + }) + }) + + test('identifier in nested array destructure assignment', () => { + expect.assertions(1) + const ast = babelParse(`[[a], b] = arr`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'a') { + expect(isInDestructureAssignment(parent!, parentStack)).toBe(true) + } + }) + }) + + test('identifier in mixed destructure assignment', () => { + expect.assertions(1) + const ast = babelParse(`({ a: [b, c] } = obj)`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'b') { + expect(isInDestructureAssignment(parent!, parentStack)).toBe(true) + } + }) + }) + + test('identifier in destructure assignment with default value', () => { + expect.assertions(1) + const ast = babelParse(`({ a = 1 } = obj)`, 'ts') + walkIdentifiers(ast.body[0], (node, parent, parentStack) => { + if (node.type === 'Identifier' && node.name === 'a') { + expect(isInDestructureAssignment(parent!, parentStack)).toBe(false) + } + }) + }) + }) }) diff --git a/tests/walk.test.ts b/tests/walk.test.ts index 5073072..136a9f6 100644 --- a/tests/walk.test.ts +++ b/tests/walk.test.ts @@ -2,11 +2,15 @@ import { describe, expect, test } from 'vitest' import { babelParse, isTypeOf, + walkBlockDeclarations, walkExportDeclaration, + walkFunctionParams, + walkIdentifiers, walkImportDeclaration, type ExportBinding, type ImportBinding, } from '../src' +import type { BlockStatement, FunctionDeclaration } from '@babel/types' describe('walk', () => { test('walkImportDeclaration', () => { @@ -169,4 +173,298 @@ describe('walk', () => { expect(mapExports(exports)).toMatchSnapshot() }) }) + + describe('walkIdentifiers', () => { + test('JSXIdentifier', () => { + const ast = babelParse( + ` + function Comp({ Foo }){ + const a = 1 + return + } + `, + 'tsx', + ) + walkIdentifiers((ast.body[0] as FunctionDeclaration).body, (id) => { + expect(id.name).toBe('Foo') + }) + }) + + test('JSXMemberExpression', () => { + const ast = babelParse( + ` + function Comp(props){ + return + } + `, + 'tsx', + ) + + walkIdentifiers((ast.body[0] as FunctionDeclaration).body, (id) => { + expect(id.name).toBe('props') + }) + }) + + test('nested identifiers', () => { + const ast = babelParse( + ` + function nested() { + const a = 1; + function inner() { + const b = 2; + return a + b; + } + return inner(); + } + `, + 'ts', + ) + const identifiers: string[] = [] + walkIdentifiers( + (ast.body[0] as FunctionDeclaration).body, + (id) => { + identifiers.push(id.name) + }, + true, + ) + expect(identifiers).toEqual(['a', 'inner', 'b', 'a', 'b', 'inner']) + }) + + test('object pattern destructuring', () => { + const ast = babelParse( + ` + function destructure({ x, y }) { + return x + y; + } + `, + 'ts', + ) + const identifiers: string[] = [] + walkIdentifiers((ast.body[0] as FunctionDeclaration).body, (id) => { + identifiers.push(id.name) + }) + expect(identifiers).toEqual(['x', 'y']) + }) + + test('array pattern destructuring', () => { + const ast = babelParse( + ` + function destructure([a, b]) { + return a + b; + } + `, + 'ts', + ) + const identifiers: string[] = [] + walkIdentifiers((ast.body[0] as FunctionDeclaration).body, (id) => { + identifiers.push(id.name) + }) + expect(identifiers).toEqual(['a', 'b']) + }) + + test('catch clause identifiers', () => { + const ast = babelParse( + ` + try { + throw new Error('test'); + } catch (error) { + ;[error] + } + `, + 'ts', + ) + const identifiers: string[] = [] + walkIdentifiers( + (ast.body[0] as any).handler, + (id) => { + identifiers.push(id.name) + }, + true, + ) + expect(identifiers).toEqual(['error', 'error']) + }) + + test('for loop identifiers', () => { + const ast = babelParse( + ` + for (let i = 0; i < 10; i++) { + ;[i] + } + `, + 'ts', + ) + const identifiers: string[] = [] + walkIdentifiers( + ast.body[0] as any, + (id, _, __, isReference) => { + if (isReference) identifiers.push(id.name) + }, + true, + ) + expect(identifiers).toEqual(['i', 'i', 'i']) + }) + + test('function parameters', () => { + const ast = babelParse( + ` + function params(a, b, c) { + return a + b + c; + function inner(a, b, c) { + return a + b + c; + } + } + `, + 'ts', + ) + const identifiers: string[] = [] + walkIdentifiers( + ast.body[0] as FunctionDeclaration, + (id) => { + identifiers.push(id.name) + }, + true, + ) + expect(identifiers).toEqual([ + 'params', + 'a', + 'b', + 'c', + 'a', + 'b', + 'c', + 'inner', + 'a', + 'b', + 'c', + 'a', + 'b', + 'c', + ]) + }) + + test('ignore type annotations', () => { + const ast = babelParse( + ` + function typed(a: number, b: string): void { + ;[a, b] + }`, + 'ts', + ) + const identifiers: string[] = [] + walkIdentifiers( + ast.body[0] as FunctionDeclaration, + (id) => { + identifiers.push(id.name) + }, + true, + ) + expect(identifiers).toEqual(['typed', 'a', 'b', 'a', 'b']) + }) + + test('walk ExpressionStatement', () => { + const ast = babelParse(`a`, 'ts') + walkIdentifiers(ast, (id) => { + expect(id.name).toBe('a') + }) + }) + }) + + test('walkFunctionParams', () => { + const ast = babelParse(`function Comp({ foo }){}`, 'ts') + walkFunctionParams(ast.body[0] as FunctionDeclaration, (id) => { + expect(id.name).toBe('foo') + }) + }) + + describe('walkBlockDeclarations', () => { + test('variable declarations', () => { + const ast = babelParse( + ` + { + let a = 1; + const b = 2; + var c = 3; + } + `, + 'ts', + ) + const identifiers: string[] = [] + walkBlockDeclarations(ast.body[0] as BlockStatement, (id) => { + identifiers.push(id.name) + }) + expect(identifiers).toEqual(['a', 'b', 'c']) + }) + + test('function and class declarations', () => { + const ast = babelParse( + ` + { + function foo() {} + class Bar {} + } + `, + 'ts', + ) + const identifiers: string[] = [] + walkBlockDeclarations(ast.body[0] as BlockStatement, (id) => { + identifiers.push(id.name) + }) + expect(identifiers).toEqual(['foo', 'Bar']) + }) + + test('for loop variable declarations', () => { + const ast = babelParse( + ` + { + for (let i = 0; i < 10; i++) {} + for (const j of [1, 2, 3]) {} + for (var k in { a: 1, b: 2 }) {} + } + `, + 'ts', + ) + const identifiers: string[] = [] + walkBlockDeclarations(ast.body[0] as any, (id) => { + identifiers.push(id.name) + }) + expect(identifiers).toEqual(['k']) + }) + + test('nested block declarations', () => { + const ast = babelParse( + ` + { + { + let x = 1; + const y = 2; + } + var z = 3; + } + `, + 'ts', + ) + const identifiers: string[] = [] + walkBlockDeclarations(ast.body[0] as any, (id) => { + identifiers.push(id.name) + }) + expect(identifiers).toEqual(['z']) + }) + + test('ignore declared variables', () => { + const ast = babelParse( + ` + { + declare const a: number; + declare function foo(): void; + } + `, + 'ts', + ) + const identifiers: string[] = [] + walkBlockDeclarations(ast.body[0] as any, (id) => { + identifiers.push(id.name) + }) + expect(identifiers).toEqual([]) + }) + }) })