forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathr3_control_flow.ts
473 lines (404 loc) · 17.2 KB
/
r3_control_flow.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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ASTWithSource} from '../expression_parser/ast';
import * as html from '../ml_parser/ast';
import {ParseError, ParseSourceSpan} from '../parse_util';
import {BindingParser} from '../template_parser/binding_parser';
import * as t from './r3_ast';
/** Pattern for the expression in a for loop block. */
const FOR_LOOP_EXPRESSION_PATTERN = /^\s*([0-9A-Za-z_$]*)\s+of\s+(.*)/;
/** Pattern for the tracking expression in a for loop block. */
const FOR_LOOP_TRACK_PATTERN = /^track\s+([\S\s]*)/;
/** Pattern for the `as` expression in a conditional block. */
const CONDITIONAL_ALIAS_PATTERN = /^as\s+(.*)/;
/** Pattern used to identify an `else if` block. */
const ELSE_IF_PATTERN = /^else[^\S\r\n]+if/;
/** Pattern used to identify a `let` parameter. */
const FOR_LOOP_LET_PATTERN = /^let\s+([\S\s]*)/;
/** Names of variables that are allowed to be used in the `let` expression of a `for` loop. */
const ALLOWED_FOR_LOOP_LET_VARIABLES =
new Set<keyof t.ForLoopBlockContext>(['$index', '$first', '$last', '$even', '$odd', '$count']);
/**
* Predicate function that determines if a block with
* a specific name cam be connected to a `for` block.
*/
export function isConnectedForLoopBlock(name: string): boolean {
return name === 'empty';
}
/**
* Predicate function that determines if a block with
* a specific name cam be connected to an `if` block.
*/
export function isConnectedIfLoopBlock(name: string): boolean {
return name === 'else' || ELSE_IF_PATTERN.test(name);
}
/** Creates an `if` loop block from an HTML AST node. */
export function createIfBlock(
ast: html.Block, connectedBlocks: html.Block[], visitor: html.Visitor,
bindingParser: BindingParser): {node: t.IfBlock|null, errors: ParseError[]} {
const errors: ParseError[] = validateIfConnectedBlocks(connectedBlocks);
const branches: t.IfBlockBranch[] = [];
const mainBlockParams = parseConditionalBlockParameters(ast, errors, bindingParser);
if (mainBlockParams !== null) {
branches.push(new t.IfBlockBranch(
mainBlockParams.expression, html.visitAll(visitor, ast.children, ast.children),
mainBlockParams.expressionAlias, ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan));
}
for (const block of connectedBlocks) {
if (ELSE_IF_PATTERN.test(block.name)) {
const params = parseConditionalBlockParameters(block, errors, bindingParser);
if (params !== null) {
const children = html.visitAll(visitor, block.children, block.children);
branches.push(new t.IfBlockBranch(
params.expression, children, params.expressionAlias, block.sourceSpan,
block.startSourceSpan, block.endSourceSpan));
}
} else if (block.name === 'else') {
const children = html.visitAll(visitor, block.children, block.children);
branches.push(new t.IfBlockBranch(
null, children, null, block.sourceSpan, block.startSourceSpan, block.endSourceSpan));
}
}
// The outer IfBlock should have a span that encapsulates all branches.
const ifBlockStartSourceSpan =
branches.length > 0 ? branches[0].startSourceSpan : ast.startSourceSpan;
const ifBlockEndSourceSpan =
branches.length > 0 ? branches[branches.length - 1].endSourceSpan : ast.endSourceSpan;
let wholeSourceSpan = ast.sourceSpan;
const lastBranch = branches[branches.length - 1];
if (lastBranch !== undefined) {
wholeSourceSpan = new ParseSourceSpan(ifBlockStartSourceSpan.start, lastBranch.sourceSpan.end);
}
return {
node: new t.IfBlock(branches, wholeSourceSpan, ast.startSourceSpan, ifBlockEndSourceSpan),
errors,
};
}
/** Creates a `for` loop block from an HTML AST node. */
export function createForLoop(
ast: html.Block, connectedBlocks: html.Block[], visitor: html.Visitor,
bindingParser: BindingParser): {node: t.ForLoopBlock|null, errors: ParseError[]} {
const errors: ParseError[] = [];
const params = parseForLoopParameters(ast, errors, bindingParser);
let node: t.ForLoopBlock|null = null;
let empty: t.ForLoopBlockEmpty|null = null;
for (const block of connectedBlocks) {
if (block.name === 'empty') {
if (empty !== null) {
errors.push(new ParseError(block.sourceSpan, '@for loop can only have one @empty block'));
} else if (block.parameters.length > 0) {
errors.push(new ParseError(block.sourceSpan, '@empty block cannot have parameters'));
} else {
empty = new t.ForLoopBlockEmpty(
html.visitAll(visitor, block.children, block.children), block.sourceSpan,
block.startSourceSpan, block.endSourceSpan);
}
} else {
errors.push(new ParseError(block.sourceSpan, `Unrecognized @for loop block "${block.name}"`));
}
}
if (params !== null) {
if (params.trackBy === null) {
// TODO: We should not fail here, and instead try to produce some AST for the language
// service.
errors.push(new ParseError(ast.sourceSpan, '@for loop must have a "track" expression'));
} else {
// The `for` block has a main span that includes the `empty` branch. For only the span of the
// main `for` body, use `mainSourceSpan`.
const endSpan = empty?.endSourceSpan ?? ast.endSourceSpan;
const sourceSpan =
new ParseSourceSpan(ast.sourceSpan.start, endSpan?.end ?? ast.sourceSpan.end);
node = new t.ForLoopBlock(
params.itemName, params.expression, params.trackBy, params.context,
html.visitAll(visitor, ast.children, ast.children), empty, sourceSpan, ast.sourceSpan,
ast.startSourceSpan, endSpan);
}
}
return {node, errors};
}
/** Creates a switch block from an HTML AST node. */
export function createSwitchBlock(
ast: html.Block, visitor: html.Visitor,
bindingParser: BindingParser): {node: t.SwitchBlock|null, errors: ParseError[]} {
const errors = validateSwitchBlock(ast);
const primaryExpression = ast.parameters.length > 0 ?
parseBlockParameterToBinding(ast.parameters[0], bindingParser) :
bindingParser.parseBinding('', false, ast.sourceSpan, 0);
const cases: t.SwitchBlockCase[] = [];
const unknownBlocks: t.UnknownBlock[] = [];
let defaultCase: t.SwitchBlockCase|null = null;
// Here we assume that all the blocks are valid given that we validated them above.
for (const node of ast.children) {
if (!(node instanceof html.Block)) {
continue;
}
if ((node.name !== 'case' || node.parameters.length === 0) && node.name !== 'default') {
unknownBlocks.push(new t.UnknownBlock(node.name, node.sourceSpan, node.sourceSpan));
continue;
}
const expression = node.name === 'case' ?
parseBlockParameterToBinding(node.parameters[0], bindingParser) :
null;
const ast = new t.SwitchBlockCase(
expression, html.visitAll(visitor, node.children, node.children), node.sourceSpan,
node.startSourceSpan, node.endSourceSpan);
if (expression === null) {
defaultCase = ast;
} else {
cases.push(ast);
}
}
// Ensure that the default case is last in the array.
if (defaultCase !== null) {
cases.push(defaultCase);
}
return {
node: new t.SwitchBlock(
primaryExpression, cases, unknownBlocks, ast.sourceSpan, ast.startSourceSpan,
ast.endSourceSpan),
errors
};
}
/** Parses the parameters of a `for` loop block. */
function parseForLoopParameters(
block: html.Block, errors: ParseError[], bindingParser: BindingParser) {
if (block.parameters.length === 0) {
errors.push(new ParseError(block.sourceSpan, '@for loop does not have an expression'));
return null;
}
const [expressionParam, ...secondaryParams] = block.parameters;
const match =
stripOptionalParentheses(expressionParam, errors)?.match(FOR_LOOP_EXPRESSION_PATTERN);
if (!match || match[2].trim().length === 0) {
errors.push(new ParseError(
expressionParam.sourceSpan,
'Cannot parse expression. @for loop expression must match the pattern "<identifier> of <expression>"'));
return null;
}
const [, itemName, rawExpression] = match;
const result = {
itemName: new t.Variable(
itemName, '$implicit', expressionParam.sourceSpan, expressionParam.sourceSpan),
trackBy: null as ASTWithSource | null,
expression: parseBlockParameterToBinding(expressionParam, bindingParser, rawExpression),
context: {} as t.ForLoopBlockContext,
};
for (const param of secondaryParams) {
const letMatch = param.expression.match(FOR_LOOP_LET_PATTERN);
if (letMatch !== null) {
parseLetParameter(param.sourceSpan, letMatch[1], param.sourceSpan, result.context, errors);
continue;
}
const trackMatch = param.expression.match(FOR_LOOP_TRACK_PATTERN);
if (trackMatch !== null) {
if (result.trackBy !== null) {
errors.push(
new ParseError(param.sourceSpan, '@for loop can only have one "track" expression'));
} else {
result.trackBy = parseBlockParameterToBinding(param, bindingParser, trackMatch[1]);
}
continue;
}
errors.push(
new ParseError(param.sourceSpan, `Unrecognized @for loop paramater "${param.expression}"`));
}
// Fill out any variables that haven't been defined explicitly.
for (const variableName of ALLOWED_FOR_LOOP_LET_VARIABLES) {
if (!result.context.hasOwnProperty(variableName)) {
// Give ambiently-available context variables empty spans at the end of the start of the `for`
// block, since they are not explicitly defined.
const emptySpanAfterForBlockStart =
new ParseSourceSpan(block.startSourceSpan.end, block.startSourceSpan.end);
result.context[variableName] = new t.Variable(
variableName, variableName, emptySpanAfterForBlockStart, emptySpanAfterForBlockStart);
}
}
return result;
}
/** Parses the `let` parameter of a `for` loop block. */
function parseLetParameter(
sourceSpan: ParseSourceSpan, expression: string, span: ParseSourceSpan,
context: t.ForLoopBlockContext, errors: ParseError[]): void {
const parts = expression.split(',');
for (const part of parts) {
const expressionParts = part.split('=');
const name = expressionParts.length === 2 ? expressionParts[0].trim() : '';
const variableName = (expressionParts.length === 2 ? expressionParts[1].trim() : '') as
keyof t.ForLoopBlockContext;
if (name.length === 0 || variableName.length === 0) {
errors.push(new ParseError(
sourceSpan,
`Invalid @for loop "let" parameter. Parameter should match the pattern "<name> = <variable name>"`));
} else if (!ALLOWED_FOR_LOOP_LET_VARIABLES.has(variableName)) {
errors.push(new ParseError(
sourceSpan,
`Unknown "let" parameter variable "${variableName}". The allowed variables are: ${
Array.from(ALLOWED_FOR_LOOP_LET_VARIABLES).join(', ')}`));
} else if (context.hasOwnProperty(variableName)) {
errors.push(
new ParseError(sourceSpan, `Duplicate "let" parameter variable "${variableName}"`));
} else {
context[variableName] = new t.Variable(name, variableName, span, span);
}
}
}
/**
* Checks that the shape of the blocks connected to an
* `@if` block is correct. Returns an array of errors.
*/
function validateIfConnectedBlocks(connectedBlocks: html.Block[]): ParseError[] {
const errors: ParseError[] = [];
let hasElse = false;
for (let i = 0; i < connectedBlocks.length; i++) {
const block = connectedBlocks[i];
if (block.name === 'else') {
if (hasElse) {
errors.push(new ParseError(block.sourceSpan, 'Conditional can only have one @else block'));
} else if (connectedBlocks.length > 1 && i < connectedBlocks.length - 1) {
errors.push(
new ParseError(block.sourceSpan, '@else block must be last inside the conditional'));
} else if (block.parameters.length > 0) {
errors.push(new ParseError(block.sourceSpan, '@else block cannot have parameters'));
}
hasElse = true;
} else if (!ELSE_IF_PATTERN.test(block.name)) {
errors.push(
new ParseError(block.sourceSpan, `Unrecognized conditional block @${block.name}`));
}
}
return errors;
}
/** Checks that the shape of a `switch` block is valid. Returns an array of errors. */
function validateSwitchBlock(ast: html.Block): ParseError[] {
const errors: ParseError[] = [];
let hasDefault = false;
if (ast.parameters.length !== 1) {
errors.push(new ParseError(ast.sourceSpan, '@switch block must have exactly one parameter'));
return errors;
}
for (const node of ast.children) {
// Skip over empty text nodes inside the switch block since they can be used for formatting.
if (node instanceof html.Text && node.value.trim().length === 0) {
continue;
}
if (!(node instanceof html.Block) || (node.name !== 'case' && node.name !== 'default')) {
errors.push(new ParseError(
node.sourceSpan, '@switch block can only contain @case and @default blocks'));
continue;
}
if (node.name === 'default') {
if (hasDefault) {
errors.push(
new ParseError(node.sourceSpan, '@switch block can only have one @default block'));
} else if (node.parameters.length > 0) {
errors.push(new ParseError(node.sourceSpan, '@default block cannot have parameters'));
}
hasDefault = true;
} else if (node.name === 'case' && node.parameters.length !== 1) {
errors.push(new ParseError(node.sourceSpan, '@case block must have exactly one parameter'));
}
}
return errors;
}
/**
* Parses a block parameter into a binding AST.
* @param ast Block parameter that should be parsed.
* @param bindingParser Parser that the expression should be parsed with.
* @param part Specific part of the expression that should be parsed.
*/
function parseBlockParameterToBinding(
ast: html.BlockParameter, bindingParser: BindingParser, part?: string): ASTWithSource {
let start: number;
let end: number;
if (typeof part === 'string') {
// Note: `lastIndexOf` here should be enough to know the start index of the expression,
// because we know that it'll be at the end of the param. Ideally we could use the `d`
// flag when matching via regex and get the index from `match.indices`, but it's unclear
// if we can use it yet since it's a relatively new feature. See:
// https://github.com/tc39/proposal-regexp-match-indices
start = Math.max(0, ast.expression.lastIndexOf(part));
end = start + part.length;
} else {
start = 0;
end = ast.expression.length;
}
return bindingParser.parseBinding(
ast.expression.slice(start, end), false, ast.sourceSpan, ast.sourceSpan.start.offset + start);
}
/** Parses the parameter of a conditional block (`if` or `else if`). */
function parseConditionalBlockParameters(
block: html.Block, errors: ParseError[], bindingParser: BindingParser) {
if (block.parameters.length === 0) {
errors.push(new ParseError(block.sourceSpan, 'Conditional block does not have an expression'));
return null;
}
const expression = parseBlockParameterToBinding(block.parameters[0], bindingParser);
let expressionAlias: t.Variable|null = null;
// Start from 1 since we processed the first parameter already.
for (let i = 1; i < block.parameters.length; i++) {
const param = block.parameters[i];
const aliasMatch = param.expression.match(CONDITIONAL_ALIAS_PATTERN);
// For now conditionals can only have an `as` parameter.
// We may want to rework this later if we add more.
if (aliasMatch === null) {
errors.push(new ParseError(
param.sourceSpan, `Unrecognized conditional paramater "${param.expression}"`));
} else if (block.name !== 'if') {
errors.push(new ParseError(
param.sourceSpan, '"as" expression is only allowed on the primary @if block'));
} else if (expressionAlias !== null) {
errors.push(
new ParseError(param.sourceSpan, 'Conditional can only have one "as" expression'));
} else {
const name = aliasMatch[1].trim();
expressionAlias = new t.Variable(name, name, param.sourceSpan, param.sourceSpan);
}
}
return {expression, expressionAlias};
}
/** Strips optional parentheses around from a control from expression parameter. */
function stripOptionalParentheses(param: html.BlockParameter, errors: ParseError[]): string|null {
const expression = param.expression;
const spaceRegex = /^\s$/;
let openParens = 0;
let start = 0;
let end = expression.length - 1;
for (let i = 0; i < expression.length; i++) {
const char = expression[i];
if (char === '(') {
start = i + 1;
openParens++;
} else if (spaceRegex.test(char)) {
continue;
} else {
break;
}
}
if (openParens === 0) {
return expression;
}
for (let i = expression.length - 1; i > -1; i--) {
const char = expression[i];
if (char === ')') {
end = i;
openParens--;
if (openParens === 0) {
break;
}
} else if (spaceRegex.test(char)) {
continue;
} else {
break;
}
}
if (openParens !== 0) {
errors.push(new ParseError(param.sourceSpan, 'Unclosed parentheses in expression'));
return null;
}
return expression.slice(start, end);
}