_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/compiler/src/render3/r3_class_debug_info_compiler.ts_0_2817 | /**
* @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.dev/license
*/
import {mapLiteral} from '../output/map_util';
import * as o from '../output/output_ast';
import {Identifiers as R3} from './r3_identifiers';
import {devOnlyGuardedExpression} from './util';
/**
* Info needed for runtime errors related to a class, such as the location in which the class is
* defined.
*/
export interface R3ClassDebugInfo {
/** The class identifier */
type: o.Expression;
/**
* A string literal containing the original class name as appears in its definition.
*/
className: o.Expression;
/**
* A string literal containing the relative path of the file in which the class is defined.
*
* The path is relative to the project root. The compiler does the best effort to find the project
* root (e.g., using the rootDir of tsconfig), but if it fails this field is set to null,
* indicating that the file path was failed to be computed. In this case, the downstream consumers
* of the debug info will usually ignore the `lineNumber` field as well and just show the
* `className`. For security reasons we never show the absolute file path and prefer to just
* return null here.
*/
filePath: o.Expression | null;
/**
* A number literal number containing the line number in which this class is defined.
*/
lineNumber: o.Expression;
/**
* Whether to check if this component is being rendered without its NgModule being loaded into the
* browser. Such checks is carried out only in dev mode.
*/
forbidOrphanRendering: boolean;
}
/**
* Generate an ngDevMode guarded call to setClassDebugInfo with the debug info about the class
* (e.g., the file name in which the class is defined)
*/
export function compileClassDebugInfo(debugInfo: R3ClassDebugInfo): o.Expression {
const debugInfoObject: {
className: o.Expression;
filePath?: o.Expression;
lineNumber?: o.Expression;
forbidOrphanRendering?: o.Expression;
} = {
className: debugInfo.className,
};
// Include file path and line number only if the file relative path is calculated successfully.
if (debugInfo.filePath) {
debugInfoObject.filePath = debugInfo.filePath;
debugInfoObject.lineNumber = debugInfo.lineNumber;
}
// Include forbidOrphanRendering only if it's set to true (to reduce generated code)
if (debugInfo.forbidOrphanRendering) {
debugInfoObject.forbidOrphanRendering = o.literal(true);
}
const fnCall = o
.importExpr(R3.setClassDebugInfo)
.callFn([debugInfo.type, mapLiteral(debugInfoObject)]);
const iife = o.arrowFn([], [devOnlyGuardedExpression(fnCall).toStmt()]);
return iife.callFn([]);
}
| {
"end_byte": 2817,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_class_debug_info_compiler.ts"
} |
angular/packages/compiler/src/render3/r3_control_flow.ts_0_6808 | /**
* @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.dev/license
*/
import {ASTWithSource, EmptyExpr} 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+([\S\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]*)/;
/**
* Pattern to group a string into leading whitespace, non whitespace, and trailing whitespace.
* Useful for getting the variable name span when a span can contain leading and trailing space.
*/
const CHARACTERS_IN_SURROUNDING_WHITESPACE_PATTERN = /(\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([
'$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,
ast.nameSpan,
ast.i18n,
),
);
}
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,
block.nameSpan,
block.i18n,
),
);
}
} 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,
block.nameSpan,
block.i18n,
),
);
}
}
// 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,
ast.nameSpan,
),
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,
block.nameSpan,
block.i18n,
);
}
} 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.startSourceSpan, '@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.expression,
params.trackBy.keywordSpan,
params.context,
html.visitAll(visitor, ast.children, ast.children),
empty,
sourceSpan,
ast.sourceSpan,
ast.startSourceSpan,
endSpan,
ast.nameSpan,
ast.i18n,
);
}
}
return {node, errors};
}
/** Creates a switch block from an HTML AST node. */ | {
"end_byte": 6808,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_control_flow.ts"
} |
angular/packages/compiler/src/render3/r3_control_flow.ts_6809_15369 | 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.nameSpan));
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,
node.nameSpan,
node.i18n,
);
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,
ast.nameSpan,
),
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.startSourceSpan, '@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;
if (ALLOWED_FOR_LOOP_LET_VARIABLES.has(itemName)) {
errors.push(
new ParseError(
expressionParam.sourceSpan,
`@for loop item name cannot be one of ${Array.from(ALLOWED_FOR_LOOP_LET_VARIABLES).join(
', ',
)}.`,
),
);
}
// `expressionParam.expression` contains the variable declaration and the expression of the
// for...of statement, i.e. 'user of users' The variable of a ForOfStatement is _only_ the "const
// user" part and does not include "of x".
const variableName = expressionParam.expression.split(' ')[0];
const variableSpan = new ParseSourceSpan(
expressionParam.sourceSpan.start,
expressionParam.sourceSpan.start.moveBy(variableName.length),
);
const result = {
itemName: new t.Variable(itemName, '$implicit', variableSpan, variableSpan),
trackBy: null as {expression: ASTWithSource; keywordSpan: ParseSourceSpan} | null,
expression: parseBlockParameterToBinding(expressionParam, bindingParser, rawExpression),
context: Array.from(ALLOWED_FOR_LOOP_LET_VARIABLES, (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,
);
return new t.Variable(
variableName,
variableName,
emptySpanAfterForBlockStart,
emptySpanAfterForBlockStart,
);
}),
};
for (const param of secondaryParams) {
const letMatch = param.expression.match(FOR_LOOP_LET_PATTERN);
if (letMatch !== null) {
const variablesSpan = new ParseSourceSpan(
param.sourceSpan.start.moveBy(letMatch[0].length - letMatch[1].length),
param.sourceSpan.end,
);
parseLetParameter(
param.sourceSpan,
letMatch[1],
variablesSpan,
itemName,
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 {
const expression = parseBlockParameterToBinding(param, bindingParser, trackMatch[1]);
if (expression.ast instanceof EmptyExpr) {
errors.push(
new ParseError(block.startSourceSpan, '@for loop must have a "track" expression'),
);
}
const keywordSpan = new ParseSourceSpan(
param.sourceSpan.start,
param.sourceSpan.start.moveBy('track'.length),
);
result.trackBy = {expression, keywordSpan};
}
continue;
}
errors.push(
new ParseError(param.sourceSpan, `Unrecognized @for loop paramater "${param.expression}"`),
);
}
return result;
}
/** Parses the `let` parameter of a `for` loop block. */
function parseLetParameter(
sourceSpan: ParseSourceSpan,
expression: string,
span: ParseSourceSpan,
loopItemName: string,
context: t.Variable[],
errors: ParseError[],
): void {
const parts = expression.split(',');
let startSpan = span.start;
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() : '';
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 (name === loopItemName) {
errors.push(
new ParseError(
sourceSpan,
`Invalid @for loop "let" parameter. Variable cannot be called "${loopItemName}"`,
),
);
} else if (context.some((v) => v.name === name)) {
errors.push(
new ParseError(sourceSpan, `Duplicate "let" parameter variable "${variableName}"`),
);
} else {
const [, keyLeadingWhitespace, keyName] =
expressionParts[0].match(CHARACTERS_IN_SURROUNDING_WHITESPACE_PATTERN) ?? [];
const keySpan =
keyLeadingWhitespace !== undefined && expressionParts.length === 2
? new ParseSourceSpan(
/* strip leading spaces */
startSpan.moveBy(keyLeadingWhitespace.length),
/* advance to end of the variable name */
startSpan.moveBy(keyLeadingWhitespace.length + keyName.length),
)
: span;
let valueSpan: ParseSourceSpan | undefined = undefined;
if (expressionParts.length === 2) {
const [, valueLeadingWhitespace, implicit] =
expressionParts[1].match(CHARACTERS_IN_SURROUNDING_WHITESPACE_PATTERN) ?? [];
valueSpan =
valueLeadingWhitespace !== undefined
? new ParseSourceSpan(
startSpan.moveBy(expressionParts[0].length + 1 + valueLeadingWhitespace.length),
startSpan.moveBy(
expressionParts[0].length + 1 + valueLeadingWhitespace.length + implicit.length,
),
)
: undefined;
}
const sourceSpan = new ParseSourceSpan(keySpan.start, valueSpan?.end ?? keySpan.end);
context.push(new t.Variable(name, variableName, sourceSpan, keySpan, valueSpan));
}
startSpan = startSpan.moveBy(part.length + 1 /* add 1 to move past the comma */);
}
} | {
"end_byte": 15369,
"start_byte": 6809,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_control_flow.ts"
} |
angular/packages/compiler/src/render3/r3_control_flow.ts_15371_22121 | /**
* 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.startSourceSpan, 'Conditional can only have one @else block'),
);
} else if (connectedBlocks.length > 1 && i < connectedBlocks.length - 1) {
errors.push(
new ParseError(block.startSourceSpan, '@else block must be last inside the conditional'),
);
} else if (block.parameters.length > 0) {
errors.push(new ParseError(block.startSourceSpan, '@else block cannot have parameters'));
}
hasElse = true;
} else if (!ELSE_IF_PATTERN.test(block.name)) {
errors.push(
new ParseError(block.startSourceSpan, `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.startSourceSpan, '@switch block must have exactly one parameter'),
);
return errors;
}
for (const node of ast.children) {
// Skip over comments and empty text nodes inside the switch block.
// Empty text nodes can be used for formatting while comments don't affect the runtime.
if (
node instanceof html.Comment ||
(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.startSourceSpan, '@switch block can only have one @default block'),
);
} else if (node.parameters.length > 0) {
errors.push(new ParseError(node.startSourceSpan, '@default block cannot have parameters'));
}
hasDefault = true;
} else if (node.name === 'case' && node.parameters.length !== 1) {
errors.push(
new ParseError(node.startSourceSpan, '@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.startSourceSpan, '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[2].trim();
const variableStart = param.sourceSpan.start.moveBy(aliasMatch[1].length);
const variableSpan = new ParseSourceSpan(variableStart, variableStart.moveBy(name.length));
expressionAlias = new t.Variable(name, name, variableSpan, variableSpan);
}
}
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);
} | {
"end_byte": 22121,
"start_byte": 15371,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_control_flow.ts"
} |
angular/packages/compiler/src/render3/r3_class_metadata_compiler.ts_0_5729 | /**
* @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.dev/license
*/
import * as o from '../output/output_ast';
import {Identifiers as R3} from './r3_identifiers';
import {devOnlyGuardedExpression} from './util';
import {R3DeferPerComponentDependency} from './view/api';
export type CompileClassMetadataFn = (metadata: R3ClassMetadata) => o.Expression;
/**
* Metadata of a class which captures the original Angular decorators of a class. The original
* decorators are preserved in the generated code to allow TestBed APIs to recompile the class
* using the original decorator with a set of overrides applied.
*/
export interface R3ClassMetadata {
/**
* The class type for which the metadata is captured.
*/
type: o.Expression;
/**
* An expression representing the Angular decorators that were applied on the class.
*/
decorators: o.Expression;
/**
* An expression representing the Angular decorators applied to constructor parameters, or `null`
* if there is no constructor.
*/
ctorParameters: o.Expression | null;
/**
* An expression representing the Angular decorators that were applied on the properties of the
* class, or `null` if no properties have decorators.
*/
propDecorators: o.Expression | null;
}
export function compileClassMetadata(metadata: R3ClassMetadata): o.InvokeFunctionExpr {
const fnCall = internalCompileClassMetadata(metadata);
return o.arrowFn([], [devOnlyGuardedExpression(fnCall).toStmt()]).callFn([]);
}
/** Compiles only the `setClassMetadata` call without any additional wrappers. */
function internalCompileClassMetadata(metadata: R3ClassMetadata): o.InvokeFunctionExpr {
return o
.importExpr(R3.setClassMetadata)
.callFn([
metadata.type,
metadata.decorators,
metadata.ctorParameters ?? o.literal(null),
metadata.propDecorators ?? o.literal(null),
]);
}
/**
* Wraps the `setClassMetadata` function with extra logic that dynamically
* loads dependencies from `@defer` blocks.
*
* Generates a call like this:
* ```
* setClassMetadataAsync(type, () => [
* import('./cmp-a').then(m => m.CmpA);
* import('./cmp-b').then(m => m.CmpB);
* ], (CmpA, CmpB) => {
* setClassMetadata(type, decorators, ctorParameters, propParameters);
* });
* ```
*
* Similar to the `setClassMetadata` call, it's wrapped into the `ngDevMode`
* check to tree-shake away this code in production mode.
*/
export function compileComponentClassMetadata(
metadata: R3ClassMetadata,
dependencies: R3DeferPerComponentDependency[] | null,
): o.Expression {
if (dependencies === null || dependencies.length === 0) {
// If there are no deferrable symbols - just generate a regular `setClassMetadata` call.
return compileClassMetadata(metadata);
}
return internalCompileSetClassMetadataAsync(
metadata,
dependencies.map((dep) => new o.FnParam(dep.symbolName, o.DYNAMIC_TYPE)),
compileComponentMetadataAsyncResolver(dependencies),
);
}
/**
* Identical to `compileComponentClassMetadata`. Used for the cases where we're unable to
* analyze the deferred block dependencies, but we have a reference to the compiled
* dependency resolver function that we can use as is.
* @param metadata Class metadata for the internal `setClassMetadata` call.
* @param deferResolver Expression representing the deferred dependency loading function.
* @param deferredDependencyNames Names of the dependencies that are being loaded asynchronously.
*/
export function compileOpaqueAsyncClassMetadata(
metadata: R3ClassMetadata,
deferResolver: o.Expression,
deferredDependencyNames: string[],
): o.Expression {
return internalCompileSetClassMetadataAsync(
metadata,
deferredDependencyNames.map((name) => new o.FnParam(name, o.DYNAMIC_TYPE)),
deferResolver,
);
}
/**
* Internal logic used to compile a `setClassMetadataAsync` call.
* @param metadata Class metadata for the internal `setClassMetadata` call.
* @param wrapperParams Parameters to be set on the callback that wraps `setClassMetata`.
* @param dependencyResolverFn Function to resolve the deferred dependencies.
*/
function internalCompileSetClassMetadataAsync(
metadata: R3ClassMetadata,
wrapperParams: o.FnParam[],
dependencyResolverFn: o.Expression,
): o.Expression {
// Omit the wrapper since it'll be added around `setClassMetadataAsync` instead.
const setClassMetadataCall = internalCompileClassMetadata(metadata);
const setClassMetaWrapper = o.arrowFn(wrapperParams, [setClassMetadataCall.toStmt()]);
const setClassMetaAsync = o
.importExpr(R3.setClassMetadataAsync)
.callFn([metadata.type, dependencyResolverFn, setClassMetaWrapper]);
return o.arrowFn([], [devOnlyGuardedExpression(setClassMetaAsync).toStmt()]).callFn([]);
}
/**
* Compiles the function that loads the dependencies for the
* entire component in `setClassMetadataAsync`.
*/
export function compileComponentMetadataAsyncResolver(
dependencies: R3DeferPerComponentDependency[],
): o.ArrowFunctionExpr {
const dynamicImports = dependencies.map(({symbolName, importPath, isDefaultImport}) => {
// e.g. `(m) => m.CmpA`
const innerFn =
// Default imports are always accessed through the `default` property.
o.arrowFn(
[new o.FnParam('m', o.DYNAMIC_TYPE)],
o.variable('m').prop(isDefaultImport ? 'default' : symbolName),
);
// e.g. `import('./cmp-a').then(...)`
return new o.DynamicImportExpr(importPath).prop('then').callFn([innerFn]);
});
// e.g. `() => [ ... ];`
return o.arrowFn([], o.literalArr(dynamicImports));
}
| {
"end_byte": 5729,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_class_metadata_compiler.ts"
} |
angular/packages/compiler/src/render3/r3_deferred_blocks.ts_0_7758 | /**
* @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.dev/license
*/
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';
import {
getTriggerParametersStart,
parseDeferredTime,
parseNeverTrigger,
parseOnTrigger,
parseWhenTrigger,
} from './r3_deferred_triggers';
/** Pattern to identify a `prefetch when` trigger. */
const PREFETCH_WHEN_PATTERN = /^prefetch\s+when\s/;
/** Pattern to identify a `prefetch on` trigger. */
const PREFETCH_ON_PATTERN = /^prefetch\s+on\s/;
/** Pattern to identify a `hydrate when` trigger. */
const HYDRATE_WHEN_PATTERN = /^hydrate\s+when\s/;
/** Pattern to identify a `hydrate on` trigger. */
const HYDRATE_ON_PATTERN = /^hydrate\s+on\s/;
/** Pattern to identify a `hydrate never` trigger. */
const HYDRATE_NEVER_PATTERN = /^hydrate\s+never(\s*)$/;
/** Pattern to identify a `minimum` parameter in a block. */
const MINIMUM_PARAMETER_PATTERN = /^minimum\s/;
/** Pattern to identify a `after` parameter in a block. */
const AFTER_PARAMETER_PATTERN = /^after\s/;
/** Pattern to identify a `when` parameter in a block. */
const WHEN_PARAMETER_PATTERN = /^when\s/;
/** Pattern to identify a `on` parameter in a block. */
const ON_PARAMETER_PATTERN = /^on\s/;
/**
* Predicate function that determines if a block with
* a specific name cam be connected to a `defer` block.
*/
export function isConnectedDeferLoopBlock(name: string): boolean {
return name === 'placeholder' || name === 'loading' || name === 'error';
}
/** Creates a deferred block from an HTML AST node. */
export function createDeferredBlock(
ast: html.Block,
connectedBlocks: html.Block[],
visitor: html.Visitor,
bindingParser: BindingParser,
): {node: t.DeferredBlock; errors: ParseError[]} {
const errors: ParseError[] = [];
const {placeholder, loading, error} = parseConnectedBlocks(connectedBlocks, errors, visitor);
const {triggers, prefetchTriggers, hydrateTriggers} = parsePrimaryTriggers(
ast,
bindingParser,
errors,
placeholder,
);
// The `defer` block has a main span encompassing all of the connected branches as well.
let lastEndSourceSpan = ast.endSourceSpan;
let endOfLastSourceSpan = ast.sourceSpan.end;
if (connectedBlocks.length > 0) {
const lastConnectedBlock = connectedBlocks[connectedBlocks.length - 1];
lastEndSourceSpan = lastConnectedBlock.endSourceSpan;
endOfLastSourceSpan = lastConnectedBlock.sourceSpan.end;
}
const sourceSpanWithConnectedBlocks = new ParseSourceSpan(
ast.sourceSpan.start,
endOfLastSourceSpan,
);
const node = new t.DeferredBlock(
html.visitAll(visitor, ast.children, ast.children),
triggers,
prefetchTriggers,
hydrateTriggers,
placeholder,
loading,
error,
ast.nameSpan,
sourceSpanWithConnectedBlocks,
ast.sourceSpan,
ast.startSourceSpan,
lastEndSourceSpan,
ast.i18n,
);
return {node, errors};
}
function parseConnectedBlocks(
connectedBlocks: html.Block[],
errors: ParseError[],
visitor: html.Visitor,
) {
let placeholder: t.DeferredBlockPlaceholder | null = null;
let loading: t.DeferredBlockLoading | null = null;
let error: t.DeferredBlockError | null = null;
for (const block of connectedBlocks) {
try {
if (!isConnectedDeferLoopBlock(block.name)) {
errors.push(new ParseError(block.startSourceSpan, `Unrecognized block "@${block.name}"`));
break;
}
switch (block.name) {
case 'placeholder':
if (placeholder !== null) {
errors.push(
new ParseError(
block.startSourceSpan,
`@defer block can only have one @placeholder block`,
),
);
} else {
placeholder = parsePlaceholderBlock(block, visitor);
}
break;
case 'loading':
if (loading !== null) {
errors.push(
new ParseError(
block.startSourceSpan,
`@defer block can only have one @loading block`,
),
);
} else {
loading = parseLoadingBlock(block, visitor);
}
break;
case 'error':
if (error !== null) {
errors.push(
new ParseError(block.startSourceSpan, `@defer block can only have one @error block`),
);
} else {
error = parseErrorBlock(block, visitor);
}
break;
}
} catch (e) {
errors.push(new ParseError(block.startSourceSpan, (e as Error).message));
}
}
return {placeholder, loading, error};
}
function parsePlaceholderBlock(ast: html.Block, visitor: html.Visitor): t.DeferredBlockPlaceholder {
let minimumTime: number | null = null;
for (const param of ast.parameters) {
if (MINIMUM_PARAMETER_PATTERN.test(param.expression)) {
if (minimumTime != null) {
throw new Error(`@placeholder block can only have one "minimum" parameter`);
}
const parsedTime = parseDeferredTime(
param.expression.slice(getTriggerParametersStart(param.expression)),
);
if (parsedTime === null) {
throw new Error(`Could not parse time value of parameter "minimum"`);
}
minimumTime = parsedTime;
} else {
throw new Error(`Unrecognized parameter in @placeholder block: "${param.expression}"`);
}
}
return new t.DeferredBlockPlaceholder(
html.visitAll(visitor, ast.children, ast.children),
minimumTime,
ast.nameSpan,
ast.sourceSpan,
ast.startSourceSpan,
ast.endSourceSpan,
ast.i18n,
);
}
function parseLoadingBlock(ast: html.Block, visitor: html.Visitor): t.DeferredBlockLoading {
let afterTime: number | null = null;
let minimumTime: number | null = null;
for (const param of ast.parameters) {
if (AFTER_PARAMETER_PATTERN.test(param.expression)) {
if (afterTime != null) {
throw new Error(`@loading block can only have one "after" parameter`);
}
const parsedTime = parseDeferredTime(
param.expression.slice(getTriggerParametersStart(param.expression)),
);
if (parsedTime === null) {
throw new Error(`Could not parse time value of parameter "after"`);
}
afterTime = parsedTime;
} else if (MINIMUM_PARAMETER_PATTERN.test(param.expression)) {
if (minimumTime != null) {
throw new Error(`@loading block can only have one "minimum" parameter`);
}
const parsedTime = parseDeferredTime(
param.expression.slice(getTriggerParametersStart(param.expression)),
);
if (parsedTime === null) {
throw new Error(`Could not parse time value of parameter "minimum"`);
}
minimumTime = parsedTime;
} else {
throw new Error(`Unrecognized parameter in @loading block: "${param.expression}"`);
}
}
return new t.DeferredBlockLoading(
html.visitAll(visitor, ast.children, ast.children),
afterTime,
minimumTime,
ast.nameSpan,
ast.sourceSpan,
ast.startSourceSpan,
ast.endSourceSpan,
ast.i18n,
);
}
function parseErrorBlock(ast: html.Block, visitor: html.Visitor): t.DeferredBlockError {
if (ast.parameters.length > 0) {
throw new Error(`@error block cannot have parameters`);
}
return new t.DeferredBlockError(
html.visitAll(visitor, ast.children, ast.children),
ast.nameSpan,
ast.sourceSpan,
ast.startSourceSpan,
ast.endSourceSpan,
ast.i18n,
);
} | {
"end_byte": 7758,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_deferred_blocks.ts"
} |
angular/packages/compiler/src/render3/r3_deferred_blocks.ts_7760_9525 | function parsePrimaryTriggers(
ast: html.Block,
bindingParser: BindingParser,
errors: ParseError[],
placeholder: t.DeferredBlockPlaceholder | null,
) {
const triggers: t.DeferredBlockTriggers = {};
const prefetchTriggers: t.DeferredBlockTriggers = {};
const hydrateTriggers: t.DeferredBlockTriggers = {};
for (const param of ast.parameters) {
// The lexer ignores the leading spaces so we can assume
// that the expression starts with a keyword.
if (WHEN_PARAMETER_PATTERN.test(param.expression)) {
parseWhenTrigger(param, bindingParser, triggers, errors);
} else if (ON_PARAMETER_PATTERN.test(param.expression)) {
parseOnTrigger(param, triggers, errors, placeholder);
} else if (PREFETCH_WHEN_PATTERN.test(param.expression)) {
parseWhenTrigger(param, bindingParser, prefetchTriggers, errors);
} else if (PREFETCH_ON_PATTERN.test(param.expression)) {
parseOnTrigger(param, prefetchTriggers, errors, placeholder);
} else if (HYDRATE_WHEN_PATTERN.test(param.expression)) {
parseWhenTrigger(param, bindingParser, hydrateTriggers, errors);
} else if (HYDRATE_ON_PATTERN.test(param.expression)) {
parseOnTrigger(param, hydrateTriggers, errors, placeholder);
} else if (HYDRATE_NEVER_PATTERN.test(param.expression)) {
parseNeverTrigger(param, hydrateTriggers, errors);
} else {
errors.push(new ParseError(param.sourceSpan, 'Unrecognized trigger'));
}
}
if (hydrateTriggers.never && Object.keys(hydrateTriggers).length > 1) {
errors.push(
new ParseError(
ast.startSourceSpan,
'Cannot specify additional `hydrate` triggers if `hydrate never` is present',
),
);
}
return {triggers, prefetchTriggers, hydrateTriggers};
} | {
"end_byte": 9525,
"start_byte": 7760,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_deferred_blocks.ts"
} |
angular/packages/compiler/src/render3/r3_template_transform.ts_0_3032 | /**
* @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.dev/license
*/
import {EmptyExpr, ParsedEvent, ParsedProperty, ParsedVariable} from '../expression_parser/ast';
import * as i18n from '../i18n/i18n_ast';
import * as html from '../ml_parser/ast';
import {replaceNgsp} from '../ml_parser/html_whitespaces';
import {isNgTemplate} from '../ml_parser/tags';
import {InterpolatedAttributeToken, InterpolatedTextToken} from '../ml_parser/tokens';
import {ParseError, ParseErrorLevel, ParseSourceSpan} from '../parse_util';
import {isStyleUrlResolvable} from '../style_url_resolver';
import {isI18nRootNode} from '../template/pipeline/src/ingest';
import {BindingParser} from '../template_parser/binding_parser';
import {PreparsedElementType, preparseElement} from '../template_parser/template_preparser';
import * as t from './r3_ast';
import {
createForLoop,
createIfBlock,
createSwitchBlock,
isConnectedForLoopBlock,
isConnectedIfLoopBlock,
} from './r3_control_flow';
import {createDeferredBlock, isConnectedDeferLoopBlock} from './r3_deferred_blocks';
import {I18N_ICU_VAR_PREFIX} from './view/i18n/util';
const BIND_NAME_REGEXP = /^(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.*)$/;
// Group 1 = "bind-"
const KW_BIND_IDX = 1;
// Group 2 = "let-"
const KW_LET_IDX = 2;
// Group 3 = "ref-/#"
const KW_REF_IDX = 3;
// Group 4 = "on-"
const KW_ON_IDX = 4;
// Group 5 = "bindon-"
const KW_BINDON_IDX = 5;
// Group 6 = "@"
const KW_AT_IDX = 6;
// Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
const IDENT_KW_IDX = 7;
const BINDING_DELIMS = {
BANANA_BOX: {start: '[(', end: ')]'},
PROPERTY: {start: '[', end: ']'},
EVENT: {start: '(', end: ')'},
};
const TEMPLATE_ATTR_PREFIX = '*';
// Result of the html AST to Ivy AST transformation
export interface Render3ParseResult {
nodes: t.Node[];
errors: ParseError[];
styles: string[];
styleUrls: string[];
ngContentSelectors: string[];
// Will be defined if `Render3ParseOptions['collectCommentNodes']` is true
commentNodes?: t.Comment[];
}
interface Render3ParseOptions {
collectCommentNodes: boolean;
}
export function htmlAstToRender3Ast(
htmlNodes: html.Node[],
bindingParser: BindingParser,
options: Render3ParseOptions,
): Render3ParseResult {
const transformer = new HtmlAstToIvyAst(bindingParser, options);
const ivyNodes = html.visitAll(transformer, htmlNodes, htmlNodes);
// Errors might originate in either the binding parser or the html to ivy transformer
const allErrors = bindingParser.errors.concat(transformer.errors);
const result: Render3ParseResult = {
nodes: ivyNodes,
errors: allErrors,
styleUrls: transformer.styleUrls,
styles: transformer.styles,
ngContentSelectors: transformer.ngContentSelectors,
};
if (options.collectCommentNodes) {
result.commentNodes = transformer.commentNodes;
}
return result;
} | {
"end_byte": 3032,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_template_transform.ts"
} |
angular/packages/compiler/src/render3/r3_template_transform.ts_3034_11721 | class HtmlAstToIvyAst implements html.Visitor {
errors: ParseError[] = [];
styles: string[] = [];
styleUrls: string[] = [];
ngContentSelectors: string[] = [];
// This array will be populated if `Render3ParseOptions['collectCommentNodes']` is true
commentNodes: t.Comment[] = [];
private inI18nBlock: boolean = false;
/**
* Keeps track of the nodes that have been processed already when previous nodes were visited.
* These are typically blocks connected to other blocks or text nodes between connected blocks.
*/
private processedNodes = new Set<html.Block | html.Text>();
constructor(
private bindingParser: BindingParser,
private options: Render3ParseOptions,
) {}
// HTML visitor
visitElement(element: html.Element): t.Node | null {
const isI18nRootElement = isI18nRootNode(element.i18n);
if (isI18nRootElement) {
if (this.inI18nBlock) {
this.reportError(
'Cannot mark an element as translatable inside of a translatable section. Please remove the nested i18n marker.',
element.sourceSpan,
);
}
this.inI18nBlock = true;
}
const preparsedElement = preparseElement(element);
if (preparsedElement.type === PreparsedElementType.SCRIPT) {
return null;
} else if (preparsedElement.type === PreparsedElementType.STYLE) {
const contents = textContents(element);
if (contents !== null) {
this.styles.push(contents);
}
return null;
} else if (
preparsedElement.type === PreparsedElementType.STYLESHEET &&
isStyleUrlResolvable(preparsedElement.hrefAttr)
) {
this.styleUrls.push(preparsedElement.hrefAttr);
return null;
}
// Whether the element is a `<ng-template>`
const isTemplateElement = isNgTemplate(element.name);
const parsedProperties: ParsedProperty[] = [];
const boundEvents: t.BoundEvent[] = [];
const variables: t.Variable[] = [];
const references: t.Reference[] = [];
const attributes: t.TextAttribute[] = [];
const i18nAttrsMeta: {[key: string]: i18n.I18nMeta} = {};
const templateParsedProperties: ParsedProperty[] = [];
const templateVariables: t.Variable[] = [];
// Whether the element has any *-attribute
let elementHasInlineTemplate = false;
for (const attribute of element.attrs) {
let hasBinding = false;
const normalizedName = normalizeAttributeName(attribute.name);
// `*attr` defines template bindings
let isTemplateBinding = false;
if (attribute.i18n) {
i18nAttrsMeta[attribute.name] = attribute.i18n;
}
if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX)) {
// *-attributes
if (elementHasInlineTemplate) {
this.reportError(
`Can't have multiple template bindings on one element. Use only one attribute prefixed with *`,
attribute.sourceSpan,
);
}
isTemplateBinding = true;
elementHasInlineTemplate = true;
const templateValue = attribute.value;
const templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX.length);
const parsedVariables: ParsedVariable[] = [];
const absoluteValueOffset = attribute.valueSpan
? attribute.valueSpan.start.offset
: // If there is no value span the attribute does not have a value, like `attr` in
//`<div attr></div>`. In this case, point to one character beyond the last character of
// the attribute name.
attribute.sourceSpan.start.offset + attribute.name.length;
this.bindingParser.parseInlineTemplateBinding(
templateKey,
templateValue,
attribute.sourceSpan,
absoluteValueOffset,
[],
templateParsedProperties,
parsedVariables,
true /* isIvyAst */,
);
templateVariables.push(
...parsedVariables.map(
(v) => new t.Variable(v.name, v.value, v.sourceSpan, v.keySpan, v.valueSpan),
),
);
} else {
// Check for variables, events, property bindings, interpolation
hasBinding = this.parseAttribute(
isTemplateElement,
attribute,
[],
parsedProperties,
boundEvents,
variables,
references,
);
}
if (!hasBinding && !isTemplateBinding) {
// don't include the bindings as attributes as well in the AST
attributes.push(this.visitAttribute(attribute));
}
}
let children: t.Node[];
if (preparsedElement.nonBindable) {
// The `NonBindableVisitor` may need to return an array of nodes for blocks so we need
// to flatten the array here. Avoid doing this for the `HtmlAstToIvyAst` since `flat` creates
// a new array.
children = html.visitAll(NON_BINDABLE_VISITOR, element.children).flat(Infinity);
} else {
children = html.visitAll(this, element.children, element.children);
}
let parsedElement: t.Content | t.Template | t.Element | undefined;
if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
const selector = preparsedElement.selectAttr;
const attrs: t.TextAttribute[] = element.attrs.map((attr) => this.visitAttribute(attr));
parsedElement = new t.Content(selector, attrs, children, element.sourceSpan, element.i18n);
this.ngContentSelectors.push(selector);
} else if (isTemplateElement) {
// `<ng-template>`
const attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
parsedElement = new t.Template(
element.name,
attributes,
attrs.bound,
boundEvents,
[
/* no template attributes */
],
children,
references,
variables,
element.sourceSpan,
element.startSourceSpan,
element.endSourceSpan,
element.i18n,
);
} else {
const attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
parsedElement = new t.Element(
element.name,
attributes,
attrs.bound,
boundEvents,
children,
references,
element.sourceSpan,
element.startSourceSpan,
element.endSourceSpan,
element.i18n,
);
}
if (elementHasInlineTemplate) {
// If this node is an inline-template (e.g. has *ngFor) then we need to create a template
// node that contains this node.
// Moreover, if the node is an element, then we need to hoist its attributes to the template
// node for matching against content projection selectors.
const attrs = this.extractAttributes('ng-template', templateParsedProperties, i18nAttrsMeta);
const templateAttrs: (t.TextAttribute | t.BoundAttribute)[] = [];
attrs.literal.forEach((attr) => templateAttrs.push(attr));
attrs.bound.forEach((attr) => templateAttrs.push(attr));
const hoistedAttrs =
parsedElement instanceof t.Element
? {
attributes: parsedElement.attributes,
inputs: parsedElement.inputs,
outputs: parsedElement.outputs,
}
: {attributes: [], inputs: [], outputs: []};
// For <ng-template>s with structural directives on them, avoid passing i18n information to
// the wrapping template to prevent unnecessary i18n instructions from being generated. The
// necessary i18n meta information will be extracted from child elements.
const i18n = isTemplateElement && isI18nRootElement ? undefined : element.i18n;
const name = parsedElement instanceof t.Template ? null : parsedElement.name;
parsedElement = new t.Template(
name,
hoistedAttrs.attributes,
hoistedAttrs.inputs,
hoistedAttrs.outputs,
templateAttrs,
[parsedElement],
[
/* no references */
],
templateVariables,
element.sourceSpan,
element.startSourceSpan,
element.endSourceSpan,
i18n,
);
}
if (isI18nRootElement) {
this.inI18nBlock = false;
}
return parsedElement;
}
visitAttribute(attribute: html.Attribute): t.TextAttribute {
return new t.TextAttribute(
attribute.name,
attribute.value,
attribute.sourceSpan,
attribute.keySpan,
attribute.valueSpan,
attribute.i18n,
);
}
visitText(text: html.Text): t.Node | null {
return this.processedNodes.has(text)
? null
: this._visitTextWithInterpolation(text.value, text.sourceSpan, text.tokens, text.i18n);
} | {
"end_byte": 11721,
"start_byte": 3034,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_template_transform.ts"
} |
angular/packages/compiler/src/render3/r3_template_transform.ts_11725_18960 | visitExpansion(expansion: html.Expansion): t.Icu | null {
if (!expansion.i18n) {
// do not generate Icu in case it was created
// outside of i18n block in a template
return null;
}
if (!isI18nRootNode(expansion.i18n)) {
throw new Error(
`Invalid type "${
expansion.i18n.constructor
}" for "i18n" property of ${expansion.sourceSpan.toString()}. Expected a "Message"`,
);
}
const message = expansion.i18n;
const vars: {[name: string]: t.BoundText} = {};
const placeholders: {[name: string]: t.Text | t.BoundText} = {};
// extract VARs from ICUs - we process them separately while
// assembling resulting message via goog.getMsg function, since
// we need to pass them to top-level goog.getMsg call
Object.keys(message.placeholders).forEach((key) => {
const value = message.placeholders[key];
if (key.startsWith(I18N_ICU_VAR_PREFIX)) {
// Currently when the `plural` or `select` keywords in an ICU contain trailing spaces (e.g.
// `{count, select , ...}`), these spaces are also included into the key names in ICU vars
// (e.g. "VAR_SELECT "). These trailing spaces are not desirable, since they will later be
// converted into `_` symbols while normalizing placeholder names, which might lead to
// mismatches at runtime (i.e. placeholder will not be replaced with the correct value).
const formattedKey = key.trim();
const ast = this.bindingParser.parseInterpolationExpression(value.text, value.sourceSpan);
vars[formattedKey] = new t.BoundText(ast, value.sourceSpan);
} else {
placeholders[key] = this._visitTextWithInterpolation(value.text, value.sourceSpan, null);
}
});
return new t.Icu(vars, placeholders, expansion.sourceSpan, message);
}
visitExpansionCase(expansionCase: html.ExpansionCase): null {
return null;
}
visitComment(comment: html.Comment): null {
if (this.options.collectCommentNodes) {
this.commentNodes.push(new t.Comment(comment.value || '', comment.sourceSpan));
}
return null;
}
visitLetDeclaration(decl: html.LetDeclaration, context: any) {
const value = this.bindingParser.parseBinding(
decl.value,
false,
decl.valueSpan,
decl.valueSpan.start.offset,
);
if (value.errors.length === 0 && value.ast instanceof EmptyExpr) {
this.reportError('@let declaration value cannot be empty', decl.valueSpan);
}
return new t.LetDeclaration(decl.name, value, decl.sourceSpan, decl.nameSpan, decl.valueSpan);
}
visitBlockParameter() {
return null;
}
visitBlock(block: html.Block, context: html.Node[]) {
const index = Array.isArray(context) ? context.indexOf(block) : -1;
if (index === -1) {
throw new Error(
'Visitor invoked incorrectly. Expecting visitBlock to be invoked siblings array as its context',
);
}
// Connected blocks may have been processed as a part of the previous block.
if (this.processedNodes.has(block)) {
return null;
}
let result: {node: t.Node | null; errors: ParseError[]} | null = null;
switch (block.name) {
case 'defer':
result = createDeferredBlock(
block,
this.findConnectedBlocks(index, context, isConnectedDeferLoopBlock),
this,
this.bindingParser,
);
break;
case 'switch':
result = createSwitchBlock(block, this, this.bindingParser);
break;
case 'for':
result = createForLoop(
block,
this.findConnectedBlocks(index, context, isConnectedForLoopBlock),
this,
this.bindingParser,
);
break;
case 'if':
result = createIfBlock(
block,
this.findConnectedBlocks(index, context, isConnectedIfLoopBlock),
this,
this.bindingParser,
);
break;
default:
let errorMessage: string;
if (isConnectedDeferLoopBlock(block.name)) {
errorMessage = `@${block.name} block can only be used after an @defer block.`;
this.processedNodes.add(block);
} else if (isConnectedForLoopBlock(block.name)) {
errorMessage = `@${block.name} block can only be used after an @for block.`;
this.processedNodes.add(block);
} else if (isConnectedIfLoopBlock(block.name)) {
errorMessage = `@${block.name} block can only be used after an @if or @else if block.`;
this.processedNodes.add(block);
} else {
errorMessage = `Unrecognized block @${block.name}.`;
}
result = {
node: new t.UnknownBlock(block.name, block.sourceSpan, block.nameSpan),
errors: [new ParseError(block.sourceSpan, errorMessage)],
};
break;
}
this.errors.push(...result.errors);
return result.node;
}
private findConnectedBlocks(
primaryBlockIndex: number,
siblings: html.Node[],
predicate: (blockName: string) => boolean,
): html.Block[] {
const relatedBlocks: html.Block[] = [];
for (let i = primaryBlockIndex + 1; i < siblings.length; i++) {
const node = siblings[i];
// Skip over comments.
if (node instanceof html.Comment) {
continue;
}
// Ignore empty text nodes between blocks.
if (node instanceof html.Text && node.value.trim().length === 0) {
// Add the text node to the processed nodes since we don't want
// it to be generated between the connected nodes.
this.processedNodes.add(node);
continue;
}
// Stop searching as soon as we hit a non-block node or a block that is unrelated.
if (!(node instanceof html.Block) || !predicate(node.name)) {
break;
}
relatedBlocks.push(node);
this.processedNodes.add(node);
}
return relatedBlocks;
}
// convert view engine `ParsedProperty` to a format suitable for IVY
private extractAttributes(
elementName: string,
properties: ParsedProperty[],
i18nPropsMeta: {[key: string]: i18n.I18nMeta},
): {bound: t.BoundAttribute[]; literal: t.TextAttribute[]} {
const bound: t.BoundAttribute[] = [];
const literal: t.TextAttribute[] = [];
properties.forEach((prop) => {
const i18n = i18nPropsMeta[prop.name];
if (prop.isLiteral) {
literal.push(
new t.TextAttribute(
prop.name,
prop.expression.source || '',
prop.sourceSpan,
prop.keySpan,
prop.valueSpan,
i18n,
),
);
} else {
// Note that validation is skipped and property mapping is disabled
// due to the fact that we need to make sure a given prop is not an
// input of a directive and directive matching happens at runtime.
const bep = this.bindingParser.createBoundElementProperty(
elementName,
prop,
/* skipValidation */ true,
/* mapPropertyName */ false,
);
bound.push(t.BoundAttribute.fromBoundElementProperty(bep, i18n));
}
});
return {bound, literal};
} | {
"end_byte": 18960,
"start_byte": 11725,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_template_transform.ts"
} |
angular/packages/compiler/src/render3/r3_template_transform.ts_18964_27894 | private parseAttribute(
isTemplateElement: boolean,
attribute: html.Attribute,
matchableAttributes: string[][],
parsedProperties: ParsedProperty[],
boundEvents: t.BoundEvent[],
variables: t.Variable[],
references: t.Reference[],
) {
const name = normalizeAttributeName(attribute.name);
const value = attribute.value;
const srcSpan = attribute.sourceSpan;
const absoluteOffset = attribute.valueSpan
? attribute.valueSpan.start.offset
: srcSpan.start.offset;
function createKeySpan(srcSpan: ParseSourceSpan, prefix: string, identifier: string) {
// We need to adjust the start location for the keySpan to account for the removed 'data-'
// prefix from `normalizeAttributeName`.
const normalizationAdjustment = attribute.name.length - name.length;
const keySpanStart = srcSpan.start.moveBy(prefix.length + normalizationAdjustment);
const keySpanEnd = keySpanStart.moveBy(identifier.length);
return new ParseSourceSpan(keySpanStart, keySpanEnd, keySpanStart, identifier);
}
const bindParts = name.match(BIND_NAME_REGEXP);
if (bindParts) {
if (bindParts[KW_BIND_IDX] != null) {
const identifier = bindParts[IDENT_KW_IDX];
const keySpan = createKeySpan(srcSpan, bindParts[KW_BIND_IDX], identifier);
this.bindingParser.parsePropertyBinding(
identifier,
value,
false,
false,
srcSpan,
absoluteOffset,
attribute.valueSpan,
matchableAttributes,
parsedProperties,
keySpan,
);
} else if (bindParts[KW_LET_IDX]) {
if (isTemplateElement) {
const identifier = bindParts[IDENT_KW_IDX];
const keySpan = createKeySpan(srcSpan, bindParts[KW_LET_IDX], identifier);
this.parseVariable(identifier, value, srcSpan, keySpan, attribute.valueSpan, variables);
} else {
this.reportError(`"let-" is only supported on ng-template elements.`, srcSpan);
}
} else if (bindParts[KW_REF_IDX]) {
const identifier = bindParts[IDENT_KW_IDX];
const keySpan = createKeySpan(srcSpan, bindParts[KW_REF_IDX], identifier);
this.parseReference(identifier, value, srcSpan, keySpan, attribute.valueSpan, references);
} else if (bindParts[KW_ON_IDX]) {
const events: ParsedEvent[] = [];
const identifier = bindParts[IDENT_KW_IDX];
const keySpan = createKeySpan(srcSpan, bindParts[KW_ON_IDX], identifier);
this.bindingParser.parseEvent(
identifier,
value,
/* isAssignmentEvent */ false,
srcSpan,
attribute.valueSpan || srcSpan,
matchableAttributes,
events,
keySpan,
);
addEvents(events, boundEvents);
} else if (bindParts[KW_BINDON_IDX]) {
const identifier = bindParts[IDENT_KW_IDX];
const keySpan = createKeySpan(srcSpan, bindParts[KW_BINDON_IDX], identifier);
this.bindingParser.parsePropertyBinding(
identifier,
value,
false,
true,
srcSpan,
absoluteOffset,
attribute.valueSpan,
matchableAttributes,
parsedProperties,
keySpan,
);
this.parseAssignmentEvent(
identifier,
value,
srcSpan,
attribute.valueSpan,
matchableAttributes,
boundEvents,
keySpan,
);
} else if (bindParts[KW_AT_IDX]) {
const keySpan = createKeySpan(srcSpan, '', name);
this.bindingParser.parseLiteralAttr(
name,
value,
srcSpan,
absoluteOffset,
attribute.valueSpan,
matchableAttributes,
parsedProperties,
keySpan,
);
}
return true;
}
// We didn't see a kw-prefixed property binding, but we have not yet checked
// for the []/()/[()] syntax.
let delims: {start: string; end: string} | null = null;
if (name.startsWith(BINDING_DELIMS.BANANA_BOX.start)) {
delims = BINDING_DELIMS.BANANA_BOX;
} else if (name.startsWith(BINDING_DELIMS.PROPERTY.start)) {
delims = BINDING_DELIMS.PROPERTY;
} else if (name.startsWith(BINDING_DELIMS.EVENT.start)) {
delims = BINDING_DELIMS.EVENT;
}
if (
delims !== null &&
// NOTE: older versions of the parser would match a start/end delimited
// binding iff the property name was terminated by the ending delimiter
// and the identifier in the binding was non-empty.
// TODO(ayazhafiz): update this to handle malformed bindings.
name.endsWith(delims.end) &&
name.length > delims.start.length + delims.end.length
) {
const identifier = name.substring(delims.start.length, name.length - delims.end.length);
const keySpan = createKeySpan(srcSpan, delims.start, identifier);
if (delims.start === BINDING_DELIMS.BANANA_BOX.start) {
this.bindingParser.parsePropertyBinding(
identifier,
value,
false,
true,
srcSpan,
absoluteOffset,
attribute.valueSpan,
matchableAttributes,
parsedProperties,
keySpan,
);
this.parseAssignmentEvent(
identifier,
value,
srcSpan,
attribute.valueSpan,
matchableAttributes,
boundEvents,
keySpan,
);
} else if (delims.start === BINDING_DELIMS.PROPERTY.start) {
this.bindingParser.parsePropertyBinding(
identifier,
value,
false,
false,
srcSpan,
absoluteOffset,
attribute.valueSpan,
matchableAttributes,
parsedProperties,
keySpan,
);
} else {
const events: ParsedEvent[] = [];
this.bindingParser.parseEvent(
identifier,
value,
/* isAssignmentEvent */ false,
srcSpan,
attribute.valueSpan || srcSpan,
matchableAttributes,
events,
keySpan,
);
addEvents(events, boundEvents);
}
return true;
}
// No explicit binding found.
const keySpan = createKeySpan(srcSpan, '' /* prefix */, name);
const hasBinding = this.bindingParser.parsePropertyInterpolation(
name,
value,
srcSpan,
attribute.valueSpan,
matchableAttributes,
parsedProperties,
keySpan,
attribute.valueTokens ?? null,
);
return hasBinding;
}
private _visitTextWithInterpolation(
value: string,
sourceSpan: ParseSourceSpan,
interpolatedTokens: InterpolatedAttributeToken[] | InterpolatedTextToken[] | null,
i18n?: i18n.I18nMeta,
): t.Text | t.BoundText {
const valueNoNgsp = replaceNgsp(value);
const expr = this.bindingParser.parseInterpolation(valueNoNgsp, sourceSpan, interpolatedTokens);
return expr ? new t.BoundText(expr, sourceSpan, i18n) : new t.Text(valueNoNgsp, sourceSpan);
}
private parseVariable(
identifier: string,
value: string,
sourceSpan: ParseSourceSpan,
keySpan: ParseSourceSpan,
valueSpan: ParseSourceSpan | undefined,
variables: t.Variable[],
) {
if (identifier.indexOf('-') > -1) {
this.reportError(`"-" is not allowed in variable names`, sourceSpan);
} else if (identifier.length === 0) {
this.reportError(`Variable does not have a name`, sourceSpan);
}
variables.push(new t.Variable(identifier, value, sourceSpan, keySpan, valueSpan));
}
private parseReference(
identifier: string,
value: string,
sourceSpan: ParseSourceSpan,
keySpan: ParseSourceSpan,
valueSpan: ParseSourceSpan | undefined,
references: t.Reference[],
) {
if (identifier.indexOf('-') > -1) {
this.reportError(`"-" is not allowed in reference names`, sourceSpan);
} else if (identifier.length === 0) {
this.reportError(`Reference does not have a name`, sourceSpan);
} else if (references.some((reference) => reference.name === identifier)) {
this.reportError(`Reference "#${identifier}" is defined more than once`, sourceSpan);
}
references.push(new t.Reference(identifier, value, sourceSpan, keySpan, valueSpan));
}
private parseAssignmentEvent(
name: string,
expression: string,
sourceSpan: ParseSourceSpan,
valueSpan: ParseSourceSpan | undefined,
targetMatchableAttrs: string[][],
boundEvents: t.BoundEvent[],
keySpan: ParseSourceSpan,
) {
const events: ParsedEvent[] = [];
this.bindingParser.parseEvent(
`${name}Change`,
expression,
/* isAssignmentEvent */ true,
sourceSpan,
valueSpan || sourceSpan,
targetMatchableAttrs,
events,
keySpan,
);
addEvents(events, boundEvents);
} | {
"end_byte": 27894,
"start_byte": 18964,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_template_transform.ts"
} |
angular/packages/compiler/src/render3/r3_template_transform.ts_27898_30883 | private reportError(
message: string,
sourceSpan: ParseSourceSpan,
level: ParseErrorLevel = ParseErrorLevel.ERROR,
) {
this.errors.push(new ParseError(sourceSpan, message, level));
}
}
class NonBindableVisitor implements html.Visitor {
visitElement(ast: html.Element): t.Element | null {
const preparsedElement = preparseElement(ast);
if (
preparsedElement.type === PreparsedElementType.SCRIPT ||
preparsedElement.type === PreparsedElementType.STYLE ||
preparsedElement.type === PreparsedElementType.STYLESHEET
) {
// Skipping <script> for security reasons
// Skipping <style> and stylesheets as we already processed them
// in the StyleCompiler
return null;
}
const children: t.Node[] = html.visitAll(this, ast.children, null);
return new t.Element(
ast.name,
html.visitAll(this, ast.attrs) as t.TextAttribute[],
/* inputs */ [],
/* outputs */ [],
children,
/* references */ [],
ast.sourceSpan,
ast.startSourceSpan,
ast.endSourceSpan,
);
}
visitComment(comment: html.Comment): any {
return null;
}
visitAttribute(attribute: html.Attribute): t.TextAttribute {
return new t.TextAttribute(
attribute.name,
attribute.value,
attribute.sourceSpan,
attribute.keySpan,
attribute.valueSpan,
attribute.i18n,
);
}
visitText(text: html.Text): t.Text {
return new t.Text(text.value, text.sourceSpan);
}
visitExpansion(expansion: html.Expansion): any {
return null;
}
visitExpansionCase(expansionCase: html.ExpansionCase): any {
return null;
}
visitBlock(block: html.Block, context: any) {
const nodes = [
// In an ngNonBindable context we treat the opening/closing tags of block as plain text.
// This is the as if the `tokenizeBlocks` option was disabled.
new t.Text(block.startSourceSpan.toString(), block.startSourceSpan),
...html.visitAll(this, block.children),
];
if (block.endSourceSpan !== null) {
nodes.push(new t.Text(block.endSourceSpan.toString(), block.endSourceSpan));
}
return nodes;
}
visitBlockParameter(parameter: html.BlockParameter, context: any) {
return null;
}
visitLetDeclaration(decl: html.LetDeclaration, context: any) {
return new t.Text(`@let ${decl.name} = ${decl.value};`, decl.sourceSpan);
}
}
const NON_BINDABLE_VISITOR = new NonBindableVisitor();
function normalizeAttributeName(attrName: string): string {
return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
}
function addEvents(events: ParsedEvent[], boundEvents: t.BoundEvent[]) {
boundEvents.push(...events.map((e) => t.BoundEvent.fromParsedEvent(e)));
}
function textContents(node: html.Element): string | null {
if (node.children.length !== 1 || !(node.children[0] instanceof html.Text)) {
return null;
} else {
return (node.children[0] as html.Text).value;
}
} | {
"end_byte": 30883,
"start_byte": 27898,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_template_transform.ts"
} |
angular/packages/compiler/src/render3/r3_jit.ts_0_1174 | /**
* @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.dev/license
*/
import * as o from '../output/output_ast';
import {ExternalReferenceResolver} from '../output/output_jit';
/**
* Implementation of `CompileReflector` which resolves references to @angular/core
* symbols at runtime, according to a consumer-provided mapping.
*
* Only supports `resolveExternalReference`, all other methods throw.
*/
export class R3JitReflector implements ExternalReferenceResolver {
constructor(private context: {[key: string]: unknown}) {}
resolveExternalReference(ref: o.ExternalReference): unknown {
// This reflector only handles @angular/core imports.
if (ref.moduleName !== '@angular/core') {
throw new Error(
`Cannot resolve external reference to ${ref.moduleName}, only references to @angular/core are supported.`,
);
}
if (!this.context.hasOwnProperty(ref.name!)) {
throw new Error(`No value provided for @angular/core symbol '${ref.name!}'.`);
}
return this.context[ref.name!];
}
}
| {
"end_byte": 1174,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_jit.ts"
} |
angular/packages/compiler/src/render3/r3_injector_compiler.ts_0_1309 | /**
* @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.dev/license
*/
import * as o from '../output/output_ast';
import {Identifiers as R3} from './r3_identifiers';
import {R3CompiledExpression, R3Reference} from './util';
import {DefinitionMap} from './view/util';
export interface R3InjectorMetadata {
name: string;
type: R3Reference;
providers: o.Expression | null;
imports: o.Expression[];
}
export function compileInjector(meta: R3InjectorMetadata): R3CompiledExpression {
const definitionMap = new DefinitionMap<{providers: o.Expression; imports: o.Expression}>();
if (meta.providers !== null) {
definitionMap.set('providers', meta.providers);
}
if (meta.imports.length > 0) {
definitionMap.set('imports', o.literalArr(meta.imports));
}
const expression = o
.importExpr(R3.defineInjector)
.callFn([definitionMap.toLiteralMap()], undefined, true);
const type = createInjectorType(meta);
return {expression, type, statements: []};
}
export function createInjectorType(meta: R3InjectorMetadata): o.Type {
return new o.ExpressionType(
o.importExpr(R3.InjectorDeclaration, [new o.ExpressionType(meta.type.type)]),
);
}
| {
"end_byte": 1309,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_injector_compiler.ts"
} |
angular/packages/compiler/src/render3/util.ts_0_5954 | /**
* @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.dev/license
*/
import {escapeIdentifier} from '../output/abstract_emitter';
import * as o from '../output/output_ast';
import {Identifiers} from './r3_identifiers';
export function typeWithParameters(type: o.Expression, numParams: number): o.ExpressionType {
if (numParams === 0) {
return o.expressionType(type);
}
const params: o.Type[] = [];
for (let i = 0; i < numParams; i++) {
params.push(o.DYNAMIC_TYPE);
}
return o.expressionType(type, undefined, params);
}
export interface R3Reference {
value: o.Expression;
type: o.Expression;
}
/**
* Result of compilation of a render3 code unit, e.g. component, directive, pipe, etc.
*/
export interface R3CompiledExpression {
expression: o.Expression;
type: o.Type;
statements: o.Statement[];
}
const ANIMATE_SYMBOL_PREFIX = '@';
export function prepareSyntheticPropertyName(name: string) {
return `${ANIMATE_SYMBOL_PREFIX}${name}`;
}
export function prepareSyntheticListenerName(name: string, phase: string) {
return `${ANIMATE_SYMBOL_PREFIX}${name}.${phase}`;
}
export function getSafePropertyAccessString(accessor: string, name: string): string {
const escapedName = escapeIdentifier(name, false, false);
return escapedName !== name ? `${accessor}[${escapedName}]` : `${accessor}.${name}`;
}
export function prepareSyntheticListenerFunctionName(name: string, phase: string) {
return `animation_${name}_${phase}`;
}
export function jitOnlyGuardedExpression(expr: o.Expression): o.Expression {
return guardedExpression('ngJitMode', expr);
}
export function devOnlyGuardedExpression(expr: o.Expression): o.Expression {
return guardedExpression('ngDevMode', expr);
}
export function guardedExpression(guard: string, expr: o.Expression): o.Expression {
const guardExpr = new o.ExternalExpr({name: guard, moduleName: null});
const guardNotDefined = new o.BinaryOperatorExpr(
o.BinaryOperator.Identical,
new o.TypeofExpr(guardExpr),
o.literal('undefined'),
);
const guardUndefinedOrTrue = new o.BinaryOperatorExpr(
o.BinaryOperator.Or,
guardNotDefined,
guardExpr,
/* type */ undefined,
/* sourceSpan */ undefined,
true,
);
return new o.BinaryOperatorExpr(o.BinaryOperator.And, guardUndefinedOrTrue, expr);
}
export function wrapReference(value: any): R3Reference {
const wrapped = new o.WrappedNodeExpr(value);
return {value: wrapped, type: wrapped};
}
export function refsToArray(refs: R3Reference[], shouldForwardDeclare: boolean): o.Expression {
const values = o.literalArr(refs.map((ref) => ref.value));
return shouldForwardDeclare ? o.arrowFn([], values) : values;
}
/**
* Describes an expression that may have been wrapped in a `forwardRef()` guard.
*
* This is used when describing expressions that can refer to types that may eagerly reference types
* that have not yet been defined.
*/
export interface MaybeForwardRefExpression<T extends o.Expression = o.Expression> {
/**
* The unwrapped expression.
*/
expression: T;
/**
* Specified whether the `expression` contains a reference to something that has not yet been
* defined, and whether the expression is still wrapped in a `forwardRef()` call.
*
* If this value is `ForwardRefHandling.None` then the `expression` is safe to use as-is.
*
* Otherwise the `expression` was wrapped in a call to `forwardRef()` and must not be eagerly
* evaluated. Instead it must be wrapped in a function closure that will be evaluated lazily to
* allow the definition of the expression to be evaluated first.
*
* In full AOT compilation it can be safe to unwrap the `forwardRef()` call up front if the
* expression will actually be evaluated lazily inside a function call after the value of
* `expression` has been defined.
*
* But in other cases, such as partial AOT compilation or JIT compilation the expression will be
* evaluated eagerly in top level code so will need to continue to be wrapped in a `forwardRef()`
* call.
*
*/
forwardRef: ForwardRefHandling;
}
export function createMayBeForwardRefExpression<T extends o.Expression>(
expression: T,
forwardRef: ForwardRefHandling,
): MaybeForwardRefExpression<T> {
return {expression, forwardRef};
}
/**
* Convert a `MaybeForwardRefExpression` to an `Expression`, possibly wrapping its expression in a
* `forwardRef()` call.
*
* If `MaybeForwardRefExpression.forwardRef` is `ForwardRefHandling.Unwrapped` then the expression
* was originally wrapped in a `forwardRef()` call to prevent the value from being eagerly evaluated
* in the code.
*
* See `packages/compiler-cli/src/ngtsc/annotations/src/injectable.ts` and
* `packages/compiler/src/jit_compiler_facade.ts` for more information.
*/
export function convertFromMaybeForwardRefExpression({
expression,
forwardRef,
}: MaybeForwardRefExpression): o.Expression {
switch (forwardRef) {
case ForwardRefHandling.None:
case ForwardRefHandling.Wrapped:
return expression;
case ForwardRefHandling.Unwrapped:
return generateForwardRef(expression);
}
}
/**
* Generate an expression that has the given `expr` wrapped in the following form:
*
* ```
* forwardRef(() => expr)
* ```
*/
export function generateForwardRef(expr: o.Expression): o.Expression {
return o.importExpr(Identifiers.forwardRef).callFn([o.arrowFn([], expr)]);
}
/**
* Specifies how a forward ref has been handled in a MaybeForwardRefExpression
*/
export const enum ForwardRefHandling {
/** The expression was not wrapped in a `forwardRef()` call in the first place. */
None,
/** The expression is still wrapped in a `forwardRef()` call. */
Wrapped,
/** The expression was wrapped in a `forwardRef()` call but has since been unwrapped. */
Unwrapped,
}
| {
"end_byte": 5954,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/util.ts"
} |
angular/packages/compiler/src/render3/r3_module_compiler.ts_0_8481 | /**
* @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.dev/license
*/
import {R3DeclareNgModuleFacade} from '../compiler_facade_interface';
import * as o from '../output/output_ast';
import {Identifiers as R3} from './r3_identifiers';
import {jitOnlyGuardedExpression, R3CompiledExpression, R3Reference, refsToArray} from './util';
import {DefinitionMap} from './view/util';
/**
* How the selector scope of an NgModule (its declarations, imports, and exports) should be emitted
* as a part of the NgModule definition.
*/
export enum R3SelectorScopeMode {
/**
* Emit the declarations inline into the module definition.
*
* This option is useful in certain contexts where it's known that JIT support is required. The
* tradeoff here is that this emit style prevents directives and pipes from being tree-shaken if
* they are unused, but the NgModule is used.
*/
Inline,
/**
* Emit the declarations using a side effectful function call, `ɵɵsetNgModuleScope`, that is
* guarded with the `ngJitMode` flag.
*
* This form of emit supports JIT and can be optimized away if the `ngJitMode` flag is set to
* false, which allows unused directives and pipes to be tree-shaken.
*/
SideEffect,
/**
* Don't generate selector scopes at all.
*
* This is useful for contexts where JIT support is known to be unnecessary.
*/
Omit,
}
/**
* The type of the NgModule meta data.
* - Global: Used for full and partial compilation modes which mainly includes R3References.
* - Local: Used for the local compilation mode which mainly includes the raw expressions as appears
* in the NgModule decorator.
*/
export enum R3NgModuleMetadataKind {
Global,
Local,
}
interface R3NgModuleMetadataCommon {
kind: R3NgModuleMetadataKind;
/**
* An expression representing the module type being compiled.
*/
type: R3Reference;
/**
* How to emit the selector scope values (declarations, imports, exports).
*/
selectorScopeMode: R3SelectorScopeMode;
/**
* The set of schemas that declare elements to be allowed in the NgModule.
*/
schemas: R3Reference[] | null;
/** Unique ID or expression representing the unique ID of an NgModule. */
id: o.Expression | null;
}
/**
* Metadata required by the module compiler in full/partial mode to generate a module def (`ɵmod`)
* for a type.
*/
export interface R3NgModuleMetadataGlobal extends R3NgModuleMetadataCommon {
kind: R3NgModuleMetadataKind.Global;
/**
* An array of expressions representing the bootstrap components specified by the module.
*/
bootstrap: R3Reference[];
/**
* An array of expressions representing the directives and pipes declared by the module.
*/
declarations: R3Reference[];
/**
* Those declarations which should be visible to downstream consumers. If not specified, all
* declarations are made visible to downstream consumers.
*/
publicDeclarationTypes: o.Expression[] | null;
/**
* An array of expressions representing the imports of the module.
*/
imports: R3Reference[];
/**
* Whether or not to include `imports` in generated type declarations.
*/
includeImportTypes: boolean;
/**
* An array of expressions representing the exports of the module.
*/
exports: R3Reference[];
/**
* Whether to generate closure wrappers for bootstrap, declarations, imports, and exports.
*/
containsForwardDecls: boolean;
}
/**
* Metadata required by the module compiler in local mode to generate a module def (`ɵmod`) for a
* type.
*/
export interface R3NgModuleMetadataLocal extends R3NgModuleMetadataCommon {
kind: R3NgModuleMetadataKind.Local;
/**
* The output expression representing the bootstrap components specified by the module.
*/
bootstrapExpression: o.Expression | null;
/**
* The output expression representing the declarations of the module.
*/
declarationsExpression: o.Expression | null;
/**
* The output expression representing the imports of the module.
*/
importsExpression: o.Expression | null;
/**
* The output expression representing the exports of the module.
*/
exportsExpression: o.Expression | null;
/**
* Local compilation mode always requires scope to be handled using side effect function calls.
*/
selectorScopeMode: R3SelectorScopeMode.SideEffect;
}
/**
* Metadata required by the module compiler to generate a module def (`ɵmod`) for a type.
*/
export type R3NgModuleMetadata = R3NgModuleMetadataGlobal | R3NgModuleMetadataLocal;
/**
* The shape of the object literal that is passed to the `ɵɵdefineNgModule()` call.
*/
interface R3NgModuleDefMap {
/**
* An expression representing the module type being compiled.
*/
type: o.Expression;
/**
* An expression evaluating to an array of expressions representing the bootstrap components
* specified by the module.
*/
bootstrap?: o.Expression;
/**
* An expression evaluating to an array of expressions representing the directives and pipes
* declared by the module.
*/
declarations?: o.Expression;
/**
* An expression evaluating to an array of expressions representing the imports of the module.
*/
imports?: o.Expression;
/**
* An expression evaluating to an array of expressions representing the exports of the module.
*/
exports?: o.Expression;
/**
* A literal array expression containing the schemas that declare elements to be allowed in the
* NgModule.
*/
schemas?: o.LiteralArrayExpr;
/**
* An expression evaluating to the unique ID of an NgModule.
* */
id?: o.Expression;
}
/**
* Construct an `R3NgModuleDef` for the given `R3NgModuleMetadata`.
*/
export function compileNgModule(meta: R3NgModuleMetadata): R3CompiledExpression {
const statements: o.Statement[] = [];
const definitionMap = new DefinitionMap<R3NgModuleDefMap>();
definitionMap.set('type', meta.type.value);
// Assign bootstrap definition. In local compilation mode (i.e., for
// `R3NgModuleMetadataKind.LOCAL`) we assign the bootstrap field using the runtime
// `ɵɵsetNgModuleScope`.
if (meta.kind === R3NgModuleMetadataKind.Global && meta.bootstrap.length > 0) {
definitionMap.set('bootstrap', refsToArray(meta.bootstrap, meta.containsForwardDecls));
}
if (meta.selectorScopeMode === R3SelectorScopeMode.Inline) {
// If requested to emit scope information inline, pass the `declarations`, `imports` and
// `exports` to the `ɵɵdefineNgModule()` call directly.
if (meta.declarations.length > 0) {
definitionMap.set('declarations', refsToArray(meta.declarations, meta.containsForwardDecls));
}
if (meta.imports.length > 0) {
definitionMap.set('imports', refsToArray(meta.imports, meta.containsForwardDecls));
}
if (meta.exports.length > 0) {
definitionMap.set('exports', refsToArray(meta.exports, meta.containsForwardDecls));
}
} else if (meta.selectorScopeMode === R3SelectorScopeMode.SideEffect) {
// In this mode, scope information is not passed into `ɵɵdefineNgModule` as it
// would prevent tree-shaking of the declarations, imports and exports references. Instead, it's
// patched onto the NgModule definition with a `ɵɵsetNgModuleScope` call that's guarded by the
// `ngJitMode` flag.
const setNgModuleScopeCall = generateSetNgModuleScopeCall(meta);
if (setNgModuleScopeCall !== null) {
statements.push(setNgModuleScopeCall);
}
} else {
// Selector scope emit was not requested, so skip it.
}
if (meta.schemas !== null && meta.schemas.length > 0) {
definitionMap.set('schemas', o.literalArr(meta.schemas.map((ref) => ref.value)));
}
if (meta.id !== null) {
definitionMap.set('id', meta.id);
// Generate a side-effectful call to register this NgModule by its id, as per the semantics of
// NgModule ids.
statements.push(
o.importExpr(R3.registerNgModuleType).callFn([meta.type.value, meta.id]).toStmt(),
);
}
const expression = o
.importExpr(R3.defineNgModule)
.callFn([definitionMap.toLiteralMap()], undefined, true);
const type = createNgModuleType(meta);
return {expression, type, statements};
}
/**
* This function is used in JIT mode to generate the call to `ɵɵdefineNgModule()` from a call to
* `ɵɵngDeclareNgModule()`.
*/
export function co | {
"end_byte": 8481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_module_compiler.ts"
} |
angular/packages/compiler/src/render3/r3_module_compiler.ts_8482_12855 | pileNgModuleDeclarationExpression(meta: R3DeclareNgModuleFacade): o.Expression {
const definitionMap = new DefinitionMap<R3NgModuleDefMap>();
definitionMap.set('type', new o.WrappedNodeExpr(meta.type));
if (meta.bootstrap !== undefined) {
definitionMap.set('bootstrap', new o.WrappedNodeExpr(meta.bootstrap));
}
if (meta.declarations !== undefined) {
definitionMap.set('declarations', new o.WrappedNodeExpr(meta.declarations));
}
if (meta.imports !== undefined) {
definitionMap.set('imports', new o.WrappedNodeExpr(meta.imports));
}
if (meta.exports !== undefined) {
definitionMap.set('exports', new o.WrappedNodeExpr(meta.exports));
}
if (meta.schemas !== undefined) {
definitionMap.set('schemas', new o.WrappedNodeExpr(meta.schemas));
}
if (meta.id !== undefined) {
definitionMap.set('id', new o.WrappedNodeExpr(meta.id));
}
return o.importExpr(R3.defineNgModule).callFn([definitionMap.toLiteralMap()]);
}
export function createNgModuleType(meta: R3NgModuleMetadata): o.ExpressionType {
if (meta.kind === R3NgModuleMetadataKind.Local) {
return new o.ExpressionType(meta.type.value);
}
const {
type: moduleType,
declarations,
exports,
imports,
includeImportTypes,
publicDeclarationTypes,
} = meta;
return new o.ExpressionType(
o.importExpr(R3.NgModuleDeclaration, [
new o.ExpressionType(moduleType.type),
publicDeclarationTypes === null
? tupleTypeOf(declarations)
: tupleOfTypes(publicDeclarationTypes),
includeImportTypes ? tupleTypeOf(imports) : o.NONE_TYPE,
tupleTypeOf(exports),
]),
);
}
/**
* Generates a function call to `ɵɵsetNgModuleScope` with all necessary information so that the
* transitive module scope can be computed during runtime in JIT mode. This call is marked pure
* such that the references to declarations, imports and exports may be elided causing these
* symbols to become tree-shakeable.
*/
function generateSetNgModuleScopeCall(meta: R3NgModuleMetadata): o.Statement | null {
const scopeMap = new DefinitionMap<{
declarations: o.Expression;
imports: o.Expression;
exports: o.Expression;
bootstrap: o.Expression;
}>();
if (meta.kind === R3NgModuleMetadataKind.Global) {
if (meta.declarations.length > 0) {
scopeMap.set('declarations', refsToArray(meta.declarations, meta.containsForwardDecls));
}
} else {
if (meta.declarationsExpression) {
scopeMap.set('declarations', meta.declarationsExpression);
}
}
if (meta.kind === R3NgModuleMetadataKind.Global) {
if (meta.imports.length > 0) {
scopeMap.set('imports', refsToArray(meta.imports, meta.containsForwardDecls));
}
} else {
if (meta.importsExpression) {
scopeMap.set('imports', meta.importsExpression);
}
}
if (meta.kind === R3NgModuleMetadataKind.Global) {
if (meta.exports.length > 0) {
scopeMap.set('exports', refsToArray(meta.exports, meta.containsForwardDecls));
}
} else {
if (meta.exportsExpression) {
scopeMap.set('exports', meta.exportsExpression);
}
}
if (meta.kind === R3NgModuleMetadataKind.Local && meta.bootstrapExpression) {
scopeMap.set('bootstrap', meta.bootstrapExpression);
}
if (Object.keys(scopeMap.values).length === 0) {
return null;
}
// setNgModuleScope(...)
const fnCall = new o.InvokeFunctionExpr(
/* fn */ o.importExpr(R3.setNgModuleScope),
/* args */ [meta.type.value, scopeMap.toLiteralMap()],
);
// (ngJitMode guard) && setNgModuleScope(...)
const guardedCall = jitOnlyGuardedExpression(fnCall);
// function() { (ngJitMode guard) && setNgModuleScope(...); }
const iife = new o.FunctionExpr(/* params */ [], /* statements */ [guardedCall.toStmt()]);
// (function() { (ngJitMode guard) && setNgModuleScope(...); })()
const iifeCall = new o.InvokeFunctionExpr(/* fn */ iife, /* args */ []);
return iifeCall.toStmt();
}
function tupleTypeOf(exp: R3Reference[]): o.Type {
const types = exp.map((ref) => o.typeofExpr(ref.type));
return exp.length > 0 ? o.expressionType(o.literalArr(types)) : o.NONE_TYPE;
}
function tupleOfTypes(types: o.Expression[]): o.Type {
const typeofTypes = types.map((type) => o.typeofExpr(type));
return types.length > 0 ? o.expressionType(o.literalArr(typeofTypes)) : o.NONE_TYPE;
}
| {
"end_byte": 12855,
"start_byte": 8482,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_module_compiler.ts"
} |
angular/packages/compiler/src/render3/r3_deferred_triggers.ts_0_5299 | /**
* @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.dev/license
*/
import * as chars from '../chars';
import {Lexer, Token, TokenType} from '../expression_parser/lexer';
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 a timing value in a trigger. */
const TIME_PATTERN = /^\d+\.?\d*(ms|s)?$/;
/** Pattern for a separator between keywords in a trigger expression. */
const SEPARATOR_PATTERN = /^\s$/;
/** Pairs of characters that form syntax that is comma-delimited. */
const COMMA_DELIMITED_SYNTAX = new Map([
[chars.$LBRACE, chars.$RBRACE], // Object literals
[chars.$LBRACKET, chars.$RBRACKET], // Array literals
[chars.$LPAREN, chars.$RPAREN], // Function calls
]);
/** Possible types of `on` triggers. */
enum OnTriggerType {
IDLE = 'idle',
TIMER = 'timer',
INTERACTION = 'interaction',
IMMEDIATE = 'immediate',
HOVER = 'hover',
VIEWPORT = 'viewport',
NEVER = 'never',
}
/** Function that validates the structure of a reference-based trigger. */
type ReferenceTriggerValidator = (
type: OnTriggerType,
parameters: string[],
placeholder: t.DeferredBlockPlaceholder | null,
) => void;
/** Parses a `when` deferred trigger. */
export function parseNeverTrigger(
{expression, sourceSpan}: html.BlockParameter,
triggers: t.DeferredBlockTriggers,
errors: ParseError[],
): void {
const neverIndex = expression.indexOf('never');
const neverSourceSpan = new ParseSourceSpan(
sourceSpan.start.moveBy(neverIndex),
sourceSpan.start.moveBy(neverIndex + 'never'.length),
);
const prefetchSpan = getPrefetchSpan(expression, sourceSpan);
const hydrateSpan = getHydrateSpan(expression, sourceSpan);
// This is here just to be safe, we shouldn't enter this function
// in the first place if a block doesn't have the "on" keyword.
if (neverIndex === -1) {
errors.push(new ParseError(sourceSpan, `Could not find "never" keyword in expression`));
} else {
trackTrigger(
'never',
triggers,
errors,
new t.NeverDeferredTrigger(neverSourceSpan, sourceSpan, prefetchSpan, null, hydrateSpan),
);
}
}
/** Parses a `when` deferred trigger. */
export function parseWhenTrigger(
{expression, sourceSpan}: html.BlockParameter,
bindingParser: BindingParser,
triggers: t.DeferredBlockTriggers,
errors: ParseError[],
): void {
const whenIndex = expression.indexOf('when');
const whenSourceSpan = new ParseSourceSpan(
sourceSpan.start.moveBy(whenIndex),
sourceSpan.start.moveBy(whenIndex + 'when'.length),
);
const prefetchSpan = getPrefetchSpan(expression, sourceSpan);
const hydrateSpan = getHydrateSpan(expression, sourceSpan);
// This is here just to be safe, we shouldn't enter this function
// in the first place if a block doesn't have the "when" keyword.
if (whenIndex === -1) {
errors.push(new ParseError(sourceSpan, `Could not find "when" keyword in expression`));
} else {
const start = getTriggerParametersStart(expression, whenIndex + 1);
const parsed = bindingParser.parseBinding(
expression.slice(start),
false,
sourceSpan,
sourceSpan.start.offset + start,
);
trackTrigger(
'when',
triggers,
errors,
new t.BoundDeferredTrigger(parsed, sourceSpan, prefetchSpan, whenSourceSpan, hydrateSpan),
);
}
}
/** Parses an `on` trigger */
export function parseOnTrigger(
{expression, sourceSpan}: html.BlockParameter,
triggers: t.DeferredBlockTriggers,
errors: ParseError[],
placeholder: t.DeferredBlockPlaceholder | null,
): void {
const onIndex = expression.indexOf('on');
const onSourceSpan = new ParseSourceSpan(
sourceSpan.start.moveBy(onIndex),
sourceSpan.start.moveBy(onIndex + 'on'.length),
);
const prefetchSpan = getPrefetchSpan(expression, sourceSpan);
const hydrateSpan = getHydrateSpan(expression, sourceSpan);
// This is here just to be safe, we shouldn't enter this function
// in the first place if a block doesn't have the "on" keyword.
if (onIndex === -1) {
errors.push(new ParseError(sourceSpan, `Could not find "on" keyword in expression`));
} else {
const start = getTriggerParametersStart(expression, onIndex + 1);
const parser = new OnTriggerParser(
expression,
start,
sourceSpan,
triggers,
errors,
expression.startsWith('hydrate')
? validateHydrateReferenceBasedTrigger
: validatePlainReferenceBasedTrigger,
placeholder,
prefetchSpan,
onSourceSpan,
hydrateSpan,
);
parser.parse();
}
}
function getPrefetchSpan(expression: string, sourceSpan: ParseSourceSpan) {
if (!expression.startsWith('prefetch')) {
return null;
}
return new ParseSourceSpan(sourceSpan.start, sourceSpan.start.moveBy('prefetch'.length));
}
function getHydrateSpan(expression: string, sourceSpan: ParseSourceSpan) {
if (!expression.startsWith('hydrate')) {
return null;
}
return new ParseSourceSpan(sourceSpan.start, sourceSpan.start.moveBy('hydrate'.length));
} | {
"end_byte": 5299,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_deferred_triggers.ts"
} |
angular/packages/compiler/src/render3/r3_deferred_triggers.ts_5301_14184 | class OnTriggerParser {
private index = 0;
private tokens: Token[];
constructor(
private expression: string,
private start: number,
private span: ParseSourceSpan,
private triggers: t.DeferredBlockTriggers,
private errors: ParseError[],
private validator: ReferenceTriggerValidator,
private placeholder: t.DeferredBlockPlaceholder | null,
private prefetchSpan: ParseSourceSpan | null,
private onSourceSpan: ParseSourceSpan,
private hydrateSpan: ParseSourceSpan | null,
) {
this.tokens = new Lexer().tokenize(expression.slice(start));
}
parse(): void {
while (this.tokens.length > 0 && this.index < this.tokens.length) {
const token = this.token();
if (!token.isIdentifier()) {
this.unexpectedToken(token);
break;
}
// An identifier immediately followed by a comma or the end of
// the expression cannot have parameters so we can exit early.
if (this.isFollowedByOrLast(chars.$COMMA)) {
this.consumeTrigger(token, []);
this.advance();
} else if (this.isFollowedByOrLast(chars.$LPAREN)) {
this.advance(); // Advance to the opening paren.
const prevErrors = this.errors.length;
const parameters = this.consumeParameters();
if (this.errors.length !== prevErrors) {
break;
}
this.consumeTrigger(token, parameters);
this.advance(); // Advance past the closing paren.
} else if (this.index < this.tokens.length - 1) {
this.unexpectedToken(this.tokens[this.index + 1]);
}
this.advance();
}
}
private advance() {
this.index++;
}
private isFollowedByOrLast(char: number): boolean {
if (this.index === this.tokens.length - 1) {
return true;
}
return this.tokens[this.index + 1].isCharacter(char);
}
private token(): Token {
return this.tokens[Math.min(this.index, this.tokens.length - 1)];
}
private consumeTrigger(identifier: Token, parameters: string[]) {
const triggerNameStartSpan = this.span.start.moveBy(
this.start + identifier.index - this.tokens[0].index,
);
const nameSpan = new ParseSourceSpan(
triggerNameStartSpan,
triggerNameStartSpan.moveBy(identifier.strValue.length),
);
const endSpan = triggerNameStartSpan.moveBy(this.token().end - identifier.index);
// Put the prefetch and on spans with the first trigger
// This should maybe be refactored to have something like an outer OnGroup AST
// Since triggers can be grouped with commas "on hover(x), interaction(y)"
const isFirstTrigger = identifier.index === 0;
const onSourceSpan = isFirstTrigger ? this.onSourceSpan : null;
const prefetchSourceSpan = isFirstTrigger ? this.prefetchSpan : null;
const hydrateSourceSpan = isFirstTrigger ? this.hydrateSpan : null;
const sourceSpan = new ParseSourceSpan(
isFirstTrigger ? this.span.start : triggerNameStartSpan,
endSpan,
);
try {
switch (identifier.toString()) {
case OnTriggerType.IDLE:
this.trackTrigger(
'idle',
createIdleTrigger(
parameters,
nameSpan,
sourceSpan,
prefetchSourceSpan,
onSourceSpan,
hydrateSourceSpan,
),
);
break;
case OnTriggerType.TIMER:
this.trackTrigger(
'timer',
createTimerTrigger(
parameters,
nameSpan,
sourceSpan,
this.prefetchSpan,
this.onSourceSpan,
this.hydrateSpan,
),
);
break;
case OnTriggerType.INTERACTION:
this.trackTrigger(
'interaction',
createInteractionTrigger(
parameters,
nameSpan,
sourceSpan,
this.prefetchSpan,
this.onSourceSpan,
this.hydrateSpan,
this.placeholder,
this.validator,
),
);
break;
case OnTriggerType.IMMEDIATE:
this.trackTrigger(
'immediate',
createImmediateTrigger(
parameters,
nameSpan,
sourceSpan,
this.prefetchSpan,
this.onSourceSpan,
this.hydrateSpan,
),
);
break;
case OnTriggerType.HOVER:
this.trackTrigger(
'hover',
createHoverTrigger(
parameters,
nameSpan,
sourceSpan,
this.prefetchSpan,
this.onSourceSpan,
this.hydrateSpan,
this.placeholder,
this.validator,
),
);
break;
case OnTriggerType.VIEWPORT:
this.trackTrigger(
'viewport',
createViewportTrigger(
parameters,
nameSpan,
sourceSpan,
this.prefetchSpan,
this.onSourceSpan,
this.hydrateSpan,
this.placeholder,
this.validator,
),
);
break;
default:
throw new Error(`Unrecognized trigger type "${identifier}"`);
}
} catch (e) {
this.error(identifier, (e as Error).message);
}
}
private consumeParameters(): string[] {
const parameters: string[] = [];
if (!this.token().isCharacter(chars.$LPAREN)) {
this.unexpectedToken(this.token());
return parameters;
}
this.advance();
const commaDelimStack: number[] = [];
let current = '';
while (this.index < this.tokens.length) {
const token = this.token();
// Stop parsing if we've hit the end character and we're outside of a comma-delimited syntax.
// Note that we don't need to account for strings here since the lexer already parsed them
// into string tokens.
if (token.isCharacter(chars.$RPAREN) && commaDelimStack.length === 0) {
if (current.length) {
parameters.push(current);
}
break;
}
// In the `on` microsyntax "top-level" commas (e.g. ones outside of an parameters) separate
// the different triggers (e.g. `on idle,timer(500)`). This is problematic, because the
// function-like syntax also implies that multiple parameters can be passed into the
// individual trigger (e.g. `on foo(a, b)`). To avoid tripping up the parser with commas that
// are part of other sorts of syntax (object literals, arrays), we treat anything inside
// a comma-delimited syntax block as plain text.
if (token.type === TokenType.Character && COMMA_DELIMITED_SYNTAX.has(token.numValue)) {
commaDelimStack.push(COMMA_DELIMITED_SYNTAX.get(token.numValue)!);
}
if (
commaDelimStack.length > 0 &&
token.isCharacter(commaDelimStack[commaDelimStack.length - 1])
) {
commaDelimStack.pop();
}
// If we hit a comma outside of a comma-delimited syntax, it means
// that we're at the top level and we're starting a new parameter.
if (commaDelimStack.length === 0 && token.isCharacter(chars.$COMMA) && current.length > 0) {
parameters.push(current);
current = '';
this.advance();
continue;
}
// Otherwise treat the token as a plain text character in the current parameter.
current += this.tokenText();
this.advance();
}
if (!this.token().isCharacter(chars.$RPAREN) || commaDelimStack.length > 0) {
this.error(this.token(), 'Unexpected end of expression');
}
if (
this.index < this.tokens.length - 1 &&
!this.tokens[this.index + 1].isCharacter(chars.$COMMA)
) {
this.unexpectedToken(this.tokens[this.index + 1]);
}
return parameters;
}
private tokenText(): string {
// Tokens have a toString already which we could use, but for string tokens it omits the quotes.
// Eventually we could expose this information on the token directly.
return this.expression.slice(this.start + this.token().index, this.start + this.token().end);
}
private trackTrigger(name: keyof t.DeferredBlockTriggers, trigger: t.DeferredTrigger): void {
trackTrigger(name, this.triggers, this.errors, trigger);
}
private error(token: Token, message: string): void {
const newStart = this.span.start.moveBy(this.start + token.index);
const newEnd = newStart.moveBy(token.end - token.index);
this.errors.push(new ParseError(new ParseSourceSpan(newStart, newEnd), message));
}
private unexpectedToken(token: Token) {
this.error(token, `Unexpected token "${token}"`);
}
}
/** Adds a trigger to a map of triggers. */ | {
"end_byte": 14184,
"start_byte": 5301,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_deferred_triggers.ts"
} |
angular/packages/compiler/src/render3/r3_deferred_triggers.ts_14185_20082 | function trackTrigger(
name: keyof t.DeferredBlockTriggers,
allTriggers: t.DeferredBlockTriggers,
errors: ParseError[],
trigger: t.DeferredTrigger,
) {
if (allTriggers[name]) {
errors.push(new ParseError(trigger.sourceSpan, `Duplicate "${name}" trigger is not allowed`));
} else {
allTriggers[name] = trigger as any;
}
}
function createIdleTrigger(
parameters: string[],
nameSpan: ParseSourceSpan,
sourceSpan: ParseSourceSpan,
prefetchSpan: ParseSourceSpan | null,
onSourceSpan: ParseSourceSpan | null,
hydrateSpan: ParseSourceSpan | null,
): t.IdleDeferredTrigger {
if (parameters.length > 0) {
throw new Error(`"${OnTriggerType.IDLE}" trigger cannot have parameters`);
}
return new t.IdleDeferredTrigger(nameSpan, sourceSpan, prefetchSpan, onSourceSpan, hydrateSpan);
}
function createTimerTrigger(
parameters: string[],
nameSpan: ParseSourceSpan,
sourceSpan: ParseSourceSpan,
prefetchSpan: ParseSourceSpan | null,
onSourceSpan: ParseSourceSpan | null,
hydrateSpan: ParseSourceSpan | null,
) {
if (parameters.length !== 1) {
throw new Error(`"${OnTriggerType.TIMER}" trigger must have exactly one parameter`);
}
const delay = parseDeferredTime(parameters[0]);
if (delay === null) {
throw new Error(`Could not parse time value of trigger "${OnTriggerType.TIMER}"`);
}
return new t.TimerDeferredTrigger(
delay,
nameSpan,
sourceSpan,
prefetchSpan,
onSourceSpan,
hydrateSpan,
);
}
function createImmediateTrigger(
parameters: string[],
nameSpan: ParseSourceSpan,
sourceSpan: ParseSourceSpan,
prefetchSpan: ParseSourceSpan | null,
onSourceSpan: ParseSourceSpan | null,
hydrateSpan: ParseSourceSpan | null,
): t.ImmediateDeferredTrigger {
if (parameters.length > 0) {
throw new Error(`"${OnTriggerType.IMMEDIATE}" trigger cannot have parameters`);
}
return new t.ImmediateDeferredTrigger(
nameSpan,
sourceSpan,
prefetchSpan,
onSourceSpan,
hydrateSpan,
);
}
function createHoverTrigger(
parameters: string[],
nameSpan: ParseSourceSpan,
sourceSpan: ParseSourceSpan,
prefetchSpan: ParseSourceSpan | null,
onSourceSpan: ParseSourceSpan | null,
hydrateSpan: ParseSourceSpan | null,
placeholder: t.DeferredBlockPlaceholder | null,
validator: ReferenceTriggerValidator,
): t.HoverDeferredTrigger {
validator(OnTriggerType.HOVER, parameters, placeholder);
return new t.HoverDeferredTrigger(
parameters[0] ?? null,
nameSpan,
sourceSpan,
prefetchSpan,
onSourceSpan,
hydrateSpan,
);
}
function createInteractionTrigger(
parameters: string[],
nameSpan: ParseSourceSpan,
sourceSpan: ParseSourceSpan,
prefetchSpan: ParseSourceSpan | null,
onSourceSpan: ParseSourceSpan | null,
hydrateSpan: ParseSourceSpan | null,
placeholder: t.DeferredBlockPlaceholder | null,
validator: ReferenceTriggerValidator,
): t.InteractionDeferredTrigger {
validator(OnTriggerType.INTERACTION, parameters, placeholder);
return new t.InteractionDeferredTrigger(
parameters[0] ?? null,
nameSpan,
sourceSpan,
prefetchSpan,
onSourceSpan,
hydrateSpan,
);
}
function createViewportTrigger(
parameters: string[],
nameSpan: ParseSourceSpan,
sourceSpan: ParseSourceSpan,
prefetchSpan: ParseSourceSpan | null,
onSourceSpan: ParseSourceSpan | null,
hydrateSpan: ParseSourceSpan | null,
placeholder: t.DeferredBlockPlaceholder | null,
validator: ReferenceTriggerValidator,
): t.ViewportDeferredTrigger {
validator(OnTriggerType.VIEWPORT, parameters, placeholder);
return new t.ViewportDeferredTrigger(
parameters[0] ?? null,
nameSpan,
sourceSpan,
prefetchSpan,
onSourceSpan,
hydrateSpan,
);
}
/**
* Checks whether the structure of a non-hydrate reference-based trigger is valid.
* @param type Type of the trigger being validated.
* @param parameters Parameters of the trigger.
* @param placeholder Placeholder of the defer block.
*/
function validatePlainReferenceBasedTrigger(
type: OnTriggerType,
parameters: string[],
placeholder: t.DeferredBlockPlaceholder | null,
) {
if (parameters.length > 1) {
throw new Error(`"${type}" trigger can only have zero or one parameters`);
}
if (parameters.length === 0) {
if (placeholder === null) {
throw new Error(
`"${type}" trigger with no parameters can only be placed on an @defer that has a @placeholder block`,
);
}
if (placeholder.children.length !== 1 || !(placeholder.children[0] instanceof t.Element)) {
throw new Error(
`"${type}" trigger with no parameters can only be placed on an @defer that has a ` +
`@placeholder block with exactly one root element node`,
);
}
}
}
/**
* Checks whether the structure of a hydrate trigger is valid.
* @param type Type of the trigger being validated.
* @param parameters Parameters of the trigger.
*/
function validateHydrateReferenceBasedTrigger(type: OnTriggerType, parameters: string[]) {
if (parameters.length > 0) {
throw new Error(`Hydration trigger "${type}" cannot have parameters`);
}
}
/** Gets the index within an expression at which the trigger parameters start. */
export function getTriggerParametersStart(value: string, startPosition = 0): number {
let hasFoundSeparator = false;
for (let i = startPosition; i < value.length; i++) {
if (SEPARATOR_PATTERN.test(value[i])) {
hasFoundSeparator = true;
} else if (hasFoundSeparator) {
return i;
}
}
return -1;
}
/**
* Parses a time expression from a deferred trigger to
* milliseconds. Returns null if it cannot be parsed.
*/
export function parseDeferredTime(value: string): number | null {
const match = value.match(TIME_PATTERN);
if (!match) {
return null;
}
const [time, units] = match;
return parseFloat(time) * (units === 's' ? 1000 : 1);
} | {
"end_byte": 20082,
"start_byte": 14185,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_deferred_triggers.ts"
} |
angular/packages/compiler/src/render3/r3_hmr_compiler.ts_0_4351 | /*!
* @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.dev/license
*/
import * as o from '../output/output_ast';
import {Identifiers as R3} from './r3_identifiers';
import {devOnlyGuardedExpression} from './util';
/** Metadata necessary to compile HMR-related code call. */
export interface R3HmrMetadata {
/** Component class for which HMR is being enabled. */
type: o.Expression;
/** Name of the component class. */
className: string;
/** File path of the component class. */
filePath: string;
/** Name under which `@angular/core` should be referred to in the compiled HMR code. */
coreName: string;
/**
* HMR update functions cannot contain imports so any locals the generated code depends on
* (e.g. references to imports within the same file or imported symbols) have to be passed in
* as function parameters. This array contains the names of those local symbols.
*/
locals: string[];
}
/**
* Compiles the expression that initializes HMR for a class.
* @param meta HMR metadata extracted from the class.
*/
export function compileHmrInitializer(meta: R3HmrMetadata): o.Expression {
const id = encodeURIComponent(`${meta.filePath}@${meta.className}`);
const urlPartial = `/@ng/component?c=${id}&t=`;
const moduleName = 'm';
const dataName = 'd';
const locals = meta.locals.map((localName) => o.variable(localName));
// ɵɵreplaceMetadata(Comp, m.default, [...]);
const replaceMetadata = o
.importExpr(R3.replaceMetadata)
.callFn([meta.type, o.variable(moduleName).prop('default'), o.literalArr(locals)]);
// (m) => ɵɵreplaceMetadata(...)
const replaceCallback = o.arrowFn([new o.FnParam(moduleName)], replaceMetadata);
// '<urlPartial>' + encodeURIComponent(d.timestamp)
const urlValue = o
.literal(urlPartial)
.plus(o.variable('encodeURIComponent').callFn([o.variable(dataName).prop('timestamp')]));
// import(/* @vite-ignore */ url).then(() => replaceMetadata(...));
// The vite-ignore special comment is required to avoid Vite from generating a superfluous
// warning for each usage within the development code. If Vite provides a method to
// programmatically avoid this warning in the future, this added comment can be removed here.
const dynamicImport = new o.DynamicImportExpr(urlValue, null, '@vite-ignore')
.prop('then')
.callFn([replaceCallback]);
// (d) => { if (d.id === <id>) { replaceMetadata(...) } }
const listenerCallback = o.arrowFn(
[new o.FnParam(dataName)],
[o.ifStmt(o.variable(dataName).prop('id').equals(o.literal(id)), [dynamicImport.toStmt()])],
);
// import.meta.hot
const hotRead = o.variable('import').prop('meta').prop('hot');
// import.meta.hot.on('angular:component-update', () => ...);
const hotListener = hotRead
.clone()
.prop('on')
.callFn([o.literal('angular:component-update'), listenerCallback]);
// import.meta.hot && import.meta.hot.on(...)
return o.arrowFn([], [devOnlyGuardedExpression(hotRead.and(hotListener)).toStmt()]).callFn([]);
}
/**
* Compiles the HMR update callback for a class.
* @param definitions Compiled definitions for the class (e.g. `defineComponent` calls).
* @param constantStatements Supporting constants statements that were generated alongside
* the definition.
* @param meta HMR metadata extracted from the class.
*/
export function compileHmrUpdateCallback(
definitions: {name: string; initializer: o.Expression | null; statements: o.Statement[]}[],
constantStatements: o.Statement[],
meta: R3HmrMetadata,
): o.DeclareFunctionStmt {
// The class name should always be first and core should be second.
const params = [meta.className, meta.coreName, ...meta.locals].map(
(name) => new o.FnParam(name, o.DYNAMIC_TYPE),
);
const body: o.Statement[] = [...constantStatements];
for (const field of definitions) {
if (field.initializer !== null) {
body.push(o.variable(meta.className).prop(field.name).set(field.initializer).toStmt());
for (const stmt of field.statements) {
body.push(stmt);
}
}
}
return new o.DeclareFunctionStmt(
`${meta.className}_UpdateMetadata`,
params,
body,
null,
o.StmtModifier.Final,
);
}
| {
"end_byte": 4351,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_hmr_compiler.ts"
} |
angular/packages/compiler/src/render3/partial/class_metadata.ts_0_3086 | /**
* @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.dev/license
*/
import * as o from '../../output/output_ast';
import {
compileComponentMetadataAsyncResolver,
R3ClassMetadata,
} from '../r3_class_metadata_compiler';
import {Identifiers as R3} from '../r3_identifiers';
import {R3DeferPerComponentDependency} from '../view/api';
import {DefinitionMap} from '../view/util';
import {R3DeclareClassMetadata, R3DeclareClassMetadataAsync} from './api';
/**
* Every time we make a breaking change to the declaration interface or partial-linker behavior, we
* must update this constant to prevent old partial-linkers from incorrectly processing the
* declaration.
*
* Do not include any prerelease in these versions as they are ignored.
*/
const MINIMUM_PARTIAL_LINKER_VERSION = '12.0.0';
/**
* Minimum version at which deferred blocks are supported in the linker.
*/
const MINIMUM_PARTIAL_LINKER_DEFER_SUPPORT_VERSION = '18.0.0';
export function compileDeclareClassMetadata(metadata: R3ClassMetadata): o.Expression {
const definitionMap = new DefinitionMap<R3DeclareClassMetadata>();
definitionMap.set('minVersion', o.literal(MINIMUM_PARTIAL_LINKER_VERSION));
definitionMap.set('version', o.literal('0.0.0-PLACEHOLDER'));
definitionMap.set('ngImport', o.importExpr(R3.core));
definitionMap.set('type', metadata.type);
definitionMap.set('decorators', metadata.decorators);
definitionMap.set('ctorParameters', metadata.ctorParameters);
definitionMap.set('propDecorators', metadata.propDecorators);
return o.importExpr(R3.declareClassMetadata).callFn([definitionMap.toLiteralMap()]);
}
export function compileComponentDeclareClassMetadata(
metadata: R3ClassMetadata,
dependencies: R3DeferPerComponentDependency[] | null,
): o.Expression {
if (dependencies === null || dependencies.length === 0) {
return compileDeclareClassMetadata(metadata);
}
const definitionMap = new DefinitionMap<R3DeclareClassMetadataAsync>();
const callbackReturnDefinitionMap = new DefinitionMap<R3ClassMetadata>();
callbackReturnDefinitionMap.set('decorators', metadata.decorators);
callbackReturnDefinitionMap.set('ctorParameters', metadata.ctorParameters ?? o.literal(null));
callbackReturnDefinitionMap.set('propDecorators', metadata.propDecorators ?? o.literal(null));
definitionMap.set('minVersion', o.literal(MINIMUM_PARTIAL_LINKER_DEFER_SUPPORT_VERSION));
definitionMap.set('version', o.literal('0.0.0-PLACEHOLDER'));
definitionMap.set('ngImport', o.importExpr(R3.core));
definitionMap.set('type', metadata.type);
definitionMap.set('resolveDeferredDeps', compileComponentMetadataAsyncResolver(dependencies));
definitionMap.set(
'resolveMetadata',
o.arrowFn(
dependencies.map((dep) => new o.FnParam(dep.symbolName, o.DYNAMIC_TYPE)),
callbackReturnDefinitionMap.toLiteralMap(),
),
);
return o.importExpr(R3.declareClassMetadataAsync).callFn([definitionMap.toLiteralMap()]);
}
| {
"end_byte": 3086,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/partial/class_metadata.ts"
} |
angular/packages/compiler/src/render3/partial/pipe.ts_0_2105 | /**
* @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.dev/license
*/
import * as o from '../../output/output_ast';
import {Identifiers as R3} from '../r3_identifiers';
import {createPipeType, R3PipeMetadata} from '../r3_pipe_compiler';
import {R3CompiledExpression} from '../util';
import {DefinitionMap} from '../view/util';
import {R3DeclarePipeMetadata} from './api';
/**
* Every time we make a breaking change to the declaration interface or partial-linker behavior, we
* must update this constant to prevent old partial-linkers from incorrectly processing the
* declaration.
*
* Do not include any prerelease in these versions as they are ignored.
*/
const MINIMUM_PARTIAL_LINKER_VERSION = '14.0.0';
/**
* Compile a Pipe declaration defined by the `R3PipeMetadata`.
*/
export function compileDeclarePipeFromMetadata(meta: R3PipeMetadata): R3CompiledExpression {
const definitionMap = createPipeDefinitionMap(meta);
const expression = o.importExpr(R3.declarePipe).callFn([definitionMap.toLiteralMap()]);
const type = createPipeType(meta);
return {expression, type, statements: []};
}
/**
* Gathers the declaration fields for a Pipe into a `DefinitionMap`.
*/
export function createPipeDefinitionMap(
meta: R3PipeMetadata,
): DefinitionMap<R3DeclarePipeMetadata> {
const definitionMap = new DefinitionMap<R3DeclarePipeMetadata>();
definitionMap.set('minVersion', o.literal(MINIMUM_PARTIAL_LINKER_VERSION));
definitionMap.set('version', o.literal('0.0.0-PLACEHOLDER'));
definitionMap.set('ngImport', o.importExpr(R3.core));
// e.g. `type: MyPipe`
definitionMap.set('type', meta.type.value);
if (meta.isStandalone !== undefined) {
definitionMap.set('isStandalone', o.literal(meta.isStandalone));
}
// e.g. `name: "myPipe"`
definitionMap.set('name', o.literal(meta.pipeName));
if (meta.pure === false) {
// e.g. `pure: false`
definitionMap.set('pure', o.literal(meta.pure));
}
return definitionMap;
}
| {
"end_byte": 2105,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/partial/pipe.ts"
} |
angular/packages/compiler/src/render3/partial/component.ts_0_7625 | /**
* @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.dev/license
*/
import * as core from '../../core';
import {DEFAULT_INTERPOLATION_CONFIG} from '../../ml_parser/defaults';
import * as o from '../../output/output_ast';
import {ParseLocation, ParseSourceFile, ParseSourceSpan} from '../../parse_util';
import {RecursiveVisitor, visitAll} from '../r3_ast';
import {Identifiers as R3} from '../r3_identifiers';
import {generateForwardRef, R3CompiledExpression} from '../util';
import {
DeclarationListEmitMode,
DeferBlockDepsEmitMode,
R3ComponentMetadata,
R3TemplateDependencyKind,
R3TemplateDependencyMetadata,
} from '../view/api';
import {createComponentType} from '../view/compiler';
import {ParsedTemplate} from '../view/template';
import {DefinitionMap} from '../view/util';
import {
R3DeclareComponentMetadata,
R3DeclareDirectiveDependencyMetadata,
R3DeclareNgModuleDependencyMetadata,
R3DeclarePipeDependencyMetadata,
} from './api';
import {createDirectiveDefinitionMap} from './directive';
import {toOptionalLiteralArray} from './util';
export interface DeclareComponentTemplateInfo {
/**
* The string contents of the template.
*
* This is the "logical" template string, after expansion of any escaped characters (for inline
* templates). This may differ from the actual template bytes as they appear in the .ts file.
*/
content: string;
/**
* A full path to the file which contains the template.
*
* This can be either the original .ts file if the template is inline, or the .html file if an
* external file was used.
*/
sourceUrl: string;
/**
* Whether the template was inline (using `template`) or external (using `templateUrl`).
*/
isInline: boolean;
/**
* If the template was defined inline by a direct string literal, then this is that literal
* expression. Otherwise `null`, if the template was not defined inline or was not a literal.
*/
inlineTemplateLiteralExpression: o.Expression | null;
}
/**
* Compile a component declaration defined by the `R3ComponentMetadata`.
*/
export function compileDeclareComponentFromMetadata(
meta: R3ComponentMetadata<R3TemplateDependencyMetadata>,
template: ParsedTemplate,
additionalTemplateInfo: DeclareComponentTemplateInfo,
): R3CompiledExpression {
const definitionMap = createComponentDefinitionMap(meta, template, additionalTemplateInfo);
const expression = o.importExpr(R3.declareComponent).callFn([definitionMap.toLiteralMap()]);
const type = createComponentType(meta);
return {expression, type, statements: []};
}
/**
* Gathers the declaration fields for a component into a `DefinitionMap`.
*/
export function createComponentDefinitionMap(
meta: R3ComponentMetadata<R3TemplateDependencyMetadata>,
template: ParsedTemplate,
templateInfo: DeclareComponentTemplateInfo,
): DefinitionMap<R3DeclareComponentMetadata> {
const definitionMap: DefinitionMap<R3DeclareComponentMetadata> =
createDirectiveDefinitionMap(meta);
const blockVisitor = new BlockPresenceVisitor();
visitAll(blockVisitor, template.nodes);
definitionMap.set('template', getTemplateExpression(template, templateInfo));
if (templateInfo.isInline) {
definitionMap.set('isInline', o.literal(true));
}
// Set the minVersion to 17.0.0 if the component is using at least one block in its template.
// We don't do this for templates without blocks, in order to preserve backwards compatibility.
if (blockVisitor.hasBlocks) {
definitionMap.set('minVersion', o.literal('17.0.0'));
}
definitionMap.set('styles', toOptionalLiteralArray(meta.styles, o.literal));
definitionMap.set('dependencies', compileUsedDependenciesMetadata(meta));
definitionMap.set('viewProviders', meta.viewProviders);
definitionMap.set('animations', meta.animations);
if (meta.changeDetection !== null) {
if (typeof meta.changeDetection === 'object') {
throw new Error('Impossible state! Change detection flag is not resolved!');
}
definitionMap.set(
'changeDetection',
o
.importExpr(R3.ChangeDetectionStrategy)
.prop(core.ChangeDetectionStrategy[meta.changeDetection]),
);
}
if (meta.encapsulation !== core.ViewEncapsulation.Emulated) {
definitionMap.set(
'encapsulation',
o.importExpr(R3.ViewEncapsulation).prop(core.ViewEncapsulation[meta.encapsulation]),
);
}
if (meta.interpolation !== DEFAULT_INTERPOLATION_CONFIG) {
definitionMap.set(
'interpolation',
o.literalArr([o.literal(meta.interpolation.start), o.literal(meta.interpolation.end)]),
);
}
if (template.preserveWhitespaces === true) {
definitionMap.set('preserveWhitespaces', o.literal(true));
}
if (meta.defer.mode === DeferBlockDepsEmitMode.PerBlock) {
const resolvers: o.Expression[] = [];
let hasResolvers = false;
for (const deps of meta.defer.blocks.values()) {
// Note: we need to push a `null` even if there are no dependencies, because matching of
// defer resolver functions to defer blocks happens by index and not adding an array
// entry for a block can throw off the blocks coming after it.
if (deps === null) {
resolvers.push(o.literal(null));
} else {
resolvers.push(deps);
hasResolvers = true;
}
}
// If *all* the resolvers are null, we can skip the field.
if (hasResolvers) {
definitionMap.set('deferBlockDependencies', o.literalArr(resolvers));
}
} else {
throw new Error('Unsupported defer function emit mode in partial compilation');
}
return definitionMap;
}
function getTemplateExpression(
template: ParsedTemplate,
templateInfo: DeclareComponentTemplateInfo,
): o.Expression {
// If the template has been defined using a direct literal, we use that expression directly
// without any modifications. This is ensures proper source mapping from the partially
// compiled code to the source file declaring the template. Note that this does not capture
// template literals referenced indirectly through an identifier.
if (templateInfo.inlineTemplateLiteralExpression !== null) {
return templateInfo.inlineTemplateLiteralExpression;
}
// If the template is defined inline but not through a literal, the template has been resolved
// through static interpretation. We create a literal but cannot provide any source span. Note
// that we cannot use the expression defining the template because the linker expects the template
// to be defined as a literal in the declaration.
if (templateInfo.isInline) {
return o.literal(templateInfo.content, null, null);
}
// The template is external so we must synthesize an expression node with
// the appropriate source-span.
const contents = templateInfo.content;
const file = new ParseSourceFile(contents, templateInfo.sourceUrl);
const start = new ParseLocation(file, 0, 0, 0);
const end = computeEndLocation(file, contents);
const span = new ParseSourceSpan(start, end);
return o.literal(contents, null, span);
}
function computeEndLocation(file: ParseSourceFile, contents: string): ParseLocation {
const length = contents.length;
let lineStart = 0;
let lastLineStart = 0;
let line = 0;
do {
lineStart = contents.indexOf('\n', lastLineStart);
if (lineStart !== -1) {
lastLineStart = lineStart + 1;
line++;
}
} while (lineStart !== -1);
return new ParseLocation(file, length, line, length - lastLineStart);
} | {
"end_byte": 7625,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/partial/component.ts"
} |
angular/packages/compiler/src/render3/partial/component.ts_7627_10173 | function compileUsedDependenciesMetadata(
meta: R3ComponentMetadata<R3TemplateDependencyMetadata>,
): o.LiteralArrayExpr | null {
const wrapType =
meta.declarationListEmitMode !== DeclarationListEmitMode.Direct
? generateForwardRef
: (expr: o.Expression) => expr;
if (meta.declarationListEmitMode === DeclarationListEmitMode.RuntimeResolved) {
throw new Error(`Unsupported emit mode`);
}
return toOptionalLiteralArray(meta.declarations, (decl) => {
switch (decl.kind) {
case R3TemplateDependencyKind.Directive:
const dirMeta = new DefinitionMap<R3DeclareDirectiveDependencyMetadata>();
dirMeta.set('kind', o.literal(decl.isComponent ? 'component' : 'directive'));
dirMeta.set('type', wrapType(decl.type));
dirMeta.set('selector', o.literal(decl.selector));
dirMeta.set('inputs', toOptionalLiteralArray(decl.inputs, o.literal));
dirMeta.set('outputs', toOptionalLiteralArray(decl.outputs, o.literal));
dirMeta.set('exportAs', toOptionalLiteralArray(decl.exportAs, o.literal));
return dirMeta.toLiteralMap();
case R3TemplateDependencyKind.Pipe:
const pipeMeta = new DefinitionMap<R3DeclarePipeDependencyMetadata>();
pipeMeta.set('kind', o.literal('pipe'));
pipeMeta.set('type', wrapType(decl.type));
pipeMeta.set('name', o.literal(decl.name));
return pipeMeta.toLiteralMap();
case R3TemplateDependencyKind.NgModule:
const ngModuleMeta = new DefinitionMap<R3DeclareNgModuleDependencyMetadata>();
ngModuleMeta.set('kind', o.literal('ngmodule'));
ngModuleMeta.set('type', wrapType(decl.type));
return ngModuleMeta.toLiteralMap();
}
});
}
class BlockPresenceVisitor extends RecursiveVisitor {
hasBlocks = false;
override visitDeferredBlock(): void {
this.hasBlocks = true;
}
override visitDeferredBlockPlaceholder(): void {
this.hasBlocks = true;
}
override visitDeferredBlockLoading(): void {
this.hasBlocks = true;
}
override visitDeferredBlockError(): void {
this.hasBlocks = true;
}
override visitIfBlock(): void {
this.hasBlocks = true;
}
override visitIfBlockBranch(): void {
this.hasBlocks = true;
}
override visitForLoopBlock(): void {
this.hasBlocks = true;
}
override visitForLoopBlockEmpty(): void {
this.hasBlocks = true;
}
override visitSwitchBlock(): void {
this.hasBlocks = true;
}
override visitSwitchBlockCase(): void {
this.hasBlocks = true;
}
} | {
"end_byte": 10173,
"start_byte": 7627,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/partial/component.ts"
} |
angular/packages/compiler/src/render3/partial/ng_module.ts_0_3094 | /**
* @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.dev/license
*/
import * as o from '../../output/output_ast';
import {Identifiers as R3} from '../r3_identifiers';
import {
createNgModuleType,
R3NgModuleMetadata,
R3NgModuleMetadataKind,
} from '../r3_module_compiler';
import {R3CompiledExpression, refsToArray} from '../util';
import {DefinitionMap} from '../view/util';
import {R3DeclareNgModuleMetadata} from './api';
/**
* Every time we make a breaking change to the declaration interface or partial-linker behavior, we
* must update this constant to prevent old partial-linkers from incorrectly processing the
* declaration.
*
* Do not include any prerelease in these versions as they are ignored.
*/
const MINIMUM_PARTIAL_LINKER_VERSION = '14.0.0';
export function compileDeclareNgModuleFromMetadata(meta: R3NgModuleMetadata): R3CompiledExpression {
const definitionMap = createNgModuleDefinitionMap(meta);
const expression = o.importExpr(R3.declareNgModule).callFn([definitionMap.toLiteralMap()]);
const type = createNgModuleType(meta);
return {expression, type, statements: []};
}
/**
* Gathers the declaration fields for an NgModule into a `DefinitionMap`.
*/
function createNgModuleDefinitionMap(
meta: R3NgModuleMetadata,
): DefinitionMap<R3DeclareNgModuleMetadata> {
const definitionMap = new DefinitionMap<R3DeclareNgModuleMetadata>();
if (meta.kind === R3NgModuleMetadataKind.Local) {
throw new Error(
'Invalid path! Local compilation mode should not get into the partial compilation path',
);
}
definitionMap.set('minVersion', o.literal(MINIMUM_PARTIAL_LINKER_VERSION));
definitionMap.set('version', o.literal('0.0.0-PLACEHOLDER'));
definitionMap.set('ngImport', o.importExpr(R3.core));
definitionMap.set('type', meta.type.value);
// We only generate the keys in the metadata if the arrays contain values.
// We must wrap the arrays inside a function if any of the values are a forward reference to a
// not-yet-declared class. This is to support JIT execution of the `ɵɵngDeclareNgModule()` call.
// In the linker these wrappers are stripped and then reapplied for the `ɵɵdefineNgModule()` call.
if (meta.bootstrap.length > 0) {
definitionMap.set('bootstrap', refsToArray(meta.bootstrap, meta.containsForwardDecls));
}
if (meta.declarations.length > 0) {
definitionMap.set('declarations', refsToArray(meta.declarations, meta.containsForwardDecls));
}
if (meta.imports.length > 0) {
definitionMap.set('imports', refsToArray(meta.imports, meta.containsForwardDecls));
}
if (meta.exports.length > 0) {
definitionMap.set('exports', refsToArray(meta.exports, meta.containsForwardDecls));
}
if (meta.schemas !== null && meta.schemas.length > 0) {
definitionMap.set('schemas', o.literalArr(meta.schemas.map((ref) => ref.value)));
}
if (meta.id !== null) {
definitionMap.set('id', meta.id);
}
return definitionMap;
}
| {
"end_byte": 3094,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/partial/ng_module.ts"
} |
angular/packages/compiler/src/render3/partial/directive.ts_0_7690 | /**
* @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.dev/license
*/
import * as o from '../../output/output_ast';
import {Identifiers as R3} from '../r3_identifiers';
import {
convertFromMaybeForwardRefExpression,
generateForwardRef,
R3CompiledExpression,
} from '../util';
import {R3DirectiveMetadata, R3HostMetadata, R3QueryMetadata} from '../view/api';
import {createDirectiveType, createHostDirectivesMappingArray} from '../view/compiler';
import {
asLiteral,
conditionallyCreateDirectiveBindingLiteral,
DefinitionMap,
UNSAFE_OBJECT_KEY_NAME_REGEXP,
} from '../view/util';
import {R3DeclareDirectiveMetadata, R3DeclareQueryMetadata} from './api';
import {toOptionalLiteralMap} from './util';
/**
* Compile a directive declaration defined by the `R3DirectiveMetadata`.
*/
export function compileDeclareDirectiveFromMetadata(
meta: R3DirectiveMetadata,
): R3CompiledExpression {
const definitionMap = createDirectiveDefinitionMap(meta);
const expression = o.importExpr(R3.declareDirective).callFn([definitionMap.toLiteralMap()]);
const type = createDirectiveType(meta);
return {expression, type, statements: []};
}
/**
* Gathers the declaration fields for a directive into a `DefinitionMap`. This allows for reusing
* this logic for components, as they extend the directive metadata.
*/
export function createDirectiveDefinitionMap(
meta: R3DirectiveMetadata,
): DefinitionMap<R3DeclareDirectiveMetadata> {
const definitionMap = new DefinitionMap<R3DeclareDirectiveMetadata>();
const minVersion = getMinimumVersionForPartialOutput(meta);
definitionMap.set('minVersion', o.literal(minVersion));
definitionMap.set('version', o.literal('0.0.0-PLACEHOLDER'));
// e.g. `type: MyDirective`
definitionMap.set('type', meta.type.value);
if (meta.isStandalone !== undefined) {
definitionMap.set('isStandalone', o.literal(meta.isStandalone));
}
if (meta.isSignal) {
definitionMap.set('isSignal', o.literal(meta.isSignal));
}
// e.g. `selector: 'some-dir'`
if (meta.selector !== null) {
definitionMap.set('selector', o.literal(meta.selector));
}
definitionMap.set(
'inputs',
needsNewInputPartialOutput(meta)
? createInputsPartialMetadata(meta.inputs)
: legacyInputsPartialMetadata(meta.inputs),
);
definitionMap.set('outputs', conditionallyCreateDirectiveBindingLiteral(meta.outputs));
definitionMap.set('host', compileHostMetadata(meta.host));
definitionMap.set('providers', meta.providers);
if (meta.queries.length > 0) {
definitionMap.set('queries', o.literalArr(meta.queries.map(compileQuery)));
}
if (meta.viewQueries.length > 0) {
definitionMap.set('viewQueries', o.literalArr(meta.viewQueries.map(compileQuery)));
}
if (meta.exportAs !== null) {
definitionMap.set('exportAs', asLiteral(meta.exportAs));
}
if (meta.usesInheritance) {
definitionMap.set('usesInheritance', o.literal(true));
}
if (meta.lifecycle.usesOnChanges) {
definitionMap.set('usesOnChanges', o.literal(true));
}
if (meta.hostDirectives?.length) {
definitionMap.set('hostDirectives', createHostDirectives(meta.hostDirectives));
}
definitionMap.set('ngImport', o.importExpr(R3.core));
return definitionMap;
}
/**
* Determines the minimum linker version for the partial output
* generated for this directive.
*
* Every time we make a breaking change to the declaration interface or partial-linker
* behavior, we must update the minimum versions to prevent old partial-linkers from
* incorrectly processing the declaration.
*
* NOTE: Do not include any prerelease in these versions as they are ignored.
*/
function getMinimumVersionForPartialOutput(meta: R3DirectiveMetadata): string {
// We are starting with the oldest minimum version that can work for common
// directive partial compilation output. As we discover usages of new features
// that require a newer partial output emit, we bump the `minVersion`. Our goal
// is to keep libraries as much compatible with older linker versions as possible.
let minVersion = '14.0.0';
// Note: in order to allow consuming Angular libraries that have been compiled with 16.1+ in
// Angular 16.0, we only force a minimum version of 16.1 if input transform feature as introduced
// in 16.1 is actually used.
const hasDecoratorTransformFunctions = Object.values(meta.inputs).some(
(input) => input.transformFunction !== null,
);
if (hasDecoratorTransformFunctions) {
minVersion = '16.1.0';
}
// If there are input flags and we need the new emit, use the actual minimum version,
// where this was introduced. i.e. in 17.1.0
// TODO(legacy-partial-output-inputs): Remove in v18.
if (needsNewInputPartialOutput(meta)) {
minVersion = '17.1.0';
}
// If there are signal-based queries, partial output generates an extra field
// that should be parsed by linkers. Ensure a proper minimum linker version.
if (meta.queries.some((q) => q.isSignal) || meta.viewQueries.some((q) => q.isSignal)) {
minVersion = '17.2.0';
}
return minVersion;
}
/**
* Gets whether the given directive needs the new input partial output structure
* that can hold additional metadata like `isRequired`, `isSignal` etc.
*/
function needsNewInputPartialOutput(meta: R3DirectiveMetadata): boolean {
return Object.values(meta.inputs).some((input) => input.isSignal);
}
/**
* Compiles the metadata of a single query into its partial declaration form as declared
* by `R3DeclareQueryMetadata`.
*/
function compileQuery(query: R3QueryMetadata): o.LiteralMapExpr {
const meta = new DefinitionMap<R3DeclareQueryMetadata>();
meta.set('propertyName', o.literal(query.propertyName));
if (query.first) {
meta.set('first', o.literal(true));
}
meta.set(
'predicate',
Array.isArray(query.predicate)
? asLiteral(query.predicate)
: convertFromMaybeForwardRefExpression(query.predicate),
);
if (!query.emitDistinctChangesOnly) {
// `emitDistinctChangesOnly` is special because we expect it to be `true`.
// Therefore we explicitly emit the field, and explicitly place it only when it's `false`.
meta.set('emitDistinctChangesOnly', o.literal(false));
} else {
// The linker will assume that an absent `emitDistinctChangesOnly` flag is by default `true`.
}
if (query.descendants) {
meta.set('descendants', o.literal(true));
}
meta.set('read', query.read);
if (query.static) {
meta.set('static', o.literal(true));
}
if (query.isSignal) {
meta.set('isSignal', o.literal(true));
}
return meta.toLiteralMap();
}
/**
* Compiles the host metadata into its partial declaration form as declared
* in `R3DeclareDirectiveMetadata['host']`
*/
function compileHostMetadata(meta: R3HostMetadata): o.LiteralMapExpr | null {
const hostMetadata = new DefinitionMap<NonNullable<R3DeclareDirectiveMetadata['host']>>();
hostMetadata.set(
'attributes',
toOptionalLiteralMap(meta.attributes, (expression) => expression),
);
hostMetadata.set('listeners', toOptionalLiteralMap(meta.listeners, o.literal));
hostMetadata.set('properties', toOptionalLiteralMap(meta.properties, o.literal));
if (meta.specialAttributes.styleAttr) {
hostMetadata.set('styleAttribute', o.literal(meta.specialAttributes.styleAttr));
}
if (meta.specialAttributes.classAttr) {
hostMetadata.set('classAttribute', o.literal(meta.specialAttributes.classAttr));
}
if (hostMetadata.values.length > 0) {
return hostMetadata.toLiteralMap();
} else {
return null;
}
} | {
"end_byte": 7690,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/partial/directive.ts"
} |
angular/packages/compiler/src/render3/partial/directive.ts_7692_11763 | function createHostDirectives(
hostDirectives: NonNullable<R3DirectiveMetadata['hostDirectives']>,
): o.LiteralArrayExpr {
const expressions = hostDirectives.map((current) => {
const keys = [
{
key: 'directive',
value: current.isForwardReference
? generateForwardRef(current.directive.type)
: current.directive.type,
quoted: false,
},
];
const inputsLiteral = current.inputs ? createHostDirectivesMappingArray(current.inputs) : null;
const outputsLiteral = current.outputs
? createHostDirectivesMappingArray(current.outputs)
: null;
if (inputsLiteral) {
keys.push({key: 'inputs', value: inputsLiteral, quoted: false});
}
if (outputsLiteral) {
keys.push({key: 'outputs', value: outputsLiteral, quoted: false});
}
return o.literalMap(keys);
});
// If there's a forward reference, we generate a `function() { return [{directive: HostDir}] }`,
// otherwise we can save some bytes by using a plain array, e.g. `[{directive: HostDir}]`.
return o.literalArr(expressions);
}
/**
* Generates partial output metadata for inputs of a directive.
*
* The generated structure is expected to match `R3DeclareDirectiveFacade['inputs']`.
*/
function createInputsPartialMetadata(inputs: R3DirectiveMetadata['inputs']): o.Expression | null {
const keys = Object.getOwnPropertyNames(inputs);
if (keys.length === 0) {
return null;
}
return o.literalMap(
keys.map((declaredName) => {
const value = inputs[declaredName];
return {
key: declaredName,
// put quotes around keys that contain potentially unsafe characters
quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(declaredName),
value: o.literalMap([
{key: 'classPropertyName', quoted: false, value: asLiteral(value.classPropertyName)},
{key: 'publicName', quoted: false, value: asLiteral(value.bindingPropertyName)},
{key: 'isSignal', quoted: false, value: asLiteral(value.isSignal)},
{key: 'isRequired', quoted: false, value: asLiteral(value.required)},
{key: 'transformFunction', quoted: false, value: value.transformFunction ?? o.NULL_EXPR},
]),
};
}),
);
}
/**
* Pre v18 legacy partial output for inputs.
*
* Previously, inputs did not capture metadata like `isSignal` in the partial compilation output.
* To enable capturing such metadata, we restructured how input metadata is communicated in the
* partial output. This would make libraries incompatible with older Angular FW versions where the
* linker would not know how to handle this new "format". For this reason, if we know this metadata
* does not need to be captured- we fall back to the old format. This is what this function
* generates.
*
* See:
* https://github.com/angular/angular/blob/d4b423690210872b5c32a322a6090beda30b05a3/packages/core/src/compiler/compiler_facade_interface.ts#L197-L199
*/
function legacyInputsPartialMetadata(inputs: R3DirectiveMetadata['inputs']): o.Expression | null {
// TODO(legacy-partial-output-inputs): Remove function in v18.
const keys = Object.getOwnPropertyNames(inputs);
if (keys.length === 0) {
return null;
}
return o.literalMap(
keys.map((declaredName) => {
const value = inputs[declaredName];
const publicName = value.bindingPropertyName;
const differentDeclaringName = publicName !== declaredName;
let result: o.Expression;
if (differentDeclaringName || value.transformFunction !== null) {
const values = [asLiteral(publicName), asLiteral(declaredName)];
if (value.transformFunction !== null) {
values.push(value.transformFunction);
}
result = o.literalArr(values);
} else {
result = asLiteral(publicName);
}
return {
key: declaredName,
// put quotes around keys that contain potentially unsafe characters
quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(declaredName),
value: result,
};
}),
);
} | {
"end_byte": 11763,
"start_byte": 7692,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/partial/directive.ts"
} |
angular/packages/compiler/src/render3/partial/api.ts_0_8228 | /**
* @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.dev/license
*/
import {ChangeDetectionStrategy, ViewEncapsulation} from '../../core';
import * as o from '../../output/output_ast';
export interface R3PartialDeclaration {
/**
* The minimum version of the compiler that can process this partial declaration.
*/
minVersion: string;
/**
* Version number of the Angular compiler that was used to compile this declaration. The linker
* will be able to detect which version a library is using and interpret its metadata accordingly.
*/
version: string;
/**
* A reference to the `@angular/core` ES module, which allows access
* to all Angular exports, including Ivy instructions.
*/
ngImport: o.Expression;
/**
* Reference to the decorated class, which is subject to this partial declaration.
*/
type: o.Expression;
}
// TODO(legacy-partial-output-inputs): Remove in v18.
// https://github.com/angular/angular/blob/d4b423690210872b5c32a322a6090beda30b05a3/packages/core/src/compiler/compiler_facade_interface.ts#L197-L199
export type LegacyInputPartialMapping =
| string
| [bindingPropertyName: string, classPropertyName: string, transformFunction?: o.Expression];
/**
* Describes the shape of the object that the `ɵɵngDeclareDirective()` function accepts.
*/
export interface R3DeclareDirectiveMetadata extends R3PartialDeclaration {
/**
* Unparsed selector of the directive.
*/
selector?: string;
/**
* A mapping of inputs from class property names to binding property names, or to a tuple of
* binding property name and class property name if the names are different.
*/
inputs?: {
[fieldName: string]:
| {
classPropertyName: string;
publicName: string;
isSignal: boolean;
isRequired: boolean;
transformFunction: o.Expression | null;
}
| LegacyInputPartialMapping;
};
/**
* A mapping of outputs from class property names to binding property names.
*/
outputs?: {[classPropertyName: string]: string};
/**
* Information about host bindings present on the component.
*/
host?: {
/**
* A mapping of attribute names to their value expression.
*/
attributes?: {[key: string]: o.Expression};
/**
* A mapping of event names to their unparsed event handler expression.
*/
listeners: {[key: string]: string};
/**
* A mapping of bound properties to their unparsed binding expression.
*/
properties?: {[key: string]: string};
/**
* The value of the class attribute, if present. This is stored outside of `attributes` as its
* string value must be known statically.
*/
classAttribute?: string;
/**
* The value of the style attribute, if present. This is stored outside of `attributes` as its
* string value must be known statically.
*/
styleAttribute?: string;
};
/**
* Information about the content queries made by the directive.
*/
queries?: R3DeclareQueryMetadata[];
/**
* Information about the view queries made by the directive.
*/
viewQueries?: R3DeclareQueryMetadata[];
/**
* The list of providers provided by the directive.
*/
providers?: o.Expression;
/**
* The names by which the directive is exported.
*/
exportAs?: string[];
/**
* Whether the directive has an inheritance clause. Defaults to false.
*/
usesInheritance?: boolean;
/**
* Whether the directive implements the `ngOnChanges` hook. Defaults to false.
*/
usesOnChanges?: boolean;
/**
* Whether the directive is standalone. Defaults to false.
*/
isStandalone?: boolean;
/**
* Whether the directive is a signal-based directive. Defaults to false.
*/
isSignal?: boolean;
/**
* Additional directives applied to the directive host.
*/
hostDirectives?: R3DeclareHostDirectiveMetadata[];
}
/**
* Describes the shape of the object that the `ɵɵngDeclareComponent()` function accepts.
*/
export interface R3DeclareComponentMetadata extends R3DeclareDirectiveMetadata {
/**
* The component's unparsed template string as opaque expression. The template is represented
* using either a string literal or template literal without substitutions, but its value is
* not read directly. Instead, the template parser is given the full source file's text and
* the range of this expression to parse directly from source.
*/
template: o.Expression;
/**
* Whether the template was inline (using `template`) or external (using `templateUrl`).
* Defaults to false.
*/
isInline?: boolean;
/**
* CSS from inline styles and included styleUrls.
*/
styles?: string[];
/**
* List of components which matched in the template, including sufficient
* metadata for each directive to attribute bindings and references within
* the template to each directive specifically, if the runtime instructions
* support this.
*/
components?: R3DeclareDirectiveDependencyMetadata[];
/**
* List of directives which matched in the template, including sufficient
* metadata for each directive to attribute bindings and references within
* the template to each directive specifically, if the runtime instructions
* support this.
*/
directives?: R3DeclareDirectiveDependencyMetadata[];
/**
* List of dependencies which matched in the template, including sufficient
* metadata for each directive/pipe to attribute bindings and references within
* the template to each directive specifically, if the runtime instructions
* support this.
*/
dependencies?: R3DeclareTemplateDependencyMetadata[];
/**
* List of defer block dependency functions, ordered by the appearance
* of the corresponding deferred block in the template.
*/
deferBlockDependencies?: o.Expression[];
/**
* A map of pipe names to an expression referencing the pipe type (possibly a forward reference
* wrapped in a `forwardRef` invocation) which are used in the template.
*/
pipes?: {[pipeName: string]: o.Expression | (() => o.Expression)};
/**
* The list of view providers defined in the component.
*/
viewProviders?: o.Expression;
/**
* A collection of animation triggers that will be used in the component template.
*/
animations?: o.Expression;
/**
* Strategy used for detecting changes in the component.
* Defaults to `ChangeDetectionStrategy.Default`.
*/
changeDetection?: ChangeDetectionStrategy;
/**
* An encapsulation policy for the component's styling.
* Defaults to `ViewEncapsulation.Emulated`.
*/
encapsulation?: ViewEncapsulation;
/**
* Overrides the default interpolation start and end delimiters. Defaults to {{ and }}.
*/
interpolation?: [string, string];
/**
* Whether whitespace in the template should be preserved. Defaults to false.
*/
preserveWhitespaces?: boolean;
}
export type R3DeclareTemplateDependencyMetadata =
| R3DeclareDirectiveDependencyMetadata
| R3DeclarePipeDependencyMetadata
| R3DeclareNgModuleDependencyMetadata;
export interface R3DeclareDirectiveDependencyMetadata {
kind: 'directive' | 'component';
/**
* Selector of the directive.
*/
selector: string;
/**
* Reference to the directive class (possibly a forward reference wrapped in a `forwardRef`
* invocation).
*/
type: o.Expression | (() => o.Expression);
/**
* Property names of the directive's inputs.
*/
inputs?: string[];
/**
* Event names of the directive's outputs.
*/
outputs?: string[];
/**
* Names by which this directive exports itself for references.
*/
exportAs?: string[];
}
export interface R3DeclarePipeDependencyMetadata {
kind: 'pipe';
name: string;
/**
* Reference to the pipe class (possibly a forward reference wrapped in a `forwardRef`
* invocation).
*/
type: o.Expression | (() => o.Expression);
}
export interface R3DeclareNgModuleDependencyMetadata {
kind: 'ngmodule';
type: o.Expression | (() => o.Expression);
}
ex | {
"end_byte": 8228,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/partial/api.ts"
} |
angular/packages/compiler/src/render3/partial/api.ts_8230_16887 | rt interface R3DeclareQueryMetadata {
/**
* Name of the property on the class to update with query results.
*/
propertyName: string;
/**
* Whether to read only the first matching result, or an array of results. Defaults to false.
*/
first?: boolean;
/**
* Either an expression representing a type (possibly wrapped in a `forwardRef()`) or
* `InjectionToken` for the query predicate, or a set of string selectors.
*/
predicate: o.Expression | string[];
/**
* Whether to include only direct children or all descendants. Defaults to false.
*/
descendants?: boolean;
/**
* True to only fire changes if there are underlying changes to the query.
*/
emitDistinctChangesOnly?: boolean;
/**
* An expression representing a type to read from each matched node, or null if the default value
* for a given node is to be returned.
*/
read?: o.Expression;
/**
* Whether or not this query should collect only static results. Defaults to false.
*
* If static is true, the query's results will be set on the component after nodes are created,
* but before change detection runs. This means that any results that relied upon change detection
* to run (e.g. results inside *ngIf or *ngFor views) will not be collected. Query results are
* available in the ngOnInit hook.
*
* If static is false, the query's results will be set on the component after change detection
* runs. This means that the query results can contain nodes inside *ngIf or *ngFor views, but
* the results will not be available in the ngOnInit hook (only in the ngAfterContentInit for
* content hooks and ngAfterViewInit for view hooks).
*/
static?: boolean;
/** Whether the query is signal-based. */
isSignal: boolean;
}
/**
* Describes the shape of the objects that the `ɵɵngDeclareNgModule()` accepts.
*/
export interface R3DeclareNgModuleMetadata extends R3PartialDeclaration {
/**
* An array of expressions representing the bootstrap components specified by the module.
*/
bootstrap?: o.Expression[];
/**
* An array of expressions representing the directives and pipes declared by the module.
*/
declarations?: o.Expression[];
/**
* An array of expressions representing the imports of the module.
*/
imports?: o.Expression[];
/**
* An array of expressions representing the exports of the module.
*/
exports?: o.Expression[];
/**
* The set of schemas that declare elements to be allowed in the NgModule.
*/
schemas?: o.Expression[];
/** Unique ID or expression representing the unique ID of an NgModule. */
id?: o.Expression;
}
/**
* Describes the shape of the objects that the `ɵɵngDeclareInjector()` accepts.
*/
export interface R3DeclareInjectorMetadata extends R3PartialDeclaration {
/**
* The list of providers provided by the injector.
*/
providers?: o.Expression;
/**
* The list of imports into the injector.
*/
imports?: o.Expression[];
}
/**
* Describes the shape of the object that the `ɵɵngDeclarePipe()` function accepts.
*
* This interface serves primarily as documentation, as conformance to this interface is not
* enforced during linking.
*/
export interface R3DeclarePipeMetadata extends R3PartialDeclaration {
/**
* The name to use in templates to refer to this pipe.
*/
name: string;
/**
* Whether this pipe is "pure".
*
* A pure pipe's `transform()` method is only invoked when its input arguments change.
*
* Default: true.
*/
pure?: boolean;
/**
* Whether the pipe is standalone.
*
* Default: false.
*/
isStandalone?: boolean;
}
/**
* Describes the shape of the object that the `ɵɵngDeclareFactory()` function accepts.
*
* This interface serves primarily as documentation, as conformance to this interface is not
* enforced during linking.
*/
export interface R3DeclareFactoryMetadata extends R3PartialDeclaration {
/**
* A collection of dependencies that this factory relies upon.
*
* If this is `null`, then the type's constructor is nonexistent and will be inherited from an
* ancestor of the type.
*
* If this is `'invalid'`, then one or more of the parameters wasn't resolvable and any attempt to
* use these deps will result in a runtime error.
*/
deps: R3DeclareDependencyMetadata[] | 'invalid' | null;
/**
* Type of the target being created by the factory.
*/
target: FactoryTarget;
}
export enum FactoryTarget {
Directive = 0,
Component = 1,
Injectable = 2,
Pipe = 3,
NgModule = 4,
}
/**
* Describes the shape of the object that the `ɵɵngDeclareInjectable()` function accepts.
*
* This interface serves primarily as documentation, as conformance to this interface is not
* enforced during linking.
*/
export interface R3DeclareInjectableMetadata extends R3PartialDeclaration {
/**
* If provided, specifies that the declared injectable belongs to a particular injector:
* - `InjectorType` such as `NgModule`,
* - `'root'` the root injector
* - `'any'` all injectors.
* If not provided, then it does not belong to any injector. Must be explicitly listed in the
* providers of an injector.
*/
providedIn?: o.Expression;
/**
* If provided, an expression that evaluates to a class to use when creating an instance of this
* injectable.
*/
useClass?: o.Expression;
/**
* If provided, an expression that evaluates to a function to use when creating an instance of
* this injectable.
*/
useFactory?: o.Expression;
/**
* If provided, an expression that evaluates to a token of another injectable that this injectable
* aliases.
*/
useExisting?: o.Expression;
/**
* If provided, an expression that evaluates to the value of the instance of this injectable.
*/
useValue?: o.Expression;
/**
* An array of dependencies to support instantiating this injectable via `useClass` or
* `useFactory`.
*/
deps?: R3DeclareDependencyMetadata[];
}
/**
* Metadata indicating how a dependency should be injected into a factory.
*/
export interface R3DeclareDependencyMetadata {
/**
* An expression representing the token or value to be injected, or `null` if the dependency is
* not valid.
*
* If this dependency is due to the `@Attribute()` decorator, then this is an expression
* evaluating to the name of the attribute.
*/
token: o.Expression | null;
/**
* Whether the dependency is injecting an attribute value.
* Default: false.
*/
attribute?: boolean;
/**
* Whether the dependency has an @Host qualifier.
* Default: false,
*/
host?: boolean;
/**
* Whether the dependency has an @Optional qualifier.
* Default: false,
*/
optional?: boolean;
/**
* Whether the dependency has an @Self qualifier.
* Default: false,
*/
self?: boolean;
/**
* Whether the dependency has an @SkipSelf qualifier.
* Default: false,
*/
skipSelf?: boolean;
}
/**
* Describes the shape of the object that the `ɵɵngDeclareClassMetadata()` function accepts.
*
* This interface serves primarily as documentation, as conformance to this interface is not
* enforced during linking.
*/
export interface R3DeclareClassMetadata extends R3PartialDeclaration {
/**
* The Angular decorators of the class.
*/
decorators: o.Expression;
/**
* Optionally specifies the constructor parameters, their types and the Angular decorators of each
* parameter. This property is omitted if the class does not have a constructor.
*/
ctorParameters?: o.Expression;
/**
* Optionally specifies the Angular decorators applied to the class properties. This property is
* omitted if no properties have any decorators.
*/
propDecorators?: o.Expression;
}
/**
* Describes the shape of the object that the `ɵɵngDeclareClassMetadataAsync()` function accepts.
*
* This interface serves primarily as documentation, as conformance to this interface is not
* enforced during linking.
*/
export interface R3DeclareClassMetadataAsync extends R3PartialDeclaration {
/** Function that loads the deferred dependencies associated with the component. */
resolveDeferredDeps: o.Expression;
/**
* Function that, when invoked with the resolved deferred
* dependencies, will return the class metadata.
*/
resolveMetadata: o.Expression;
}
/**
* Describes the shape of the object literal that can be
* passed in as a part of the `hostDirectives` array.
*/
export interface R3DeclareHostDirectiveMetadata {
directive: o.Expression;
inputs?: string[];
outputs?: string[];
}
| {
"end_byte": 16887,
"start_byte": 8230,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/partial/api.ts"
} |
angular/packages/compiler/src/render3/partial/factory.ts_0_1639 | /**
* @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.dev/license
*/
import * as o from '../../output/output_ast';
import {createFactoryType, FactoryTarget, R3FactoryMetadata} from '../r3_factory';
import {Identifiers as R3} from '../r3_identifiers';
import {R3CompiledExpression} from '../util';
import {DefinitionMap} from '../view/util';
import {R3DeclareFactoryMetadata} from './api';
import {compileDependencies} from './util';
/**
* Every time we make a breaking change to the declaration interface or partial-linker behavior, we
* must update this constant to prevent old partial-linkers from incorrectly processing the
* declaration.
*
* Do not include any prerelease in these versions as they are ignored.
*/
const MINIMUM_PARTIAL_LINKER_VERSION = '12.0.0';
export function compileDeclareFactoryFunction(meta: R3FactoryMetadata): R3CompiledExpression {
const definitionMap = new DefinitionMap<R3DeclareFactoryMetadata>();
definitionMap.set('minVersion', o.literal(MINIMUM_PARTIAL_LINKER_VERSION));
definitionMap.set('version', o.literal('0.0.0-PLACEHOLDER'));
definitionMap.set('ngImport', o.importExpr(R3.core));
definitionMap.set('type', meta.type.value);
definitionMap.set('deps', compileDependencies(meta.deps));
definitionMap.set('target', o.importExpr(R3.FactoryTarget).prop(FactoryTarget[meta.target]));
return {
expression: o.importExpr(R3.declareFactory).callFn([definitionMap.toLiteralMap()]),
statements: [],
type: createFactoryType(meta),
};
}
| {
"end_byte": 1639,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/partial/factory.ts"
} |
angular/packages/compiler/src/render3/partial/injector.ts_0_1897 | /**
* @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.dev/license
*/
import * as o from '../../output/output_ast';
import {Identifiers as R3} from '../r3_identifiers';
import {createInjectorType, R3InjectorMetadata} from '../r3_injector_compiler';
import {R3CompiledExpression} from '../util';
import {DefinitionMap} from '../view/util';
import {R3DeclareInjectorMetadata} from './api';
/**
* Every time we make a breaking change to the declaration interface or partial-linker behavior, we
* must update this constant to prevent old partial-linkers from incorrectly processing the
* declaration.
*
* Do not include any prerelease in these versions as they are ignored.
*/
const MINIMUM_PARTIAL_LINKER_VERSION = '12.0.0';
export function compileDeclareInjectorFromMetadata(meta: R3InjectorMetadata): R3CompiledExpression {
const definitionMap = createInjectorDefinitionMap(meta);
const expression = o.importExpr(R3.declareInjector).callFn([definitionMap.toLiteralMap()]);
const type = createInjectorType(meta);
return {expression, type, statements: []};
}
/**
* Gathers the declaration fields for an Injector into a `DefinitionMap`.
*/
function createInjectorDefinitionMap(
meta: R3InjectorMetadata,
): DefinitionMap<R3DeclareInjectorMetadata> {
const definitionMap = new DefinitionMap<R3DeclareInjectorMetadata>();
definitionMap.set('minVersion', o.literal(MINIMUM_PARTIAL_LINKER_VERSION));
definitionMap.set('version', o.literal('0.0.0-PLACEHOLDER'));
definitionMap.set('ngImport', o.importExpr(R3.core));
definitionMap.set('type', meta.type.value);
definitionMap.set('providers', meta.providers);
if (meta.imports.length > 0) {
definitionMap.set('imports', o.literalArr(meta.imports));
}
return definitionMap;
}
| {
"end_byte": 1897,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/partial/injector.ts"
} |
angular/packages/compiler/src/render3/partial/util.ts_0_3073 | /**
* @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.dev/license
*/
import * as o from '../../output/output_ast';
import {R3DependencyMetadata} from '../r3_factory';
import {DefinitionMap} from '../view/util';
import {R3DeclareDependencyMetadata} from './api';
/**
* Creates an array literal expression from the given array, mapping all values to an expression
* using the provided mapping function. If the array is empty or null, then null is returned.
*
* @param values The array to transfer into literal array expression.
* @param mapper The logic to use for creating an expression for the array's values.
* @returns An array literal expression representing `values`, or null if `values` is empty or
* is itself null.
*/
export function toOptionalLiteralArray<T>(
values: T[] | null,
mapper: (value: T) => o.Expression,
): o.LiteralArrayExpr | null {
if (values === null || values.length === 0) {
return null;
}
return o.literalArr(values.map((value) => mapper(value)));
}
/**
* Creates an object literal expression from the given object, mapping all values to an expression
* using the provided mapping function. If the object has no keys, then null is returned.
*
* @param object The object to transfer into an object literal expression.
* @param mapper The logic to use for creating an expression for the object's values.
* @returns An object literal expression representing `object`, or null if `object` does not have
* any keys.
*/
export function toOptionalLiteralMap<T>(
object: {[key: string]: T},
mapper: (value: T) => o.Expression,
): o.LiteralMapExpr | null {
const entries = Object.keys(object).map((key) => {
const value = object[key];
return {key, value: mapper(value), quoted: true};
});
if (entries.length > 0) {
return o.literalMap(entries);
} else {
return null;
}
}
export function compileDependencies(
deps: R3DependencyMetadata[] | 'invalid' | null,
): o.LiteralExpr | o.LiteralArrayExpr {
if (deps === 'invalid') {
// The `deps` can be set to the string "invalid" by the `unwrapConstructorDependencies()`
// function, which tries to convert `ConstructorDeps` into `R3DependencyMetadata[]`.
return o.literal('invalid');
} else if (deps === null) {
return o.literal(null);
} else {
return o.literalArr(deps.map(compileDependency));
}
}
export function compileDependency(dep: R3DependencyMetadata): o.LiteralMapExpr {
const depMeta = new DefinitionMap<R3DeclareDependencyMetadata>();
depMeta.set('token', dep.token);
if (dep.attributeNameType !== null) {
depMeta.set('attribute', o.literal(true));
}
if (dep.host) {
depMeta.set('host', o.literal(true));
}
if (dep.optional) {
depMeta.set('optional', o.literal(true));
}
if (dep.self) {
depMeta.set('self', o.literal(true));
}
if (dep.skipSelf) {
depMeta.set('skipSelf', o.literal(true));
}
return depMeta.toLiteralMap();
}
| {
"end_byte": 3073,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/partial/util.ts"
} |
angular/packages/compiler/src/render3/partial/injectable.ts_0_3108 | /**
* @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.dev/license
*/
import {createInjectableType, R3InjectableMetadata} from '../../injectable_compiler_2';
import * as o from '../../output/output_ast';
import {Identifiers as R3} from '../r3_identifiers';
import {convertFromMaybeForwardRefExpression, R3CompiledExpression} from '../util';
import {DefinitionMap} from '../view/util';
import {R3DeclareInjectableMetadata} from './api';
import {compileDependency} from './util';
/**
* Every time we make a breaking change to the declaration interface or partial-linker behavior, we
* must update this constant to prevent old partial-linkers from incorrectly processing the
* declaration.
*
* Do not include any prerelease in these versions as they are ignored.
*/
const MINIMUM_PARTIAL_LINKER_VERSION = '12.0.0';
/**
* Compile a Injectable declaration defined by the `R3InjectableMetadata`.
*/
export function compileDeclareInjectableFromMetadata(
meta: R3InjectableMetadata,
): R3CompiledExpression {
const definitionMap = createInjectableDefinitionMap(meta);
const expression = o.importExpr(R3.declareInjectable).callFn([definitionMap.toLiteralMap()]);
const type = createInjectableType(meta);
return {expression, type, statements: []};
}
/**
* Gathers the declaration fields for a Injectable into a `DefinitionMap`.
*/
export function createInjectableDefinitionMap(
meta: R3InjectableMetadata,
): DefinitionMap<R3DeclareInjectableMetadata> {
const definitionMap = new DefinitionMap<R3DeclareInjectableMetadata>();
definitionMap.set('minVersion', o.literal(MINIMUM_PARTIAL_LINKER_VERSION));
definitionMap.set('version', o.literal('0.0.0-PLACEHOLDER'));
definitionMap.set('ngImport', o.importExpr(R3.core));
definitionMap.set('type', meta.type.value);
// Only generate providedIn property if it has a non-null value
if (meta.providedIn !== undefined) {
const providedIn = convertFromMaybeForwardRefExpression(meta.providedIn);
if ((providedIn as o.LiteralExpr).value !== null) {
definitionMap.set('providedIn', providedIn);
}
}
if (meta.useClass !== undefined) {
definitionMap.set('useClass', convertFromMaybeForwardRefExpression(meta.useClass));
}
if (meta.useExisting !== undefined) {
definitionMap.set('useExisting', convertFromMaybeForwardRefExpression(meta.useExisting));
}
if (meta.useValue !== undefined) {
definitionMap.set('useValue', convertFromMaybeForwardRefExpression(meta.useValue));
}
// Factories do not contain `ForwardRef`s since any types are already wrapped in a function call
// so the types will not be eagerly evaluated. Therefore we do not need to process this expression
// with `convertFromProviderExpression()`.
if (meta.useFactory !== undefined) {
definitionMap.set('useFactory', meta.useFactory);
}
if (meta.deps !== undefined) {
definitionMap.set('deps', o.literalArr(meta.deps.map(compileDependency)));
}
return definitionMap;
}
| {
"end_byte": 3108,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/partial/injectable.ts"
} |
angular/packages/compiler/src/render3/view/t2_binder.ts_0_6299 | /**
* @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.dev/license
*/
import {
AST,
BindingPipe,
ImplicitReceiver,
PropertyRead,
PropertyWrite,
RecursiveAstVisitor,
SafePropertyRead,
ThisReceiver,
} from '../../expression_parser/ast';
import {CssSelector, SelectorMatcher} from '../../selector';
import {
BoundAttribute,
BoundEvent,
BoundText,
Comment,
Content,
DeferredBlock,
DeferredBlockError,
DeferredBlockLoading,
DeferredBlockPlaceholder,
DeferredTrigger,
Element,
ForLoopBlock,
ForLoopBlockEmpty,
HoverDeferredTrigger,
Icu,
IfBlock,
IfBlockBranch,
InteractionDeferredTrigger,
LetDeclaration,
Node,
Reference,
SwitchBlock,
SwitchBlockCase,
Template,
Text,
TextAttribute,
UnknownBlock,
Variable,
ViewportDeferredTrigger,
Visitor,
} from '../r3_ast';
import {
BoundTarget,
DirectiveMeta,
ReferenceTarget,
ScopedNode,
Target,
TargetBinder,
TemplateEntity,
} from './t2_api';
import {parseTemplate} from './template';
import {createCssSelectorFromNode} from './util';
/**
* Computes a difference between full list (first argument) and
* list of items that should be excluded from the full list (second
* argument).
*/
function diff(fullList: string[], itemsToExclude: string[]): string[] {
const exclude = new Set(itemsToExclude);
return fullList.filter((item) => !exclude.has(item));
}
/**
* Given a template string and a set of available directive selectors,
* computes a list of matching selectors and splits them into 2 buckets:
* (1) eagerly used in a template and (2) directives used only in defer
* blocks. Similarly, returns 2 lists of pipes (eager and deferrable).
*
* Note: deferrable directives selectors and pipes names used in `@defer`
* blocks are **candidates** and API caller should make sure that:
*
* * A Component where a given template is defined is standalone
* * Underlying dependency classes are also standalone
* * Dependency class symbols are not eagerly used in a TS file
* where a host component (that owns the template) is located
*/
export function findMatchingDirectivesAndPipes(template: string, directiveSelectors: string[]) {
const matcher = new SelectorMatcher<unknown[]>();
for (const selector of directiveSelectors) {
// Create a fake directive instance to account for the logic inside
// of the `R3TargetBinder` class (which invokes the `hasBindingPropertyName`
// function internally).
const fakeDirective = {
selector,
exportAs: null,
inputs: {
hasBindingPropertyName() {
return false;
},
},
outputs: {
hasBindingPropertyName() {
return false;
},
},
};
matcher.addSelectables(CssSelector.parse(selector), [fakeDirective]);
}
const parsedTemplate = parseTemplate(template, '' /* templateUrl */);
const binder = new R3TargetBinder(matcher as any);
const bound = binder.bind({template: parsedTemplate.nodes});
const eagerDirectiveSelectors = bound.getEagerlyUsedDirectives().map((dir) => dir.selector!);
const allMatchedDirectiveSelectors = bound.getUsedDirectives().map((dir) => dir.selector!);
const eagerPipes = bound.getEagerlyUsedPipes();
return {
directives: {
regular: eagerDirectiveSelectors,
deferCandidates: diff(allMatchedDirectiveSelectors, eagerDirectiveSelectors),
},
pipes: {
regular: eagerPipes,
deferCandidates: diff(bound.getUsedPipes(), eagerPipes),
},
};
}
/**
* Processes `Target`s with a given set of directives and performs a binding operation, which
* returns an object similar to TypeScript's `ts.TypeChecker` that contains knowledge about the
* target.
*/
export class R3TargetBinder<DirectiveT extends DirectiveMeta> implements TargetBinder<DirectiveT> {
constructor(private directiveMatcher: SelectorMatcher<DirectiveT[]>) {}
/**
* Perform a binding operation on the given `Target` and return a `BoundTarget` which contains
* metadata about the types referenced in the template.
*/
bind(target: Target): BoundTarget<DirectiveT> {
if (!target.template) {
// TODO(alxhub): handle targets which contain things like HostBindings, etc.
throw new Error('Binding without a template not yet supported');
}
// First, parse the template into a `Scope` structure. This operation captures the syntactic
// scopes in the template and makes them available for later use.
const scope = Scope.apply(target.template);
// Use the `Scope` to extract the entities present at every level of the template.
const scopedNodeEntities = extractScopedNodeEntities(scope);
// Next, perform directive matching on the template using the `DirectiveBinder`. This returns:
// - directives: Map of nodes (elements & ng-templates) to the directives on them.
// - bindings: Map of inputs, outputs, and attributes to the directive/element that claims
// them. TODO(alxhub): handle multiple directives claiming an input/output/etc.
// - references: Map of #references to their targets.
const {directives, eagerDirectives, bindings, references} = DirectiveBinder.apply(
target.template,
this.directiveMatcher,
);
// Finally, run the TemplateBinder to bind references, variables, and other entities within the
// template. This extracts all the metadata that doesn't depend on directive matching.
const {expressions, symbols, nestingLevel, usedPipes, eagerPipes, deferBlocks} =
TemplateBinder.applyWithScope(target.template, scope);
return new R3BoundTarget(
target,
directives,
eagerDirectives,
bindings,
references,
expressions,
symbols,
nestingLevel,
scopedNodeEntities,
usedPipes,
eagerPipes,
deferBlocks,
);
}
}
/**
* Represents a binding scope within a template.
*
* Any variables, references, or other named entities declared within the template will
* be captured and available by name in `namedEntities`. Additionally, child templates will
* be analyzed and have their child `Scope`s available in `childScopes`.
*/ | {
"end_byte": 6299,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/t2_binder.ts"
} |
angular/packages/compiler/src/render3/view/t2_binder.ts_6300_12831 | class Scope implements Visitor {
/**
* Named members of the `Scope`, such as `Reference`s or `Variable`s.
*/
readonly namedEntities = new Map<string, TemplateEntity>();
/**
* Set of elements that belong to this scope.
*/
readonly elementsInScope = new Set<Element>();
/**
* Child `Scope`s for immediately nested `ScopedNode`s.
*/
readonly childScopes = new Map<ScopedNode, Scope>();
/** Whether this scope is deferred or if any of its ancestors are deferred. */
readonly isDeferred: boolean;
private constructor(
readonly parentScope: Scope | null,
readonly rootNode: ScopedNode | null,
) {
this.isDeferred =
parentScope !== null && parentScope.isDeferred ? true : rootNode instanceof DeferredBlock;
}
static newRootScope(): Scope {
return new Scope(null, null);
}
/**
* Process a template (either as a `Template` sub-template with variables, or a plain array of
* template `Node`s) and construct its `Scope`.
*/
static apply(template: Node[]): Scope {
const scope = Scope.newRootScope();
scope.ingest(template);
return scope;
}
/**
* Internal method to process the scoped node and populate the `Scope`.
*/
private ingest(nodeOrNodes: ScopedNode | Node[]): void {
if (nodeOrNodes instanceof Template) {
// Variables on an <ng-template> are defined in the inner scope.
nodeOrNodes.variables.forEach((node) => this.visitVariable(node));
// Process the nodes of the template.
nodeOrNodes.children.forEach((node) => node.visit(this));
} else if (nodeOrNodes instanceof IfBlockBranch) {
if (nodeOrNodes.expressionAlias !== null) {
this.visitVariable(nodeOrNodes.expressionAlias);
}
nodeOrNodes.children.forEach((node) => node.visit(this));
} else if (nodeOrNodes instanceof ForLoopBlock) {
this.visitVariable(nodeOrNodes.item);
nodeOrNodes.contextVariables.forEach((v) => this.visitVariable(v));
nodeOrNodes.children.forEach((node) => node.visit(this));
} else if (
nodeOrNodes instanceof SwitchBlockCase ||
nodeOrNodes instanceof ForLoopBlockEmpty ||
nodeOrNodes instanceof DeferredBlock ||
nodeOrNodes instanceof DeferredBlockError ||
nodeOrNodes instanceof DeferredBlockPlaceholder ||
nodeOrNodes instanceof DeferredBlockLoading ||
nodeOrNodes instanceof Content
) {
nodeOrNodes.children.forEach((node) => node.visit(this));
} else {
// No overarching `Template` instance, so process the nodes directly.
nodeOrNodes.forEach((node) => node.visit(this));
}
}
visitElement(element: Element) {
// `Element`s in the template may have `Reference`s which are captured in the scope.
element.references.forEach((node) => this.visitReference(node));
// Recurse into the `Element`'s children.
element.children.forEach((node) => node.visit(this));
this.elementsInScope.add(element);
}
visitTemplate(template: Template) {
// References on a <ng-template> are defined in the outer scope, so capture them before
// processing the template's child scope.
template.references.forEach((node) => this.visitReference(node));
// Next, create an inner scope and process the template within it.
this.ingestScopedNode(template);
}
visitVariable(variable: Variable) {
// Declare the variable if it's not already.
this.maybeDeclare(variable);
}
visitReference(reference: Reference) {
// Declare the variable if it's not already.
this.maybeDeclare(reference);
}
visitDeferredBlock(deferred: DeferredBlock) {
this.ingestScopedNode(deferred);
deferred.placeholder?.visit(this);
deferred.loading?.visit(this);
deferred.error?.visit(this);
}
visitDeferredBlockPlaceholder(block: DeferredBlockPlaceholder) {
this.ingestScopedNode(block);
}
visitDeferredBlockError(block: DeferredBlockError) {
this.ingestScopedNode(block);
}
visitDeferredBlockLoading(block: DeferredBlockLoading) {
this.ingestScopedNode(block);
}
visitSwitchBlock(block: SwitchBlock) {
block.cases.forEach((node) => node.visit(this));
}
visitSwitchBlockCase(block: SwitchBlockCase) {
this.ingestScopedNode(block);
}
visitForLoopBlock(block: ForLoopBlock) {
this.ingestScopedNode(block);
block.empty?.visit(this);
}
visitForLoopBlockEmpty(block: ForLoopBlockEmpty) {
this.ingestScopedNode(block);
}
visitIfBlock(block: IfBlock) {
block.branches.forEach((node) => node.visit(this));
}
visitIfBlockBranch(block: IfBlockBranch) {
this.ingestScopedNode(block);
}
visitContent(content: Content) {
this.ingestScopedNode(content);
}
visitLetDeclaration(decl: LetDeclaration) {
this.maybeDeclare(decl);
}
// Unused visitors.
visitBoundAttribute(attr: BoundAttribute) {}
visitBoundEvent(event: BoundEvent) {}
visitBoundText(text: BoundText) {}
visitText(text: Text) {}
visitTextAttribute(attr: TextAttribute) {}
visitIcu(icu: Icu) {}
visitDeferredTrigger(trigger: DeferredTrigger) {}
visitUnknownBlock(block: UnknownBlock) {}
private maybeDeclare(thing: TemplateEntity) {
// Declare something with a name, as long as that name isn't taken.
if (!this.namedEntities.has(thing.name)) {
this.namedEntities.set(thing.name, thing);
}
}
/**
* Look up a variable within this `Scope`.
*
* This can recurse into a parent `Scope` if it's available.
*/
lookup(name: string): TemplateEntity | null {
if (this.namedEntities.has(name)) {
// Found in the local scope.
return this.namedEntities.get(name)!;
} else if (this.parentScope !== null) {
// Not in the local scope, but there's a parent scope so check there.
return this.parentScope.lookup(name);
} else {
// At the top level and it wasn't found.
return null;
}
}
/**
* Get the child scope for a `ScopedNode`.
*
* This should always be defined.
*/
getChildScope(node: ScopedNode): Scope {
const res = this.childScopes.get(node);
if (res === undefined) {
throw new Error(`Assertion error: child scope for ${node} not found`);
}
return res;
}
private ingestScopedNode(node: ScopedNode) {
const scope = new Scope(this, node);
scope.ingest(node);
this.childScopes.set(node, scope);
}
}
/**
* Processes a template and matches directives on nodes (elements and templates).
*
* Usually used via the static `apply()` method.
*/ | {
"end_byte": 12831,
"start_byte": 6300,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/t2_binder.ts"
} |
angular/packages/compiler/src/render3/view/t2_binder.ts_12832_21289 | class DirectiveBinder<DirectiveT extends DirectiveMeta> implements Visitor {
// Indicates whether we are visiting elements within a `defer` block
private isInDeferBlock = false;
private constructor(
private matcher: SelectorMatcher<DirectiveT[]>,
private directives: Map<Element | Template, DirectiveT[]>,
private eagerDirectives: DirectiveT[],
private bindings: Map<
BoundAttribute | BoundEvent | TextAttribute,
DirectiveT | Element | Template
>,
private references: Map<
Reference,
{directive: DirectiveT; node: Element | Template} | Element | Template
>,
) {}
/**
* Process a template (list of `Node`s) and perform directive matching against each node.
*
* @param template the list of template `Node`s to match (recursively).
* @param selectorMatcher a `SelectorMatcher` containing the directives that are in scope for
* this template.
* @returns three maps which contain information about directives in the template: the
* `directives` map which lists directives matched on each node, the `bindings` map which
* indicates which directives claimed which bindings (inputs, outputs, etc), and the `references`
* map which resolves #references (`Reference`s) within the template to the named directive or
* template node.
*/
static apply<DirectiveT extends DirectiveMeta>(
template: Node[],
selectorMatcher: SelectorMatcher<DirectiveT[]>,
): {
directives: Map<Element | Template, DirectiveT[]>;
eagerDirectives: DirectiveT[];
bindings: Map<BoundAttribute | BoundEvent | TextAttribute, DirectiveT | Element | Template>;
references: Map<
Reference,
{directive: DirectiveT; node: Element | Template} | Element | Template
>;
} {
const directives = new Map<Element | Template, DirectiveT[]>();
const bindings = new Map<
BoundAttribute | BoundEvent | TextAttribute,
DirectiveT | Element | Template
>();
const references = new Map<
Reference,
{directive: DirectiveT; node: Element | Template} | Element | Template
>();
const eagerDirectives: DirectiveT[] = [];
const matcher = new DirectiveBinder(
selectorMatcher,
directives,
eagerDirectives,
bindings,
references,
);
matcher.ingest(template);
return {directives, eagerDirectives, bindings, references};
}
private ingest(template: Node[]): void {
template.forEach((node) => node.visit(this));
}
visitElement(element: Element): void {
this.visitElementOrTemplate(element);
}
visitTemplate(template: Template): void {
this.visitElementOrTemplate(template);
}
visitElementOrTemplate(node: Element | Template): void {
// First, determine the HTML shape of the node for the purpose of directive matching.
// Do this by building up a `CssSelector` for the node.
const cssSelector = createCssSelectorFromNode(node);
// Next, use the `SelectorMatcher` to get the list of directives on the node.
const directives: DirectiveT[] = [];
this.matcher.match(cssSelector, (_selector, results) => directives.push(...results));
if (directives.length > 0) {
this.directives.set(node, directives);
if (!this.isInDeferBlock) {
this.eagerDirectives.push(...directives);
}
}
// Resolve any references that are created on this node.
node.references.forEach((ref) => {
let dirTarget: DirectiveT | null = null;
// If the reference expression is empty, then it matches the "primary" directive on the node
// (if there is one). Otherwise it matches the host node itself (either an element or
// <ng-template> node).
if (ref.value.trim() === '') {
// This could be a reference to a component if there is one.
dirTarget = directives.find((dir) => dir.isComponent) || null;
} else {
// This should be a reference to a directive exported via exportAs.
dirTarget =
directives.find(
(dir) => dir.exportAs !== null && dir.exportAs.some((value) => value === ref.value),
) || null;
// Check if a matching directive was found.
if (dirTarget === null) {
// No matching directive was found - this reference points to an unknown target. Leave it
// unmapped.
return;
}
}
if (dirTarget !== null) {
// This reference points to a directive.
this.references.set(ref, {directive: dirTarget, node});
} else {
// This reference points to the node itself.
this.references.set(ref, node);
}
});
// Associate attributes/bindings on the node with directives or with the node itself.
type BoundNode = BoundAttribute | BoundEvent | TextAttribute;
const setAttributeBinding = (
attribute: BoundNode,
ioType: keyof Pick<DirectiveMeta, 'inputs' | 'outputs'>,
) => {
const dir = directives.find((dir) => dir[ioType].hasBindingPropertyName(attribute.name));
const binding = dir !== undefined ? dir : node;
this.bindings.set(attribute, binding);
};
// Node inputs (bound attributes) and text attributes can be bound to an
// input on a directive.
node.inputs.forEach((input) => setAttributeBinding(input, 'inputs'));
node.attributes.forEach((attr) => setAttributeBinding(attr, 'inputs'));
if (node instanceof Template) {
node.templateAttrs.forEach((attr) => setAttributeBinding(attr, 'inputs'));
}
// Node outputs (bound events) can be bound to an output on a directive.
node.outputs.forEach((output) => setAttributeBinding(output, 'outputs'));
// Recurse into the node's children.
node.children.forEach((child) => child.visit(this));
}
visitDeferredBlock(deferred: DeferredBlock): void {
const wasInDeferBlock = this.isInDeferBlock;
this.isInDeferBlock = true;
deferred.children.forEach((child) => child.visit(this));
this.isInDeferBlock = wasInDeferBlock;
deferred.placeholder?.visit(this);
deferred.loading?.visit(this);
deferred.error?.visit(this);
}
visitDeferredBlockPlaceholder(block: DeferredBlockPlaceholder): void {
block.children.forEach((child) => child.visit(this));
}
visitDeferredBlockError(block: DeferredBlockError): void {
block.children.forEach((child) => child.visit(this));
}
visitDeferredBlockLoading(block: DeferredBlockLoading): void {
block.children.forEach((child) => child.visit(this));
}
visitSwitchBlock(block: SwitchBlock) {
block.cases.forEach((node) => node.visit(this));
}
visitSwitchBlockCase(block: SwitchBlockCase) {
block.children.forEach((node) => node.visit(this));
}
visitForLoopBlock(block: ForLoopBlock) {
block.item.visit(this);
block.contextVariables.forEach((v) => v.visit(this));
block.children.forEach((node) => node.visit(this));
block.empty?.visit(this);
}
visitForLoopBlockEmpty(block: ForLoopBlockEmpty) {
block.children.forEach((node) => node.visit(this));
}
visitIfBlock(block: IfBlock) {
block.branches.forEach((node) => node.visit(this));
}
visitIfBlockBranch(block: IfBlockBranch) {
block.expressionAlias?.visit(this);
block.children.forEach((node) => node.visit(this));
}
visitContent(content: Content): void {
content.children.forEach((child) => child.visit(this));
}
// Unused visitors.
visitVariable(variable: Variable): void {}
visitReference(reference: Reference): void {}
visitTextAttribute(attribute: TextAttribute): void {}
visitBoundAttribute(attribute: BoundAttribute): void {}
visitBoundEvent(attribute: BoundEvent): void {}
visitBoundAttributeOrEvent(node: BoundAttribute | BoundEvent) {}
visitText(text: Text): void {}
visitBoundText(text: BoundText): void {}
visitIcu(icu: Icu): void {}
visitDeferredTrigger(trigger: DeferredTrigger): void {}
visitUnknownBlock(block: UnknownBlock) {}
visitLetDeclaration(decl: LetDeclaration) {}
}
/**
* Processes a template and extract metadata about expressions and symbols within.
*
* This is a companion to the `DirectiveBinder` that doesn't require knowledge of directives matched
* within the template in order to operate.
*
* Expressions are visited by the superclass `RecursiveAstVisitor`, with custom logic provided
* by overridden methods from that visitor.
*/
class TemplateBinder extends RecursiveAstVisitor implements Visitor | {
"end_byte": 21289,
"start_byte": 12832,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/t2_binder.ts"
} |
angular/packages/compiler/src/render3/view/t2_binder.ts_21290_29865 | {
private visitNode: (node: Node) => void;
private constructor(
private bindings: Map<AST, TemplateEntity>,
private symbols: Map<TemplateEntity, ScopedNode>,
private usedPipes: Set<string>,
private eagerPipes: Set<string>,
private deferBlocks: [DeferredBlock, Scope][],
private nestingLevel: Map<ScopedNode, number>,
private scope: Scope,
private rootNode: ScopedNode | null,
private level: number,
) {
super();
// Save a bit of processing time by constructing this closure in advance.
this.visitNode = (node: Node) => node.visit(this);
}
// This method is defined to reconcile the type of TemplateBinder since both
// RecursiveAstVisitor and Visitor define the visit() method in their
// interfaces.
override visit(node: AST | Node, context?: any) {
if (node instanceof AST) {
node.visit(this, context);
} else {
node.visit(this);
}
}
/**
* Process a template and extract metadata about expressions and symbols within.
*
* @param nodes the nodes of the template to process
* @param scope the `Scope` of the template being processed.
* @returns three maps which contain metadata about the template: `expressions` which interprets
* special `AST` nodes in expressions as pointing to references or variables declared within the
* template, `symbols` which maps those variables and references to the nested `Template` which
* declares them, if any, and `nestingLevel` which associates each `Template` with a integer
* nesting level (how many levels deep within the template structure the `Template` is), starting
* at 1.
*/
static applyWithScope(
nodes: Node[],
scope: Scope,
): {
expressions: Map<AST, TemplateEntity>;
symbols: Map<TemplateEntity, Template>;
nestingLevel: Map<ScopedNode, number>;
usedPipes: Set<string>;
eagerPipes: Set<string>;
deferBlocks: [DeferredBlock, Scope][];
} {
const expressions = new Map<AST, TemplateEntity>();
const symbols = new Map<TemplateEntity, Template>();
const nestingLevel = new Map<ScopedNode, number>();
const usedPipes = new Set<string>();
const eagerPipes = new Set<string>();
const template = nodes instanceof Template ? nodes : null;
const deferBlocks: [DeferredBlock, Scope][] = [];
// The top-level template has nesting level 0.
const binder = new TemplateBinder(
expressions,
symbols,
usedPipes,
eagerPipes,
deferBlocks,
nestingLevel,
scope,
template,
0,
);
binder.ingest(nodes);
return {expressions, symbols, nestingLevel, usedPipes, eagerPipes, deferBlocks};
}
private ingest(nodeOrNodes: ScopedNode | Node[]): void {
if (nodeOrNodes instanceof Template) {
// For <ng-template>s, process only variables and child nodes. Inputs, outputs, templateAttrs,
// and references were all processed in the scope of the containing template.
nodeOrNodes.variables.forEach(this.visitNode);
nodeOrNodes.children.forEach(this.visitNode);
// Set the nesting level.
this.nestingLevel.set(nodeOrNodes, this.level);
} else if (nodeOrNodes instanceof IfBlockBranch) {
if (nodeOrNodes.expressionAlias !== null) {
this.visitNode(nodeOrNodes.expressionAlias);
}
nodeOrNodes.children.forEach(this.visitNode);
this.nestingLevel.set(nodeOrNodes, this.level);
} else if (nodeOrNodes instanceof ForLoopBlock) {
this.visitNode(nodeOrNodes.item);
nodeOrNodes.contextVariables.forEach((v) => this.visitNode(v));
nodeOrNodes.trackBy.visit(this);
nodeOrNodes.children.forEach(this.visitNode);
this.nestingLevel.set(nodeOrNodes, this.level);
} else if (nodeOrNodes instanceof DeferredBlock) {
if (this.scope.rootNode !== nodeOrNodes) {
throw new Error(
`Assertion error: resolved incorrect scope for deferred block ${nodeOrNodes}`,
);
}
this.deferBlocks.push([nodeOrNodes, this.scope]);
nodeOrNodes.children.forEach((node) => node.visit(this));
this.nestingLevel.set(nodeOrNodes, this.level);
} else if (
nodeOrNodes instanceof SwitchBlockCase ||
nodeOrNodes instanceof ForLoopBlockEmpty ||
nodeOrNodes instanceof DeferredBlockError ||
nodeOrNodes instanceof DeferredBlockPlaceholder ||
nodeOrNodes instanceof DeferredBlockLoading ||
nodeOrNodes instanceof Content
) {
nodeOrNodes.children.forEach((node) => node.visit(this));
this.nestingLevel.set(nodeOrNodes, this.level);
} else {
// Visit each node from the top-level template.
nodeOrNodes.forEach(this.visitNode);
}
}
visitElement(element: Element) {
// Visit the inputs, outputs, and children of the element.
element.inputs.forEach(this.visitNode);
element.outputs.forEach(this.visitNode);
element.children.forEach(this.visitNode);
element.references.forEach(this.visitNode);
}
visitTemplate(template: Template) {
// First, visit inputs, outputs and template attributes of the template node.
template.inputs.forEach(this.visitNode);
template.outputs.forEach(this.visitNode);
template.templateAttrs.forEach(this.visitNode);
template.references.forEach(this.visitNode);
// Next, recurse into the template.
this.ingestScopedNode(template);
}
visitVariable(variable: Variable) {
// Register the `Variable` as a symbol in the current `Template`.
if (this.rootNode !== null) {
this.symbols.set(variable, this.rootNode);
}
}
visitReference(reference: Reference) {
// Register the `Reference` as a symbol in the current `Template`.
if (this.rootNode !== null) {
this.symbols.set(reference, this.rootNode);
}
}
// Unused template visitors
visitText(text: Text) {}
visitTextAttribute(attribute: TextAttribute) {}
visitUnknownBlock(block: UnknownBlock) {}
visitDeferredTrigger(): void {}
visitIcu(icu: Icu): void {
Object.keys(icu.vars).forEach((key) => icu.vars[key].visit(this));
Object.keys(icu.placeholders).forEach((key) => icu.placeholders[key].visit(this));
}
// The remaining visitors are concerned with processing AST expressions within template bindings
visitBoundAttribute(attribute: BoundAttribute) {
attribute.value.visit(this);
}
visitBoundEvent(event: BoundEvent) {
event.handler.visit(this);
}
visitDeferredBlock(deferred: DeferredBlock) {
this.ingestScopedNode(deferred);
deferred.triggers.when?.value.visit(this);
deferred.prefetchTriggers.when?.value.visit(this);
deferred.hydrateTriggers.when?.value.visit(this);
deferred.hydrateTriggers.never?.visit(this);
deferred.placeholder && this.visitNode(deferred.placeholder);
deferred.loading && this.visitNode(deferred.loading);
deferred.error && this.visitNode(deferred.error);
}
visitDeferredBlockPlaceholder(block: DeferredBlockPlaceholder) {
this.ingestScopedNode(block);
}
visitDeferredBlockError(block: DeferredBlockError) {
this.ingestScopedNode(block);
}
visitDeferredBlockLoading(block: DeferredBlockLoading) {
this.ingestScopedNode(block);
}
visitSwitchBlock(block: SwitchBlock) {
block.expression.visit(this);
block.cases.forEach(this.visitNode);
}
visitSwitchBlockCase(block: SwitchBlockCase) {
block.expression?.visit(this);
this.ingestScopedNode(block);
}
visitForLoopBlock(block: ForLoopBlock) {
block.expression.visit(this);
this.ingestScopedNode(block);
block.empty?.visit(this);
}
visitForLoopBlockEmpty(block: ForLoopBlockEmpty) {
this.ingestScopedNode(block);
}
visitIfBlock(block: IfBlock) {
block.branches.forEach((node) => node.visit(this));
}
visitIfBlockBranch(block: IfBlockBranch) {
block.expression?.visit(this);
this.ingestScopedNode(block);
}
visitContent(content: Content) {
this.ingestScopedNode(content);
}
visitBoundText(text: BoundText) {
text.value.visit(this);
}
visitLetDeclaration(decl: LetDeclaration) {
decl.value.visit(this);
if (this.rootNode !== null) {
this.symbols.set(decl, this.rootNode);
}
}
override visitPipe(ast: BindingPipe, context: any): any {
this.usedPipes.add(ast.name);
if (!this.scope.isDeferred) {
this.eagerPipes.add(ast.name);
}
return super.visitPipe(ast, context);
}
// These five types of AST expressions can refer to expression roots, which could be variables
// or references in the current scope. | {
"end_byte": 29865,
"start_byte": 21290,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/t2_binder.ts"
} |
angular/packages/compiler/src/render3/view/t2_binder.ts_29869_37737 | override visitPropertyRead(ast: PropertyRead, context: any): any {
this.maybeMap(ast, ast.name);
return super.visitPropertyRead(ast, context);
}
override visitSafePropertyRead(ast: SafePropertyRead, context: any): any {
this.maybeMap(ast, ast.name);
return super.visitSafePropertyRead(ast, context);
}
override visitPropertyWrite(ast: PropertyWrite, context: any): any {
this.maybeMap(ast, ast.name);
return super.visitPropertyWrite(ast, context);
}
private ingestScopedNode(node: ScopedNode) {
const childScope = this.scope.getChildScope(node);
const binder = new TemplateBinder(
this.bindings,
this.symbols,
this.usedPipes,
this.eagerPipes,
this.deferBlocks,
this.nestingLevel,
childScope,
node,
this.level + 1,
);
binder.ingest(node);
}
private maybeMap(ast: PropertyRead | SafePropertyRead | PropertyWrite, name: string): void {
// If the receiver of the expression isn't the `ImplicitReceiver`, this isn't the root of an
// `AST` expression that maps to a `Variable` or `Reference`.
if (!(ast.receiver instanceof ImplicitReceiver) || ast.receiver instanceof ThisReceiver) {
return;
}
// Check whether the name exists in the current scope. If so, map it. Otherwise, the name is
// probably a property on the top-level component context.
const target = this.scope.lookup(name);
if (target !== null) {
this.bindings.set(ast, target);
}
}
}
/**
* Metadata container for a `Target` that allows queries for specific bits of metadata.
*
* See `BoundTarget` for documentation on the individual methods.
*/
export class R3BoundTarget<DirectiveT extends DirectiveMeta> implements BoundTarget<DirectiveT> {
/** Deferred blocks, ordered as they appear in the template. */
private deferredBlocks: DeferredBlock[];
/** Map of deferred blocks to their scope. */
private deferredScopes: Map<DeferredBlock, Scope>;
constructor(
readonly target: Target,
private directives: Map<Element | Template, DirectiveT[]>,
private eagerDirectives: DirectiveT[],
private bindings: Map<
BoundAttribute | BoundEvent | TextAttribute,
DirectiveT | Element | Template
>,
private references: Map<
BoundAttribute | BoundEvent | Reference | TextAttribute,
{directive: DirectiveT; node: Element | Template} | Element | Template
>,
private exprTargets: Map<AST, TemplateEntity>,
private symbols: Map<TemplateEntity, Template>,
private nestingLevel: Map<ScopedNode, number>,
private scopedNodeEntities: Map<ScopedNode | null, ReadonlySet<TemplateEntity>>,
private usedPipes: Set<string>,
private eagerPipes: Set<string>,
rawDeferred: [DeferredBlock, Scope][],
) {
this.deferredBlocks = rawDeferred.map((current) => current[0]);
this.deferredScopes = new Map(rawDeferred);
}
getEntitiesInScope(node: ScopedNode | null): ReadonlySet<TemplateEntity> {
return this.scopedNodeEntities.get(node) ?? new Set();
}
getDirectivesOfNode(node: Element | Template): DirectiveT[] | null {
return this.directives.get(node) || null;
}
getReferenceTarget(ref: Reference): ReferenceTarget<DirectiveT> | null {
return this.references.get(ref) || null;
}
getConsumerOfBinding(
binding: BoundAttribute | BoundEvent | TextAttribute,
): DirectiveT | Element | Template | null {
return this.bindings.get(binding) || null;
}
getExpressionTarget(expr: AST): TemplateEntity | null {
return this.exprTargets.get(expr) || null;
}
getDefinitionNodeOfSymbol(symbol: TemplateEntity): ScopedNode | null {
return this.symbols.get(symbol) || null;
}
getNestingLevel(node: ScopedNode): number {
return this.nestingLevel.get(node) || 0;
}
getUsedDirectives(): DirectiveT[] {
const set = new Set<DirectiveT>();
this.directives.forEach((dirs) => dirs.forEach((dir) => set.add(dir)));
return Array.from(set.values());
}
getEagerlyUsedDirectives(): DirectiveT[] {
const set = new Set<DirectiveT>(this.eagerDirectives);
return Array.from(set.values());
}
getUsedPipes(): string[] {
return Array.from(this.usedPipes);
}
getEagerlyUsedPipes(): string[] {
return Array.from(this.eagerPipes);
}
getDeferBlocks(): DeferredBlock[] {
return this.deferredBlocks;
}
getDeferredTriggerTarget(block: DeferredBlock, trigger: DeferredTrigger): Element | null {
// Only triggers that refer to DOM nodes can be resolved.
if (
!(trigger instanceof InteractionDeferredTrigger) &&
!(trigger instanceof ViewportDeferredTrigger) &&
!(trigger instanceof HoverDeferredTrigger)
) {
return null;
}
const name = trigger.reference;
if (name === null) {
let trigger: Element | null = null;
if (block.placeholder !== null) {
for (const child of block.placeholder.children) {
// Skip over comment nodes. Currently by default the template parser doesn't capture
// comments, but we have a safeguard here just in case since it can be enabled.
if (child instanceof Comment) {
continue;
}
// We can only infer the trigger if there's one root element node. Any other
// nodes at the root make it so that we can't infer the trigger anymore.
if (trigger !== null) {
return null;
}
if (child instanceof Element) {
trigger = child;
}
}
}
return trigger;
}
const outsideRef = this.findEntityInScope(block, name);
// First try to resolve the target in the scope of the main deferred block. Note that we
// skip triggers defined inside the main block itself, because they might not exist yet.
if (outsideRef instanceof Reference && this.getDefinitionNodeOfSymbol(outsideRef) !== block) {
const target = this.getReferenceTarget(outsideRef);
if (target !== null) {
return this.referenceTargetToElement(target);
}
}
// If the trigger couldn't be found in the main block, check the
// placeholder block which is shown before the main block has loaded.
if (block.placeholder !== null) {
const refInPlaceholder = this.findEntityInScope(block.placeholder, name);
const targetInPlaceholder =
refInPlaceholder instanceof Reference ? this.getReferenceTarget(refInPlaceholder) : null;
if (targetInPlaceholder !== null) {
return this.referenceTargetToElement(targetInPlaceholder);
}
}
return null;
}
isDeferred(element: Element): boolean {
for (const block of this.deferredBlocks) {
if (!this.deferredScopes.has(block)) {
continue;
}
const stack: Scope[] = [this.deferredScopes.get(block)!];
while (stack.length > 0) {
const current = stack.pop()!;
if (current.elementsInScope.has(element)) {
return true;
}
stack.push(...current.childScopes.values());
}
}
return false;
}
/**
* Finds an entity with a specific name in a scope.
* @param rootNode Root node of the scope.
* @param name Name of the entity.
*/
private findEntityInScope(rootNode: ScopedNode, name: string): TemplateEntity | null {
const entities = this.getEntitiesInScope(rootNode);
for (const entity of entities) {
if (entity.name === name) {
return entity;
}
}
return null;
}
/** Coerces a `ReferenceTarget` to an `Element`, if possible. */
private referenceTargetToElement(target: ReferenceTarget<DirectiveT>): Element | null {
if (target instanceof Element) {
return target;
}
if (target instanceof Template) {
return null;
}
return this.referenceTargetToElement(target.node);
}
} | {
"end_byte": 37737,
"start_byte": 29869,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/t2_binder.ts"
} |
angular/packages/compiler/src/render3/view/t2_binder.ts_37739_38946 | function extractScopedNodeEntities(rootScope: Scope): Map<ScopedNode | null, Set<TemplateEntity>> {
const entityMap = new Map<ScopedNode | null, Map<string, TemplateEntity>>();
function extractScopeEntities(scope: Scope): Map<string, TemplateEntity> {
if (entityMap.has(scope.rootNode)) {
return entityMap.get(scope.rootNode)!;
}
const currentEntities = scope.namedEntities;
let entities: Map<string, TemplateEntity>;
if (scope.parentScope !== null) {
entities = new Map([...extractScopeEntities(scope.parentScope), ...currentEntities]);
} else {
entities = new Map(currentEntities);
}
entityMap.set(scope.rootNode, entities);
return entities;
}
const scopesToProcess: Scope[] = [rootScope];
while (scopesToProcess.length > 0) {
const scope = scopesToProcess.pop()!;
for (const childScope of scope.childScopes.values()) {
scopesToProcess.push(childScope);
}
extractScopeEntities(scope);
}
const templateEntities = new Map<ScopedNode | null, Set<TemplateEntity>>();
for (const [template, entities] of entityMap) {
templateEntities.set(template, new Set(entities.values()));
}
return templateEntities;
} | {
"end_byte": 38946,
"start_byte": 37739,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/t2_binder.ts"
} |
angular/packages/compiler/src/render3/view/t2_api.ts_0_7584 | /**
* @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.dev/license
*/
import {AST} from '../../expression_parser/ast';
import {
BoundAttribute,
BoundEvent,
Content,
DeferredBlock,
DeferredBlockError,
DeferredBlockLoading,
DeferredBlockPlaceholder,
DeferredTrigger,
Element,
ForLoopBlock,
ForLoopBlockEmpty,
IfBlockBranch,
LetDeclaration,
Node,
Reference,
SwitchBlockCase,
Template,
TextAttribute,
Variable,
} from '../r3_ast';
/** Node that has a `Scope` associated with it. */
export type ScopedNode =
| Template
| SwitchBlockCase
| IfBlockBranch
| ForLoopBlock
| ForLoopBlockEmpty
| DeferredBlock
| DeferredBlockError
| DeferredBlockLoading
| DeferredBlockPlaceholder
| Content;
/** Possible values that a reference can be resolved to. */
export type ReferenceTarget<DirectiveT> =
| {
directive: DirectiveT;
node: Element | Template;
}
| Element
| Template;
/** Entity that is local to the template and defined within the template. */
export type TemplateEntity = Reference | Variable | LetDeclaration;
/*
* t2 is the replacement for the `TemplateDefinitionBuilder`. It handles the operations of
* analyzing Angular templates, extracting semantic info, and ultimately producing a template
* definition function which renders the template using Ivy instructions.
*
* t2 data is also utilized by the template type-checking facilities to understand a template enough
* to generate type-checking code for it.
*/
/**
* A logical target for analysis, which could contain a template or other types of bindings.
*/
export interface Target {
template?: Node[];
}
/**
* A data structure which can indicate whether a given property name is present or not.
*
* This is used to represent the set of inputs or outputs present on a directive, and allows the
* binder to query for the presence of a mapping for property names.
*/
export interface InputOutputPropertySet {
hasBindingPropertyName(propertyName: string): boolean;
}
/**
* A data structure which captures the animation trigger names that are statically resolvable
* and whether some names could not be statically evaluated.
*/
export interface AnimationTriggerNames {
includesDynamicAnimations: boolean;
staticTriggerNames: string[];
}
/**
* Metadata regarding a directive that's needed to match it against template elements. This is
* provided by a consumer of the t2 APIs.
*/
export interface DirectiveMeta {
/**
* Name of the directive class (used for debugging).
*/
name: string;
/** The selector for the directive or `null` if there isn't one. */
selector: string | null;
/**
* Whether the directive is a component.
*/
isComponent: boolean;
/**
* Set of inputs which this directive claims.
*
* Goes from property names to field names.
*/
inputs: InputOutputPropertySet;
/**
* Set of outputs which this directive claims.
*
* Goes from property names to field names.
*/
outputs: InputOutputPropertySet;
/**
* Name under which the directive is exported, if any (exportAs in Angular).
*
* Null otherwise
*/
exportAs: string[] | null;
/**
* Whether the directive is a structural directive (e.g. `<div *ngIf></div>`).
*/
isStructural: boolean;
/**
* If the directive is a component, includes the selectors of its `ng-content` elements.
*/
ngContentSelectors: string[] | null;
/**
* Whether the template of the component preserves whitespaces.
*/
preserveWhitespaces: boolean;
/**
* The name of animations that the user defines in the component.
* Only includes the animation names.
*/
animationTriggerNames: AnimationTriggerNames | null;
}
/**
* Interface to the binding API, which processes a template and returns an object similar to the
* `ts.TypeChecker`.
*
* The returned `BoundTarget` has an API for extracting information about the processed target.
*/
export interface TargetBinder<D extends DirectiveMeta> {
bind(target: Target): BoundTarget<D>;
}
/**
* Result of performing the binding operation against a `Target`.
*
* The original `Target` is accessible, as well as a suite of methods for extracting binding
* information regarding the `Target`.
*
* @param DirectiveT directive metadata type
*/
export interface BoundTarget<DirectiveT extends DirectiveMeta> {
/**
* Get the original `Target` that was bound.
*/
readonly target: Target;
/**
* For a given template node (either an `Element` or a `Template`), get the set of directives
* which matched the node, if any.
*/
getDirectivesOfNode(node: Element | Template): DirectiveT[] | null;
/**
* For a given `Reference`, get the reference's target - either an `Element`, a `Template`, or
* a directive on a particular node.
*/
getReferenceTarget(ref: Reference): ReferenceTarget<DirectiveT> | null;
/**
* For a given binding, get the entity to which the binding is being made.
*
* This will either be a directive or the node itself.
*/
getConsumerOfBinding(
binding: BoundAttribute | BoundEvent | TextAttribute,
): DirectiveT | Element | Template | null;
/**
* If the given `AST` expression refers to a `Reference` or `Variable` within the `Target`, then
* return that.
*
* Otherwise, returns `null`.
*
* This is only defined for `AST` expressions that read or write to a property of an
* `ImplicitReceiver`.
*/
getExpressionTarget(expr: AST): TemplateEntity | null;
/**
* Given a particular `Reference` or `Variable`, get the `ScopedNode` which created it.
*
* All `Variable`s are defined on node, so this will always return a value for a `Variable`
* from the `Target`. Returns `null` otherwise.
*/
getDefinitionNodeOfSymbol(symbol: TemplateEntity): ScopedNode | null;
/**
* Get the nesting level of a particular `ScopedNode`.
*
* This starts at 1 for top-level nodes within the `Target` and increases for nodes
* nested at deeper levels.
*/
getNestingLevel(node: ScopedNode): number;
/**
* Get all `Reference`s and `Variables` visible within the given `ScopedNode` (or at the top
* level, if `null` is passed).
*/
getEntitiesInScope(node: ScopedNode | null): ReadonlySet<TemplateEntity>;
/**
* Get a list of all the directives used by the target,
* including directives from `@defer` blocks.
*/
getUsedDirectives(): DirectiveT[];
/**
* Get a list of eagerly used directives from the target.
* Note: this list *excludes* directives from `@defer` blocks.
*/
getEagerlyUsedDirectives(): DirectiveT[];
/**
* Get a list of all the pipes used by the target,
* including pipes from `@defer` blocks.
*/
getUsedPipes(): string[];
/**
* Get a list of eagerly used pipes from the target.
* Note: this list *excludes* pipes from `@defer` blocks.
*/
getEagerlyUsedPipes(): string[];
/**
* Get a list of all `@defer` blocks used by the target.
*/
getDeferBlocks(): DeferredBlock[];
/**
* Gets the element that a specific deferred block trigger is targeting.
* @param block Block that the trigger belongs to.
* @param trigger Trigger whose target is being looked up.
*/
getDeferredTriggerTarget(block: DeferredBlock, trigger: DeferredTrigger): Element | null;
/**
* Whether a given node is located in a `@defer` block.
*/
isDeferred(node: Element): boolean;
}
| {
"end_byte": 7584,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/t2_api.ts"
} |
angular/packages/compiler/src/render3/view/template.ts_0_5617 | /**
* @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.dev/license
*/
import {Lexer} from '../../expression_parser/lexer';
import {Parser} from '../../expression_parser/parser';
import * as html from '../../ml_parser/ast';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../../ml_parser/defaults';
import {HtmlParser} from '../../ml_parser/html_parser';
import {WhitespaceVisitor} from '../../ml_parser/html_whitespaces';
import {LexerRange} from '../../ml_parser/lexer';
import {ParseError} from '../../parse_util';
import {DomElementSchemaRegistry} from '../../schema/dom_element_schema_registry';
import {BindingParser} from '../../template_parser/binding_parser';
import * as t from '../r3_ast';
import {htmlAstToRender3Ast} from '../r3_template_transform';
import {I18nMetaVisitor} from './i18n/meta';
export const LEADING_TRIVIA_CHARS = [' ', '\n', '\r', '\t'];
/**
* Options that can be used to modify how a template is parsed by `parseTemplate()`.
*/
export interface ParseTemplateOptions {
/**
* Include whitespace nodes in the parsed output.
*/
preserveWhitespaces?: boolean;
/**
* Preserve original line endings instead of normalizing '\r\n' endings to '\n'.
*/
preserveLineEndings?: boolean;
/**
* Preserve whitespace significant to rendering.
*/
preserveSignificantWhitespace?: boolean;
/**
* How to parse interpolation markers.
*/
interpolationConfig?: InterpolationConfig;
/**
* The start and end point of the text to parse within the `source` string.
* The entire `source` string is parsed if this is not provided.
* */
range?: LexerRange;
/**
* If this text is stored in a JavaScript string, then we have to deal with escape sequences.
*
* **Example 1:**
*
* ```
* "abc\"def\nghi"
* ```
*
* - The `\"` must be converted to `"`.
* - The `\n` must be converted to a new line character in a token,
* but it should not increment the current line for source mapping.
*
* **Example 2:**
*
* ```
* "abc\
* def"
* ```
*
* The line continuation (`\` followed by a newline) should be removed from a token
* but the new line should increment the current line for source mapping.
*/
escapedString?: boolean;
/**
* An array of characters that should be considered as leading trivia.
* Leading trivia are characters that are not important to the developer, and so should not be
* included in source-map segments. A common example is whitespace.
*/
leadingTriviaChars?: string[];
/**
* Render `$localize` message ids with additional legacy message ids.
*
* This option defaults to `true` but in the future the default will be flipped.
*
* For now set this option to false if you have migrated the translation files to use the new
* `$localize` message id format and you are not using compile time translation merging.
*/
enableI18nLegacyMessageIdFormat?: boolean;
/**
* If this text is stored in an external template (e.g. via `templateUrl`) then we need to decide
* whether or not to normalize the line-endings (from `\r\n` to `\n`) when processing ICU
* expressions.
*
* If `true` then we will normalize ICU expression line endings.
* The default is `false`, but this will be switched in a future major release.
*/
i18nNormalizeLineEndingsInICUs?: boolean;
/**
* Whether to always attempt to convert the parsed HTML AST to an R3 AST, despite HTML or i18n
* Meta parse errors.
*
*
* This option is useful in the context of the language service, where we want to get as much
* information as possible, despite any errors in the HTML. As an example, a user may be adding
* a new tag and expecting autocomplete on that tag. In this scenario, the HTML is in an errored
* state, as there is an incomplete open tag. However, we're still able to convert the HTML AST
* nodes to R3 AST nodes in order to provide information for the language service.
*
* Note that even when `true` the HTML parse and i18n errors are still appended to the errors
* output, but this is done after converting the HTML AST to R3 AST.
*/
alwaysAttemptHtmlToR3AstConversion?: boolean;
/**
* Include HTML Comment nodes in a top-level comments array on the returned R3 AST.
*
* This option is required by tooling that needs to know the location of comment nodes within the
* AST. A concrete example is @angular-eslint which requires this in order to enable
* "eslint-disable" comments within HTML templates, which then allows users to turn off specific
* rules on a case by case basis, instead of for their whole project within a configuration file.
*/
collectCommentNodes?: boolean;
/** Whether the @ block syntax is enabled. */
enableBlockSyntax?: boolean;
/** Whether the `@let` syntax is enabled. */
enableLetSyntax?: boolean;
// TODO(crisbeto): delete this option when the migration is deleted.
/**
* Whether the parser should allow invalid two-way bindings.
*
* This option is only present to support an automated migration away from the invalid syntax.
*/
allowInvalidAssignmentEvents?: boolean;
}
/**
* Parse a template into render3 `Node`s and additional metadata, with no other dependencies.
*
* @param template text of the template to parse
* @param templateUrl URL to use for source mapping of the parsed template
* @param options options to modify how the template is parsed
*/ | {
"end_byte": 5617,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/template.ts"
} |
angular/packages/compiler/src/render3/view/template.ts_5618_12337 | export function parseTemplate(
template: string,
templateUrl: string,
options: ParseTemplateOptions = {},
): ParsedTemplate {
const {
interpolationConfig,
preserveWhitespaces,
enableI18nLegacyMessageIdFormat,
allowInvalidAssignmentEvents,
} = options;
const bindingParser = makeBindingParser(interpolationConfig, allowInvalidAssignmentEvents);
const htmlParser = new HtmlParser();
const parseResult = htmlParser.parse(template, templateUrl, {
leadingTriviaChars: LEADING_TRIVIA_CHARS,
...options,
tokenizeExpansionForms: true,
tokenizeBlocks: options.enableBlockSyntax ?? true,
tokenizeLet: options.enableLetSyntax ?? true,
});
if (
!options.alwaysAttemptHtmlToR3AstConversion &&
parseResult.errors &&
parseResult.errors.length > 0
) {
const parsedTemplate: ParsedTemplate = {
interpolationConfig,
preserveWhitespaces,
errors: parseResult.errors,
nodes: [],
styleUrls: [],
styles: [],
ngContentSelectors: [],
};
if (options.collectCommentNodes) {
parsedTemplate.commentNodes = [];
}
return parsedTemplate;
}
let rootNodes: html.Node[] = parseResult.rootNodes;
// We need to use the same `retainEmptyTokens` value for both parses to avoid
// causing a mismatch when reusing source spans, even if the
// `preserveSignificantWhitespace` behavior is different between the two
// parses.
const retainEmptyTokens = !(options.preserveSignificantWhitespace ?? true);
// process i18n meta information (scan attributes, generate ids)
// before we run whitespace removal process, because existing i18n
// extraction process (ng extract-i18n) relies on a raw content to generate
// message ids
const i18nMetaVisitor = new I18nMetaVisitor(
interpolationConfig,
/* keepI18nAttrs */ !preserveWhitespaces,
enableI18nLegacyMessageIdFormat,
/* containerBlocks */ undefined,
options.preserveSignificantWhitespace,
retainEmptyTokens,
);
const i18nMetaResult = i18nMetaVisitor.visitAllWithErrors(rootNodes);
if (
!options.alwaysAttemptHtmlToR3AstConversion &&
i18nMetaResult.errors &&
i18nMetaResult.errors.length > 0
) {
const parsedTemplate: ParsedTemplate = {
interpolationConfig,
preserveWhitespaces,
errors: i18nMetaResult.errors,
nodes: [],
styleUrls: [],
styles: [],
ngContentSelectors: [],
};
if (options.collectCommentNodes) {
parsedTemplate.commentNodes = [];
}
return parsedTemplate;
}
rootNodes = i18nMetaResult.rootNodes;
if (!preserveWhitespaces) {
// Always preserve significant whitespace here because this is used to generate the `goog.getMsg`
// and `$localize` calls which should retain significant whitespace in order to render the
// correct output. We let this diverge from the message IDs generated earlier which might not
// have preserved significant whitespace.
//
// This should use `visitAllWithSiblings` to set `WhitespaceVisitor` context correctly, however
// there is an existing bug where significant whitespace is not properly retained in the JS
// output of leading/trailing whitespace for ICU messages due to the existing lack of context\
// in `WhitespaceVisitor`. Using `visitAllWithSiblings` here would fix that bug and retain the
// whitespace, however it would also change the runtime representation which we don't want to do
// right now.
rootNodes = html.visitAll(
new WhitespaceVisitor(
/* preserveSignificantWhitespace */ true,
/* originalNodeMap */ undefined,
/* requireContext */ false,
),
rootNodes,
);
// run i18n meta visitor again in case whitespaces are removed (because that might affect
// generated i18n message content) and first pass indicated that i18n content is present in a
// template. During this pass i18n IDs generated at the first pass will be preserved, so we can
// mimic existing extraction process (ng extract-i18n)
if (i18nMetaVisitor.hasI18nMeta) {
rootNodes = html.visitAll(
new I18nMetaVisitor(
interpolationConfig,
/* keepI18nAttrs */ false,
/* enableI18nLegacyMessageIdFormat */ undefined,
/* containerBlocks */ undefined,
/* preserveSignificantWhitespace */ true,
retainEmptyTokens,
),
rootNodes,
);
}
}
const {nodes, errors, styleUrls, styles, ngContentSelectors, commentNodes} = htmlAstToRender3Ast(
rootNodes,
bindingParser,
{collectCommentNodes: !!options.collectCommentNodes},
);
errors.push(...parseResult.errors, ...i18nMetaResult.errors);
const parsedTemplate: ParsedTemplate = {
interpolationConfig,
preserveWhitespaces,
errors: errors.length > 0 ? errors : null,
nodes,
styleUrls,
styles,
ngContentSelectors,
};
if (options.collectCommentNodes) {
parsedTemplate.commentNodes = commentNodes;
}
return parsedTemplate;
}
const elementRegistry = new DomElementSchemaRegistry();
/**
* Construct a `BindingParser` with a default configuration.
*/
export function makeBindingParser(
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG,
allowInvalidAssignmentEvents = false,
): BindingParser {
return new BindingParser(
new Parser(new Lexer()),
interpolationConfig,
elementRegistry,
[],
allowInvalidAssignmentEvents,
);
}
/**
* Information about the template which was extracted during parsing.
*
* This contains the actual parsed template as well as any metadata collected during its parsing,
* some of which might be useful for re-parsing the template with different options.
*/
export interface ParsedTemplate {
/**
* Include whitespace nodes in the parsed output.
*/
preserveWhitespaces?: boolean;
/**
* How to parse interpolation markers.
*/
interpolationConfig?: InterpolationConfig;
/**
* Any errors from parsing the template the first time.
*
* `null` if there are no errors. Otherwise, the array of errors is guaranteed to be non-empty.
*/
errors: ParseError[] | null;
/**
* The template AST, parsed from the template.
*/
nodes: t.Node[];
/**
* Any styleUrls extracted from the metadata.
*/
styleUrls: string[];
/**
* Any inline styles extracted from the metadata.
*/
styles: string[];
/**
* Any ng-content selectors extracted from the template.
*/
ngContentSelectors: string[];
/**
* Any R3 Comment Nodes extracted from the template when the `collectCommentNodes` parse template
* option is enabled.
*/
commentNodes?: t.Comment[];
} | {
"end_byte": 12337,
"start_byte": 5618,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/template.ts"
} |
angular/packages/compiler/src/render3/view/api.ts_0_8870 | /**
* @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.dev/license
*/
import {ChangeDetectionStrategy, ViewEncapsulation} from '../../core';
import {InterpolationConfig} from '../../ml_parser/defaults';
import * as o from '../../output/output_ast';
import {ParseSourceSpan} from '../../parse_util';
import * as t from '../r3_ast';
import {R3DependencyMetadata} from '../r3_factory';
import {MaybeForwardRefExpression, R3Reference} from '../util';
/**
* Information needed to compile a directive for the render3 runtime.
*/
export interface R3DirectiveMetadata {
/**
* Name of the directive type.
*/
name: string;
/**
* An expression representing a reference to the directive itself.
*/
type: R3Reference;
/**
* Number of generic type parameters of the type itself.
*/
typeArgumentCount: number;
/**
* A source span for the directive type.
*/
typeSourceSpan: ParseSourceSpan;
/**
* Dependencies of the directive's constructor.
*/
deps: R3DependencyMetadata[] | 'invalid' | null;
/**
* Unparsed selector of the directive, or `null` if there was no selector.
*/
selector: string | null;
/**
* Information about the content queries made by the directive.
*/
queries: R3QueryMetadata[];
/**
* Information about the view queries made by the directive.
*/
viewQueries: R3QueryMetadata[];
/**
* Mappings indicating how the directive interacts with its host element (host bindings,
* listeners, etc).
*/
host: R3HostMetadata;
/**
* Information about usage of specific lifecycle events which require special treatment in the
* code generator.
*/
lifecycle: {
/**
* Whether the directive uses NgOnChanges.
*/
usesOnChanges: boolean;
};
/**
* A mapping of inputs from class property names to binding property names, or to a tuple of
* binding property name and class property name if the names are different.
*/
inputs: {[field: string]: R3InputMetadata};
/**
* A mapping of outputs from class property names to binding property names, or to a tuple of
* binding property name and class property name if the names are different.
*/
outputs: {[field: string]: string};
/**
* Whether or not the component or directive inherits from another class
*/
usesInheritance: boolean;
/**
* Whether or not the component or directive inherits its entire decorator from its base class.
*/
fullInheritance: boolean;
/**
* Reference name under which to export the directive's type in a template,
* if any.
*/
exportAs: string[] | null;
/**
* The list of providers defined in the directive.
*/
providers: o.Expression | null;
/**
* Whether or not the component or directive is standalone.
*/
isStandalone: boolean;
/**
* Whether or not the component or directive is signal-based.
*/
isSignal: boolean;
/**
* Additional directives applied to the directive host.
*/
hostDirectives: R3HostDirectiveMetadata[] | null;
}
/**
* Defines how dynamic imports for deferred dependencies should be emitted in the
* generated output:
* - either in a function on per-component basis (in case of local compilation)
* - or in a function on per-block basis (in full compilation mode)
*/
export const enum DeferBlockDepsEmitMode {
/**
* Dynamic imports are grouped on per-block basis.
*
* This is used in full compilation mode, when compiler has more information
* about particular dependencies that belong to this block.
*/
PerBlock,
/**
* Dynamic imports are grouped on per-component basis.
*
* In local compilation, compiler doesn't have enough information to determine
* which deferred dependencies belong to which block. In this case we group all
* dynamic imports into a single file on per-component basis.
*/
PerComponent,
}
/**
* Specifies how a list of declaration type references should be emitted into the generated code.
*/
export const enum DeclarationListEmitMode {
/**
* The list of declarations is emitted into the generated code as is.
*
* ```
* directives: [MyDir],
* ```
*/
Direct,
/**
* The list of declarations is emitted into the generated code wrapped inside a closure, which
* is needed when at least one declaration is a forward reference.
*
* ```
* directives: function () { return [MyDir, ForwardDir]; },
* ```
*/
Closure,
/**
* Similar to `Closure`, with the addition that the list of declarations can contain individual
* items that are themselves forward references. This is relevant for JIT compilations, as
* unwrapping the forwardRef cannot be done statically so must be deferred. This mode emits
* the declaration list using a mapping transform through `resolveForwardRef` to ensure that
* any forward references within the list are resolved when the outer closure is invoked.
*
* Consider the case where the runtime has captured two declarations in two distinct values:
* ```
* const dirA = MyDir;
* const dirB = forwardRef(function() { return ForwardRef; });
* ```
*
* This mode would emit the declarations captured in `dirA` and `dirB` as follows:
* ```
* directives: function () { return [dirA, dirB].map(ng.resolveForwardRef); },
* ```
*/
ClosureResolved,
RuntimeResolved,
}
/**
* Information needed to compile a component for the render3 runtime.
*/
export interface R3ComponentMetadata<DeclarationT extends R3TemplateDependency>
extends R3DirectiveMetadata {
/**
* Information about the component's template.
*/
template: {
/**
* Parsed nodes of the template.
*/
nodes: t.Node[];
/**
* Any ng-content selectors extracted from the template. Contains `*` when an ng-content
* element without selector is present.
*/
ngContentSelectors: string[];
/**
* Whether the template preserves whitespaces from the user's code.
*/
preserveWhitespaces?: boolean;
};
declarations: DeclarationT[];
/** Metadata related to the deferred blocks in the component's template. */
defer: R3ComponentDeferMetadata;
/**
* Specifies how the 'directives' and/or `pipes` array, if generated, need to be emitted.
*/
declarationListEmitMode: DeclarationListEmitMode;
/**
* A collection of styling data that will be applied and scoped to the component.
*/
styles: string[];
/**
* A collection of style paths for external stylesheets that will be applied and scoped to the component.
*/
externalStyles?: string[];
/**
* An encapsulation policy for the component's styling.
* Possible values:
* - `ViewEncapsulation.Emulated`: Apply modified component styles in order to emulate
* a native Shadow DOM CSS encapsulation behavior.
* - `ViewEncapsulation.None`: Apply component styles globally without any sort of encapsulation.
* - `ViewEncapsulation.ShadowDom`: Use the browser's native Shadow DOM API to encapsulate styles.
*/
encapsulation: ViewEncapsulation;
/**
* A collection of animation triggers that will be used in the component template.
*/
animations: o.Expression | null;
/**
* The list of view providers defined in the component.
*/
viewProviders: o.Expression | null;
/**
* Path to the .ts file in which this template's generated code will be included, relative to
* the compilation root. This will be used to generate identifiers that need to be globally
* unique in certain contexts (such as g3).
*/
relativeContextFilePath: string;
/**
* Whether translation variable name should contain external message id
* (used by Closure Compiler's output of `goog.getMsg` for transition period).
*/
i18nUseExternalIds: boolean;
/**
* Overrides the default interpolation start and end delimiters ({{ and }}).
*/
interpolation: InterpolationConfig;
/**
* Strategy used for detecting changes in the component.
*
* In global compilation mode the value is ChangeDetectionStrategy if available as it is
* statically resolved during analysis phase. Whereas in local compilation mode the value is the
* expression as appears in the decorator.
*/
changeDetection: ChangeDetectionStrategy | o.Expression | null;
/**
* The imports expression as appears on the component decorate for standalone component. This
* field is currently needed only for local compilation, and so in other compilation modes it may
* not be set. If component has empty array imports then this field is not set.
*/
rawImports?: o.Expression;
}
/**
* Information about the deferred blocks in a component's template.
*/ | {
"end_byte": 8870,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/api.ts"
} |
angular/packages/compiler/src/render3/view/api.ts_8871_15846 | export type R3ComponentDeferMetadata =
| {
mode: DeferBlockDepsEmitMode.PerBlock;
blocks: Map<t.DeferredBlock, o.Expression | null>;
}
| {
mode: DeferBlockDepsEmitMode.PerComponent;
dependenciesFn: o.Expression | null;
};
/**
* Metadata for an individual input on a directive.
*/
export interface R3InputMetadata {
classPropertyName: string;
bindingPropertyName: string;
required: boolean;
isSignal: boolean;
/**
* Transform function for the input.
*
* Null if there is no transform, or if this is a signal input.
* Signal inputs capture their transform as part of the `InputSignal`.
*/
transformFunction: o.Expression | null;
}
export enum R3TemplateDependencyKind {
Directive = 0,
Pipe = 1,
NgModule = 2,
}
/**
* A dependency that's used within a component template.
*/
export interface R3TemplateDependency {
kind: R3TemplateDependencyKind;
/**
* The type of the dependency as an expression.
*/
type: o.Expression;
}
/**
* A dependency that's used within a component template
*/
export type R3TemplateDependencyMetadata =
| R3DirectiveDependencyMetadata
| R3PipeDependencyMetadata
| R3NgModuleDependencyMetadata;
/**
* Information about a directive that is used in a component template. Only the stable, public
* facing information of the directive is stored here.
*/
export interface R3DirectiveDependencyMetadata extends R3TemplateDependency {
kind: R3TemplateDependencyKind.Directive;
/**
* The selector of the directive.
*/
selector: string;
/**
* The binding property names of the inputs of the directive.
*/
inputs: string[];
/**
* The binding property names of the outputs of the directive.
*/
outputs: string[];
/**
* Name under which the directive is exported, if any (exportAs in Angular). Null otherwise.
*/
exportAs: string[] | null;
/**
* If true then this directive is actually a component; otherwise it is not.
*/
isComponent: boolean;
}
export interface R3PipeDependencyMetadata extends R3TemplateDependency {
kind: R3TemplateDependencyKind.Pipe;
name: string;
}
export interface R3NgModuleDependencyMetadata extends R3TemplateDependency {
kind: R3TemplateDependencyKind.NgModule;
}
/**
* Information needed to compile a query (view or content).
*/
export interface R3QueryMetadata {
/**
* Name of the property on the class to update with query results.
*/
propertyName: string;
/**
* Whether to read only the first matching result, or an array of results.
*/
first: boolean;
/**
* Either an expression representing a type or `InjectionToken` for the query
* predicate, or a set of string selectors.
*
* Note: At compile time we split selectors as an optimization that avoids this
* extra work at runtime creation phase.
*
* Notably, if the selector is not statically analyzable due to an expression,
* the selectors may need to be split up at runtime.
*/
predicate: MaybeForwardRefExpression | string[];
/**
* Whether to include only direct children or all descendants.
*/
descendants: boolean;
/**
* If the `QueryList` should fire change event only if actual change to query was computed (vs old
* behavior where the change was fired whenever the query was recomputed, even if the recomputed
* query resulted in the same list.)
*/
emitDistinctChangesOnly: boolean;
/**
* An expression representing a type to read from each matched node, or null if the default value
* for a given node is to be returned.
*/
read: o.Expression | null;
/**
* Whether or not this query should collect only static results.
*
* If static is true, the query's results will be set on the component after nodes are created,
* but before change detection runs. This means that any results that relied upon change detection
* to run (e.g. results inside *ngIf or *ngFor views) will not be collected. Query results are
* available in the ngOnInit hook.
*
* If static is false, the query's results will be set on the component after change detection
* runs. This means that the query results can contain nodes inside *ngIf or *ngFor views, but
* the results will not be available in the ngOnInit hook (only in the ngAfterContentInit for
* content hooks and ngAfterViewInit for view hooks).
*
* Note: For signal-based queries, this option does not have any effect.
*/
static: boolean;
/** Whether the query is signal-based. */
isSignal: boolean;
}
/**
* Mappings indicating how the class interacts with its
* host element (host bindings, listeners, etc).
*/
export interface R3HostMetadata {
/**
* A mapping of attribute binding keys to `o.Expression`s.
*/
attributes: {[key: string]: o.Expression};
/**
* A mapping of event binding keys to unparsed expressions.
*/
listeners: {[key: string]: string};
/**
* A mapping of property binding keys to unparsed expressions.
*/
properties: {[key: string]: string};
specialAttributes: {styleAttr?: string; classAttr?: string};
}
/**
* Information needed to compile a host directive for the render3 runtime.
*/
export interface R3HostDirectiveMetadata {
/** An expression representing the host directive class itself. */
directive: R3Reference;
/** Whether the expression referring to the host directive is a forward reference. */
isForwardReference: boolean;
/** Inputs from the host directive that will be exposed on the host. */
inputs: {[publicName: string]: string} | null;
/** Outputs from the host directive that will be exposed on the host. */
outputs: {[publicName: string]: string} | null;
}
/**
* Information needed to compile the defer block resolver function.
*/
export type R3DeferResolverFunctionMetadata =
| {
mode: DeferBlockDepsEmitMode.PerBlock;
dependencies: R3DeferPerBlockDependency[];
}
| {
mode: DeferBlockDepsEmitMode.PerComponent;
dependencies: R3DeferPerComponentDependency[];
};
/**
* Information about a single dependency of a defer block in `PerBlock` mode.
*/
export interface R3DeferPerBlockDependency {
/**
* Reference to a dependency.
*/
typeReference: o.Expression;
/**
* Dependency class name.
*/
symbolName: string;
/**
* Whether this dependency can be defer-loaded.
*/
isDeferrable: boolean;
/**
* Import path where this dependency is located.
*/
importPath: string | null;
/**
* Whether the symbol is the default export.
*/
isDefaultImport: boolean;
}
/**
* Information about a single dependency of a defer block in `PerComponent` mode.
*/
export interface R3DeferPerComponentDependency {
/**
* Dependency class name.
*/
symbolName: string;
/**
* Import path where this dependency is located.
*/
importPath: string;
/**
* Whether the symbol is the default export.
*/
isDefaultImport: boolean;
} | {
"end_byte": 15846,
"start_byte": 8871,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/api.ts"
} |
angular/packages/compiler/src/render3/view/query_generation.ts_0_7058 | /**
* @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.dev/license
*/
import {ConstantPool} from '../../constant_pool';
import * as core from '../../core';
import * as o from '../../output/output_ast';
import {Identifiers as R3} from '../r3_identifiers';
import {ForwardRefHandling} from '../util';
import {R3QueryMetadata} from './api';
import {CONTEXT_NAME, RENDER_FLAGS, TEMPORARY_NAME, temporaryAllocator} from './util';
// if (rf & flags) { .. }
function renderFlagCheckIfStmt(flags: core.RenderFlags, statements: o.Statement[]): o.IfStmt {
return o.ifStmt(o.variable(RENDER_FLAGS).bitwiseAnd(o.literal(flags), null, false), statements);
}
/**
* A set of flags to be used with Queries.
*
* NOTE: Ensure changes here are in sync with `packages/core/src/render3/interfaces/query.ts`
*/
export const enum QueryFlags {
/**
* No flags
*/
none = 0b0000,
/**
* Whether or not the query should descend into children.
*/
descendants = 0b0001,
/**
* The query can be computed statically and hence can be assigned eagerly.
*
* NOTE: Backwards compatibility with ViewEngine.
*/
isStatic = 0b0010,
/**
* If the `QueryList` should fire change event only if actual change to query was computed (vs old
* behavior where the change was fired whenever the query was recomputed, even if the recomputed
* query resulted in the same list.)
*/
emitDistinctChangesOnly = 0b0100,
}
/**
* Translates query flags into `TQueryFlags` type in
* packages/core/src/render3/interfaces/query.ts
* @param query
*/
function toQueryFlags(query: R3QueryMetadata): number {
return (
(query.descendants ? QueryFlags.descendants : QueryFlags.none) |
(query.static ? QueryFlags.isStatic : QueryFlags.none) |
(query.emitDistinctChangesOnly ? QueryFlags.emitDistinctChangesOnly : QueryFlags.none)
);
}
export function getQueryPredicate(
query: R3QueryMetadata,
constantPool: ConstantPool,
): o.Expression {
if (Array.isArray(query.predicate)) {
let predicate: o.Expression[] = [];
query.predicate.forEach((selector: string): void => {
// Each item in predicates array may contain strings with comma-separated refs
// (for ex. 'ref, ref1, ..., refN'), thus we extract individual refs and store them
// as separate array entities
const selectors = selector.split(',').map((token) => o.literal(token.trim()));
predicate.push(...selectors);
});
return constantPool.getConstLiteral(o.literalArr(predicate), true);
} else {
// The original predicate may have been wrapped in a `forwardRef()` call.
switch (query.predicate.forwardRef) {
case ForwardRefHandling.None:
case ForwardRefHandling.Unwrapped:
return query.predicate.expression;
case ForwardRefHandling.Wrapped:
return o.importExpr(R3.resolveForwardRef).callFn([query.predicate.expression]);
}
}
}
export function createQueryCreateCall(
query: R3QueryMetadata,
constantPool: ConstantPool,
queryTypeFns: {signalBased: o.ExternalReference; nonSignal: o.ExternalReference},
prependParams?: o.Expression[],
): o.InvokeFunctionExpr {
const parameters: o.Expression[] = [];
if (prependParams !== undefined) {
parameters.push(...prependParams);
}
if (query.isSignal) {
parameters.push(new o.ReadPropExpr(o.variable(CONTEXT_NAME), query.propertyName));
}
parameters.push(getQueryPredicate(query, constantPool), o.literal(toQueryFlags(query)));
if (query.read) {
parameters.push(query.read);
}
const queryCreateFn = query.isSignal ? queryTypeFns.signalBased : queryTypeFns.nonSignal;
return o.importExpr(queryCreateFn).callFn(parameters);
}
const queryAdvancePlaceholder = Symbol('queryAdvancePlaceholder');
/**
* Collapses query advance placeholders in a list of statements.
*
* This allows for less generated code because multiple sibling query advance
* statements can be collapsed into a single call with the count as argument.
*
* e.g.
*
* ```ts
* bla();
* queryAdvance();
* queryAdvance();
* bla();
* ```
*
* --> will turn into
*
* ```
* bla();
* queryAdvance(2);
* bla();
* ```
*/
function collapseAdvanceStatements(
statements: (o.Statement | typeof queryAdvancePlaceholder)[],
): o.Statement[] {
const result: o.Statement[] = [];
let advanceCollapseCount = 0;
const flushAdvanceCount = () => {
if (advanceCollapseCount > 0) {
result.unshift(
o
.importExpr(R3.queryAdvance)
.callFn(advanceCollapseCount === 1 ? [] : [o.literal(advanceCollapseCount)])
.toStmt(),
);
advanceCollapseCount = 0;
}
};
// Iterate through statements in reverse and collapse advance placeholders.
for (let i = statements.length - 1; i >= 0; i--) {
const st = statements[i];
if (st === queryAdvancePlaceholder) {
advanceCollapseCount++;
} else {
flushAdvanceCount();
result.unshift(st);
}
}
flushAdvanceCount();
return result;
}
// Define and update any view queries
export function createViewQueriesFunction(
viewQueries: R3QueryMetadata[],
constantPool: ConstantPool,
name?: string,
): o.Expression {
const createStatements: o.Statement[] = [];
const updateStatements: (o.Statement | typeof queryAdvancePlaceholder)[] = [];
const tempAllocator = temporaryAllocator((st) => updateStatements.push(st), TEMPORARY_NAME);
viewQueries.forEach((query: R3QueryMetadata) => {
// creation call, e.g. r3.viewQuery(somePredicate, true) or
// r3.viewQuerySignal(ctx.prop, somePredicate, true);
const queryDefinitionCall = createQueryCreateCall(query, constantPool, {
signalBased: R3.viewQuerySignal,
nonSignal: R3.viewQuery,
});
createStatements.push(queryDefinitionCall.toStmt());
// Signal queries update lazily and we just advance the index.
if (query.isSignal) {
updateStatements.push(queryAdvancePlaceholder);
return;
}
// update, e.g. (r3.queryRefresh(tmp = r3.loadQuery()) && (ctx.someDir = tmp));
const temporary = tempAllocator();
const getQueryList = o.importExpr(R3.loadQuery).callFn([]);
const refresh = o.importExpr(R3.queryRefresh).callFn([temporary.set(getQueryList)]);
const updateDirective = o
.variable(CONTEXT_NAME)
.prop(query.propertyName)
.set(query.first ? temporary.prop('first') : temporary);
updateStatements.push(refresh.and(updateDirective).toStmt());
});
const viewQueryFnName = name ? `${name}_Query` : null;
return o.fn(
[new o.FnParam(RENDER_FLAGS, o.NUMBER_TYPE), new o.FnParam(CONTEXT_NAME, null)],
[
renderFlagCheckIfStmt(core.RenderFlags.Create, createStatements),
renderFlagCheckIfStmt(core.RenderFlags.Update, collapseAdvanceStatements(updateStatements)),
],
o.INFERRED_TYPE,
null,
viewQueryFnName,
);
}
// Define and update any content queries | {
"end_byte": 7058,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/query_generation.ts"
} |
angular/packages/compiler/src/render3/view/query_generation.ts_7059_9026 | export function createContentQueriesFunction(
queries: R3QueryMetadata[],
constantPool: ConstantPool,
name?: string,
): o.Expression {
const createStatements: o.Statement[] = [];
const updateStatements: (o.Statement | typeof queryAdvancePlaceholder)[] = [];
const tempAllocator = temporaryAllocator((st) => updateStatements.push(st), TEMPORARY_NAME);
for (const query of queries) {
// creation, e.g. r3.contentQuery(dirIndex, somePredicate, true, null) or
// r3.contentQuerySignal(dirIndex, propName, somePredicate, <flags>, <read>).
createStatements.push(
createQueryCreateCall(
query,
constantPool,
{nonSignal: R3.contentQuery, signalBased: R3.contentQuerySignal},
/* prependParams */ [o.variable('dirIndex')],
).toStmt(),
);
// Signal queries update lazily and we just advance the index.
if (query.isSignal) {
updateStatements.push(queryAdvancePlaceholder);
continue;
}
// update, e.g. (r3.queryRefresh(tmp = r3.loadQuery()) && (ctx.someDir = tmp));
const temporary = tempAllocator();
const getQueryList = o.importExpr(R3.loadQuery).callFn([]);
const refresh = o.importExpr(R3.queryRefresh).callFn([temporary.set(getQueryList)]);
const updateDirective = o
.variable(CONTEXT_NAME)
.prop(query.propertyName)
.set(query.first ? temporary.prop('first') : temporary);
updateStatements.push(refresh.and(updateDirective).toStmt());
}
const contentQueriesFnName = name ? `${name}_ContentQueries` : null;
return o.fn(
[
new o.FnParam(RENDER_FLAGS, o.NUMBER_TYPE),
new o.FnParam(CONTEXT_NAME, null),
new o.FnParam('dirIndex', null),
],
[
renderFlagCheckIfStmt(core.RenderFlags.Create, createStatements),
renderFlagCheckIfStmt(core.RenderFlags.Update, collapseAdvanceStatements(updateStatements)),
],
o.INFERRED_TYPE,
null,
contentQueriesFnName,
);
} | {
"end_byte": 9026,
"start_byte": 7059,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/query_generation.ts"
} |
angular/packages/compiler/src/render3/view/util.ts_0_7575 | /**
* @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.dev/license
*/
import {InputFlags} from '../../core';
import {BindingType} from '../../expression_parser/ast';
import {splitNsName} from '../../ml_parser/tags';
import * as o from '../../output/output_ast';
import {CssSelector} from '../../selector';
import * as t from '../r3_ast';
import {isI18nAttribute} from './i18n/util';
/**
* Checks whether an object key contains potentially unsafe chars, thus the key should be wrapped in
* quotes. Note: we do not wrap all keys into quotes, as it may have impact on minification and may
* not work in some cases when object keys are mangled by a minifier.
*
* TODO(FW-1136): this is a temporary solution, we need to come up with a better way of working with
* inputs that contain potentially unsafe chars.
*/
export const UNSAFE_OBJECT_KEY_NAME_REGEXP = /[-.]/;
/** Name of the temporary to use during data binding */
export const TEMPORARY_NAME = '_t';
/** Name of the context parameter passed into a template function */
export const CONTEXT_NAME = 'ctx';
/** Name of the RenderFlag passed into a template function */
export const RENDER_FLAGS = 'rf';
/**
* Creates an allocator for a temporary variable.
*
* A variable declaration is added to the statements the first time the allocator is invoked.
*/
export function temporaryAllocator(
pushStatement: (st: o.Statement) => void,
name: string,
): () => o.ReadVarExpr {
let temp: o.ReadVarExpr | null = null;
return () => {
if (!temp) {
pushStatement(new o.DeclareVarStmt(TEMPORARY_NAME, undefined, o.DYNAMIC_TYPE));
temp = o.variable(name);
}
return temp;
};
}
export function invalid<T>(this: t.Visitor, arg: o.Expression | o.Statement | t.Node): never {
throw new Error(
`Invalid state: Visitor ${this.constructor.name} doesn't handle ${arg.constructor.name}`,
);
}
export function asLiteral(value: any): o.Expression {
if (Array.isArray(value)) {
return o.literalArr(value.map(asLiteral));
}
return o.literal(value, o.INFERRED_TYPE);
}
/**
* Serializes inputs and outputs for `defineDirective` and `defineComponent`.
*
* This will attempt to generate optimized data structures to minimize memory or
* file size of fully compiled applications.
*/
export function conditionallyCreateDirectiveBindingLiteral(
map: Record<
string,
| string
| {
classPropertyName: string;
bindingPropertyName: string;
transformFunction: o.Expression | null;
isSignal: boolean;
}
>,
forInputs?: boolean,
): o.Expression | null {
const keys = Object.getOwnPropertyNames(map);
if (keys.length === 0) {
return null;
}
return o.literalMap(
keys.map((key) => {
const value = map[key];
let declaredName: string;
let publicName: string;
let minifiedName: string;
let expressionValue: o.Expression;
if (typeof value === 'string') {
// canonical syntax: `dirProp: publicProp`
declaredName = key;
minifiedName = key;
publicName = value;
expressionValue = asLiteral(publicName);
} else {
minifiedName = key;
declaredName = value.classPropertyName;
publicName = value.bindingPropertyName;
const differentDeclaringName = publicName !== declaredName;
const hasDecoratorInputTransform = value.transformFunction !== null;
let flags = InputFlags.None;
// Build up input flags
if (value.isSignal) {
flags |= InputFlags.SignalBased;
}
if (hasDecoratorInputTransform) {
flags |= InputFlags.HasDecoratorInputTransform;
}
// Inputs, compared to outputs, will track their declared name (for `ngOnChanges`), support
// decorator input transform functions, or store flag information if there is any.
if (
forInputs &&
(differentDeclaringName || hasDecoratorInputTransform || flags !== InputFlags.None)
) {
const result = [o.literal(flags), asLiteral(publicName)];
if (differentDeclaringName || hasDecoratorInputTransform) {
result.push(asLiteral(declaredName));
if (hasDecoratorInputTransform) {
result.push(value.transformFunction!);
}
}
expressionValue = o.literalArr(result);
} else {
expressionValue = asLiteral(publicName);
}
}
return {
key: minifiedName,
// put quotes around keys that contain potentially unsafe characters
quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(minifiedName),
value: expressionValue,
};
}),
);
}
/**
* A representation for an object literal used during codegen of definition objects. The generic
* type `T` allows to reference a documented type of the generated structure, such that the
* property names that are set can be resolved to their documented declaration.
*/
export class DefinitionMap<T = any> {
values: {key: string; quoted: boolean; value: o.Expression}[] = [];
set(key: keyof T, value: o.Expression | null): void {
if (value) {
const existing = this.values.find((value) => value.key === key);
if (existing) {
existing.value = value;
} else {
this.values.push({key: key as string, value, quoted: false});
}
}
}
toLiteralMap(): o.LiteralMapExpr {
return o.literalMap(this.values);
}
}
/**
* Creates a `CssSelector` from an AST node.
*/
export function createCssSelectorFromNode(node: t.Element | t.Template): CssSelector {
const elementName = node instanceof t.Element ? node.name : 'ng-template';
const attributes = getAttrsForDirectiveMatching(node);
const cssSelector = new CssSelector();
const elementNameNoNs = splitNsName(elementName)[1];
cssSelector.setElement(elementNameNoNs);
Object.getOwnPropertyNames(attributes).forEach((name) => {
const nameNoNs = splitNsName(name)[1];
const value = attributes[name];
cssSelector.addAttribute(nameNoNs, value);
if (name.toLowerCase() === 'class') {
const classes = value.trim().split(/\s+/);
classes.forEach((className) => cssSelector.addClassName(className));
}
});
return cssSelector;
}
/**
* Extract a map of properties to values for a given element or template node, which can be used
* by the directive matching machinery.
*
* @param elOrTpl the element or template in question
* @return an object set up for directive matching. For attributes on the element/template, this
* object maps a property name to its (static) value. For any bindings, this map simply maps the
* property name to an empty string.
*/
function getAttrsForDirectiveMatching(elOrTpl: t.Element | t.Template): {[name: string]: string} {
const attributesMap: {[name: string]: string} = {};
if (elOrTpl instanceof t.Template && elOrTpl.tagName !== 'ng-template') {
elOrTpl.templateAttrs.forEach((a) => (attributesMap[a.name] = ''));
} else {
elOrTpl.attributes.forEach((a) => {
if (!isI18nAttribute(a.name)) {
attributesMap[a.name] = a.value;
}
});
elOrTpl.inputs.forEach((i) => {
if (i.type === BindingType.Property || i.type === BindingType.TwoWay) {
attributesMap[i.name] = '';
}
});
elOrTpl.outputs.forEach((o) => {
attributesMap[o.name] = '';
});
}
return attributesMap;
}
| {
"end_byte": 7575,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/util.ts"
} |
angular/packages/compiler/src/render3/view/compiler.ts_0_5804 | /**
* @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.dev/license
*/
import {ConstantPool} from '../../constant_pool';
import * as core from '../../core';
import * as o from '../../output/output_ast';
import {ParseError, ParseSourceSpan} from '../../parse_util';
import {CssSelector} from '../../selector';
import {ShadowCss} from '../../shadow_css';
import {CompilationJobKind} from '../../template/pipeline/src/compilation';
import {emitHostBindingFunction, emitTemplateFn, transform} from '../../template/pipeline/src/emit';
import {ingestComponent, ingestHostBinding} from '../../template/pipeline/src/ingest';
import {BindingParser} from '../../template_parser/binding_parser';
import {Identifiers as R3} from '../r3_identifiers';
import {R3CompiledExpression, typeWithParameters} from '../util';
import {
DeclarationListEmitMode,
DeferBlockDepsEmitMode,
R3ComponentMetadata,
R3DeferPerBlockDependency,
R3DeferPerComponentDependency,
R3DeferResolverFunctionMetadata,
R3DirectiveMetadata,
R3HostMetadata,
R3TemplateDependency,
} from './api';
import {createContentQueriesFunction, createViewQueriesFunction} from './query_generation';
import {makeBindingParser} from './template';
import {asLiteral, conditionallyCreateDirectiveBindingLiteral, DefinitionMap} from './util';
const COMPONENT_VARIABLE = '%COMP%';
const HOST_ATTR = `_nghost-${COMPONENT_VARIABLE}`;
const CONTENT_ATTR = `_ngcontent-${COMPONENT_VARIABLE}`;
function baseDirectiveFields(
meta: R3DirectiveMetadata,
constantPool: ConstantPool,
bindingParser: BindingParser,
): DefinitionMap {
const definitionMap = new DefinitionMap();
const selectors = core.parseSelectorToR3Selector(meta.selector);
// e.g. `type: MyDirective`
definitionMap.set('type', meta.type.value);
// e.g. `selectors: [['', 'someDir', '']]`
if (selectors.length > 0) {
definitionMap.set('selectors', asLiteral(selectors));
}
if (meta.queries.length > 0) {
// e.g. `contentQueries: (rf, ctx, dirIndex) => { ... }
definitionMap.set(
'contentQueries',
createContentQueriesFunction(meta.queries, constantPool, meta.name),
);
}
if (meta.viewQueries.length) {
definitionMap.set(
'viewQuery',
createViewQueriesFunction(meta.viewQueries, constantPool, meta.name),
);
}
// e.g. `hostBindings: (rf, ctx) => { ... }
definitionMap.set(
'hostBindings',
createHostBindingsFunction(
meta.host,
meta.typeSourceSpan,
bindingParser,
constantPool,
meta.selector || '',
meta.name,
definitionMap,
),
);
// e.g 'inputs: {a: 'a'}`
definitionMap.set('inputs', conditionallyCreateDirectiveBindingLiteral(meta.inputs, true));
// e.g 'outputs: {a: 'a'}`
definitionMap.set('outputs', conditionallyCreateDirectiveBindingLiteral(meta.outputs));
if (meta.exportAs !== null) {
definitionMap.set('exportAs', o.literalArr(meta.exportAs.map((e) => o.literal(e))));
}
if (meta.isStandalone === false) {
definitionMap.set('standalone', o.literal(false));
}
if (meta.isSignal) {
definitionMap.set('signals', o.literal(true));
}
return definitionMap;
}
/**
* Add features to the definition map.
*/
function addFeatures(
definitionMap: DefinitionMap,
meta: R3DirectiveMetadata | R3ComponentMetadata<R3TemplateDependency>,
) {
// e.g. `features: [NgOnChangesFeature]`
const features: o.Expression[] = [];
const providers = meta.providers;
const viewProviders = (meta as R3ComponentMetadata<R3TemplateDependency>).viewProviders;
const inputKeys = Object.keys(meta.inputs);
if (providers || viewProviders) {
const args = [providers || new o.LiteralArrayExpr([])];
if (viewProviders) {
args.push(viewProviders);
}
features.push(o.importExpr(R3.ProvidersFeature).callFn(args));
}
for (const key of inputKeys) {
if (meta.inputs[key].transformFunction !== null) {
features.push(o.importExpr(R3.InputTransformsFeatureFeature));
break;
}
}
// Note: host directives feature needs to be inserted before the
// inheritance feature to ensure the correct execution order.
if (meta.hostDirectives?.length) {
features.push(
o
.importExpr(R3.HostDirectivesFeature)
.callFn([createHostDirectivesFeatureArg(meta.hostDirectives)]),
);
}
if (meta.usesInheritance) {
features.push(o.importExpr(R3.InheritDefinitionFeature));
}
if (meta.fullInheritance) {
features.push(o.importExpr(R3.CopyDefinitionFeature));
}
if (meta.lifecycle.usesOnChanges) {
features.push(o.importExpr(R3.NgOnChangesFeature));
}
if ('externalStyles' in meta && meta.externalStyles?.length) {
const externalStyleNodes = meta.externalStyles.map((externalStyle) => o.literal(externalStyle));
features.push(
o.importExpr(R3.ExternalStylesFeature).callFn([o.literalArr(externalStyleNodes)]),
);
}
if (features.length) {
definitionMap.set('features', o.literalArr(features));
}
}
/**
* Compile a directive for the render3 runtime as defined by the `R3DirectiveMetadata`.
*/
export function compileDirectiveFromMetadata(
meta: R3DirectiveMetadata,
constantPool: ConstantPool,
bindingParser: BindingParser,
): R3CompiledExpression {
const definitionMap = baseDirectiveFields(meta, constantPool, bindingParser);
addFeatures(definitionMap, meta);
const expression = o
.importExpr(R3.defineDirective)
.callFn([definitionMap.toLiteralMap()], undefined, true);
const type = createDirectiveType(meta);
return {expression, type, statements: []};
}
/**
* Compile a component for the render3 runtime as defined by the `R3ComponentMetadata`.
*/ | {
"end_byte": 5804,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/compiler.ts"
} |
angular/packages/compiler/src/render3/view/compiler.ts_5805_13568 | export function compileComponentFromMetadata(
meta: R3ComponentMetadata<R3TemplateDependency>,
constantPool: ConstantPool,
bindingParser: BindingParser,
): R3CompiledExpression {
const definitionMap = baseDirectiveFields(meta, constantPool, bindingParser);
addFeatures(definitionMap, meta);
const selector = meta.selector && CssSelector.parse(meta.selector);
const firstSelector = selector && selector[0];
// e.g. `attr: ["class", ".my.app"]`
// This is optional an only included if the first selector of a component specifies attributes.
if (firstSelector) {
const selectorAttributes = firstSelector.getAttrs();
if (selectorAttributes.length) {
definitionMap.set(
'attrs',
constantPool.getConstLiteral(
o.literalArr(
selectorAttributes.map((value) =>
value != null ? o.literal(value) : o.literal(undefined),
),
),
/* forceShared */ true,
),
);
}
}
// e.g. `template: function MyComponent_Template(_ctx, _cm) {...}`
const templateTypeName = meta.name;
let allDeferrableDepsFn: o.ReadVarExpr | null = null;
if (
meta.defer.mode === DeferBlockDepsEmitMode.PerComponent &&
meta.defer.dependenciesFn !== null
) {
const fnName = `${templateTypeName}_DeferFn`;
constantPool.statements.push(
new o.DeclareVarStmt(fnName, meta.defer.dependenciesFn, undefined, o.StmtModifier.Final),
);
allDeferrableDepsFn = o.variable(fnName);
}
// First the template is ingested into IR:
const tpl = ingestComponent(
meta.name,
meta.template.nodes,
constantPool,
meta.relativeContextFilePath,
meta.i18nUseExternalIds,
meta.defer,
allDeferrableDepsFn,
);
// Then the IR is transformed to prepare it for cod egeneration.
transform(tpl, CompilationJobKind.Tmpl);
// Finally we emit the template function:
const templateFn = emitTemplateFn(tpl, constantPool);
if (tpl.contentSelectors !== null) {
definitionMap.set('ngContentSelectors', tpl.contentSelectors);
}
definitionMap.set('decls', o.literal(tpl.root.decls as number));
definitionMap.set('vars', o.literal(tpl.root.vars as number));
if (tpl.consts.length > 0) {
if (tpl.constsInitializers.length > 0) {
definitionMap.set(
'consts',
o.arrowFn([], [...tpl.constsInitializers, new o.ReturnStatement(o.literalArr(tpl.consts))]),
);
} else {
definitionMap.set('consts', o.literalArr(tpl.consts));
}
}
definitionMap.set('template', templateFn);
if (
meta.declarationListEmitMode !== DeclarationListEmitMode.RuntimeResolved &&
meta.declarations.length > 0
) {
definitionMap.set(
'dependencies',
compileDeclarationList(
o.literalArr(meta.declarations.map((decl) => decl.type)),
meta.declarationListEmitMode,
),
);
} else if (meta.declarationListEmitMode === DeclarationListEmitMode.RuntimeResolved) {
const args = [meta.type.value];
if (meta.rawImports) {
args.push(meta.rawImports);
}
definitionMap.set('dependencies', o.importExpr(R3.getComponentDepsFactory).callFn(args));
}
if (meta.encapsulation === null) {
meta.encapsulation = core.ViewEncapsulation.Emulated;
}
let hasStyles = !!meta.externalStyles?.length;
// e.g. `styles: [str1, str2]`
if (meta.styles && meta.styles.length) {
const styleValues =
meta.encapsulation == core.ViewEncapsulation.Emulated
? compileStyles(meta.styles, CONTENT_ATTR, HOST_ATTR)
: meta.styles;
const styleNodes = styleValues.reduce((result, style) => {
if (style.trim().length > 0) {
result.push(constantPool.getConstLiteral(o.literal(style)));
}
return result;
}, [] as o.Expression[]);
if (styleNodes.length > 0) {
hasStyles = true;
definitionMap.set('styles', o.literalArr(styleNodes));
}
}
if (!hasStyles && meta.encapsulation === core.ViewEncapsulation.Emulated) {
// If there is no style, don't generate css selectors on elements
meta.encapsulation = core.ViewEncapsulation.None;
}
// Only set view encapsulation if it's not the default value
if (meta.encapsulation !== core.ViewEncapsulation.Emulated) {
definitionMap.set('encapsulation', o.literal(meta.encapsulation));
}
// e.g. `animation: [trigger('123', [])]`
if (meta.animations !== null) {
definitionMap.set(
'data',
o.literalMap([{key: 'animation', value: meta.animations, quoted: false}]),
);
}
// Setting change detection flag
if (meta.changeDetection !== null) {
if (
typeof meta.changeDetection === 'number' &&
meta.changeDetection !== core.ChangeDetectionStrategy.Default
) {
// changeDetection is resolved during analysis. Only set it if not the default.
definitionMap.set('changeDetection', o.literal(meta.changeDetection));
} else if (typeof meta.changeDetection === 'object') {
// changeDetection is not resolved during analysis (e.g., we are in local compilation mode).
// So place it as is.
definitionMap.set('changeDetection', meta.changeDetection);
}
}
const expression = o
.importExpr(R3.defineComponent)
.callFn([definitionMap.toLiteralMap()], undefined, true);
const type = createComponentType(meta);
return {expression, type, statements: []};
}
/**
* Creates the type specification from the component meta. This type is inserted into .d.ts files
* to be consumed by upstream compilations.
*/
export function createComponentType(meta: R3ComponentMetadata<R3TemplateDependency>): o.Type {
const typeParams = createBaseDirectiveTypeParams(meta);
typeParams.push(stringArrayAsType(meta.template.ngContentSelectors));
typeParams.push(o.expressionType(o.literal(meta.isStandalone)));
typeParams.push(createHostDirectivesType(meta));
// TODO(signals): Always include this metadata starting with v17. Right
// now Angular v16.0.x does not support this field and library distributions
// would then be incompatible with v16.0.x framework users.
if (meta.isSignal) {
typeParams.push(o.expressionType(o.literal(meta.isSignal)));
}
return o.expressionType(o.importExpr(R3.ComponentDeclaration, typeParams));
}
/**
* Compiles the array literal of declarations into an expression according to the provided emit
* mode.
*/
function compileDeclarationList(
list: o.LiteralArrayExpr,
mode: DeclarationListEmitMode,
): o.Expression {
switch (mode) {
case DeclarationListEmitMode.Direct:
// directives: [MyDir],
return list;
case DeclarationListEmitMode.Closure:
// directives: function () { return [MyDir]; }
return o.arrowFn([], list);
case DeclarationListEmitMode.ClosureResolved:
// directives: function () { return [MyDir].map(ng.resolveForwardRef); }
const resolvedList = list.prop('map').callFn([o.importExpr(R3.resolveForwardRef)]);
return o.arrowFn([], resolvedList);
case DeclarationListEmitMode.RuntimeResolved:
throw new Error(`Unsupported with an array of pre-resolved dependencies`);
}
}
function stringAsType(str: string): o.Type {
return o.expressionType(o.literal(str));
}
function stringMapAsLiteralExpression(map: {[key: string]: string | string[]}): o.LiteralMapExpr {
const mapValues = Object.keys(map).map((key) => {
const value = Array.isArray(map[key]) ? map[key][0] : map[key];
return {
key,
value: o.literal(value),
quoted: true,
};
});
return o.literalMap(mapValues);
}
function stringArrayAsType(arr: ReadonlyArray<string | null>): o.Type {
return arr.length > 0
? o.expressionType(o.literalArr(arr.map((value) => o.literal(value))))
: o.NONE_TYPE;
} | {
"end_byte": 13568,
"start_byte": 5805,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/compiler.ts"
} |
angular/packages/compiler/src/render3/view/compiler.ts_13570_21934 | function createBaseDirectiveTypeParams(meta: R3DirectiveMetadata): o.Type[] {
// On the type side, remove newlines from the selector as it will need to fit into a TypeScript
// string literal, which must be on one line.
const selectorForType = meta.selector !== null ? meta.selector.replace(/\n/g, '') : null;
return [
typeWithParameters(meta.type.type, meta.typeArgumentCount),
selectorForType !== null ? stringAsType(selectorForType) : o.NONE_TYPE,
meta.exportAs !== null ? stringArrayAsType(meta.exportAs) : o.NONE_TYPE,
o.expressionType(getInputsTypeExpression(meta)),
o.expressionType(stringMapAsLiteralExpression(meta.outputs)),
stringArrayAsType(meta.queries.map((q) => q.propertyName)),
];
}
function getInputsTypeExpression(meta: R3DirectiveMetadata): o.Expression {
return o.literalMap(
Object.keys(meta.inputs).map((key) => {
const value = meta.inputs[key];
const values = [
{key: 'alias', value: o.literal(value.bindingPropertyName), quoted: true},
{key: 'required', value: o.literal(value.required), quoted: true},
];
// TODO(legacy-partial-output-inputs): Consider always emitting this information,
// or leaving it as is.
if (value.isSignal) {
values.push({key: 'isSignal', value: o.literal(value.isSignal), quoted: true});
}
return {key, value: o.literalMap(values), quoted: true};
}),
);
}
/**
* Creates the type specification from the directive meta. This type is inserted into .d.ts files
* to be consumed by upstream compilations.
*/
export function createDirectiveType(meta: R3DirectiveMetadata): o.Type {
const typeParams = createBaseDirectiveTypeParams(meta);
// Directives have no NgContentSelectors slot, but instead express a `never` type
// so that future fields align.
typeParams.push(o.NONE_TYPE);
typeParams.push(o.expressionType(o.literal(meta.isStandalone)));
typeParams.push(createHostDirectivesType(meta));
// TODO(signals): Always include this metadata starting with v17. Right
// now Angular v16.0.x does not support this field and library distributions
// would then be incompatible with v16.0.x framework users.
if (meta.isSignal) {
typeParams.push(o.expressionType(o.literal(meta.isSignal)));
}
return o.expressionType(o.importExpr(R3.DirectiveDeclaration, typeParams));
}
// Return a host binding function or null if one is not necessary.
function createHostBindingsFunction(
hostBindingsMetadata: R3HostMetadata,
typeSourceSpan: ParseSourceSpan,
bindingParser: BindingParser,
constantPool: ConstantPool,
selector: string,
name: string,
definitionMap: DefinitionMap,
): o.Expression | null {
const bindings = bindingParser.createBoundHostProperties(
hostBindingsMetadata.properties,
typeSourceSpan,
);
// Calculate host event bindings
const eventBindings = bindingParser.createDirectiveHostEventAsts(
hostBindingsMetadata.listeners,
typeSourceSpan,
);
// The parser for host bindings treats class and style attributes specially -- they are
// extracted into these separate fields. This is not the case for templates, so the compiler can
// actually already handle these special attributes internally. Therefore, we just drop them
// into the attributes map.
if (hostBindingsMetadata.specialAttributes.styleAttr) {
hostBindingsMetadata.attributes['style'] = o.literal(
hostBindingsMetadata.specialAttributes.styleAttr,
);
}
if (hostBindingsMetadata.specialAttributes.classAttr) {
hostBindingsMetadata.attributes['class'] = o.literal(
hostBindingsMetadata.specialAttributes.classAttr,
);
}
const hostJob = ingestHostBinding(
{
componentName: name,
componentSelector: selector,
properties: bindings,
events: eventBindings,
attributes: hostBindingsMetadata.attributes,
},
bindingParser,
constantPool,
);
transform(hostJob, CompilationJobKind.Host);
definitionMap.set('hostAttrs', hostJob.root.attributes);
const varCount = hostJob.root.vars;
if (varCount !== null && varCount > 0) {
definitionMap.set('hostVars', o.literal(varCount));
}
return emitHostBindingFunction(hostJob);
}
const HOST_REG_EXP = /^(?:\[([^\]]+)\])|(?:\(([^\)]+)\))$/;
// Represents the groups in the above regex.
const enum HostBindingGroup {
// group 1: "prop" from "[prop]", or "attr.role" from "[attr.role]", or @anim from [@anim]
Binding = 1,
// group 2: "event" from "(event)"
Event = 2,
}
// Defines Host Bindings structure that contains attributes, listeners, and properties,
// parsed from the `host` object defined for a Type.
export interface ParsedHostBindings {
attributes: {[key: string]: o.Expression};
listeners: {[key: string]: string};
properties: {[key: string]: string};
specialAttributes: {styleAttr?: string; classAttr?: string};
}
export function parseHostBindings(host: {
[key: string]: string | o.Expression;
}): ParsedHostBindings {
const attributes: {[key: string]: o.Expression} = {};
const listeners: {[key: string]: string} = {};
const properties: {[key: string]: string} = {};
const specialAttributes: {styleAttr?: string; classAttr?: string} = {};
for (const key of Object.keys(host)) {
const value = host[key];
const matches = key.match(HOST_REG_EXP);
if (matches === null) {
switch (key) {
case 'class':
if (typeof value !== 'string') {
// TODO(alxhub): make this a diagnostic.
throw new Error(`Class binding must be string`);
}
specialAttributes.classAttr = value;
break;
case 'style':
if (typeof value !== 'string') {
// TODO(alxhub): make this a diagnostic.
throw new Error(`Style binding must be string`);
}
specialAttributes.styleAttr = value;
break;
default:
if (typeof value === 'string') {
attributes[key] = o.literal(value);
} else {
attributes[key] = value;
}
}
} else if (matches[HostBindingGroup.Binding] != null) {
if (typeof value !== 'string') {
// TODO(alxhub): make this a diagnostic.
throw new Error(`Property binding must be string`);
}
// synthetic properties (the ones that have a `@` as a prefix)
// are still treated the same as regular properties. Therefore
// there is no point in storing them in a separate map.
properties[matches[HostBindingGroup.Binding]] = value;
} else if (matches[HostBindingGroup.Event] != null) {
if (typeof value !== 'string') {
// TODO(alxhub): make this a diagnostic.
throw new Error(`Event binding must be string`);
}
listeners[matches[HostBindingGroup.Event]] = value;
}
}
return {attributes, listeners, properties, specialAttributes};
}
/**
* Verifies host bindings and returns the list of errors (if any). Empty array indicates that a
* given set of host bindings has no errors.
*
* @param bindings set of host bindings to verify.
* @param sourceSpan source span where host bindings were defined.
* @returns array of errors associated with a given set of host bindings.
*/
export function verifyHostBindings(
bindings: ParsedHostBindings,
sourceSpan: ParseSourceSpan,
): ParseError[] {
// TODO: abstract out host bindings verification logic and use it instead of
// creating events and properties ASTs to detect errors (FW-996)
const bindingParser = makeBindingParser();
bindingParser.createDirectiveHostEventAsts(bindings.listeners, sourceSpan);
bindingParser.createBoundHostProperties(bindings.properties, sourceSpan);
return bindingParser.errors;
}
function compileStyles(styles: string[], selector: string, hostSelector: string): string[] {
const shadowCss = new ShadowCss();
return styles.map((style) => {
return shadowCss!.shimCssText(style, selector, hostSelector);
});
}
/**
* Encapsulates a CSS stylesheet with emulated view encapsulation.
* This allows a stylesheet to be used with an Angular component that
* is using the `ViewEncapsulation.Emulated` mode.
*
* @param style The content of a CSS stylesheet.
* @param componentIdentifier The identifier to use within the CSS rules.
* @returns The encapsulated content for the style.
*/ | {
"end_byte": 21934,
"start_byte": 13570,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/compiler.ts"
} |
angular/packages/compiler/src/render3/view/compiler.ts_21935_27090 | export function encapsulateStyle(style: string, componentIdentifier?: string): string {
const shadowCss = new ShadowCss();
const selector = componentIdentifier
? CONTENT_ATTR.replace(COMPONENT_VARIABLE, componentIdentifier)
: CONTENT_ATTR;
const hostSelector = componentIdentifier
? HOST_ATTR.replace(COMPONENT_VARIABLE, componentIdentifier)
: HOST_ATTR;
return shadowCss.shimCssText(style, selector, hostSelector);
}
function createHostDirectivesType(meta: R3DirectiveMetadata): o.Type {
if (!meta.hostDirectives?.length) {
return o.NONE_TYPE;
}
return o.expressionType(
o.literalArr(
meta.hostDirectives.map((hostMeta) =>
o.literalMap([
{key: 'directive', value: o.typeofExpr(hostMeta.directive.type), quoted: false},
{
key: 'inputs',
value: stringMapAsLiteralExpression(hostMeta.inputs || {}),
quoted: false,
},
{
key: 'outputs',
value: stringMapAsLiteralExpression(hostMeta.outputs || {}),
quoted: false,
},
]),
),
),
);
}
function createHostDirectivesFeatureArg(
hostDirectives: NonNullable<R3DirectiveMetadata['hostDirectives']>,
): o.Expression {
const expressions: o.Expression[] = [];
let hasForwardRef = false;
for (const current of hostDirectives) {
// Use a shorthand if there are no inputs or outputs.
if (!current.inputs && !current.outputs) {
expressions.push(current.directive.type);
} else {
const keys = [{key: 'directive', value: current.directive.type, quoted: false}];
if (current.inputs) {
const inputsLiteral = createHostDirectivesMappingArray(current.inputs);
if (inputsLiteral) {
keys.push({key: 'inputs', value: inputsLiteral, quoted: false});
}
}
if (current.outputs) {
const outputsLiteral = createHostDirectivesMappingArray(current.outputs);
if (outputsLiteral) {
keys.push({key: 'outputs', value: outputsLiteral, quoted: false});
}
}
expressions.push(o.literalMap(keys));
}
if (current.isForwardReference) {
hasForwardRef = true;
}
}
// If there's a forward reference, we generate a `function() { return [HostDir] }`,
// otherwise we can save some bytes by using a plain array, e.g. `[HostDir]`.
return hasForwardRef
? new o.FunctionExpr([], [new o.ReturnStatement(o.literalArr(expressions))])
: o.literalArr(expressions);
}
/**
* Converts an input/output mapping object literal into an array where the even keys are the
* public name of the binding and the odd ones are the name it was aliased to. E.g.
* `{inputOne: 'aliasOne', inputTwo: 'aliasTwo'}` will become
* `['inputOne', 'aliasOne', 'inputTwo', 'aliasTwo']`.
*
* This conversion is necessary, because hosts bind to the public name of the host directive and
* keeping the mapping in an object literal will break for apps using property renaming.
*/
export function createHostDirectivesMappingArray(
mapping: Record<string, string>,
): o.LiteralArrayExpr | null {
const elements: o.LiteralExpr[] = [];
for (const publicName in mapping) {
if (mapping.hasOwnProperty(publicName)) {
elements.push(o.literal(publicName), o.literal(mapping[publicName]));
}
}
return elements.length > 0 ? o.literalArr(elements) : null;
}
/**
* Compiles the dependency resolver function for a defer block.
*/
export function compileDeferResolverFunction(
meta: R3DeferResolverFunctionMetadata,
): o.ArrowFunctionExpr {
const depExpressions: o.Expression[] = [];
if (meta.mode === DeferBlockDepsEmitMode.PerBlock) {
for (const dep of meta.dependencies) {
if (dep.isDeferrable) {
// Callback function, e.g. `m () => m.MyCmp;`.
const innerFn = o.arrowFn(
// Default imports are always accessed through the `default` property.
[new o.FnParam('m', o.DYNAMIC_TYPE)],
o.variable('m').prop(dep.isDefaultImport ? 'default' : dep.symbolName),
);
// Dynamic import, e.g. `import('./a').then(...)`.
const importExpr = new o.DynamicImportExpr(dep.importPath!).prop('then').callFn([innerFn]);
depExpressions.push(importExpr);
} else {
// Non-deferrable symbol, just use a reference to the type. Note that it's important to
// go through `typeReference`, rather than `symbolName` in order to preserve the
// original reference within the source file.
depExpressions.push(dep.typeReference);
}
}
} else {
for (const {symbolName, importPath, isDefaultImport} of meta.dependencies) {
// Callback function, e.g. `m () => m.MyCmp;`.
const innerFn = o.arrowFn(
[new o.FnParam('m', o.DYNAMIC_TYPE)],
o.variable('m').prop(isDefaultImport ? 'default' : symbolName),
);
// Dynamic import, e.g. `import('./a').then(...)`.
const importExpr = new o.DynamicImportExpr(importPath).prop('then').callFn([innerFn]);
depExpressions.push(importExpr);
}
}
return o.arrowFn([], o.literalArr(depExpressions));
} | {
"end_byte": 27090,
"start_byte": 21935,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/compiler.ts"
} |
angular/packages/compiler/src/render3/view/i18n/meta.ts_0_2714 | /**
* @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.dev/license
*/
import {WhitespaceVisitor, visitAllWithSiblings} from '../../../ml_parser/html_whitespaces';
import {computeDecimalDigest, computeDigest, decimalDigest} from '../../../i18n/digest';
import * as i18n from '../../../i18n/i18n_ast';
import {createI18nMessageFactory, VisitNodeFn} from '../../../i18n/i18n_parser';
import {I18nError} from '../../../i18n/parse_util';
import * as html from '../../../ml_parser/ast';
import {
DEFAULT_CONTAINER_BLOCKS,
DEFAULT_INTERPOLATION_CONFIG,
InterpolationConfig,
} from '../../../ml_parser/defaults';
import {ParseTreeResult} from '../../../ml_parser/parser';
import * as o from '../../../output/output_ast';
import {isTrustedTypesSink} from '../../../schema/trusted_types_sinks';
import {hasI18nAttrs, I18N_ATTR, I18N_ATTR_PREFIX, icuFromI18nMessage} from './util';
export type I18nMeta = {
id?: string;
customId?: string;
legacyIds?: string[];
description?: string;
meaning?: string;
};
const setI18nRefs = (originalNodeMap: Map<html.Node, html.Node>): VisitNodeFn => {
return (trimmedNode, i18nNode) => {
// We need to set i18n properties on the original, untrimmed AST nodes. The i18n nodes needs to
// use the trimmed content for message IDs to make messages more stable to whitespace changes.
// But we don't want to actually trim the content, so we can't use the trimmed HTML AST for
// general code gen. Instead we map the trimmed HTML AST back to the original AST and then
// attach the i18n nodes so we get trimmed i18n nodes on the original (untrimmed) HTML AST.
const originalNode = originalNodeMap.get(trimmedNode) ?? trimmedNode;
if (originalNode instanceof html.NodeWithI18n) {
if (i18nNode instanceof i18n.IcuPlaceholder && originalNode.i18n instanceof i18n.Message) {
// This html node represents an ICU but this is a second processing pass, and the legacy id
// was computed in the previous pass and stored in the `i18n` property as a message.
// We are about to wipe out that property so capture the previous message to be reused when
// generating the message for this ICU later. See `_generateI18nMessage()`.
i18nNode.previousMessage = originalNode.i18n;
}
originalNode.i18n = i18nNode;
}
return i18nNode;
};
};
/**
* This visitor walks over HTML parse tree and converts information stored in
* i18n-related attributes ("i18n" and "i18n-*") into i18n meta object that is
* stored with other element's and attribute's information.
*/ | {
"end_byte": 2714,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/i18n/meta.ts"
} |
angular/packages/compiler/src/render3/view/i18n/meta.ts_2715_11527 | export class I18nMetaVisitor implements html.Visitor {
// whether visited nodes contain i18n information
public hasI18nMeta: boolean = false;
private _errors: I18nError[] = [];
constructor(
private interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG,
private keepI18nAttrs = false,
private enableI18nLegacyMessageIdFormat = false,
private containerBlocks: Set<string> = DEFAULT_CONTAINER_BLOCKS,
private readonly preserveSignificantWhitespace: boolean = true,
// When dropping significant whitespace we need to retain empty tokens or
// else we won't be able to reuse source spans because empty tokens would be
// removed and cause a mismatch. Unfortunately this still needs to be
// configurable and sometimes needs to be set independently in order to make
// sure the number of nodes don't change between parses, even when
// `preserveSignificantWhitespace` changes.
private readonly retainEmptyTokens: boolean = !preserveSignificantWhitespace,
) {}
private _generateI18nMessage(
nodes: html.Node[],
meta: string | i18n.I18nMeta = '',
visitNodeFn?: VisitNodeFn,
): i18n.Message {
const {meaning, description, customId} = this._parseMetadata(meta);
const createI18nMessage = createI18nMessageFactory(
this.interpolationConfig,
this.containerBlocks,
this.retainEmptyTokens,
/* preserveExpressionWhitespace */ this.preserveSignificantWhitespace,
);
const message = createI18nMessage(nodes, meaning, description, customId, visitNodeFn);
this._setMessageId(message, meta);
this._setLegacyIds(message, meta);
return message;
}
visitAllWithErrors(nodes: html.Node[]): ParseTreeResult {
const result = nodes.map((node) => node.visit(this, null));
return new ParseTreeResult(result, this._errors);
}
visitElement(element: html.Element): any {
let message: i18n.Message | undefined = undefined;
if (hasI18nAttrs(element)) {
this.hasI18nMeta = true;
const attrs: html.Attribute[] = [];
const attrsMeta: {[key: string]: string} = {};
for (const attr of element.attrs) {
if (attr.name === I18N_ATTR) {
// root 'i18n' node attribute
const i18n = element.i18n || attr.value;
// Generate a new AST with whitespace trimmed, but also generate a map
// to correlate each new node to its original so we can apply i18n
// information to the original node based on the trimmed content.
//
// `WhitespaceVisitor` removes *insignificant* whitespace as well as
// significant whitespace. Enabling this visitor should be conditional
// on `preserveWhitespace` rather than `preserveSignificantWhitespace`,
// however this would be a breaking change for existing behavior where
// `preserveWhitespace` was not respected correctly when generating
// message IDs. This is really a bug but one we need to keep to maintain
// backwards compatibility.
const originalNodeMap = new Map<html.Node, html.Node>();
const trimmedNodes = this.preserveSignificantWhitespace
? element.children
: visitAllWithSiblings(
new WhitespaceVisitor(false /* preserveSignificantWhitespace */, originalNodeMap),
element.children,
);
message = this._generateI18nMessage(trimmedNodes, i18n, setI18nRefs(originalNodeMap));
if (message.nodes.length === 0) {
// Ignore the message if it is empty.
message = undefined;
}
// Store the message on the element
element.i18n = message;
} else if (attr.name.startsWith(I18N_ATTR_PREFIX)) {
// 'i18n-*' attributes
const name = attr.name.slice(I18N_ATTR_PREFIX.length);
if (isTrustedTypesSink(element.name, name)) {
this._reportError(
attr,
`Translating attribute '${name}' is disallowed for security reasons.`,
);
} else {
attrsMeta[name] = attr.value;
}
} else {
// non-i18n attributes
attrs.push(attr);
}
}
// set i18n meta for attributes
if (Object.keys(attrsMeta).length) {
for (const attr of attrs) {
const meta = attrsMeta[attr.name];
// do not create translation for empty attributes
if (meta !== undefined && attr.value) {
attr.i18n = this._generateI18nMessage([attr], attr.i18n || meta);
}
}
}
if (!this.keepI18nAttrs) {
// update element's attributes,
// keeping only non-i18n related ones
element.attrs = attrs;
}
}
html.visitAll(this, element.children, message);
return element;
}
visitExpansion(expansion: html.Expansion, currentMessage: i18n.Message | null): any {
let message;
const meta = expansion.i18n;
this.hasI18nMeta = true;
if (meta instanceof i18n.IcuPlaceholder) {
// set ICU placeholder name (e.g. "ICU_1"),
// generated while processing root element contents,
// so we can reference it when we output translation
const name = meta.name;
message = this._generateI18nMessage([expansion], meta);
const icu = icuFromI18nMessage(message);
icu.name = name;
if (currentMessage !== null) {
// Also update the placeholderToMessage map with this new message
currentMessage.placeholderToMessage[name] = message;
}
} else {
// ICU is a top level message, try to use metadata from container element if provided via
// `context` argument. Note: context may not be available for standalone ICUs (without
// wrapping element), so fallback to ICU metadata in this case.
message = this._generateI18nMessage([expansion], currentMessage || meta);
}
expansion.i18n = message;
return expansion;
}
visitText(text: html.Text): any {
return text;
}
visitAttribute(attribute: html.Attribute): any {
return attribute;
}
visitComment(comment: html.Comment): any {
return comment;
}
visitExpansionCase(expansionCase: html.ExpansionCase): any {
return expansionCase;
}
visitBlock(block: html.Block, context: any) {
html.visitAll(this, block.children, context);
return block;
}
visitBlockParameter(parameter: html.BlockParameter, context: any) {
return parameter;
}
visitLetDeclaration(decl: html.LetDeclaration, context: any) {
return decl;
}
/**
* Parse the general form `meta` passed into extract the explicit metadata needed to create a
* `Message`.
*
* There are three possibilities for the `meta` variable
* 1) a string from an `i18n` template attribute: parse it to extract the metadata values.
* 2) a `Message` from a previous processing pass: reuse the metadata values in the message.
* 4) other: ignore this and just process the message metadata as normal
*
* @param meta the bucket that holds information about the message
* @returns the parsed metadata.
*/
private _parseMetadata(meta: string | i18n.I18nMeta): I18nMeta {
return typeof meta === 'string'
? parseI18nMeta(meta)
: meta instanceof i18n.Message
? meta
: {};
}
/**
* Generate (or restore) message id if not specified already.
*/
private _setMessageId(message: i18n.Message, meta: string | i18n.I18nMeta): void {
if (!message.id) {
message.id = (meta instanceof i18n.Message && meta.id) || decimalDigest(message);
}
}
/**
* Update the `message` with a `legacyId` if necessary.
*
* @param message the message whose legacy id should be set
* @param meta information about the message being processed
*/
private _setLegacyIds(message: i18n.Message, meta: string | i18n.I18nMeta): void {
if (this.enableI18nLegacyMessageIdFormat) {
message.legacyIds = [computeDigest(message), computeDecimalDigest(message)];
} else if (typeof meta !== 'string') {
// This occurs if we are doing the 2nd pass after whitespace removal (see `parseTemplate()` in
// `packages/compiler/src/render3/view/template.ts`).
// In that case we want to reuse the legacy message generated in the 1st pass (see
// `setI18nRefs()`).
const previousMessage =
meta instanceof i18n.Message
? meta
: meta instanceof i18n.IcuPlaceholder
? meta.previousMessage
: undefined;
message.legacyIds = previousMessage ? previousMessage.legacyIds : [];
}
}
private _reportError(node: html.Node, msg: string): void {
this._errors.push(new I18nError(node.sourceSpan, msg));
}
} | {
"end_byte": 11527,
"start_byte": 2715,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/i18n/meta.ts"
} |
angular/packages/compiler/src/render3/view/i18n/meta.ts_11529_13237 | /** I18n separators for metadata **/
const I18N_MEANING_SEPARATOR = '|';
const I18N_ID_SEPARATOR = '@@';
/**
* Parses i18n metas like:
* - "@@id",
* - "description[@@id]",
* - "meaning|description[@@id]"
* and returns an object with parsed output.
*
* @param meta String that represents i18n meta
* @returns Object with id, meaning and description fields
*/
export function parseI18nMeta(meta: string = ''): I18nMeta {
let customId: string | undefined;
let meaning: string | undefined;
let description: string | undefined;
meta = meta.trim();
if (meta) {
const idIndex = meta.indexOf(I18N_ID_SEPARATOR);
const descIndex = meta.indexOf(I18N_MEANING_SEPARATOR);
let meaningAndDesc: string;
[meaningAndDesc, customId] =
idIndex > -1 ? [meta.slice(0, idIndex), meta.slice(idIndex + 2)] : [meta, ''];
[meaning, description] =
descIndex > -1
? [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)]
: ['', meaningAndDesc];
}
return {customId, meaning, description};
}
// Converts i18n meta information for a message (id, description, meaning)
// to a JsDoc statement formatted as expected by the Closure compiler.
export function i18nMetaToJSDoc(meta: I18nMeta): o.JSDocComment {
const tags: o.JSDocTag[] = [];
if (meta.description) {
tags.push({tagName: o.JSDocTagName.Desc, text: meta.description});
} else {
// Suppress the JSCompiler warning that a `@desc` was not given for this message.
tags.push({tagName: o.JSDocTagName.Suppress, text: '{msgDescriptions}'});
}
if (meta.meaning) {
tags.push({tagName: o.JSDocTagName.Meaning, text: meta.meaning});
}
return o.jsDocComment(tags);
} | {
"end_byte": 13237,
"start_byte": 11529,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/i18n/meta.ts"
} |
angular/packages/compiler/src/render3/view/i18n/localize_utils.ts_0_6235 | /**
* @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.dev/license
*/
import * as i18n from '../../../i18n/i18n_ast';
import * as o from '../../../output/output_ast';
import {ParseLocation, ParseSourceSpan} from '../../../parse_util';
import {serializeIcuNode} from './icu_serializer';
import {formatI18nPlaceholderName} from './util';
export function createLocalizeStatements(
variable: o.ReadVarExpr,
message: i18n.Message,
params: {[name: string]: o.Expression},
): o.Statement[] {
const {messageParts, placeHolders} = serializeI18nMessageForLocalize(message);
const sourceSpan = getSourceSpan(message);
const expressions = placeHolders.map((ph) => params[ph.text]);
const localizedString = o.localizedString(
message,
messageParts,
placeHolders,
expressions,
sourceSpan,
);
const variableInitialization = variable.set(localizedString);
return [new o.ExpressionStatement(variableInitialization)];
}
/**
* This visitor walks over an i18n tree, capturing literal strings and placeholders.
*
* The result can be used for generating the `$localize` tagged template literals.
*/
class LocalizeSerializerVisitor implements i18n.Visitor {
constructor(
private placeholderToMessage: {[phName: string]: i18n.Message},
private pieces: o.MessagePiece[],
) {}
visitText(text: i18n.Text): any {
if (this.pieces[this.pieces.length - 1] instanceof o.LiteralPiece) {
// Two literal pieces in a row means that there was some comment node in-between.
this.pieces[this.pieces.length - 1].text += text.value;
} else {
const sourceSpan = new ParseSourceSpan(
text.sourceSpan.fullStart,
text.sourceSpan.end,
text.sourceSpan.fullStart,
text.sourceSpan.details,
);
this.pieces.push(new o.LiteralPiece(text.value, sourceSpan));
}
}
visitContainer(container: i18n.Container): any {
container.children.forEach((child) => child.visit(this));
}
visitIcu(icu: i18n.Icu): any {
this.pieces.push(new o.LiteralPiece(serializeIcuNode(icu), icu.sourceSpan));
}
visitTagPlaceholder(ph: i18n.TagPlaceholder): any {
this.pieces.push(
this.createPlaceholderPiece(ph.startName, ph.startSourceSpan ?? ph.sourceSpan),
);
if (!ph.isVoid) {
ph.children.forEach((child) => child.visit(this));
this.pieces.push(
this.createPlaceholderPiece(ph.closeName, ph.endSourceSpan ?? ph.sourceSpan),
);
}
}
visitPlaceholder(ph: i18n.Placeholder): any {
this.pieces.push(this.createPlaceholderPiece(ph.name, ph.sourceSpan));
}
visitBlockPlaceholder(ph: i18n.BlockPlaceholder): any {
this.pieces.push(
this.createPlaceholderPiece(ph.startName, ph.startSourceSpan ?? ph.sourceSpan),
);
ph.children.forEach((child) => child.visit(this));
this.pieces.push(this.createPlaceholderPiece(ph.closeName, ph.endSourceSpan ?? ph.sourceSpan));
}
visitIcuPlaceholder(ph: i18n.IcuPlaceholder): any {
this.pieces.push(
this.createPlaceholderPiece(ph.name, ph.sourceSpan, this.placeholderToMessage[ph.name]),
);
}
private createPlaceholderPiece(
name: string,
sourceSpan: ParseSourceSpan,
associatedMessage?: i18n.Message,
): o.PlaceholderPiece {
return new o.PlaceholderPiece(
formatI18nPlaceholderName(name, /* useCamelCase */ false),
sourceSpan,
associatedMessage,
);
}
}
/**
* Serialize an i18n message into two arrays: messageParts and placeholders.
*
* These arrays will be used to generate `$localize` tagged template literals.
*
* @param message The message to be serialized.
* @returns an object containing the messageParts and placeholders.
*/
export function serializeI18nMessageForLocalize(message: i18n.Message): {
messageParts: o.LiteralPiece[];
placeHolders: o.PlaceholderPiece[];
} {
const pieces: o.MessagePiece[] = [];
const serializerVisitor = new LocalizeSerializerVisitor(message.placeholderToMessage, pieces);
message.nodes.forEach((node) => node.visit(serializerVisitor));
return processMessagePieces(pieces);
}
function getSourceSpan(message: i18n.Message): ParseSourceSpan {
const startNode = message.nodes[0];
const endNode = message.nodes[message.nodes.length - 1];
return new ParseSourceSpan(
startNode.sourceSpan.fullStart,
endNode.sourceSpan.end,
startNode.sourceSpan.fullStart,
startNode.sourceSpan.details,
);
}
/**
* Convert the list of serialized MessagePieces into two arrays.
*
* One contains the literal string pieces and the other the placeholders that will be replaced by
* expressions when rendering `$localize` tagged template literals.
*
* @param pieces The pieces to process.
* @returns an object containing the messageParts and placeholders.
*/
function processMessagePieces(pieces: o.MessagePiece[]): {
messageParts: o.LiteralPiece[];
placeHolders: o.PlaceholderPiece[];
} {
const messageParts: o.LiteralPiece[] = [];
const placeHolders: o.PlaceholderPiece[] = [];
if (pieces[0] instanceof o.PlaceholderPiece) {
// The first piece was a placeholder so we need to add an initial empty message part.
messageParts.push(createEmptyMessagePart(pieces[0].sourceSpan.start));
}
for (let i = 0; i < pieces.length; i++) {
const part = pieces[i];
if (part instanceof o.LiteralPiece) {
messageParts.push(part);
} else {
placeHolders.push(part);
if (pieces[i - 1] instanceof o.PlaceholderPiece) {
// There were two placeholders in a row, so we need to add an empty message part.
messageParts.push(createEmptyMessagePart(pieces[i - 1].sourceSpan.end));
}
}
}
if (pieces[pieces.length - 1] instanceof o.PlaceholderPiece) {
// The last piece was a placeholder so we need to add a final empty message part.
messageParts.push(createEmptyMessagePart(pieces[pieces.length - 1].sourceSpan.end));
}
return {messageParts, placeHolders};
}
function createEmptyMessagePart(location: ParseLocation): o.LiteralPiece {
return new o.LiteralPiece('', new ParseSourceSpan(location, location));
}
| {
"end_byte": 6235,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/i18n/localize_utils.ts"
} |
angular/packages/compiler/src/render3/view/i18n/get_msg_utils.ts_0_5265 | /**
* @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.dev/license
*/
import * as i18n from '../../../i18n/i18n_ast';
import {mapLiteral} from '../../../output/map_util';
import * as o from '../../../output/output_ast';
import {serializeIcuNode} from './icu_serializer';
import {i18nMetaToJSDoc} from './meta';
import {formatI18nPlaceholderName, formatI18nPlaceholderNamesInMap} from './util';
/** Closure uses `goog.getMsg(message)` to lookup translations */
const GOOG_GET_MSG = 'goog.getMsg';
/**
* Generates a `goog.getMsg()` statement and reassignment. The template:
*
* ```html
* <div i18n>Sent from {{ sender }} to <span class="receiver">{{ receiver }}</span></div>
* ```
*
* Generates:
*
* ```typescript
* const MSG_FOO = goog.getMsg(
* // Message template.
* 'Sent from {$interpolation} to {$startTagSpan}{$interpolation_1}{$closeTagSpan}.',
* // Placeholder values, set to magic strings which get replaced by the Angular runtime.
* {
* 'interpolation': '\uFFFD0\uFFFD',
* 'startTagSpan': '\uFFFD1\uFFFD',
* 'interpolation_1': '\uFFFD2\uFFFD',
* 'closeTagSpan': '\uFFFD3\uFFFD',
* },
* // Options bag.
* {
* // Maps each placeholder to the original Angular source code which generates it's value.
* original_code: {
* 'interpolation': '{{ sender }}',
* 'startTagSpan': '<span class="receiver">',
* 'interpolation_1': '{{ receiver }}',
* 'closeTagSpan': '</span>',
* },
* },
* );
* const I18N_0 = MSG_FOO;
* ```
*/
export function createGoogleGetMsgStatements(
variable: o.ReadVarExpr,
message: i18n.Message,
closureVar: o.ReadVarExpr,
placeholderValues: {[name: string]: o.Expression},
): o.Statement[] {
const messageString = serializeI18nMessageForGetMsg(message);
const args = [o.literal(messageString) as o.Expression];
if (Object.keys(placeholderValues).length) {
// Message template parameters containing the magic strings replaced by the Angular runtime with
// real data, e.g. `{'interpolation': '\uFFFD0\uFFFD'}`.
args.push(
mapLiteral(
formatI18nPlaceholderNamesInMap(placeholderValues, true /* useCamelCase */),
true /* quoted */,
),
);
// Message options object, which contains original source code for placeholders (as they are
// present in a template, e.g.
// `{original_code: {'interpolation': '{{ name }}', 'startTagSpan': '<span>'}}`.
args.push(
mapLiteral({
original_code: o.literalMap(
Object.keys(placeholderValues).map((param) => ({
key: formatI18nPlaceholderName(param),
quoted: true,
value: message.placeholders[param]
? // Get source span for typical placeholder if it exists.
o.literal(message.placeholders[param].sourceSpan.toString())
: // Otherwise must be an ICU expression, get it's source span.
o.literal(
message.placeholderToMessage[param].nodes
.map((node) => node.sourceSpan.toString())
.join(''),
),
})),
),
}),
);
}
// /**
// * @desc description of message
// * @meaning meaning of message
// */
// const MSG_... = goog.getMsg(..);
// I18N_X = MSG_...;
const googGetMsgStmt = closureVar.set(o.variable(GOOG_GET_MSG).callFn(args)).toConstDecl();
googGetMsgStmt.addLeadingComment(i18nMetaToJSDoc(message));
const i18nAssignmentStmt = new o.ExpressionStatement(variable.set(closureVar));
return [googGetMsgStmt, i18nAssignmentStmt];
}
/**
* This visitor walks over i18n tree and generates its string representation, including ICUs and
* placeholders in `{$placeholder}` (for plain messages) or `{PLACEHOLDER}` (inside ICUs) format.
*/
class GetMsgSerializerVisitor implements i18n.Visitor {
private formatPh(value: string): string {
return `{$${formatI18nPlaceholderName(value)}}`;
}
visitText(text: i18n.Text): any {
return text.value;
}
visitContainer(container: i18n.Container): any {
return container.children.map((child) => child.visit(this)).join('');
}
visitIcu(icu: i18n.Icu): any {
return serializeIcuNode(icu);
}
visitTagPlaceholder(ph: i18n.TagPlaceholder): any {
return ph.isVoid
? this.formatPh(ph.startName)
: `${this.formatPh(ph.startName)}${ph.children
.map((child) => child.visit(this))
.join('')}${this.formatPh(ph.closeName)}`;
}
visitPlaceholder(ph: i18n.Placeholder): any {
return this.formatPh(ph.name);
}
visitBlockPlaceholder(ph: i18n.BlockPlaceholder): any {
return `${this.formatPh(ph.startName)}${ph.children
.map((child) => child.visit(this))
.join('')}${this.formatPh(ph.closeName)}`;
}
visitIcuPlaceholder(ph: i18n.IcuPlaceholder, context?: any): any {
return this.formatPh(ph.name);
}
}
const serializerVisitor = new GetMsgSerializerVisitor();
export function serializeI18nMessageForGetMsg(message: i18n.Message): string {
return message.nodes.map((node) => node.visit(serializerVisitor, null)).join('');
}
| {
"end_byte": 5265,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/i18n/get_msg_utils.ts"
} |
angular/packages/compiler/src/render3/view/i18n/icu_serializer.ts_0_1753 | /**
* @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.dev/license
*/
import * as i18n from '../../../i18n/i18n_ast';
import {formatI18nPlaceholderName} from './util';
class IcuSerializerVisitor implements i18n.Visitor {
visitText(text: i18n.Text): any {
return text.value;
}
visitContainer(container: i18n.Container): any {
return container.children.map((child) => child.visit(this)).join('');
}
visitIcu(icu: i18n.Icu): any {
const strCases = Object.keys(icu.cases).map(
(k: string) => `${k} {${icu.cases[k].visit(this)}}`,
);
const result = `{${icu.expressionPlaceholder}, ${icu.type}, ${strCases.join(' ')}}`;
return result;
}
visitTagPlaceholder(ph: i18n.TagPlaceholder): any {
return ph.isVoid
? this.formatPh(ph.startName)
: `${this.formatPh(ph.startName)}${ph.children
.map((child) => child.visit(this))
.join('')}${this.formatPh(ph.closeName)}`;
}
visitPlaceholder(ph: i18n.Placeholder): any {
return this.formatPh(ph.name);
}
visitBlockPlaceholder(ph: i18n.BlockPlaceholder): any {
return `${this.formatPh(ph.startName)}${ph.children
.map((child) => child.visit(this))
.join('')}${this.formatPh(ph.closeName)}`;
}
visitIcuPlaceholder(ph: i18n.IcuPlaceholder, context?: any): any {
return this.formatPh(ph.name);
}
private formatPh(value: string): string {
return `{${formatI18nPlaceholderName(value, /* useCamelCase */ false)}}`;
}
}
const serializer = new IcuSerializerVisitor();
export function serializeIcuNode(icu: i18n.Icu): string {
return icu.visit(serializer);
}
| {
"end_byte": 1753,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/i18n/icu_serializer.ts"
} |
angular/packages/compiler/src/render3/view/i18n/util.ts_0_3117 | /**
* @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.dev/license
*/
import * as i18n from '../../../i18n/i18n_ast';
import {toPublicName} from '../../../i18n/serializers/xmb';
import * as html from '../../../ml_parser/ast';
import * as o from '../../../output/output_ast';
/** Name of the i18n attributes **/
export const I18N_ATTR = 'i18n';
export const I18N_ATTR_PREFIX = 'i18n-';
/** Prefix of var expressions used in ICUs */
export const I18N_ICU_VAR_PREFIX = 'VAR_';
export function isI18nAttribute(name: string): boolean {
return name === I18N_ATTR || name.startsWith(I18N_ATTR_PREFIX);
}
export function hasI18nAttrs(element: html.Element): boolean {
return element.attrs.some((attr: html.Attribute) => isI18nAttribute(attr.name));
}
export function icuFromI18nMessage(message: i18n.Message) {
return message.nodes[0] as i18n.IcuPlaceholder;
}
export function placeholdersToParams(placeholders: Map<string, string[]>): {
[name: string]: o.LiteralExpr;
} {
const params: {[name: string]: o.LiteralExpr} = {};
placeholders.forEach((values: string[], key: string) => {
params[key] = o.literal(values.length > 1 ? `[${values.join('|')}]` : values[0]);
});
return params;
}
/**
* Format the placeholder names in a map of placeholders to expressions.
*
* The placeholder names are converted from "internal" format (e.g. `START_TAG_DIV_1`) to "external"
* format (e.g. `startTagDiv_1`).
*
* @param params A map of placeholder names to expressions.
* @param useCamelCase whether to camelCase the placeholder name when formatting.
* @returns A new map of formatted placeholder names to expressions.
*/
export function formatI18nPlaceholderNamesInMap(
params: {[name: string]: o.Expression} = {},
useCamelCase: boolean,
) {
const _params: {[key: string]: o.Expression} = {};
if (params && Object.keys(params).length) {
Object.keys(params).forEach(
(key) => (_params[formatI18nPlaceholderName(key, useCamelCase)] = params[key]),
);
}
return _params;
}
/**
* Converts internal placeholder names to public-facing format
* (for example to use in goog.getMsg call).
* Example: `START_TAG_DIV_1` is converted to `startTagDiv_1`.
*
* @param name The placeholder name that should be formatted
* @returns Formatted placeholder name
*/
export function formatI18nPlaceholderName(name: string, useCamelCase: boolean = true): string {
const publicName = toPublicName(name);
if (!useCamelCase) {
return publicName;
}
const chunks = publicName.split('_');
if (chunks.length === 1) {
// if no "_" found - just lowercase the value
return name.toLowerCase();
}
let postfix;
// eject last element if it's a number
if (/^\d+$/.test(chunks[chunks.length - 1])) {
postfix = chunks.pop();
}
let raw = chunks.shift()!.toLowerCase();
if (chunks.length) {
raw += chunks.map((c) => c.charAt(0).toUpperCase() + c.slice(1).toLowerCase()).join('');
}
return postfix ? `${raw}_${postfix}` : raw;
}
| {
"end_byte": 3117,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/view/i18n/util.ts"
} |
angular/packages/compiler/src/expression_parser/serializer.ts_0_5475 | /**
* @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.dev/license
*/
import * as expr from './ast';
/** Serializes the given AST into a normalized string format. */
export function serialize(expression: expr.ASTWithSource): string {
return expression.visit(new SerializeExpressionVisitor());
}
class SerializeExpressionVisitor implements expr.AstVisitor {
visitUnary(ast: expr.Unary, context: any): string {
return `${ast.operator}${ast.expr.visit(this, context)}`;
}
visitBinary(ast: expr.Binary, context: any): string {
return `${ast.left.visit(this, context)} ${ast.operation} ${ast.right.visit(this, context)}`;
}
visitChain(ast: expr.Chain, context: any): string {
return ast.expressions.map((e) => e.visit(this, context)).join('; ');
}
visitConditional(ast: expr.Conditional, context: any): string {
return `${ast.condition.visit(this, context)} ? ${ast.trueExp.visit(
this,
context,
)} : ${ast.falseExp.visit(this, context)}`;
}
visitThisReceiver(): string {
return 'this';
}
visitImplicitReceiver(): string {
return '';
}
visitInterpolation(ast: expr.Interpolation, context: any): string {
return interleave(
ast.strings,
ast.expressions.map((e) => e.visit(this, context)),
).join('');
}
visitKeyedRead(ast: expr.KeyedRead, context: any): string {
return `${ast.receiver.visit(this, context)}[${ast.key.visit(this, context)}]`;
}
visitKeyedWrite(ast: expr.KeyedWrite, context: any): string {
return `${ast.receiver.visit(this, context)}[${ast.key.visit(
this,
context,
)}] = ${ast.value.visit(this, context)}`;
}
visitLiteralArray(ast: expr.LiteralArray, context: any): string {
return `[${ast.expressions.map((e) => e.visit(this, context)).join(', ')}]`;
}
visitLiteralMap(ast: expr.LiteralMap, context: any): string {
return `{${zip(
ast.keys.map((literal) => (literal.quoted ? `'${literal.key}'` : literal.key)),
ast.values.map((value) => value.visit(this, context)),
)
.map(([key, value]) => `${key}: ${value}`)
.join(', ')}}`;
}
visitLiteralPrimitive(ast: expr.LiteralPrimitive): string {
if (ast.value === null) return 'null';
switch (typeof ast.value) {
case 'number':
case 'boolean':
return ast.value.toString();
case 'undefined':
return 'undefined';
case 'string':
return `'${ast.value.replace(/'/g, `\\'`)}'`;
default:
throw new Error(`Unsupported primitive type: ${ast.value}`);
}
}
visitPipe(ast: expr.BindingPipe, context: any): string {
return `${ast.exp.visit(this, context)} | ${ast.name}`;
}
visitPrefixNot(ast: expr.PrefixNot, context: any): string {
return `!${ast.expression.visit(this, context)}`;
}
visitNonNullAssert(ast: expr.NonNullAssert, context: any): string {
return `${ast.expression.visit(this, context)}!`;
}
visitPropertyRead(ast: expr.PropertyRead, context: any): string {
if (ast.receiver instanceof expr.ImplicitReceiver) {
return ast.name;
} else {
return `${ast.receiver.visit(this, context)}.${ast.name}`;
}
}
visitPropertyWrite(ast: expr.PropertyWrite, context: any): string {
if (ast.receiver instanceof expr.ImplicitReceiver) {
return `${ast.name} = ${ast.value.visit(this, context)}`;
} else {
return `${ast.receiver.visit(this, context)}.${ast.name} = ${ast.value.visit(this, context)}`;
}
}
visitSafePropertyRead(ast: expr.SafePropertyRead, context: any): string {
return `${ast.receiver.visit(this, context)}?.${ast.name}`;
}
visitSafeKeyedRead(ast: expr.SafeKeyedRead, context: any): string {
return `${ast.receiver.visit(this, context)}?.[${ast.key.visit(this, context)}]`;
}
visitCall(ast: expr.Call, context: any): string {
return `${ast.receiver.visit(this, context)}(${ast.args
.map((e) => e.visit(this, context))
.join(', ')})`;
}
visitSafeCall(ast: expr.SafeCall, context: any): string {
return `${ast.receiver.visit(this, context)}?.(${ast.args
.map((e) => e.visit(this, context))
.join(', ')})`;
}
visitTypeofExpresion(ast: expr.TypeofExpression, context: any) {
return `typeof ${ast.expression.visit(this, context)}`;
}
visitASTWithSource(ast: expr.ASTWithSource, context: any): string {
return ast.ast.visit(this, context);
}
}
/** Zips the two input arrays into a single array of pairs of elements at the same index. */
function zip<Left, Right>(left: Left[], right: Right[]): Array<[Left, Right]> {
if (left.length !== right.length) throw new Error('Array lengths must match');
return left.map((l, i) => [l, right[i]]);
}
/**
* Interleaves the two arrays, starting with the first item on the left, then the first item
* on the right, second item from the left, and so on. When the first array's items are exhausted,
* the remaining items from the other array are included with no interleaving.
*/
function interleave<Left, Right>(left: Left[], right: Right[]): Array<Left | Right> {
const result: Array<Left | Right> = [];
for (let index = 0; index < Math.max(left.length, right.length); index++) {
if (index < left.length) result.push(left[index]);
if (index < right.length) result.push(right[index]);
}
return result;
}
| {
"end_byte": 5475,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/serializer.ts"
} |
angular/packages/compiler/src/expression_parser/lexer.ts_0_4254 | /**
* @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.dev/license
*/
import * as chars from '../chars';
export enum TokenType {
Character,
Identifier,
PrivateIdentifier,
Keyword,
String,
Operator,
Number,
Error,
}
const KEYWORDS = [
'var',
'let',
'as',
'null',
'undefined',
'true',
'false',
'if',
'else',
'this',
'typeof',
];
export class Lexer {
tokenize(text: string): Token[] {
const scanner = new _Scanner(text);
const tokens: Token[] = [];
let token = scanner.scanToken();
while (token != null) {
tokens.push(token);
token = scanner.scanToken();
}
return tokens;
}
}
export class Token {
constructor(
public index: number,
public end: number,
public type: TokenType,
public numValue: number,
public strValue: string,
) {}
isCharacter(code: number): boolean {
return this.type == TokenType.Character && this.numValue == code;
}
isNumber(): boolean {
return this.type == TokenType.Number;
}
isString(): boolean {
return this.type == TokenType.String;
}
isOperator(operator: string): boolean {
return this.type == TokenType.Operator && this.strValue == operator;
}
isIdentifier(): boolean {
return this.type == TokenType.Identifier;
}
isPrivateIdentifier(): boolean {
return this.type == TokenType.PrivateIdentifier;
}
isKeyword(): boolean {
return this.type == TokenType.Keyword;
}
isKeywordLet(): boolean {
return this.type == TokenType.Keyword && this.strValue == 'let';
}
isKeywordAs(): boolean {
return this.type == TokenType.Keyword && this.strValue == 'as';
}
isKeywordNull(): boolean {
return this.type == TokenType.Keyword && this.strValue == 'null';
}
isKeywordUndefined(): boolean {
return this.type == TokenType.Keyword && this.strValue == 'undefined';
}
isKeywordTrue(): boolean {
return this.type == TokenType.Keyword && this.strValue == 'true';
}
isKeywordFalse(): boolean {
return this.type == TokenType.Keyword && this.strValue == 'false';
}
isKeywordThis(): boolean {
return this.type == TokenType.Keyword && this.strValue == 'this';
}
isKeywordTypeof(): boolean {
return this.type === TokenType.Keyword && this.strValue === 'typeof';
}
isError(): boolean {
return this.type == TokenType.Error;
}
toNumber(): number {
return this.type == TokenType.Number ? this.numValue : -1;
}
toString(): string | null {
switch (this.type) {
case TokenType.Character:
case TokenType.Identifier:
case TokenType.Keyword:
case TokenType.Operator:
case TokenType.PrivateIdentifier:
case TokenType.String:
case TokenType.Error:
return this.strValue;
case TokenType.Number:
return this.numValue.toString();
default:
return null;
}
}
}
function newCharacterToken(index: number, end: number, code: number): Token {
return new Token(index, end, TokenType.Character, code, String.fromCharCode(code));
}
function newIdentifierToken(index: number, end: number, text: string): Token {
return new Token(index, end, TokenType.Identifier, 0, text);
}
function newPrivateIdentifierToken(index: number, end: number, text: string): Token {
return new Token(index, end, TokenType.PrivateIdentifier, 0, text);
}
function newKeywordToken(index: number, end: number, text: string): Token {
return new Token(index, end, TokenType.Keyword, 0, text);
}
function newOperatorToken(index: number, end: number, text: string): Token {
return new Token(index, end, TokenType.Operator, 0, text);
}
function newStringToken(index: number, end: number, text: string): Token {
return new Token(index, end, TokenType.String, 0, text);
}
function newNumberToken(index: number, end: number, n: number): Token {
return new Token(index, end, TokenType.Number, n, '');
}
function newErrorToken(index: number, end: number, message: string): Token {
return new Token(index, end, TokenType.Error, 0, message);
}
export const EOF: Token = new Token(-1, -1, TokenType.Character, 0, ''); | {
"end_byte": 4254,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/lexer.ts"
} |
angular/packages/compiler/src/expression_parser/lexer.ts_4256_12537 | class _Scanner {
length: number;
peek: number = 0;
index: number = -1;
constructor(public input: string) {
this.length = input.length;
this.advance();
}
advance() {
this.peek = ++this.index >= this.length ? chars.$EOF : this.input.charCodeAt(this.index);
}
scanToken(): Token | null {
const input = this.input,
length = this.length;
let peek = this.peek,
index = this.index;
// Skip whitespace.
while (peek <= chars.$SPACE) {
if (++index >= length) {
peek = chars.$EOF;
break;
} else {
peek = input.charCodeAt(index);
}
}
this.peek = peek;
this.index = index;
if (index >= length) {
return null;
}
// Handle identifiers and numbers.
if (isIdentifierStart(peek)) return this.scanIdentifier();
if (chars.isDigit(peek)) return this.scanNumber(index);
const start: number = index;
switch (peek) {
case chars.$PERIOD:
this.advance();
return chars.isDigit(this.peek)
? this.scanNumber(start)
: newCharacterToken(start, this.index, chars.$PERIOD);
case chars.$LPAREN:
case chars.$RPAREN:
case chars.$LBRACE:
case chars.$RBRACE:
case chars.$LBRACKET:
case chars.$RBRACKET:
case chars.$COMMA:
case chars.$COLON:
case chars.$SEMICOLON:
return this.scanCharacter(start, peek);
case chars.$SQ:
case chars.$DQ:
return this.scanString();
case chars.$HASH:
return this.scanPrivateIdentifier();
case chars.$PLUS:
case chars.$MINUS:
case chars.$STAR:
case chars.$SLASH:
case chars.$PERCENT:
case chars.$CARET:
return this.scanOperator(start, String.fromCharCode(peek));
case chars.$QUESTION:
return this.scanQuestion(start);
case chars.$LT:
case chars.$GT:
return this.scanComplexOperator(start, String.fromCharCode(peek), chars.$EQ, '=');
case chars.$BANG:
case chars.$EQ:
return this.scanComplexOperator(
start,
String.fromCharCode(peek),
chars.$EQ,
'=',
chars.$EQ,
'=',
);
case chars.$AMPERSAND:
return this.scanComplexOperator(start, '&', chars.$AMPERSAND, '&');
case chars.$BAR:
return this.scanComplexOperator(start, '|', chars.$BAR, '|');
case chars.$NBSP:
while (chars.isWhitespace(this.peek)) this.advance();
return this.scanToken();
}
this.advance();
return this.error(`Unexpected character [${String.fromCharCode(peek)}]`, 0);
}
scanCharacter(start: number, code: number): Token {
this.advance();
return newCharacterToken(start, this.index, code);
}
scanOperator(start: number, str: string): Token {
this.advance();
return newOperatorToken(start, this.index, str);
}
/**
* Tokenize a 2/3 char long operator
*
* @param start start index in the expression
* @param one first symbol (always part of the operator)
* @param twoCode code point for the second symbol
* @param two second symbol (part of the operator when the second code point matches)
* @param threeCode code point for the third symbol
* @param three third symbol (part of the operator when provided and matches source expression)
*/
scanComplexOperator(
start: number,
one: string,
twoCode: number,
two: string,
threeCode?: number,
three?: string,
): Token {
this.advance();
let str: string = one;
if (this.peek == twoCode) {
this.advance();
str += two;
}
if (threeCode != null && this.peek == threeCode) {
this.advance();
str += three;
}
return newOperatorToken(start, this.index, str);
}
scanIdentifier(): Token {
const start: number = this.index;
this.advance();
while (isIdentifierPart(this.peek)) this.advance();
const str: string = this.input.substring(start, this.index);
return KEYWORDS.indexOf(str) > -1
? newKeywordToken(start, this.index, str)
: newIdentifierToken(start, this.index, str);
}
/** Scans an ECMAScript private identifier. */
scanPrivateIdentifier(): Token {
const start: number = this.index;
this.advance();
if (!isIdentifierStart(this.peek)) {
return this.error('Invalid character [#]', -1);
}
while (isIdentifierPart(this.peek)) this.advance();
const identifierName: string = this.input.substring(start, this.index);
return newPrivateIdentifierToken(start, this.index, identifierName);
}
scanNumber(start: number): Token {
let simple = this.index === start;
let hasSeparators = false;
this.advance(); // Skip initial digit.
while (true) {
if (chars.isDigit(this.peek)) {
// Do nothing.
} else if (this.peek === chars.$_) {
// Separators are only valid when they're surrounded by digits. E.g. `1_0_1` is
// valid while `_101` and `101_` are not. The separator can't be next to the decimal
// point or another separator either. Note that it's unlikely that we'll hit a case where
// the underscore is at the start, because that's a valid identifier and it will be picked
// up earlier in the parsing. We validate for it anyway just in case.
if (
!chars.isDigit(this.input.charCodeAt(this.index - 1)) ||
!chars.isDigit(this.input.charCodeAt(this.index + 1))
) {
return this.error('Invalid numeric separator', 0);
}
hasSeparators = true;
} else if (this.peek === chars.$PERIOD) {
simple = false;
} else if (isExponentStart(this.peek)) {
this.advance();
if (isExponentSign(this.peek)) this.advance();
if (!chars.isDigit(this.peek)) return this.error('Invalid exponent', -1);
simple = false;
} else {
break;
}
this.advance();
}
let str = this.input.substring(start, this.index);
if (hasSeparators) {
str = str.replace(/_/g, '');
}
const value = simple ? parseIntAutoRadix(str) : parseFloat(str);
return newNumberToken(start, this.index, value);
}
scanString(): Token {
const start: number = this.index;
const quote: number = this.peek;
this.advance(); // Skip initial quote.
let buffer: string = '';
let marker: number = this.index;
const input: string = this.input;
while (this.peek != quote) {
if (this.peek == chars.$BACKSLASH) {
buffer += input.substring(marker, this.index);
let unescapedCode: number;
this.advance(); // mutates this.peek
// @ts-expect-error see microsoft/TypeScript#9998
if (this.peek == chars.$u) {
// 4 character hex code for unicode character.
const hex: string = input.substring(this.index + 1, this.index + 5);
if (/^[0-9a-f]+$/i.test(hex)) {
unescapedCode = parseInt(hex, 16);
} else {
return this.error(`Invalid unicode escape [\\u${hex}]`, 0);
}
for (let i: number = 0; i < 5; i++) {
this.advance();
}
} else {
unescapedCode = unescape(this.peek);
this.advance();
}
buffer += String.fromCharCode(unescapedCode);
marker = this.index;
} else if (this.peek == chars.$EOF) {
return this.error('Unterminated quote', 0);
} else {
this.advance();
}
}
const last: string = input.substring(marker, this.index);
this.advance(); // Skip terminating quote.
return newStringToken(start, this.index, buffer + last);
}
scanQuestion(start: number): Token {
this.advance();
let str: string = '?';
// Either `a ?? b` or 'a?.b'.
if (this.peek === chars.$QUESTION || this.peek === chars.$PERIOD) {
str += this.peek === chars.$PERIOD ? '.' : '?';
this.advance();
}
return newOperatorToken(start, this.index, str);
}
error(message: string, offset: number): Token {
const position: number = this.index + offset;
return newErrorToken(
position,
this.index,
`Lexer Error: ${message} at column ${position} in expression [${this.input}]`,
);
}
} | {
"end_byte": 12537,
"start_byte": 4256,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/lexer.ts"
} |
angular/packages/compiler/src/expression_parser/lexer.ts_12539_13629 | function isIdentifierStart(code: number): boolean {
return (
(chars.$a <= code && code <= chars.$z) ||
(chars.$A <= code && code <= chars.$Z) ||
code == chars.$_ ||
code == chars.$$
);
}
function isIdentifierPart(code: number): boolean {
return chars.isAsciiLetter(code) || chars.isDigit(code) || code == chars.$_ || code == chars.$$;
}
function isExponentStart(code: number): boolean {
return code == chars.$e || code == chars.$E;
}
function isExponentSign(code: number): boolean {
return code == chars.$MINUS || code == chars.$PLUS;
}
function unescape(code: number): number {
switch (code) {
case chars.$n:
return chars.$LF;
case chars.$f:
return chars.$FF;
case chars.$r:
return chars.$CR;
case chars.$t:
return chars.$TAB;
case chars.$v:
return chars.$VTAB;
default:
return code;
}
}
function parseIntAutoRadix(text: string): number {
const result: number = parseInt(text);
if (isNaN(result)) {
throw new Error('Invalid integer literal when parsing ' + text);
}
return result;
} | {
"end_byte": 13629,
"start_byte": 12539,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/lexer.ts"
} |
angular/packages/compiler/src/expression_parser/ast.ts_0_7666 | /**
* @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.dev/license
*/
import {SecurityContext} from '../core';
import {ParseSourceSpan} from '../parse_util';
export class ParserError {
public message: string;
constructor(
message: string,
public input: string,
public errLocation: string,
public ctxLocation?: any,
) {
this.message = `Parser Error: ${message} ${errLocation} [${input}] in ${ctxLocation}`;
}
}
export class ParseSpan {
constructor(
public start: number,
public end: number,
) {}
toAbsolute(absoluteOffset: number): AbsoluteSourceSpan {
return new AbsoluteSourceSpan(absoluteOffset + this.start, absoluteOffset + this.end);
}
}
export abstract class AST {
constructor(
public span: ParseSpan,
/**
* Absolute location of the expression AST in a source code file.
*/
public sourceSpan: AbsoluteSourceSpan,
) {}
abstract visit(visitor: AstVisitor, context?: any): any;
toString(): string {
return 'AST';
}
}
export abstract class ASTWithName extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public nameSpan: AbsoluteSourceSpan,
) {
super(span, sourceSpan);
}
}
export class EmptyExpr extends AST {
override visit(visitor: AstVisitor, context: any = null) {
// do nothing
}
}
export class ImplicitReceiver extends AST {
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitImplicitReceiver(this, context);
}
}
/**
* Receiver when something is accessed through `this` (e.g. `this.foo`). Note that this class
* inherits from `ImplicitReceiver`, because accessing something through `this` is treated the
* same as accessing it implicitly inside of an Angular template (e.g. `[attr.title]="this.title"`
* is the same as `[attr.title]="title"`.). Inheriting allows for the `this` accesses to be treated
* the same as implicit ones, except for a couple of exceptions like `$event` and `$any`.
* TODO: we should find a way for this class not to extend from `ImplicitReceiver` in the future.
*/
export class ThisReceiver extends ImplicitReceiver {
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitThisReceiver?.(this, context);
}
}
/**
* Multiple expressions separated by a semicolon.
*/
export class Chain extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public expressions: any[],
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitChain(this, context);
}
}
export class Conditional extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public condition: AST,
public trueExp: AST,
public falseExp: AST,
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitConditional(this, context);
}
}
export class PropertyRead extends ASTWithName {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
nameSpan: AbsoluteSourceSpan,
public receiver: AST,
public name: string,
) {
super(span, sourceSpan, nameSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitPropertyRead(this, context);
}
}
export class PropertyWrite extends ASTWithName {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
nameSpan: AbsoluteSourceSpan,
public receiver: AST,
public name: string,
public value: AST,
) {
super(span, sourceSpan, nameSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitPropertyWrite(this, context);
}
}
export class SafePropertyRead extends ASTWithName {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
nameSpan: AbsoluteSourceSpan,
public receiver: AST,
public name: string,
) {
super(span, sourceSpan, nameSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitSafePropertyRead(this, context);
}
}
export class KeyedRead extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public receiver: AST,
public key: AST,
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitKeyedRead(this, context);
}
}
export class SafeKeyedRead extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public receiver: AST,
public key: AST,
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitSafeKeyedRead(this, context);
}
}
export class KeyedWrite extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public receiver: AST,
public key: AST,
public value: AST,
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitKeyedWrite(this, context);
}
}
export class BindingPipe extends ASTWithName {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public exp: AST,
public name: string,
public args: any[],
nameSpan: AbsoluteSourceSpan,
) {
super(span, sourceSpan, nameSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitPipe(this, context);
}
}
export class LiteralPrimitive extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public value: any,
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitLiteralPrimitive(this, context);
}
}
export class LiteralArray extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public expressions: any[],
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitLiteralArray(this, context);
}
}
export type LiteralMapKey = {
key: string;
quoted: boolean;
isShorthandInitialized?: boolean;
};
export class LiteralMap extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public keys: LiteralMapKey[],
public values: any[],
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitLiteralMap(this, context);
}
}
export class Interpolation extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public strings: string[],
public expressions: AST[],
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitInterpolation(this, context);
}
}
export class Binary extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public operation: string,
public left: AST,
public right: AST,
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitBinary(this, context);
}
}
/**
* For backwards compatibility reasons, `Unary` inherits from `Binary` and mimics the binary AST
* node that was originally used. This inheritance relation can be deleted in some future major,
* after consumers have been given a chance to fully support Unary.
*/ | {
"end_byte": 7666,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/ast.ts"
} |
angular/packages/compiler/src/expression_parser/ast.ts_7667_14300 | export class Unary extends Binary {
// Redeclare the properties that are inherited from `Binary` as `never`, as consumers should not
// depend on these fields when operating on `Unary`.
override left: never = null as never;
override right: never = null as never;
override operation: never = null as never;
/**
* Creates a unary minus expression "-x", represented as `Binary` using "0 - x".
*/
static createMinus(span: ParseSpan, sourceSpan: AbsoluteSourceSpan, expr: AST): Unary {
return new Unary(
span,
sourceSpan,
'-',
expr,
'-',
new LiteralPrimitive(span, sourceSpan, 0),
expr,
);
}
/**
* Creates a unary plus expression "+x", represented as `Binary` using "x - 0".
*/
static createPlus(span: ParseSpan, sourceSpan: AbsoluteSourceSpan, expr: AST): Unary {
return new Unary(
span,
sourceSpan,
'+',
expr,
'-',
expr,
new LiteralPrimitive(span, sourceSpan, 0),
);
}
/**
* During the deprecation period this constructor is private, to avoid consumers from creating
* a `Unary` with the fallback properties for `Binary`.
*/
private constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public operator: string,
public expr: AST,
binaryOp: string,
binaryLeft: AST,
binaryRight: AST,
) {
super(span, sourceSpan, binaryOp, binaryLeft, binaryRight);
}
override visit(visitor: AstVisitor, context: any = null): any {
if (visitor.visitUnary !== undefined) {
return visitor.visitUnary(this, context);
}
return visitor.visitBinary(this, context);
}
}
export class PrefixNot extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public expression: AST,
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitPrefixNot(this, context);
}
}
export class TypeofExpression extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public expression: AST,
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitTypeofExpresion(this, context);
}
}
export class NonNullAssert extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public expression: AST,
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitNonNullAssert(this, context);
}
}
export class Call extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public receiver: AST,
public args: AST[],
public argumentSpan: AbsoluteSourceSpan,
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitCall(this, context);
}
}
export class SafeCall extends AST {
constructor(
span: ParseSpan,
sourceSpan: AbsoluteSourceSpan,
public receiver: AST,
public args: AST[],
public argumentSpan: AbsoluteSourceSpan,
) {
super(span, sourceSpan);
}
override visit(visitor: AstVisitor, context: any = null): any {
return visitor.visitSafeCall(this, context);
}
}
/**
* Records the absolute position of a text span in a source file, where `start` and `end` are the
* starting and ending byte offsets, respectively, of the text span in a source file.
*/
export class AbsoluteSourceSpan {
constructor(
public readonly start: number,
public readonly end: number,
) {}
}
export class ASTWithSource<T extends AST = AST> extends AST {
constructor(
public ast: T,
public source: string | null,
public location: string,
absoluteOffset: number,
public errors: ParserError[],
) {
super(
new ParseSpan(0, source === null ? 0 : source.length),
new AbsoluteSourceSpan(
absoluteOffset,
source === null ? absoluteOffset : absoluteOffset + source.length,
),
);
}
override visit(visitor: AstVisitor, context: any = null): any {
if (visitor.visitASTWithSource) {
return visitor.visitASTWithSource(this, context);
}
return this.ast.visit(visitor, context);
}
override toString(): string {
return `${this.source} in ${this.location}`;
}
}
/**
* TemplateBinding refers to a particular key-value pair in a microsyntax
* expression. A few examples are:
*
* |---------------------|--------------|---------|--------------|
* | expression | key | value | binding type |
* |---------------------|--------------|---------|--------------|
* | 1. let item | item | null | variable |
* | 2. of items | ngForOf | items | expression |
* | 3. let x = y | x | y | variable |
* | 4. index as i | i | index | variable |
* | 5. trackBy: func | ngForTrackBy | func | expression |
* | 6. *ngIf="cond" | ngIf | cond | expression |
* |---------------------|--------------|---------|--------------|
*
* (6) is a notable exception because it is a binding from the template key in
* the LHS of a HTML attribute to the expression in the RHS. All other bindings
* in the example above are derived solely from the RHS.
*/
export type TemplateBinding = VariableBinding | ExpressionBinding;
export class VariableBinding {
/**
* @param sourceSpan entire span of the binding.
* @param key name of the LHS along with its span.
* @param value optional value for the RHS along with its span.
*/
constructor(
public readonly sourceSpan: AbsoluteSourceSpan,
public readonly key: TemplateBindingIdentifier,
public readonly value: TemplateBindingIdentifier | null,
) {}
}
export class ExpressionBinding {
/**
* @param sourceSpan entire span of the binding.
* @param key binding name, like ngForOf, ngForTrackBy, ngIf, along with its
* span. Note that the length of the span may not be the same as
* `key.source.length`. For example,
* 1. key.source = ngFor, key.span is for "ngFor"
* 2. key.source = ngForOf, key.span is for "of"
* 3. key.source = ngForTrackBy, key.span is for "trackBy"
* @param value optional expression for the RHS.
*/
constructor(
public readonly sourceSpan: AbsoluteSourceSpan,
public readonly key: TemplateBindingIdentifier,
public readonly value: ASTWithSource | null,
) {}
}
export interface TemplateBindingIdentifier {
source: string;
span: AbsoluteSourceSpan;
} | {
"end_byte": 14300,
"start_byte": 7667,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/ast.ts"
} |
angular/packages/compiler/src/expression_parser/ast.ts_14302_19286 | export interface AstVisitor {
/**
* The `visitUnary` method is declared as optional for backwards compatibility. In an upcoming
* major release, this method will be made required.
*/
visitUnary?(ast: Unary, context: any): any;
visitBinary(ast: Binary, context: any): any;
visitChain(ast: Chain, context: any): any;
visitConditional(ast: Conditional, context: any): any;
/**
* The `visitThisReceiver` method is declared as optional for backwards compatibility.
* In an upcoming major release, this method will be made required.
*/
visitThisReceiver?(ast: ThisReceiver, context: any): any;
visitImplicitReceiver(ast: ImplicitReceiver, context: any): any;
visitInterpolation(ast: Interpolation, context: any): any;
visitKeyedRead(ast: KeyedRead, context: any): any;
visitKeyedWrite(ast: KeyedWrite, context: any): any;
visitLiteralArray(ast: LiteralArray, context: any): any;
visitLiteralMap(ast: LiteralMap, context: any): any;
visitLiteralPrimitive(ast: LiteralPrimitive, context: any): any;
visitPipe(ast: BindingPipe, context: any): any;
visitPrefixNot(ast: PrefixNot, context: any): any;
visitTypeofExpresion(ast: TypeofExpression, context: any): any;
visitNonNullAssert(ast: NonNullAssert, context: any): any;
visitPropertyRead(ast: PropertyRead, context: any): any;
visitPropertyWrite(ast: PropertyWrite, context: any): any;
visitSafePropertyRead(ast: SafePropertyRead, context: any): any;
visitSafeKeyedRead(ast: SafeKeyedRead, context: any): any;
visitCall(ast: Call, context: any): any;
visitSafeCall(ast: SafeCall, context: any): any;
visitASTWithSource?(ast: ASTWithSource, context: any): any;
/**
* This function is optionally defined to allow classes that implement this
* interface to selectively decide if the specified `ast` should be visited.
* @param ast node to visit
* @param context context that gets passed to the node and all its children
*/
visit?(ast: AST, context?: any): any;
}
export class RecursiveAstVisitor implements AstVisitor {
visit(ast: AST, context?: any): any {
// The default implementation just visits every node.
// Classes that extend RecursiveAstVisitor should override this function
// to selectively visit the specified node.
ast.visit(this, context);
}
visitUnary(ast: Unary, context: any): any {
this.visit(ast.expr, context);
}
visitBinary(ast: Binary, context: any): any {
this.visit(ast.left, context);
this.visit(ast.right, context);
}
visitChain(ast: Chain, context: any): any {
this.visitAll(ast.expressions, context);
}
visitConditional(ast: Conditional, context: any): any {
this.visit(ast.condition, context);
this.visit(ast.trueExp, context);
this.visit(ast.falseExp, context);
}
visitPipe(ast: BindingPipe, context: any): any {
this.visit(ast.exp, context);
this.visitAll(ast.args, context);
}
visitImplicitReceiver(ast: ThisReceiver, context: any): any {}
visitThisReceiver(ast: ThisReceiver, context: any): any {}
visitInterpolation(ast: Interpolation, context: any): any {
this.visitAll(ast.expressions, context);
}
visitKeyedRead(ast: KeyedRead, context: any): any {
this.visit(ast.receiver, context);
this.visit(ast.key, context);
}
visitKeyedWrite(ast: KeyedWrite, context: any): any {
this.visit(ast.receiver, context);
this.visit(ast.key, context);
this.visit(ast.value, context);
}
visitLiteralArray(ast: LiteralArray, context: any): any {
this.visitAll(ast.expressions, context);
}
visitLiteralMap(ast: LiteralMap, context: any): any {
this.visitAll(ast.values, context);
}
visitLiteralPrimitive(ast: LiteralPrimitive, context: any): any {}
visitPrefixNot(ast: PrefixNot, context: any): any {
this.visit(ast.expression, context);
}
visitTypeofExpresion(ast: TypeofExpression, context: any) {
this.visit(ast.expression, context);
}
visitNonNullAssert(ast: NonNullAssert, context: any): any {
this.visit(ast.expression, context);
}
visitPropertyRead(ast: PropertyRead, context: any): any {
this.visit(ast.receiver, context);
}
visitPropertyWrite(ast: PropertyWrite, context: any): any {
this.visit(ast.receiver, context);
this.visit(ast.value, context);
}
visitSafePropertyRead(ast: SafePropertyRead, context: any): any {
this.visit(ast.receiver, context);
}
visitSafeKeyedRead(ast: SafeKeyedRead, context: any): any {
this.visit(ast.receiver, context);
this.visit(ast.key, context);
}
visitCall(ast: Call, context: any): any {
this.visit(ast.receiver, context);
this.visitAll(ast.args, context);
}
visitSafeCall(ast: SafeCall, context: any): any {
this.visit(ast.receiver, context);
this.visitAll(ast.args, context);
}
// This is not part of the AstVisitor interface, just a helper method
visitAll(asts: AST[], context: any): any {
for (const ast of asts) {
this.visit(ast, context);
}
}
} | {
"end_byte": 19286,
"start_byte": 14302,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/ast.ts"
} |
angular/packages/compiler/src/expression_parser/ast.ts_19288_23658 | export class AstTransformer implements AstVisitor {
visitImplicitReceiver(ast: ImplicitReceiver, context: any): AST {
return ast;
}
visitThisReceiver(ast: ThisReceiver, context: any): AST {
return ast;
}
visitInterpolation(ast: Interpolation, context: any): AST {
return new Interpolation(ast.span, ast.sourceSpan, ast.strings, this.visitAll(ast.expressions));
}
visitLiteralPrimitive(ast: LiteralPrimitive, context: any): AST {
return new LiteralPrimitive(ast.span, ast.sourceSpan, ast.value);
}
visitPropertyRead(ast: PropertyRead, context: any): AST {
return new PropertyRead(
ast.span,
ast.sourceSpan,
ast.nameSpan,
ast.receiver.visit(this),
ast.name,
);
}
visitPropertyWrite(ast: PropertyWrite, context: any): AST {
return new PropertyWrite(
ast.span,
ast.sourceSpan,
ast.nameSpan,
ast.receiver.visit(this),
ast.name,
ast.value.visit(this),
);
}
visitSafePropertyRead(ast: SafePropertyRead, context: any): AST {
return new SafePropertyRead(
ast.span,
ast.sourceSpan,
ast.nameSpan,
ast.receiver.visit(this),
ast.name,
);
}
visitLiteralArray(ast: LiteralArray, context: any): AST {
return new LiteralArray(ast.span, ast.sourceSpan, this.visitAll(ast.expressions));
}
visitLiteralMap(ast: LiteralMap, context: any): AST {
return new LiteralMap(ast.span, ast.sourceSpan, ast.keys, this.visitAll(ast.values));
}
visitUnary(ast: Unary, context: any): AST {
switch (ast.operator) {
case '+':
return Unary.createPlus(ast.span, ast.sourceSpan, ast.expr.visit(this));
case '-':
return Unary.createMinus(ast.span, ast.sourceSpan, ast.expr.visit(this));
default:
throw new Error(`Unknown unary operator ${ast.operator}`);
}
}
visitBinary(ast: Binary, context: any): AST {
return new Binary(
ast.span,
ast.sourceSpan,
ast.operation,
ast.left.visit(this),
ast.right.visit(this),
);
}
visitPrefixNot(ast: PrefixNot, context: any): AST {
return new PrefixNot(ast.span, ast.sourceSpan, ast.expression.visit(this));
}
visitTypeofExpresion(ast: TypeofExpression, context: any): AST {
return new TypeofExpression(ast.span, ast.sourceSpan, ast.expression.visit(this));
}
visitNonNullAssert(ast: NonNullAssert, context: any): AST {
return new NonNullAssert(ast.span, ast.sourceSpan, ast.expression.visit(this));
}
visitConditional(ast: Conditional, context: any): AST {
return new Conditional(
ast.span,
ast.sourceSpan,
ast.condition.visit(this),
ast.trueExp.visit(this),
ast.falseExp.visit(this),
);
}
visitPipe(ast: BindingPipe, context: any): AST {
return new BindingPipe(
ast.span,
ast.sourceSpan,
ast.exp.visit(this),
ast.name,
this.visitAll(ast.args),
ast.nameSpan,
);
}
visitKeyedRead(ast: KeyedRead, context: any): AST {
return new KeyedRead(ast.span, ast.sourceSpan, ast.receiver.visit(this), ast.key.visit(this));
}
visitKeyedWrite(ast: KeyedWrite, context: any): AST {
return new KeyedWrite(
ast.span,
ast.sourceSpan,
ast.receiver.visit(this),
ast.key.visit(this),
ast.value.visit(this),
);
}
visitCall(ast: Call, context: any): AST {
return new Call(
ast.span,
ast.sourceSpan,
ast.receiver.visit(this),
this.visitAll(ast.args),
ast.argumentSpan,
);
}
visitSafeCall(ast: SafeCall, context: any): AST {
return new SafeCall(
ast.span,
ast.sourceSpan,
ast.receiver.visit(this),
this.visitAll(ast.args),
ast.argumentSpan,
);
}
visitAll(asts: any[]): any[] {
const res = [];
for (let i = 0; i < asts.length; ++i) {
res[i] = asts[i].visit(this);
}
return res;
}
visitChain(ast: Chain, context: any): AST {
return new Chain(ast.span, ast.sourceSpan, this.visitAll(ast.expressions));
}
visitSafeKeyedRead(ast: SafeKeyedRead, context: any): AST {
return new SafeKeyedRead(
ast.span,
ast.sourceSpan,
ast.receiver.visit(this),
ast.key.visit(this),
);
}
}
// A transformer that only creates new nodes if the transformer makes a change or
// a change is made a child node. | {
"end_byte": 23658,
"start_byte": 19288,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/ast.ts"
} |
angular/packages/compiler/src/expression_parser/ast.ts_23659_31613 | export class AstMemoryEfficientTransformer implements AstVisitor {
visitImplicitReceiver(ast: ImplicitReceiver, context: any): AST {
return ast;
}
visitThisReceiver(ast: ThisReceiver, context: any): AST {
return ast;
}
visitInterpolation(ast: Interpolation, context: any): Interpolation {
const expressions = this.visitAll(ast.expressions);
if (expressions !== ast.expressions)
return new Interpolation(ast.span, ast.sourceSpan, ast.strings, expressions);
return ast;
}
visitLiteralPrimitive(ast: LiteralPrimitive, context: any): AST {
return ast;
}
visitPropertyRead(ast: PropertyRead, context: any): AST {
const receiver = ast.receiver.visit(this);
if (receiver !== ast.receiver) {
return new PropertyRead(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name);
}
return ast;
}
visitPropertyWrite(ast: PropertyWrite, context: any): AST {
const receiver = ast.receiver.visit(this);
const value = ast.value.visit(this);
if (receiver !== ast.receiver || value !== ast.value) {
return new PropertyWrite(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name, value);
}
return ast;
}
visitSafePropertyRead(ast: SafePropertyRead, context: any): AST {
const receiver = ast.receiver.visit(this);
if (receiver !== ast.receiver) {
return new SafePropertyRead(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name);
}
return ast;
}
visitLiteralArray(ast: LiteralArray, context: any): AST {
const expressions = this.visitAll(ast.expressions);
if (expressions !== ast.expressions) {
return new LiteralArray(ast.span, ast.sourceSpan, expressions);
}
return ast;
}
visitLiteralMap(ast: LiteralMap, context: any): AST {
const values = this.visitAll(ast.values);
if (values !== ast.values) {
return new LiteralMap(ast.span, ast.sourceSpan, ast.keys, values);
}
return ast;
}
visitUnary(ast: Unary, context: any): AST {
const expr = ast.expr.visit(this);
if (expr !== ast.expr) {
switch (ast.operator) {
case '+':
return Unary.createPlus(ast.span, ast.sourceSpan, expr);
case '-':
return Unary.createMinus(ast.span, ast.sourceSpan, expr);
default:
throw new Error(`Unknown unary operator ${ast.operator}`);
}
}
return ast;
}
visitBinary(ast: Binary, context: any): AST {
const left = ast.left.visit(this);
const right = ast.right.visit(this);
if (left !== ast.left || right !== ast.right) {
return new Binary(ast.span, ast.sourceSpan, ast.operation, left, right);
}
return ast;
}
visitPrefixNot(ast: PrefixNot, context: any): AST {
const expression = ast.expression.visit(this);
if (expression !== ast.expression) {
return new PrefixNot(ast.span, ast.sourceSpan, expression);
}
return ast;
}
visitTypeofExpresion(ast: TypeofExpression, context: any): AST {
const expression = ast.expression.visit(this);
if (expression !== ast.expression) {
return new TypeofExpression(ast.span, ast.sourceSpan, expression);
}
return ast;
}
visitNonNullAssert(ast: NonNullAssert, context: any): AST {
const expression = ast.expression.visit(this);
if (expression !== ast.expression) {
return new NonNullAssert(ast.span, ast.sourceSpan, expression);
}
return ast;
}
visitConditional(ast: Conditional, context: any): AST {
const condition = ast.condition.visit(this);
const trueExp = ast.trueExp.visit(this);
const falseExp = ast.falseExp.visit(this);
if (condition !== ast.condition || trueExp !== ast.trueExp || falseExp !== ast.falseExp) {
return new Conditional(ast.span, ast.sourceSpan, condition, trueExp, falseExp);
}
return ast;
}
visitPipe(ast: BindingPipe, context: any): AST {
const exp = ast.exp.visit(this);
const args = this.visitAll(ast.args);
if (exp !== ast.exp || args !== ast.args) {
return new BindingPipe(ast.span, ast.sourceSpan, exp, ast.name, args, ast.nameSpan);
}
return ast;
}
visitKeyedRead(ast: KeyedRead, context: any): AST {
const obj = ast.receiver.visit(this);
const key = ast.key.visit(this);
if (obj !== ast.receiver || key !== ast.key) {
return new KeyedRead(ast.span, ast.sourceSpan, obj, key);
}
return ast;
}
visitKeyedWrite(ast: KeyedWrite, context: any): AST {
const obj = ast.receiver.visit(this);
const key = ast.key.visit(this);
const value = ast.value.visit(this);
if (obj !== ast.receiver || key !== ast.key || value !== ast.value) {
return new KeyedWrite(ast.span, ast.sourceSpan, obj, key, value);
}
return ast;
}
visitAll(asts: any[]): any[] {
const res = [];
let modified = false;
for (let i = 0; i < asts.length; ++i) {
const original = asts[i];
const value = original.visit(this);
res[i] = value;
modified = modified || value !== original;
}
return modified ? res : asts;
}
visitChain(ast: Chain, context: any): AST {
const expressions = this.visitAll(ast.expressions);
if (expressions !== ast.expressions) {
return new Chain(ast.span, ast.sourceSpan, expressions);
}
return ast;
}
visitCall(ast: Call, context: any): AST {
const receiver = ast.receiver.visit(this);
const args = this.visitAll(ast.args);
if (receiver !== ast.receiver || args !== ast.args) {
return new Call(ast.span, ast.sourceSpan, receiver, args, ast.argumentSpan);
}
return ast;
}
visitSafeCall(ast: SafeCall, context: any): AST {
const receiver = ast.receiver.visit(this);
const args = this.visitAll(ast.args);
if (receiver !== ast.receiver || args !== ast.args) {
return new SafeCall(ast.span, ast.sourceSpan, receiver, args, ast.argumentSpan);
}
return ast;
}
visitSafeKeyedRead(ast: SafeKeyedRead, context: any): AST {
const obj = ast.receiver.visit(this);
const key = ast.key.visit(this);
if (obj !== ast.receiver || key !== ast.key) {
return new SafeKeyedRead(ast.span, ast.sourceSpan, obj, key);
}
return ast;
}
}
// Bindings
export class ParsedProperty {
public readonly isLiteral: boolean;
public readonly isAnimation: boolean;
constructor(
public name: string,
public expression: ASTWithSource,
public type: ParsedPropertyType,
public sourceSpan: ParseSourceSpan,
readonly keySpan: ParseSourceSpan,
public valueSpan: ParseSourceSpan | undefined,
) {
this.isLiteral = this.type === ParsedPropertyType.LITERAL_ATTR;
this.isAnimation = this.type === ParsedPropertyType.ANIMATION;
}
}
export enum ParsedPropertyType {
DEFAULT,
LITERAL_ATTR,
ANIMATION,
TWO_WAY,
}
export enum ParsedEventType {
// DOM or Directive event
Regular,
// Animation specific event
Animation,
// Event side of a two-way binding (e.g. `[(property)]="expression"`).
TwoWay,
}
export class ParsedEvent {
// Regular events have a target
// Animation events have a phase
constructor(
name: string,
targetOrPhase: string,
type: ParsedEventType.TwoWay,
handler: ASTWithSource<NonNullAssert | PropertyRead | KeyedRead>,
sourceSpan: ParseSourceSpan,
handlerSpan: ParseSourceSpan,
keySpan: ParseSourceSpan,
);
constructor(
name: string,
targetOrPhase: string,
type: ParsedEventType,
handler: ASTWithSource,
sourceSpan: ParseSourceSpan,
handlerSpan: ParseSourceSpan,
keySpan: ParseSourceSpan,
);
constructor(
public name: string,
public targetOrPhase: string,
public type: ParsedEventType,
public handler: ASTWithSource,
public sourceSpan: ParseSourceSpan,
public handlerSpan: ParseSourceSpan,
readonly keySpan: ParseSourceSpan,
) {}
}
/**
* ParsedVariable represents a variable declaration in a microsyntax expression.
*/ | {
"end_byte": 31613,
"start_byte": 23659,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/ast.ts"
} |
angular/packages/compiler/src/expression_parser/ast.ts_31614_32774 | export class ParsedVariable {
constructor(
public readonly name: string,
public readonly value: string,
public readonly sourceSpan: ParseSourceSpan,
public readonly keySpan: ParseSourceSpan,
public readonly valueSpan?: ParseSourceSpan,
) {}
}
export enum BindingType {
// A regular binding to a property (e.g. `[property]="expression"`).
Property,
// A binding to an element attribute (e.g. `[attr.name]="expression"`).
Attribute,
// A binding to a CSS class (e.g. `[class.name]="condition"`).
Class,
// A binding to a style rule (e.g. `[style.rule]="expression"`).
Style,
// A binding to an animation reference (e.g. `[animate.key]="expression"`).
Animation,
// Property side of a two-way binding (e.g. `[(property)]="expression"`).
TwoWay,
}
export class BoundElementProperty {
constructor(
public name: string,
public type: BindingType,
public securityContext: SecurityContext,
public value: ASTWithSource,
public unit: string | null,
public sourceSpan: ParseSourceSpan,
readonly keySpan: ParseSourceSpan | undefined,
public valueSpan: ParseSourceSpan | undefined,
) {}
} | {
"end_byte": 32774,
"start_byte": 31614,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/ast.ts"
} |
angular/packages/compiler/src/expression_parser/parser.ts_0_1721 | /**
* @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.dev/license
*/
import * as chars from '../chars';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../ml_parser/defaults';
import {
InterpolatedAttributeToken,
InterpolatedTextToken,
TokenType as MlParserTokenType,
} from '../ml_parser/tokens';
import {
AbsoluteSourceSpan,
AST,
ASTWithSource,
Binary,
BindingPipe,
Call,
Chain,
Conditional,
EmptyExpr,
ExpressionBinding,
ImplicitReceiver,
Interpolation,
KeyedRead,
KeyedWrite,
LiteralArray,
LiteralMap,
LiteralMapKey,
LiteralPrimitive,
NonNullAssert,
ParserError,
ParseSpan,
PrefixNot,
TypeofExpression,
PropertyRead,
PropertyWrite,
RecursiveAstVisitor,
SafeCall,
SafeKeyedRead,
SafePropertyRead,
TemplateBinding,
TemplateBindingIdentifier,
ThisReceiver,
Unary,
VariableBinding,
} from './ast';
import {EOF, Lexer, Token, TokenType} from './lexer';
export interface InterpolationPiece {
text: string;
start: number;
end: number;
}
export class SplitInterpolation {
constructor(
public strings: InterpolationPiece[],
public expressions: InterpolationPiece[],
public offsets: number[],
) {}
}
export class TemplateBindingParseResult {
constructor(
public templateBindings: TemplateBinding[],
public warnings: string[],
public errors: ParserError[],
) {}
}
/**
* Represents the possible parse modes to be used as a bitmask.
*/
export const enum ParseFlags {
None = 0,
/**
* Whether an output binding is being parsed.
*/
Action = 1 << 0,
} | {
"end_byte": 1721,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/parser.ts"
} |
angular/packages/compiler/src/expression_parser/parser.ts_1723_8623 | export class Parser {
private errors: ParserError[] = [];
constructor(private _lexer: Lexer) {}
parseAction(
input: string,
location: string,
absoluteOffset: number,
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG,
): ASTWithSource {
this._checkNoInterpolation(input, location, interpolationConfig);
const sourceToLex = this._stripComments(input);
const tokens = this._lexer.tokenize(sourceToLex);
const ast = new _ParseAST(
input,
location,
absoluteOffset,
tokens,
ParseFlags.Action,
this.errors,
0,
).parseChain();
return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
}
parseBinding(
input: string,
location: string,
absoluteOffset: number,
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG,
): ASTWithSource {
const ast = this._parseBindingAst(input, location, absoluteOffset, interpolationConfig);
return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
}
private checkSimpleExpression(ast: AST): string[] {
const checker = new SimpleExpressionChecker();
ast.visit(checker);
return checker.errors;
}
// Host bindings parsed here
parseSimpleBinding(
input: string,
location: string,
absoluteOffset: number,
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG,
): ASTWithSource {
const ast = this._parseBindingAst(input, location, absoluteOffset, interpolationConfig);
const errors = this.checkSimpleExpression(ast);
if (errors.length > 0) {
this._reportError(
`Host binding expression cannot contain ${errors.join(' ')}`,
input,
location,
);
}
return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
}
private _reportError(message: string, input: string, errLocation: string, ctxLocation?: string) {
this.errors.push(new ParserError(message, input, errLocation, ctxLocation));
}
private _parseBindingAst(
input: string,
location: string,
absoluteOffset: number,
interpolationConfig: InterpolationConfig,
): AST {
this._checkNoInterpolation(input, location, interpolationConfig);
const sourceToLex = this._stripComments(input);
const tokens = this._lexer.tokenize(sourceToLex);
return new _ParseAST(
input,
location,
absoluteOffset,
tokens,
ParseFlags.None,
this.errors,
0,
).parseChain();
}
/**
* Parse microsyntax template expression and return a list of bindings or
* parsing errors in case the given expression is invalid.
*
* For example,
* ```
* <div *ngFor="let item of items">
* ^ ^ absoluteValueOffset for `templateValue`
* absoluteKeyOffset for `templateKey`
* ```
* contains three bindings:
* 1. ngFor -> null
* 2. item -> NgForOfContext.$implicit
* 3. ngForOf -> items
*
* This is apparent from the de-sugared template:
* ```
* <ng-template ngFor let-item [ngForOf]="items">
* ```
*
* @param templateKey name of directive, without the * prefix. For example: ngIf, ngFor
* @param templateValue RHS of the microsyntax attribute
* @param templateUrl template filename if it's external, component filename if it's inline
* @param absoluteKeyOffset start of the `templateKey`
* @param absoluteValueOffset start of the `templateValue`
*/
parseTemplateBindings(
templateKey: string,
templateValue: string,
templateUrl: string,
absoluteKeyOffset: number,
absoluteValueOffset: number,
): TemplateBindingParseResult {
const tokens = this._lexer.tokenize(templateValue);
const parser = new _ParseAST(
templateValue,
templateUrl,
absoluteValueOffset,
tokens,
ParseFlags.None,
this.errors,
0 /* relative offset */,
);
return parser.parseTemplateBindings({
source: templateKey,
span: new AbsoluteSourceSpan(absoluteKeyOffset, absoluteKeyOffset + templateKey.length),
});
}
parseInterpolation(
input: string,
location: string,
absoluteOffset: number,
interpolatedTokens: InterpolatedAttributeToken[] | InterpolatedTextToken[] | null,
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG,
): ASTWithSource | null {
const {strings, expressions, offsets} = this.splitInterpolation(
input,
location,
interpolatedTokens,
interpolationConfig,
);
if (expressions.length === 0) return null;
const expressionNodes: AST[] = [];
for (let i = 0; i < expressions.length; ++i) {
const expressionText = expressions[i].text;
const sourceToLex = this._stripComments(expressionText);
const tokens = this._lexer.tokenize(sourceToLex);
const ast = new _ParseAST(
input,
location,
absoluteOffset,
tokens,
ParseFlags.None,
this.errors,
offsets[i],
).parseChain();
expressionNodes.push(ast);
}
return this.createInterpolationAst(
strings.map((s) => s.text),
expressionNodes,
input,
location,
absoluteOffset,
);
}
/**
* Similar to `parseInterpolation`, but treats the provided string as a single expression
* element that would normally appear within the interpolation prefix and suffix (`{{` and `}}`).
* This is used for parsing the switch expression in ICUs.
*/
parseInterpolationExpression(
expression: string,
location: string,
absoluteOffset: number,
): ASTWithSource {
const sourceToLex = this._stripComments(expression);
const tokens = this._lexer.tokenize(sourceToLex);
const ast = new _ParseAST(
expression,
location,
absoluteOffset,
tokens,
ParseFlags.None,
this.errors,
0,
).parseChain();
const strings = ['', '']; // The prefix and suffix strings are both empty
return this.createInterpolationAst(strings, [ast], expression, location, absoluteOffset);
}
private createInterpolationAst(
strings: string[],
expressions: AST[],
input: string,
location: string,
absoluteOffset: number,
): ASTWithSource {
const span = new ParseSpan(0, input.length);
const interpolation = new Interpolation(
span,
span.toAbsolute(absoluteOffset),
strings,
expressions,
);
return new ASTWithSource(interpolation, input, location, absoluteOffset, this.errors);
}
/**
* Splits a string of text into "raw" text segments and expressions present in interpolations in
* the string.
* Returns `null` if there are no interpolations, otherwise a
* `SplitInterpolation` with splits that look like
* <raw text> <expression> <raw text> ... <raw text> <expression> <raw text>
*/ | {
"end_byte": 8623,
"start_byte": 1723,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/parser.ts"
} |
angular/packages/compiler/src/expression_parser/parser.ts_8626_15064 | splitInterpolation(
input: string,
location: string,
interpolatedTokens: InterpolatedAttributeToken[] | InterpolatedTextToken[] | null,
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG,
): SplitInterpolation {
const strings: InterpolationPiece[] = [];
const expressions: InterpolationPiece[] = [];
const offsets: number[] = [];
const inputToTemplateIndexMap = interpolatedTokens
? getIndexMapForOriginalTemplate(interpolatedTokens)
: null;
let i = 0;
let atInterpolation = false;
let extendLastString = false;
let {start: interpStart, end: interpEnd} = interpolationConfig;
while (i < input.length) {
if (!atInterpolation) {
// parse until starting {{
const start = i;
i = input.indexOf(interpStart, i);
if (i === -1) {
i = input.length;
}
const text = input.substring(start, i);
strings.push({text, start, end: i});
atInterpolation = true;
} else {
// parse from starting {{ to ending }} while ignoring content inside quotes.
const fullStart = i;
const exprStart = fullStart + interpStart.length;
const exprEnd = this._getInterpolationEndIndex(input, interpEnd, exprStart);
if (exprEnd === -1) {
// Could not find the end of the interpolation; do not parse an expression.
// Instead we should extend the content on the last raw string.
atInterpolation = false;
extendLastString = true;
break;
}
const fullEnd = exprEnd + interpEnd.length;
const text = input.substring(exprStart, exprEnd);
if (text.trim().length === 0) {
this._reportError(
'Blank expressions are not allowed in interpolated strings',
input,
`at column ${i} in`,
location,
);
}
expressions.push({text, start: fullStart, end: fullEnd});
const startInOriginalTemplate = inputToTemplateIndexMap?.get(fullStart) ?? fullStart;
const offset = startInOriginalTemplate + interpStart.length;
offsets.push(offset);
i = fullEnd;
atInterpolation = false;
}
}
if (!atInterpolation) {
// If we are now at a text section, add the remaining content as a raw string.
if (extendLastString) {
const piece = strings[strings.length - 1];
piece.text += input.substring(i);
piece.end = input.length;
} else {
strings.push({text: input.substring(i), start: i, end: input.length});
}
}
return new SplitInterpolation(strings, expressions, offsets);
}
wrapLiteralPrimitive(
input: string | null,
location: string,
absoluteOffset: number,
): ASTWithSource {
const span = new ParseSpan(0, input == null ? 0 : input.length);
return new ASTWithSource(
new LiteralPrimitive(span, span.toAbsolute(absoluteOffset), input),
input,
location,
absoluteOffset,
this.errors,
);
}
private _stripComments(input: string): string {
const i = this._commentStart(input);
return i != null ? input.substring(0, i) : input;
}
private _commentStart(input: string): number | null {
let outerQuote: number | null = null;
for (let i = 0; i < input.length - 1; i++) {
const char = input.charCodeAt(i);
const nextChar = input.charCodeAt(i + 1);
if (char === chars.$SLASH && nextChar == chars.$SLASH && outerQuote == null) return i;
if (outerQuote === char) {
outerQuote = null;
} else if (outerQuote == null && chars.isQuote(char)) {
outerQuote = char;
}
}
return null;
}
private _checkNoInterpolation(
input: string,
location: string,
{start, end}: InterpolationConfig,
): void {
let startIndex = -1;
let endIndex = -1;
for (const charIndex of this._forEachUnquotedChar(input, 0)) {
if (startIndex === -1) {
if (input.startsWith(start)) {
startIndex = charIndex;
}
} else {
endIndex = this._getInterpolationEndIndex(input, end, charIndex);
if (endIndex > -1) {
break;
}
}
}
if (startIndex > -1 && endIndex > -1) {
this._reportError(
`Got interpolation (${start}${end}) where expression was expected`,
input,
`at column ${startIndex} in`,
location,
);
}
}
/**
* Finds the index of the end of an interpolation expression
* while ignoring comments and quoted content.
*/
private _getInterpolationEndIndex(input: string, expressionEnd: string, start: number): number {
for (const charIndex of this._forEachUnquotedChar(input, start)) {
if (input.startsWith(expressionEnd, charIndex)) {
return charIndex;
}
// Nothing else in the expression matters after we've
// hit a comment so look directly for the end token.
if (input.startsWith('//', charIndex)) {
return input.indexOf(expressionEnd, charIndex);
}
}
return -1;
}
/**
* Generator used to iterate over the character indexes of a string that are outside of quotes.
* @param input String to loop through.
* @param start Index within the string at which to start.
*/
private *_forEachUnquotedChar(input: string, start: number) {
let currentQuote: string | null = null;
let escapeCount = 0;
for (let i = start; i < input.length; i++) {
const char = input[i];
// Skip the characters inside quotes. Note that we only care about the outer-most
// quotes matching up and we need to account for escape characters.
if (
chars.isQuote(input.charCodeAt(i)) &&
(currentQuote === null || currentQuote === char) &&
escapeCount % 2 === 0
) {
currentQuote = currentQuote === null ? char : null;
} else if (currentQuote === null) {
yield i;
}
escapeCount = char === '\\' ? escapeCount + 1 : 0;
}
}
}
/** Describes a stateful context an expression parser is in. */
enum ParseContextFlags {
None = 0,
/**
* A Writable context is one in which a value may be written to an lvalue.
* For example, after we see a property access, we may expect a write to the
* property via the "=" operator.
* prop
* ^ possible "=" after
*/
Writable = 1,
} | {
"end_byte": 15064,
"start_byte": 8626,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/parser.ts"
} |
angular/packages/compiler/src/expression_parser/parser.ts_15066_22727 | class _ParseAST {
private rparensExpected = 0;
private rbracketsExpected = 0;
private rbracesExpected = 0;
private context = ParseContextFlags.None;
// Cache of expression start and input indeces to the absolute source span they map to, used to
// prevent creating superfluous source spans in `sourceSpan`.
// A serial of the expression start and input index is used for mapping because both are stateful
// and may change for subsequent expressions visited by the parser.
private sourceSpanCache = new Map<string, AbsoluteSourceSpan>();
private index: number = 0;
constructor(
private input: string,
private location: string,
private absoluteOffset: number,
private tokens: Token[],
private parseFlags: ParseFlags,
private errors: ParserError[],
private offset: number,
) {}
private peek(offset: number): Token {
const i = this.index + offset;
return i < this.tokens.length ? this.tokens[i] : EOF;
}
private get next(): Token {
return this.peek(0);
}
/** Whether all the parser input has been processed. */
private get atEOF(): boolean {
return this.index >= this.tokens.length;
}
/**
* Index of the next token to be processed, or the end of the last token if all have been
* processed.
*/
private get inputIndex(): number {
return this.atEOF ? this.currentEndIndex : this.next.index + this.offset;
}
/**
* End index of the last processed token, or the start of the first token if none have been
* processed.
*/
private get currentEndIndex(): number {
if (this.index > 0) {
const curToken = this.peek(-1);
return curToken.end + this.offset;
}
// No tokens have been processed yet; return the next token's start or the length of the input
// if there is no token.
if (this.tokens.length === 0) {
return this.input.length + this.offset;
}
return this.next.index + this.offset;
}
/**
* Returns the absolute offset of the start of the current token.
*/
private get currentAbsoluteOffset(): number {
return this.absoluteOffset + this.inputIndex;
}
/**
* Retrieve a `ParseSpan` from `start` to the current position (or to `artificialEndIndex` if
* provided).
*
* @param start Position from which the `ParseSpan` will start.
* @param artificialEndIndex Optional ending index to be used if provided (and if greater than the
* natural ending index)
*/
private span(start: number, artificialEndIndex?: number): ParseSpan {
let endIndex = this.currentEndIndex;
if (artificialEndIndex !== undefined && artificialEndIndex > this.currentEndIndex) {
endIndex = artificialEndIndex;
}
// In some unusual parsing scenarios (like when certain tokens are missing and an `EmptyExpr` is
// being created), the current token may already be advanced beyond the `currentEndIndex`. This
// appears to be a deep-seated parser bug.
//
// As a workaround for now, swap the start and end indices to ensure a valid `ParseSpan`.
// TODO(alxhub): fix the bug upstream in the parser state, and remove this workaround.
if (start > endIndex) {
const tmp = endIndex;
endIndex = start;
start = tmp;
}
return new ParseSpan(start, endIndex);
}
private sourceSpan(start: number, artificialEndIndex?: number): AbsoluteSourceSpan {
const serial = `${start}@${this.inputIndex}:${artificialEndIndex}`;
if (!this.sourceSpanCache.has(serial)) {
this.sourceSpanCache.set(
serial,
this.span(start, artificialEndIndex).toAbsolute(this.absoluteOffset),
);
}
return this.sourceSpanCache.get(serial)!;
}
private advance() {
this.index++;
}
/**
* Executes a callback in the provided context.
*/
private withContext<T>(context: ParseContextFlags, cb: () => T): T {
this.context |= context;
const ret = cb();
this.context ^= context;
return ret;
}
private consumeOptionalCharacter(code: number): boolean {
if (this.next.isCharacter(code)) {
this.advance();
return true;
} else {
return false;
}
}
private peekKeywordLet(): boolean {
return this.next.isKeywordLet();
}
private peekKeywordAs(): boolean {
return this.next.isKeywordAs();
}
/**
* Consumes an expected character, otherwise emits an error about the missing expected character
* and skips over the token stream until reaching a recoverable point.
*
* See `this.error` and `this.skip` for more details.
*/
private expectCharacter(code: number) {
if (this.consumeOptionalCharacter(code)) return;
this.error(`Missing expected ${String.fromCharCode(code)}`);
}
private consumeOptionalOperator(op: string): boolean {
if (this.next.isOperator(op)) {
this.advance();
return true;
} else {
return false;
}
}
private expectOperator(operator: string) {
if (this.consumeOptionalOperator(operator)) return;
this.error(`Missing expected operator ${operator}`);
}
private prettyPrintToken(tok: Token): string {
return tok === EOF ? 'end of input' : `token ${tok}`;
}
private expectIdentifierOrKeyword(): string | null {
const n = this.next;
if (!n.isIdentifier() && !n.isKeyword()) {
if (n.isPrivateIdentifier()) {
this._reportErrorForPrivateIdentifier(n, 'expected identifier or keyword');
} else {
this.error(`Unexpected ${this.prettyPrintToken(n)}, expected identifier or keyword`);
}
return null;
}
this.advance();
return n.toString() as string;
}
private expectIdentifierOrKeywordOrString(): string {
const n = this.next;
if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) {
if (n.isPrivateIdentifier()) {
this._reportErrorForPrivateIdentifier(n, 'expected identifier, keyword or string');
} else {
this.error(
`Unexpected ${this.prettyPrintToken(n)}, expected identifier, keyword, or string`,
);
}
return '';
}
this.advance();
return n.toString() as string;
}
parseChain(): AST {
const exprs: AST[] = [];
const start = this.inputIndex;
while (this.index < this.tokens.length) {
const expr = this.parsePipe();
exprs.push(expr);
if (this.consumeOptionalCharacter(chars.$SEMICOLON)) {
if (!(this.parseFlags & ParseFlags.Action)) {
this.error('Binding expression cannot contain chained expression');
}
while (this.consumeOptionalCharacter(chars.$SEMICOLON)) {} // read all semicolons
} else if (this.index < this.tokens.length) {
const errorIndex = this.index;
this.error(`Unexpected token '${this.next}'`);
// The `error` call above will skip ahead to the next recovery point in an attempt to
// recover part of the expression, but that might be the token we started from which will
// lead to an infinite loop. If that's the case, break the loop assuming that we can't
// parse further.
if (this.index === errorIndex) {
break;
}
}
}
if (exprs.length === 0) {
// We have no expressions so create an empty expression that spans the entire input length
const artificialStart = this.offset;
const artificialEnd = this.offset + this.input.length;
return new EmptyExpr(
this.span(artificialStart, artificialEnd),
this.sourceSpan(artificialStart, artificialEnd),
);
}
if (exprs.length == 1) return exprs[0];
return new Chain(this.span(start), this.sourceSpan(start), exprs);
} | {
"end_byte": 22727,
"start_byte": 15066,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/parser.ts"
} |
angular/packages/compiler/src/expression_parser/parser.ts_22731_31115 | private parsePipe(): AST {
const start = this.inputIndex;
let result = this.parseExpression();
if (this.consumeOptionalOperator('|')) {
if (this.parseFlags & ParseFlags.Action) {
this.error(`Cannot have a pipe in an action expression`);
}
do {
const nameStart = this.inputIndex;
let nameId = this.expectIdentifierOrKeyword();
let nameSpan: AbsoluteSourceSpan;
let fullSpanEnd: number | undefined = undefined;
if (nameId !== null) {
nameSpan = this.sourceSpan(nameStart);
} else {
// No valid identifier was found, so we'll assume an empty pipe name ('').
nameId = '';
// However, there may have been whitespace present between the pipe character and the next
// token in the sequence (or the end of input). We want to track this whitespace so that
// the `BindingPipe` we produce covers not just the pipe character, but any trailing
// whitespace beyond it. Another way of thinking about this is that the zero-length name
// is assumed to be at the end of any whitespace beyond the pipe character.
//
// Therefore, we push the end of the `ParseSpan` for this pipe all the way up to the
// beginning of the next token, or until the end of input if the next token is EOF.
fullSpanEnd = this.next.index !== -1 ? this.next.index : this.input.length + this.offset;
// The `nameSpan` for an empty pipe name is zero-length at the end of any whitespace
// beyond the pipe character.
nameSpan = new ParseSpan(fullSpanEnd, fullSpanEnd).toAbsolute(this.absoluteOffset);
}
const args: AST[] = [];
while (this.consumeOptionalCharacter(chars.$COLON)) {
args.push(this.parseExpression());
// If there are additional expressions beyond the name, then the artificial end for the
// name is no longer relevant.
}
result = new BindingPipe(
this.span(start),
this.sourceSpan(start, fullSpanEnd),
result,
nameId,
args,
nameSpan,
);
} while (this.consumeOptionalOperator('|'));
}
return result;
}
private parseExpression(): AST {
return this.parseConditional();
}
private parseConditional(): AST {
const start = this.inputIndex;
const result = this.parseLogicalOr();
if (this.consumeOptionalOperator('?')) {
const yes = this.parsePipe();
let no: AST;
if (!this.consumeOptionalCharacter(chars.$COLON)) {
const end = this.inputIndex;
const expression = this.input.substring(start, end);
this.error(`Conditional expression ${expression} requires all 3 expressions`);
no = new EmptyExpr(this.span(start), this.sourceSpan(start));
} else {
no = this.parsePipe();
}
return new Conditional(this.span(start), this.sourceSpan(start), result, yes, no);
} else {
return result;
}
}
private parseLogicalOr(): AST {
// '||'
const start = this.inputIndex;
let result = this.parseLogicalAnd();
while (this.consumeOptionalOperator('||')) {
const right = this.parseLogicalAnd();
result = new Binary(this.span(start), this.sourceSpan(start), '||', result, right);
}
return result;
}
private parseLogicalAnd(): AST {
// '&&'
const start = this.inputIndex;
let result = this.parseNullishCoalescing();
while (this.consumeOptionalOperator('&&')) {
const right = this.parseNullishCoalescing();
result = new Binary(this.span(start), this.sourceSpan(start), '&&', result, right);
}
return result;
}
private parseNullishCoalescing(): AST {
// '??'
const start = this.inputIndex;
let result = this.parseEquality();
while (this.consumeOptionalOperator('??')) {
const right = this.parseEquality();
result = new Binary(this.span(start), this.sourceSpan(start), '??', result, right);
}
return result;
}
private parseEquality(): AST {
// '==','!=','===','!=='
const start = this.inputIndex;
let result = this.parseRelational();
while (this.next.type == TokenType.Operator) {
const operator = this.next.strValue;
switch (operator) {
case '==':
case '===':
case '!=':
case '!==':
this.advance();
const right = this.parseRelational();
result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
continue;
}
break;
}
return result;
}
private parseRelational(): AST {
// '<', '>', '<=', '>='
const start = this.inputIndex;
let result = this.parseAdditive();
while (this.next.type == TokenType.Operator) {
const operator = this.next.strValue;
switch (operator) {
case '<':
case '>':
case '<=':
case '>=':
this.advance();
const right = this.parseAdditive();
result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
continue;
}
break;
}
return result;
}
private parseAdditive(): AST {
// '+', '-'
const start = this.inputIndex;
let result = this.parseMultiplicative();
while (this.next.type == TokenType.Operator) {
const operator = this.next.strValue;
switch (operator) {
case '+':
case '-':
this.advance();
let right = this.parseMultiplicative();
result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
continue;
}
break;
}
return result;
}
private parseMultiplicative(): AST {
// '*', '%', '/'
const start = this.inputIndex;
let result = this.parsePrefix();
while (this.next.type == TokenType.Operator) {
const operator = this.next.strValue;
switch (operator) {
case '*':
case '%':
case '/':
this.advance();
let right = this.parsePrefix();
result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
continue;
}
break;
}
return result;
}
private parsePrefix(): AST {
if (this.next.type == TokenType.Operator) {
const start = this.inputIndex;
const operator = this.next.strValue;
let result: AST;
switch (operator) {
case '+':
this.advance();
result = this.parsePrefix();
return Unary.createPlus(this.span(start), this.sourceSpan(start), result);
case '-':
this.advance();
result = this.parsePrefix();
return Unary.createMinus(this.span(start), this.sourceSpan(start), result);
case '!':
this.advance();
result = this.parsePrefix();
return new PrefixNot(this.span(start), this.sourceSpan(start), result);
}
} else if (this.next.isKeywordTypeof()) {
this.advance();
const start = this.inputIndex;
let result = this.parsePrefix();
return new TypeofExpression(this.span(start), this.sourceSpan(start), result);
}
return this.parseCallChain();
}
private parseCallChain(): AST {
const start = this.inputIndex;
let result = this.parsePrimary();
while (true) {
if (this.consumeOptionalCharacter(chars.$PERIOD)) {
result = this.parseAccessMember(result, start, false);
} else if (this.consumeOptionalOperator('?.')) {
if (this.consumeOptionalCharacter(chars.$LPAREN)) {
result = this.parseCall(result, start, true);
} else {
result = this.consumeOptionalCharacter(chars.$LBRACKET)
? this.parseKeyedReadOrWrite(result, start, true)
: this.parseAccessMember(result, start, true);
}
} else if (this.consumeOptionalCharacter(chars.$LBRACKET)) {
result = this.parseKeyedReadOrWrite(result, start, false);
} else if (this.consumeOptionalCharacter(chars.$LPAREN)) {
result = this.parseCall(result, start, false);
} else if (this.consumeOptionalOperator('!')) {
result = new NonNullAssert(this.span(start), this.sourceSpan(start), result);
} else {
return result;
}
}
} | {
"end_byte": 31115,
"start_byte": 22731,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/parser.ts"
} |
angular/packages/compiler/src/expression_parser/parser.ts_31119_39318 | private parsePrimary(): AST {
const start = this.inputIndex;
if (this.consumeOptionalCharacter(chars.$LPAREN)) {
this.rparensExpected++;
const result = this.parsePipe();
this.rparensExpected--;
this.expectCharacter(chars.$RPAREN);
return result;
} else if (this.next.isKeywordNull()) {
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), null);
} else if (this.next.isKeywordUndefined()) {
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), void 0);
} else if (this.next.isKeywordTrue()) {
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), true);
} else if (this.next.isKeywordFalse()) {
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), false);
} else if (this.next.isKeywordThis()) {
this.advance();
return new ThisReceiver(this.span(start), this.sourceSpan(start));
} else if (this.consumeOptionalCharacter(chars.$LBRACKET)) {
this.rbracketsExpected++;
const elements = this.parseExpressionList(chars.$RBRACKET);
this.rbracketsExpected--;
this.expectCharacter(chars.$RBRACKET);
return new LiteralArray(this.span(start), this.sourceSpan(start), elements);
} else if (this.next.isCharacter(chars.$LBRACE)) {
return this.parseLiteralMap();
} else if (this.next.isIdentifier()) {
return this.parseAccessMember(
new ImplicitReceiver(this.span(start), this.sourceSpan(start)),
start,
false,
);
} else if (this.next.isNumber()) {
const value = this.next.toNumber();
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), value);
} else if (this.next.isString()) {
const literalValue = this.next.toString();
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), literalValue);
} else if (this.next.isPrivateIdentifier()) {
this._reportErrorForPrivateIdentifier(this.next, null);
return new EmptyExpr(this.span(start), this.sourceSpan(start));
} else if (this.index >= this.tokens.length) {
this.error(`Unexpected end of expression: ${this.input}`);
return new EmptyExpr(this.span(start), this.sourceSpan(start));
} else {
this.error(`Unexpected token ${this.next}`);
return new EmptyExpr(this.span(start), this.sourceSpan(start));
}
}
private parseExpressionList(terminator: number): AST[] {
const result: AST[] = [];
do {
if (!this.next.isCharacter(terminator)) {
result.push(this.parsePipe());
} else {
break;
}
} while (this.consumeOptionalCharacter(chars.$COMMA));
return result;
}
private parseLiteralMap(): LiteralMap {
const keys: LiteralMapKey[] = [];
const values: AST[] = [];
const start = this.inputIndex;
this.expectCharacter(chars.$LBRACE);
if (!this.consumeOptionalCharacter(chars.$RBRACE)) {
this.rbracesExpected++;
do {
const keyStart = this.inputIndex;
const quoted = this.next.isString();
const key = this.expectIdentifierOrKeywordOrString();
const literalMapKey: LiteralMapKey = {key, quoted};
keys.push(literalMapKey);
// Properties with quoted keys can't use the shorthand syntax.
if (quoted) {
this.expectCharacter(chars.$COLON);
values.push(this.parsePipe());
} else if (this.consumeOptionalCharacter(chars.$COLON)) {
values.push(this.parsePipe());
} else {
literalMapKey.isShorthandInitialized = true;
const span = this.span(keyStart);
const sourceSpan = this.sourceSpan(keyStart);
values.push(
new PropertyRead(
span,
sourceSpan,
sourceSpan,
new ImplicitReceiver(span, sourceSpan),
key,
),
);
}
} while (
this.consumeOptionalCharacter(chars.$COMMA) &&
!this.next.isCharacter(chars.$RBRACE)
);
this.rbracesExpected--;
this.expectCharacter(chars.$RBRACE);
}
return new LiteralMap(this.span(start), this.sourceSpan(start), keys, values);
}
private parseAccessMember(readReceiver: AST, start: number, isSafe: boolean): AST {
const nameStart = this.inputIndex;
const id = this.withContext(ParseContextFlags.Writable, () => {
const id = this.expectIdentifierOrKeyword() ?? '';
if (id.length === 0) {
this.error(`Expected identifier for property access`, readReceiver.span.end);
}
return id;
});
const nameSpan = this.sourceSpan(nameStart);
let receiver: AST;
if (isSafe) {
if (this.consumeOptionalOperator('=')) {
this.error("The '?.' operator cannot be used in the assignment");
receiver = new EmptyExpr(this.span(start), this.sourceSpan(start));
} else {
receiver = new SafePropertyRead(
this.span(start),
this.sourceSpan(start),
nameSpan,
readReceiver,
id,
);
}
} else {
if (this.consumeOptionalOperator('=')) {
if (!(this.parseFlags & ParseFlags.Action)) {
this.error('Bindings cannot contain assignments');
return new EmptyExpr(this.span(start), this.sourceSpan(start));
}
const value = this.parseConditional();
receiver = new PropertyWrite(
this.span(start),
this.sourceSpan(start),
nameSpan,
readReceiver,
id,
value,
);
} else {
receiver = new PropertyRead(
this.span(start),
this.sourceSpan(start),
nameSpan,
readReceiver,
id,
);
}
}
return receiver;
}
private parseCall(receiver: AST, start: number, isSafe: boolean): AST {
const argumentStart = this.inputIndex;
this.rparensExpected++;
const args = this.parseCallArguments();
const argumentSpan = this.span(argumentStart, this.inputIndex).toAbsolute(this.absoluteOffset);
this.expectCharacter(chars.$RPAREN);
this.rparensExpected--;
const span = this.span(start);
const sourceSpan = this.sourceSpan(start);
return isSafe
? new SafeCall(span, sourceSpan, receiver, args, argumentSpan)
: new Call(span, sourceSpan, receiver, args, argumentSpan);
}
private parseCallArguments(): BindingPipe[] {
if (this.next.isCharacter(chars.$RPAREN)) return [];
const positionals: AST[] = [];
do {
positionals.push(this.parsePipe());
} while (this.consumeOptionalCharacter(chars.$COMMA));
return positionals as BindingPipe[];
}
/**
* Parses an identifier, a keyword, a string with an optional `-` in between,
* and returns the string along with its absolute source span.
*/
private expectTemplateBindingKey(): TemplateBindingIdentifier {
let result = '';
let operatorFound = false;
const start = this.currentAbsoluteOffset;
do {
result += this.expectIdentifierOrKeywordOrString();
operatorFound = this.consumeOptionalOperator('-');
if (operatorFound) {
result += '-';
}
} while (operatorFound);
return {
source: result,
span: new AbsoluteSourceSpan(start, start + result.length),
};
}
/**
* Parse microsyntax template expression and return a list of bindings or
* parsing errors in case the given expression is invalid.
*
* For example,
* ```
* <div *ngFor="let item of items; index as i; trackBy: func">
* ```
* contains five bindings:
* 1. ngFor -> null
* 2. item -> NgForOfContext.$implicit
* 3. ngForOf -> items
* 4. i -> NgForOfContext.index
* 5. ngForTrackBy -> func
*
* For a full description of the microsyntax grammar, see
* https://gist.github.com/mhevery/d3530294cff2e4a1b3fe15ff75d08855
*
* @param templateKey name of the microsyntax directive, like ngIf, ngFor,
* without the *, along with its absolute span.
*/ | {
"end_byte": 39318,
"start_byte": 31119,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/parser.ts"
} |
angular/packages/compiler/src/expression_parser/parser.ts_39321_47484 | parseTemplateBindings(templateKey: TemplateBindingIdentifier): TemplateBindingParseResult {
const bindings: TemplateBinding[] = [];
// The first binding is for the template key itself
// In *ngFor="let item of items", key = "ngFor", value = null
// In *ngIf="cond | pipe", key = "ngIf", value = "cond | pipe"
bindings.push(...this.parseDirectiveKeywordBindings(templateKey));
while (this.index < this.tokens.length) {
// If it starts with 'let', then this must be variable declaration
const letBinding = this.parseLetBinding();
if (letBinding) {
bindings.push(letBinding);
} else {
// Two possible cases here, either `value "as" key` or
// "directive-keyword expression". We don't know which case, but both
// "value" and "directive-keyword" are template binding key, so consume
// the key first.
const key = this.expectTemplateBindingKey();
// Peek at the next token, if it is "as" then this must be variable
// declaration.
const binding = this.parseAsBinding(key);
if (binding) {
bindings.push(binding);
} else {
// Otherwise the key must be a directive keyword, like "of". Transform
// the key to actual key. Eg. of -> ngForOf, trackBy -> ngForTrackBy
key.source =
templateKey.source + key.source.charAt(0).toUpperCase() + key.source.substring(1);
bindings.push(...this.parseDirectiveKeywordBindings(key));
}
}
this.consumeStatementTerminator();
}
return new TemplateBindingParseResult(bindings, [] /* warnings */, this.errors);
}
private parseKeyedReadOrWrite(receiver: AST, start: number, isSafe: boolean): AST {
return this.withContext(ParseContextFlags.Writable, () => {
this.rbracketsExpected++;
const key = this.parsePipe();
if (key instanceof EmptyExpr) {
this.error(`Key access cannot be empty`);
}
this.rbracketsExpected--;
this.expectCharacter(chars.$RBRACKET);
if (this.consumeOptionalOperator('=')) {
if (isSafe) {
this.error("The '?.' operator cannot be used in the assignment");
} else {
const value = this.parseConditional();
return new KeyedWrite(this.span(start), this.sourceSpan(start), receiver, key, value);
}
} else {
return isSafe
? new SafeKeyedRead(this.span(start), this.sourceSpan(start), receiver, key)
: new KeyedRead(this.span(start), this.sourceSpan(start), receiver, key);
}
return new EmptyExpr(this.span(start), this.sourceSpan(start));
});
}
/**
* Parse a directive keyword, followed by a mandatory expression.
* For example, "of items", "trackBy: func".
* The bindings are: ngForOf -> items, ngForTrackBy -> func
* There could be an optional "as" binding that follows the expression.
* For example,
* ```
* *ngFor="let item of items | slice:0:1 as collection".
* ^^ ^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
* keyword bound target optional 'as' binding
* ```
*
* @param key binding key, for example, ngFor, ngIf, ngForOf, along with its
* absolute span.
*/
private parseDirectiveKeywordBindings(key: TemplateBindingIdentifier): TemplateBinding[] {
const bindings: TemplateBinding[] = [];
this.consumeOptionalCharacter(chars.$COLON); // trackBy: trackByFunction
const value = this.getDirectiveBoundTarget();
let spanEnd = this.currentAbsoluteOffset;
// The binding could optionally be followed by "as". For example,
// *ngIf="cond | pipe as x". In this case, the key in the "as" binding
// is "x" and the value is the template key itself ("ngIf"). Note that the
// 'key' in the current context now becomes the "value" in the next binding.
const asBinding = this.parseAsBinding(key);
if (!asBinding) {
this.consumeStatementTerminator();
spanEnd = this.currentAbsoluteOffset;
}
const sourceSpan = new AbsoluteSourceSpan(key.span.start, spanEnd);
bindings.push(new ExpressionBinding(sourceSpan, key, value));
if (asBinding) {
bindings.push(asBinding);
}
return bindings;
}
/**
* Return the expression AST for the bound target of a directive keyword
* binding. For example,
* ```
* *ngIf="condition | pipe"
* ^^^^^^^^^^^^^^^^ bound target for "ngIf"
* *ngFor="let item of items"
* ^^^^^ bound target for "ngForOf"
* ```
*/
private getDirectiveBoundTarget(): ASTWithSource | null {
if (this.next === EOF || this.peekKeywordAs() || this.peekKeywordLet()) {
return null;
}
const ast = this.parsePipe(); // example: "condition | async"
const {start, end} = ast.span;
const value = this.input.substring(start, end);
return new ASTWithSource(ast, value, this.location, this.absoluteOffset + start, this.errors);
}
/**
* Return the binding for a variable declared using `as`. Note that the order
* of the key-value pair in this declaration is reversed. For example,
* ```
* *ngFor="let item of items; index as i"
* ^^^^^ ^
* value key
* ```
*
* @param value name of the value in the declaration, "ngIf" in the example
* above, along with its absolute span.
*/
private parseAsBinding(value: TemplateBindingIdentifier): TemplateBinding | null {
if (!this.peekKeywordAs()) {
return null;
}
this.advance(); // consume the 'as' keyword
const key = this.expectTemplateBindingKey();
this.consumeStatementTerminator();
const sourceSpan = new AbsoluteSourceSpan(value.span.start, this.currentAbsoluteOffset);
return new VariableBinding(sourceSpan, key, value);
}
/**
* Return the binding for a variable declared using `let`. For example,
* ```
* *ngFor="let item of items; let i=index;"
* ^^^^^^^^ ^^^^^^^^^^^
* ```
* In the first binding, `item` is bound to `NgForOfContext.$implicit`.
* In the second binding, `i` is bound to `NgForOfContext.index`.
*/
private parseLetBinding(): TemplateBinding | null {
if (!this.peekKeywordLet()) {
return null;
}
const spanStart = this.currentAbsoluteOffset;
this.advance(); // consume the 'let' keyword
const key = this.expectTemplateBindingKey();
let value: TemplateBindingIdentifier | null = null;
if (this.consumeOptionalOperator('=')) {
value = this.expectTemplateBindingKey();
}
this.consumeStatementTerminator();
const sourceSpan = new AbsoluteSourceSpan(spanStart, this.currentAbsoluteOffset);
return new VariableBinding(sourceSpan, key, value);
}
/**
* Consume the optional statement terminator: semicolon or comma.
*/
private consumeStatementTerminator() {
this.consumeOptionalCharacter(chars.$SEMICOLON) || this.consumeOptionalCharacter(chars.$COMMA);
}
/**
* Records an error and skips over the token stream until reaching a recoverable point. See
* `this.skip` for more details on token skipping.
*/
private error(message: string, index: number | null = null) {
this.errors.push(new ParserError(message, this.input, this.locationText(index), this.location));
this.skip();
}
private locationText(index: number | null = null) {
if (index == null) index = this.index;
return index < this.tokens.length
? `at column ${this.tokens[index].index + 1} in`
: `at the end of the expression`;
}
/**
* Records an error for an unexpected private identifier being discovered.
* @param token Token representing a private identifier.
* @param extraMessage Optional additional message being appended to the error.
*/
private _reportErrorForPrivateIdentifier(token: Token, extraMessage: string | null) {
let errorMessage = `Private identifiers are not supported. Unexpected private identifier: ${token}`;
if (extraMessage !== null) {
errorMessage += `, ${extraMessage}`;
}
this.error(errorMessage);
} | {
"end_byte": 47484,
"start_byte": 39321,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/parser.ts"
} |
angular/packages/compiler/src/expression_parser/parser.ts_47488_51505 | /**
* Error recovery should skip tokens until it encounters a recovery point.
*
* The following are treated as unconditional recovery points:
* - end of input
* - ';' (parseChain() is always the root production, and it expects a ';')
* - '|' (since pipes may be chained and each pipe expression may be treated independently)
*
* The following are conditional recovery points:
* - ')', '}', ']' if one of calling productions is expecting one of these symbols
* - This allows skip() to recover from errors such as '(a.) + 1' allowing more of the AST to
* be retained (it doesn't skip any tokens as the ')' is retained because of the '(' begins
* an '(' <expr> ')' production).
* The recovery points of grouping symbols must be conditional as they must be skipped if
* none of the calling productions are not expecting the closing token else we will never
* make progress in the case of an extraneous group closing symbol (such as a stray ')').
* That is, we skip a closing symbol if we are not in a grouping production.
* - '=' in a `Writable` context
* - In this context, we are able to recover after seeing the `=` operator, which
* signals the presence of an independent rvalue expression following the `=` operator.
*
* If a production expects one of these token it increments the corresponding nesting count,
* and then decrements it just prior to checking if the token is in the input.
*/
private skip() {
let n = this.next;
while (
this.index < this.tokens.length &&
!n.isCharacter(chars.$SEMICOLON) &&
!n.isOperator('|') &&
(this.rparensExpected <= 0 || !n.isCharacter(chars.$RPAREN)) &&
(this.rbracesExpected <= 0 || !n.isCharacter(chars.$RBRACE)) &&
(this.rbracketsExpected <= 0 || !n.isCharacter(chars.$RBRACKET)) &&
(!(this.context & ParseContextFlags.Writable) || !n.isOperator('='))
) {
if (this.next.isError()) {
this.errors.push(
new ParserError(this.next.toString()!, this.input, this.locationText(), this.location),
);
}
this.advance();
n = this.next;
}
}
}
class SimpleExpressionChecker extends RecursiveAstVisitor {
errors: string[] = [];
override visitPipe() {
this.errors.push('pipes');
}
}
/**
* Computes the real offset in the original template for indexes in an interpolation.
*
* Because templates can have encoded HTML entities and the input passed to the parser at this stage
* of the compiler is the _decoded_ value, we need to compute the real offset using the original
* encoded values in the interpolated tokens. Note that this is only a special case handling for
* `MlParserTokenType.ENCODED_ENTITY` token types. All other interpolated tokens are expected to
* have parts which exactly match the input string for parsing the interpolation.
*
* @param interpolatedTokens The tokens for the interpolated value.
*
* @returns A map of index locations in the decoded template to indexes in the original template
*/
function getIndexMapForOriginalTemplate(
interpolatedTokens: InterpolatedAttributeToken[] | InterpolatedTextToken[],
): Map<number, number> {
let offsetMap = new Map<number, number>();
let consumedInOriginalTemplate = 0;
let consumedInInput = 0;
let tokenIndex = 0;
while (tokenIndex < interpolatedTokens.length) {
const currentToken = interpolatedTokens[tokenIndex];
if (currentToken.type === MlParserTokenType.ENCODED_ENTITY) {
const [decoded, encoded] = currentToken.parts;
consumedInOriginalTemplate += encoded.length;
consumedInInput += decoded.length;
} else {
const lengthOfParts = currentToken.parts.reduce((sum, current) => sum + current.length, 0);
consumedInInput += lengthOfParts;
consumedInOriginalTemplate += lengthOfParts;
}
offsetMap.set(consumedInInput, consumedInOriginalTemplate);
tokenIndex++;
}
return offsetMap;
} | {
"end_byte": 51505,
"start_byte": 47488,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/expression_parser/parser.ts"
} |
angular/packages/compiler/src/i18n/i18n_html_parser.ts_0_2594 | /**
* @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.dev/license
*/
import {MissingTranslationStrategy} from '../core';
import {DEFAULT_INTERPOLATION_CONFIG} from '../ml_parser/defaults';
import {HtmlParser} from '../ml_parser/html_parser';
import {TokenizeOptions} from '../ml_parser/lexer';
import {ParseTreeResult} from '../ml_parser/parser';
import {Console} from '../util';
import {digest} from './digest';
import {mergeTranslations} from './extractor_merger';
import {Serializer} from './serializers/serializer';
import {Xliff} from './serializers/xliff';
import {Xliff2} from './serializers/xliff2';
import {Xmb} from './serializers/xmb';
import {Xtb} from './serializers/xtb';
import {TranslationBundle} from './translation_bundle';
export class I18NHtmlParser implements HtmlParser {
// @override
getTagDefinition: any;
private _translationBundle: TranslationBundle;
constructor(
private _htmlParser: HtmlParser,
translations?: string,
translationsFormat?: string,
missingTranslation: MissingTranslationStrategy = MissingTranslationStrategy.Warning,
console?: Console,
) {
if (translations) {
const serializer = createSerializer(translationsFormat);
this._translationBundle = TranslationBundle.load(
translations,
'i18n',
serializer,
missingTranslation,
console,
);
} else {
this._translationBundle = new TranslationBundle(
{},
null,
digest,
undefined,
missingTranslation,
console,
);
}
}
parse(source: string, url: string, options: TokenizeOptions = {}): ParseTreeResult {
const interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
const parseResult = this._htmlParser.parse(source, url, {interpolationConfig, ...options});
if (parseResult.errors.length) {
return new ParseTreeResult(parseResult.rootNodes, parseResult.errors);
}
return mergeTranslations(
parseResult.rootNodes,
this._translationBundle,
interpolationConfig,
[],
{},
);
}
}
function createSerializer(format?: string): Serializer {
format = (format || 'xlf').toLowerCase();
switch (format) {
case 'xmb':
return new Xmb();
case 'xtb':
return new Xtb();
case 'xliff2':
case 'xlf2':
return new Xliff2();
case 'xliff':
case 'xlf':
default:
return new Xliff();
}
}
| {
"end_byte": 2594,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/i18n_html_parser.ts"
} |
angular/packages/compiler/src/i18n/i18n_ast.ts_0_8196 | /**
* @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.dev/license
*/
import {ParseSourceSpan} from '../parse_util';
/**
* Describes the text contents of a placeholder as it appears in an ICU expression, including its
* source span information.
*/
export interface MessagePlaceholder {
/** The text contents of the placeholder */
text: string;
/** The source span of the placeholder */
sourceSpan: ParseSourceSpan;
}
export class Message {
sources: MessageSpan[];
id: string;
/** The ids to use if there are no custom id and if `i18nLegacyMessageIdFormat` is not empty */
legacyIds: string[] = [];
messageString: string;
/**
* @param nodes message AST
* @param placeholders maps placeholder names to static content and their source spans
* @param placeholderToMessage maps placeholder names to messages (used for nested ICU messages)
* @param meaning
* @param description
* @param customId
*/
constructor(
public nodes: Node[],
public placeholders: {[phName: string]: MessagePlaceholder},
public placeholderToMessage: {[phName: string]: Message},
public meaning: string,
public description: string,
public customId: string,
) {
this.id = this.customId;
this.messageString = serializeMessage(this.nodes);
if (nodes.length) {
this.sources = [
{
filePath: nodes[0].sourceSpan.start.file.url,
startLine: nodes[0].sourceSpan.start.line + 1,
startCol: nodes[0].sourceSpan.start.col + 1,
endLine: nodes[nodes.length - 1].sourceSpan.end.line + 1,
endCol: nodes[0].sourceSpan.start.col + 1,
},
];
} else {
this.sources = [];
}
}
}
// line and columns indexes are 1 based
export interface MessageSpan {
filePath: string;
startLine: number;
startCol: number;
endLine: number;
endCol: number;
}
export interface Node {
sourceSpan: ParseSourceSpan;
visit(visitor: Visitor, context?: any): any;
}
export class Text implements Node {
constructor(
public value: string,
public sourceSpan: ParseSourceSpan,
) {}
visit(visitor: Visitor, context?: any): any {
return visitor.visitText(this, context);
}
}
// TODO(vicb): do we really need this node (vs an array) ?
export class Container implements Node {
constructor(
public children: Node[],
public sourceSpan: ParseSourceSpan,
) {}
visit(visitor: Visitor, context?: any): any {
return visitor.visitContainer(this, context);
}
}
export class Icu implements Node {
constructor(
public expression: string,
public type: string,
public cases: {[k: string]: Node},
public sourceSpan: ParseSourceSpan,
public expressionPlaceholder?: string,
) {}
visit(visitor: Visitor, context?: any): any {
return visitor.visitIcu(this, context);
}
}
export class TagPlaceholder implements Node {
constructor(
public tag: string,
public attrs: {[k: string]: string},
public startName: string,
public closeName: string,
public children: Node[],
public isVoid: boolean,
// TODO sourceSpan should cover all (we need a startSourceSpan and endSourceSpan)
public sourceSpan: ParseSourceSpan,
public startSourceSpan: ParseSourceSpan | null,
public endSourceSpan: ParseSourceSpan | null,
) {}
visit(visitor: Visitor, context?: any): any {
return visitor.visitTagPlaceholder(this, context);
}
}
export class Placeholder implements Node {
constructor(
public value: string,
public name: string,
public sourceSpan: ParseSourceSpan,
) {}
visit(visitor: Visitor, context?: any): any {
return visitor.visitPlaceholder(this, context);
}
}
export class IcuPlaceholder implements Node {
/** Used to capture a message computed from a previous processing pass (see `setI18nRefs()`). */
previousMessage?: Message;
constructor(
public value: Icu,
public name: string,
public sourceSpan: ParseSourceSpan,
) {}
visit(visitor: Visitor, context?: any): any {
return visitor.visitIcuPlaceholder(this, context);
}
}
export class BlockPlaceholder implements Node {
constructor(
public name: string,
public parameters: string[],
public startName: string,
public closeName: string,
public children: Node[],
public sourceSpan: ParseSourceSpan,
public startSourceSpan: ParseSourceSpan | null,
public endSourceSpan: ParseSourceSpan | null,
) {}
visit(visitor: Visitor, context?: any): any {
return visitor.visitBlockPlaceholder(this, context);
}
}
/**
* Each HTML node that is affect by an i18n tag will also have an `i18n` property that is of type
* `I18nMeta`.
* This information is either a `Message`, which indicates it is the root of an i18n message, or a
* `Node`, which indicates is it part of a containing `Message`.
*/
export type I18nMeta = Message | Node;
export interface Visitor {
visitText(text: Text, context?: any): any;
visitContainer(container: Container, context?: any): any;
visitIcu(icu: Icu, context?: any): any;
visitTagPlaceholder(ph: TagPlaceholder, context?: any): any;
visitPlaceholder(ph: Placeholder, context?: any): any;
visitIcuPlaceholder(ph: IcuPlaceholder, context?: any): any;
visitBlockPlaceholder(ph: BlockPlaceholder, context?: any): any;
}
// Clone the AST
export class CloneVisitor implements Visitor {
visitText(text: Text, context?: any): Text {
return new Text(text.value, text.sourceSpan);
}
visitContainer(container: Container, context?: any): Container {
const children = container.children.map((n) => n.visit(this, context));
return new Container(children, container.sourceSpan);
}
visitIcu(icu: Icu, context?: any): Icu {
const cases: {[k: string]: Node} = {};
Object.keys(icu.cases).forEach((key) => (cases[key] = icu.cases[key].visit(this, context)));
const msg = new Icu(icu.expression, icu.type, cases, icu.sourceSpan, icu.expressionPlaceholder);
return msg;
}
visitTagPlaceholder(ph: TagPlaceholder, context?: any): TagPlaceholder {
const children = ph.children.map((n) => n.visit(this, context));
return new TagPlaceholder(
ph.tag,
ph.attrs,
ph.startName,
ph.closeName,
children,
ph.isVoid,
ph.sourceSpan,
ph.startSourceSpan,
ph.endSourceSpan,
);
}
visitPlaceholder(ph: Placeholder, context?: any): Placeholder {
return new Placeholder(ph.value, ph.name, ph.sourceSpan);
}
visitIcuPlaceholder(ph: IcuPlaceholder, context?: any): IcuPlaceholder {
return new IcuPlaceholder(ph.value, ph.name, ph.sourceSpan);
}
visitBlockPlaceholder(ph: BlockPlaceholder, context?: any): BlockPlaceholder {
const children = ph.children.map((n) => n.visit(this, context));
return new BlockPlaceholder(
ph.name,
ph.parameters,
ph.startName,
ph.closeName,
children,
ph.sourceSpan,
ph.startSourceSpan,
ph.endSourceSpan,
);
}
}
// Visit all the nodes recursively
export class RecurseVisitor implements Visitor {
visitText(text: Text, context?: any): any {}
visitContainer(container: Container, context?: any): any {
container.children.forEach((child) => child.visit(this));
}
visitIcu(icu: Icu, context?: any): any {
Object.keys(icu.cases).forEach((k) => {
icu.cases[k].visit(this);
});
}
visitTagPlaceholder(ph: TagPlaceholder, context?: any): any {
ph.children.forEach((child) => child.visit(this));
}
visitPlaceholder(ph: Placeholder, context?: any): any {}
visitIcuPlaceholder(ph: IcuPlaceholder, context?: any): any {}
visitBlockPlaceholder(ph: BlockPlaceholder, context?: any): any {
ph.children.forEach((child) => child.visit(this));
}
}
/**
* Serialize the message to the Localize backtick string format that would appear in compiled code.
*/
function serializeMessage(messageNodes: Node[]): string {
const visitor = new LocalizeMessageStringVisitor();
const str = messageNodes.map((n) => n.visit(visitor)).join('');
return str;
} | {
"end_byte": 8196,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/i18n_ast.ts"
} |
angular/packages/compiler/src/i18n/i18n_ast.ts_8198_9215 | class LocalizeMessageStringVisitor implements Visitor {
visitText(text: Text): any {
return text.value;
}
visitContainer(container: Container): any {
return container.children.map((child) => child.visit(this)).join('');
}
visitIcu(icu: Icu): any {
const strCases = Object.keys(icu.cases).map(
(k: string) => `${k} {${icu.cases[k].visit(this)}}`,
);
return `{${icu.expressionPlaceholder}, ${icu.type}, ${strCases.join(' ')}}`;
}
visitTagPlaceholder(ph: TagPlaceholder): any {
const children = ph.children.map((child) => child.visit(this)).join('');
return `{$${ph.startName}}${children}{$${ph.closeName}}`;
}
visitPlaceholder(ph: Placeholder): any {
return `{$${ph.name}}`;
}
visitIcuPlaceholder(ph: IcuPlaceholder): any {
return `{$${ph.name}}`;
}
visitBlockPlaceholder(ph: BlockPlaceholder): any {
const children = ph.children.map((child) => child.visit(this)).join('');
return `{$${ph.startName}}${children}{$${ph.closeName}}`;
}
} | {
"end_byte": 9215,
"start_byte": 8198,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/i18n_ast.ts"
} |
angular/packages/compiler/src/i18n/i18n_parser.ts_0_2253 | /**
* @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.dev/license
*/
import {Lexer as ExpressionLexer} from '../expression_parser/lexer';
import {Parser as ExpressionParser} from '../expression_parser/parser';
import {serialize as serializeExpression} from '../expression_parser/serializer';
import * as html from '../ml_parser/ast';
import {InterpolationConfig} from '../ml_parser/defaults';
import {getHtmlTagDefinition} from '../ml_parser/html_tags';
import {
AttributeValueInterpolationToken,
InterpolatedAttributeToken,
InterpolatedTextToken,
InterpolationToken,
TokenType,
} from '../ml_parser/tokens';
import {ParseSourceSpan} from '../parse_util';
import * as i18n from './i18n_ast';
import {PlaceholderRegistry} from './serializers/placeholder';
const _expParser = new ExpressionParser(new ExpressionLexer());
export type VisitNodeFn = (html: html.Node, i18n: i18n.Node) => i18n.Node;
export interface I18nMessageFactory {
(
nodes: html.Node[],
meaning: string | undefined,
description: string | undefined,
customId: string | undefined,
visitNodeFn?: VisitNodeFn,
): i18n.Message;
}
/**
* Returns a function converting html nodes to an i18n Message given an interpolationConfig
*/
export function createI18nMessageFactory(
interpolationConfig: InterpolationConfig,
containerBlocks: Set<string>,
retainEmptyTokens: boolean,
preserveExpressionWhitespace: boolean,
): I18nMessageFactory {
const visitor = new _I18nVisitor(
_expParser,
interpolationConfig,
containerBlocks,
retainEmptyTokens,
preserveExpressionWhitespace,
);
return (nodes, meaning, description, customId, visitNodeFn) =>
visitor.toI18nMessage(nodes, meaning, description, customId, visitNodeFn);
}
interface I18nMessageVisitorContext {
isIcu: boolean;
icuDepth: number;
placeholderRegistry: PlaceholderRegistry;
placeholderToContent: {[phName: string]: i18n.MessagePlaceholder};
placeholderToMessage: {[phName: string]: i18n.Message};
visitNodeFn: VisitNodeFn;
}
function noopVisitNodeFn(_html: html.Node, i18n: i18n.Node): i18n.Node {
return i18n;
} | {
"end_byte": 2253,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/i18n_parser.ts"
} |
angular/packages/compiler/src/i18n/i18n_parser.ts_2255_9004 | class _I18nVisitor implements html.Visitor {
constructor(
private _expressionParser: ExpressionParser,
private _interpolationConfig: InterpolationConfig,
private _containerBlocks: Set<string>,
private readonly _retainEmptyTokens: boolean,
private readonly _preserveExpressionWhitespace: boolean,
) {}
public toI18nMessage(
nodes: html.Node[],
meaning = '',
description = '',
customId = '',
visitNodeFn: VisitNodeFn | undefined,
): i18n.Message {
const context: I18nMessageVisitorContext = {
isIcu: nodes.length == 1 && nodes[0] instanceof html.Expansion,
icuDepth: 0,
placeholderRegistry: new PlaceholderRegistry(),
placeholderToContent: {},
placeholderToMessage: {},
visitNodeFn: visitNodeFn || noopVisitNodeFn,
};
const i18nodes: i18n.Node[] = html.visitAll(this, nodes, context);
return new i18n.Message(
i18nodes,
context.placeholderToContent,
context.placeholderToMessage,
meaning,
description,
customId,
);
}
visitElement(el: html.Element, context: I18nMessageVisitorContext): i18n.Node {
const children = html.visitAll(this, el.children, context);
const attrs: {[k: string]: string} = {};
el.attrs.forEach((attr) => {
// Do not visit the attributes, translatable ones are top-level ASTs
attrs[attr.name] = attr.value;
});
const isVoid: boolean = getHtmlTagDefinition(el.name).isVoid;
const startPhName = context.placeholderRegistry.getStartTagPlaceholderName(
el.name,
attrs,
isVoid,
);
context.placeholderToContent[startPhName] = {
text: el.startSourceSpan.toString(),
sourceSpan: el.startSourceSpan,
};
let closePhName = '';
if (!isVoid) {
closePhName = context.placeholderRegistry.getCloseTagPlaceholderName(el.name);
context.placeholderToContent[closePhName] = {
text: `</${el.name}>`,
sourceSpan: el.endSourceSpan ?? el.sourceSpan,
};
}
const node = new i18n.TagPlaceholder(
el.name,
attrs,
startPhName,
closePhName,
children,
isVoid,
el.sourceSpan,
el.startSourceSpan,
el.endSourceSpan,
);
return context.visitNodeFn(el, node);
}
visitAttribute(attribute: html.Attribute, context: I18nMessageVisitorContext): i18n.Node {
const node =
attribute.valueTokens === undefined || attribute.valueTokens.length === 1
? new i18n.Text(attribute.value, attribute.valueSpan || attribute.sourceSpan)
: this._visitTextWithInterpolation(
attribute.valueTokens,
attribute.valueSpan || attribute.sourceSpan,
context,
attribute.i18n,
);
return context.visitNodeFn(attribute, node);
}
visitText(text: html.Text, context: I18nMessageVisitorContext): i18n.Node {
const node =
text.tokens.length === 1
? new i18n.Text(text.value, text.sourceSpan)
: this._visitTextWithInterpolation(text.tokens, text.sourceSpan, context, text.i18n);
return context.visitNodeFn(text, node);
}
visitComment(comment: html.Comment, context: I18nMessageVisitorContext): i18n.Node | null {
return null;
}
visitExpansion(icu: html.Expansion, context: I18nMessageVisitorContext): i18n.Node {
context.icuDepth++;
const i18nIcuCases: {[k: string]: i18n.Node} = {};
const i18nIcu = new i18n.Icu(icu.switchValue, icu.type, i18nIcuCases, icu.sourceSpan);
icu.cases.forEach((caze): void => {
i18nIcuCases[caze.value] = new i18n.Container(
caze.expression.map((node) => node.visit(this, context)),
caze.expSourceSpan,
);
});
context.icuDepth--;
if (context.isIcu || context.icuDepth > 0) {
// Returns an ICU node when:
// - the message (vs a part of the message) is an ICU message, or
// - the ICU message is nested.
const expPh = context.placeholderRegistry.getUniquePlaceholder(`VAR_${icu.type}`);
i18nIcu.expressionPlaceholder = expPh;
context.placeholderToContent[expPh] = {
text: icu.switchValue,
sourceSpan: icu.switchValueSourceSpan,
};
return context.visitNodeFn(icu, i18nIcu);
}
// Else returns a placeholder
// ICU placeholders should not be replaced with their original content but with the their
// translations.
// TODO(vicb): add a html.Node -> i18n.Message cache to avoid having to re-create the msg
const phName = context.placeholderRegistry.getPlaceholderName('ICU', icu.sourceSpan.toString());
context.placeholderToMessage[phName] = this.toI18nMessage([icu], '', '', '', undefined);
const node = new i18n.IcuPlaceholder(i18nIcu, phName, icu.sourceSpan);
return context.visitNodeFn(icu, node);
}
visitExpansionCase(_icuCase: html.ExpansionCase, _context: I18nMessageVisitorContext): i18n.Node {
throw new Error('Unreachable code');
}
visitBlock(block: html.Block, context: I18nMessageVisitorContext) {
const children = html.visitAll(this, block.children, context);
if (this._containerBlocks.has(block.name)) {
return new i18n.Container(children, block.sourceSpan);
}
const parameters = block.parameters.map((param) => param.expression);
const startPhName = context.placeholderRegistry.getStartBlockPlaceholderName(
block.name,
parameters,
);
const closePhName = context.placeholderRegistry.getCloseBlockPlaceholderName(block.name);
context.placeholderToContent[startPhName] = {
text: block.startSourceSpan.toString(),
sourceSpan: block.startSourceSpan,
};
context.placeholderToContent[closePhName] = {
text: block.endSourceSpan ? block.endSourceSpan.toString() : '}',
sourceSpan: block.endSourceSpan ?? block.sourceSpan,
};
const node = new i18n.BlockPlaceholder(
block.name,
parameters,
startPhName,
closePhName,
children,
block.sourceSpan,
block.startSourceSpan,
block.endSourceSpan,
);
return context.visitNodeFn(block, node);
}
visitBlockParameter(_parameter: html.BlockParameter, _context: I18nMessageVisitorContext) {
throw new Error('Unreachable code');
}
visitLetDeclaration(decl: html.LetDeclaration, context: any) {
return null;
}
/**
* Convert, text and interpolated tokens up into text and placeholder pieces.
*
* @param tokens The text and interpolated tokens.
* @param sourceSpan The span of the whole of the `text` string.
* @param context The current context of the visitor, used to compute and store placeholders.
* @param previousI18n Any i18n metadata associated with this `text` from a previous pass.
*/ | {
"end_byte": 9004,
"start_byte": 2255,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/i18n_parser.ts"
} |
angular/packages/compiler/src/i18n/i18n_parser.ts_9007_16409 | private _visitTextWithInterpolation(
tokens: (InterpolatedTextToken | InterpolatedAttributeToken)[],
sourceSpan: ParseSourceSpan,
context: I18nMessageVisitorContext,
previousI18n: i18n.I18nMeta | undefined,
): i18n.Node {
// Return a sequence of `Text` and `Placeholder` nodes grouped in a `Container`.
const nodes: i18n.Node[] = [];
// We will only create a container if there are actually interpolations,
// so this flag tracks that.
let hasInterpolation = false;
for (const token of tokens) {
switch (token.type) {
case TokenType.INTERPOLATION:
case TokenType.ATTR_VALUE_INTERPOLATION:
hasInterpolation = true;
const [startMarker, expression, endMarker] = token.parts;
const baseName = extractPlaceholderName(expression) || 'INTERPOLATION';
const phName = context.placeholderRegistry.getPlaceholderName(baseName, expression);
if (this._preserveExpressionWhitespace) {
context.placeholderToContent[phName] = {
text: token.parts.join(''),
sourceSpan: token.sourceSpan,
};
nodes.push(new i18n.Placeholder(expression, phName, token.sourceSpan));
} else {
const normalized = this.normalizeExpression(token);
context.placeholderToContent[phName] = {
text: `${startMarker}${normalized}${endMarker}`,
sourceSpan: token.sourceSpan,
};
nodes.push(new i18n.Placeholder(normalized, phName, token.sourceSpan));
}
break;
default:
// Try to merge text tokens with previous tokens. We do this even for all tokens
// when `retainEmptyTokens == true` because whitespace tokens may have non-zero
// length, but will be trimmed by `WhitespaceVisitor` in one extraction pass and
// be considered "empty" there. Therefore a whitespace token with
// `retainEmptyTokens === true` should be treated like an empty token and either
// retained or merged into the previous node. Since extraction does two passes with
// different trimming behavior, the second pass needs to have identical node count
// to reuse source spans, so we need this check to get the same answer when both
// trimming and not trimming.
if (token.parts[0].length > 0 || this._retainEmptyTokens) {
// This token is text or an encoded entity.
// If it is following on from a previous text node then merge it into that node
// Otherwise, if it is following an interpolation, then add a new node.
const previous = nodes[nodes.length - 1];
if (previous instanceof i18n.Text) {
previous.value += token.parts[0];
previous.sourceSpan = new ParseSourceSpan(
previous.sourceSpan.start,
token.sourceSpan.end,
previous.sourceSpan.fullStart,
previous.sourceSpan.details,
);
} else {
nodes.push(new i18n.Text(token.parts[0], token.sourceSpan));
}
} else {
// Retain empty tokens to avoid breaking dropping entire nodes such that source
// spans should not be reusable across multiple parses of a template. We *should*
// do this all the time, however we need to maintain backwards compatibility
// with existing message IDs so we can't do it by default and should only enable
// this when removing significant whitespace.
if (this._retainEmptyTokens) {
nodes.push(new i18n.Text(token.parts[0], token.sourceSpan));
}
}
break;
}
}
if (hasInterpolation) {
// Whitespace removal may have invalidated the interpolation source-spans.
reusePreviousSourceSpans(nodes, previousI18n);
return new i18n.Container(nodes, sourceSpan);
} else {
return nodes[0];
}
}
// Normalize expression whitespace by parsing and re-serializing it. This makes
// message IDs more durable to insignificant whitespace changes.
normalizeExpression(token: InterpolationToken | AttributeValueInterpolationToken): string {
const expression = token.parts[1];
const expr = this._expressionParser.parseBinding(
expression,
/* location */ token.sourceSpan.start.toString(),
/* absoluteOffset */ token.sourceSpan.start.offset,
this._interpolationConfig,
);
return serializeExpression(expr);
}
}
/**
* Re-use the source-spans from `previousI18n` metadata for the `nodes`.
*
* Whitespace removal can invalidate the source-spans of interpolation nodes, so we
* reuse the source-span stored from a previous pass before the whitespace was removed.
*
* @param nodes The `Text` and `Placeholder` nodes to be processed.
* @param previousI18n Any i18n metadata for these `nodes` stored from a previous pass.
*/
function reusePreviousSourceSpans(
nodes: i18n.Node[],
previousI18n: i18n.I18nMeta | undefined,
): void {
if (previousI18n instanceof i18n.Message) {
// The `previousI18n` is an i18n `Message`, so we are processing an `Attribute` with i18n
// metadata. The `Message` should consist only of a single `Container` that contains the
// parts (`Text` and `Placeholder`) to process.
assertSingleContainerMessage(previousI18n);
previousI18n = previousI18n.nodes[0];
}
if (previousI18n instanceof i18n.Container) {
// The `previousI18n` is a `Container`, which means that this is a second i18n extraction pass
// after whitespace has been removed from the AST nodes.
assertEquivalentNodes(previousI18n.children, nodes);
// Reuse the source-spans from the first pass.
for (let i = 0; i < nodes.length; i++) {
nodes[i].sourceSpan = previousI18n.children[i].sourceSpan;
}
}
}
/**
* Asserts that the `message` contains exactly one `Container` node.
*/
function assertSingleContainerMessage(message: i18n.Message): void {
const nodes = message.nodes;
if (nodes.length !== 1 || !(nodes[0] instanceof i18n.Container)) {
throw new Error(
'Unexpected previous i18n message - expected it to consist of only a single `Container` node.',
);
}
}
/**
* Asserts that the `previousNodes` and `node` collections have the same number of elements and
* corresponding elements have the same node type.
*/
function assertEquivalentNodes(previousNodes: i18n.Node[], nodes: i18n.Node[]): void {
if (previousNodes.length !== nodes.length) {
throw new Error(
`
The number of i18n message children changed between first and second pass.
First pass (${previousNodes.length} tokens):
${previousNodes.map((node) => `"${node.sourceSpan.toString()}"`).join('\n')}
Second pass (${nodes.length} tokens):
${nodes.map((node) => `"${node.sourceSpan.toString()}"`).join('\n')}
`.trim(),
);
}
if (previousNodes.some((node, i) => nodes[i].constructor !== node.constructor)) {
throw new Error(
'The types of the i18n message children changed between first and second pass.',
);
}
}
const _CUSTOM_PH_EXP =
/\/\/[\s\S]*i18n[\s\S]*\([\s\S]*ph[\s\S]*=[\s\S]*("|')([\s\S]*?)\1[\s\S]*\)/g;
function extractPlaceholderName(input: string): string {
return input.split(_CUSTOM_PH_EXP)[2];
} | {
"end_byte": 16409,
"start_byte": 9007,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/i18n_parser.ts"
} |
angular/packages/compiler/src/i18n/translation_bundle.ts_0_8127 | /**
* @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.dev/license
*/
import {MissingTranslationStrategy} from '../core';
import * as html from '../ml_parser/ast';
import {HtmlParser} from '../ml_parser/html_parser';
import {Console} from '../util';
import * as i18n from './i18n_ast';
import {I18nError} from './parse_util';
import {PlaceholderMapper, Serializer} from './serializers/serializer';
import {escapeXml} from './serializers/xml_helper';
/**
* A container for translated messages
*/
export class TranslationBundle {
private _i18nToHtml: I18nToHtmlVisitor;
constructor(
private _i18nNodesByMsgId: {[msgId: string]: i18n.Node[]} = {},
locale: string | null,
public digest: (m: i18n.Message) => string,
public mapperFactory?: (m: i18n.Message) => PlaceholderMapper,
missingTranslationStrategy: MissingTranslationStrategy = MissingTranslationStrategy.Warning,
console?: Console,
) {
this._i18nToHtml = new I18nToHtmlVisitor(
_i18nNodesByMsgId,
locale,
digest,
mapperFactory!,
missingTranslationStrategy,
console,
);
}
// Creates a `TranslationBundle` by parsing the given `content` with the `serializer`.
static load(
content: string,
url: string,
serializer: Serializer,
missingTranslationStrategy: MissingTranslationStrategy,
console?: Console,
): TranslationBundle {
const {locale, i18nNodesByMsgId} = serializer.load(content, url);
const digestFn = (m: i18n.Message) => serializer.digest(m);
const mapperFactory = (m: i18n.Message) => serializer.createNameMapper(m)!;
return new TranslationBundle(
i18nNodesByMsgId,
locale,
digestFn,
mapperFactory,
missingTranslationStrategy,
console,
);
}
// Returns the translation as HTML nodes from the given source message.
get(srcMsg: i18n.Message): html.Node[] {
const html = this._i18nToHtml.convert(srcMsg);
if (html.errors.length) {
throw new Error(html.errors.join('\n'));
}
return html.nodes;
}
has(srcMsg: i18n.Message): boolean {
return this.digest(srcMsg) in this._i18nNodesByMsgId;
}
}
class I18nToHtmlVisitor implements i18n.Visitor {
// using non-null assertions because they're (re)set by convert()
private _srcMsg!: i18n.Message;
private _errors: I18nError[] = [];
private _contextStack: {msg: i18n.Message; mapper: (name: string) => string}[] = [];
private _mapper!: (name: string) => string;
constructor(
private _i18nNodesByMsgId: {[msgId: string]: i18n.Node[]} = {},
private _locale: string | null,
private _digest: (m: i18n.Message) => string,
private _mapperFactory: (m: i18n.Message) => PlaceholderMapper,
private _missingTranslationStrategy: MissingTranslationStrategy,
private _console?: Console,
) {}
convert(srcMsg: i18n.Message): {nodes: html.Node[]; errors: I18nError[]} {
this._contextStack.length = 0;
this._errors.length = 0;
// i18n to text
const text = this._convertToText(srcMsg);
// text to html
const url = srcMsg.nodes[0].sourceSpan.start.file.url;
const html = new HtmlParser().parse(text, url, {tokenizeExpansionForms: true});
return {
nodes: html.rootNodes,
errors: [...this._errors, ...html.errors],
};
}
visitText(text: i18n.Text, context?: any): string {
// `convert()` uses an `HtmlParser` to return `html.Node`s
// we should then make sure that any special characters are escaped
return escapeXml(text.value);
}
visitContainer(container: i18n.Container, context?: any): any {
return container.children.map((n) => n.visit(this)).join('');
}
visitIcu(icu: i18n.Icu, context?: any): any {
const cases = Object.keys(icu.cases).map((k) => `${k} {${icu.cases[k].visit(this)}}`);
// TODO(vicb): Once all format switch to using expression placeholders
// we should throw when the placeholder is not in the source message
const exp = this._srcMsg.placeholders.hasOwnProperty(icu.expression)
? this._srcMsg.placeholders[icu.expression].text
: icu.expression;
return `{${exp}, ${icu.type}, ${cases.join(' ')}}`;
}
visitPlaceholder(ph: i18n.Placeholder, context?: any): string {
const phName = this._mapper(ph.name);
if (this._srcMsg.placeholders.hasOwnProperty(phName)) {
return this._srcMsg.placeholders[phName].text;
}
if (this._srcMsg.placeholderToMessage.hasOwnProperty(phName)) {
return this._convertToText(this._srcMsg.placeholderToMessage[phName]);
}
this._addError(ph, `Unknown placeholder "${ph.name}"`);
return '';
}
// Loaded message contains only placeholders (vs tag and icu placeholders).
// However when a translation can not be found, we need to serialize the source message
// which can contain tag placeholders
visitTagPlaceholder(ph: i18n.TagPlaceholder, context?: any): string {
const tag = `${ph.tag}`;
const attrs = Object.keys(ph.attrs)
.map((name) => `${name}="${ph.attrs[name]}"`)
.join(' ');
if (ph.isVoid) {
return `<${tag} ${attrs}/>`;
}
const children = ph.children.map((c: i18n.Node) => c.visit(this)).join('');
return `<${tag} ${attrs}>${children}</${tag}>`;
}
// Loaded message contains only placeholders (vs tag and icu placeholders).
// However when a translation can not be found, we need to serialize the source message
// which can contain tag placeholders
visitIcuPlaceholder(ph: i18n.IcuPlaceholder, context?: any): string {
// An ICU placeholder references the source message to be serialized
return this._convertToText(this._srcMsg.placeholderToMessage[ph.name]);
}
visitBlockPlaceholder(ph: i18n.BlockPlaceholder, context?: any): string {
const params = ph.parameters.length === 0 ? '' : ` (${ph.parameters.join('; ')})`;
const children = ph.children.map((c: i18n.Node) => c.visit(this)).join('');
return `@${ph.name}${params} {${children}}`;
}
/**
* Convert a source message to a translated text string:
* - text nodes are replaced with their translation,
* - placeholders are replaced with their content,
* - ICU nodes are converted to ICU expressions.
*/
private _convertToText(srcMsg: i18n.Message): string {
const id = this._digest(srcMsg);
const mapper = this._mapperFactory ? this._mapperFactory(srcMsg) : null;
let nodes: i18n.Node[];
this._contextStack.push({msg: this._srcMsg, mapper: this._mapper});
this._srcMsg = srcMsg;
if (this._i18nNodesByMsgId.hasOwnProperty(id)) {
// When there is a translation use its nodes as the source
// And create a mapper to convert serialized placeholder names to internal names
nodes = this._i18nNodesByMsgId[id];
this._mapper = (name: string) => (mapper ? mapper.toInternalName(name)! : name);
} else {
// When no translation has been found
// - report an error / a warning / nothing,
// - use the nodes from the original message
// - placeholders are already internal and need no mapper
if (this._missingTranslationStrategy === MissingTranslationStrategy.Error) {
const ctx = this._locale ? ` for locale "${this._locale}"` : '';
this._addError(srcMsg.nodes[0], `Missing translation for message "${id}"${ctx}`);
} else if (
this._console &&
this._missingTranslationStrategy === MissingTranslationStrategy.Warning
) {
const ctx = this._locale ? ` for locale "${this._locale}"` : '';
this._console.warn(`Missing translation for message "${id}"${ctx}`);
}
nodes = srcMsg.nodes;
this._mapper = (name: string) => name;
}
const text = nodes.map((node) => node.visit(this)).join('');
const context = this._contextStack.pop()!;
this._srcMsg = context.msg;
this._mapper = context.mapper;
return text;
}
private _addError(el: i18n.Node, msg: string) {
this._errors.push(new I18nError(el.sourceSpan, msg));
}
}
| {
"end_byte": 8127,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/translation_bundle.ts"
} |
angular/packages/compiler/src/i18n/parse_util.ts_0_414 | /**
* @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.dev/license
*/
import {ParseError, ParseSourceSpan} from '../parse_util';
/**
* An i18n error.
*/
export class I18nError extends ParseError {
constructor(span: ParseSourceSpan, msg: string) {
super(span, msg);
}
}
| {
"end_byte": 414,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/parse_util.ts"
} |
angular/packages/compiler/src/i18n/extractor_merger.ts_0_7512 | /**
* @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.dev/license
*/
import * as html from '../ml_parser/ast';
import {DEFAULT_CONTAINER_BLOCKS, InterpolationConfig} from '../ml_parser/defaults';
import {ParseTreeResult} from '../ml_parser/parser';
import {TokenType} from '../ml_parser/tokens';
import * as i18n from './i18n_ast';
import {createI18nMessageFactory, I18nMessageFactory} from './i18n_parser';
import {I18nError} from './parse_util';
import {TranslationBundle} from './translation_bundle';
const _I18N_ATTR = 'i18n';
const _I18N_ATTR_PREFIX = 'i18n-';
const _I18N_COMMENT_PREFIX_REGEXP = /^i18n:?/;
const MEANING_SEPARATOR = '|';
const ID_SEPARATOR = '@@';
let i18nCommentsWarned = false;
/**
* Extract translatable messages from an html AST
*/
export function extractMessages(
nodes: html.Node[],
interpolationConfig: InterpolationConfig,
implicitTags: string[],
implicitAttrs: {[k: string]: string[]},
preserveSignificantWhitespace: boolean,
): ExtractionResult {
const visitor = new _Visitor(implicitTags, implicitAttrs, preserveSignificantWhitespace);
return visitor.extract(nodes, interpolationConfig);
}
export function mergeTranslations(
nodes: html.Node[],
translations: TranslationBundle,
interpolationConfig: InterpolationConfig,
implicitTags: string[],
implicitAttrs: {[k: string]: string[]},
): ParseTreeResult {
const visitor = new _Visitor(implicitTags, implicitAttrs);
return visitor.merge(nodes, translations, interpolationConfig);
}
export class ExtractionResult {
constructor(
public messages: i18n.Message[],
public errors: I18nError[],
) {}
}
enum _VisitorMode {
Extract,
Merge,
}
/**
* This Visitor is used:
* 1. to extract all the translatable strings from an html AST (see `extract()`),
* 2. to replace the translatable strings with the actual translations (see `merge()`)
*
* @internal
*/
class _Visitor implements html.Visitor {
// Using non-null assertions because all variables are (re)set in init()
private _depth!: number;
// <el i18n>...</el>
private _inI18nNode!: boolean;
private _inImplicitNode!: boolean;
// <!--i18n-->...<!--/i18n-->
private _inI18nBlock!: boolean;
private _blockMeaningAndDesc!: string;
private _blockChildren!: html.Node[];
private _blockStartDepth!: number;
// {<icu message>}
private _inIcu!: boolean;
// set to void 0 when not in a section
private _msgCountAtSectionStart: number | undefined;
private _errors!: I18nError[];
private _mode!: _VisitorMode;
// _VisitorMode.Extract only
private _messages!: i18n.Message[];
// _VisitorMode.Merge only
private _translations!: TranslationBundle;
private _createI18nMessage!: I18nMessageFactory;
constructor(
private _implicitTags: string[],
private _implicitAttrs: {[k: string]: string[]},
private readonly _preserveSignificantWhitespace: boolean = true,
) {}
/**
* Extracts the messages from the tree
*/
extract(nodes: html.Node[], interpolationConfig: InterpolationConfig): ExtractionResult {
this._init(_VisitorMode.Extract, interpolationConfig);
nodes.forEach((node) => node.visit(this, null));
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], 'Unclosed block');
}
return new ExtractionResult(this._messages, this._errors);
}
/**
* Returns a tree where all translatable nodes are translated
*/
merge(
nodes: html.Node[],
translations: TranslationBundle,
interpolationConfig: InterpolationConfig,
): ParseTreeResult {
this._init(_VisitorMode.Merge, interpolationConfig);
this._translations = translations;
// Construct a single fake root element
const wrapper = new html.Element('wrapper', [], nodes, undefined!, undefined!, undefined);
const translatedNode = wrapper.visit(this, null);
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], 'Unclosed block');
}
return new ParseTreeResult(translatedNode.children, this._errors);
}
visitExpansionCase(icuCase: html.ExpansionCase, context: any): any {
// Parse cases for translatable html attributes
const expression = html.visitAll(this, icuCase.expression, context);
if (this._mode === _VisitorMode.Merge) {
return new html.ExpansionCase(
icuCase.value,
expression,
icuCase.sourceSpan,
icuCase.valueSourceSpan,
icuCase.expSourceSpan,
);
}
}
visitExpansion(icu: html.Expansion, context: any): html.Expansion {
this._mayBeAddBlockChildren(icu);
const wasInIcu = this._inIcu;
if (!this._inIcu) {
// nested ICU messages should not be extracted but top-level translated as a whole
if (this._isInTranslatableSection) {
this._addMessage([icu]);
}
this._inIcu = true;
}
const cases = html.visitAll(this, icu.cases, context);
if (this._mode === _VisitorMode.Merge) {
icu = new html.Expansion(
icu.switchValue,
icu.type,
cases,
icu.sourceSpan,
icu.switchValueSourceSpan,
);
}
this._inIcu = wasInIcu;
return icu;
}
visitComment(comment: html.Comment, context: any): any {
const isOpening = _isOpeningComment(comment);
if (isOpening && this._isInTranslatableSection) {
this._reportError(comment, 'Could not start a block inside a translatable section');
return;
}
const isClosing = _isClosingComment(comment);
if (isClosing && !this._inI18nBlock) {
this._reportError(comment, 'Trying to close an unopened block');
return;
}
if (!this._inI18nNode && !this._inIcu) {
if (!this._inI18nBlock) {
if (isOpening) {
// deprecated from v5 you should use <ng-container i18n> instead of i18n comments
if (!i18nCommentsWarned && <any>console && <any>console.warn) {
i18nCommentsWarned = true;
const details = comment.sourceSpan.details ? `, ${comment.sourceSpan.details}` : '';
// TODO(ocombe): use a log service once there is a public one available
console.warn(
`I18n comments are deprecated, use an <ng-container> element instead (${comment.sourceSpan.start}${details})`,
);
}
this._inI18nBlock = true;
this._blockStartDepth = this._depth;
this._blockChildren = [];
this._blockMeaningAndDesc = comment
.value!.replace(_I18N_COMMENT_PREFIX_REGEXP, '')
.trim();
this._openTranslatableSection(comment);
}
} else {
if (isClosing) {
if (this._depth == this._blockStartDepth) {
this._closeTranslatableSection(comment, this._blockChildren);
this._inI18nBlock = false;
const message = this._addMessage(this._blockChildren, this._blockMeaningAndDesc)!;
// merge attributes in sections
const nodes = this._translateMessage(comment, message);
return html.visitAll(this, nodes);
} else {
this._reportError(comment, 'I18N blocks should not cross element boundaries');
return;
}
}
}
}
}
visitText(text: html.Text, context: any): html.Text {
if (this._isInTranslatableSection) {
this._mayBeAddBlockChildren(text);
}
return text;
} | {
"end_byte": 7512,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/extractor_merger.ts"
} |
angular/packages/compiler/src/i18n/extractor_merger.ts_7516_14970 | visitElement(el: html.Element, context: any): html.Element | null {
this._mayBeAddBlockChildren(el);
this._depth++;
const wasInI18nNode = this._inI18nNode;
const wasInImplicitNode = this._inImplicitNode;
let childNodes: html.Node[] = [];
let translatedChildNodes: html.Node[] = undefined!;
// Extract:
// - top level nodes with the (implicit) "i18n" attribute if not already in a section
// - ICU messages
const i18nAttr = _getI18nAttr(el);
const i18nMeta = i18nAttr ? i18nAttr.value : '';
const isImplicit =
this._implicitTags.some((tag) => el.name === tag) &&
!this._inIcu &&
!this._isInTranslatableSection;
const isTopLevelImplicit = !wasInImplicitNode && isImplicit;
this._inImplicitNode = wasInImplicitNode || isImplicit;
if (!this._isInTranslatableSection && !this._inIcu) {
if (i18nAttr || isTopLevelImplicit) {
this._inI18nNode = true;
const message = this._addMessage(el.children, i18nMeta)!;
translatedChildNodes = this._translateMessage(el, message);
}
if (this._mode == _VisitorMode.Extract) {
const isTranslatable = i18nAttr || isTopLevelImplicit;
if (isTranslatable) this._openTranslatableSection(el);
html.visitAll(this, el.children);
if (isTranslatable) this._closeTranslatableSection(el, el.children);
}
} else {
if (i18nAttr || isTopLevelImplicit) {
this._reportError(
el,
'Could not mark an element as translatable inside a translatable section',
);
}
if (this._mode == _VisitorMode.Extract) {
// Descend into child nodes for extraction
html.visitAll(this, el.children);
}
}
if (this._mode === _VisitorMode.Merge) {
const visitNodes = translatedChildNodes || el.children;
visitNodes.forEach((child) => {
const visited = child.visit(this, context);
if (visited && !this._isInTranslatableSection) {
// Do not add the children from translatable sections (= i18n blocks here)
// They will be added later in this loop when the block closes (i.e. on `<!-- /i18n -->`)
childNodes = childNodes.concat(visited);
}
});
}
this._visitAttributesOf(el);
this._depth--;
this._inI18nNode = wasInI18nNode;
this._inImplicitNode = wasInImplicitNode;
if (this._mode === _VisitorMode.Merge) {
const translatedAttrs = this._translateAttributes(el);
return new html.Element(
el.name,
translatedAttrs,
childNodes,
el.sourceSpan,
el.startSourceSpan,
el.endSourceSpan,
);
}
return null;
}
visitAttribute(attribute: html.Attribute, context: any): any {
throw new Error('unreachable code');
}
visitBlock(block: html.Block, context: any) {
html.visitAll(this, block.children, context);
}
visitBlockParameter(parameter: html.BlockParameter, context: any) {}
visitLetDeclaration(decl: html.LetDeclaration, context: any) {}
private _init(mode: _VisitorMode, interpolationConfig: InterpolationConfig): void {
this._mode = mode;
this._inI18nBlock = false;
this._inI18nNode = false;
this._depth = 0;
this._inIcu = false;
this._msgCountAtSectionStart = undefined;
this._errors = [];
this._messages = [];
this._inImplicitNode = false;
this._createI18nMessage = createI18nMessageFactory(
interpolationConfig,
DEFAULT_CONTAINER_BLOCKS,
// When dropping significant whitespace we need to retain whitespace tokens or
// else we won't be able to reuse source spans because empty tokens would be
// removed and cause a mismatch.
/* retainEmptyTokens */ !this._preserveSignificantWhitespace,
/* preserveExpressionWhitespace */ this._preserveSignificantWhitespace,
);
}
// looks for translatable attributes
private _visitAttributesOf(el: html.Element): void {
const explicitAttrNameToValue: {[k: string]: string} = {};
const implicitAttrNames: string[] = this._implicitAttrs[el.name] || [];
el.attrs
.filter((attr) => attr.name.startsWith(_I18N_ATTR_PREFIX))
.forEach(
(attr) => (explicitAttrNameToValue[attr.name.slice(_I18N_ATTR_PREFIX.length)] = attr.value),
);
el.attrs.forEach((attr) => {
if (attr.name in explicitAttrNameToValue) {
this._addMessage([attr], explicitAttrNameToValue[attr.name]);
} else if (implicitAttrNames.some((name) => attr.name === name)) {
this._addMessage([attr]);
}
});
}
// add a translatable message
private _addMessage(ast: html.Node[], msgMeta?: string): i18n.Message | null {
if (
ast.length == 0 ||
this._isEmptyAttributeValue(ast) ||
this._isPlaceholderOnlyAttributeValue(ast) ||
this._isPlaceholderOnlyMessage(ast)
) {
// Do not create empty messages
return null;
}
const {meaning, description, id} = _parseMessageMeta(msgMeta);
const message = this._createI18nMessage(ast, meaning, description, id);
this._messages.push(message);
return message;
}
// Check for cases like `<div i18n-title title="">`.
private _isEmptyAttributeValue(ast: html.Node[]): boolean {
if (!isAttrNode(ast)) return false;
const node = ast[0];
return node.value.trim() === '';
}
// Check for cases like `<div i18n-title title="{{ name }}">`.
private _isPlaceholderOnlyAttributeValue(ast: html.Node[]): boolean {
if (!isAttrNode(ast)) return false;
const tokens = ast[0].valueTokens ?? [];
const interpolations = tokens.filter(
(token) => token.type === TokenType.ATTR_VALUE_INTERPOLATION,
);
const plainText = tokens
.filter((token) => token.type === TokenType.ATTR_VALUE_TEXT)
// `AttributeValueTextToken` always has exactly one part per its type.
.map((token) => token.parts[0].trim())
.join('');
// Check if there is a single interpolation and all text around it is empty.
return interpolations.length === 1 && plainText === '';
}
// Check for cases like `<div i18n>{{ name }}</div>`.
private _isPlaceholderOnlyMessage(ast: html.Node[]): boolean {
if (!isTextNode(ast)) return false;
const tokens = ast[0].tokens;
const interpolations = tokens.filter((token) => token.type === TokenType.INTERPOLATION);
const plainText = tokens
.filter((token) => token.type === TokenType.TEXT)
// `TextToken` always has exactly one part per its type.
.map((token) => token.parts[0].trim())
.join('');
// Check if there is a single interpolation and all text around it is empty.
return interpolations.length === 1 && plainText === '';
}
// Translates the given message given the `TranslationBundle`
// This is used for translating elements / blocks - see `_translateAttributes` for attributes
// no-op when called in extraction mode (returns [])
private _translateMessage(el: html.Node, message: i18n.Message): html.Node[] {
if (message && this._mode === _VisitorMode.Merge) {
const nodes = this._translations.get(message);
if (nodes) {
return nodes;
}
this._reportError(
el,
`Translation unavailable for message id="${this._translations.digest(message)}"`,
);
}
return [];
}
// translate the attributes of an element and remove i18n specific attributes | {
"end_byte": 14970,
"start_byte": 7516,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/extractor_merger.ts"
} |
angular/packages/compiler/src/i18n/extractor_merger.ts_14973_21224 | private _translateAttributes(el: html.Element): html.Attribute[] {
const attributes = el.attrs;
const i18nParsedMessageMeta: {
[name: string]: {meaning: string; description: string; id: string};
} = {};
attributes.forEach((attr) => {
if (attr.name.startsWith(_I18N_ATTR_PREFIX)) {
i18nParsedMessageMeta[attr.name.slice(_I18N_ATTR_PREFIX.length)] = _parseMessageMeta(
attr.value,
);
}
});
const translatedAttributes: html.Attribute[] = [];
attributes.forEach((attr) => {
if (attr.name === _I18N_ATTR || attr.name.startsWith(_I18N_ATTR_PREFIX)) {
// strip i18n specific attributes
return;
}
if (attr.value && attr.value != '' && i18nParsedMessageMeta.hasOwnProperty(attr.name)) {
const {meaning, description, id} = i18nParsedMessageMeta[attr.name];
const message: i18n.Message = this._createI18nMessage([attr], meaning, description, id);
const nodes = this._translations.get(message);
if (nodes) {
if (nodes.length == 0) {
translatedAttributes.push(
new html.Attribute(
attr.name,
'',
attr.sourceSpan,
undefined /* keySpan */,
undefined /* valueSpan */,
undefined /* valueTokens */,
undefined /* i18n */,
),
);
} else if (nodes[0] instanceof html.Text) {
const value = (nodes[0] as html.Text).value;
translatedAttributes.push(
new html.Attribute(
attr.name,
value,
attr.sourceSpan,
undefined /* keySpan */,
undefined /* valueSpan */,
undefined /* valueTokens */,
undefined /* i18n */,
),
);
} else {
this._reportError(
el,
`Unexpected translation for attribute "${attr.name}" (id="${
id || this._translations.digest(message)
}")`,
);
}
} else {
this._reportError(
el,
`Translation unavailable for attribute "${attr.name}" (id="${
id || this._translations.digest(message)
}")`,
);
}
} else {
translatedAttributes.push(attr);
}
});
return translatedAttributes;
}
/**
* Add the node as a child of the block when:
* - we are in a block,
* - we are not inside a ICU message (those are handled separately),
* - the node is a "direct child" of the block
*/
private _mayBeAddBlockChildren(node: html.Node): void {
if (this._inI18nBlock && !this._inIcu && this._depth == this._blockStartDepth) {
this._blockChildren.push(node);
}
}
/**
* Marks the start of a section, see `_closeTranslatableSection`
*/
private _openTranslatableSection(node: html.Node): void {
if (this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section start');
} else {
this._msgCountAtSectionStart = this._messages.length;
}
}
/**
* A translatable section could be:
* - the content of translatable element,
* - nodes between `<!-- i18n -->` and `<!-- /i18n -->` comments
*/
private get _isInTranslatableSection(): boolean {
return this._msgCountAtSectionStart !== void 0;
}
/**
* Terminates a section.
*
* If a section has only one significant children (comments not significant) then we should not
* keep the message from this children:
*
* `<p i18n="meaning|description">{ICU message}</p>` would produce two messages:
* - one for the <p> content with meaning and description,
* - another one for the ICU message.
*
* In this case the last message is discarded as it contains less information (the AST is
* otherwise identical).
*
* Note that we should still keep messages extracted from attributes inside the section (ie in the
* ICU message here)
*/
private _closeTranslatableSection(node: html.Node, directChildren: html.Node[]): void {
if (!this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section end');
return;
}
const startIndex = this._msgCountAtSectionStart;
const significantChildren: number = directChildren.reduce(
(count: number, node: html.Node): number => count + (node instanceof html.Comment ? 0 : 1),
0,
);
if (significantChildren == 1) {
for (let i = this._messages.length - 1; i >= startIndex!; i--) {
const ast = this._messages[i].nodes;
if (!(ast.length == 1 && ast[0] instanceof i18n.Text)) {
this._messages.splice(i, 1);
break;
}
}
}
this._msgCountAtSectionStart = undefined;
}
private _reportError(node: html.Node, msg: string): void {
this._errors.push(new I18nError(node.sourceSpan, msg));
}
}
function _isOpeningComment(n: html.Node): boolean {
return !!(n instanceof html.Comment && n.value && n.value.startsWith('i18n'));
}
function _isClosingComment(n: html.Node): boolean {
return !!(n instanceof html.Comment && n.value && n.value === '/i18n');
}
function _getI18nAttr(p: html.Element): html.Attribute | null {
return p.attrs.find((attr) => attr.name === _I18N_ATTR) || null;
}
function _parseMessageMeta(i18n?: string): {meaning: string; description: string; id: string} {
if (!i18n) return {meaning: '', description: '', id: ''};
const idIndex = i18n.indexOf(ID_SEPARATOR);
const descIndex = i18n.indexOf(MEANING_SEPARATOR);
const [meaningAndDesc, id] =
idIndex > -1 ? [i18n.slice(0, idIndex), i18n.slice(idIndex + 2)] : [i18n, ''];
const [meaning, description] =
descIndex > -1
? [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)]
: ['', meaningAndDesc];
return {meaning, description, id: id.trim()};
}
function isTextNode(ast: html.Node[]): ast is [html.Text] {
return ast.length === 1 && ast[0] instanceof html.Text;
}
function isAttrNode(ast: html.Node[]): ast is [html.Attribute] {
return ast.length === 1 && ast[0] instanceof html.Attribute;
} | {
"end_byte": 21224,
"start_byte": 14973,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/extractor_merger.ts"
} |
angular/packages/compiler/src/i18n/index.ts_0_560 | /**
* @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.dev/license
*/
export {computeMsgId} from './digest';
export {I18NHtmlParser} from './i18n_html_parser';
export {MessageBundle} from './message_bundle';
export {Serializer} from './serializers/serializer';
export {Xliff} from './serializers/xliff';
export {Xliff2} from './serializers/xliff2';
export {Xmb} from './serializers/xmb';
export {Xtb} from './serializers/xtb';
| {
"end_byte": 560,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/index.ts"
} |
angular/packages/compiler/src/i18n/digest.ts_0_6464 | /**
* @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.dev/license
*/
import {Byte} from '../util';
import * as i18n from './i18n_ast';
/**
* A lazily created TextEncoder instance for converting strings into UTF-8 bytes
*/
let textEncoder: TextEncoder | undefined;
/**
* Return the message id or compute it using the XLIFF1 digest.
*/
export function digest(message: i18n.Message): string {
return message.id || computeDigest(message);
}
/**
* Compute the message id using the XLIFF1 digest.
*/
export function computeDigest(message: i18n.Message): string {
return sha1(serializeNodes(message.nodes).join('') + `[${message.meaning}]`);
}
/**
* Return the message id or compute it using the XLIFF2/XMB/$localize digest.
*/
export function decimalDigest(message: i18n.Message): string {
return message.id || computeDecimalDigest(message);
}
/**
* Compute the message id using the XLIFF2/XMB/$localize digest.
*/
export function computeDecimalDigest(message: i18n.Message): string {
const visitor = new _SerializerIgnoreIcuExpVisitor();
const parts = message.nodes.map((a) => a.visit(visitor, null));
return computeMsgId(parts.join(''), message.meaning);
}
/**
* Serialize the i18n ast to something xml-like in order to generate an UID.
*
* The visitor is also used in the i18n parser tests
*
* @internal
*/
class _SerializerVisitor implements i18n.Visitor {
visitText(text: i18n.Text, context: any): any {
return text.value;
}
visitContainer(container: i18n.Container, context: any): any {
return `[${container.children.map((child) => child.visit(this)).join(', ')}]`;
}
visitIcu(icu: i18n.Icu, context: any): any {
const strCases = Object.keys(icu.cases).map(
(k: string) => `${k} {${icu.cases[k].visit(this)}}`,
);
return `{${icu.expression}, ${icu.type}, ${strCases.join(', ')}}`;
}
visitTagPlaceholder(ph: i18n.TagPlaceholder, context: any): any {
return ph.isVoid
? `<ph tag name="${ph.startName}"/>`
: `<ph tag name="${ph.startName}">${ph.children
.map((child) => child.visit(this))
.join(', ')}</ph name="${ph.closeName}">`;
}
visitPlaceholder(ph: i18n.Placeholder, context: any): any {
return ph.value ? `<ph name="${ph.name}">${ph.value}</ph>` : `<ph name="${ph.name}"/>`;
}
visitIcuPlaceholder(ph: i18n.IcuPlaceholder, context?: any): any {
return `<ph icu name="${ph.name}">${ph.value.visit(this)}</ph>`;
}
visitBlockPlaceholder(ph: i18n.BlockPlaceholder, context: any): any {
return `<ph block name="${ph.startName}">${ph.children
.map((child) => child.visit(this))
.join(', ')}</ph name="${ph.closeName}">`;
}
}
const serializerVisitor = new _SerializerVisitor();
export function serializeNodes(nodes: i18n.Node[]): string[] {
return nodes.map((a) => a.visit(serializerVisitor, null));
}
/**
* Serialize the i18n ast to something xml-like in order to generate an UID.
*
* Ignore the ICU expressions so that message IDs stays identical if only the expression changes.
*
* @internal
*/
class _SerializerIgnoreIcuExpVisitor extends _SerializerVisitor {
override visitIcu(icu: i18n.Icu): string {
let strCases = Object.keys(icu.cases).map((k: string) => `${k} {${icu.cases[k].visit(this)}}`);
// Do not take the expression into account
return `{${icu.type}, ${strCases.join(', ')}}`;
}
}
/**
* Compute the SHA1 of the given string
*
* see https://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
*
* WARNING: this function has not been designed not tested with security in mind.
* DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT.
*/
export function sha1(str: string): string {
textEncoder ??= new TextEncoder();
const utf8 = [...textEncoder.encode(str)];
const words32 = bytesToWords32(utf8, Endian.Big);
const len = utf8.length * 8;
const w = new Uint32Array(80);
let a = 0x67452301,
b = 0xefcdab89,
c = 0x98badcfe,
d = 0x10325476,
e = 0xc3d2e1f0;
words32[len >> 5] |= 0x80 << (24 - (len % 32));
words32[(((len + 64) >> 9) << 4) + 15] = len;
for (let i = 0; i < words32.length; i += 16) {
const h0 = a,
h1 = b,
h2 = c,
h3 = d,
h4 = e;
for (let j = 0; j < 80; j++) {
if (j < 16) {
w[j] = words32[i + j];
} else {
w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
}
const fkVal = fk(j, b, c, d);
const f = fkVal[0];
const k = fkVal[1];
const temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32);
e = d;
d = c;
c = rol32(b, 30);
b = a;
a = temp;
}
a = add32(a, h0);
b = add32(b, h1);
c = add32(c, h2);
d = add32(d, h3);
e = add32(e, h4);
}
// Convert the output parts to a 160-bit hexadecimal string
return toHexU32(a) + toHexU32(b) + toHexU32(c) + toHexU32(d) + toHexU32(e);
}
/**
* Convert and format a number as a string representing a 32-bit unsigned hexadecimal number.
* @param value The value to format as a string.
* @returns A hexadecimal string representing the value.
*/
function toHexU32(value: number): string {
// unsigned right shift of zero ensures an unsigned 32-bit number
return (value >>> 0).toString(16).padStart(8, '0');
}
function fk(index: number, b: number, c: number, d: number): [number, number] {
if (index < 20) {
return [(b & c) | (~b & d), 0x5a827999];
}
if (index < 40) {
return [b ^ c ^ d, 0x6ed9eba1];
}
if (index < 60) {
return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc];
}
return [b ^ c ^ d, 0xca62c1d6];
}
/**
* Compute the fingerprint of the given string
*
* The output is 64 bit number encoded as a decimal string
*
* based on:
* https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
*/
export function fingerprint(str: string): bigint {
textEncoder ??= new TextEncoder();
const utf8 = textEncoder.encode(str);
const view = new DataView(utf8.buffer, utf8.byteOffset, utf8.byteLength);
let hi = hash32(view, utf8.length, 0);
let lo = hash32(view, utf8.length, 102072);
if (hi == 0 && (lo == 0 || lo == 1)) {
hi = hi ^ 0x130f9bef;
lo = lo ^ -0x6b5f56d8;
}
return (BigInt.asUintN(32, BigInt(hi)) << BigInt(32)) | BigInt.asUintN(32, BigInt(lo));
} | {
"end_byte": 6464,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/digest.ts"
} |
angular/packages/compiler/src/i18n/digest.ts_6466_10055 | export function computeMsgId(msg: string, meaning: string = ''): string {
let msgFingerprint = fingerprint(msg);
if (meaning) {
// Rotate the 64-bit message fingerprint one bit to the left and then add the meaning
// fingerprint.
msgFingerprint =
BigInt.asUintN(64, msgFingerprint << BigInt(1)) |
((msgFingerprint >> BigInt(63)) & BigInt(1));
msgFingerprint += fingerprint(meaning);
}
return BigInt.asUintN(63, msgFingerprint).toString();
}
function hash32(view: DataView, length: number, c: number): number {
let a = 0x9e3779b9,
b = 0x9e3779b9;
let index = 0;
const end = length - 12;
for (; index <= end; index += 12) {
a += view.getUint32(index, true);
b += view.getUint32(index + 4, true);
c += view.getUint32(index + 8, true);
const res = mix(a, b, c);
(a = res[0]), (b = res[1]), (c = res[2]);
}
const remainder = length - index;
// the first byte of c is reserved for the length
c += length;
if (remainder >= 4) {
a += view.getUint32(index, true);
index += 4;
if (remainder >= 8) {
b += view.getUint32(index, true);
index += 4;
// Partial 32-bit word for c
if (remainder >= 9) {
c += view.getUint8(index++) << 8;
}
if (remainder >= 10) {
c += view.getUint8(index++) << 16;
}
if (remainder === 11) {
c += view.getUint8(index++) << 24;
}
} else {
// Partial 32-bit word for b
if (remainder >= 5) {
b += view.getUint8(index++);
}
if (remainder >= 6) {
b += view.getUint8(index++) << 8;
}
if (remainder === 7) {
b += view.getUint8(index++) << 16;
}
}
} else {
// Partial 32-bit word for a
if (remainder >= 1) {
a += view.getUint8(index++);
}
if (remainder >= 2) {
a += view.getUint8(index++) << 8;
}
if (remainder === 3) {
a += view.getUint8(index++) << 16;
}
}
return mix(a, b, c)[2];
}
function mix(a: number, b: number, c: number): [number, number, number] {
a -= b;
a -= c;
a ^= c >>> 13;
b -= c;
b -= a;
b ^= a << 8;
c -= a;
c -= b;
c ^= b >>> 13;
a -= b;
a -= c;
a ^= c >>> 12;
b -= c;
b -= a;
b ^= a << 16;
c -= a;
c -= b;
c ^= b >>> 5;
a -= b;
a -= c;
a ^= c >>> 3;
b -= c;
b -= a;
b ^= a << 10;
c -= a;
c -= b;
c ^= b >>> 15;
return [a, b, c];
}
// Utils
enum Endian {
Little,
Big,
}
function add32(a: number, b: number): number {
return add32to64(a, b)[1];
}
function add32to64(a: number, b: number): [number, number] {
const low = (a & 0xffff) + (b & 0xffff);
const high = (a >>> 16) + (b >>> 16) + (low >>> 16);
return [high >>> 16, (high << 16) | (low & 0xffff)];
}
// Rotate a 32b number left `count` position
function rol32(a: number, count: number): number {
return (a << count) | (a >>> (32 - count));
}
function bytesToWords32(bytes: Byte[], endian: Endian): number[] {
const size = (bytes.length + 3) >>> 2;
const words32 = [];
for (let i = 0; i < size; i++) {
words32[i] = wordAt(bytes, i * 4, endian);
}
return words32;
}
function byteAt(bytes: Byte[], index: number): Byte {
return index >= bytes.length ? 0 : bytes[index];
}
function wordAt(bytes: Byte[], index: number, endian: Endian): number {
let word = 0;
if (endian === Endian.Big) {
for (let i = 0; i < 4; i++) {
word += byteAt(bytes, index + i) << (24 - 8 * i);
}
} else {
for (let i = 0; i < 4; i++) {
word += byteAt(bytes, index + i) << (8 * i);
}
}
return word;
} | {
"end_byte": 10055,
"start_byte": 6466,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/digest.ts"
} |
angular/packages/compiler/src/i18n/message_bundle.ts_0_5332 | /**
* @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.dev/license
*/
import {InterpolationConfig} from '../ml_parser/defaults';
import {HtmlParser} from '../ml_parser/html_parser';
import {WhitespaceVisitor, visitAllWithSiblings} from '../ml_parser/html_whitespaces';
import {ParseError} from '../parse_util';
import {extractMessages} from './extractor_merger';
import * as i18n from './i18n_ast';
import {PlaceholderMapper, Serializer} from './serializers/serializer';
/**
* A container for message extracted from the templates.
*/
export class MessageBundle {
private _messages: i18n.Message[] = [];
constructor(
private _htmlParser: HtmlParser,
private _implicitTags: string[],
private _implicitAttrs: {[k: string]: string[]},
private _locale: string | null = null,
private readonly _preserveWhitespace = true,
) {}
updateFromTemplate(
source: string,
url: string,
interpolationConfig: InterpolationConfig,
): ParseError[] {
const htmlParserResult = this._htmlParser.parse(source, url, {
tokenizeExpansionForms: true,
interpolationConfig,
});
if (htmlParserResult.errors.length) {
return htmlParserResult.errors;
}
// Trim unnecessary whitespace from extracted messages if requested. This
// makes the messages more durable to trivial whitespace changes without
// affected message IDs.
const rootNodes = this._preserveWhitespace
? htmlParserResult.rootNodes
: visitAllWithSiblings(
new WhitespaceVisitor(/* preserveSignificantWhitespace */ false),
htmlParserResult.rootNodes,
);
const i18nParserResult = extractMessages(
rootNodes,
interpolationConfig,
this._implicitTags,
this._implicitAttrs,
/* preserveSignificantWhitespace */ this._preserveWhitespace,
);
if (i18nParserResult.errors.length) {
return i18nParserResult.errors;
}
this._messages.push(...i18nParserResult.messages);
return [];
}
// Return the message in the internal format
// The public (serialized) format might be different, see the `write` method.
getMessages(): i18n.Message[] {
return this._messages;
}
write(serializer: Serializer, filterSources?: (path: string) => string): string {
const messages: {[id: string]: i18n.Message} = {};
const mapperVisitor = new MapPlaceholderNames();
// Deduplicate messages based on their ID
this._messages.forEach((message) => {
const id = serializer.digest(message);
if (!messages.hasOwnProperty(id)) {
messages[id] = message;
} else {
messages[id].sources.push(...message.sources);
}
});
// Transform placeholder names using the serializer mapping
const msgList = Object.keys(messages).map((id) => {
const mapper = serializer.createNameMapper(messages[id]);
const src = messages[id];
const nodes = mapper ? mapperVisitor.convert(src.nodes, mapper) : src.nodes;
let transformedMessage = new i18n.Message(nodes, {}, {}, src.meaning, src.description, id);
transformedMessage.sources = src.sources;
if (filterSources) {
transformedMessage.sources.forEach(
(source: i18n.MessageSpan) => (source.filePath = filterSources(source.filePath)),
);
}
return transformedMessage;
});
return serializer.write(msgList, this._locale);
}
}
// Transform an i18n AST by renaming the placeholder nodes with the given mapper
class MapPlaceholderNames extends i18n.CloneVisitor {
convert(nodes: i18n.Node[], mapper: PlaceholderMapper): i18n.Node[] {
return mapper ? nodes.map((n) => n.visit(this, mapper)) : nodes;
}
override visitTagPlaceholder(
ph: i18n.TagPlaceholder,
mapper: PlaceholderMapper,
): i18n.TagPlaceholder {
const startName = mapper.toPublicName(ph.startName)!;
const closeName = ph.closeName ? mapper.toPublicName(ph.closeName)! : ph.closeName;
const children = ph.children.map((n) => n.visit(this, mapper));
return new i18n.TagPlaceholder(
ph.tag,
ph.attrs,
startName,
closeName,
children,
ph.isVoid,
ph.sourceSpan,
ph.startSourceSpan,
ph.endSourceSpan,
);
}
override visitBlockPlaceholder(
ph: i18n.BlockPlaceholder,
mapper: PlaceholderMapper,
): i18n.BlockPlaceholder {
const startName = mapper.toPublicName(ph.startName)!;
const closeName = ph.closeName ? mapper.toPublicName(ph.closeName)! : ph.closeName;
const children = ph.children.map((n) => n.visit(this, mapper));
return new i18n.BlockPlaceholder(
ph.name,
ph.parameters,
startName,
closeName,
children,
ph.sourceSpan,
ph.startSourceSpan,
ph.endSourceSpan,
);
}
override visitPlaceholder(ph: i18n.Placeholder, mapper: PlaceholderMapper): i18n.Placeholder {
return new i18n.Placeholder(ph.value, mapper.toPublicName(ph.name)!, ph.sourceSpan);
}
override visitIcuPlaceholder(
ph: i18n.IcuPlaceholder,
mapper: PlaceholderMapper,
): i18n.IcuPlaceholder {
return new i18n.IcuPlaceholder(ph.value, mapper.toPublicName(ph.name)!, ph.sourceSpan);
}
}
| {
"end_byte": 5332,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/message_bundle.ts"
} |
angular/packages/compiler/src/i18n/serializers/xtb.ts_0_7405 | /**
* @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.dev/license
*/
import * as ml from '../../ml_parser/ast';
import {XmlParser} from '../../ml_parser/xml_parser';
import * as i18n from '../i18n_ast';
import {I18nError} from '../parse_util';
import {PlaceholderMapper, Serializer, SimplePlaceholderMapper} from './serializer';
import {digest, toPublicName} from './xmb';
const _TRANSLATIONS_TAG = 'translationbundle';
const _TRANSLATION_TAG = 'translation';
const _PLACEHOLDER_TAG = 'ph';
export class Xtb extends Serializer {
override write(messages: i18n.Message[], locale: string | null): string {
throw new Error('Unsupported');
}
override load(
content: string,
url: string,
): {locale: string; i18nNodesByMsgId: {[msgId: string]: i18n.Node[]}} {
// xtb to xml nodes
const xtbParser = new XtbParser();
const {locale, msgIdToHtml, errors} = xtbParser.parse(content, url);
// xml nodes to i18n nodes
const i18nNodesByMsgId: {[msgId: string]: i18n.Node[]} = {};
const converter = new XmlToI18n();
// Because we should be able to load xtb files that rely on features not supported by angular,
// we need to delay the conversion of html to i18n nodes so that non angular messages are not
// converted
Object.keys(msgIdToHtml).forEach((msgId) => {
const valueFn = function () {
const {i18nNodes, errors} = converter.convert(msgIdToHtml[msgId], url);
if (errors.length) {
throw new Error(`xtb parse errors:\n${errors.join('\n')}`);
}
return i18nNodes;
};
createLazyProperty(i18nNodesByMsgId, msgId, valueFn);
});
if (errors.length) {
throw new Error(`xtb parse errors:\n${errors.join('\n')}`);
}
return {locale: locale!, i18nNodesByMsgId};
}
override digest(message: i18n.Message): string {
return digest(message);
}
override createNameMapper(message: i18n.Message): PlaceholderMapper {
return new SimplePlaceholderMapper(message, toPublicName);
}
}
function createLazyProperty(messages: any, id: string, valueFn: () => any) {
Object.defineProperty(messages, id, {
configurable: true,
enumerable: true,
get: function () {
const value = valueFn();
Object.defineProperty(messages, id, {enumerable: true, value});
return value;
},
set: (_) => {
throw new Error('Could not overwrite an XTB translation');
},
});
}
// Extract messages as xml nodes from the xtb file
class XtbParser implements ml.Visitor {
// using non-null assertions because they're (re)set by parse()
private _bundleDepth!: number;
private _errors!: I18nError[];
private _msgIdToHtml!: {[msgId: string]: string};
private _locale: string | null = null;
parse(xtb: string, url: string) {
this._bundleDepth = 0;
this._msgIdToHtml = {};
// We can not parse the ICU messages at this point as some messages might not originate
// from Angular that could not be lex'd.
const xml = new XmlParser().parse(xtb, url);
this._errors = xml.errors;
ml.visitAll(this, xml.rootNodes);
return {
msgIdToHtml: this._msgIdToHtml,
errors: this._errors,
locale: this._locale,
};
}
visitElement(element: ml.Element, context: any): any {
switch (element.name) {
case _TRANSLATIONS_TAG:
this._bundleDepth++;
if (this._bundleDepth > 1) {
this._addError(element, `<${_TRANSLATIONS_TAG}> elements can not be nested`);
}
const langAttr = element.attrs.find((attr) => attr.name === 'lang');
if (langAttr) {
this._locale = langAttr.value;
}
ml.visitAll(this, element.children, null);
this._bundleDepth--;
break;
case _TRANSLATION_TAG:
const idAttr = element.attrs.find((attr) => attr.name === 'id');
if (!idAttr) {
this._addError(element, `<${_TRANSLATION_TAG}> misses the "id" attribute`);
} else {
const id = idAttr.value;
if (this._msgIdToHtml.hasOwnProperty(id)) {
this._addError(element, `Duplicated translations for msg ${id}`);
} else {
const innerTextStart = element.startSourceSpan.end.offset;
const innerTextEnd = element.endSourceSpan!.start.offset;
const content = element.startSourceSpan.start.file.content;
const innerText = content.slice(innerTextStart!, innerTextEnd!);
this._msgIdToHtml[id] = innerText;
}
}
break;
default:
this._addError(element, 'Unexpected tag');
}
}
visitAttribute(attribute: ml.Attribute, context: any): any {}
visitText(text: ml.Text, context: any): any {}
visitComment(comment: ml.Comment, context: any): any {}
visitExpansion(expansion: ml.Expansion, context: any): any {}
visitExpansionCase(expansionCase: ml.ExpansionCase, context: any): any {}
visitBlock(block: ml.Block, context: any) {}
visitBlockParameter(block: ml.BlockParameter, context: any) {}
visitLetDeclaration(decl: ml.LetDeclaration, context: any) {}
private _addError(node: ml.Node, message: string): void {
this._errors.push(new I18nError(node.sourceSpan, message));
}
}
// Convert ml nodes (xtb syntax) to i18n nodes
class XmlToI18n implements ml.Visitor {
// using non-null assertion because it's (re)set by convert()
private _errors!: I18nError[];
convert(message: string, url: string) {
const xmlIcu = new XmlParser().parse(message, url, {tokenizeExpansionForms: true});
this._errors = xmlIcu.errors;
const i18nNodes =
this._errors.length > 0 || xmlIcu.rootNodes.length == 0
? []
: ml.visitAll(this, xmlIcu.rootNodes);
return {
i18nNodes,
errors: this._errors,
};
}
visitText(text: ml.Text, context: any) {
return new i18n.Text(text.value, text.sourceSpan);
}
visitExpansion(icu: ml.Expansion, context: any) {
const caseMap: {[value: string]: i18n.Node} = {};
ml.visitAll(this, icu.cases).forEach((c) => {
caseMap[c.value] = new i18n.Container(c.nodes, icu.sourceSpan);
});
return new i18n.Icu(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
}
visitExpansionCase(icuCase: ml.ExpansionCase, context: any): any {
return {
value: icuCase.value,
nodes: ml.visitAll(this, icuCase.expression),
};
}
visitElement(el: ml.Element, context: any): i18n.Placeholder | null {
if (el.name === _PLACEHOLDER_TAG) {
const nameAttr = el.attrs.find((attr) => attr.name === 'name');
if (nameAttr) {
return new i18n.Placeholder('', nameAttr.value, el.sourceSpan);
}
this._addError(el, `<${_PLACEHOLDER_TAG}> misses the "name" attribute`);
} else {
this._addError(el, `Unexpected tag`);
}
return null;
}
visitComment(comment: ml.Comment, context: any) {}
visitAttribute(attribute: ml.Attribute, context: any) {}
visitBlock(block: ml.Block, context: any) {}
visitBlockParameter(block: ml.BlockParameter, context: any) {}
visitLetDeclaration(decl: ml.LetDeclaration, context: any) {}
private _addError(node: ml.Node, message: string): void {
this._errors.push(new I18nError(node.sourceSpan, message));
}
}
| {
"end_byte": 7405,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/serializers/xtb.ts"
} |
angular/packages/compiler/src/i18n/serializers/serializer.ts_0_3760 | /**
* @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.dev/license
*/
import * as i18n from '../i18n_ast';
export abstract class Serializer {
// - The `placeholders` and `placeholderToMessage` properties are irrelevant in the input messages
// - The `id` contains the message id that the serializer is expected to use
// - Placeholder names are already map to public names using the provided mapper
abstract write(messages: i18n.Message[], locale: string | null): string;
abstract load(
content: string,
url: string,
): {locale: string | null; i18nNodesByMsgId: {[msgId: string]: i18n.Node[]}};
abstract digest(message: i18n.Message): string;
// Creates a name mapper, see `PlaceholderMapper`
// Returning `null` means that no name mapping is used.
createNameMapper(message: i18n.Message): PlaceholderMapper | null {
return null;
}
}
/**
* A `PlaceholderMapper` converts placeholder names from internal to serialized representation and
* back.
*
* It should be used for serialization format that put constraints on the placeholder names.
*/
export interface PlaceholderMapper {
toPublicName(internalName: string): string | null;
toInternalName(publicName: string): string | null;
}
/**
* A simple mapper that take a function to transform an internal name to a public name
*/
export class SimplePlaceholderMapper extends i18n.RecurseVisitor implements PlaceholderMapper {
private internalToPublic: {[k: string]: string} = {};
private publicToNextId: {[k: string]: number} = {};
private publicToInternal: {[k: string]: string} = {};
// create a mapping from the message
constructor(
message: i18n.Message,
private mapName: (name: string) => string,
) {
super();
message.nodes.forEach((node) => node.visit(this));
}
toPublicName(internalName: string): string | null {
return this.internalToPublic.hasOwnProperty(internalName)
? this.internalToPublic[internalName]
: null;
}
toInternalName(publicName: string): string | null {
return this.publicToInternal.hasOwnProperty(publicName)
? this.publicToInternal[publicName]
: null;
}
override visitText(text: i18n.Text, context?: any): any {
return null;
}
override visitTagPlaceholder(ph: i18n.TagPlaceholder, context?: any): any {
this.visitPlaceholderName(ph.startName);
super.visitTagPlaceholder(ph, context);
this.visitPlaceholderName(ph.closeName);
}
override visitPlaceholder(ph: i18n.Placeholder, context?: any): any {
this.visitPlaceholderName(ph.name);
}
override visitBlockPlaceholder(ph: i18n.BlockPlaceholder, context?: any): any {
this.visitPlaceholderName(ph.startName);
super.visitBlockPlaceholder(ph, context);
this.visitPlaceholderName(ph.closeName);
}
override visitIcuPlaceholder(ph: i18n.IcuPlaceholder, context?: any): any {
this.visitPlaceholderName(ph.name);
}
// XMB placeholders could only contains A-Z, 0-9 and _
private visitPlaceholderName(internalName: string): void {
if (!internalName || this.internalToPublic.hasOwnProperty(internalName)) {
return;
}
let publicName = this.mapName(internalName);
if (this.publicToInternal.hasOwnProperty(publicName)) {
// Create a new XMB when it has already been used
const nextId = this.publicToNextId[publicName];
this.publicToNextId[publicName] = nextId + 1;
publicName = `${publicName}_${nextId}`;
} else {
this.publicToNextId[publicName] = 1;
}
this.internalToPublic[internalName] = publicName;
this.publicToInternal[publicName] = internalName;
}
}
| {
"end_byte": 3760,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/serializers/serializer.ts"
} |
angular/packages/compiler/src/i18n/serializers/xml_helper.ts_0_3176 | /**
* @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.dev/license
*/
export interface IVisitor {
visitTag(tag: Tag): any;
visitText(text: Text): any;
visitDeclaration(decl: Declaration): any;
visitDoctype(doctype: Doctype): any;
}
class _Visitor implements IVisitor {
visitTag(tag: Tag): string {
const strAttrs = this._serializeAttributes(tag.attrs);
if (tag.children.length == 0) {
return `<${tag.name}${strAttrs}/>`;
}
const strChildren = tag.children.map((node) => node.visit(this));
return `<${tag.name}${strAttrs}>${strChildren.join('')}</${tag.name}>`;
}
visitText(text: Text): string {
return text.value;
}
visitDeclaration(decl: Declaration): string {
return `<?xml${this._serializeAttributes(decl.attrs)} ?>`;
}
private _serializeAttributes(attrs: {[k: string]: string}) {
const strAttrs = Object.keys(attrs)
.map((name: string) => `${name}="${attrs[name]}"`)
.join(' ');
return strAttrs.length > 0 ? ' ' + strAttrs : '';
}
visitDoctype(doctype: Doctype): any {
return `<!DOCTYPE ${doctype.rootTag} [\n${doctype.dtd}\n]>`;
}
}
const _visitor = new _Visitor();
export function serialize(nodes: Node[]): string {
return nodes.map((node: Node): string => node.visit(_visitor)).join('');
}
export interface Node {
visit(visitor: IVisitor): any;
}
export class Declaration implements Node {
public attrs: {[k: string]: string} = {};
constructor(unescapedAttrs: {[k: string]: string}) {
Object.keys(unescapedAttrs).forEach((k: string) => {
this.attrs[k] = escapeXml(unescapedAttrs[k]);
});
}
visit(visitor: IVisitor): any {
return visitor.visitDeclaration(this);
}
}
export class Doctype implements Node {
constructor(
public rootTag: string,
public dtd: string,
) {}
visit(visitor: IVisitor): any {
return visitor.visitDoctype(this);
}
}
export class Tag implements Node {
public attrs: {[k: string]: string} = {};
constructor(
public name: string,
unescapedAttrs: {[k: string]: string} = {},
public children: Node[] = [],
) {
Object.keys(unescapedAttrs).forEach((k: string) => {
this.attrs[k] = escapeXml(unescapedAttrs[k]);
});
}
visit(visitor: IVisitor): any {
return visitor.visitTag(this);
}
}
export class Text implements Node {
value: string;
constructor(unescapedValue: string) {
this.value = escapeXml(unescapedValue);
}
visit(visitor: IVisitor): any {
return visitor.visitText(this);
}
}
export class CR extends Text {
constructor(ws: number = 0) {
super(`\n${new Array(ws + 1).join(' ')}`);
}
}
const _ESCAPED_CHARS: [RegExp, string][] = [
[/&/g, '&'],
[/"/g, '"'],
[/'/g, '''],
[/</g, '<'],
[/>/g, '>'],
];
// Escape `_ESCAPED_CHARS` characters in the given text with encoded entities
export function escapeXml(text: string): string {
return _ESCAPED_CHARS.reduce(
(text: string, entry: [RegExp, string]) => text.replace(entry[0], entry[1]),
text,
);
}
| {
"end_byte": 3176,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/serializers/xml_helper.ts"
} |
angular/packages/compiler/src/i18n/serializers/xliff2.ts_0_7061 | /**
* @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.dev/license
*/
import * as ml from '../../ml_parser/ast';
import {XmlParser} from '../../ml_parser/xml_parser';
import {decimalDigest} from '../digest';
import * as i18n from '../i18n_ast';
import {I18nError} from '../parse_util';
import {Serializer} from './serializer';
import * as xml from './xml_helper';
const _VERSION = '2.0';
const _XMLNS = 'urn:oasis:names:tc:xliff:document:2.0';
// TODO(vicb): make this a param (s/_/-/)
const _DEFAULT_SOURCE_LANG = 'en';
const _PLACEHOLDER_TAG = 'ph';
const _PLACEHOLDER_SPANNING_TAG = 'pc';
const _MARKER_TAG = 'mrk';
const _XLIFF_TAG = 'xliff';
const _SOURCE_TAG = 'source';
const _TARGET_TAG = 'target';
const _UNIT_TAG = 'unit';
// https://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html
export class Xliff2 extends Serializer {
override write(messages: i18n.Message[], locale: string | null): string {
const visitor = new _WriteVisitor();
const units: xml.Node[] = [];
messages.forEach((message) => {
const unit = new xml.Tag(_UNIT_TAG, {id: message.id});
const notes = new xml.Tag('notes');
if (message.description || message.meaning) {
if (message.description) {
notes.children.push(
new xml.CR(8),
new xml.Tag('note', {category: 'description'}, [new xml.Text(message.description)]),
);
}
if (message.meaning) {
notes.children.push(
new xml.CR(8),
new xml.Tag('note', {category: 'meaning'}, [new xml.Text(message.meaning)]),
);
}
}
message.sources.forEach((source: i18n.MessageSpan) => {
notes.children.push(
new xml.CR(8),
new xml.Tag('note', {category: 'location'}, [
new xml.Text(
`${source.filePath}:${source.startLine}${
source.endLine !== source.startLine ? ',' + source.endLine : ''
}`,
),
]),
);
});
notes.children.push(new xml.CR(6));
unit.children.push(new xml.CR(6), notes);
const segment = new xml.Tag('segment');
segment.children.push(
new xml.CR(8),
new xml.Tag(_SOURCE_TAG, {}, visitor.serialize(message.nodes)),
new xml.CR(6),
);
unit.children.push(new xml.CR(6), segment, new xml.CR(4));
units.push(new xml.CR(4), unit);
});
const file = new xml.Tag('file', {'original': 'ng.template', id: 'ngi18n'}, [
...units,
new xml.CR(2),
]);
const xliff = new xml.Tag(
_XLIFF_TAG,
{version: _VERSION, xmlns: _XMLNS, srcLang: locale || _DEFAULT_SOURCE_LANG},
[new xml.CR(2), file, new xml.CR()],
);
return xml.serialize([
new xml.Declaration({version: '1.0', encoding: 'UTF-8'}),
new xml.CR(),
xliff,
new xml.CR(),
]);
}
override load(
content: string,
url: string,
): {locale: string; i18nNodesByMsgId: {[msgId: string]: i18n.Node[]}} {
// xliff to xml nodes
const xliff2Parser = new Xliff2Parser();
const {locale, msgIdToHtml, errors} = xliff2Parser.parse(content, url);
// xml nodes to i18n nodes
const i18nNodesByMsgId: {[msgId: string]: i18n.Node[]} = {};
const converter = new XmlToI18n();
Object.keys(msgIdToHtml).forEach((msgId) => {
const {i18nNodes, errors: e} = converter.convert(msgIdToHtml[msgId], url);
errors.push(...e);
i18nNodesByMsgId[msgId] = i18nNodes;
});
if (errors.length) {
throw new Error(`xliff2 parse errors:\n${errors.join('\n')}`);
}
return {locale: locale!, i18nNodesByMsgId};
}
override digest(message: i18n.Message): string {
return decimalDigest(message);
}
}
class _WriteVisitor implements i18n.Visitor {
private _nextPlaceholderId = 0;
visitText(text: i18n.Text, context?: any): xml.Node[] {
return [new xml.Text(text.value)];
}
visitContainer(container: i18n.Container, context?: any): xml.Node[] {
const nodes: xml.Node[] = [];
container.children.forEach((node: i18n.Node) => nodes.push(...node.visit(this)));
return nodes;
}
visitIcu(icu: i18n.Icu, context?: any): xml.Node[] {
const nodes = [new xml.Text(`{${icu.expressionPlaceholder}, ${icu.type}, `)];
Object.keys(icu.cases).forEach((c: string) => {
nodes.push(new xml.Text(`${c} {`), ...icu.cases[c].visit(this), new xml.Text(`} `));
});
nodes.push(new xml.Text(`}`));
return nodes;
}
visitTagPlaceholder(ph: i18n.TagPlaceholder, context?: any): xml.Node[] {
const type = getTypeForTag(ph.tag);
if (ph.isVoid) {
const tagPh = new xml.Tag(_PLACEHOLDER_TAG, {
id: (this._nextPlaceholderId++).toString(),
equiv: ph.startName,
type: type,
disp: `<${ph.tag}/>`,
});
return [tagPh];
}
const tagPc = new xml.Tag(_PLACEHOLDER_SPANNING_TAG, {
id: (this._nextPlaceholderId++).toString(),
equivStart: ph.startName,
equivEnd: ph.closeName,
type: type,
dispStart: `<${ph.tag}>`,
dispEnd: `</${ph.tag}>`,
});
const nodes: xml.Node[] = [].concat(...ph.children.map((node) => node.visit(this)));
if (nodes.length) {
nodes.forEach((node: xml.Node) => tagPc.children.push(node));
} else {
tagPc.children.push(new xml.Text(''));
}
return [tagPc];
}
visitPlaceholder(ph: i18n.Placeholder, context?: any): xml.Node[] {
const idStr = (this._nextPlaceholderId++).toString();
return [
new xml.Tag(_PLACEHOLDER_TAG, {
id: idStr,
equiv: ph.name,
disp: `{{${ph.value}}}`,
}),
];
}
visitBlockPlaceholder(ph: i18n.BlockPlaceholder, context?: any): xml.Node[] {
const tagPc = new xml.Tag(_PLACEHOLDER_SPANNING_TAG, {
id: (this._nextPlaceholderId++).toString(),
equivStart: ph.startName,
equivEnd: ph.closeName,
type: 'other',
dispStart: `@${ph.name}`,
dispEnd: `}`,
});
const nodes: xml.Node[] = [].concat(...ph.children.map((node) => node.visit(this)));
if (nodes.length) {
nodes.forEach((node: xml.Node) => tagPc.children.push(node));
} else {
tagPc.children.push(new xml.Text(''));
}
return [tagPc];
}
visitIcuPlaceholder(ph: i18n.IcuPlaceholder, context?: any): xml.Node[] {
const cases = Object.keys(ph.value.cases)
.map((value: string) => value + ' {...}')
.join(' ');
const idStr = (this._nextPlaceholderId++).toString();
return [
new xml.Tag(_PLACEHOLDER_TAG, {
id: idStr,
equiv: ph.name,
disp: `{${ph.value.expression}, ${ph.value.type}, ${cases}}`,
}),
];
}
serialize(nodes: i18n.Node[]): xml.Node[] {
this._nextPlaceholderId = 0;
return [].concat(...nodes.map((node) => node.visit(this)));
}
}
// Extract messages as xml nodes from the xliff file | {
"end_byte": 7061,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/serializers/xliff2.ts"
} |
angular/packages/compiler/src/i18n/serializers/xliff2.ts_7062_13593 | class Xliff2Parser implements ml.Visitor {
// using non-null assertions because they're all (re)set by parse()
private _unitMlString!: string | null;
private _errors!: I18nError[];
private _msgIdToHtml!: {[msgId: string]: string};
private _locale: string | null = null;
parse(xliff: string, url: string) {
this._unitMlString = null;
this._msgIdToHtml = {};
const xml = new XmlParser().parse(xliff, url);
this._errors = xml.errors;
ml.visitAll(this, xml.rootNodes, null);
return {
msgIdToHtml: this._msgIdToHtml,
errors: this._errors,
locale: this._locale,
};
}
visitElement(element: ml.Element, context: any): any {
switch (element.name) {
case _UNIT_TAG:
this._unitMlString = null;
const idAttr = element.attrs.find((attr) => attr.name === 'id');
if (!idAttr) {
this._addError(element, `<${_UNIT_TAG}> misses the "id" attribute`);
} else {
const id = idAttr.value;
if (this._msgIdToHtml.hasOwnProperty(id)) {
this._addError(element, `Duplicated translations for msg ${id}`);
} else {
ml.visitAll(this, element.children, null);
if (typeof this._unitMlString === 'string') {
this._msgIdToHtml[id] = this._unitMlString;
} else {
this._addError(element, `Message ${id} misses a translation`);
}
}
}
break;
case _SOURCE_TAG:
// ignore source message
break;
case _TARGET_TAG:
const innerTextStart = element.startSourceSpan.end.offset;
const innerTextEnd = element.endSourceSpan!.start.offset;
const content = element.startSourceSpan.start.file.content;
const innerText = content.slice(innerTextStart, innerTextEnd);
this._unitMlString = innerText;
break;
case _XLIFF_TAG:
const localeAttr = element.attrs.find((attr) => attr.name === 'trgLang');
if (localeAttr) {
this._locale = localeAttr.value;
}
const versionAttr = element.attrs.find((attr) => attr.name === 'version');
if (versionAttr) {
const version = versionAttr.value;
if (version !== '2.0') {
this._addError(
element,
`The XLIFF file version ${version} is not compatible with XLIFF 2.0 serializer`,
);
} else {
ml.visitAll(this, element.children, null);
}
}
break;
default:
ml.visitAll(this, element.children, null);
}
}
visitAttribute(attribute: ml.Attribute, context: any): any {}
visitText(text: ml.Text, context: any): any {}
visitComment(comment: ml.Comment, context: any): any {}
visitExpansion(expansion: ml.Expansion, context: any): any {}
visitExpansionCase(expansionCase: ml.ExpansionCase, context: any): any {}
visitBlock(block: ml.Block, context: any) {}
visitBlockParameter(parameter: ml.BlockParameter, context: any) {}
visitLetDeclaration(decl: ml.LetDeclaration, context: any) {}
private _addError(node: ml.Node, message: string): void {
this._errors.push(new I18nError(node.sourceSpan, message));
}
}
// Convert ml nodes (xliff syntax) to i18n nodes
class XmlToI18n implements ml.Visitor {
// using non-null assertion because re(set) by convert()
private _errors!: I18nError[];
convert(message: string, url: string) {
const xmlIcu = new XmlParser().parse(message, url, {tokenizeExpansionForms: true});
this._errors = xmlIcu.errors;
const i18nNodes =
this._errors.length > 0 || xmlIcu.rootNodes.length == 0
? []
: [].concat(...ml.visitAll(this, xmlIcu.rootNodes));
return {
i18nNodes,
errors: this._errors,
};
}
visitText(text: ml.Text, context: any) {
return new i18n.Text(text.value, text.sourceSpan);
}
visitElement(el: ml.Element, context: any): i18n.Node[] | null {
switch (el.name) {
case _PLACEHOLDER_TAG:
const nameAttr = el.attrs.find((attr) => attr.name === 'equiv');
if (nameAttr) {
return [new i18n.Placeholder('', nameAttr.value, el.sourceSpan)];
}
this._addError(el, `<${_PLACEHOLDER_TAG}> misses the "equiv" attribute`);
break;
case _PLACEHOLDER_SPANNING_TAG:
const startAttr = el.attrs.find((attr) => attr.name === 'equivStart');
const endAttr = el.attrs.find((attr) => attr.name === 'equivEnd');
if (!startAttr) {
this._addError(el, `<${_PLACEHOLDER_TAG}> misses the "equivStart" attribute`);
} else if (!endAttr) {
this._addError(el, `<${_PLACEHOLDER_TAG}> misses the "equivEnd" attribute`);
} else {
const startId = startAttr.value;
const endId = endAttr.value;
const nodes: i18n.Node[] = [];
return nodes.concat(
new i18n.Placeholder('', startId, el.sourceSpan),
...el.children.map((node) => node.visit(this, null)),
new i18n.Placeholder('', endId, el.sourceSpan),
);
}
break;
case _MARKER_TAG:
return [].concat(...ml.visitAll(this, el.children));
default:
this._addError(el, `Unexpected tag`);
}
return null;
}
visitExpansion(icu: ml.Expansion, context: any) {
const caseMap: {[value: string]: i18n.Node} = {};
ml.visitAll(this, icu.cases).forEach((c: any) => {
caseMap[c.value] = new i18n.Container(c.nodes, icu.sourceSpan);
});
return new i18n.Icu(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
}
visitExpansionCase(icuCase: ml.ExpansionCase, context: any): any {
return {
value: icuCase.value,
nodes: [].concat(...ml.visitAll(this, icuCase.expression)),
};
}
visitComment(comment: ml.Comment, context: any) {}
visitAttribute(attribute: ml.Attribute, context: any) {}
visitBlock(block: ml.Block, context: any) {}
visitBlockParameter(parameter: ml.BlockParameter, context: any) {}
visitLetDeclaration(decl: ml.LetDeclaration, context: any) {}
private _addError(node: ml.Node, message: string): void {
this._errors.push(new I18nError(node.sourceSpan, message));
}
}
function getTypeForTag(tag: string): string {
switch (tag.toLowerCase()) {
case 'br':
case 'b':
case 'i':
case 'u':
return 'fmt';
case 'img':
return 'image';
case 'a':
return 'link';
default:
return 'other';
}
} | {
"end_byte": 13593,
"start_byte": 7062,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/serializers/xliff2.ts"
} |
angular/packages/compiler/src/i18n/serializers/xmb.ts_0_7895 | /**
* @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.dev/license
*/
import {decimalDigest} from '../digest';
import * as i18n from '../i18n_ast';
import {PlaceholderMapper, Serializer, SimplePlaceholderMapper} from './serializer';
import * as xml from './xml_helper';
/**
* Defines the `handler` value on the serialized XMB, indicating that Angular
* generated the bundle. This is useful for analytics in Translation Console.
*
* NOTE: Keep in sync with
* packages/localize/tools/src/extract/translation_files/xmb_translation_serializer.ts.
*/
const _XMB_HANDLER = 'angular';
const _MESSAGES_TAG = 'messagebundle';
const _MESSAGE_TAG = 'msg';
const _PLACEHOLDER_TAG = 'ph';
const _EXAMPLE_TAG = 'ex';
const _SOURCE_TAG = 'source';
const _DOCTYPE = `<!ELEMENT messagebundle (msg)*>
<!ATTLIST messagebundle class CDATA #IMPLIED>
<!ELEMENT msg (#PCDATA|ph|source)*>
<!ATTLIST msg id CDATA #IMPLIED>
<!ATTLIST msg seq CDATA #IMPLIED>
<!ATTLIST msg name CDATA #IMPLIED>
<!ATTLIST msg desc CDATA #IMPLIED>
<!ATTLIST msg meaning CDATA #IMPLIED>
<!ATTLIST msg obsolete (obsolete) #IMPLIED>
<!ATTLIST msg xml:space (default|preserve) "default">
<!ATTLIST msg is_hidden CDATA #IMPLIED>
<!ELEMENT source (#PCDATA)>
<!ELEMENT ph (#PCDATA|ex)*>
<!ATTLIST ph name CDATA #REQUIRED>
<!ELEMENT ex (#PCDATA)>`;
export class Xmb extends Serializer {
override write(messages: i18n.Message[], locale: string | null): string {
const exampleVisitor = new ExampleVisitor();
const visitor = new _Visitor();
const rootNode = new xml.Tag(_MESSAGES_TAG);
rootNode.attrs['handler'] = _XMB_HANDLER;
messages.forEach((message) => {
const attrs: {[k: string]: string} = {id: message.id};
if (message.description) {
attrs['desc'] = message.description;
}
if (message.meaning) {
attrs['meaning'] = message.meaning;
}
let sourceTags: xml.Tag[] = [];
message.sources.forEach((source: i18n.MessageSpan) => {
sourceTags.push(
new xml.Tag(_SOURCE_TAG, {}, [
new xml.Text(
`${source.filePath}:${source.startLine}${
source.endLine !== source.startLine ? ',' + source.endLine : ''
}`,
),
]),
);
});
rootNode.children.push(
new xml.CR(2),
new xml.Tag(_MESSAGE_TAG, attrs, [...sourceTags, ...visitor.serialize(message.nodes)]),
);
});
rootNode.children.push(new xml.CR());
return xml.serialize([
new xml.Declaration({version: '1.0', encoding: 'UTF-8'}),
new xml.CR(),
new xml.Doctype(_MESSAGES_TAG, _DOCTYPE),
new xml.CR(),
exampleVisitor.addDefaultExamples(rootNode),
new xml.CR(),
]);
}
override load(
content: string,
url: string,
): {locale: string; i18nNodesByMsgId: {[msgId: string]: i18n.Node[]}} {
throw new Error('Unsupported');
}
override digest(message: i18n.Message): string {
return digest(message);
}
override createNameMapper(message: i18n.Message): PlaceholderMapper {
return new SimplePlaceholderMapper(message, toPublicName);
}
}
class _Visitor implements i18n.Visitor {
visitText(text: i18n.Text, context?: any): xml.Node[] {
return [new xml.Text(text.value)];
}
visitContainer(container: i18n.Container, context: any): xml.Node[] {
const nodes: xml.Node[] = [];
container.children.forEach((node: i18n.Node) => nodes.push(...node.visit(this)));
return nodes;
}
visitIcu(icu: i18n.Icu, context?: any): xml.Node[] {
const nodes = [new xml.Text(`{${icu.expressionPlaceholder}, ${icu.type}, `)];
Object.keys(icu.cases).forEach((c: string) => {
nodes.push(new xml.Text(`${c} {`), ...icu.cases[c].visit(this), new xml.Text(`} `));
});
nodes.push(new xml.Text(`}`));
return nodes;
}
visitTagPlaceholder(ph: i18n.TagPlaceholder, context?: any): xml.Node[] {
const startTagAsText = new xml.Text(`<${ph.tag}>`);
const startEx = new xml.Tag(_EXAMPLE_TAG, {}, [startTagAsText]);
// TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
const startTagPh = new xml.Tag(_PLACEHOLDER_TAG, {name: ph.startName}, [
startEx,
startTagAsText,
]);
if (ph.isVoid) {
// void tags have no children nor closing tags
return [startTagPh];
}
const closeTagAsText = new xml.Text(`</${ph.tag}>`);
const closeEx = new xml.Tag(_EXAMPLE_TAG, {}, [closeTagAsText]);
// TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
const closeTagPh = new xml.Tag(_PLACEHOLDER_TAG, {name: ph.closeName}, [
closeEx,
closeTagAsText,
]);
return [startTagPh, ...this.serialize(ph.children), closeTagPh];
}
visitPlaceholder(ph: i18n.Placeholder, context?: any): xml.Node[] {
const interpolationAsText = new xml.Text(`{{${ph.value}}}`);
// Example tag needs to be not-empty for TC.
const exTag = new xml.Tag(_EXAMPLE_TAG, {}, [interpolationAsText]);
return [
// TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
new xml.Tag(_PLACEHOLDER_TAG, {name: ph.name}, [exTag, interpolationAsText]),
];
}
visitBlockPlaceholder(ph: i18n.BlockPlaceholder, context?: any): xml.Node[] {
const startAsText = new xml.Text(`@${ph.name}`);
const startEx = new xml.Tag(_EXAMPLE_TAG, {}, [startAsText]);
// TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
const startTagPh = new xml.Tag(_PLACEHOLDER_TAG, {name: ph.startName}, [startEx, startAsText]);
const closeAsText = new xml.Text(`}`);
const closeEx = new xml.Tag(_EXAMPLE_TAG, {}, [closeAsText]);
// TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
const closeTagPh = new xml.Tag(_PLACEHOLDER_TAG, {name: ph.closeName}, [closeEx, closeAsText]);
return [startTagPh, ...this.serialize(ph.children), closeTagPh];
}
visitIcuPlaceholder(ph: i18n.IcuPlaceholder, context?: any): xml.Node[] {
const icuExpression = ph.value.expression;
const icuType = ph.value.type;
const icuCases = Object.keys(ph.value.cases)
.map((value: string) => value + ' {...}')
.join(' ');
const icuAsText = new xml.Text(`{${icuExpression}, ${icuType}, ${icuCases}}`);
const exTag = new xml.Tag(_EXAMPLE_TAG, {}, [icuAsText]);
return [
// TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
new xml.Tag(_PLACEHOLDER_TAG, {name: ph.name}, [exTag, icuAsText]),
];
}
serialize(nodes: i18n.Node[]): xml.Node[] {
return [].concat(...nodes.map((node) => node.visit(this)));
}
}
export function digest(message: i18n.Message): string {
return decimalDigest(message);
}
// TC requires at least one non-empty example on placeholders
class ExampleVisitor implements xml.IVisitor {
addDefaultExamples(node: xml.Node): xml.Node {
node.visit(this);
return node;
}
visitTag(tag: xml.Tag): void {
if (tag.name === _PLACEHOLDER_TAG) {
if (!tag.children || tag.children.length == 0) {
const exText = new xml.Text(tag.attrs['name'] || '...');
tag.children = [new xml.Tag(_EXAMPLE_TAG, {}, [exText])];
}
} else if (tag.children) {
tag.children.forEach((node) => node.visit(this));
}
}
visitText(text: xml.Text): void {}
visitDeclaration(decl: xml.Declaration): void {}
visitDoctype(doctype: xml.Doctype): void {}
}
// XMB/XTB placeholders can only contain A-Z, 0-9 and _
export function toPublicName(internalName: string): string {
return internalName.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
}
| {
"end_byte": 7895,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/serializers/xmb.ts"
} |
angular/packages/compiler/src/i18n/serializers/xliff.ts_0_6825 | /**
* @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.dev/license
*/
import * as ml from '../../ml_parser/ast';
import {XmlParser} from '../../ml_parser/xml_parser';
import {digest} from '../digest';
import * as i18n from '../i18n_ast';
import {I18nError} from '../parse_util';
import {Serializer} from './serializer';
import * as xml from './xml_helper';
const _VERSION = '1.2';
const _XMLNS = 'urn:oasis:names:tc:xliff:document:1.2';
// TODO(vicb): make this a param (s/_/-/)
const _DEFAULT_SOURCE_LANG = 'en';
const _PLACEHOLDER_TAG = 'x';
const _MARKER_TAG = 'mrk';
const _FILE_TAG = 'file';
const _SOURCE_TAG = 'source';
const _SEGMENT_SOURCE_TAG = 'seg-source';
const _ALT_TRANS_TAG = 'alt-trans';
const _TARGET_TAG = 'target';
const _UNIT_TAG = 'trans-unit';
const _CONTEXT_GROUP_TAG = 'context-group';
const _CONTEXT_TAG = 'context';
// https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html
// https://docs.oasis-open.org/xliff/v1.2/xliff-profile-html/xliff-profile-html-1.2.html
export class Xliff extends Serializer {
override write(messages: i18n.Message[], locale: string | null): string {
const visitor = new _WriteVisitor();
const transUnits: xml.Node[] = [];
messages.forEach((message) => {
let contextTags: xml.Node[] = [];
message.sources.forEach((source: i18n.MessageSpan) => {
let contextGroupTag = new xml.Tag(_CONTEXT_GROUP_TAG, {purpose: 'location'});
contextGroupTag.children.push(
new xml.CR(10),
new xml.Tag(_CONTEXT_TAG, {'context-type': 'sourcefile'}, [
new xml.Text(source.filePath),
]),
new xml.CR(10),
new xml.Tag(_CONTEXT_TAG, {'context-type': 'linenumber'}, [
new xml.Text(`${source.startLine}`),
]),
new xml.CR(8),
);
contextTags.push(new xml.CR(8), contextGroupTag);
});
const transUnit = new xml.Tag(_UNIT_TAG, {id: message.id, datatype: 'html'});
transUnit.children.push(
new xml.CR(8),
new xml.Tag(_SOURCE_TAG, {}, visitor.serialize(message.nodes)),
...contextTags,
);
if (message.description) {
transUnit.children.push(
new xml.CR(8),
new xml.Tag('note', {priority: '1', from: 'description'}, [
new xml.Text(message.description),
]),
);
}
if (message.meaning) {
transUnit.children.push(
new xml.CR(8),
new xml.Tag('note', {priority: '1', from: 'meaning'}, [new xml.Text(message.meaning)]),
);
}
transUnit.children.push(new xml.CR(6));
transUnits.push(new xml.CR(6), transUnit);
});
const body = new xml.Tag('body', {}, [...transUnits, new xml.CR(4)]);
const file = new xml.Tag(
'file',
{
'source-language': locale || _DEFAULT_SOURCE_LANG,
datatype: 'plaintext',
original: 'ng2.template',
},
[new xml.CR(4), body, new xml.CR(2)],
);
const xliff = new xml.Tag('xliff', {version: _VERSION, xmlns: _XMLNS}, [
new xml.CR(2),
file,
new xml.CR(),
]);
return xml.serialize([
new xml.Declaration({version: '1.0', encoding: 'UTF-8'}),
new xml.CR(),
xliff,
new xml.CR(),
]);
}
override load(
content: string,
url: string,
): {locale: string; i18nNodesByMsgId: {[msgId: string]: i18n.Node[]}} {
// xliff to xml nodes
const xliffParser = new XliffParser();
const {locale, msgIdToHtml, errors} = xliffParser.parse(content, url);
// xml nodes to i18n nodes
const i18nNodesByMsgId: {[msgId: string]: i18n.Node[]} = {};
const converter = new XmlToI18n();
Object.keys(msgIdToHtml).forEach((msgId) => {
const {i18nNodes, errors: e} = converter.convert(msgIdToHtml[msgId], url);
errors.push(...e);
i18nNodesByMsgId[msgId] = i18nNodes;
});
if (errors.length) {
throw new Error(`xliff parse errors:\n${errors.join('\n')}`);
}
return {locale: locale!, i18nNodesByMsgId};
}
override digest(message: i18n.Message): string {
return digest(message);
}
}
class _WriteVisitor implements i18n.Visitor {
visitText(text: i18n.Text, context?: any): xml.Node[] {
return [new xml.Text(text.value)];
}
visitContainer(container: i18n.Container, context?: any): xml.Node[] {
const nodes: xml.Node[] = [];
container.children.forEach((node: i18n.Node) => nodes.push(...node.visit(this)));
return nodes;
}
visitIcu(icu: i18n.Icu, context?: any): xml.Node[] {
const nodes = [new xml.Text(`{${icu.expressionPlaceholder}, ${icu.type}, `)];
Object.keys(icu.cases).forEach((c: string) => {
nodes.push(new xml.Text(`${c} {`), ...icu.cases[c].visit(this), new xml.Text(`} `));
});
nodes.push(new xml.Text(`}`));
return nodes;
}
visitTagPlaceholder(ph: i18n.TagPlaceholder, context?: any): xml.Node[] {
const ctype = getCtypeForTag(ph.tag);
if (ph.isVoid) {
// void tags have no children nor closing tags
return [
new xml.Tag(_PLACEHOLDER_TAG, {id: ph.startName, ctype, 'equiv-text': `<${ph.tag}/>`}),
];
}
const startTagPh = new xml.Tag(_PLACEHOLDER_TAG, {
id: ph.startName,
ctype,
'equiv-text': `<${ph.tag}>`,
});
const closeTagPh = new xml.Tag(_PLACEHOLDER_TAG, {
id: ph.closeName,
ctype,
'equiv-text': `</${ph.tag}>`,
});
return [startTagPh, ...this.serialize(ph.children), closeTagPh];
}
visitPlaceholder(ph: i18n.Placeholder, context?: any): xml.Node[] {
return [new xml.Tag(_PLACEHOLDER_TAG, {id: ph.name, 'equiv-text': `{{${ph.value}}}`})];
}
visitBlockPlaceholder(ph: i18n.BlockPlaceholder, context?: any): xml.Node[] {
const ctype = `x-${ph.name.toLowerCase().replace(/[^a-z0-9]/g, '-')}`;
const startTagPh = new xml.Tag(_PLACEHOLDER_TAG, {
id: ph.startName,
ctype,
'equiv-text': `@${ph.name}`,
});
const closeTagPh = new xml.Tag(_PLACEHOLDER_TAG, {id: ph.closeName, ctype, 'equiv-text': `}`});
return [startTagPh, ...this.serialize(ph.children), closeTagPh];
}
visitIcuPlaceholder(ph: i18n.IcuPlaceholder, context?: any): xml.Node[] {
const equivText = `{${ph.value.expression}, ${ph.value.type}, ${Object.keys(ph.value.cases)
.map((value: string) => value + ' {...}')
.join(' ')}}`;
return [new xml.Tag(_PLACEHOLDER_TAG, {id: ph.name, 'equiv-text': equivText})];
}
serialize(nodes: i18n.Node[]): xml.Node[] {
return [].concat(...nodes.map((node) => node.visit(this)));
}
}
// TODO(vicb): add error management (structure)
// Extract messages as xml nodes from the xliff file | {
"end_byte": 6825,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/serializers/xliff.ts"
} |
angular/packages/compiler/src/i18n/serializers/xliff.ts_6826_12219 | class XliffParser implements ml.Visitor {
// using non-null assertions because they're re(set) by parse()
private _unitMlString!: string | null;
private _errors!: I18nError[];
private _msgIdToHtml!: {[msgId: string]: string};
private _locale: string | null = null;
parse(xliff: string, url: string) {
this._unitMlString = null;
this._msgIdToHtml = {};
const xml = new XmlParser().parse(xliff, url);
this._errors = xml.errors;
ml.visitAll(this, xml.rootNodes, null);
return {
msgIdToHtml: this._msgIdToHtml,
errors: this._errors,
locale: this._locale,
};
}
visitElement(element: ml.Element, context: any): any {
switch (element.name) {
case _UNIT_TAG:
this._unitMlString = null!;
const idAttr = element.attrs.find((attr) => attr.name === 'id');
if (!idAttr) {
this._addError(element, `<${_UNIT_TAG}> misses the "id" attribute`);
} else {
const id = idAttr.value;
if (this._msgIdToHtml.hasOwnProperty(id)) {
this._addError(element, `Duplicated translations for msg ${id}`);
} else {
ml.visitAll(this, element.children, null);
if (typeof this._unitMlString === 'string') {
this._msgIdToHtml[id] = this._unitMlString;
} else {
this._addError(element, `Message ${id} misses a translation`);
}
}
}
break;
// ignore those tags
case _SOURCE_TAG:
case _SEGMENT_SOURCE_TAG:
case _ALT_TRANS_TAG:
break;
case _TARGET_TAG:
const innerTextStart = element.startSourceSpan.end.offset;
const innerTextEnd = element.endSourceSpan!.start.offset;
const content = element.startSourceSpan.start.file.content;
const innerText = content.slice(innerTextStart, innerTextEnd);
this._unitMlString = innerText;
break;
case _FILE_TAG:
const localeAttr = element.attrs.find((attr) => attr.name === 'target-language');
if (localeAttr) {
this._locale = localeAttr.value;
}
ml.visitAll(this, element.children, null);
break;
default:
// TODO(vicb): assert file structure, xliff version
// For now only recurse on unhandled nodes
ml.visitAll(this, element.children, null);
}
}
visitAttribute(attribute: ml.Attribute, context: any): any {}
visitText(text: ml.Text, context: any): any {}
visitComment(comment: ml.Comment, context: any): any {}
visitExpansion(expansion: ml.Expansion, context: any): any {}
visitExpansionCase(expansionCase: ml.ExpansionCase, context: any): any {}
visitBlock(block: ml.Block, context: any) {}
visitBlockParameter(parameter: ml.BlockParameter, context: any) {}
visitLetDeclaration(decl: ml.LetDeclaration, context: any) {}
private _addError(node: ml.Node, message: string): void {
this._errors.push(new I18nError(node.sourceSpan, message));
}
}
// Convert ml nodes (xliff syntax) to i18n nodes
class XmlToI18n implements ml.Visitor {
// using non-null assertion because it's re(set) by convert()
private _errors!: I18nError[];
convert(message: string, url: string) {
const xmlIcu = new XmlParser().parse(message, url, {tokenizeExpansionForms: true});
this._errors = xmlIcu.errors;
const i18nNodes =
this._errors.length > 0 || xmlIcu.rootNodes.length == 0
? []
: [].concat(...ml.visitAll(this, xmlIcu.rootNodes));
return {
i18nNodes: i18nNodes,
errors: this._errors,
};
}
visitText(text: ml.Text, context: any) {
return new i18n.Text(text.value, text.sourceSpan);
}
visitElement(el: ml.Element, context: any): i18n.Placeholder | ml.Node[] | null {
if (el.name === _PLACEHOLDER_TAG) {
const nameAttr = el.attrs.find((attr) => attr.name === 'id');
if (nameAttr) {
return new i18n.Placeholder('', nameAttr.value, el.sourceSpan);
}
this._addError(el, `<${_PLACEHOLDER_TAG}> misses the "id" attribute`);
return null;
}
if (el.name === _MARKER_TAG) {
return [].concat(...ml.visitAll(this, el.children));
}
this._addError(el, `Unexpected tag`);
return null;
}
visitExpansion(icu: ml.Expansion, context: any) {
const caseMap: {[value: string]: i18n.Node} = {};
ml.visitAll(this, icu.cases).forEach((c: any) => {
caseMap[c.value] = new i18n.Container(c.nodes, icu.sourceSpan);
});
return new i18n.Icu(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
}
visitExpansionCase(icuCase: ml.ExpansionCase, context: any): any {
return {
value: icuCase.value,
nodes: ml.visitAll(this, icuCase.expression),
};
}
visitComment(comment: ml.Comment, context: any) {}
visitAttribute(attribute: ml.Attribute, context: any) {}
visitBlock(block: ml.Block, context: any) {}
visitBlockParameter(parameter: ml.BlockParameter, context: any) {}
visitLetDeclaration(decl: ml.LetDeclaration, context: any) {}
private _addError(node: ml.Node, message: string): void {
this._errors.push(new I18nError(node.sourceSpan, message));
}
}
function getCtypeForTag(tag: string): string {
switch (tag.toLowerCase()) {
case 'br':
return 'lb';
case 'img':
return 'image';
default:
return `x-${tag}`;
}
} | {
"end_byte": 12219,
"start_byte": 6826,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/i18n/serializers/xliff.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.