-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclasses.lsc
More file actions
213 lines (183 loc) · 7.09 KB
/
classes.lsc
File metadata and controls
213 lines (183 loc) · 7.09 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
import t, { is, isa, assertOneOf } from '../types'
import { restToSpread, spreadIsAlreadySafe } from '../helpers/variables'
import { getFunctionParent } from '../helpers/blocks'
// Check if the given path or any of its descendants contains a `super()`
// call expression.
export containsSuperCall(path) ->
let hasSuper = false
path.traverse({
noScope: true
Class(path): void -> path.skip()
// XXX: this may not be necessary due to super calls in free functions
// being syntax errors caught by js engine.
Function(path): void -> path.skip()
LscFunction(path): void -> path.skip()
Super(superPath): void ->
if is("CallExpression", superPath.parentPath):
now hasSuper = true
superPath.stop()
})
hasSuper
// Ensure that a class body has a constructor, optionally ensuring that
// the constructor itself has a `super(...args)` call.
//
// TODO: consider refactoring here
// - "hasConstructor" function to look for the constructor with traverse()
// - "addEmptyConstructor" to make the empty constructor
// - "addSuperCallToConstructor" to make the supercall.
export ensureConstructor(classPath, constructorBodyPath, withSuper = true) ->
if not constructorBodyPath:
emptyConstructor = t.classMethod(
"constructor"
t.identifier("constructor")
[]
t.blockStatement([])
)
// XXX: this marks this constructor for super insertion.
// why is it doing it like this? seems hackish, rethink
emptyConstructor.skinny = true
classPath.get("body").unshiftContainer("body", emptyConstructor)
now constructorBodyPath = classPath.get("body.body.0.body")
if(
withSuper and
classPath.node.superClass and
constructorBodyPath.parentPath.node.skinny and
not containsSuperCall(constructorBodyPath)
):
superCall = if constructorBodyPath.parentPath.node.params.length:
// constructor(<args>) -> super(<args>)
t.expressionStatement(
t.callExpression(
t.super()
constructorBodyPath.parentPath.node.params~restToSpread!
)
)
else:
// constructor(...args) -> super(...args)
let argsUid = classPath.scope.generateUidIdentifier("args");
constructorBodyPath.parentPath.node.params = [t.restElement(argsUid)];
t.expressionStatement(
t.callExpression(t.super(), [
t.spreadElement(argsUid)~spreadIsAlreadySafe!
])
)
constructorBodyPath.unshiftContainer("body", superCall)
constructorBodyPath
// Insert code into class constructor which will autobind a list of class
// methods at construction time.
export bindMethodsInConstructor(classPath, constructorPath, methodIds) ->
// `this.method = this.method.bind(this);`
assignments = [...for elem methodId in methodIds:
assertOneOf(methodId, ["Identifier", "Expression"])
isComputed = !is("Identifier", methodId)
thisDotMethod = t.memberExpression(t.thisExpression(), methodId, isComputed)
[t.expressionStatement(
t.assignmentExpression("="
thisDotMethod
t.callExpression(
t.memberExpression(thisDotMethod, t.identifier("bind"))
[t.thisExpression()]
)
)
)]
]
// directly after each instance of super(), insert the thingies there.
if (classPath.node.superClass) {
constructorPath.traverse({
Super(superPath) {
if (!superPath.parentPath~isa("CallExpression")) return;
let superStatementPath = superPath.getStatementParent();
// things get super weird when you return super();
// TODO: consider trying to handle it
let enclosingReturn = superPath
.findParent((p) => p~isa("ReturnStatement") && p~getFunctionParent() === constructorPath.parentPath);
if (enclosingReturn) throw new Error("Can't use => with `return super()`; try removing `return`.");
superStatementPath.insertAfter(assignments);
return
}
});
} else {
constructorPath.unshiftContainer("body", assignments);
}
export bindMethods(path, methodIds) ->
let assignId, inExpression = false;
if (path~isa("ClassDeclaration")) {
now assignId = path.node.id;
} else if (
path.parentPath~isa("AssignmentExpression") &&
path.parentPath.parentPath~isa("ExpressionStatement")
) {
now assignId = path.parentPath.node.left;
} else if (path.parentPath~isa("VariableDeclarator")) {
now assignId = path.parentPath.node.id;
} else {
let id = path~isa("Class") ? "class" : "obj";
now assignId = path.getStatementParent().scope.generateDeclaredUidIdentifier(id);
now inExpression = true;
}
assertOneOf(assignId, ["Identifier", "MemberExpression"]);
let assignments = methodIds.map((methodId) => {
// could be computed, eg `['blah']() => {}`
assertOneOf(methodId, ["Identifier", "Expression"]);
let isComputed = !(methodId~isa("Identifier"));
let objDotMethod = t.memberExpression(assignId, methodId, isComputed);
let bind = t.callExpression(
t.memberExpression(objDotMethod, t.identifier("bind")),
[assignId]
);
return t.assignmentExpression("=", objDotMethod, bind);
});
if (inExpression) {
path.replaceWith(t.sequenceExpression([
t.assignmentExpression("=", assignId, path.node),
...assignments,
assignId
]));
} else {
path.getStatementParent().insertAfter(
assignments.map((a) => t.expressionStatement(a))
);
}
// Examine class body and retrieve info needed to transform it
enumerateClassBody(path) ->
fatArrows = []
fatStaticArrows = []
let constructorPath = null
body = path.node.body
body.forEach((method, i) => {
if (!t.isMethod(method)) return;
if (method.kind === "constructor") {
now constructorPath = path.get(`body.${i}.body`);
} else if (method.static && method.skinny === false) {
fatStaticArrows.push(method.key);
method.skinny = true; // prevent infinite recursion
} else if (method.skinny === false) {
fatArrows.push(method.key);
method.skinny = true; // prevent infinite recursion
}
});
{ fatArrows, fatStaticArrows, constructorPath }
export transformClassBody(path): void ->
let { fatArrows, fatStaticArrows, constructorPath } = enumerateClassBody(path)
let maybeAddSuper = path.parentPath.node.superClass && constructorPath;
if (fatArrows.length || maybeAddSuper) {
now constructorPath = ensureConstructor(path.parentPath, constructorPath, true);
}
if (fatArrows.length) {
bindMethodsInConstructor(path.parentPath, constructorPath, fatArrows);
}
if (fatStaticArrows.length) {
bindMethods(path.parentPath, fatStaticArrows);
}
export transformObjectMethod(path): void ->
{ node } = path
// Transform methods with fat arrows
if (node.kind != "method") or (node.skinny != false): return
// Fat arrows should get lexical `this`
// Transform to an objectProperty with an ArrowFunctionExpression body
func = t.arrowFunctionExpression(node.params, node.body, node.async)
func.generator = node.generator
func.returnType = node.returnType
func.typeParameters = node.typeParameters
prop = t.objectProperty(node.key, func, node.computed, false, node.decorators)
path.replaceWith(prop)