-
Notifications
You must be signed in to change notification settings - Fork 51k
Expand file tree
/
Copy pathDeriveMinimalDependenciesHIR.ts
More file actions
389 lines (366 loc) · 12.1 KB
/
DeriveMinimalDependenciesHIR.ts
File metadata and controls
389 lines (366 loc) · 12.1 KB
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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {CompilerError} from '../CompilerError';
import {
DependencyPathEntry,
GeneratedSource,
Identifier,
PropertyLiteral,
ReactiveScopeDependency,
SourceLocation,
} from '../HIR';
import {printIdentifier} from '../HIR/PrintHIR';
/**
* Simpler fork of DeriveMinimalDependencies, see PropagateScopeDependenciesHIR
* for detailed explanation.
*/
export class ReactiveScopeDependencyTreeHIR {
/**
* Paths from which we can hoist PropertyLoads. If an `identifier`,
* `identifier.path`, or `identifier?.path` is in this map, it is safe to
* evaluate (non-optional) PropertyLoads from.
*/
#hoistableObjects: Map<Identifier, HoistableNode & {reactive: boolean}> =
new Map();
#deps: Map<Identifier, DependencyNode & {reactive: boolean}> = new Map();
/**
* @param hoistableObjects a set of paths from which we can safely evaluate
* PropertyLoads. Note that we expect these to not contain duplicates (e.g.
* both `a?.b` and `a.b`) only because CollectHoistablePropertyLoads merges
* duplicates when traversing the CFG.
*/
constructor(hoistableObjects: Iterable<ReactiveScopeDependency>) {
for (const {path, identifier, reactive, loc} of hoistableObjects) {
let currNode = ReactiveScopeDependencyTreeHIR.#getOrCreateRoot(
identifier,
reactive,
this.#hoistableObjects,
path.length > 0 && path[0].optional ? 'Optional' : 'NonNull',
loc,
);
for (let i = 0; i < path.length; i++) {
const prevAccessType = currNode.properties.get(
path[i].property,
)?.accessType;
const accessType =
i + 1 < path.length && path[i + 1].optional ? 'Optional' : 'NonNull';
CompilerError.invariant(
prevAccessType == null || prevAccessType === accessType,
{
reason: 'Conflicting access types',
loc: GeneratedSource,
},
);
let nextNode = currNode.properties.get(path[i].property);
if (nextNode == null) {
nextNode = {
properties: new Map(),
accessType,
loc: path[i].loc,
};
currNode.properties.set(path[i].property, nextNode);
}
currNode = nextNode;
}
}
}
static #getOrCreateRoot<T extends string>(
identifier: Identifier,
reactive: boolean,
roots: Map<Identifier, TreeNode<T> & {reactive: boolean}>,
defaultAccessType: T,
loc: SourceLocation,
): TreeNode<T> {
// roots can always be accessed unconditionally in JS
let rootNode = roots.get(identifier);
if (rootNode === undefined) {
rootNode = {
properties: new Map(),
reactive,
accessType: defaultAccessType,
loc,
};
roots.set(identifier, rootNode);
} else {
CompilerError.invariant(reactive === rootNode.reactive, {
reason: '[DeriveMinimalDependenciesHIR] Conflicting reactive root flag',
description: `Identifier ${printIdentifier(identifier)}`,
loc: GeneratedSource,
});
}
return rootNode;
}
/**
* Join a dependency with `#hoistableObjects` to record the hoistable
* dependency. This effectively truncates @param dep to its maximal
* safe-to-evaluate subpath
*/
addDependency(dep: ReactiveScopeDependency): void {
const {identifier, reactive, path, loc} = dep;
let depCursor = ReactiveScopeDependencyTreeHIR.#getOrCreateRoot(
identifier,
reactive,
this.#deps,
PropertyAccessType.UnconditionalAccess,
loc,
);
/**
* hoistableCursor is null if depCursor is not an object we can hoist
* property reads from otherwise, it represents the same node in the
* hoistable / cfg-informed tree
*/
let hoistableCursor: HoistableNode | undefined =
this.#hoistableObjects.get(identifier);
// All properties read 'on the way' to a dependency are marked as 'access'
for (const entry of path) {
let nextHoistableCursor: HoistableNode | undefined;
let nextDepCursor: DependencyNode;
if (entry.optional) {
/**
* No need to check the access type since we can match both optional or non-optionals
* in the hoistable
* e.g. a?.b<rest> is hoistable if a.b<rest> is hoistable
*/
if (hoistableCursor != null) {
nextHoistableCursor = hoistableCursor?.properties.get(entry.property);
}
let accessType;
if (
hoistableCursor != null &&
hoistableCursor.accessType === 'NonNull'
) {
/**
* For an optional chain dep `a?.b`: if the hoistable tree only
* contains `a`, we can keep either `a?.b` or 'a.b' as a dependency.
* (note that we currently do the latter for perf)
*/
accessType = PropertyAccessType.UnconditionalAccess;
} else {
/**
* Given that it's safe to evaluate `depCursor` and optional load
* never throws, it's also safe to evaluate `depCursor?.entry`
*/
accessType = PropertyAccessType.OptionalAccess;
}
nextDepCursor = makeOrMergeProperty(
depCursor,
entry.property,
accessType,
entry.loc,
);
} else if (
hoistableCursor != null &&
hoistableCursor.accessType === 'NonNull'
) {
nextHoistableCursor = hoistableCursor.properties.get(entry.property);
nextDepCursor = makeOrMergeProperty(
depCursor,
entry.property,
PropertyAccessType.UnconditionalAccess,
entry.loc,
);
} else {
/**
* Break to truncate the dependency on its first non-optional entry that PropertyLoads are not hoistable from
*/
break;
}
depCursor = nextDepCursor;
hoistableCursor = nextHoistableCursor;
}
// mark the final node as a dependency
depCursor.accessType = merge(
depCursor.accessType,
PropertyAccessType.OptionalDependency,
);
}
deriveMinimalDependencies(): Set<ReactiveScopeDependency> {
const results = new Set<ReactiveScopeDependency>();
for (const [rootId, rootNode] of this.#deps.entries()) {
collectMinimalDependenciesInSubtree(
rootNode,
rootNode.reactive,
rootId,
[],
results,
);
}
return results;
}
/*
* Prints dependency tree to string for debugging.
* @param includeAccesses
* @returns string representation of DependencyTree
*/
printDeps(includeAccesses: boolean): string {
let res: Array<Array<string>> = [];
for (const [rootId, rootNode] of this.#deps.entries()) {
const rootResults = printSubtree(rootNode, includeAccesses).map(
result => `${printIdentifier(rootId)}.${result}`,
);
res.push(rootResults);
}
return res.flat().join('\n');
}
static debug<T extends string>(roots: Map<Identifier, TreeNode<T>>): string {
const buf: Array<string> = [`tree() [`];
for (const [rootId, rootNode] of roots) {
buf.push(`${printIdentifier(rootId)} (${rootNode.accessType}):`);
this.#debugImpl(buf, rootNode, 1);
}
buf.push(']');
return buf.length > 2 ? buf.join('\n') : buf.join('');
}
static #debugImpl<T extends string>(
buf: Array<string>,
node: TreeNode<T>,
depth: number = 0,
): void {
for (const [property, childNode] of node.properties) {
buf.push(`${' '.repeat(depth)}.${property} (${childNode.accessType}):`);
this.#debugImpl(buf, childNode, depth + 1);
}
}
}
/*
* Enum representing the access type of single property on a parent object.
* We distinguish on two independent axes:
* Optional / Unconditional:
* - whether this property is an optional load (within an optional chain)
* Access / Dependency:
* - Access: this property is read on the path of a dependency. We do not
* need to track change variables for accessed properties. Tracking accesses
* helps Forget do more granular dependency tracking.
* - Dependency: this property is read as a dependency and we must track changes
* to it for correctness.
* ```javascript
* // props.a is a dependency here and must be tracked
* deps: {props.a, props.a.b} ---> minimalDeps: {props.a}
* // props.a is just an access here and does not need to be tracked
* deps: {props.a.b} ---> minimalDeps: {props.a.b}
* ```
*/
enum PropertyAccessType {
OptionalAccess = 'OptionalAccess',
UnconditionalAccess = 'UnconditionalAccess',
OptionalDependency = 'OptionalDependency',
UnconditionalDependency = 'UnconditionalDependency',
}
function isOptional(access: PropertyAccessType): boolean {
return (
access === PropertyAccessType.OptionalAccess ||
access === PropertyAccessType.OptionalDependency
);
}
function isDependency(access: PropertyAccessType): boolean {
return (
access === PropertyAccessType.OptionalDependency ||
access === PropertyAccessType.UnconditionalDependency
);
}
function merge(
access1: PropertyAccessType,
access2: PropertyAccessType,
): PropertyAccessType {
const resultIsUnconditional = !(isOptional(access1) && isOptional(access2));
const resultIsDependency = isDependency(access1) || isDependency(access2);
/*
* Straightforward merge.
* This can be represented as bitwise OR, but is written out for readability
*
* Observe that `UnconditionalAccess | ConditionalDependency` produces an
* unconditionally accessed conditional dependency. We currently use these
* as we use unconditional dependencies. (i.e. to codegen change variables)
*/
if (resultIsUnconditional) {
if (resultIsDependency) {
return PropertyAccessType.UnconditionalDependency;
} else {
return PropertyAccessType.UnconditionalAccess;
}
} else {
// result is optional
if (resultIsDependency) {
return PropertyAccessType.OptionalDependency;
} else {
return PropertyAccessType.OptionalAccess;
}
}
}
type TreeNode<T extends string> = {
properties: Map<PropertyLiteral, TreeNode<T>>;
accessType: T;
loc: SourceLocation;
};
type HoistableNode = TreeNode<'Optional' | 'NonNull'>;
type DependencyNode = TreeNode<PropertyAccessType>;
/**
* Recursively calculates minimal dependencies in a subtree.
* @param node DependencyNode representing a dependency subtree.
* @returns a minimal list of dependencies in this subtree.
*/
function collectMinimalDependenciesInSubtree(
node: DependencyNode,
reactive: boolean,
rootIdentifier: Identifier,
path: Array<DependencyPathEntry>,
results: Set<ReactiveScopeDependency>,
): void {
if (isDependency(node.accessType)) {
results.add({identifier: rootIdentifier, reactive, path, loc: node.loc});
} else {
for (const [childName, childNode] of node.properties) {
collectMinimalDependenciesInSubtree(
childNode,
reactive,
rootIdentifier,
[
...path,
{
property: childName,
optional: isOptional(childNode.accessType),
loc: childNode.loc,
},
],
results,
);
}
}
}
function printSubtree(
node: DependencyNode,
includeAccesses: boolean,
): Array<string> {
const results: Array<string> = [];
for (const [propertyName, propertyNode] of node.properties) {
if (includeAccesses || isDependency(propertyNode.accessType)) {
results.push(`${propertyName} (${propertyNode.accessType})`);
}
const propertyResults = printSubtree(propertyNode, includeAccesses);
results.push(...propertyResults.map(result => `${propertyName}.${result}`));
}
return results;
}
function makeOrMergeProperty(
node: DependencyNode,
property: PropertyLiteral,
accessType: PropertyAccessType,
loc: SourceLocation,
): DependencyNode {
let child = node.properties.get(property);
if (child == null) {
child = {
properties: new Map(),
accessType,
loc,
};
node.properties.set(property, child);
} else {
child.accessType = merge(child.accessType, accessType);
}
return child;
}