-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvariable-manager.ts
More file actions
291 lines (242 loc) · 11 KB
/
Copy pathvariable-manager.ts
File metadata and controls
291 lines (242 loc) · 11 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
import { fromPairs } from 'lodash-es';
import { BeforeModelDestroyedEvent } from '../../model/events/before-model-destroyed-event';
import { ModelChangedEvent } from '../../model/events/model-changed-event';
import { ModelManager } from '../../model/manager/model-manager';
import { PropertyLocation } from '../../model/property/property-location';
import { Logger } from '../../util/logging/logger';
import { EvaluationResult } from '../evaluator/variable-evaluator';
import { ExpressionParser } from '../parser/expression-parser';
import { ParseNodeType } from '../parser/parse-node';
import { VariableReference } from '../reference/variable-reference';
import { VariableValue } from '../value/variable-value';
import { ResolveDictionary, VariableDictionary } from '../variable-dictionary';
/**
* Variable manager handles read, write and update of variable values,
* supporting serialization and deserialization to convert variables into
* values and back.
*/
export class VariableManager {
private readonly variableDictionaries: WeakMap<object, VariableDictionary> = new WeakMap();
private readonly variableReferences: WeakMap<object, Map<string, VariableReference>> = new WeakMap();
public constructor(
private readonly logger: Logger,
private readonly modelManager: ModelManager,
private readonly modelChangedEvent: ModelChangedEvent,
private readonly beforeModelDestroyedEvent: BeforeModelDestroyedEvent
) {}
/**
* Assign a value to the given key and scope. Scope should be a model object.
*/
public set(key: string, value: unknown, modelScope: object): void {
if (!this.variableDictionaries.has(modelScope)) {
this.variableDictionaries.set(modelScope, new Map());
}
const variableDictionary = this.variableDictionaries.get(modelScope)!;
if (variableDictionary.has(key)) {
variableDictionary.get(key)!.currentValue = value;
} else {
const newValue = this.createVariableValue(key, value);
this.shadowExistingReferencesIfNeeded(modelScope, newValue);
variableDictionary.set(key, newValue);
}
this.updateAllReferences(variableDictionary.get(key)!);
}
/**
* Retrieves a value for the given key. If that value has been assigned in this scope,
* it will be returned. Otherwise, scopes will be searched upwards in the model tree
* returning undefined if no match is found.
*/
public get<T = unknown>(key: string, modelScope: object): T | undefined {
const variableValue = this.getVariableValue<T>(key, modelScope);
if (!variableValue) {
this.logger.warn(`Attempting to lookup unassigned variable: ${key}`);
}
return variableValue && variableValue.currentValue;
}
/**
* Indicates whether the provided key is registered, accessible at the given scope
* and returns a defined value.
*/
public has(key: string, modelScope: object): boolean {
const variableValue = this.getVariableValue<unknown>(key, modelScope);
return variableValue ? variableValue.currentValue !== undefined : false;
}
/**
* Begin tracking the provided expression at `location`. The value will be set based on
* variables, and updated as variables changed.
*
* Throws Error if the provided location is already being tracked
*/
public registerReference(location: PropertyLocation, variableExpression: string): unknown {
const referenceMap = this.getOrCreateReferenceMapForModelContainingLocation(location);
if (referenceMap.has(location.toString())) {
this.logger.error(`Attempting to register reference which has already been declared at ${location.toString()}`);
} else {
const autoCleanupSubscription = this.beforeModelDestroyedEvent
.getBeforeDestructionObservable(location.parentModel)
.subscribe(() => this.deregisterReference(location));
referenceMap.set(
location.toString(),
new VariableReference(variableExpression, location, autoCleanupSubscription)
);
}
const reference = referenceMap.get(location.toString())!;
return this.updateReference(reference);
}
/**
* Indicates whether the value at `location` is currently being tracked as a variable reference
*/
public isVariableReference(location: PropertyLocation): boolean {
return !!this.getReferenceAtLocation(location);
}
/**
* Indicates whether the provided string should be treated as a variable expression
*/
public isVariableExpression(potentialExpression: string): boolean {
const parsed = new ExpressionParser(potentialExpression).parse();
return parsed.children.some(child => child.type === ParseNodeType.Expression);
}
/**
* Ends tracking for the variable at `location`. Returns the original variable string.
* The value at `location` is left as is.
*
* Throws Error if the provided location is not being tracked
*/
public deregisterReference(location: PropertyLocation): string {
const reference = this.getReferenceAtLocation(location);
if (!reference) {
return this.logger
.error(
`Attempted to deregister reference at ${location.toString()} which does not contain a registered reference`
)
.throw();
}
this.getOrCreateReferenceMapForModelContainingLocation(location).delete(reference.location.toString());
const result = reference.unresolve();
reference.autoCleanupSubscription.unsubscribe();
this.updateValueReferenceTrackingFromEvaluationResult(reference, result);
return result.value!;
}
/**
* Retrieves the original variable expression from `location`. This value will continue
* to be tracked.
*
* Throws Error if the provided location is not being tracked
*/
public getVariableExpressionFromLocation(location: PropertyLocation): string {
const reference = this.getReferenceAtLocation(location);
if (!reference) {
return this.logger
.error(`Attempted to resolve reference at ${location.toString()} which does not contain a registered reference`)
.throw();
}
/* Unresolve is stateful, but it *should* be OK. on the following resolution, it will think new variables are being
used, but we're using sets so the extra references should be deduped
*/
const expression = reference.unresolve().value!;
return expression;
}
private getParentModelScope(modelScope: object): object | undefined {
const parentModel = this.modelManager.getParent(modelScope);
if (!parentModel) {
return undefined;
}
return this.variableDictionaries.has(parentModel) ? parentModel : this.getParentModelScope(parentModel);
}
private createVariableValue<T>(key: string, value: T): VariableValue<T> {
return {
key: key,
currentValue: value,
references: new Set()
};
}
private updateAllReferences(value: VariableValue<unknown>): void {
value.references.forEach(reference => this.updateReference(reference));
}
private updateReference(reference: VariableReference): unknown {
const modelScope = reference.location.parentModel;
const result = reference.resolve(this.getResolveDictionaryForModel(modelScope));
this.updateValueReferenceTrackingFromEvaluationResult(reference, result);
this.modelChangedEvent.publishChange(reference.location.parentModel);
return result.value;
}
private getReferenceAtLocation(location: PropertyLocation): VariableReference | undefined {
const referenceMapForModel = this.variableReferences.get(location.parentModel);
if (referenceMapForModel) {
return referenceMapForModel.get(location.toString());
}
return undefined;
}
private getDictionaryContainingKey(key: string, modelScope: object): VariableDictionary | undefined {
const dictionaryWithRequestedScope = this.variableDictionaries.get(modelScope);
if (dictionaryWithRequestedScope && dictionaryWithRequestedScope.has(key)) {
return dictionaryWithRequestedScope;
}
const parent = this.getParentModelScope(modelScope);
return parent ? this.getDictionaryContainingKey(key, parent) : undefined;
}
private getOrCreateReferenceMapForModelContainingLocation(
location: PropertyLocation
): Map<string, VariableReference> {
if (!this.variableReferences.has(location.parentModel)) {
this.variableReferences.set(location.parentModel, new Map());
}
return this.variableReferences.get(location.parentModel)!;
}
private getResolveDictionaryForModel(modelScope: object): ResolveDictionary {
const variablePairs: [string, VariableValue<unknown>][] = [];
let nextModelScope = this.variableDictionaries.has(modelScope) ? modelScope : this.getParentModelScope(modelScope);
while (nextModelScope) {
// Later takes precedence, so we always unshift on to beginning
variablePairs.unshift(...this.variableDictionaries.get(nextModelScope)!);
nextModelScope = this.getParentModelScope(nextModelScope);
}
return fromPairs(variablePairs.map(([key, value]) => [key, value.currentValue]));
}
private getVariableValue<T>(key: string, modelScope: object): VariableValue<T> | undefined {
const dictionaryWithKey = this.getDictionaryContainingKey(key, modelScope);
return dictionaryWithKey && (dictionaryWithKey.get(key) as VariableValue<T> | undefined);
}
private updateValueReferenceTrackingFromEvaluationResult(
reference: VariableReference,
evaluationResult: EvaluationResult<unknown>
): void {
const modelScope = reference.location.parentModel;
evaluationResult.variableNamesRemoved.forEach(name => {
// Every variable name previously referenced should have a placeholder
this.getVariableValue(name, modelScope)!.references.delete(reference);
});
evaluationResult.variableNamesAdded.forEach(name => {
if (!this.has(name, modelScope)) {
this.addPlaceholderVariable(name, modelScope);
}
this.getVariableValue(name, modelScope)!.references.add(reference);
});
}
private shadowExistingReferencesIfNeeded(modelScope: object, newVariableValue: VariableValue<unknown>): void {
// References registered before this new value may be inside this scope and should be switched over
const parentModelScope = this.getParentModelScope(modelScope);
const parentDictionary =
parentModelScope && this.getDictionaryContainingKey(newVariableValue.key, parentModelScope);
if (!parentDictionary) {
return; // This variable is not shadowing any other
}
const existingReferences = parentDictionary.get(newVariableValue.key)!.references;
const referencesToUpdate: VariableReference[] = [];
existingReferences.forEach(reference => {
if (
reference.location.parentModel === modelScope ||
this.modelManager.isAncestor(reference.location.parentModel, modelScope)
) {
referencesToUpdate.push(reference);
}
});
referencesToUpdate.forEach(referenence => {
existingReferences.delete(referenence);
newVariableValue.references.add(referenence);
});
}
private addPlaceholderVariable(variableName: string, modelScope: object): void {
this.set(variableName, undefined, this.modelManager.getRoot(modelScope));
}
}