/
Identifier.ts
290 lines (264 loc) · 8.36 KB
/
Identifier.ts
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
import isReference, { type NodeWithFieldDefinition } from 'is-reference';
import type MagicString from 'magic-string';
import type { NormalizedTreeshakingOptions } from '../../rollup/types';
import { BLANK } from '../../utils/blank';
import type { NodeRenderOptions, RenderOptions } from '../../utils/renderHelpers';
import type { DeoptimizableEntity } from '../DeoptimizableEntity';
import type { HasEffectsContext, InclusionContext } from '../ExecutionContext';
import type { NodeInteractionWithThisArg } from '../NodeInteractions';
import {
INTERACTION_ACCESSED,
INTERACTION_ASSIGNED,
INTERACTION_CALLED,
NODE_INTERACTION_UNKNOWN_ACCESS,
NodeInteraction,
NodeInteractionCalled
} from '../NodeInteractions';
import type FunctionScope from '../scopes/FunctionScope';
import { EMPTY_PATH, type ObjectPath, type PathTracker } from '../utils/PathTracker';
import GlobalVariable from '../variables/GlobalVariable';
import LocalVariable from '../variables/LocalVariable';
import type Variable from '../variables/Variable';
import * as NodeType from './NodeType';
import type SpreadElement from './SpreadElement';
import {
type ExpressionEntity,
type LiteralValueOrUnknown,
UNKNOWN_EXPRESSION
} from './shared/Expression';
import { NodeBase } from './shared/Node';
import type { PatternNode } from './shared/Pattern';
export type IdentifierWithVariable = Identifier & { variable: Variable };
const tdzVariableKinds = {
__proto__: null,
class: true,
const: true,
let: true,
var: true
};
export default class Identifier extends NodeBase implements PatternNode {
declare name: string;
declare type: NodeType.tIdentifier;
variable: Variable | null = null;
private isTDZAccess: boolean | null = null;
addExportedVariables(
variables: Variable[],
exportNamesByVariable: ReadonlyMap<Variable, readonly string[]>
): void {
if (exportNamesByVariable.has(this.variable!)) {
variables.push(this.variable!);
}
}
bind(): void {
if (!this.variable && isReference(this, this.parent as NodeWithFieldDefinition)) {
this.variable = this.scope.findVariable(this.name);
this.variable.addReference(this);
}
}
declare(kind: string, init: ExpressionEntity): LocalVariable[] {
let variable: LocalVariable;
const { treeshake } = this.context.options;
switch (kind) {
case 'var':
variable = this.scope.addDeclaration(this, this.context, init, true);
if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
// Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
variable.markInitializersForDeoptimization();
}
break;
case 'function':
// in strict mode, functions are only hoisted within a scope but not across block scopes
variable = this.scope.addDeclaration(this, this.context, init, false);
break;
case 'let':
case 'const':
case 'class':
variable = this.scope.addDeclaration(this, this.context, init, false);
break;
case 'parameter':
variable = (this.scope as FunctionScope).addParameterDeclaration(this);
break;
/* istanbul ignore next */
default:
/* istanbul ignore next */
throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
}
variable.kind = kind;
return [(this.variable = variable)];
}
deoptimizePath(path: ObjectPath): void {
if (path.length === 0 && !this.scope.contains(this.name)) {
this.disallowImportReassignment();
}
// We keep conditional chaining because an unknown Node could have an
// Identifier as property that might be deoptimized by default
this.variable?.deoptimizePath(path);
}
deoptimizeThisOnInteractionAtPath(
interaction: NodeInteractionWithThisArg,
path: ObjectPath,
recursionTracker: PathTracker
): void {
this.variable!.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
}
getLiteralValueAtPath(
path: ObjectPath,
recursionTracker: PathTracker,
origin: DeoptimizableEntity
): LiteralValueOrUnknown {
return this.getVariableRespectingTDZ()!.getLiteralValueAtPath(path, recursionTracker, origin);
}
getReturnExpressionWhenCalledAtPath(
path: ObjectPath,
interaction: NodeInteractionCalled,
recursionTracker: PathTracker,
origin: DeoptimizableEntity
): ExpressionEntity {
return this.getVariableRespectingTDZ()!.getReturnExpressionWhenCalledAtPath(
path,
interaction,
recursionTracker,
origin
);
}
hasEffects(context: HasEffectsContext): boolean {
if (!this.deoptimized) this.applyDeoptimizations();
if (this.isPossibleTDZ() && this.variable!.kind !== 'var') {
return true;
}
return (
(this.context.options.treeshake as NormalizedTreeshakingOptions).unknownGlobalSideEffects &&
this.variable instanceof GlobalVariable &&
this.variable.hasEffectsOnInteractionAtPath(
EMPTY_PATH,
NODE_INTERACTION_UNKNOWN_ACCESS,
context
)
);
}
hasEffectsOnInteractionAtPath(
path: ObjectPath,
interaction: NodeInteraction,
context: HasEffectsContext
): boolean {
switch (interaction.type) {
case INTERACTION_ACCESSED:
return (
this.variable !== null &&
this.getVariableRespectingTDZ()!.hasEffectsOnInteractionAtPath(path, interaction, context)
);
case INTERACTION_ASSIGNED:
return (
path.length > 0 ? this.getVariableRespectingTDZ() : this.variable
)!.hasEffectsOnInteractionAtPath(path, interaction, context);
case INTERACTION_CALLED:
return this.getVariableRespectingTDZ()!.hasEffectsOnInteractionAtPath(
path,
interaction,
context
);
}
}
include(): void {
if (!this.deoptimized) this.applyDeoptimizations();
if (!this.included) {
this.included = true;
if (this.variable !== null) {
this.context.includeVariableInModule(this.variable);
}
}
}
includeCallArguments(
context: InclusionContext,
args: readonly (ExpressionEntity | SpreadElement)[]
): void {
this.variable!.includeCallArguments(context, args);
}
isPossibleTDZ(): boolean {
// return cached value to avoid issues with the next tree-shaking pass
if (this.isTDZAccess !== null) return this.isTDZAccess;
if (
!(this.variable instanceof LocalVariable) ||
!this.variable.kind ||
!(this.variable.kind in tdzVariableKinds)
) {
return (this.isTDZAccess = false);
}
let decl_id;
if (
this.variable.declarations &&
this.variable.declarations.length === 1 &&
(decl_id = this.variable.declarations[0] as any) &&
this.start < decl_id.start &&
closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)
) {
// a variable accessed before its declaration
// in the same function or at top level of module
return (this.isTDZAccess = true);
}
if (!this.variable.initReached) {
// Either a const/let TDZ violation or
// var use before declaration was encountered.
return (this.isTDZAccess = true);
}
return (this.isTDZAccess = false);
}
markDeclarationReached(): void {
this.variable!.initReached = true;
}
render(
code: MagicString,
{ snippets: { getPropertyAccess } }: RenderOptions,
{ renderedParentType, isCalleeOfRenderedParent, isShorthandProperty }: NodeRenderOptions = BLANK
): void {
if (this.variable) {
const name = this.variable.getName(getPropertyAccess);
if (name !== this.name) {
code.overwrite(this.start, this.end, name, {
contentOnly: true,
storeName: true
});
if (isShorthandProperty) {
code.prependRight(this.start, `${this.name}: `);
}
}
// In strict mode, any variable named "eval" must be the actual "eval" function
if (
name === 'eval' &&
renderedParentType === NodeType.CallExpression &&
isCalleeOfRenderedParent
) {
code.appendRight(this.start, '0, ');
}
}
}
protected applyDeoptimizations(): void {
this.deoptimized = true;
if (this.variable instanceof LocalVariable) {
this.variable.consolidateInitializers();
this.context.requestTreeshakingPass();
}
}
private disallowImportReassignment(): never {
return this.context.error(
{
code: 'ILLEGAL_REASSIGNMENT',
message: `Illegal reassignment to import '${this.name}'`
},
this.start
);
}
private getVariableRespectingTDZ(): ExpressionEntity | null {
if (this.isPossibleTDZ()) {
return UNKNOWN_EXPRESSION;
}
return this.variable;
}
}
function closestParentFunctionOrProgram(node: any): any {
while (node && !/^Program|Function/.test(node.type)) {
node = node.parent;
}
// one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
return node;
}