UNPKG

8.23 kBJavaScriptView Raw
1
2
3import {ContextualKeyword} from "../parser/tokenizer/keywords";
4import {TokenType as tt} from "../parser/tokenizer/types";
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 * Get information about the class fields for this class, given a token processor pointing to the
46 * open-brace at the start of the class.
47 */
48export default function getClassInfo(
49 rootTransformer,
50 tokens,
51 nameManager,
52) {
53 const snapshot = tokens.snapshot();
54
55 const headerInfo = processClassHeader(tokens);
56
57 let constructorInitializerStatements = [];
58 const instanceInitializerNames = [];
59 const staticInitializerNames = [];
60 let constructorInsertPos = null;
61 const fields = [];
62 const rangesToRemove = [];
63
64 const classContextId = tokens.currentToken().contextId;
65 if (classContextId == null) {
66 throw new Error("Expected non-null class context ID on class open-brace.");
67 }
68
69 tokens.nextToken();
70 while (!tokens.matchesContextIdAndLabel(tt.braceR, classContextId)) {
71 if (tokens.matchesContextual(ContextualKeyword._constructor) && !tokens.currentToken().isType) {
72 ({constructorInitializerStatements, constructorInsertPos} = processConstructor(tokens));
73 } else if (tokens.matches1(tt.semi)) {
74 rangesToRemove.push({start: tokens.currentIndex(), end: tokens.currentIndex() + 1});
75 tokens.nextToken();
76 } else if (tokens.currentToken().isType) {
77 tokens.nextToken();
78 } else {
79 // Either a method or a field. Skip to the identifier part.
80 const statementStartIndex = tokens.currentIndex();
81 let isStatic = false;
82 while (isAccessModifier(tokens.currentToken())) {
83 if (tokens.matches1(tt._static)) {
84 isStatic = true;
85 }
86 tokens.nextToken();
87 }
88 if (
89 tokens.matchesContextual(ContextualKeyword._constructor) &&
90 !tokens.currentToken().isType
91 ) {
92 ({constructorInitializerStatements, constructorInsertPos} = processConstructor(tokens));
93 continue;
94 }
95 const nameStartIndex = tokens.currentIndex();
96 skipFieldName(tokens);
97 if (tokens.matches1(tt.lessThan) || tokens.matches1(tt.parenL)) {
98 // This is a method, so just skip to the next method/field. To do that, we seek forward to
99 // the next start of a class name (either an open bracket or an identifier, or the closing
100 // curly brace), then seek backward to include any access modifiers.
101 while (tokens.currentToken().contextId !== classContextId) {
102 tokens.nextToken();
103 }
104 while (isAccessModifier(tokens.tokenAtRelativeIndex(-1))) {
105 tokens.previousToken();
106 }
107 continue;
108 }
109 // There might be a type annotation that we need to skip.
110 while (tokens.currentToken().isType) {
111 tokens.nextToken();
112 }
113 if (tokens.matches1(tt.eq)) {
114 const equalsIndex = tokens.currentIndex();
115 // This is an initializer, so we need to wrap in an initializer method.
116 const valueEnd = tokens.currentToken().rhsEndIndex;
117 if (valueEnd == null) {
118 throw new Error("Expected rhsEndIndex on class field assignment.");
119 }
120 tokens.nextToken();
121 while (tokens.currentIndex() < valueEnd) {
122 rootTransformer.processToken();
123 }
124 let initializerName;
125 if (isStatic) {
126 initializerName = nameManager.claimFreeName("__initStatic");
127 staticInitializerNames.push(initializerName);
128 } else {
129 initializerName = nameManager.claimFreeName("__init");
130 instanceInitializerNames.push(initializerName);
131 }
132 // Fields start at the name, so `static x = 1;` has a field range of `x = 1;`.
133 fields.push({
134 initializerName,
135 equalsIndex,
136 start: nameStartIndex,
137 end: tokens.currentIndex(),
138 });
139 } else {
140 // This is just a declaration, so doesn't need to produce any code in the output.
141 rangesToRemove.push({start: statementStartIndex, end: tokens.currentIndex()});
142 }
143 }
144 }
145
146 tokens.restoreToSnapshot(snapshot);
147 return {
148 headerInfo,
149 constructorInitializerStatements,
150 instanceInitializerNames,
151 staticInitializerNames,
152 constructorInsertPos,
153 fields,
154 rangesToRemove,
155 };
156}
157
158function processClassHeader(tokens) {
159 const classToken = tokens.currentToken();
160 const contextId = classToken.contextId;
161 if (contextId == null) {
162 throw new Error("Expected context ID on class token.");
163 }
164 const isExpression = classToken.isExpression;
165 if (isExpression == null) {
166 throw new Error("Expected isExpression on class token.");
167 }
168 let className = null;
169 let hasSuperclass = false;
170 tokens.nextToken();
171 if (tokens.matches1(tt.name)) {
172 className = tokens.identifierName();
173 }
174 while (!tokens.matchesContextIdAndLabel(tt.braceL, contextId)) {
175 // If this has a superclass, there will always be an `extends` token. If it doesn't have a
176 // superclass, only type parameters and `implements` clauses can show up here, all of which
177 // consist only of type tokens. A declaration like `class A<B extends C> {` should *not* count
178 // as having a superclass.
179 if (tokens.matches1(tt._extends) && !tokens.currentToken().isType) {
180 hasSuperclass = true;
181 }
182 tokens.nextToken();
183 }
184 return {isExpression, className, hasSuperclass};
185}
186
187/**
188 * Extract useful information out of a constructor, starting at the "constructor" name.
189 */
190function processConstructor(
191 tokens,
192) {
193 const constructorInitializerStatements = [];
194
195 tokens.nextToken();
196 const constructorContextId = tokens.currentToken().contextId;
197 if (constructorContextId == null) {
198 throw new Error("Expected context ID on open-paren starting constructor params.");
199 }
200 tokens.nextToken();
201 // Advance through parameters looking for access modifiers.
202 while (!tokens.matchesContextIdAndLabel(tt.parenR, constructorContextId)) {
203 if (isAccessModifier(tokens.currentToken())) {
204 tokens.nextToken();
205 while (isAccessModifier(tokens.currentToken())) {
206 tokens.nextToken();
207 }
208 const token = tokens.currentToken();
209 if (token.type !== tt.name) {
210 throw new Error("Expected identifier after access modifiers in constructor arg.");
211 }
212 const name = tokens.identifierNameForToken(token);
213 constructorInitializerStatements.push(`this.${name} = ${name}`);
214 }
215 tokens.nextToken();
216 }
217 // )
218 tokens.nextToken();
219 let constructorInsertPos = tokens.currentIndex();
220
221 // Advance through body looking for a super call.
222 let foundSuperCall = false;
223 while (!tokens.matchesContextIdAndLabel(tt.braceR, constructorContextId)) {
224 if (!foundSuperCall && tokens.matches2(tt._super, tt.parenL)) {
225 tokens.nextToken();
226 const superCallContextId = tokens.currentToken().contextId;
227 if (superCallContextId == null) {
228 throw new Error("Expected a context ID on the super call");
229 }
230 while (!tokens.matchesContextIdAndLabel(tt.parenR, superCallContextId)) {
231 tokens.nextToken();
232 }
233 constructorInsertPos = tokens.currentIndex();
234 foundSuperCall = true;
235 }
236 tokens.nextToken();
237 }
238 // }
239 tokens.nextToken();
240
241 return {constructorInitializerStatements, constructorInsertPos};
242}
243
244/**
245 * Determine if this is any token that can go before the name in a method/field.
246 */
247function isAccessModifier(token) {
248 return [
249 tt._async,
250 tt._get,
251 tt._set,
252 tt.plus,
253 tt.minus,
254 tt._readonly,
255 tt._static,
256 tt._public,
257 tt._private,
258 tt._protected,
259 tt._abstract,
260 ].includes(token.type);
261}
262
263/**
264 * The next token or set of tokens is either an identifier or an expression in square brackets, for
265 * a method or field name.
266 */
267function skipFieldName(tokens) {
268 if (tokens.matches1(tt.bracketL)) {
269 const startToken = tokens.currentToken();
270 const classContextId = startToken.contextId;
271 if (classContextId == null) {
272 throw new Error("Expected class context ID on computed name open bracket.");
273 }
274 while (!tokens.matchesContextIdAndLabel(tt.bracketR, classContextId)) {
275 tokens.nextToken();
276 }
277 tokens.nextToken();
278 } else {
279 tokens.nextToken();
280 }
281}