fcs
2025-04-10 0163870d662dc5b7d69ceff977490ede594f7d82
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
import assertNever from 'assert-never';
import {ancestor as walk} from 'babel-walk';
import * as t from '@babel/types';
import isReferenced from './reference';
 
const isScope = (node: t.Node) => t.isFunctionParent(node) || t.isProgram(node);
const isBlockScope = (node: t.Node) =>
  t.isBlockStatement(node) || isScope(node);
 
const declaresArguments = (node: t.Node) =>
  t.isFunction(node) && !t.isArrowFunctionExpression(node);
 
const declaresThis = declaresArguments;
 
const LOCALS_SYMBOL = Symbol('locals');
 
const getLocals = (node: t.Node): Set<string> | undefined =>
  (node as any)[LOCALS_SYMBOL];
const declareLocals = (node: t.Node): Set<string> =>
  ((node as any)[LOCALS_SYMBOL] = (node as any)[LOCALS_SYMBOL] || new Set());
 
const setLocal = (node: t.Node, name: string) => declareLocals(node).add(name);
 
// First pass
 
function declareFunction(node: t.Function) {
  for (const param of node.params) {
    declarePattern(param, node);
  }
  const id = (node as t.FunctionDeclaration).id;
  if (id) {
    setLocal(node, id.name);
  }
}
 
function declarePattern(node: t.LVal, parent: t.Node) {
  switch (node.type) {
    case 'Identifier':
      setLocal(parent, node.name);
      break;
    case 'ObjectPattern':
      for (const prop of node.properties) {
        switch (prop.type) {
          case 'RestElement':
            declarePattern(prop.argument, parent);
            break;
          case 'ObjectProperty':
            declarePattern(prop.value as t.LVal, parent);
            break;
          default:
            assertNever(prop);
            break;
        }
      }
      break;
    case 'ArrayPattern':
      for (const element of node.elements) {
        if (element) declarePattern(element, parent);
      }
      break;
    case 'RestElement':
      declarePattern(node.argument, parent);
      break;
    case 'AssignmentPattern':
      declarePattern(node.left, parent);
      break;
    // istanbul ignore next
    default:
      throw new Error('Unrecognized pattern type: ' + node.type);
  }
}
 
function declareModuleSpecifier(
  node:
    | t.ImportSpecifier
    | t.ImportDefaultSpecifier
    | t.ImportNamespaceSpecifier,
  _state: unknown,
  parents: t.Node[],
) {
  for (let i = parents.length - 2; i >= 0; i--) {
    if (isScope(parents[i])) {
      setLocal(parents[i], node.local.name);
      return;
    }
  }
}
 
const firstPass = walk({
  VariableDeclaration(node, _state, parents) {
    for (let i = parents.length - 2; i >= 0; i--) {
      if (
        node.kind === 'var'
          ? t.isFunctionParent(parents[i])
          : isBlockScope(parents[i])
      ) {
        for (const declaration of node.declarations) {
          declarePattern(declaration.id, parents[i]);
        }
        return;
      }
    }
  },
  FunctionDeclaration(node, _state, parents) {
    if (node.id) {
      for (let i = parents.length - 2; i >= 0; i--) {
        if (isScope(parents[i])) {
          setLocal(parents[i], node.id.name);
          return;
        }
      }
    }
  },
  Function: declareFunction,
  ClassDeclaration(node, _state, parents) {
    for (let i = parents.length - 2; i >= 0; i--) {
      if (isScope(parents[i])) {
        setLocal(parents[i], node.id.name);
        return;
      }
    }
  },
  TryStatement(node) {
    if (node.handler === null) return;
    if (node.handler.param === null) return;
    declarePattern(node.handler.param, node.handler);
  },
  ImportDefaultSpecifier: declareModuleSpecifier,
  ImportSpecifier: declareModuleSpecifier,
  ImportNamespaceSpecifier: declareModuleSpecifier,
});
 
// Second pass
 
const secondPass = walk<{
  globals: (t.Identifier | t.ThisExpression)[];
}>({
  Identifier(node, state, parents) {
    const name = node.name;
    if (name === 'undefined') return;
 
    const lastParent = parents[parents.length - 2];
    if (lastParent) {
      if (!isReferenced(node, lastParent)) return;
 
      for (const parent of parents) {
        if (name === 'arguments' && declaresArguments(parent)) {
          return;
        }
        if (getLocals(parent)?.has(name)) {
          return;
        }
      }
    }
 
    state.globals.push(node);
  },
 
  ThisExpression(node, state, parents) {
    for (const parent of parents) {
      if (declaresThis(parent)) {
        return;
      }
    }
 
    state.globals.push(node);
  },
});
 
export default function findGlobals(ast: t.Node) {
  const globals: (t.Identifier | t.ThisExpression)[] = [];
 
  // istanbul ignore if
  if (!t.isNode(ast)) {
    throw new TypeError('Source must be a Babylon AST');
  }
 
  firstPass(ast, undefined);
  secondPass(ast, {globals});
 
  const groupedGlobals = new Map<string, (t.Identifier | t.ThisExpression)[]>();
  for (const node of globals) {
    const name: string = node.type === 'ThisExpression' ? 'this' : node.name;
    const existing = groupedGlobals.get(name);
    if (existing) {
      existing.push(node);
    } else {
      groupedGlobals.set(name, [node]);
    }
  }
 
  return [...groupedGlobals]
    .map(([name, nodes]) => ({name, nodes}))
    .sort((a, b) => (a.name < b.name ? -1 : 1));
}