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

Function parseForLoopParameters

packages/compiler/src/render3/r3_control_flow.ts:360–473  ·  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

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

Callers 1

createForLoopFunction · 0.85

Calls 8

stripOptionalParenthesesFunction · 0.85
parseLetParameterFunction · 0.85
moveByMethod · 0.80
hasMethod · 0.65
joinMethod · 0.65
pushMethod · 0.45
matchMethod · 0.45

Tested by

no test coverage detected