/
MemberExpression.ts
325 lines (301 loc) · 10.1 KB
/
MemberExpression.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
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
import MagicString from 'magic-string';
import { NormalizedTreeshakingOptions } from '../../rollup/types';
import { BLANK } from '../../utils/blank';
import relativeId from '../../utils/relativeId';
import { NodeRenderOptions, RenderOptions } from '../../utils/renderHelpers';
import { CallOptions } from '../CallOptions';
import { DeoptimizableEntity } from '../DeoptimizableEntity';
import { HasEffectsContext, InclusionContext } from '../ExecutionContext';
import {
EMPTY_PATH,
ObjectPath,
ObjectPathKey,
PathTracker,
SHARED_RECURSION_TRACKER,
UnknownKey,
UNKNOWN_PATH
} from '../utils/PathTracker';
import { LiteralValueOrUnknown, UnknownValue } from '../values';
import ExternalVariable from '../variables/ExternalVariable';
import NamespaceVariable from '../variables/NamespaceVariable';
import Variable from '../variables/Variable';
import Identifier from './Identifier';
import Literal from './Literal';
import * as NodeType from './NodeType';
import PrivateIdentifier from './PrivateIdentifier';
import { ExpressionNode, IncludeChildren, NodeBase } from './shared/Node';
import SpreadElement from './SpreadElement';
import Super from './Super';
function getResolvablePropertyKey(memberExpression: MemberExpression): string | null {
return memberExpression.computed
? getResolvableComputedPropertyKey(memberExpression.property)
: (memberExpression.property as Identifier).name;
}
function getResolvableComputedPropertyKey(propertyKey: ExpressionNode): string | null {
if (propertyKey instanceof Literal) {
return String(propertyKey.value);
}
return null;
}
type PathWithPositions = { key: string; pos: number }[];
function getPathIfNotComputed(memberExpression: MemberExpression): PathWithPositions | null {
const nextPathKey = memberExpression.propertyKey;
const object = memberExpression.object;
if (typeof nextPathKey === 'string') {
if (object instanceof Identifier) {
return [
{ key: object.name, pos: object.start },
{ key: nextPathKey, pos: memberExpression.property.start }
];
}
if (object instanceof MemberExpression) {
const parentPath = getPathIfNotComputed(object);
return (
parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]
);
}
}
return null;
}
function getStringFromPath(path: PathWithPositions): string {
let pathString = path[0].key;
for (let index = 1; index < path.length; index++) {
pathString += '.' + path[index].key;
}
return pathString;
}
export default class MemberExpression extends NodeBase implements DeoptimizableEntity {
computed!: boolean;
object!: ExpressionNode | Super;
optional!: boolean;
property!: ExpressionNode | PrivateIdentifier;
propertyKey!: ObjectPathKey | null;
type!: NodeType.tMemberExpression;
variable: Variable | null = null;
private bound = false;
private expressionsToBeDeoptimized: DeoptimizableEntity[] = [];
private replacement: string | null = null;
private wasPathDeoptimizedWhileOptimized = false;
bind() {
if (this.bound) return;
this.bound = true;
const path = getPathIfNotComputed(this);
const baseVariable = path && this.scope.findVariable(path[0].key);
if (baseVariable && baseVariable.isNamespace) {
const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path!.slice(1));
if (!resolvedVariable) {
super.bind();
} else if (typeof resolvedVariable === 'string') {
this.replacement = resolvedVariable;
} else {
this.variable = resolvedVariable;
this.scope.addNamespaceMemberAccess(getStringFromPath(path!), resolvedVariable);
}
} else {
super.bind();
// ensure the propertyKey is set for the tree-shaking passes
this.getPropertyKey();
}
}
deoptimizeCache() {
const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
this.expressionsToBeDeoptimized = [];
this.propertyKey = UnknownKey;
if (this.wasPathDeoptimizedWhileOptimized) {
this.object.deoptimizePath(UNKNOWN_PATH);
}
for (const expression of expressionsToBeDeoptimized) {
expression.deoptimizeCache();
}
}
deoptimizePath(path: ObjectPath) {
if (!this.bound) this.bind();
if (path.length === 0) this.disallowNamespaceReassignment();
if (this.variable) {
this.variable.deoptimizePath(path);
} else if (!this.replacement) {
this.wasPathDeoptimizedWhileOptimized = true;
this.object.deoptimizePath([this.getPropertyKey(), ...path]);
}
}
getLiteralValueAtPath(
path: ObjectPath,
recursionTracker: PathTracker,
origin: DeoptimizableEntity
): LiteralValueOrUnknown {
if (!this.bound) this.bind();
if (this.variable !== null) {
return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
}
this.expressionsToBeDeoptimized.push(origin);
return this.object.getLiteralValueAtPath(
[this.getPropertyKey(), ...path],
recursionTracker,
origin
);
}
getReturnExpressionWhenCalledAtPath(
path: ObjectPath,
recursionTracker: PathTracker,
origin: DeoptimizableEntity
) {
if (!this.bound) this.bind();
if (this.variable !== null) {
return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
}
this.expressionsToBeDeoptimized.push(origin);
return this.object.getReturnExpressionWhenCalledAtPath(
[this.getPropertyKey(), ...path],
recursionTracker,
origin
);
}
hasEffects(context: HasEffectsContext): boolean {
const propertyReadSideEffects = (this.context.options.treeshake as NormalizedTreeshakingOptions)
.propertyReadSideEffects;
return (
propertyReadSideEffects === 'always' ||
this.property.hasEffects(context) ||
this.object.hasEffects(context) ||
(propertyReadSideEffects &&
this.object.hasEffectsWhenAccessedAtPath([this.propertyKey!], context))
);
}
hasEffectsWhenAccessedAtPath(path: ObjectPath, context: HasEffectsContext): boolean {
if (path.length === 0) return false;
if (this.variable !== null) {
return this.variable.hasEffectsWhenAccessedAtPath(path, context);
}
return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey!, ...path], context);
}
hasEffectsWhenAssignedAtPath(path: ObjectPath, context: HasEffectsContext): boolean {
if (this.variable !== null) {
return this.variable.hasEffectsWhenAssignedAtPath(path, context);
}
return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey!, ...path], context);
}
hasEffectsWhenCalledAtPath(
path: ObjectPath,
callOptions: CallOptions,
context: HasEffectsContext
): boolean {
if (this.variable !== null) {
return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
}
return this.object.hasEffectsWhenCalledAtPath(
[this.propertyKey!, ...path],
callOptions,
context
);
}
include(context: InclusionContext, includeChildrenRecursively: IncludeChildren) {
if (!this.included) {
this.included = true;
if (this.variable !== null) {
this.context.includeVariableInModule(this.variable);
}
}
this.object.include(context, includeChildrenRecursively);
this.property.include(context, includeChildrenRecursively);
}
includeCallArguments(context: InclusionContext, args: (ExpressionNode | SpreadElement)[]): void {
if (this.variable) {
this.variable.includeCallArguments(context, args);
} else {
super.includeCallArguments(context, args);
}
}
initialise() {
this.propertyKey = getResolvablePropertyKey(this);
}
mayModifyThisWhenCalledAtPath(path: ObjectPath, recursionTracker: PathTracker) {
if (this.variable) {
return this.variable.mayModifyThisWhenCalledAtPath(path, recursionTracker);
}
return this.object.mayModifyThisWhenCalledAtPath(
[this.propertyKey as ObjectPathKey].concat(path),
recursionTracker
);
}
render(
code: MagicString,
options: RenderOptions,
{
renderedParentType,
isCalleeOfRenderedParent,
renderedSurroundingElement
}: NodeRenderOptions = BLANK
) {
const isCalleeOfDifferentParent =
renderedParentType === NodeType.CallExpression && isCalleeOfRenderedParent;
if (this.variable || this.replacement) {
let replacement = this.variable ? this.variable.getName() : this.replacement;
if (isCalleeOfDifferentParent) replacement = '0, ' + replacement;
code.overwrite(this.start, this.end, replacement!, {
contentOnly: true,
storeName: true
});
} else {
if (isCalleeOfDifferentParent) {
code.appendRight(this.start, '0, ');
}
const surroundingElement = renderedParentType || renderedSurroundingElement;
this.object.render(
code,
options,
surroundingElement ? { renderedSurroundingElement: surroundingElement } : BLANK
);
this.property.render(code, options);
}
}
private disallowNamespaceReassignment() {
if (this.object instanceof Identifier) {
const variable = this.scope.findVariable(this.object.name);
if (variable.isNamespace) {
if (this.variable) {
this.context.includeVariableInModule(this.variable);
}
this.context.warn(
{
code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
message: `Illegal reassignment to import '${this.object.name}'`
},
this.start
);
}
}
}
private getPropertyKey(): ObjectPathKey {
if (this.propertyKey === null) {
this.propertyKey = UnknownKey;
const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
return (this.propertyKey = value === UnknownValue ? UnknownKey : String(value));
}
return this.propertyKey;
}
private resolveNamespaceVariables(
baseVariable: Variable,
path: PathWithPositions
): Variable | string | null {
if (path.length === 0) return baseVariable;
if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable) return null;
const exportName = path[0].key;
const variable = (baseVariable as NamespaceVariable).context.traceExport(exportName);
if (!variable) {
const fileName = (baseVariable as NamespaceVariable).context.fileName;
this.context.warn(
{
code: 'MISSING_EXPORT',
exporter: relativeId(fileName),
importer: relativeId(this.context.fileName),
message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
missing: exportName,
url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
},
path[0].pos
);
return 'undefined';
}
return this.resolveNamespaceVariables(variable, path.slice(1));
}
}