MCPcopy Create free account
hub / github.com/angular/angular / parseForLoopParameters

Function parseForLoopParameters

packages/compiler/src/render3/r3_control_flow.ts:354–490  ·  view source on GitHub ↗

Parses the parameters of a `for` loop block.

(
  block: html.Block,
  errors: ParseError[],
  bindingParser: BindingParser,
)

Source from the content-addressed store, hash-verified

352
353/** Parses the parameters of a `for` loop block. */
354function parseForLoopParameters(
355 block: html.Block,
356 errors: ParseError[],
357 bindingParser: BindingParser,
358) {
359 if (block.parameters.length === 0) {
360 errors.push(new ParseError(block.startSourceSpan, '@for loop does not have an expression'));
361 return null;
362 }
363
364 const [expressionParam, ...secondaryParams] = block.parameters;
365 const match = stripOptionalParentheses(expressionParam, errors)?.match(
366 FOR_LOOP_EXPRESSION_PATTERN,
367 );
368
369 if (!match || match[2].trim().length === 0) {
370 errors.push(
371 new ParseError(
372 expressionParam.sourceSpan,
373 'Cannot parse expression. @for loop expression must match the pattern "<identifier> of <expression>"',
374 ),
375 );
376 return null;
377 }
378
379 const [, itemName, rawExpression] = match;
380 if (ALLOWED_FOR_LOOP_LET_VARIABLES.has(itemName)) {
381 errors.push(
382 new ParseError(
383 expressionParam.sourceSpan,
384 `@for loop item name cannot be one of ${Array.from(ALLOWED_FOR_LOOP_LET_VARIABLES).join(
385 ', ',
386 )}.`,
387 ),
388 );
389 }
390
391 // `expressionParam.expression` contains the variable declaration and the expression of the
392 // for...of statement, i.e. 'user of users' The variable of a ForOfStatement is _only_ the "const
393 // user" part and does not include "of x".
394 const variableName = expressionParam.expression.split(' ')[0];
395 const variableSpan = new ParseSourceSpan(
396 expressionParam.sourceSpan.start,
397 expressionParam.sourceSpan.start.moveBy(variableName.length),
398 );
399 const result = {
400 itemName: new t.Variable(itemName, '$implicit', variableSpan, variableSpan),
401 trackBy: null as {expression: ASTWithSource; keywordSpan: ParseSourceSpan} | null,
402 expression: parseBlockParameterToBinding(expressionParam, bindingParser, rawExpression),
403 context: Array.from(ALLOWED_FOR_LOOP_LET_VARIABLES, (variableName) => {
404 // Give ambiently-available context variables empty spans at the end of
405 // the start of the `for` block, since they are not explicitly defined.
406 const emptySpanAfterForBlockStart = new ParseSourceSpan(
407 block.startSourceSpan.end,
408 block.startSourceSpan.end,
409 );
410 return new t.Variable(
411 variableName,

Callers 1

createForLoopFunction · 0.85

Calls 9

parseLetParametersFunction · 0.90
stripOptionalParenthesesFunction · 0.85
moveByMethod · 0.80
someMethod · 0.80
hasMethod · 0.65
joinMethod · 0.65
pushMethod · 0.45
matchMethod · 0.45

Tested by

no test coverage detected