-
Notifications
You must be signed in to change notification settings - Fork 582
/
Copy pathPlaceholderParser.js
344 lines (314 loc) · 10.4 KB
/
PlaceholderParser.js
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
// Copyright 2012 Traceur Authors.
//
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {
ARGUMENT_LIST,
BLOCK,
EXPRESSION_STATEMENT,
FUNCTION_BODY,
IDENTIFIER_EXPRESSION
} from '../syntax/trees/ParseTreeType.js';
import {IdentifierToken} from '../syntax/IdentifierToken.js';
import {LiteralToken} from '../syntax/LiteralToken.js';
import {CollectingErrorReporter} from '../util/CollectingErrorReporter.js';
import {Options} from '../Options.js';
import {ParseTree} from '../syntax/trees/ParseTree.js';
import {ParseTreeTransformer} from './ParseTreeTransformer.js';
import {Parser} from '../syntax/Parser.js';
import {
LiteralExpression,
LiteralPropertyName,
TypeName
} from '../syntax/trees/ParseTrees.js';
import {SourceFile} from '../syntax/SourceFile.js';
import {IDENTIFIER} from '../syntax/TokenType.js';
import {
createArrayLiteral,
createBindingIdentifier,
createBlock,
createBooleanLiteral,
createCommaExpression,
createExpressionStatement,
createFunctionBody,
createIdentifierExpression,
createIdentifierToken,
createMemberExpression,
createNullLiteral,
createNumberLiteral,
createParenExpression,
createStringLiteral,
createVoid0
} from './ParseTreeFactory.js';
/**
* @fileoverview This file provides a few template string functions,
* |parseExpression|, |parseStatement|, etc, which parse a string with
* placeholders. The values in the placeholders can be JS values, ParseTrees or
* IdentifierTokens.
*
* For example:
*
* parseExpression`function() { return ${myTree}; }`
*
* returns a FunctionExpression tree that returns |myTree|.
*
* At the moment placeholders are allowed where a BindingIdentifier and
* IdentifierExpression are allowed.
*
* Beware that strings are treated as BindingIdentifiers in binding context but
* string literals in expression context. To work around that pass in an
* IdentifierToken.
*/
/**
* Sentinel used for |getValue_| to signal no value was found.
*/
const NOT_FOUND = {};
/**
* @param {function(Parser) : ParseTree} doParse Function that calls the correct
* parse method on the parser.
*/
function makeParseFunction(doParse) {
let cache = new Map();
return (sourceLiterals, ...values) => {
return parse(sourceLiterals, values, doParse, cache);
};
}
/**
* @param {Array.<string>} sourceLiterals
* @param {Array} values An array containing values or parse trees.
* @return {ParseTree}
*/
export let parseExpression = makeParseFunction((p) => p.parseExpression());
export let parseStatement = makeParseFunction((p) => p.parseStatement());
export let parseModule = makeParseFunction((p) => p.parseModule());
export let parseScript = makeParseFunction((p) => p.parseScript());
export let parseStatements = makeParseFunction((p) => p.parseStatements());
export let parsePropertyDefinition =
makeParseFunction((p) => p.parsePropertyDefinition());
function parse(sourceLiterals, values, doParse, cache) {
let tree = cache.get(sourceLiterals);
if (!tree) {
let source = insertPlaceholderIdentifiers(sourceLiterals);
let errorReporter = new CollectingErrorReporter();
let parser = getParser(source, errorReporter);
tree = doParse(parser);
if (errorReporter.hadError() || !tree || !parser.isAtEnd()) {
throw new Error(
`Internal error trying to parse:\n\n${source}\n\n${
errorReporter.errorsAsString()}`);
}
cache.set(sourceLiterals, tree);
}
if (!values.length)
return tree;
// We allow either a ParseTree or an Array as the result of doParse. An
// array is returned for parseStatements.
if (tree instanceof ParseTree)
return new PlaceholderTransformer(values).transformAny(tree);
return new PlaceholderTransformer(values).transformList(tree);
}
const PREFIX = '$__placeholder__';
/**
* @param {Array.<string>} sourceLiterals
* @return {string}
*/
function insertPlaceholderIdentifiers(sourceLiterals) {
let source = sourceLiterals[0];
for (let i = 1; i < sourceLiterals.length; i++) {
source += PREFIX + String(i - 1) + sourceLiterals[i];
}
return source;
}
let counter = 0;
function getParser(source, errorReporter) {
let file = new SourceFile(null, source);
let options = new Options();
// Enable internal code to always use all experimental features.
options.experimental = true;
return new Parser(file, errorReporter, options);
}
/**
* @param {*} value
* @return {ParseTree}
*/
function convertValueToExpression(value) {
if (value instanceof ParseTree)
return value;
if (value instanceof IdentifierToken)
return createIdentifierExpression(value);
if (value instanceof LiteralToken)
return new LiteralExpression(value.location, value);
if (Array.isArray(value)) {
if (value[0] instanceof ParseTree) {
if (value.length === 1)
return value[0];
if (value[0].isStatement())
return createBlock(value);
else
return createParenExpression(createCommaExpression(value));
}
return createArrayLiteral(value.map(convertValueToExpression));
}
if (value === null)
return createNullLiteral();
if (value === undefined)
return createVoid0();
switch (typeof value) {
case 'string':
return createStringLiteral(value);
case 'boolean':
return createBooleanLiteral(value);
case 'number':
return createNumberLiteral(value);
}
throw new Error('Not implemented');
}
function convertValueToIdentifierToken(value) {
if (value instanceof IdentifierToken)
return value;
return createIdentifierToken(value);
}
function convertValueToType(value) {
// We allow null here since it is common to have `var x : ${value}`.
if (value === null) return null;
if (value instanceof ParseTree) return value;
if (typeof value === 'string') {
return new TypeName(null, null, convertValueToIdentifierToken(value));
}
if (value instanceof IdentifierToken) {
return new TypeName(null, null, value);
}
throw new Error('Not implemented');
}
/**
* Transforms a ParseTree containing placeholders.
*/
export class PlaceholderTransformer extends ParseTreeTransformer {
/**
* @param {Array} values The values to replace the placeholders with.
*/
constructor(values) {
super();
this.values = values;
}
/**
* This gets called by the transformer when the index'th placeholder is
* going to be replaced.
* @param {number} index
* @return {ParseTree}
*/
getValueAt(index) {
return this.values[index];
}
/**
*
* @param {string} str
* @return {*} This returns the |NOT_FOUND| sentinel if the |str| does not
* represent a placeholder.
*/
getValue_(str) {
if (str.indexOf(PREFIX) !== 0)
return NOT_FOUND;
return this.getValueAt(Number(str.slice(PREFIX.length)));
}
transformIdentifierExpression(tree) {
let value = this.getValue_(tree.identifierToken.value);
if (value === NOT_FOUND)
return tree;
return convertValueToExpression(value);
}
transformBindingIdentifier(tree) {
let value = this.getValue_(tree.identifierToken.value);
if (value === NOT_FOUND)
return tree;
return createBindingIdentifier(value);
}
transformExpressionStatement(tree) {
if (tree.expression.type === IDENTIFIER_EXPRESSION) {
let transformedExpression =
this.transformIdentifierExpression(tree.expression);
if (transformedExpression === tree.expression)
return tree;
if (transformedExpression.isStatementListItem() ||
transformedExpression.type === FUNCTION_BODY) {
return transformedExpression;
}
return createExpressionStatement(transformedExpression);
}
return super.transformExpressionStatement(tree);
}
transformBlock(tree) {
if (tree.statements.length === 1 &&
tree.statements[0].type === EXPRESSION_STATEMENT) {
let transformedStatement =
this.transformExpressionStatement(tree.statements[0]);
if (transformedStatement === tree.statements[0])
return tree;
if (transformedStatement.type === BLOCK)
return transformedStatement;
}
return super.transformBlock(tree);
}
transformFunctionBody(tree) {
if (tree.statements.length === 1 &&
tree.statements[0].type === EXPRESSION_STATEMENT) {
let transformedStatement =
this.transformExpressionStatement(tree.statements[0]);
if (transformedStatement.type === FUNCTION_BODY)
return transformedStatement;
if (transformedStatement === tree.statements[0])
return tree;
if (transformedStatement.type === BLOCK)
return createFunctionBody(transformedStatement.statements);
}
return super.transformFunctionBody(tree);
}
transformMemberExpression(tree) {
let value = this.getValue_(tree.memberName.value);
if (value === NOT_FOUND)
return super.transformMemberExpression(tree);
let operand = this.transformAny(tree.operand);
return createMemberExpression(operand, value);
}
transformLiteralPropertyName(tree) {
if (tree.literalToken.type === IDENTIFIER) {
let value = this.getValue_(tree.literalToken.value);
if (value !== NOT_FOUND) {
return new LiteralPropertyName(null,
convertValueToIdentifierToken(value));
}
}
return super.transformLiteralPropertyName(tree);
}
transformArgumentList(tree) {
if (tree.args.length === 1 &&
tree.args[0].type === IDENTIFIER_EXPRESSION) {
let arg0 = this.transformAny(tree.args[0]);
if (arg0 === tree.args[0])
return tree;
if (arg0.type === ARGUMENT_LIST)
return arg0;
}
return super.transformArgumentList(tree);
}
transformTypeName(tree) {
let value = this.getValue_(tree.name.value);
if (value === NOT_FOUND)
return super.transformTypeName(tree);
let moduleName = this.transformAny(tree.moduleName);
if (moduleName !== null) {
return new TypeName(null, moduleName,
convertValueToIdentifierToken(value));
}
return convertValueToType(value);
}
}