All files / compiler-core/src babelUtils.ts

87.77% Statements 316/360
78.39% Branches 127/162
100% Functions 18/18
87.77% Lines 316/360

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 5132x                                   2x 336x 336x             336x 336x 336x 336x 336x       336x 336x 4x 332x   336x 336x 1628x 1628x 1628x 1292x 8x 1628x 4x 4x 1628x 594x 594x 594x 491x 491x 594x 1030x   178x 1030x   78x 1030x 75x 3x 75x     72x 43x 72x 72x 952x 61x   61x   61x 6x 61x 61x 877x 2x 2x 2x 816x 4x 3x 4x 4x 1628x 336x 1608x 1608x 14x 18x 18x 18x 18x 18x 14x 1608x 336x 336x   2x 772x 772x 772x 772x 772x       772x 4x 4x     772x       768x 418x 418x       350x 771x 772x 57x 772x 772x 2x 772x   291x 291x   2x 63x 63x 63x 63x 63x 63x 63x 23x 23x 50x 50x 5x 50x 18x 18x 50x 23x 58x 58x   2x 61x 61x 66x 66x 2x 66x 59x 59x 66x 59x 59x   2x 81x 81x 81x 81x 41x 45x 45x 41x 81x   2x 61x 61x 61x 61x 35x 5x 5x 5x 5x 5x 5x 5x 30x 30x 30x     30x 4x 4x 35x 61x   844x 844x 844x 844x 844x 842x 840x   844x   8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4x 4x 4x 4x 4x 4x 8x   2x 203x 203x 203x 203x 203x 114x 114x   203x               203x 61x 82x 2x 82x 80x 80x 82x 61x   203x 2x 2x 2x 2x   203x       203x 26x 26x 203x   203x 203x   58x 58x 4x 58x 54x 54x 58x   54x 54x 54x 54x 54x 54x 54x     54x 54x 54x   2x 4894x 4894x   2x 606x 603x 167x   2x 413x                     768x 768x       768x 768x 90x 48x 48x 42x   768x       768x 27x       768x 19x           768x           768x 768x 768x 4x 4x 4x             768x 317x 194x 194x   317x       768x         768x         768x 768x         768x 19x       768x 54x     768x       768x 1x     768x 4x   768x 768x         768x 768x 3x       768x 768x           768x                         768x 768x 768x 10x     768x       768x         768x 768x 2x       768x         768x         768x         768x           768x   218x 218x   2x 2x 2x 2x 2x 2x 2x   2x 1179x 13x 1179x 1166x 1166x 1179x  
// should only use types from @babel/types
// do not import runtime methods
import type {
  BlockStatement,
  ForInStatement,
  ForOfStatement,
  ForStatement,
  Function,
  Identifier,
  Node,
  ObjectProperty,
  Program,
} from '@babel/types'
import { walk } from 'estree-walker'
 
/**
 * Return value indicates whether the AST walked can be a constant
 */
export function walkIdentifiers(
  root: Node,
  onIdentifier: (
    node: Identifier,
    parent: Node | null,
    parentStack: Node[],
    isReference: boolean,
    isLocal: boolean,
  ) => void,
  includeAll = false,
  parentStack: Node[] = [],
  knownIds: Record<string, number> = Object.create(null),
): void {
  if (__BROWSER__) {
    return
  }
 
  const rootExp =
    root.type === 'Program'
      ? root.body[0].type === 'ExpressionStatement' && root.body[0].expression
      : root
 
  walk(root, {
    enter(node: Node & { scopeIds?: Set<string> }, parent: Node | null) {
      parent && parentStack.push(parent)
      if (
        parent &&
        parent.type.startsWith('TS') &&
        !TS_NODE_TYPES.includes(parent.type)
      ) {
        return this.skip()
      }
      if (node.type === 'Identifier') {
        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' &&
        // eslint-disable-next-line no-restricted-syntax
        parent?.type === 'ObjectPattern'
      ) {
        // mark property in destructure pattern
        ;(node as any).inPattern = true
      } else if (isFunctionType(node)) {
        if (node.scopeIds) {
          node.scopeIds.forEach(id => markKnownIds(id, knownIds))
        } 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') {
        if (node.scopeIds) {
          node.scopeIds.forEach(id => markKnownIds(id, knownIds))
        } 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: Node & { scopeIds?: Set<string> }, parent: Node | null) {
      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 isReferencedIdentifier(
  id: Identifier,
  parent: Node | null,
  parentStack: Node[],
): boolean {
  if (__BROWSER__) {
    return false
  }
 
  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: Node,
  parentStack: 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: 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
}
 
export function walkFunctionParams(
  node: Function,
  onIdent: (id: Identifier) => void,
): void {
  for (const p of node.params) {
    for (const id of extractIdentifiers(p)) {
      onIdent(id)
    }
  }
}
 
export function walkBlockDeclarations(
  block: BlockStatement | Program,
  onIdent: (node: 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'
    ) {
      if (stmt.declare || !stmt.id) continue
      onIdent(stmt.id)
    } else if (isForStatement(stmt)) {
      walkForStatement(stmt, true, onIdent)
    }
  }
}
 
function isForStatement(
  stmt: Node,
): stmt is ForStatement | ForOfStatement | ForInStatement {
  return (
    stmt.type === 'ForOfStatement' ||
    stmt.type === 'ForInStatement' ||
    stmt.type === 'ForStatement'
  )
}
 
function walkForStatement(
  stmt: ForStatement | ForOfStatement | ForInStatement,
  isVar: boolean,
  onIdent: (id: 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)
      }
    }
  }
}
 
export function extractIdentifiers(
  param: Node,
  nodes: Identifier[] = [],
): Identifier[] {
  switch (param.type) {
    case 'Identifier':
      nodes.push(param)
      break
 
    case 'MemberExpression':
      let object: any = param
      while (object.type === 'MemberExpression') {
        object = object.object
      }
      nodes.push(object)
      break
 
    case 'ObjectPattern':
      for (const prop of param.properties) {
        if (prop.type === 'RestElement') {
          extractIdentifiers(prop.argument, nodes)
        } else {
          extractIdentifiers(prop.value, nodes)
        }
      }
      break
 
    case 'ArrayPattern':
      param.elements.forEach(element => {
        if (element) extractIdentifiers(element, nodes)
      })
      break
 
    case 'RestElement':
      extractIdentifiers(param.argument, nodes)
      break
 
    case 'AssignmentPattern':
      extractIdentifiers(param.left, nodes)
      break
  }
 
  return nodes
}
 
function markKnownIds(name: string, knownIds: Record<string, number>) {
  if (name in knownIds) {
    knownIds[name]++
  } else {
    knownIds[name] = 1
  }
}
 
function markScopeIdentifier(
  node: Node & { scopeIds?: Set<string> },
  child: Identifier,
  knownIds: Record<string, number>,
) {
  const { name } = child
  if (node.scopeIds && node.scopeIds.has(name)) {
    return
  }
  markKnownIds(name, knownIds)
  ;(node.scopeIds || (node.scopeIds = new Set())).add(name)
}
 
export const isFunctionType = (node: Node): node is Function => {
  return /Function(?:Expression|Declaration)$|Method$/.test(node.type)
}
 
export const isStaticProperty = (node: Node): node is ObjectProperty =>
  node &&
  (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  !node.computed
 
export const isStaticPropertyKey = (node: Node, parent: Node): boolean =>
  isStaticProperty(parent) && parent.key === node
 
/**
 * Copied from https://github.com/babel/babel/blob/main/packages/babel-types/src/validators/isReferenced.ts
 * To avoid runtime dependency on @babel/types (which includes process references)
 * This file should not change very often in babel but we may need to keep it
 * up-to-date from time to time.
 *
 * https://github.com/babel/babel/blob/main/LICENSE
 *
 */
function isReferenced(node: Node, parent: Node, grandparent?: Node): boolean {
  switch (parent.type) {
    // yes: PARENT[NODE]
    // yes: NODE.child
    // no: parent.NODE
    case 'MemberExpression':
    case 'OptionalMemberExpression':
      if (parent.property === node) {
        return !!parent.computed
      }
      return parent.object === node
 
    case 'JSXMemberExpression':
      return parent.object === node
    // no: let NODE = init;
    // yes: let id = NODE;
    case 'VariableDeclarator':
      return parent.init === node
 
    // yes: () => NODE
    // no: (NODE) => {}
    case 'ArrowFunctionExpression':
      return parent.body === node
 
    // no: class { #NODE; }
    // no: class { get #NODE() {} }
    // no: class { #NODE() {} }
    // no: class { fn() { return this.#NODE; } }
    case 'PrivateName':
      return false
 
    // no: class { NODE() {} }
    // yes: class { [NODE]() {} }
    // no: class { foo(NODE) {} }
    case 'ClassMethod':
    case 'ClassPrivateMethod':
    case 'ObjectMethod':
      if (parent.key === node) {
        return !!parent.computed
      }
      return false
 
    // yes: { [NODE]: "" }
    // no: { NODE: "" }
    // depends: { NODE }
    // depends: { key: NODE }
    case 'ObjectProperty':
      if (parent.key === node) {
        return !!parent.computed
      }
      // parent.value === node
      return !grandparent || grandparent.type !== 'ObjectPattern'
    // no: class { NODE = value; }
    // yes: class { [NODE] = value; }
    // yes: class { key = NODE; }
    case 'ClassProperty':
      if (parent.key === node) {
        return !!parent.computed
      }
      return true
    case 'ClassPrivateProperty':
      return parent.key !== node
 
    // no: class NODE {}
    // yes: class Foo extends NODE {}
    case 'ClassDeclaration':
    case 'ClassExpression':
      return parent.superClass === node
 
    // yes: left = NODE;
    // no: NODE = right;
    case 'AssignmentExpression':
      return parent.right === node
 
    // no: [NODE = foo] = [];
    // yes: [foo = NODE] = [];
    case 'AssignmentPattern':
      return parent.right === node
 
    // no: NODE: for (;;) {}
    case 'LabeledStatement':
      return false
 
    // no: try {} catch (NODE) {}
    case 'CatchClause':
      return false
 
    // no: function foo(...NODE) {}
    case 'RestElement':
      return false
 
    case 'BreakStatement':
    case 'ContinueStatement':
      return false
 
    // no: function NODE() {}
    // no: function foo(NODE) {}
    case 'FunctionDeclaration':
    case 'FunctionExpression':
      return false
 
    // no: export NODE from "foo";
    // no: export * as NODE from "foo";
    case 'ExportNamespaceSpecifier':
    case 'ExportDefaultSpecifier':
      return false
 
    // no: export { foo as NODE };
    // yes: export { NODE as foo };
    // no: export { NODE as foo } from "foo";
    case 'ExportSpecifier':
      // @ts-expect-error
      // eslint-disable-next-line no-restricted-syntax
      if (grandparent?.source) {
        return false
      }
      return parent.local === node
 
    // no: import NODE from "foo";
    // no: import * as NODE from "foo";
    // no: import { NODE as foo } from "foo";
    // no: import { foo as NODE } from "foo";
    // no: import NODE from "bar";
    case 'ImportDefaultSpecifier':
    case 'ImportNamespaceSpecifier':
    case 'ImportSpecifier':
      return false
 
    // no: import "foo" assert { NODE: "json" }
    case 'ImportAttribute':
      return false
 
    // no: <div NODE="foo" />
    case 'JSXAttribute':
      return false
 
    // no: [NODE] = [];
    // no: ({ NODE }) = [];
    case 'ObjectPattern':
    case 'ArrayPattern':
      return false
 
    // no: new.NODE
    // no: NODE.target
    case 'MetaProperty':
      return false
 
    // yes: type X = { someProperty: NODE }
    // no: type X = { NODE: OtherType }
    case 'ObjectTypeProperty':
      return parent.key !== node
 
    // yes: enum X { Foo = NODE }
    // no: enum X { NODE }
    case 'TSEnumMember':
      return parent.id !== node
 
    // yes: { [NODE]: value }
    // no: { NODE: value }
    case 'TSPropertySignature':
      if (parent.key === node) {
        return !!parent.computed
      }
 
      return true
  }
 
  return true
}
 
export const TS_NODE_TYPES: string[] = [
  'TSAsExpression', // foo as number
  'TSTypeAssertion', // (<number>foo)
  'TSNonNullExpression', // foo!
  'TSInstantiationExpression', // foo<string>
  'TSSatisfiesExpression', // foo satisfies T
]
 
export function unwrapTSNode(node: Node): Node {
  if (TS_NODE_TYPES.includes(node.type)) {
    return unwrapTSNode((node as any).expression)
  } else {
    return node
  }
}