-
Notifications
You must be signed in to change notification settings - Fork 414
/
RequirementsResolver.ts
208 lines (181 loc) · 5.63 KB
/
RequirementsResolver.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
/**
* This file is used to extract statements required to evaluate dependencies.
* Starting from the exports.__linariaPreval passed as argument to static method on class RequirementsResolver,
* it recursively extracts paths that contains identifiers that are needed to evaluate the dependency.
*/
import { types as t } from '@babel/core';
import { Binding, NodePath } from '@babel/traverse';
type Requirement = {
result: t.Statement;
path: NodePath<t.Node>;
requirements: Set<NodePath>;
};
export default class RequirementsResolver {
public static resolve(
path: NodePath<t.Node> | NodePath<t.Node>[]
): t.Statement[] {
const resolver = new RequirementsResolver();
if (Array.isArray(path)) {
path.forEach((p) => this.resolve(p));
} else {
resolver.resolve(path);
}
return resolver.statements;
}
private requirements: Requirement[] = [];
/**
* Checks that specified node or one of its ancestors is already added
*/
private isAdded(path: NodePath<t.Node>): boolean {
if (this.requirements.some((req) => req.path === path)) {
return true;
}
if (path.parentPath) {
return this.isAdded(path.parentPath);
}
return false;
}
/**
* Makes a declaration statement, finds dependencies
* and adds all of it to the list of requirements.
*/
private resolveBinding(binding: Binding) {
let result: t.Statement;
const startPosition = binding.path.node.start;
switch (binding.kind) {
case 'module':
if (
binding.path.isImportSpecifier() &&
binding.path.parentPath.isImportDeclaration()
) {
result = t.importDeclaration(
[binding.path.node],
binding.path.parentPath.node.source
);
} else {
result = binding.path.parentPath.node as t.Statement;
}
break;
case 'const':
case 'let':
case 'var': {
let decl = (binding.path as NodePath<t.VariableDeclarator>).node;
if (
binding.path.isVariableDeclarator() &&
t.isSequenceExpression(binding.path.node.init)
) {
// Replace SequenceExpressions (expr1, expr2, expr3, ...) with the last one
decl = t.variableDeclarator(
binding.path.node.id,
binding.path.node.init.expressions[
binding.path.node.init.expressions.length - 1
]
);
}
result = t.variableDeclaration(binding.kind, [decl]);
break;
}
default:
result = binding.path.node as t.Statement;
break;
}
// result may be newly created node that not have start/end/loc info
// which is needed to sort statements
result.start = startPosition;
const req: Requirement = {
result,
path: binding.path,
requirements: new Set(),
};
this.requirements.push(req);
req.requirements = this.resolve(binding.path);
}
/**
* Checks that a specified identifier has a binding and tries to resolve it
* @return `Binding` or null if there is no binding, or it is already added, or it has useless type
*/
private resolveIdentifier(path: NodePath<t.Identifier>): Binding | null {
const binding = path.scope.getBinding(path.node.name);
if (
path.isReferenced() &&
binding &&
!this.isAdded(binding.path) &&
// @ts-ignore binding.kind can be param
binding.kind !== 'param'
) {
this.resolveBinding(binding);
return binding;
}
return null;
}
/**
* Finds all identifiers in a specified path, finds all related bindings
* and recursively calls `resolve` for each of them.
* @return `Set` with related bindings
*/
private resolve(path: NodePath<t.Node>): Set<NodePath> {
const set = new Set<NodePath>();
if (path.isIdentifier()) {
const binding = this.resolveIdentifier(path);
if (binding !== null) {
set.add(binding.path);
}
return set;
}
path.traverse({
Identifier: (p) => {
const binding = this.resolveIdentifier(p);
if (binding !== null) {
set.add(binding.path);
}
},
});
return set;
}
/**
* Returns sorted list of required statements
*/
private get statements(): t.Statement[] {
const statements: t.Statement[] = [];
let requirements = this.requirements;
while (requirements.length > 0) {
// On each step, we add to the result list only that statements
// which don't have any dependencies (`zeroDeps`)
const [zeroDeps, rest] = requirements.reduce(
(acc, req) => {
if (req.requirements.size === 0) {
acc[0].push(req);
} else {
acc[1].push(req);
}
return acc;
},
[[], []] as [Requirement[], Requirement[]]
);
if (zeroDeps.length === 0) {
// That means that we are in the endless loop.
// I don't know how it's possible, but if it's ever happened, we at least would be notified.
throw new Error('Circular dependency');
}
statements.push(...zeroDeps.map((req) => req.result));
// Let's remove already added statements from the requirements of the rest of the list.
requirements = rest.map((req) => {
const reqs = new Set(req.requirements);
zeroDeps.forEach((r) => reqs.delete(r.path));
return {
...req,
requirements: reqs,
};
});
}
// preserve original statements order, but reversed
statements.sort((a, b) => {
if (a.start && b.start) {
return b.start - a.start;
} else {
return 0;
}
});
return statements;
}
}