_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/compiler/src/template/pipeline/src/phases/nullish_coalescing.ts_0_1955
/** * @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 * as ir from '../../ir'; import type {CompilationJob} from '../compilation'; /** * Nullish coalescing expressions such as `a ?? b` have different semantics in Angular templates as * compared to JavaScript. In particular, they default to `null` instead of `undefined`. Therefore, * we replace them with ternary expressions, assigning temporaries as needed to avoid re-evaluating * the same sub-expression multiple times. */ export function generateNullishCoalesceExpressions(job: CompilationJob): void { for (const unit of job.units) { for (const op of unit.ops()) { ir.transformExpressionsInOp( op, (expr) => { if ( !(expr instanceof o.BinaryOperatorExpr) || expr.operator !== o.BinaryOperator.NullishCoalesce ) { return expr; } const assignment = new ir.AssignTemporaryExpr(expr.lhs.clone(), job.allocateXrefId()); const read = new ir.ReadTemporaryExpr(assignment.xref); // TODO: When not in compatibility mode for TemplateDefinitionBuilder, we can just emit // `t != null` instead of including an undefined check as well. return new o.ConditionalExpr( new o.BinaryOperatorExpr( o.BinaryOperator.And, new o.BinaryOperatorExpr(o.BinaryOperator.NotIdentical, assignment, o.NULL_EXPR), new o.BinaryOperatorExpr( o.BinaryOperator.NotIdentical, read, new o.LiteralExpr(undefined), ), ), read.clone(), expr.rhs, ); }, ir.VisitorContextFlag.None, ); } } }
{ "end_byte": 1955, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/nullish_coalescing.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/ordering.ts_0_5927
/** * @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 ir from '../../ir'; import {CompilationJobKind, type CompilationJob} from '../compilation'; function kindTest(kind: ir.OpKind): (op: ir.UpdateOp) => boolean { return (op: ir.UpdateOp) => op.kind === kind; } function kindWithInterpolationTest( kind: ir.OpKind.Attribute | ir.OpKind.Property | ir.OpKind.HostProperty, interpolation: boolean, ): (op: ir.UpdateOp) => boolean { return (op: ir.UpdateOp) => { return op.kind === kind && interpolation === op.expression instanceof ir.Interpolation; }; } function basicListenerKindTest(op: ir.CreateOp): boolean { return ( (op.kind === ir.OpKind.Listener && !(op.hostListener && op.isAnimationListener)) || op.kind === ir.OpKind.TwoWayListener ); } function nonInterpolationPropertyKindTest(op: ir.UpdateOp): boolean { return ( (op.kind === ir.OpKind.Property || op.kind === ir.OpKind.TwoWayProperty) && !(op.expression instanceof ir.Interpolation) ); } interface Rule<T extends ir.CreateOp | ir.UpdateOp> { test: (op: T) => boolean; transform?: (ops: Array<T>) => Array<T>; } /** * Defines the groups based on `OpKind` that ops will be divided into, for the various create * op kinds. Ops will be collected into groups, then optionally transformed, before recombining * the groups in the order defined here. */ const CREATE_ORDERING: Array<Rule<ir.CreateOp>> = [ {test: (op) => op.kind === ir.OpKind.Listener && op.hostListener && op.isAnimationListener}, {test: basicListenerKindTest}, ]; /** * Defines the groups based on `OpKind` that ops will be divided into, for the various update * op kinds. */ const UPDATE_ORDERING: Array<Rule<ir.UpdateOp>> = [ {test: kindTest(ir.OpKind.StyleMap), transform: keepLast}, {test: kindTest(ir.OpKind.ClassMap), transform: keepLast}, {test: kindTest(ir.OpKind.StyleProp)}, {test: kindTest(ir.OpKind.ClassProp)}, {test: kindWithInterpolationTest(ir.OpKind.Attribute, true)}, {test: kindWithInterpolationTest(ir.OpKind.Property, true)}, {test: nonInterpolationPropertyKindTest}, {test: kindWithInterpolationTest(ir.OpKind.Attribute, false)}, ]; /** * Host bindings have their own update ordering. */ const UPDATE_HOST_ORDERING: Array<Rule<ir.UpdateOp>> = [ {test: kindWithInterpolationTest(ir.OpKind.HostProperty, true)}, {test: kindWithInterpolationTest(ir.OpKind.HostProperty, false)}, {test: kindTest(ir.OpKind.Attribute)}, {test: kindTest(ir.OpKind.StyleMap), transform: keepLast}, {test: kindTest(ir.OpKind.ClassMap), transform: keepLast}, {test: kindTest(ir.OpKind.StyleProp)}, {test: kindTest(ir.OpKind.ClassProp)}, ]; /** * The set of all op kinds we handle in the reordering phase. */ const handledOpKinds = new Set([ ir.OpKind.Listener, ir.OpKind.TwoWayListener, ir.OpKind.StyleMap, ir.OpKind.ClassMap, ir.OpKind.StyleProp, ir.OpKind.ClassProp, ir.OpKind.Property, ir.OpKind.TwoWayProperty, ir.OpKind.HostProperty, ir.OpKind.Attribute, ]); /** * Many type of operations have ordering constraints that must be respected. For example, a * `ClassMap` instruction must be ordered after a `StyleMap` instruction, in order to have * predictable semantics that match TemplateDefinitionBuilder and don't break applications. */ export function orderOps(job: CompilationJob) { for (const unit of job.units) { // First, we pull out ops that need to be ordered. Then, when we encounter an op that shouldn't // be reordered, put the ones we've pulled so far back in the correct order. Finally, if we // still have ops pulled at the end, put them back in the correct order. // Create mode: orderWithin(unit.create, CREATE_ORDERING as Array<Rule<ir.CreateOp | ir.UpdateOp>>); // Update mode: const ordering = unit.job.kind === CompilationJobKind.Host ? UPDATE_HOST_ORDERING : UPDATE_ORDERING; orderWithin(unit.update, ordering as Array<Rule<ir.CreateOp | ir.UpdateOp>>); } } /** * Order all the ops within the specified group. */ function orderWithin( opList: ir.OpList<ir.CreateOp | ir.UpdateOp>, ordering: Array<Rule<ir.CreateOp | ir.UpdateOp>>, ) { let opsToOrder: Array<ir.CreateOp | ir.UpdateOp> = []; // Only reorder ops that target the same xref; do not mix ops that target different xrefs. let firstTargetInGroup: ir.XrefId | null = null; for (const op of opList) { const currentTarget = ir.hasDependsOnSlotContextTrait(op) ? op.target : null; if ( !handledOpKinds.has(op.kind) || (currentTarget !== firstTargetInGroup && firstTargetInGroup !== null && currentTarget !== null) ) { ir.OpList.insertBefore(reorder(opsToOrder, ordering), op); opsToOrder = []; firstTargetInGroup = null; } if (handledOpKinds.has(op.kind)) { opsToOrder.push(op); ir.OpList.remove(op); firstTargetInGroup = currentTarget ?? firstTargetInGroup; } } opList.push(reorder(opsToOrder, ordering)); } /** * Reorders the given list of ops according to the ordering defined by `ORDERING`. */ function reorder<T extends ir.CreateOp | ir.UpdateOp>( ops: Array<T>, ordering: Array<Rule<T>>, ): Array<T> { // Break the ops list into groups based on OpKind. const groups = Array.from(ordering, () => new Array<T>()); for (const op of ops) { const groupIndex = ordering.findIndex((o) => o.test(op)); groups[groupIndex].push(op); } // Reassemble the groups into a single list, in the correct order. return groups.flatMap((group, i) => { const transform = ordering[i].transform; return transform ? transform(group) : group; }); } /** * Keeps only the last op in a list of ops. */ function keepLast<T>(ops: Array<T>) { return ops.slice(ops.length - 1); }
{ "end_byte": 5927, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/ordering.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/pipe_creation.ts_0_3091
/** * @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 ir from '../../ir'; import type {CompilationJob, CompilationUnit} from '../compilation'; /** * This phase generates pipe creation instructions. We do this based on the pipe bindings found in * the update block, in the order we see them. * * When not in compatibility mode, we can simply group all these creation instructions together, to * maximize chaining opportunities. */ export function createPipes(job: CompilationJob): void { for (const unit of job.units) { processPipeBindingsInView(unit); } } function processPipeBindingsInView(unit: CompilationUnit): void { for (const updateOp of unit.update) { ir.visitExpressionsInOp(updateOp, (expr, flags) => { if (!ir.isIrExpression(expr)) { return; } if (expr.kind !== ir.ExpressionKind.PipeBinding) { return; } if (flags & ir.VisitorContextFlag.InChildOperation) { throw new Error(`AssertionError: pipe bindings should not appear in child expressions`); } if (unit.job.compatibility) { // TODO: We can delete this cast and check once compatibility mode is removed. const slotHandle = (updateOp as any).target; if (slotHandle == undefined) { throw new Error(`AssertionError: expected slot handle to be assigned for pipe creation`); } addPipeToCreationBlock(unit, (updateOp as any).target, expr); } else { // When not in compatibility mode, we just add the pipe to the end of the create block. This // is not only simpler and faster, but allows more chaining opportunities for other // instructions. unit.create.push(ir.createPipeOp(expr.target, expr.targetSlot, expr.name)); } }); } } function addPipeToCreationBlock( unit: CompilationUnit, afterTargetXref: ir.XrefId, binding: ir.PipeBindingExpr, ): void { // Find the appropriate point to insert the Pipe creation operation. // We're looking for `afterTargetXref` (and also want to insert after any other pipe operations // which might be beyond it). for (let op = unit.create.head.next!; op.kind !== ir.OpKind.ListEnd; op = op.next!) { if (!ir.hasConsumesSlotTrait<ir.CreateOp>(op)) { continue; } if (op.xref !== afterTargetXref) { continue; } // We've found a tentative insertion point; however, we also want to skip past any _other_ pipe // operations present. while (op.next!.kind === ir.OpKind.Pipe) { op = op.next!; } const pipe = ir.createPipeOp(binding.target, binding.targetSlot, binding.name) as ir.CreateOp; ir.OpList.insertBefore(pipe, op.next!); // This completes adding the pipe to the creation block. return; } // At this point, we've failed to add the pipe to the creation block. throw new Error(`AssertionError: unable to find insertion point for pipe ${binding.name}`); }
{ "end_byte": 3091, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/pipe_creation.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/conditionals.ts_0_2784
/** * @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 * as ir from '../../ir'; import {ComponentCompilationJob} from '../compilation'; /** * Collapse the various conditions of conditional ops (if, switch) into a single test expression. */ export function generateConditionalExpressions(job: ComponentCompilationJob): void { for (const unit of job.units) { for (const op of unit.ops()) { if (op.kind !== ir.OpKind.Conditional) { continue; } let test: o.Expression; // Any case with a `null` condition is `default`. If one exists, default to it instead. const defaultCase = op.conditions.findIndex((cond) => cond.expr === null); if (defaultCase >= 0) { const slot = op.conditions.splice(defaultCase, 1)[0].targetSlot; test = new ir.SlotLiteralExpr(slot); } else { // By default, a switch evaluates to `-1`, causing no template to be displayed. test = o.literal(-1); } // Switch expressions assign their main test to a temporary, to avoid re-executing it. let tmp = op.test == null ? null : new ir.AssignTemporaryExpr(op.test, job.allocateXrefId()); // For each remaining condition, test whether the temporary satifies the check. (If no temp is // present, just check each expression directly.) for (let i = op.conditions.length - 1; i >= 0; i--) { let conditionalCase = op.conditions[i]; if (conditionalCase.expr === null) { continue; } if (tmp !== null) { const useTmp = i === 0 ? tmp : new ir.ReadTemporaryExpr(tmp.xref); conditionalCase.expr = new o.BinaryOperatorExpr( o.BinaryOperator.Identical, useTmp, conditionalCase.expr, ); } else if (conditionalCase.alias !== null) { const caseExpressionTemporaryXref = job.allocateXrefId(); conditionalCase.expr = new ir.AssignTemporaryExpr( conditionalCase.expr, caseExpressionTemporaryXref, ); op.contextValue = new ir.ReadTemporaryExpr(caseExpressionTemporaryXref); } test = new o.ConditionalExpr( conditionalCase.expr, new ir.SlotLiteralExpr(conditionalCase.targetSlot), test, ); } // Save the resulting aggregate Joost-expression. op.processed = test; // Clear the original conditions array, since we no longer need it, and don't want it to // affect subsequent phases (e.g. pipe creation). op.conditions = []; } } }
{ "end_byte": 2784, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/conditionals.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/resolve_contexts.ts_0_2365
/** * @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 * as ir from '../../ir'; import { CompilationJob, CompilationUnit, ComponentCompilationJob, ViewCompilationUnit, } from '../compilation'; /** * Resolves `ir.ContextExpr` expressions (which represent embedded view or component contexts) to * either the `ctx` parameter to component functions (for the current view context) or to variables * that store those contexts (for contexts accessed via the `nextContext()` instruction). */ export function resolveContexts(job: CompilationJob): void { for (const unit of job.units) { processLexicalScope(unit, unit.create); processLexicalScope(unit, unit.update); } } function processLexicalScope( view: CompilationUnit, ops: ir.OpList<ir.CreateOp | ir.UpdateOp>, ): void { // Track the expressions used to access all available contexts within the current view, by the // view `ir.XrefId`. const scope = new Map<ir.XrefId, o.Expression>(); // The current view's context is accessible via the `ctx` parameter. scope.set(view.xref, o.variable('ctx')); for (const op of ops) { switch (op.kind) { case ir.OpKind.Variable: switch (op.variable.kind) { case ir.SemanticVariableKind.Context: scope.set(op.variable.view, new ir.ReadVariableExpr(op.xref)); break; } break; case ir.OpKind.Listener: case ir.OpKind.TwoWayListener: processLexicalScope(view, op.handlerOps); break; } } if (view === view.job.root) { // Prefer `ctx` of the root view to any variables which happen to contain the root context. scope.set(view.xref, o.variable('ctx')); } for (const op of ops) { ir.transformExpressionsInOp( op, (expr) => { if (expr instanceof ir.ContextExpr) { if (!scope.has(expr.view)) { throw new Error( `No context found for reference to view ${expr.view} from view ${view.xref}`, ); } return scope.get(expr.view)!; } else { return expr; } }, ir.VisitorContextFlag.None, ); } }
{ "end_byte": 2365, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/resolve_contexts.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/track_fn_generation.ts_0_2049
/** * @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 * as ir from '../../ir'; import type {CompilationJob} from '../compilation'; /** * Generate track functions that need to be extracted to the constant pool. This entails wrapping * them in an arrow (or traditional) function, replacing context reads with `this.`, and storing * them in the constant pool. * * Note that, if a track function was previously optimized, it will not need to be extracted, and * this phase is a no-op. */ export function generateTrackFns(job: CompilationJob): void { for (const unit of job.units) { for (const op of unit.create) { if (op.kind !== ir.OpKind.RepeaterCreate) { continue; } if (op.trackByFn !== null) { // The final track function was already set, probably because it was optimized. continue; } // Find all component context reads. let usesComponentContext = false; op.track = ir.transformExpressionsInExpression( op.track, (expr) => { if (expr instanceof ir.PipeBindingExpr || expr instanceof ir.PipeBindingVariadicExpr) { throw new Error(`Illegal State: Pipes are not allowed in this context`); } if (expr instanceof ir.TrackContextExpr) { usesComponentContext = true; return o.variable('this'); } return expr; }, ir.VisitorContextFlag.None, ); let fn: o.FunctionExpr | o.ArrowFunctionExpr; const fnParams = [new o.FnParam('$index'), new o.FnParam('$item')]; if (usesComponentContext) { fn = new o.FunctionExpr(fnParams, [new o.ReturnStatement(op.track)]); } else { fn = o.arrowFn(fnParams, op.track); } op.trackByFn = job.pool.getSharedFunctionReference(fn, '_forTrack'); } } }
{ "end_byte": 2049, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/track_fn_generation.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/generate_variables.ts_0_6617
/** * @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 * as ir from '../../ir'; import type {ComponentCompilationJob, ViewCompilationUnit} from '../compilation'; /** * Generate a preamble sequence for each view creation block and listener function which declares * any variables that be referenced in other operations in the block. * * Variables generated include: * * a saved view context to be used to restore the current view in event listeners. * * the context of the restored view within event listener handlers. * * context variables from the current view as well as all parent views (including the root * context if needed). * * local references from elements within the current view and any lexical parents. * * Variables are generated here unconditionally, and may optimized away in future operations if it * turns out their values (and any side effects) are unused. */ export function generateVariables(job: ComponentCompilationJob): void { recursivelyProcessView(job.root, /* there is no parent scope for the root view */ null); } /** * Process the given `ViewCompilation` and generate preambles for it and any listeners that it * declares. * * @param `parentScope` a scope extracted from the parent view which captures any variables which * should be inherited by this view. `null` if the current view is the root view. */ function recursivelyProcessView(view: ViewCompilationUnit, parentScope: Scope | null): void { // Extract a `Scope` from this view. const scope = getScopeForView(view, parentScope); for (const op of view.create) { switch (op.kind) { case ir.OpKind.Template: // Descend into child embedded views. recursivelyProcessView(view.job.views.get(op.xref)!, scope); break; case ir.OpKind.Projection: if (op.fallbackView !== null) { recursivelyProcessView(view.job.views.get(op.fallbackView)!, scope); } break; case ir.OpKind.RepeaterCreate: // Descend into child embedded views. recursivelyProcessView(view.job.views.get(op.xref)!, scope); if (op.emptyView) { recursivelyProcessView(view.job.views.get(op.emptyView)!, scope); } break; case ir.OpKind.Listener: case ir.OpKind.TwoWayListener: // Prepend variables to listener handler functions. op.handlerOps.prepend(generateVariablesInScopeForView(view, scope, true)); break; } } view.update.prepend(generateVariablesInScopeForView(view, scope, false)); } /** * Lexical scope of a view, including a reference to its parent view's scope, if any. */ interface Scope { /** * `XrefId` of the view to which this scope corresponds. */ view: ir.XrefId; viewContextVariable: ir.SemanticVariable; contextVariables: Map<string, ir.SemanticVariable>; aliases: Set<ir.AliasVariable>; /** * Local references collected from elements within the view. */ references: Reference[]; /** * `@let` declarations collected from the view. */ letDeclarations: LetDeclaration[]; /** * `Scope` of the parent view, if any. */ parent: Scope | null; } /** * Information needed about a local reference collected from an element within a view. */ interface Reference { /** * Name given to the local reference variable within the template. * * This is not the name which will be used for the variable declaration in the generated * template code. */ name: string; /** * `XrefId` of the element-like node which this reference targets. * * The reference may be either to the element (or template) itself, or to a directive on it. */ targetId: ir.XrefId; targetSlot: ir.SlotHandle; /** * A generated offset of this reference among all the references on a specific element. */ offset: number; variable: ir.SemanticVariable; } /** * Information about `@let` declaration collected from a view. */ interface LetDeclaration { /** `XrefId` of the `@let` declaration that the reference is pointing to. */ targetId: ir.XrefId; /** Slot in which the declaration is stored. */ targetSlot: ir.SlotHandle; /** Variable referring to the declaration. */ variable: ir.IdentifierVariable; } /** * Process a view and generate a `Scope` representing the variables available for reference within * that view. */ function getScopeForView(view: ViewCompilationUnit, parent: Scope | null): Scope { const scope: Scope = { view: view.xref, viewContextVariable: { kind: ir.SemanticVariableKind.Context, name: null, view: view.xref, }, contextVariables: new Map<string, ir.SemanticVariable>(), aliases: view.aliases, references: [], letDeclarations: [], parent, }; for (const identifier of view.contextVariables.keys()) { scope.contextVariables.set(identifier, { kind: ir.SemanticVariableKind.Identifier, name: null, identifier, local: false, }); } for (const op of view.create) { switch (op.kind) { case ir.OpKind.ElementStart: case ir.OpKind.Template: if (!Array.isArray(op.localRefs)) { throw new Error(`AssertionError: expected localRefs to be an array`); } // Record available local references from this element. for (let offset = 0; offset < op.localRefs.length; offset++) { scope.references.push({ name: op.localRefs[offset].name, targetId: op.xref, targetSlot: op.handle, offset, variable: { kind: ir.SemanticVariableKind.Identifier, name: null, identifier: op.localRefs[offset].name, local: false, }, }); } break; case ir.OpKind.DeclareLet: scope.letDeclarations.push({ targetId: op.xref, targetSlot: op.handle, variable: { kind: ir.SemanticVariableKind.Identifier, name: null, identifier: op.declaredName, local: false, }, }); break; } } return scope; } /** * Generate declarations for all variables that are in scope for a given view. * * This is a recursive process, as views inherit variables available from their parent view, which * itself may have inherited variables, etc. */
{ "end_byte": 6617, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/generate_variables.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/generate_variables.ts_6618_9099
function generateVariablesInScopeForView( view: ViewCompilationUnit, scope: Scope, isListener: boolean, ): ir.VariableOp<ir.UpdateOp>[] { const newOps: ir.VariableOp<ir.UpdateOp>[] = []; if (scope.view !== view.xref) { // Before generating variables for a parent view, we need to switch to the context of the parent // view with a `nextContext` expression. This context switching operation itself declares a // variable, because the context of the view may be referenced directly. newOps.push( ir.createVariableOp( view.job.allocateXrefId(), scope.viewContextVariable, new ir.NextContextExpr(), ir.VariableFlags.None, ), ); } // Add variables for all context variables available in this scope's view. const scopeView = view.job.views.get(scope.view)!; for (const [name, value] of scopeView.contextVariables) { const context = new ir.ContextExpr(scope.view); // We either read the context, or, if the variable is CTX_REF, use the context directly. const variable = value === ir.CTX_REF ? context : new o.ReadPropExpr(context, value); // Add the variable declaration. newOps.push( ir.createVariableOp( view.job.allocateXrefId(), scope.contextVariables.get(name)!, variable, ir.VariableFlags.None, ), ); } for (const alias of scopeView.aliases) { newOps.push( ir.createVariableOp( view.job.allocateXrefId(), alias, alias.expression.clone(), ir.VariableFlags.AlwaysInline, ), ); } // Add variables for all local references declared for elements in this scope. for (const ref of scope.references) { newOps.push( ir.createVariableOp( view.job.allocateXrefId(), ref.variable, new ir.ReferenceExpr(ref.targetId, ref.targetSlot, ref.offset), ir.VariableFlags.None, ), ); } if (scope.view !== view.xref || isListener) { for (const decl of scope.letDeclarations) { newOps.push( ir.createVariableOp<ir.UpdateOp>( view.job.allocateXrefId(), decl.variable, new ir.ContextLetReferenceExpr(decl.targetId, decl.targetSlot), ir.VariableFlags.None, ), ); } } if (scope.parent !== null) { // Recursively add variables from the parent scope. newOps.push(...generateVariablesInScopeForView(view, scope.parent, false)); } return newOps; }
{ "end_byte": 9099, "start_byte": 6618, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/generate_variables.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/empty_elements.ts_0_1856
/** * @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 ir from '../../ir'; import type {CompilationJob} from '../compilation'; const REPLACEMENTS = new Map<ir.OpKind, [ir.OpKind, ir.OpKind]>([ [ir.OpKind.ElementEnd, [ir.OpKind.ElementStart, ir.OpKind.Element]], [ir.OpKind.ContainerEnd, [ir.OpKind.ContainerStart, ir.OpKind.Container]], [ir.OpKind.I18nEnd, [ir.OpKind.I18nStart, ir.OpKind.I18n]], ]); /** * Op kinds that should not prevent merging of start/end ops. */ const IGNORED_OP_KINDS = new Set([ir.OpKind.Pipe]); /** * Replace sequences of mergable instructions (e.g. `ElementStart` and `ElementEnd`) with a * consolidated instruction (e.g. `Element`). */ export function collapseEmptyInstructions(job: CompilationJob): void { for (const unit of job.units) { for (const op of unit.create) { // Find end ops that may be able to be merged. const opReplacements = REPLACEMENTS.get(op.kind); if (opReplacements === undefined) { continue; } const [startKind, mergedKind] = opReplacements; // Locate the previous (non-ignored) op. let prevOp: ir.CreateOp | null = op.prev; while (prevOp !== null && IGNORED_OP_KINDS.has(prevOp.kind)) { prevOp = prevOp.prev; } // If the previous op is the corresponding start op, we can megre. if (prevOp !== null && prevOp.kind === startKind) { // Transmute the start instruction to the merged version. This is safe as they're designed // to be identical apart from the `kind`. (prevOp as ir.Op<ir.CreateOp>).kind = mergedKind; // Remove the end instruction. ir.OpList.remove<ir.CreateOp>(op); } } } }
{ "end_byte": 1856, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/empty_elements.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/resolve_i18n_element_placeholders.ts_0_1155
/** * @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 ir from '../../ir'; import {ComponentCompilationJob, ViewCompilationUnit} from '../compilation'; /** * Resolve the element placeholders in i18n messages. */ export function resolveI18nElementPlaceholders(job: ComponentCompilationJob) { // Record all of the element and i18n context ops for use later. const i18nContexts = new Map<ir.XrefId, ir.I18nContextOp>(); const elements = new Map<ir.XrefId, ir.ElementStartOp>(); for (const unit of job.units) { for (const op of unit.create) { switch (op.kind) { case ir.OpKind.I18nContext: i18nContexts.set(op.xref, op); break; case ir.OpKind.ElementStart: elements.set(op.xref, op); break; } } } resolvePlaceholdersForView(job, job.root, i18nContexts, elements); } /** * Recursively resolves element and template tag placeholders in the given view. */
{ "end_byte": 1155, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/resolve_i18n_element_placeholders.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/resolve_i18n_element_placeholders.ts_1156_9856
function resolvePlaceholdersForView( job: ComponentCompilationJob, unit: ViewCompilationUnit, i18nContexts: Map<ir.XrefId, ir.I18nContextOp>, elements: Map<ir.XrefId, ir.ElementStartOp>, pendingStructuralDirective?: ir.TemplateOp, ) { // Track the current i18n op and corresponding i18n context op as we step through the creation // IR. let currentOps: {i18nBlock: ir.I18nStartOp; i18nContext: ir.I18nContextOp} | null = null; let pendingStructuralDirectiveCloses = new Map<ir.XrefId, ir.TemplateOp>(); for (const op of unit.create) { switch (op.kind) { case ir.OpKind.I18nStart: if (!op.context) { throw Error('Could not find i18n context for i18n op'); } currentOps = {i18nBlock: op, i18nContext: i18nContexts.get(op.context)!}; break; case ir.OpKind.I18nEnd: currentOps = null; break; case ir.OpKind.ElementStart: // For elements with i18n placeholders, record its slot value in the params map under the // corresponding tag start placeholder. if (op.i18nPlaceholder !== undefined) { if (currentOps === null) { throw Error('i18n tag placeholder should only occur inside an i18n block'); } recordElementStart( op, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective, ); // If there is a separate close tag placeholder for this element, save the pending // structural directive so we can pass it to the closing tag as well. if (pendingStructuralDirective && op.i18nPlaceholder.closeName) { pendingStructuralDirectiveCloses.set(op.xref, pendingStructuralDirective); } // Clear out the pending structural directive now that its been accounted for. pendingStructuralDirective = undefined; } break; case ir.OpKind.ElementEnd: // For elements with i18n placeholders, record its slot value in the params map under the // corresponding tag close placeholder. const startOp = elements.get(op.xref); if (startOp && startOp.i18nPlaceholder !== undefined) { if (currentOps === null) { throw Error( 'AssertionError: i18n tag placeholder should only occur inside an i18n block', ); } recordElementClose( startOp, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirectiveCloses.get(op.xref), ); // Clear out the pending structural directive close that was accounted for. pendingStructuralDirectiveCloses.delete(op.xref); } break; case ir.OpKind.Projection: // For content projections with i18n placeholders, record its slot value in the params map // under the corresponding tag start and close placeholders. if (op.i18nPlaceholder !== undefined) { if (currentOps === null) { throw Error('i18n tag placeholder should only occur inside an i18n block'); } recordElementStart( op, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective, ); recordElementClose( op, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective, ); // Clear out the pending structural directive now that its been accounted for. pendingStructuralDirective = undefined; } break; case ir.OpKind.Template: const view = job.views.get(op.xref)!; if (op.i18nPlaceholder === undefined) { // If there is no i18n placeholder, just recurse into the view in case it contains i18n // blocks. resolvePlaceholdersForView(job, view, i18nContexts, elements); } else { if (currentOps === null) { throw Error('i18n tag placeholder should only occur inside an i18n block'); } if (op.templateKind === ir.TemplateKind.Structural) { // If this is a structural directive template, don't record anything yet. Instead pass // the current template as a pending structural directive to be recorded when we find // the element, content, or template it belongs to. This allows us to create combined // values that represent, e.g. the start of a template and element at the same time. resolvePlaceholdersForView(job, view, i18nContexts, elements, op); } else { // If this is some other kind of template, we can record its start, recurse into its // view, and then record its end. recordTemplateStart( job, view, op.handle.slot!, op.i18nPlaceholder, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective, ); resolvePlaceholdersForView(job, view, i18nContexts, elements); recordTemplateClose( job, view, op.handle.slot!, op.i18nPlaceholder, currentOps!.i18nContext, currentOps!.i18nBlock, pendingStructuralDirective, ); pendingStructuralDirective = undefined; } } break; case ir.OpKind.RepeaterCreate: if (pendingStructuralDirective !== undefined) { throw Error('AssertionError: Unexpected structural directive associated with @for block'); } // RepeaterCreate has 3 slots: the first is for the op itself, the second is for the @for // template and the (optional) third is for the @empty template. const forSlot = op.handle.slot! + 1; const forView = job.views.get(op.xref)!; // First record all of the placeholders for the @for template. if (op.i18nPlaceholder === undefined) { // If there is no i18n placeholder, just recurse into the view in case it contains i18n // blocks. resolvePlaceholdersForView(job, forView, i18nContexts, elements); } else { if (currentOps === null) { throw Error('i18n tag placeholder should only occur inside an i18n block'); } recordTemplateStart( job, forView, forSlot, op.i18nPlaceholder, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective, ); resolvePlaceholdersForView(job, forView, i18nContexts, elements); recordTemplateClose( job, forView, forSlot, op.i18nPlaceholder, currentOps!.i18nContext, currentOps!.i18nBlock, pendingStructuralDirective, ); pendingStructuralDirective = undefined; } // Then if there's an @empty template, add its placeholders as well. if (op.emptyView !== null) { // RepeaterCreate has 3 slots: the first is for the op itself, the second is for the @for // template and the (optional) third is for the @empty template. const emptySlot = op.handle.slot! + 2; const emptyView = job.views.get(op.emptyView!)!; if (op.emptyI18nPlaceholder === undefined) { // If there is no i18n placeholder, just recurse into the view in case it contains i18n // blocks. resolvePlaceholdersForView(job, emptyView, i18nContexts, elements); } else { if (currentOps === null) { throw Error('i18n tag placeholder should only occur inside an i18n block'); } recordTemplateStart( job, emptyView, emptySlot, op.emptyI18nPlaceholder, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective, ); resolvePlaceholdersForView(job, emptyView, i18nContexts, elements); recordTemplateClose( job, emptyView, emptySlot, op.emptyI18nPlaceholder, currentOps!.i18nContext, currentOps!.i18nBlock, pendingStructuralDirective, ); pendingStructuralDirective = undefined; } } break; } } } /** * Records an i18n param value for the start of an element. */
{ "end_byte": 9856, "start_byte": 1156, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/resolve_i18n_element_placeholders.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/resolve_i18n_element_placeholders.ts_9857_15541
function recordElementStart( op: ir.ElementStartOp | ir.ProjectionOp, i18nContext: ir.I18nContextOp, i18nBlock: ir.I18nStartOp, structuralDirective?: ir.TemplateOp, ) { const {startName, closeName} = op.i18nPlaceholder!; let flags = ir.I18nParamValueFlags.ElementTag | ir.I18nParamValueFlags.OpenTag; let value: ir.I18nParamValue['value'] = op.handle.slot!; // If the element is associated with a structural directive, start it as well. if (structuralDirective !== undefined) { flags |= ir.I18nParamValueFlags.TemplateTag; value = {element: value, template: structuralDirective.handle.slot!}; } // For self-closing tags, there is no close tag placeholder. Instead, the start tag // placeholder accounts for the start and close of the element. if (!closeName) { flags |= ir.I18nParamValueFlags.CloseTag; } addParam(i18nContext.params, startName, value, i18nBlock.subTemplateIndex, flags); } /** * Records an i18n param value for the closing of an element. */ function recordElementClose( op: ir.ElementStartOp | ir.ProjectionOp, i18nContext: ir.I18nContextOp, i18nBlock: ir.I18nStartOp, structuralDirective?: ir.TemplateOp, ) { const {closeName} = op.i18nPlaceholder!; // Self-closing tags don't have a closing tag placeholder, instead the element closing is // recorded via an additional flag on the element start value. if (closeName) { let flags = ir.I18nParamValueFlags.ElementTag | ir.I18nParamValueFlags.CloseTag; let value: ir.I18nParamValue['value'] = op.handle.slot!; // If the element is associated with a structural directive, close it as well. if (structuralDirective !== undefined) { flags |= ir.I18nParamValueFlags.TemplateTag; value = {element: value, template: structuralDirective.handle.slot!}; } addParam(i18nContext.params, closeName, value, i18nBlock.subTemplateIndex, flags); } } /** * Records an i18n param value for the start of a template. */ function recordTemplateStart( job: ComponentCompilationJob, view: ViewCompilationUnit, slot: number, i18nPlaceholder: i18n.TagPlaceholder | i18n.BlockPlaceholder, i18nContext: ir.I18nContextOp, i18nBlock: ir.I18nStartOp, structuralDirective?: ir.TemplateOp, ) { let {startName, closeName} = i18nPlaceholder; let flags = ir.I18nParamValueFlags.TemplateTag | ir.I18nParamValueFlags.OpenTag; // For self-closing tags, there is no close tag placeholder. Instead, the start tag // placeholder accounts for the start and close of the element. if (!closeName) { flags |= ir.I18nParamValueFlags.CloseTag; } // If the template is associated with a structural directive, record the structural directive's // start first. Since this template must be in the structural directive's view, we can just // directly use the current i18n block's sub-template index. if (structuralDirective !== undefined) { addParam( i18nContext.params, startName, structuralDirective.handle.slot!, i18nBlock.subTemplateIndex, flags, ); } // Record the start of the template. For the sub-template index, pass the index for the template's // view, rather than the current i18n block's index. addParam( i18nContext.params, startName, slot, getSubTemplateIndexForTemplateTag(job, i18nBlock, view), flags, ); } /** * Records an i18n param value for the closing of a template. */ function recordTemplateClose( job: ComponentCompilationJob, view: ViewCompilationUnit, slot: number, i18nPlaceholder: i18n.TagPlaceholder | i18n.BlockPlaceholder, i18nContext: ir.I18nContextOp, i18nBlock: ir.I18nStartOp, structuralDirective?: ir.TemplateOp, ) { const {closeName} = i18nPlaceholder; const flags = ir.I18nParamValueFlags.TemplateTag | ir.I18nParamValueFlags.CloseTag; // Self-closing tags don't have a closing tag placeholder, instead the template's closing is // recorded via an additional flag on the template start value. if (closeName) { // Record the closing of the template. For the sub-template index, pass the index for the // template's view, rather than the current i18n block's index. addParam( i18nContext.params, closeName, slot, getSubTemplateIndexForTemplateTag(job, i18nBlock, view), flags, ); // If the template is associated with a structural directive, record the structural directive's // closing after. Since this template must be in the structural directive's view, we can just // directly use the current i18n block's sub-template index. if (structuralDirective !== undefined) { addParam( i18nContext.params, closeName, structuralDirective.handle.slot!, i18nBlock.subTemplateIndex, flags, ); } } } /** * Get the subTemplateIndex for the given template op. For template ops, use the subTemplateIndex of * the child i18n block inside the template. */ function getSubTemplateIndexForTemplateTag( job: ComponentCompilationJob, i18nOp: ir.I18nStartOp, view: ViewCompilationUnit, ): number | null { for (const childOp of view.create) { if (childOp.kind === ir.OpKind.I18nStart) { return childOp.subTemplateIndex; } } return i18nOp.subTemplateIndex; } /** * Add a param value to the given params map. */ function addParam( params: Map<string, ir.I18nParamValue[]>, placeholder: string, value: string | number | {element: number; template: number}, subTemplateIndex: number | null, flags: ir.I18nParamValueFlags, ) { const values = params.get(placeholder) ?? []; values.push({value, subTemplateIndex, flags}); params.set(placeholder, values); }
{ "end_byte": 15541, "start_byte": 9857, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/resolve_i18n_element_placeholders.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/create_i18n_contexts.ts_0_4508
/** * @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 ir from '../../ir'; import {CompilationJob} from '../compilation'; /** * Create one helper context op per i18n block (including generate descending blocks). * * Also, if an ICU exists inside an i18n block that also contains other localizable content (such as * string), create an additional helper context op for the ICU. * * These context ops are later used for generating i18n messages. (Although we generate at least one * context op per nested view, we will collect them up the tree later, to generate a top-level * message.) */ export function createI18nContexts(job: CompilationJob) { // Create i18n context ops for i18n attrs. const attrContextByMessage = new Map<i18n.Message, ir.XrefId>(); for (const unit of job.units) { for (const op of unit.ops()) { switch (op.kind) { case ir.OpKind.Binding: case ir.OpKind.Property: case ir.OpKind.Attribute: case ir.OpKind.ExtractedAttribute: if (op.i18nMessage === null) { continue; } if (!attrContextByMessage.has(op.i18nMessage)) { const i18nContext = ir.createI18nContextOp( ir.I18nContextKind.Attr, job.allocateXrefId(), null, op.i18nMessage, null!, ); unit.create.push(i18nContext); attrContextByMessage.set(op.i18nMessage, i18nContext.xref); } op.i18nContext = attrContextByMessage.get(op.i18nMessage)!; break; } } } // Create i18n context ops for root i18n blocks. const blockContextByI18nBlock = new Map<ir.XrefId, ir.I18nContextOp>(); for (const unit of job.units) { for (const op of unit.create) { switch (op.kind) { case ir.OpKind.I18nStart: if (op.xref === op.root) { const contextOp = ir.createI18nContextOp( ir.I18nContextKind.RootI18n, job.allocateXrefId(), op.xref, op.message, null!, ); unit.create.push(contextOp); op.context = contextOp.xref; blockContextByI18nBlock.set(op.xref, contextOp); } break; } } } // Assign i18n contexts for child i18n blocks. These don't need their own conext, instead they // should inherit from their root i18n block. for (const unit of job.units) { for (const op of unit.create) { if (op.kind === ir.OpKind.I18nStart && op.xref !== op.root) { const rootContext = blockContextByI18nBlock.get(op.root); if (rootContext === undefined) { throw Error('AssertionError: Root i18n block i18n context should have been created.'); } op.context = rootContext.xref; blockContextByI18nBlock.set(op.xref, rootContext); } } } // Create or assign i18n contexts for ICUs. let currentI18nOp: ir.I18nStartOp | null = null; for (const unit of job.units) { for (const op of unit.create) { switch (op.kind) { case ir.OpKind.I18nStart: currentI18nOp = op; break; case ir.OpKind.I18nEnd: currentI18nOp = null; break; case ir.OpKind.IcuStart: if (currentI18nOp === null) { throw Error('AssertionError: Unexpected ICU outside of an i18n block.'); } if (op.message.id !== currentI18nOp.message.id) { // This ICU is a sub-message inside its parent i18n block message. We need to give it // its own context. const contextOp = ir.createI18nContextOp( ir.I18nContextKind.Icu, job.allocateXrefId(), currentI18nOp.root, op.message, null!, ); unit.create.push(contextOp); op.context = contextOp.xref; } else { // This ICU is the only translatable content in its parent i18n block. We need to // convert the parent's context into an ICU context. op.context = currentI18nOp.context; blockContextByI18nBlock.get(currentI18nOp.xref)!.contextKind = ir.I18nContextKind.Icu; } break; } } } }
{ "end_byte": 4508, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/create_i18n_contexts.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/chaining.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 o from '../../../../output/output_ast'; import {Identifiers as R3} from '../../../../render3/r3_identifiers'; import * as ir from '../../ir'; import {CompilationJob} from '../compilation'; const CHAINABLE = new Set([ R3.attribute, R3.classProp, R3.element, R3.elementContainer, R3.elementContainerEnd, R3.elementContainerStart, R3.elementEnd, R3.elementStart, R3.hostProperty, R3.i18nExp, R3.listener, R3.listener, R3.property, R3.styleProp, R3.stylePropInterpolate1, R3.stylePropInterpolate2, R3.stylePropInterpolate3, R3.stylePropInterpolate4, R3.stylePropInterpolate5, R3.stylePropInterpolate6, R3.stylePropInterpolate7, R3.stylePropInterpolate8, R3.stylePropInterpolateV, R3.syntheticHostListener, R3.syntheticHostProperty, R3.templateCreate, R3.twoWayProperty, R3.twoWayListener, R3.declareLet, ]); /** * Chaining results in repeated call expressions, causing a deep AST of receiver expressions. To prevent running out of * stack depth the maximum number of chained instructions is limited to this threshold, which has been selected * arbitrarily. */ const MAX_CHAIN_LENGTH = 256; /** * Post-process a reified view compilation and convert sequential calls to chainable instructions * into chain calls. * * For example, two `elementStart` operations in sequence: * * ```typescript * elementStart(0, 'div'); * elementStart(1, 'span'); * ``` * * Can be called as a chain instead: * * ```typescript * elementStart(0, 'div')(1, 'span'); * ``` */ export function chain(job: CompilationJob): void { for (const unit of job.units) { chainOperationsInList(unit.create); chainOperationsInList(unit.update); } } function chainOperationsInList(opList: ir.OpList<ir.CreateOp | ir.UpdateOp>): void { let chain: Chain | null = null; for (const op of opList) { if (op.kind !== ir.OpKind.Statement || !(op.statement instanceof o.ExpressionStatement)) { // This type of statement isn't chainable. chain = null; continue; } if ( !(op.statement.expr instanceof o.InvokeFunctionExpr) || !(op.statement.expr.fn instanceof o.ExternalExpr) ) { // This is a statement, but not an instruction-type call, so not chainable. chain = null; continue; } const instruction = op.statement.expr.fn.value; if (!CHAINABLE.has(instruction)) { // This instruction isn't chainable. chain = null; continue; } // This instruction can be chained. It can either be added on to the previous chain (if // compatible) or it can be the start of a new chain. if (chain !== null && chain.instruction === instruction && chain.length < MAX_CHAIN_LENGTH) { // This instruction can be added onto the previous chain. const expression = chain.expression.callFn( op.statement.expr.args, op.statement.expr.sourceSpan, op.statement.expr.pure, ); chain.expression = expression; chain.op.statement = expression.toStmt(); chain.length++; ir.OpList.remove(op as ir.Op<ir.CreateOp | ir.UpdateOp>); } else { // Leave this instruction alone for now, but consider it the start of a new chain. chain = { op, instruction, expression: op.statement.expr, length: 1, }; } } } /** * Structure representing an in-progress chain. */ interface Chain { /** * The statement which holds the entire chain. */ op: ir.StatementOp<ir.CreateOp | ir.UpdateOp>; /** * The expression representing the whole current chained call. * * This should be the same as `op.statement.expression`, but is extracted here for convenience * since the `op` type doesn't capture the fact that `op.statement` is an `o.ExpressionStatement`. */ expression: o.Expression; /** * The instruction that is being chained. */ instruction: o.ExternalReference; /** * The number of instructions that have been collected into this chain. */ length: number; }
{ "end_byte": 4254, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/chaining.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/attribute_extraction.ts_0_7029
/** * @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 * as ir from '../../ir'; import {CompilationJobKind, type CompilationJob, type CompilationUnit} from '../compilation'; import {createOpXrefMap} from '../util/elements'; /** * Find all extractable attribute and binding ops, and create ExtractedAttributeOps for them. * In cases where no instruction needs to be generated for the attribute or binding, it is removed. */ export function extractAttributes(job: CompilationJob): void { for (const unit of job.units) { const elements = createOpXrefMap(unit); for (const op of unit.ops()) { switch (op.kind) { case ir.OpKind.Attribute: extractAttributeOp(unit, op, elements); break; case ir.OpKind.Property: if (!op.isAnimationTrigger) { let bindingKind: ir.BindingKind; if (op.i18nMessage !== null && op.templateKind === null) { // If the binding has an i18n context, it is an i18n attribute, and should have that // kind in the consts array. bindingKind = ir.BindingKind.I18n; } else if (op.isStructuralTemplateAttribute) { bindingKind = ir.BindingKind.Template; } else { bindingKind = ir.BindingKind.Property; } ir.OpList.insertBefore<ir.CreateOp>( // Deliberately null i18nMessage value ir.createExtractedAttributeOp( op.target, bindingKind, null, op.name, /* expression */ null, /* i18nContext */ null, /* i18nMessage */ null, op.securityContext, ), lookupElement(elements, op.target), ); } break; case ir.OpKind.TwoWayProperty: ir.OpList.insertBefore<ir.CreateOp>( ir.createExtractedAttributeOp( op.target, ir.BindingKind.TwoWayProperty, null, op.name, /* expression */ null, /* i18nContext */ null, /* i18nMessage */ null, op.securityContext, ), lookupElement(elements, op.target), ); break; case ir.OpKind.StyleProp: case ir.OpKind.ClassProp: // TODO: Can style or class bindings be i18n attributes? // The old compiler treated empty style bindings as regular bindings for the purpose of // directive matching. That behavior is incorrect, but we emulate it in compatibility // mode. if ( unit.job.compatibility === ir.CompatibilityMode.TemplateDefinitionBuilder && op.expression instanceof ir.EmptyExpr ) { ir.OpList.insertBefore<ir.CreateOp>( ir.createExtractedAttributeOp( op.target, ir.BindingKind.Property, null, op.name, /* expression */ null, /* i18nContext */ null, /* i18nMessage */ null, SecurityContext.STYLE, ), lookupElement(elements, op.target), ); } break; case ir.OpKind.Listener: if (!op.isAnimationListener) { const extractedAttributeOp = ir.createExtractedAttributeOp( op.target, ir.BindingKind.Property, null, op.name, /* expression */ null, /* i18nContext */ null, /* i18nMessage */ null, SecurityContext.NONE, ); if (job.kind === CompilationJobKind.Host) { if (job.compatibility) { // TemplateDefinitionBuilder does not extract listener bindings to the const array // (which is honestly pretty inconsistent). break; } // This attribute will apply to the enclosing host binding compilation unit, so order // doesn't matter. unit.create.push(extractedAttributeOp); } else { ir.OpList.insertBefore<ir.CreateOp>( extractedAttributeOp, lookupElement(elements, op.target), ); } } break; case ir.OpKind.TwoWayListener: // Two-way listeners aren't supported in host bindings. if (job.kind !== CompilationJobKind.Host) { const extractedAttributeOp = ir.createExtractedAttributeOp( op.target, ir.BindingKind.Property, null, op.name, /* expression */ null, /* i18nContext */ null, /* i18nMessage */ null, SecurityContext.NONE, ); ir.OpList.insertBefore<ir.CreateOp>( extractedAttributeOp, lookupElement(elements, op.target), ); } break; } } } } /** * Looks up an element in the given map by xref ID. */ function lookupElement( elements: Map<ir.XrefId, ir.ConsumesSlotOpTrait & ir.CreateOp>, xref: ir.XrefId, ): ir.ConsumesSlotOpTrait & ir.CreateOp { const el = elements.get(xref); if (el === undefined) { throw new Error('All attributes should have an element-like target.'); } return el; } /** * Extracts an attribute binding. */ function extractAttributeOp( unit: CompilationUnit, op: ir.AttributeOp, elements: Map<ir.XrefId, ir.ConsumesSlotOpTrait & ir.CreateOp>, ) { if (op.expression instanceof ir.Interpolation) { return; } let extractable = op.isTextAttribute || op.expression.isConstant(); if (unit.job.compatibility === ir.CompatibilityMode.TemplateDefinitionBuilder) { // TemplateDefinitionBuilder only extracts text attributes. It does not extract attriibute // bindings, even if they are constants. extractable &&= op.isTextAttribute; } if (extractable) { const extractedAttributeOp = ir.createExtractedAttributeOp( op.target, op.isStructuralTemplateAttribute ? ir.BindingKind.Template : ir.BindingKind.Attribute, op.namespace, op.name, op.expression, op.i18nContext, op.i18nMessage, op.securityContext, ); if (unit.job.kind === CompilationJobKind.Host) { // This attribute will apply to the enclosing host binding compilation unit, so order doesn't // matter. unit.create.push(extractedAttributeOp); } else { const ownerOp = lookupElement(elements, op.target); ir.OpList.insertBefore<ir.CreateOp>(extractedAttributeOp, ownerOp); } ir.OpList.remove<ir.UpdateOp>(op); } }
{ "end_byte": 7029, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/attribute_extraction.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/any_cast.ts_0_1015
/** * @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 * as ir from '../../ir'; import {CompilationJob} from '../compilation'; /** * Find any function calls to `$any`, excluding `this.$any`, and delete them, since they have no * runtime effects. */ export function deleteAnyCasts(job: CompilationJob): void { for (const unit of job.units) { for (const op of unit.ops()) { ir.transformExpressionsInOp(op, removeAnys, ir.VisitorContextFlag.None); } } } function removeAnys(e: o.Expression): o.Expression { if ( e instanceof o.InvokeFunctionExpr && e.fn instanceof ir.LexicalReadExpr && e.fn.name === '$any' ) { if (e.args.length !== 1) { throw new Error('The $any builtin function expects exactly one argument.'); } return e.args[0]; } return e; }
{ "end_byte": 1015, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/any_cast.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/remove_i18n_contexts.ts_0_754
/** * @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 ir from '../../ir'; import {CompilationJob} from '../compilation'; /** * Remove the i18n context ops after they are no longer needed, and null out references to them to * be safe. */ export function removeI18nContexts(job: CompilationJob) { for (const unit of job.units) { for (const op of unit.create) { switch (op.kind) { case ir.OpKind.I18nContext: ir.OpList.remove<ir.CreateOp>(op); break; case ir.OpKind.I18nStart: op.context = null; break; } } } }
{ "end_byte": 754, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/remove_i18n_contexts.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/defer_resolve_targets.ts_0_4682
/** * @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 ir from '../../ir'; import type {ComponentCompilationJob, ViewCompilationUnit} from '../compilation'; /** * Some `defer` conditions can reference other elements in the template, using their local reference * names. However, the semantics are quite different from the normal local reference system: in * particular, we need to look at local reference names in enclosing views. This phase resolves * all such references to actual xrefs. */ export function resolveDeferTargetNames(job: ComponentCompilationJob): void { const scopes = new Map<ir.XrefId, Scope>(); function getScopeForView(view: ViewCompilationUnit): Scope { if (scopes.has(view.xref)) { return scopes.get(view.xref)!; } const scope = new Scope(); for (const op of view.create) { // add everything that can be referenced. if (!ir.isElementOrContainerOp(op) || op.localRefs === null) { continue; } if (!Array.isArray(op.localRefs)) { throw new Error( 'LocalRefs were already processed, but were needed to resolve defer targets.', ); } for (const ref of op.localRefs) { if (ref.target !== '') { continue; } scope.targets.set(ref.name, {xref: op.xref, slot: op.handle}); } } scopes.set(view.xref, scope); return scope; } function resolveTrigger( deferOwnerView: ViewCompilationUnit, op: ir.DeferOnOp, placeholderView: ir.XrefId | null, ): void { switch (op.trigger.kind) { case ir.DeferTriggerKind.Idle: case ir.DeferTriggerKind.Never: case ir.DeferTriggerKind.Immediate: case ir.DeferTriggerKind.Timer: return; case ir.DeferTriggerKind.Hover: case ir.DeferTriggerKind.Interaction: case ir.DeferTriggerKind.Viewport: if (op.trigger.targetName === null) { // A `null` target name indicates we should default to the first element in the // placeholder block. if (placeholderView === null) { throw new Error('defer on trigger with no target name must have a placeholder block'); } const placeholder = job.views.get(placeholderView); if (placeholder == undefined) { throw new Error('AssertionError: could not find placeholder view for defer on trigger'); } for (const placeholderOp of placeholder.create) { if ( ir.hasConsumesSlotTrait(placeholderOp) && (ir.isElementOrContainerOp(placeholderOp) || placeholderOp.kind === ir.OpKind.Projection) ) { op.trigger.targetXref = placeholderOp.xref; op.trigger.targetView = placeholderView; op.trigger.targetSlotViewSteps = -1; op.trigger.targetSlot = placeholderOp.handle; return; } } return; } let view: ViewCompilationUnit | null = placeholderView !== null ? job.views.get(placeholderView)! : deferOwnerView; let step = placeholderView !== null ? -1 : 0; while (view !== null) { const scope = getScopeForView(view); if (scope.targets.has(op.trigger.targetName)) { const {xref, slot} = scope.targets.get(op.trigger.targetName)!; op.trigger.targetXref = xref; op.trigger.targetView = view.xref; op.trigger.targetSlotViewSteps = step; op.trigger.targetSlot = slot; return; } view = view.parent !== null ? job.views.get(view.parent)! : null; step++; } break; default: throw new Error(`Trigger kind ${(op.trigger as any).kind} not handled`); } } // Find the defer ops, and assign the data about their targets. for (const unit of job.units) { const defers = new Map<ir.XrefId, ir.DeferOp>(); for (const op of unit.create) { switch (op.kind) { case ir.OpKind.Defer: defers.set(op.xref, op); break; case ir.OpKind.DeferOn: const deferOp = defers.get(op.defer)!; resolveTrigger( unit, op, op.modifier === ir.DeferOpModifierKind.HYDRATE ? deferOp.mainView : deferOp.placeholderView, ); break; } } } } class Scope { targets = new Map<string, {xref: ir.XrefId; slot: ir.SlotHandle}>(); }
{ "end_byte": 4682, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/defer_resolve_targets.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/deduplicate_text_bindings.ts_0_1680
/** * @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 ir from '../../ir'; import type {CompilationJob} from '../compilation'; /** * Deduplicate text bindings, e.g. <div class="cls1" class="cls2"> */ export function deduplicateTextBindings(job: CompilationJob): void { const seen = new Map<ir.XrefId, Set<string>>(); for (const unit of job.units) { for (const op of unit.update.reversed()) { if (op.kind === ir.OpKind.Binding && op.isTextAttribute) { const seenForElement = seen.get(op.target) || new Set(); if (seenForElement.has(op.name)) { if (job.compatibility === ir.CompatibilityMode.TemplateDefinitionBuilder) { // For most duplicated attributes, TemplateDefinitionBuilder lists all of the values in // the consts array. However, for style and class attributes it only keeps the last one. // We replicate that behavior here since it has actual consequences for apps with // duplicate class or style attrs. if (op.name === 'style' || op.name === 'class') { ir.OpList.remove<ir.UpdateOp>(op); } } else { // TODO: Determine the correct behavior. It would probably make sense to merge multiple // style and class attributes. Alternatively we could just throw an error, as HTML // doesn't permit duplicate attributes. } } seenForElement.add(op.name); seen.set(op.target, seenForElement); } } } }
{ "end_byte": 1680, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/deduplicate_text_bindings.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/remove_unused_i18n_attrs.ts_0_1071
/** * @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 ir from '../../ir'; import {CompilationJob} from '../compilation'; /** * i18nAttributes ops will be generated for each i18n attribute. However, not all i18n attribues * will contain dynamic content, and so some of these i18nAttributes ops may be unnecessary. */ export function removeUnusedI18nAttributesOps(job: CompilationJob) { for (const unit of job.units) { const ownersWithI18nExpressions = new Set<ir.XrefId>(); for (const op of unit.update) { switch (op.kind) { case ir.OpKind.I18nExpression: ownersWithI18nExpressions.add(op.i18nOwner); } } for (const op of unit.create) { switch (op.kind) { case ir.OpKind.I18nAttributes: if (ownersWithI18nExpressions.has(op.xref)) { continue; } ir.OpList.remove<ir.CreateOp>(op); } } } }
{ "end_byte": 1071, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/remove_unused_i18n_attrs.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/pure_function_extraction.ts_0_2179
/** * @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 {GenericKeyFn, SharedConstantDefinition} from '../../../../constant_pool'; import * as o from '../../../../output/output_ast'; import * as ir from '../../ir'; import type {CompilationJob} from '../compilation'; export function extractPureFunctions(job: CompilationJob): void { for (const view of job.units) { for (const op of view.ops()) { ir.visitExpressionsInOp(op, (expr) => { if (!(expr instanceof ir.PureFunctionExpr) || expr.body === null) { return; } const constantDef = new PureFunctionConstant(expr.args.length); expr.fn = job.pool.getSharedConstant(constantDef, expr.body); expr.body = null; }); } } } class PureFunctionConstant extends GenericKeyFn implements SharedConstantDefinition { constructor(private numArgs: number) { super(); } override keyOf(expr: o.Expression): string { if (expr instanceof ir.PureFunctionParameterExpr) { return `param(${expr.index})`; } else { return super.keyOf(expr); } } // TODO: Use the new pool method `getSharedFunctionReference` toSharedConstantDeclaration(declName: string, keyExpr: o.Expression): o.Statement { const fnParams: o.FnParam[] = []; for (let idx = 0; idx < this.numArgs; idx++) { fnParams.push(new o.FnParam('a' + idx)); } // We will never visit `ir.PureFunctionParameterExpr`s that don't belong to us, because this // transform runs inside another visitor which will visit nested pure functions before this one. const returnExpr = ir.transformExpressionsInExpression( keyExpr, (expr) => { if (!(expr instanceof ir.PureFunctionParameterExpr)) { return expr; } return o.variable('a' + expr.index); }, ir.VisitorContextFlag.None, ); return new o.DeclareVarStmt( declName, new o.ArrowFunctionExpr(fnParams, returnExpr), undefined, o.StmtModifier.Final, ); } }
{ "end_byte": 2179, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/pure_function_extraction.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/resolve_dollar_event.ts_0_1428
/** * @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 * as ir from '../../ir'; import type {CompilationJob} from '../compilation'; /** * Any variable inside a listener with the name `$event` will be transformed into a output lexical * read immediately, and does not participate in any of the normal logic for handling variables. */ export function resolveDollarEvent(job: CompilationJob): void { for (const unit of job.units) { transformDollarEvent(unit.create); transformDollarEvent(unit.update); } } function transformDollarEvent(ops: ir.OpList<ir.CreateOp> | ir.OpList<ir.UpdateOp>): void { for (const op of ops) { if (op.kind === ir.OpKind.Listener || op.kind === ir.OpKind.TwoWayListener) { ir.transformExpressionsInOp( op, (expr) => { if (expr instanceof ir.LexicalReadExpr && expr.name === '$event') { // Two-way listeners always consume `$event` so they omit this field. if (op.kind === ir.OpKind.Listener) { op.consumesDollarEvent = true; } return new o.ReadVarExpr(expr.name); } return expr; }, ir.VisitorContextFlag.InChildOperation, ); } } }
{ "end_byte": 1428, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/resolve_dollar_event.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/track_fn_optimization.ts_0_3888
/** * @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} from '../../../../render3/r3_identifiers'; import * as ir from '../../ir'; import type {CompilationJob} from '../compilation'; /** * `track` functions in `for` repeaters can sometimes be "optimized," i.e. transformed into inline * expressions, in lieu of an external function call. For example, tracking by `$index` can be be * optimized into an inline `trackByIndex` reference. This phase checks track expressions for * optimizable cases. */ export function optimizeTrackFns(job: CompilationJob): void { for (const unit of job.units) { for (const op of unit.create) { if (op.kind !== ir.OpKind.RepeaterCreate) { continue; } if (op.track instanceof o.ReadVarExpr && op.track.name === '$index') { // Top-level access of `$index` uses the built in `repeaterTrackByIndex`. op.trackByFn = o.importExpr(Identifiers.repeaterTrackByIndex); } else if (op.track instanceof o.ReadVarExpr && op.track.name === '$item') { // Top-level access of the item uses the built in `repeaterTrackByIdentity`. op.trackByFn = o.importExpr(Identifiers.repeaterTrackByIdentity); } else if (isTrackByFunctionCall(job.root.xref, op.track)) { // Mark the function as using the component instance to play it safe // since the method might be using `this` internally (see #53628). op.usesComponentInstance = true; // Top-level method calls in the form of `fn($index, item)` can be passed in directly. if (op.track.receiver.receiver.view === unit.xref) { // TODO: this may be wrong op.trackByFn = op.track.receiver; } else { // This is a plain method call, but not in the component's root view. // We need to get the component instance, and then call the method on it. op.trackByFn = o .importExpr(Identifiers.componentInstance) .callFn([]) .prop(op.track.receiver.name); // Because the context is not avaiable (without a special function), we don't want to // try to resolve it later. Let's get rid of it by overwriting the original track // expression (which won't be used anyway). op.track = op.trackByFn; } } else { // The track function could not be optimized. // Replace context reads with a special IR expression, since context reads in a track // function are emitted specially. op.track = ir.transformExpressionsInExpression( op.track, (expr) => { if (expr instanceof ir.ContextExpr) { op.usesComponentInstance = true; return new ir.TrackContextExpr(expr.view); } return expr; }, ir.VisitorContextFlag.None, ); } } } } function isTrackByFunctionCall( rootView: ir.XrefId, expr: o.Expression, ): expr is o.InvokeFunctionExpr & { receiver: o.ReadPropExpr & { receiver: ir.ContextExpr; }; } { if (!(expr instanceof o.InvokeFunctionExpr) || expr.args.length === 0 || expr.args.length > 2) { return false; } if ( !( expr.receiver instanceof o.ReadPropExpr && expr.receiver.receiver instanceof ir.ContextExpr ) || expr.receiver.receiver.view !== rootView ) { return false; } const [arg0, arg1] = expr.args; if (!(arg0 instanceof o.ReadVarExpr) || arg0.name !== '$index') { return false; } else if (expr.args.length === 1) { return true; } if (!(arg1 instanceof o.ReadVarExpr) || arg1.name !== '$item') { return false; } return true; }
{ "end_byte": 3888, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/track_fn_optimization.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/assign_i18n_slot_dependencies.ts_0_2344
/** * @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 ir from '../../ir'; import {CompilationJob} from '../compilation'; interface BlockState { blockXref: ir.XrefId; lastSlotConsumer: ir.XrefId; } /** * Updates i18n expression ops to target the last slot in their owning i18n block, and moves them * after the last update instruction that depends on that slot. */ export function assignI18nSlotDependencies(job: CompilationJob) { for (const unit of job.units) { // The first update op. let updateOp = unit.update.head; // I18n expressions currently being moved during the iteration. let i18nExpressionsInProgress: ir.I18nExpressionOp[] = []; // Non-null while we are iterating through an i18nStart/i18nEnd pair let state: BlockState | null = null; for (const createOp of unit.create) { if (createOp.kind === ir.OpKind.I18nStart) { state = { blockXref: createOp.xref, lastSlotConsumer: createOp.xref, }; } else if (createOp.kind === ir.OpKind.I18nEnd) { for (const op of i18nExpressionsInProgress) { op.target = state!.lastSlotConsumer; ir.OpList.insertBefore(op as ir.UpdateOp, updateOp!); } i18nExpressionsInProgress.length = 0; state = null; } if (ir.hasConsumesSlotTrait(createOp)) { if (state !== null) { state.lastSlotConsumer = createOp.xref; } while (true) { if (updateOp.next === null) { break; } if ( state !== null && updateOp.kind === ir.OpKind.I18nExpression && updateOp.usage === ir.I18nExpressionFor.I18nText && updateOp.i18nOwner === state.blockXref ) { const opToRemove = updateOp; updateOp = updateOp.next!; ir.OpList.remove<ir.UpdateOp>(opToRemove); i18nExpressionsInProgress.push(opToRemove); continue; } if (ir.hasDependsOnSlotContextTrait(updateOp) && updateOp.target !== createOp.xref) { break; } updateOp = updateOp.next!; } } } } }
{ "end_byte": 2344, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/assign_i18n_slot_dependencies.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/resolve_names.ts_0_5632
/** * @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 * as ir from '../../ir'; import {CompilationJob, CompilationUnit} from '../compilation'; /** * Resolves lexical references in views (`ir.LexicalReadExpr`) to either a target variable or to * property reads on the top-level component context. * * Also matches `ir.RestoreViewExpr` expressions with the variables of their corresponding saved * views. */ export function resolveNames(job: CompilationJob): void { for (const unit of job.units) { processLexicalScope(unit, unit.create, null); processLexicalScope(unit, unit.update, null); } } function processLexicalScope( unit: CompilationUnit, ops: ir.OpList<ir.CreateOp> | ir.OpList<ir.UpdateOp>, savedView: SavedView | null, ): void { // Maps names defined in the lexical scope of this template to the `ir.XrefId`s of the variable // declarations which represent those values. // // Since variables are generated in each view for the entire lexical scope (including any // identifiers from parent templates) only local variables need be considered here. const scope = new Map<string, ir.XrefId>(); // Symbols defined within the current scope. They take precedence over ones defined outside. const localDefinitions = new Map<string, ir.XrefId>(); // First, step through the operations list and: // 1) build up the `scope` mapping // 2) recurse into any listener functions for (const op of ops) { switch (op.kind) { case ir.OpKind.Variable: switch (op.variable.kind) { case ir.SemanticVariableKind.Identifier: if (op.variable.local) { if (localDefinitions.has(op.variable.identifier)) { continue; } localDefinitions.set(op.variable.identifier, op.xref); } else if (scope.has(op.variable.identifier)) { continue; } scope.set(op.variable.identifier, op.xref); break; case ir.SemanticVariableKind.Alias: // This variable represents some kind of identifier which can be used in the template. if (scope.has(op.variable.identifier)) { continue; } scope.set(op.variable.identifier, op.xref); break; case ir.SemanticVariableKind.SavedView: // This variable represents a snapshot of the current view context, and can be used to // restore that context within listener functions. savedView = { view: op.variable.view, variable: op.xref, }; break; } break; case ir.OpKind.Listener: case ir.OpKind.TwoWayListener: // Listener functions have separate variable declarations, so process them as a separate // lexical scope. processLexicalScope(unit, op.handlerOps, savedView); break; } } // Next, use the `scope` mapping to match `ir.LexicalReadExpr` with defined names in the lexical // scope. Also, look for `ir.RestoreViewExpr`s and match them with the snapshotted view context // variable. for (const op of ops) { if (op.kind == ir.OpKind.Listener || op.kind === ir.OpKind.TwoWayListener) { // Listeners were already processed above with their own scopes. continue; } ir.transformExpressionsInOp( op, (expr) => { if (expr instanceof ir.LexicalReadExpr) { // `expr` is a read of a name within the lexical scope of this view. // Either that name is defined within the current view, or it represents a property from the // main component context. if (localDefinitions.has(expr.name)) { return new ir.ReadVariableExpr(localDefinitions.get(expr.name)!); } else if (scope.has(expr.name)) { // This was a defined variable in the current scope. return new ir.ReadVariableExpr(scope.get(expr.name)!); } else { // Reading from the component context. return new o.ReadPropExpr(new ir.ContextExpr(unit.job.root.xref), expr.name); } } else if (expr instanceof ir.RestoreViewExpr && typeof expr.view === 'number') { // `ir.RestoreViewExpr` happens in listener functions and restores a saved view from the // parent creation list. We expect to find that we captured the `savedView` previously, and // that it matches the expected view to be restored. if (savedView === null || savedView.view !== expr.view) { throw new Error(`AssertionError: no saved view ${expr.view} from view ${unit.xref}`); } expr.view = new ir.ReadVariableExpr(savedView.variable); return expr; } else { return expr; } }, ir.VisitorContextFlag.None, ); } for (const op of ops) { ir.visitExpressionsInOp(op, (expr) => { if (expr instanceof ir.LexicalReadExpr) { throw new Error( `AssertionError: no lexical reads should remain, but found read of ${expr.name}`, ); } }); } } /** * Information about a `SavedView` variable. */ interface SavedView { /** * The view `ir.XrefId` which was saved into this variable. */ view: ir.XrefId; /** * The `ir.XrefId` of the variable into which the view was saved. */ variable: ir.XrefId; }
{ "end_byte": 5632, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/resolve_names.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/remove_empty_bindings.ts_0_891
/** * @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 ir from '../../ir'; import type {CompilationJob} from '../compilation'; /** * Binding with no content can be safely deleted. */ export function removeEmptyBindings(job: CompilationJob): void { for (const unit of job.units) { for (const op of unit.update) { switch (op.kind) { case ir.OpKind.Attribute: case ir.OpKind.Binding: case ir.OpKind.ClassProp: case ir.OpKind.ClassMap: case ir.OpKind.Property: case ir.OpKind.StyleProp: case ir.OpKind.StyleMap: if (op.expression instanceof ir.EmptyExpr) { ir.OpList.remove<ir.UpdateOp>(op); } break; } } } }
{ "end_byte": 891, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/remove_empty_bindings.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/const_collection.ts_0_8314
/** * @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 * as o from '../../../../output/output_ast'; import * as ir from '../../ir'; import { ComponentCompilationJob, HostBindingCompilationJob, type CompilationJob, } from '../compilation'; import {literalOrArrayLiteral} from '../conversion'; /** * Converts the semantic attributes of element-like operations (elements, templates) into constant * array expressions, and lifts them into the overall component `consts`. */ export function collectElementConsts(job: CompilationJob): void { // Collect all extracted attributes. const allElementAttributes = new Map<ir.XrefId, ElementAttributes>(); for (const unit of job.units) { for (const op of unit.create) { if (op.kind === ir.OpKind.ExtractedAttribute) { const attributes = allElementAttributes.get(op.target) || new ElementAttributes(job.compatibility); allElementAttributes.set(op.target, attributes); attributes.add(op.bindingKind, op.name, op.expression, op.namespace, op.trustedValueFn); ir.OpList.remove<ir.CreateOp>(op); } } } // Serialize the extracted attributes into the const array. if (job instanceof ComponentCompilationJob) { for (const unit of job.units) { for (const op of unit.create) { // TODO: Simplify and combine these cases. if (op.kind == ir.OpKind.Projection) { const attributes = allElementAttributes.get(op.xref); if (attributes !== undefined) { const attrArray = serializeAttributes(attributes); if (attrArray.entries.length > 0) { op.attributes = attrArray; } } } else if (ir.isElementOrContainerOp(op)) { op.attributes = getConstIndex(job, allElementAttributes, op.xref); // TODO(dylhunn): `@for` loops with `@empty` blocks need to be special-cased here, // because the slot consumer trait currently only supports one slot per consumer and we // need two. This should be revisited when making the refactors mentioned in: // https://github.com/angular/angular/pull/53620#discussion_r1430918822 if (op.kind === ir.OpKind.RepeaterCreate && op.emptyView !== null) { op.emptyAttributes = getConstIndex(job, allElementAttributes, op.emptyView); } } } } } else if (job instanceof HostBindingCompilationJob) { // TODO: If the host binding case further diverges, we may want to split it into its own // phase. for (const [xref, attributes] of allElementAttributes.entries()) { if (xref !== job.root.xref) { throw new Error( `An attribute would be const collected into the host binding's template function, but is not associated with the root xref.`, ); } const attrArray = serializeAttributes(attributes); if (attrArray.entries.length > 0) { job.root.attributes = attrArray; } } } } function getConstIndex( job: ComponentCompilationJob, allElementAttributes: Map<ir.XrefId, ElementAttributes>, xref: ir.XrefId, ): ir.ConstIndex | null { const attributes = allElementAttributes.get(xref); if (attributes !== undefined) { const attrArray = serializeAttributes(attributes); if (attrArray.entries.length > 0) { return job.addConst(attrArray); } } return null; } /** * Shared instance of an empty array to avoid unnecessary array allocations. */ const FLYWEIGHT_ARRAY: ReadonlyArray<o.Expression> = Object.freeze<o.Expression[]>([]); /** * Container for all of the various kinds of attributes which are applied on an element. */ class ElementAttributes { private known = new Map<ir.BindingKind, Set<string>>(); private byKind = new Map< // Property bindings are excluded here, because they need to be tracked in the same // array to maintain their order. They're tracked in the `propertyBindings` array. Exclude<ir.BindingKind, ir.BindingKind.Property | ir.BindingKind.TwoWayProperty>, o.Expression[] >(); private propertyBindings: o.Expression[] | null = null; projectAs: string | null = null; get attributes(): ReadonlyArray<o.Expression> { return this.byKind.get(ir.BindingKind.Attribute) ?? FLYWEIGHT_ARRAY; } get classes(): ReadonlyArray<o.Expression> { return this.byKind.get(ir.BindingKind.ClassName) ?? FLYWEIGHT_ARRAY; } get styles(): ReadonlyArray<o.Expression> { return this.byKind.get(ir.BindingKind.StyleProperty) ?? FLYWEIGHT_ARRAY; } get bindings(): ReadonlyArray<o.Expression> { return this.propertyBindings ?? FLYWEIGHT_ARRAY; } get template(): ReadonlyArray<o.Expression> { return this.byKind.get(ir.BindingKind.Template) ?? FLYWEIGHT_ARRAY; } get i18n(): ReadonlyArray<o.Expression> { return this.byKind.get(ir.BindingKind.I18n) ?? FLYWEIGHT_ARRAY; } constructor(private compatibility: ir.CompatibilityMode) {} private isKnown(kind: ir.BindingKind, name: string) { const nameToValue = this.known.get(kind) ?? new Set<string>(); this.known.set(kind, nameToValue); if (nameToValue.has(name)) { return true; } nameToValue.add(name); return false; } add( kind: ir.BindingKind, name: string, value: o.Expression | null, namespace: string | null, trustedValueFn: o.Expression | null, ): void { // TemplateDefinitionBuilder puts duplicate attribute, class, and style values into the consts // array. This seems inefficient, we can probably keep just the first one or the last value // (whichever actually gets applied when multiple values are listed for the same attribute). const allowDuplicates = this.compatibility === ir.CompatibilityMode.TemplateDefinitionBuilder && (kind === ir.BindingKind.Attribute || kind === ir.BindingKind.ClassName || kind === ir.BindingKind.StyleProperty); if (!allowDuplicates && this.isKnown(kind, name)) { return; } // TODO: Can this be its own phase if (name === 'ngProjectAs') { if ( value === null || !(value instanceof o.LiteralExpr) || value.value == null || typeof value.value?.toString() !== 'string' ) { throw Error('ngProjectAs must have a string literal value'); } this.projectAs = value.value.toString(); // TODO: TemplateDefinitionBuilder allows `ngProjectAs` to also be assigned as a literal // attribute. Is this sane? } const array = this.arrayFor(kind); array.push(...getAttributeNameLiterals(namespace, name)); if (kind === ir.BindingKind.Attribute || kind === ir.BindingKind.StyleProperty) { if (value === null) { throw Error('Attribute, i18n attribute, & style element attributes must have a value'); } if (trustedValueFn !== null) { if (!ir.isStringLiteral(value)) { throw Error('AssertionError: extracted attribute value should be string literal'); } array.push( o.taggedTemplate( trustedValueFn, new o.TemplateLiteral([new o.TemplateLiteralElement(value.value)], []), undefined, value.sourceSpan, ), ); } else { array.push(value); } } } private arrayFor(kind: ir.BindingKind): o.Expression[] { if (kind === ir.BindingKind.Property || kind === ir.BindingKind.TwoWayProperty) { this.propertyBindings ??= []; return this.propertyBindings; } else { if (!this.byKind.has(kind)) { this.byKind.set(kind, []); } return this.byKind.get(kind)!; } } } /** * Gets an array of literal expressions representing the attribute's namespaced name. */ function getAttributeNameLiterals(namespace: string | null, name: string): o.LiteralExpr[] { const nameLiteral = o.literal(name); if (namespace) { return [o.literal(core.AttributeMarker.NamespaceURI), o.literal(namespace), nameLiteral]; } return [nameLiteral]; } /** * Serializes an ElementAttributes object into an array expression. */
{ "end_byte": 8314, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/const_collection.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/const_collection.ts_8315_9459
function serializeAttributes({ attributes, bindings, classes, i18n, projectAs, styles, template, }: ElementAttributes): o.LiteralArrayExpr { const attrArray = [...attributes]; if (projectAs !== null) { // Parse the attribute value into a CssSelectorList. Note that we only take the // first selector, because we don't support multiple selectors in ngProjectAs. const parsedR3Selector = core.parseSelectorToR3Selector(projectAs)[0]; attrArray.push( o.literal(core.AttributeMarker.ProjectAs), literalOrArrayLiteral(parsedR3Selector), ); } if (classes.length > 0) { attrArray.push(o.literal(core.AttributeMarker.Classes), ...classes); } if (styles.length > 0) { attrArray.push(o.literal(core.AttributeMarker.Styles), ...styles); } if (bindings.length > 0) { attrArray.push(o.literal(core.AttributeMarker.Bindings), ...bindings); } if (template.length > 0) { attrArray.push(o.literal(core.AttributeMarker.Template), ...template); } if (i18n.length > 0) { attrArray.push(o.literal(core.AttributeMarker.I18n), ...i18n); } return o.literalArr(attrArray); }
{ "end_byte": 9459, "start_byte": 8315, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/const_collection.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/style_binding_specialization.ts_0_1767
/** * @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 ir from '../../ir'; import type {CompilationJob} from '../compilation'; /** * Transforms special-case bindings with 'style' or 'class' in their names. Must run before the * main binding specialization pass. */ export function specializeStyleBindings(job: CompilationJob): void { for (const unit of job.units) { for (const op of unit.update) { if (op.kind !== ir.OpKind.Binding) { continue; } switch (op.bindingKind) { case ir.BindingKind.ClassName: if (op.expression instanceof ir.Interpolation) { throw new Error(`Unexpected interpolation in ClassName binding`); } ir.OpList.replace<ir.UpdateOp>( op, ir.createClassPropOp(op.target, op.name, op.expression, op.sourceSpan), ); break; case ir.BindingKind.StyleProperty: ir.OpList.replace<ir.UpdateOp>( op, ir.createStylePropOp(op.target, op.name, op.expression, op.unit, op.sourceSpan), ); break; case ir.BindingKind.Property: case ir.BindingKind.Template: if (op.name === 'style') { ir.OpList.replace<ir.UpdateOp>( op, ir.createStyleMapOp(op.target, op.expression, op.sourceSpan), ); } else if (op.name === 'class') { ir.OpList.replace<ir.UpdateOp>( op, ir.createClassMapOp(op.target, op.expression, op.sourceSpan), ); } break; } } } }
{ "end_byte": 1767, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/style_binding_specialization.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/next_context_merging.ts_0_2867
/** * @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 * as ir from '../../ir'; import type {CompilationJob} from '../compilation'; /** * Merges logically sequential `NextContextExpr` operations. * * `NextContextExpr` can be referenced repeatedly, "popping" the runtime's context stack each time. * When two such expressions appear back-to-back, it's possible to merge them together into a single * `NextContextExpr` that steps multiple contexts. This merging is possible if all conditions are * met: * * * The result of the `NextContextExpr` that's folded into the subsequent one is not stored (that * is, the call is purely side-effectful). * * No operations in between them uses the implicit context. */ export function mergeNextContextExpressions(job: CompilationJob): void { for (const unit of job.units) { for (const op of unit.create) { if (op.kind === ir.OpKind.Listener || op.kind === ir.OpKind.TwoWayListener) { mergeNextContextsInOps(op.handlerOps); } } mergeNextContextsInOps(unit.update); } } function mergeNextContextsInOps(ops: ir.OpList<ir.UpdateOp>): void { for (const op of ops) { // Look for a candidate operation to maybe merge. if ( op.kind !== ir.OpKind.Statement || !(op.statement instanceof o.ExpressionStatement) || !(op.statement.expr instanceof ir.NextContextExpr) ) { continue; } const mergeSteps = op.statement.expr.steps; // Try to merge this `ir.NextContextExpr`. let tryToMerge = true; for ( let candidate = op.next!; candidate.kind !== ir.OpKind.ListEnd && tryToMerge; candidate = candidate.next! ) { ir.visitExpressionsInOp(candidate, (expr, flags) => { if (!ir.isIrExpression(expr)) { return expr; } if (!tryToMerge) { // Either we've already merged, or failed to merge. return; } if (flags & ir.VisitorContextFlag.InChildOperation) { // We cannot merge into child operations. return; } switch (expr.kind) { case ir.ExpressionKind.NextContext: // Merge the previous `ir.NextContextExpr` into this one. expr.steps += mergeSteps; ir.OpList.remove(op as ir.UpdateOp); tryToMerge = false; break; case ir.ExpressionKind.GetCurrentView: case ir.ExpressionKind.Reference: case ir.ExpressionKind.ContextLetReference: // Can't merge past a dependency on the context. tryToMerge = false; break; } return; }); } } }
{ "end_byte": 2867, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/next_context_merging.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/resolve_defer_deps_fns.ts_0_1181
/** * @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 ir from '../../ir'; import {ComponentCompilationJob} from '../compilation'; /** * Resolve the dependency function of a deferred block. */ export function resolveDeferDepsFns(job: ComponentCompilationJob): void { for (const unit of job.units) { for (const op of unit.create) { if (op.kind === ir.OpKind.Defer) { if (op.resolverFn !== null) { continue; } if (op.ownResolverFn !== null) { if (op.handle.slot === null) { throw new Error( 'AssertionError: slot must be assigned before extracting defer deps functions', ); } const fullPathName = unit.fnName?.replace('_Template', ''); op.resolverFn = job.pool.getSharedFunctionReference( op.ownResolverFn, `${fullPathName}_Defer_${op.handle.slot}_DepsFn`, /* Don't use unique names for TDB compatibility */ false, ); } } } } }
{ "end_byte": 1181, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/resolve_defer_deps_fns.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/has_const_expression_collection.ts_0_1065
/** * @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 * as ir from '../../ir'; import type {ComponentCompilationJob} from '../compilation'; /** * `ir.ConstCollectedExpr` may be present in any IR expression. This means that expression needs to * be lifted into the component const array, and replaced with a reference to the const array at its * * usage site. This phase walks the IR and performs this transformation. */ export function collectConstExpressions(job: ComponentCompilationJob): void { for (const unit of job.units) { for (const op of unit.ops()) { ir.transformExpressionsInOp( op, (expr) => { if (!(expr instanceof ir.ConstCollectedExpr)) { return expr; } return o.literal(job.addConst(expr.expr)); }, ir.VisitorContextFlag.None, ); } } }
{ "end_byte": 1065, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/has_const_expression_collection.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/var_counting.ts_0_6208
/** * @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 ir from '../../ir'; import {CompilationJob, ComponentCompilationJob} from '../compilation'; /** * Counts the number of variable slots used within each view, and stores that on the view itself, as * well as propagates it to the `ir.TemplateOp` for embedded views. */ export function countVariables(job: CompilationJob): void { // First, count the vars used in each view, and update the view-level counter. for (const unit of job.units) { let varCount = 0; // Count variables on top-level ops first. Don't explore nested expressions just yet. for (const op of unit.ops()) { if (ir.hasConsumesVarsTrait(op)) { varCount += varsUsedByOp(op); } } // Count variables on expressions inside ops. We do this later because some of these expressions // might be conditional (e.g. `pipeBinding` inside of a ternary), and we don't want to interfere // with indices for top-level binding slots (e.g. `property`). for (const op of unit.ops()) { ir.visitExpressionsInOp(op, (expr) => { if (!ir.isIrExpression(expr)) { return; } // TemplateDefinitionBuilder assigns variable offsets for everything but pure functions // first, and then assigns offsets to pure functions lazily. We emulate that behavior by // assigning offsets in two passes instead of one, only in compatibility mode. if ( job.compatibility === ir.CompatibilityMode.TemplateDefinitionBuilder && expr instanceof ir.PureFunctionExpr ) { return; } // Some expressions require knowledge of the number of variable slots consumed. if (ir.hasUsesVarOffsetTrait(expr)) { expr.varOffset = varCount; } if (ir.hasConsumesVarsTrait(expr)) { varCount += varsUsedByIrExpression(expr); } }); } // Compatibility mode pass for pure function offsets (as explained above). if (job.compatibility === ir.CompatibilityMode.TemplateDefinitionBuilder) { for (const op of unit.ops()) { ir.visitExpressionsInOp(op, (expr) => { if (!ir.isIrExpression(expr) || !(expr instanceof ir.PureFunctionExpr)) { return; } // Some expressions require knowledge of the number of variable slots consumed. if (ir.hasUsesVarOffsetTrait(expr)) { expr.varOffset = varCount; } if (ir.hasConsumesVarsTrait(expr)) { varCount += varsUsedByIrExpression(expr); } }); } } unit.vars = varCount; } if (job instanceof ComponentCompilationJob) { // Add var counts for each view to the `ir.TemplateOp` which declares that view (if the view is // an embedded view). for (const unit of job.units) { for (const op of unit.create) { if (op.kind !== ir.OpKind.Template && op.kind !== ir.OpKind.RepeaterCreate) { continue; } const childView = job.views.get(op.xref)!; op.vars = childView.vars; // TODO: currently we handle the vars for the RepeaterCreate empty template in the reify // phase. We should handle that here instead. } } } } /** * Different operations that implement `ir.UsesVarsTrait` use different numbers of variables, so * count the variables used by any particular `op`. */ function varsUsedByOp(op: (ir.CreateOp | ir.UpdateOp) & ir.ConsumesVarsTrait): number { let slots: number; switch (op.kind) { case ir.OpKind.Property: case ir.OpKind.HostProperty: case ir.OpKind.Attribute: // All of these bindings use 1 variable slot, plus 1 slot for every interpolated expression, // if any. slots = 1; if (op.expression instanceof ir.Interpolation && !isSingletonInterpolation(op.expression)) { slots += op.expression.expressions.length; } return slots; case ir.OpKind.TwoWayProperty: // Two-way properties can only have expressions so they only need one variable slot. return 1; case ir.OpKind.StyleProp: case ir.OpKind.ClassProp: case ir.OpKind.StyleMap: case ir.OpKind.ClassMap: // Style & class bindings use 2 variable slots, plus 1 slot for every interpolated expression, // if any. slots = 2; if (op.expression instanceof ir.Interpolation) { slots += op.expression.expressions.length; } return slots; case ir.OpKind.InterpolateText: // `ir.InterpolateTextOp`s use a variable slot for each dynamic expression. return op.interpolation.expressions.length; case ir.OpKind.I18nExpression: case ir.OpKind.Conditional: case ir.OpKind.DeferWhen: case ir.OpKind.StoreLet: return 1; case ir.OpKind.RepeaterCreate: // Repeaters may require an extra variable binding slot, if they have an empty view, for the // empty block tracking. // TODO: It's a bit odd to have a create mode instruction consume variable slots. Maybe we can // find a way to use the Repeater update op instead. return op.emptyView ? 1 : 0; default: throw new Error(`Unhandled op: ${ir.OpKind[op.kind]}`); } } export function varsUsedByIrExpression(expr: ir.Expression & ir.ConsumesVarsTrait): number { switch (expr.kind) { case ir.ExpressionKind.PureFunctionExpr: return 1 + expr.args.length; case ir.ExpressionKind.PipeBinding: return 1 + expr.args.length; case ir.ExpressionKind.PipeBindingVariadic: return 1 + expr.numArgs; case ir.ExpressionKind.StoreLet: return 1; default: throw new Error( `AssertionError: unhandled ConsumesVarsTrait expression ${expr.constructor.name}`, ); } } function isSingletonInterpolation(expr: ir.Interpolation): boolean { if (expr.expressions.length !== 1 || expr.strings.length !== 2) { return false; } if (expr.strings[0] !== '' || expr.strings[1] !== '') { return false; } return true; }
{ "end_byte": 6208, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/var_counting.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/extract_i18n_messages.ts_0_6360
/** * @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 * as ir from '../../ir'; import {CompilationJob} from '../compilation'; /** * The escape sequence used indicate message param values. */ const ESCAPE = '\uFFFD'; /** * Marker used to indicate an element tag. */ const ELEMENT_MARKER = '#'; /** * Marker used to indicate a template tag. */ const TEMPLATE_MARKER = '*'; /** * Marker used to indicate closing of an element or template tag. */ const TAG_CLOSE_MARKER = '/'; /** * Marker used to indicate the sub-template context. */ const CONTEXT_MARKER = ':'; /** * Marker used to indicate the start of a list of values. */ const LIST_START_MARKER = '['; /** * Marker used to indicate the end of a list of values. */ const LIST_END_MARKER = ']'; /** * Delimiter used to separate multiple values in a list. */ const LIST_DELIMITER = '|'; /** * Formats the param maps on extracted message ops into a maps of `Expression` objects that can be * used in the final output. */ export function extractI18nMessages(job: CompilationJob): void { // Create an i18n message for each context. // TODO: Merge the context op with the message op since they're 1:1 anyways. const i18nMessagesByContext = new Map<ir.XrefId, ir.I18nMessageOp>(); const i18nBlocks = new Map<ir.XrefId, ir.I18nStartOp>(); const i18nContexts = new Map<ir.XrefId, ir.I18nContextOp>(); for (const unit of job.units) { for (const op of unit.create) { switch (op.kind) { case ir.OpKind.I18nContext: const i18nMessageOp = createI18nMessage(job, op); unit.create.push(i18nMessageOp); i18nMessagesByContext.set(op.xref, i18nMessageOp); i18nContexts.set(op.xref, op); break; case ir.OpKind.I18nStart: i18nBlocks.set(op.xref, op); break; } } } // Associate sub-messages for ICUs with their root message. At this point we can also remove the // ICU start/end ops, as they are no longer needed. let currentIcu: ir.IcuStartOp | null = null; for (const unit of job.units) { for (const op of unit.create) { switch (op.kind) { case ir.OpKind.IcuStart: currentIcu = op; ir.OpList.remove<ir.CreateOp>(op); // Skip any contexts not associated with an ICU. const icuContext = i18nContexts.get(op.context!)!; if (icuContext.contextKind !== ir.I18nContextKind.Icu) { continue; } // Skip ICUs that share a context with their i18n message. These represent root-level // ICUs, not sub-messages. const i18nBlock = i18nBlocks.get(icuContext.i18nBlock!)!; if (i18nBlock.context === icuContext.xref) { continue; } // Find the root message and push this ICUs message as a sub-message. const rootI18nBlock = i18nBlocks.get(i18nBlock.root)!; const rootMessage = i18nMessagesByContext.get(rootI18nBlock.context!); if (rootMessage === undefined) { throw Error('AssertionError: ICU sub-message should belong to a root message.'); } const subMessage = i18nMessagesByContext.get(icuContext.xref)!; subMessage.messagePlaceholder = op.messagePlaceholder; rootMessage.subMessages.push(subMessage.xref); break; case ir.OpKind.IcuEnd: currentIcu = null; ir.OpList.remove<ir.CreateOp>(op); break; case ir.OpKind.IcuPlaceholder: // Add ICU placeholders to the message, then remove the ICU placeholder ops. if (currentIcu === null || currentIcu.context == null) { throw Error('AssertionError: Unexpected ICU placeholder outside of i18n context'); } const msg = i18nMessagesByContext.get(currentIcu.context)!; msg.postprocessingParams.set(op.name, o.literal(formatIcuPlaceholder(op))); ir.OpList.remove<ir.CreateOp>(op); break; } } } } /** * Create an i18n message op from an i18n context op. */ function createI18nMessage( job: CompilationJob, context: ir.I18nContextOp, messagePlaceholder?: string, ): ir.I18nMessageOp { let formattedParams = formatParams(context.params); const formattedPostprocessingParams = formatParams(context.postprocessingParams); let needsPostprocessing = [...context.params.values()].some((v) => v.length > 1); return ir.createI18nMessageOp( job.allocateXrefId(), context.xref, context.i18nBlock, context.message, messagePlaceholder ?? null, formattedParams, formattedPostprocessingParams, needsPostprocessing, ); } /** * Formats an ICU placeholder into a single string with expression placeholders. */ function formatIcuPlaceholder(op: ir.IcuPlaceholderOp) { if (op.strings.length !== op.expressionPlaceholders.length + 1) { throw Error( `AssertionError: Invalid ICU placeholder with ${op.strings.length} strings and ${op.expressionPlaceholders.length} expressions`, ); } const values = op.expressionPlaceholders.map(formatValue); return op.strings.flatMap((str, i) => [str, values[i] || '']).join(''); } /** * Formats a map of `I18nParamValue[]` values into a map of `Expression` values. */ function formatParams(params: Map<string, ir.I18nParamValue[]>) { const formattedParams = new Map<string, o.Expression>(); for (const [placeholder, placeholderValues] of params) { const serializedValues = formatParamValues(placeholderValues); if (serializedValues !== null) { formattedParams.set(placeholder, o.literal(serializedValues)); } } return formattedParams; } /** * Formats an `I18nParamValue[]` into a string (or null for empty array). */ function formatParamValues(values: ir.I18nParamValue[]): string | null { if (values.length === 0) { return null; } const serializedValues = values.map((value) => formatValue(value)); return serializedValues.length === 1 ? serializedValues[0] : `${LIST_START_MARKER}${serializedValues.join(LIST_DELIMITER)}${LIST_END_MARKER}`; } /** * Formats a single `I18nParamValue` into a string */
{ "end_byte": 6360, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/extract_i18n_messages.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/extract_i18n_messages.ts_6361_9221
function formatValue(value: ir.I18nParamValue): string { // Element tags with a structural directive use a special form that concatenates the element and // template values. if ( value.flags & ir.I18nParamValueFlags.ElementTag && value.flags & ir.I18nParamValueFlags.TemplateTag ) { if (typeof value.value !== 'object') { throw Error('AssertionError: Expected i18n param value to have an element and template slot'); } const elementValue = formatValue({ ...value, value: value.value.element, flags: value.flags & ~ir.I18nParamValueFlags.TemplateTag, }); const templateValue = formatValue({ ...value, value: value.value.template, flags: value.flags & ~ir.I18nParamValueFlags.ElementTag, }); // TODO(mmalerba): This is likely a bug in TemplateDefinitionBuilder, we should not need to // record the template value twice. For now I'm re-implementing the behavior here to keep the // output consistent with TemplateDefinitionBuilder. if ( value.flags & ir.I18nParamValueFlags.OpenTag && value.flags & ir.I18nParamValueFlags.CloseTag ) { return `${templateValue}${elementValue}${templateValue}`; } // To match the TemplateDefinitionBuilder output, flip the order depending on whether the // values represent a closing or opening tag (or both). // TODO(mmalerba): Figure out if this makes a difference in terms of either functionality, // or the resulting message ID. If not, we can remove the special-casing in the future. return value.flags & ir.I18nParamValueFlags.CloseTag ? `${elementValue}${templateValue}` : `${templateValue}${elementValue}`; } // Self-closing tags use a special form that concatenates the start and close tag values. if ( value.flags & ir.I18nParamValueFlags.OpenTag && value.flags & ir.I18nParamValueFlags.CloseTag ) { return `${formatValue({ ...value, flags: value.flags & ~ir.I18nParamValueFlags.CloseTag, })}${formatValue({...value, flags: value.flags & ~ir.I18nParamValueFlags.OpenTag})}`; } // If there are no special flags, just return the raw value. if (value.flags === ir.I18nParamValueFlags.None) { return `${value.value}`; } // Encode the remaining flags as part of the value. let tagMarker = ''; let closeMarker = ''; if (value.flags & ir.I18nParamValueFlags.ElementTag) { tagMarker = ELEMENT_MARKER; } else if (value.flags & ir.I18nParamValueFlags.TemplateTag) { tagMarker = TEMPLATE_MARKER; } if (tagMarker !== '') { closeMarker = value.flags & ir.I18nParamValueFlags.CloseTag ? TAG_CLOSE_MARKER : ''; } const context = value.subTemplateIndex === null ? '' : `${CONTEXT_MARKER}${value.subTemplateIndex}`; return `${ESCAPE}${closeMarker}${tagMarker}${value.value}${context}${ESCAPE}`; }
{ "end_byte": 9221, "start_byte": 6361, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/extract_i18n_messages.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/apply_i18n_expressions.ts_0_2387
/** * @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 ir from '../../ir'; import {CompilationJob} from '../compilation'; /** * Adds apply operations after i18n expressions. */ export function applyI18nExpressions(job: CompilationJob): void { const i18nContexts = new Map<ir.XrefId, ir.I18nContextOp>(); for (const unit of job.units) { for (const op of unit.create) { if (op.kind === ir.OpKind.I18nContext) { i18nContexts.set(op.xref, op); } } } for (const unit of job.units) { for (const op of unit.update) { // Only add apply after expressions that are not followed by more expressions. if (op.kind === ir.OpKind.I18nExpression && needsApplication(i18nContexts, op)) { // TODO: what should be the source span for the apply op? ir.OpList.insertAfter<ir.UpdateOp>( ir.createI18nApplyOp(op.i18nOwner, op.handle, null!), op, ); } } } } /** * Checks whether the given expression op needs to be followed with an apply op. */ function needsApplication(i18nContexts: Map<ir.XrefId, ir.I18nContextOp>, op: ir.I18nExpressionOp) { // If the next op is not another expression, we need to apply. if (op.next?.kind !== ir.OpKind.I18nExpression) { return true; } const context = i18nContexts.get(op.context); const nextContext = i18nContexts.get(op.next.context); if (context === undefined) { throw new Error( "AssertionError: expected an I18nContextOp to exist for the I18nExpressionOp's context", ); } if (nextContext === undefined) { throw new Error( "AssertionError: expected an I18nContextOp to exist for the next I18nExpressionOp's context", ); } // If the next op is an expression targeting a different i18n block (or different element, in the // case of i18n attributes), we need to apply. // First, handle the case of i18n blocks. if (context.i18nBlock !== null) { // This is a block context. Compare the blocks. if (context.i18nBlock !== nextContext.i18nBlock) { return true; } return false; } // Second, handle the case of i18n attributes. if (op.i18nOwner !== op.next.i18nOwner) { return true; } return false; }
{ "end_byte": 2387, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/apply_i18n_expressions.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/naming.ts_0_7606
/** * @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 {sanitizeIdentifier} from '../../../../parse_util'; import * as ir from '../../ir'; import {hyphenate} from './parse_extracted_styles'; import {type CompilationJob, type CompilationUnit, ViewCompilationUnit} from '../compilation'; /** * Generate names for functions and variables across all views. * * This includes propagating those names into any `ir.ReadVariableExpr`s of those variables, so that * the reads can be emitted correctly. */ export function nameFunctionsAndVariables(job: CompilationJob): void { addNamesToView( job.root, job.componentName, {index: 0}, job.compatibility === ir.CompatibilityMode.TemplateDefinitionBuilder, ); } function addNamesToView( unit: CompilationUnit, baseName: string, state: {index: number}, compatibility: boolean, ): void { if (unit.fnName === null) { // Ensure unique names for view units. This is necessary because there might be multiple // components with same names in the context of the same pool. Only add the suffix // if really needed. unit.fnName = unit.job.pool.uniqueName( sanitizeIdentifier(`${baseName}_${unit.job.fnSuffix}`), /* alwaysIncludeSuffix */ false, ); } // Keep track of the names we assign to variables in the view. We'll need to propagate these // into reads of those variables afterwards. const varNames = new Map<ir.XrefId, string>(); for (const op of unit.ops()) { switch (op.kind) { case ir.OpKind.Property: case ir.OpKind.HostProperty: if (op.isAnimationTrigger) { op.name = '@' + op.name; } break; case ir.OpKind.Listener: if (op.handlerFnName !== null) { break; } if (!op.hostListener && op.targetSlot.slot === null) { throw new Error(`Expected a slot to be assigned`); } let animation = ''; if (op.isAnimationListener) { op.name = `@${op.name}.${op.animationPhase}`; animation = 'animation'; } if (op.hostListener) { op.handlerFnName = `${baseName}_${animation}${op.name}_HostBindingHandler`; } else { op.handlerFnName = `${unit.fnName}_${op.tag!.replace('-', '_')}_${animation}${op.name}_${ op.targetSlot.slot }_listener`; } op.handlerFnName = sanitizeIdentifier(op.handlerFnName); break; case ir.OpKind.TwoWayListener: if (op.handlerFnName !== null) { break; } if (op.targetSlot.slot === null) { throw new Error(`Expected a slot to be assigned`); } op.handlerFnName = sanitizeIdentifier( `${unit.fnName}_${op.tag!.replace('-', '_')}_${op.name}_${op.targetSlot.slot}_listener`, ); break; case ir.OpKind.Variable: varNames.set(op.xref, getVariableName(unit, op.variable, state)); break; case ir.OpKind.RepeaterCreate: if (!(unit instanceof ViewCompilationUnit)) { throw new Error(`AssertionError: must be compiling a component`); } if (op.handle.slot === null) { throw new Error(`Expected slot to be assigned`); } if (op.emptyView !== null) { const emptyView = unit.job.views.get(op.emptyView)!; // Repeater empty view function is at slot +2 (metadata is in the first slot). addNamesToView( emptyView, `${baseName}_${op.functionNameSuffix}Empty_${op.handle.slot + 2}`, state, compatibility, ); } // Repeater primary view function is at slot +1 (metadata is in the first slot). addNamesToView( unit.job.views.get(op.xref)!, `${baseName}_${op.functionNameSuffix}_${op.handle.slot + 1}`, state, compatibility, ); break; case ir.OpKind.Projection: if (!(unit instanceof ViewCompilationUnit)) { throw new Error(`AssertionError: must be compiling a component`); } if (op.handle.slot === null) { throw new Error(`Expected slot to be assigned`); } if (op.fallbackView !== null) { const fallbackView = unit.job.views.get(op.fallbackView)!; addNamesToView( fallbackView, `${baseName}_ProjectionFallback_${op.handle.slot}`, state, compatibility, ); } break; case ir.OpKind.Template: if (!(unit instanceof ViewCompilationUnit)) { throw new Error(`AssertionError: must be compiling a component`); } const childView = unit.job.views.get(op.xref)!; if (op.handle.slot === null) { throw new Error(`Expected slot to be assigned`); } const suffix = op.functionNameSuffix.length === 0 ? '' : `_${op.functionNameSuffix}`; addNamesToView(childView, `${baseName}${suffix}_${op.handle.slot}`, state, compatibility); break; case ir.OpKind.StyleProp: op.name = normalizeStylePropName(op.name); if (compatibility) { op.name = stripImportant(op.name); } break; case ir.OpKind.ClassProp: if (compatibility) { op.name = stripImportant(op.name); } break; } } // Having named all variables declared in the view, now we can push those names into the // `ir.ReadVariableExpr` expressions which represent reads of those variables. for (const op of unit.ops()) { ir.visitExpressionsInOp(op, (expr) => { if (!(expr instanceof ir.ReadVariableExpr) || expr.name !== null) { return; } if (!varNames.has(expr.xref)) { throw new Error(`Variable ${expr.xref} not yet named`); } expr.name = varNames.get(expr.xref)!; }); } } function getVariableName( unit: CompilationUnit, variable: ir.SemanticVariable, state: {index: number}, ): string { if (variable.name === null) { switch (variable.kind) { case ir.SemanticVariableKind.Context: variable.name = `ctx_r${state.index++}`; break; case ir.SemanticVariableKind.Identifier: if (unit.job.compatibility === ir.CompatibilityMode.TemplateDefinitionBuilder) { // TODO: Prefix increment and `_r` are for compatibility with the old naming scheme. // This has the potential to cause collisions when `ctx` is the identifier, so we need a // special check for that as well. const compatPrefix = variable.identifier === 'ctx' ? 'i' : ''; variable.name = `${variable.identifier}_${compatPrefix}r${++state.index}`; } else { variable.name = `${variable.identifier}_i${state.index++}`; } break; default: // TODO: Prefix increment for compatibility only. variable.name = `_r${++state.index}`; break; } } return variable.name; } /** * Normalizes a style prop name by hyphenating it (unless its a CSS variable). */ function normalizeStylePropName(name: string) { return name.startsWith('--') ? name : hyphenate(name); } /** * Strips `!important` out of the given style or class name. */ function stripImportant(name: string) { const importantIndex = name.indexOf('!important'); if (importantIndex > -1) { return name.substring(0, importantIndex); } return name; }
{ "end_byte": 7606, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/naming.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/generate_local_let_references.ts_0_1102
/** * @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 ir from '../../ir'; import type {ComponentCompilationJob} from '../compilation'; /** * Replaces the `storeLet` ops with variables that can be * used to reference the value within the same view. */ export function generateLocalLetReferences(job: ComponentCompilationJob): void { for (const unit of job.units) { for (const op of unit.update) { if (op.kind !== ir.OpKind.StoreLet) { continue; } const variable: ir.IdentifierVariable = { kind: ir.SemanticVariableKind.Identifier, name: null, identifier: op.declaredName, local: true, }; ir.OpList.replace<ir.UpdateOp>( op, ir.createVariableOp<ir.UpdateOp>( job.allocateXrefId(), variable, new ir.StoreLetExpr(op.target, op.value, op.sourceSpan), ir.VariableFlags.None, ), ); } } }
{ "end_byte": 1102, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/generate_local_let_references.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/slot_allocation.ts_0_3113
/** * @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 ir from '../../ir'; import type {ComponentCompilationJob} from '../compilation'; /** * Assign data slots for all operations which implement `ConsumesSlotOpTrait`, and propagate the * assigned data slots of those operations to any expressions which reference them via * `UsesSlotIndexTrait`. * * This phase is also responsible for counting the number of slots used for each view (its `decls`) * and propagating that number into the `Template` operations which declare embedded views. */ export function allocateSlots(job: ComponentCompilationJob): void { // Map of all declarations in all views within the component which require an assigned slot index. // This map needs to be global (across all views within the component) since it's possible to // reference a slot from one view from an expression within another (e.g. local references work // this way). const slotMap = new Map<ir.XrefId, number>(); // Process all views in the component and assign slot indexes. for (const unit of job.units) { // Slot indices start at 0 for each view (and are not unique between views). let slotCount = 0; for (const op of unit.create) { // Only consider declarations which consume data slots. if (!ir.hasConsumesSlotTrait(op)) { continue; } // Assign slots to this declaration starting at the current `slotCount`. op.handle.slot = slotCount; // And track its assigned slot in the `slotMap`. slotMap.set(op.xref, op.handle.slot); // Each declaration may use more than 1 slot, so increment `slotCount` to reserve the number // of slots required. slotCount += op.numSlotsUsed; } // Record the total number of slots used on the view itself. This will later be propagated into // `ir.TemplateOp`s which declare those views (except for the root view). unit.decls = slotCount; } // After slot assignment, `slotMap` now contains slot assignments for every declaration in the // whole template, across all views. Next, look for expressions which implement // `UsesSlotIndexExprTrait` and propagate the assigned slot indexes into them. // Additionally, this second scan allows us to find `ir.TemplateOp`s which declare views and // propagate the number of slots used for each view into the operation which declares it. for (const unit of job.units) { for (const op of unit.ops()) { if (op.kind === ir.OpKind.Template || op.kind === ir.OpKind.RepeaterCreate) { // Record the number of slots used by the view this `ir.TemplateOp` declares in the // operation itself, so it can be emitted later. const childView = job.views.get(op.xref)!; op.decls = childView.decls; // TODO: currently we handle the decls for the RepeaterCreate empty template in the reify // phase. We should handle that here instead. } } } }
{ "end_byte": 3113, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/slot_allocation.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/generate_projection_def.ts_0_2135
/** * @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 {parseSelectorToR3Selector} from '../../../../core'; import * as o from '../../../../output/output_ast'; import * as ir from '../../ir'; import type {ComponentCompilationJob} from '../compilation'; import {literalOrArrayLiteral} from '../conversion'; /** * Locate projection slots, populate the each component's `ngContentSelectors` literal field, * populate `project` arguments, and generate the required `projectionDef` instruction for the job's * root view. */ export function generateProjectionDefs(job: ComponentCompilationJob): void { // TODO: Why does TemplateDefinitionBuilder force a shared constant? const share = job.compatibility === ir.CompatibilityMode.TemplateDefinitionBuilder; // Collect all selectors from this component, and its nested views. Also, assign each projection a // unique ascending projection slot index. const selectors = []; let projectionSlotIndex = 0; for (const unit of job.units) { for (const op of unit.create) { if (op.kind === ir.OpKind.Projection) { selectors.push(op.selector); op.projectionSlotIndex = projectionSlotIndex++; } } } if (selectors.length > 0) { // Create the projectionDef array. If we only found a single wildcard selector, then we use the // default behavior with no arguments instead. let defExpr: o.Expression | null = null; if (selectors.length > 1 || selectors[0] !== '*') { const def = selectors.map((s) => (s === '*' ? s : parseSelectorToR3Selector(s))); defExpr = job.pool.getConstLiteral(literalOrArrayLiteral(def), share); } // Create the ngContentSelectors constant. job.contentSelectors = job.pool.getConstLiteral(literalOrArrayLiteral(selectors), share); // The projection def instruction goes at the beginning of the root view, before any // `projection` instructions. job.root.create.prepend([ir.createProjectionDefOp(defExpr)]); } }
{ "end_byte": 2135, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/generate_projection_def.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/resolve_sanitizers.ts_0_5911
/** * @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 * as o from '../../../../output/output_ast'; import {Identifiers} from '../../../../render3/r3_identifiers'; import {isIframeSecuritySensitiveAttr} from '../../../../schema/dom_security_schema'; import * as ir from '../../ir'; import {CompilationJob, CompilationJobKind} from '../compilation'; import {createOpXrefMap} from '../util/elements'; /** * Map of security contexts to their sanitizer function. */ const sanitizerFns = new Map<SecurityContext, o.ExternalReference>([ [SecurityContext.HTML, Identifiers.sanitizeHtml], [SecurityContext.RESOURCE_URL, Identifiers.sanitizeResourceUrl], [SecurityContext.SCRIPT, Identifiers.sanitizeScript], [SecurityContext.STYLE, Identifiers.sanitizeStyle], [SecurityContext.URL, Identifiers.sanitizeUrl], ]); /** * Map of security contexts to their trusted value function. */ const trustedValueFns = new Map<SecurityContext, o.ExternalReference>([ [SecurityContext.HTML, Identifiers.trustConstantHtml], [SecurityContext.RESOURCE_URL, Identifiers.trustConstantResourceUrl], ]); /** * Resolves sanitization functions for ops that need them. */ export function resolveSanitizers(job: CompilationJob): void { for (const unit of job.units) { const elements = createOpXrefMap(unit); // For normal element bindings we create trusted values for security sensitive constant // attributes. However, for host bindings we skip this step (this matches what // TemplateDefinitionBuilder does). // TODO: Is the TDB behavior correct here? if (job.kind !== CompilationJobKind.Host) { for (const op of unit.create) { if (op.kind === ir.OpKind.ExtractedAttribute) { const trustedValueFn = trustedValueFns.get(getOnlySecurityContext(op.securityContext)) ?? null; op.trustedValueFn = trustedValueFn !== null ? o.importExpr(trustedValueFn) : null; } } } for (const op of unit.update) { switch (op.kind) { case ir.OpKind.Property: case ir.OpKind.Attribute: case ir.OpKind.HostProperty: let sanitizerFn: o.ExternalReference | null = null; if ( Array.isArray(op.securityContext) && op.securityContext.length === 2 && op.securityContext.indexOf(SecurityContext.URL) > -1 && op.securityContext.indexOf(SecurityContext.RESOURCE_URL) > -1 ) { // When the host element isn't known, some URL attributes (such as "src" and "href") may // be part of multiple different security contexts. In this case we use special // sanitization function and select the actual sanitizer at runtime based on a tag name // that is provided while invoking sanitization function. sanitizerFn = Identifiers.sanitizeUrlOrResourceUrl; } else { sanitizerFn = sanitizerFns.get(getOnlySecurityContext(op.securityContext)) ?? null; } op.sanitizer = sanitizerFn !== null ? o.importExpr(sanitizerFn) : null; // If there was no sanitization function found based on the security context of an // attribute/property, check whether this attribute/property is one of the // security-sensitive <iframe> attributes (and that the current element is actually an // <iframe>). if (op.sanitizer === null) { let isIframe = false; if (job.kind === CompilationJobKind.Host || op.kind === ir.OpKind.HostProperty) { // Note: for host bindings defined on a directive, we do not try to find all // possible places where it can be matched, so we can not determine whether // the host element is an <iframe>. In this case, we just assume it is and append a // validation function, which is invoked at runtime and would have access to the // underlying DOM element to check if it's an <iframe> and if so - run extra checks. isIframe = true; } else { // For a normal binding we can just check if the element its on is an iframe. const ownerOp = elements.get(op.target); if (ownerOp === undefined || !ir.isElementOrContainerOp(ownerOp)) { throw Error('Property should have an element-like owner'); } isIframe = isIframeElement(ownerOp); } if (isIframe && isIframeSecuritySensitiveAttr(op.name)) { op.sanitizer = o.importExpr(Identifiers.validateIframeAttribute); } } break; } } } } /** * Checks whether the given op represents an iframe element. */ function isIframeElement(op: ir.ElementOrContainerOps): boolean { return op.kind === ir.OpKind.ElementStart && op.tag?.toLowerCase() === 'iframe'; } /** * Asserts that there is only a single security context and returns it. */ function getOnlySecurityContext( securityContext: SecurityContext | SecurityContext[], ): SecurityContext { if (Array.isArray(securityContext)) { if (securityContext.length > 1) { // TODO: What should we do here? TDB just took the first one, but this feels like something we // would want to know about and create a special case for like we did for Url/ResourceUrl. My // guess is that, outside of the Url/ResourceUrl case, this never actually happens. If there // do turn out to be other cases, throwing an error until we can address it feels safer. throw Error(`AssertionError: Ambiguous security context`); } return securityContext[0] || SecurityContext.NONE; } return securityContext; }
{ "end_byte": 5911, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/resolve_sanitizers.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/i18n_text_extraction.ts_0_4643
/** * @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 ir from '../../ir'; import {CompilationJob} from '../compilation'; /** * Removes text nodes within i18n blocks since they are already hardcoded into the i18n message. * Also, replaces interpolations on these text nodes with i18n expressions of the non-text portions, * which will be applied later. */ export function convertI18nText(job: CompilationJob): void { for (const unit of job.units) { // Remove all text nodes within i18n blocks, their content is already captured in the i18n // message. let currentI18n: ir.I18nStartOp | null = null; let currentIcu: ir.IcuStartOp | null = null; const textNodeI18nBlocks = new Map<ir.XrefId, ir.I18nStartOp>(); const textNodeIcus = new Map<ir.XrefId, ir.IcuStartOp | null>(); const icuPlaceholderByText = new Map<ir.XrefId, ir.IcuPlaceholderOp>(); for (const op of unit.create) { switch (op.kind) { case ir.OpKind.I18nStart: if (op.context === null) { throw Error('I18n op should have its context set.'); } currentI18n = op; break; case ir.OpKind.I18nEnd: currentI18n = null; break; case ir.OpKind.IcuStart: if (op.context === null) { throw Error('Icu op should have its context set.'); } currentIcu = op; break; case ir.OpKind.IcuEnd: currentIcu = null; break; case ir.OpKind.Text: if (currentI18n !== null) { textNodeI18nBlocks.set(op.xref, currentI18n); textNodeIcus.set(op.xref, currentIcu); if (op.icuPlaceholder !== null) { // Create an op to represent the ICU placeholder. Initially set its static text to the // value of the text op, though this may be overwritten later if this text op is a // placeholder for an interpolation. const icuPlaceholderOp = ir.createIcuPlaceholderOp( job.allocateXrefId(), op.icuPlaceholder, [op.initialValue], ); ir.OpList.replace<ir.CreateOp>(op, icuPlaceholderOp); icuPlaceholderByText.set(op.xref, icuPlaceholderOp); } else { // Otherwise just remove the text op, since its value is already accounted for in the // translated message. ir.OpList.remove<ir.CreateOp>(op); } } break; } } // Update any interpolations to the removed text, and instead represent them as a series of i18n // expressions that we then apply. for (const op of unit.update) { switch (op.kind) { case ir.OpKind.InterpolateText: if (!textNodeI18nBlocks.has(op.target)) { continue; } const i18nOp = textNodeI18nBlocks.get(op.target)!; const icuOp = textNodeIcus.get(op.target); const icuPlaceholder = icuPlaceholderByText.get(op.target); const contextId = icuOp ? icuOp.context : i18nOp.context; const resolutionTime = icuOp ? ir.I18nParamResolutionTime.Postproccessing : ir.I18nParamResolutionTime.Creation; const ops: ir.I18nExpressionOp[] = []; for (let i = 0; i < op.interpolation.expressions.length; i++) { const expr = op.interpolation.expressions[i]; // For now, this i18nExpression depends on the slot context of the enclosing i18n block. // Later, we will modify this, and advance to a different point. ops.push( ir.createI18nExpressionOp( contextId!, i18nOp.xref, i18nOp.xref, i18nOp.handle, expr, icuPlaceholder?.xref ?? null, op.interpolation.i18nPlaceholders[i] ?? null, resolutionTime, ir.I18nExpressionFor.I18nText, '', expr.sourceSpan ?? op.sourceSpan, ), ); } ir.OpList.replaceWithMany(op as ir.UpdateOp, ops); // If this interpolation is part of an ICU placeholder, add the strings and expressions to // the placeholder. if (icuPlaceholder !== undefined) { icuPlaceholder.strings = op.interpolation.strings; } break; } } } }
{ "end_byte": 4643, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/i18n_text_extraction.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/convert_i18n_bindings.ts_0_2858
/** * @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 ir from '../../ir'; import {CompilationJob} from '../compilation'; /** * Some binding instructions in the update block may actually correspond to i18n bindings. In that * case, they should be replaced with i18nExp instructions for the dynamic portions. */ export function convertI18nBindings(job: CompilationJob): void { const i18nAttributesByElem: Map<ir.XrefId, ir.I18nAttributesOp> = new Map(); for (const unit of job.units) { for (const op of unit.create) { if (op.kind === ir.OpKind.I18nAttributes) { i18nAttributesByElem.set(op.target, op); } } for (const op of unit.update) { switch (op.kind) { case ir.OpKind.Property: case ir.OpKind.Attribute: if (op.i18nContext === null) { continue; } if (!(op.expression instanceof ir.Interpolation)) { continue; } const i18nAttributesForElem = i18nAttributesByElem.get(op.target); if (i18nAttributesForElem === undefined) { throw new Error( 'AssertionError: An i18n attribute binding instruction requires the owning element to have an I18nAttributes create instruction', ); } if (i18nAttributesForElem.target !== op.target) { throw new Error( 'AssertionError: Expected i18nAttributes target element to match binding target element', ); } const ops: ir.UpdateOp[] = []; for (let i = 0; i < op.expression.expressions.length; i++) { const expr = op.expression.expressions[i]; if (op.expression.i18nPlaceholders.length !== op.expression.expressions.length) { throw new Error( `AssertionError: An i18n attribute binding instruction requires the same number of expressions and placeholders, but found ${op.expression.i18nPlaceholders.length} placeholders and ${op.expression.expressions.length} expressions`, ); } ops.push( ir.createI18nExpressionOp( op.i18nContext, i18nAttributesForElem.target, i18nAttributesForElem.xref, i18nAttributesForElem.handle, expr, null, op.expression.i18nPlaceholders[i], ir.I18nParamResolutionTime.Creation, ir.I18nExpressionFor.I18nAttribute, op.name, op.sourceSpan, ), ); } ir.OpList.replaceWithMany(op as ir.UpdateOp, ops); break; } } } }
{ "end_byte": 2858, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/convert_i18n_bindings.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/binding_specialization.ts_0_4192
/** * @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 {splitNsName} from '../../../../ml_parser/tags'; import * as o from '../../../../output/output_ast'; import * as ir from '../../ir'; import {CompilationJob, CompilationJobKind} from '../compilation'; /** * Looks up an element in the given map by xref ID. */ function lookupElement( elements: Map<ir.XrefId, ir.ElementOrContainerOps>, xref: ir.XrefId, ): ir.ElementOrContainerOps { const el = elements.get(xref); if (el === undefined) { throw new Error('All attributes should have an element-like target.'); } return el; } export function specializeBindings(job: CompilationJob): void { const elements = new Map<ir.XrefId, ir.ElementOrContainerOps>(); for (const unit of job.units) { for (const op of unit.create) { if (!ir.isElementOrContainerOp(op)) { continue; } elements.set(op.xref, op); } } for (const unit of job.units) { for (const op of unit.ops()) { if (op.kind !== ir.OpKind.Binding) { continue; } switch (op.bindingKind) { case ir.BindingKind.Attribute: if (op.name === 'ngNonBindable') { ir.OpList.remove<ir.UpdateOp>(op); const target = lookupElement(elements, op.target); target.nonBindable = true; } else { const [namespace, name] = splitNsName(op.name); ir.OpList.replace<ir.UpdateOp>( op, ir.createAttributeOp( op.target, namespace, name, op.expression, op.securityContext, op.isTextAttribute, op.isStructuralTemplateAttribute, op.templateKind, op.i18nMessage, op.sourceSpan, ), ); } break; case ir.BindingKind.Property: case ir.BindingKind.Animation: if (job.kind === CompilationJobKind.Host) { ir.OpList.replace<ir.UpdateOp>( op, ir.createHostPropertyOp( op.name, op.expression, op.bindingKind === ir.BindingKind.Animation, op.i18nContext, op.securityContext, op.sourceSpan, ), ); } else { ir.OpList.replace<ir.UpdateOp>( op, ir.createPropertyOp( op.target, op.name, op.expression, op.bindingKind === ir.BindingKind.Animation, op.securityContext, op.isStructuralTemplateAttribute, op.templateKind, op.i18nContext, op.i18nMessage, op.sourceSpan, ), ); } break; case ir.BindingKind.TwoWayProperty: if (!(op.expression instanceof o.Expression)) { // We shouldn't be able to hit this code path since interpolations in two-way bindings // result in a parser error. We assert here so that downstream we can assume that // the value is always an expression. throw new Error( `Expected value of two-way property binding "${op.name}" to be an expression`, ); } ir.OpList.replace<ir.UpdateOp>( op, ir.createTwoWayPropertyOp( op.target, op.name, op.expression, op.securityContext, op.isStructuralTemplateAttribute, op.templateKind, op.i18nContext, op.i18nMessage, op.sourceSpan, ), ); break; case ir.BindingKind.I18n: case ir.BindingKind.ClassName: case ir.BindingKind.StyleProperty: throw new Error(`Unhandled binding of kind ${ir.BindingKind[op.bindingKind]}`); } } } }
{ "end_byte": 4192, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/binding_specialization.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/host_style_property_parsing.ts_0_2857
/** * @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 ir from '../../ir'; import type {CompilationJob} from '../compilation'; const STYLE_DOT = 'style.'; const CLASS_DOT = 'class.'; const STYLE_BANG = 'style!'; const CLASS_BANG = 'class!'; const BANG_IMPORTANT = '!important'; /** * Host bindings are compiled using a different parser entrypoint, and are parsed quite differently * as a result. Therefore, we need to do some extra parsing for host style properties, as compared * to non-host style properties. * TODO: Unify host bindings and non-host bindings in the parser. */ export function parseHostStyleProperties(job: CompilationJob): void { for (const op of job.root.update) { if (!(op.kind === ir.OpKind.Binding && op.bindingKind === ir.BindingKind.Property)) { continue; } if (op.name.endsWith(BANG_IMPORTANT)) { // Delete any `!important` suffixes from the binding name. op.name = op.name.substring(0, op.name.length - BANG_IMPORTANT.length); } if (op.name.startsWith(STYLE_DOT)) { op.bindingKind = ir.BindingKind.StyleProperty; op.name = op.name.substring(STYLE_DOT.length); if (!isCssCustomProperty(op.name)) { op.name = hyphenate(op.name); } const {property, suffix} = parseProperty(op.name); op.name = property; op.unit = suffix; } else if (op.name.startsWith(STYLE_BANG)) { op.bindingKind = ir.BindingKind.StyleProperty; op.name = 'style'; } else if (op.name.startsWith(CLASS_DOT)) { op.bindingKind = ir.BindingKind.ClassName; op.name = parseProperty(op.name.substring(CLASS_DOT.length)).property; } else if (op.name.startsWith(CLASS_BANG)) { op.bindingKind = ir.BindingKind.ClassName; op.name = parseProperty(op.name.substring(CLASS_BANG.length)).property; } } } /** * Checks whether property name is a custom CSS property. * See: https://www.w3.org/TR/css-variables-1 */ function isCssCustomProperty(name: string): boolean { return name.startsWith('--'); } function hyphenate(value: string): string { return value .replace(/[a-z][A-Z]/g, (v) => { return v.charAt(0) + '-' + v.charAt(1); }) .toLowerCase(); } function parseProperty(name: string): {property: string; suffix: string | null} { const overrideIndex = name.indexOf('!important'); if (overrideIndex !== -1) { name = overrideIndex > 0 ? name.substring(0, overrideIndex) : ''; } let suffix: string | null = null; let property = name; const unitIndex = name.lastIndexOf('.'); if (unitIndex > 0) { suffix = name.slice(unitIndex + 1); property = name.substring(0, unitIndex); } return {property, suffix}; }
{ "end_byte": 2857, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/host_style_property_parsing.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/generate_advance.ts_0_2611
/** * @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 ir from '../../ir'; import type {CompilationJob} from '../compilation'; /** * Generate `ir.AdvanceOp`s in between `ir.UpdateOp`s that ensure the runtime's implicit slot * context will be advanced correctly. */ export function generateAdvance(job: CompilationJob): void { for (const unit of job.units) { // First build a map of all of the declarations in the view that have assigned slots. const slotMap = new Map<ir.XrefId, number>(); for (const op of unit.create) { if (!ir.hasConsumesSlotTrait(op)) { continue; } else if (op.handle.slot === null) { throw new Error( `AssertionError: expected slots to have been allocated before generating advance() calls`, ); } slotMap.set(op.xref, op.handle.slot); } // Next, step through the update operations and generate `ir.AdvanceOp`s as required to ensure // the runtime's implicit slot counter will be set to the correct slot before executing each // update operation which depends on it. // // To do that, we track what the runtime's slot counter will be through the update operations. let slotContext = 0; for (const op of unit.update) { let consumer: ir.DependsOnSlotContextOpTrait | null = null; if (ir.hasDependsOnSlotContextTrait(op)) { consumer = op; } else { ir.visitExpressionsInOp(op, (expr) => { if (consumer === null && ir.hasDependsOnSlotContextTrait(expr)) { consumer = expr; } }); } if (consumer === null) { continue; } if (!slotMap.has(consumer.target)) { // We expect ops that _do_ depend on the slot counter to point at declarations that exist in // the `slotMap`. throw new Error(`AssertionError: reference to unknown slot for target ${consumer.target}`); } const slot = slotMap.get(consumer.target)!; // Does the slot counter need to be adjusted? if (slotContext !== slot) { // If so, generate an `ir.AdvanceOp` to advance the counter. const delta = slot - slotContext; if (delta < 0) { throw new Error(`AssertionError: slot counter should never need to move backwards`); } ir.OpList.insertBefore<ir.UpdateOp>(ir.createAdvanceOp(delta, consumer.sourceSpan), op); slotContext = slot; } } } }
{ "end_byte": 2611, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/generate_advance.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/transform_two_way_binding_set.ts_0_2036
/** * @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 * as ir from '../../ir'; import * as ng from '../instruction'; import type {CompilationJob} from '../compilation'; /** * Transforms a `TwoWayBindingSet` expression into an expression that either * sets a value through the `twoWayBindingSet` instruction or falls back to setting * the value directly. E.g. the expression `TwoWayBindingSet(target, value)` becomes: * `ng.twoWayBindingSet(target, value) || (target = value)`. */ export function transformTwoWayBindingSet(job: CompilationJob): void { for (const unit of job.units) { for (const op of unit.create) { if (op.kind === ir.OpKind.TwoWayListener) { ir.transformExpressionsInOp( op, (expr) => { if (!(expr instanceof ir.TwoWayBindingSetExpr)) { return expr; } const {target, value} = expr; if (target instanceof o.ReadPropExpr || target instanceof o.ReadKeyExpr) { return ng.twoWayBindingSet(target, value).or(target.set(value)); } // ASSUMPTION: here we're assuming that `ReadVariableExpr` will be a reference // to a local template variable. This appears to be the case at the time of writing. // If the expression is targeting a variable read, we only emit the `twoWayBindingSet` // since the fallback would be attempting to write into a constant. Invalid usages will be // flagged during template type checking. if (target instanceof ir.ReadVariableExpr) { return ng.twoWayBindingSet(target, value); } throw new Error(`Unsupported expression in two-way action binding.`); }, ir.VisitorContextFlag.InChildOperation, ); } } } }
{ "end_byte": 2036, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/transform_two_way_binding_set.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/defer_configs.ts_0_1191
/** * @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 ir from '../../ir'; import type {ComponentCompilationJob} from '../compilation'; import {literalOrArrayLiteral} from '../conversion'; /** * Defer instructions take a configuration array, which should be collected into the component * consts. This phase finds the config options, and creates the corresponding const array. */ export function configureDeferInstructions(job: ComponentCompilationJob): void { for (const unit of job.units) { for (const op of unit.create) { if (op.kind !== ir.OpKind.Defer) { continue; } if (op.placeholderMinimumTime !== null) { op.placeholderConfig = new ir.ConstCollectedExpr( literalOrArrayLiteral([op.placeholderMinimumTime]), ); } if (op.loadingMinimumTime !== null || op.loadingAfterTime !== null) { op.loadingConfig = new ir.ConstCollectedExpr( literalOrArrayLiteral([op.loadingMinimumTime, op.loadingAfterTime]), ); } } } }
{ "end_byte": 1191, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/defer_configs.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/nonbindable.ts_0_1751
/** * @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 ir from '../../ir'; import type {CompilationJob} from '../compilation'; /** * Looks up an element in the given map by xref ID. */ function lookupElement( elements: Map<ir.XrefId, ir.ElementOrContainerOps>, xref: ir.XrefId, ): ir.ElementOrContainerOps { const el = elements.get(xref); if (el === undefined) { throw new Error('All attributes should have an element-like target.'); } return el; } /** * When a container is marked with `ngNonBindable`, the non-bindable characteristic also applies to * all descendants of that container. Therefore, we must emit `disableBindings` and `enableBindings` * instructions for every such container. */ export function disableBindings(job: CompilationJob): void { const elements = new Map<ir.XrefId, ir.ElementOrContainerOps>(); for (const view of job.units) { for (const op of view.create) { if (!ir.isElementOrContainerOp(op)) { continue; } elements.set(op.xref, op); } } for (const unit of job.units) { for (const op of unit.create) { if ( (op.kind === ir.OpKind.ElementStart || op.kind === ir.OpKind.ContainerStart) && op.nonBindable ) { ir.OpList.insertAfter<ir.CreateOp>(ir.createDisableBindingsOp(op.xref), op); } if ( (op.kind === ir.OpKind.ElementEnd || op.kind === ir.OpKind.ContainerEnd) && lookupElement(elements, op.xref).nonBindable ) { ir.OpList.insertBefore<ir.CreateOp>(ir.createEnableBindingsOp(op.xref), op); } } } }
{ "end_byte": 1751, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/nonbindable.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/reify.ts_0_2401
/** * @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} from '../../../../render3/r3_identifiers'; import * as ir from '../../ir'; import {ViewCompilationUnit, type CompilationJob, type CompilationUnit} from '../compilation'; import * as ng from '../instruction'; /** * Map of target resolvers for event listeners. */ const GLOBAL_TARGET_RESOLVERS = new Map<string, o.ExternalReference>([ ['window', Identifiers.resolveWindow], ['document', Identifiers.resolveDocument], ['body', Identifiers.resolveBody], ]); /** * Compiles semantic operations across all views and generates output `o.Statement`s with actual * runtime calls in their place. * * Reification replaces semantic operations with selected Ivy instructions and other generated code * structures. After reification, the create/update operation lists of all views should only contain * `ir.StatementOp`s (which wrap generated `o.Statement`s). */ export function reify(job: CompilationJob): void { for (const unit of job.units) { reifyCreateOperations(unit, unit.create); reifyUpdateOperations(unit, unit.update); } } /** * This function can be used a sanity check -- it walks every expression in the const pool, and * every expression reachable from an op, and makes sure that there are no IR expressions * left. This is nice to use for debugging mysterious failures where an IR expression cannot be * output from the output AST code. */ function ensureNoIrForDebug(job: CompilationJob) { for (const stmt of job.pool.statements) { ir.transformExpressionsInStatement( stmt, (expr) => { if (ir.isIrExpression(expr)) { throw new Error( `AssertionError: IR expression found during reify: ${ir.ExpressionKind[expr.kind]}`, ); } return expr; }, ir.VisitorContextFlag.None, ); } for (const unit of job.units) { for (const op of unit.ops()) { ir.visitExpressionsInOp(op, (expr) => { if (ir.isIrExpression(expr)) { throw new Error( `AssertionError: IR expression found during reify: ${ir.ExpressionKind[expr.kind]}`, ); } }); } } }
{ "end_byte": 2401, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/reify.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/reify.ts_2403_11785
function reifyCreateOperations(unit: CompilationUnit, ops: ir.OpList<ir.CreateOp>): void { for (const op of ops) { ir.transformExpressionsInOp(op, reifyIrExpression, ir.VisitorContextFlag.None); switch (op.kind) { case ir.OpKind.Text: ir.OpList.replace(op, ng.text(op.handle.slot!, op.initialValue, op.sourceSpan)); break; case ir.OpKind.ElementStart: ir.OpList.replace( op, ng.elementStart( op.handle.slot!, op.tag!, op.attributes as number | null, op.localRefs as number | null, op.startSourceSpan, ), ); break; case ir.OpKind.Element: ir.OpList.replace( op, ng.element( op.handle.slot!, op.tag!, op.attributes as number | null, op.localRefs as number | null, op.wholeSourceSpan, ), ); break; case ir.OpKind.ElementEnd: ir.OpList.replace(op, ng.elementEnd(op.sourceSpan)); break; case ir.OpKind.ContainerStart: ir.OpList.replace( op, ng.elementContainerStart( op.handle.slot!, op.attributes as number | null, op.localRefs as number | null, op.startSourceSpan, ), ); break; case ir.OpKind.Container: ir.OpList.replace( op, ng.elementContainer( op.handle.slot!, op.attributes as number | null, op.localRefs as number | null, op.wholeSourceSpan, ), ); break; case ir.OpKind.ContainerEnd: ir.OpList.replace(op, ng.elementContainerEnd()); break; case ir.OpKind.I18nStart: ir.OpList.replace( op, ng.i18nStart(op.handle.slot!, op.messageIndex!, op.subTemplateIndex!, op.sourceSpan), ); break; case ir.OpKind.I18nEnd: ir.OpList.replace(op, ng.i18nEnd(op.sourceSpan)); break; case ir.OpKind.I18n: ir.OpList.replace( op, ng.i18n(op.handle.slot!, op.messageIndex!, op.subTemplateIndex!, op.sourceSpan), ); break; case ir.OpKind.I18nAttributes: if (op.i18nAttributesConfig === null) { throw new Error(`AssertionError: i18nAttributesConfig was not set`); } ir.OpList.replace(op, ng.i18nAttributes(op.handle.slot!, op.i18nAttributesConfig)); break; case ir.OpKind.Template: if (!(unit instanceof ViewCompilationUnit)) { throw new Error(`AssertionError: must be compiling a component`); } if (Array.isArray(op.localRefs)) { throw new Error( `AssertionError: local refs array should have been extracted into a constant`, ); } const childView = unit.job.views.get(op.xref)!; ir.OpList.replace( op, ng.template( op.handle.slot!, o.variable(childView.fnName!), childView.decls!, childView.vars!, op.tag, op.attributes, op.localRefs, op.startSourceSpan, ), ); break; case ir.OpKind.DisableBindings: ir.OpList.replace(op, ng.disableBindings()); break; case ir.OpKind.EnableBindings: ir.OpList.replace(op, ng.enableBindings()); break; case ir.OpKind.Pipe: ir.OpList.replace(op, ng.pipe(op.handle.slot!, op.name)); break; case ir.OpKind.DeclareLet: ir.OpList.replace(op, ng.declareLet(op.handle.slot!, op.sourceSpan)); break; case ir.OpKind.Listener: const listenerFn = reifyListenerHandler( unit, op.handlerFnName!, op.handlerOps, op.consumesDollarEvent, ); const eventTargetResolver = op.eventTarget ? GLOBAL_TARGET_RESOLVERS.get(op.eventTarget) : null; if (eventTargetResolver === undefined) { throw new Error( `Unexpected global target '${op.eventTarget}' defined for '${op.name}' event. Supported list of global targets: window,document,body.`, ); } ir.OpList.replace( op, ng.listener( op.name, listenerFn, eventTargetResolver, op.hostListener && op.isAnimationListener, op.sourceSpan, ), ); break; case ir.OpKind.TwoWayListener: ir.OpList.replace( op, ng.twoWayListener( op.name, reifyListenerHandler(unit, op.handlerFnName!, op.handlerOps, true), op.sourceSpan, ), ); break; case ir.OpKind.Variable: if (op.variable.name === null) { throw new Error(`AssertionError: unnamed variable ${op.xref}`); } ir.OpList.replace<ir.CreateOp>( op, ir.createStatementOp( new o.DeclareVarStmt(op.variable.name, op.initializer, undefined, o.StmtModifier.Final), ), ); break; case ir.OpKind.Namespace: switch (op.active) { case ir.Namespace.HTML: ir.OpList.replace<ir.CreateOp>(op, ng.namespaceHTML()); break; case ir.Namespace.SVG: ir.OpList.replace<ir.CreateOp>(op, ng.namespaceSVG()); break; case ir.Namespace.Math: ir.OpList.replace<ir.CreateOp>(op, ng.namespaceMath()); break; } break; case ir.OpKind.Defer: const timerScheduling = !!op.loadingMinimumTime || !!op.loadingAfterTime || !!op.placeholderMinimumTime; ir.OpList.replace( op, ng.defer( op.handle.slot!, op.mainSlot.slot!, op.resolverFn, op.loadingSlot?.slot ?? null, op.placeholderSlot?.slot! ?? null, op.errorSlot?.slot ?? null, op.loadingConfig, op.placeholderConfig, timerScheduling, op.sourceSpan, ), ); break; case ir.OpKind.DeferOn: let args: number[] = []; switch (op.trigger.kind) { case ir.DeferTriggerKind.Never: case ir.DeferTriggerKind.Idle: case ir.DeferTriggerKind.Immediate: break; case ir.DeferTriggerKind.Timer: args = [op.trigger.delay]; break; case ir.DeferTriggerKind.Interaction: case ir.DeferTriggerKind.Hover: case ir.DeferTriggerKind.Viewport: // `hydrate` triggers don't support targets. if (op.modifier === ir.DeferOpModifierKind.HYDRATE) { args = []; } else { if (op.trigger.targetSlot?.slot == null || op.trigger.targetSlotViewSteps === null) { throw new Error( `Slot or view steps not set in trigger reification for trigger kind ${op.trigger.kind}`, ); } args = [op.trigger.targetSlot.slot]; if (op.trigger.targetSlotViewSteps !== 0) { args.push(op.trigger.targetSlotViewSteps); } } break; default: throw new Error( `AssertionError: Unsupported reification of defer trigger kind ${ (op.trigger as any).kind }`, ); } ir.OpList.replace(op, ng.deferOn(op.trigger.kind, args, op.modifier, op.sourceSpan)); break; case ir.OpKind.ProjectionDef: ir.OpList.replace<ir.CreateOp>(op, ng.projectionDef(op.def)); break; case ir.OpKind.Projection: if (op.handle.slot === null) { throw new Error('No slot was assigned for project instruction'); } let fallbackViewFnName: string | null = null; let fallbackDecls: number | null = null; let fallbackVars: number | null = null; if (op.fallbackView !== null) { if (!(unit instanceof ViewCompilationUnit)) { throw new Error(`AssertionError: must be compiling a component`); } const fallbackView = unit.job.views.get(op.fallbackView); if (fallbackView === undefined) { throw new Error( 'AssertionError: projection had fallback view xref, but fallback view was not found', ); } if ( fallbackView.fnName === null || fallbackView.decls === null || fallbackView.vars === null ) { throw new Error( `AssertionError: expected projection fallback view to have been named and counted`, ); } fallbackViewFnName = fallbackView.fnName; fallbackDecls = fallbackView.decls; fallbackVars = fallbackView.vars; } ir.OpList.replace<ir.CreateOp>( op, ng.projection( op.handle.slot!, op.projectionSlotIndex, op.attributes, fallbackViewFnName, fallbackDecls, fallbackVars, op.sourceSpan, ), ); break;
{ "end_byte": 11785, "start_byte": 2403, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/reify.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/reify.ts_11792_18924
case ir.OpKind.RepeaterCreate: if (op.handle.slot === null) { throw new Error('No slot was assigned for repeater instruction'); } if (!(unit instanceof ViewCompilationUnit)) { throw new Error(`AssertionError: must be compiling a component`); } const repeaterView = unit.job.views.get(op.xref)!; if (repeaterView.fnName === null) { throw new Error(`AssertionError: expected repeater primary view to have been named`); } let emptyViewFnName: string | null = null; let emptyDecls: number | null = null; let emptyVars: number | null = null; if (op.emptyView !== null) { const emptyView = unit.job.views.get(op.emptyView); if (emptyView === undefined) { throw new Error( 'AssertionError: repeater had empty view xref, but empty view was not found', ); } if (emptyView.fnName === null || emptyView.decls === null || emptyView.vars === null) { throw new Error( `AssertionError: expected repeater empty view to have been named and counted`, ); } emptyViewFnName = emptyView.fnName; emptyDecls = emptyView.decls; emptyVars = emptyView.vars; } ir.OpList.replace( op, ng.repeaterCreate( op.handle.slot, repeaterView.fnName, op.decls!, op.vars!, op.tag, op.attributes, op.trackByFn!, op.usesComponentInstance, emptyViewFnName, emptyDecls, emptyVars, op.emptyTag, op.emptyAttributes, op.wholeSourceSpan, ), ); break; case ir.OpKind.Statement: // Pass statement operations directly through. break; default: throw new Error( `AssertionError: Unsupported reification of create op ${ir.OpKind[op.kind]}`, ); } } } function reifyUpdateOperations(_unit: CompilationUnit, ops: ir.OpList<ir.UpdateOp>): void { for (const op of ops) { ir.transformExpressionsInOp(op, reifyIrExpression, ir.VisitorContextFlag.None); switch (op.kind) { case ir.OpKind.Advance: ir.OpList.replace(op, ng.advance(op.delta, op.sourceSpan)); break; case ir.OpKind.Property: if (op.expression instanceof ir.Interpolation) { ir.OpList.replace( op, ng.propertyInterpolate( op.name, op.expression.strings, op.expression.expressions, op.sanitizer, op.sourceSpan, ), ); } else { ir.OpList.replace(op, ng.property(op.name, op.expression, op.sanitizer, op.sourceSpan)); } break; case ir.OpKind.TwoWayProperty: ir.OpList.replace( op, ng.twoWayProperty(op.name, op.expression, op.sanitizer, op.sourceSpan), ); break; case ir.OpKind.StyleProp: if (op.expression instanceof ir.Interpolation) { ir.OpList.replace( op, ng.stylePropInterpolate( op.name, op.expression.strings, op.expression.expressions, op.unit, op.sourceSpan, ), ); } else { ir.OpList.replace(op, ng.styleProp(op.name, op.expression, op.unit, op.sourceSpan)); } break; case ir.OpKind.ClassProp: ir.OpList.replace(op, ng.classProp(op.name, op.expression, op.sourceSpan)); break; case ir.OpKind.StyleMap: if (op.expression instanceof ir.Interpolation) { ir.OpList.replace( op, ng.styleMapInterpolate(op.expression.strings, op.expression.expressions, op.sourceSpan), ); } else { ir.OpList.replace(op, ng.styleMap(op.expression, op.sourceSpan)); } break; case ir.OpKind.ClassMap: if (op.expression instanceof ir.Interpolation) { ir.OpList.replace( op, ng.classMapInterpolate(op.expression.strings, op.expression.expressions, op.sourceSpan), ); } else { ir.OpList.replace(op, ng.classMap(op.expression, op.sourceSpan)); } break; case ir.OpKind.I18nExpression: ir.OpList.replace(op, ng.i18nExp(op.expression, op.sourceSpan)); break; case ir.OpKind.I18nApply: ir.OpList.replace(op, ng.i18nApply(op.handle.slot!, op.sourceSpan)); break; case ir.OpKind.InterpolateText: ir.OpList.replace( op, ng.textInterpolate(op.interpolation.strings, op.interpolation.expressions, op.sourceSpan), ); break; case ir.OpKind.Attribute: if (op.expression instanceof ir.Interpolation) { ir.OpList.replace( op, ng.attributeInterpolate( op.name, op.expression.strings, op.expression.expressions, op.sanitizer, op.sourceSpan, ), ); } else { ir.OpList.replace(op, ng.attribute(op.name, op.expression, op.sanitizer, op.namespace)); } break; case ir.OpKind.HostProperty: if (op.expression instanceof ir.Interpolation) { throw new Error('not yet handled'); } else { if (op.isAnimationTrigger) { ir.OpList.replace(op, ng.syntheticHostProperty(op.name, op.expression, op.sourceSpan)); } else { ir.OpList.replace( op, ng.hostProperty(op.name, op.expression, op.sanitizer, op.sourceSpan), ); } } break; case ir.OpKind.Variable: if (op.variable.name === null) { throw new Error(`AssertionError: unnamed variable ${op.xref}`); } ir.OpList.replace<ir.UpdateOp>( op, ir.createStatementOp( new o.DeclareVarStmt(op.variable.name, op.initializer, undefined, o.StmtModifier.Final), ), ); break; case ir.OpKind.Conditional: if (op.processed === null) { throw new Error(`Conditional test was not set.`); } ir.OpList.replace(op, ng.conditional(op.processed, op.contextValue, op.sourceSpan)); break; case ir.OpKind.Repeater: ir.OpList.replace(op, ng.repeater(op.collection, op.sourceSpan)); break; case ir.OpKind.DeferWhen: ir.OpList.replace(op, ng.deferWhen(op.modifier, op.expr, op.sourceSpan)); break; case ir.OpKind.StoreLet: throw new Error(`AssertionError: unexpected storeLet ${op.declaredName}`); case ir.OpKind.Statement: // Pass statement operations directly through. break; default: throw new Error( `AssertionError: Unsupported reification of update op ${ir.OpKind[op.kind]}`, ); } } }
{ "end_byte": 18924, "start_byte": 11792, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/reify.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/reify.ts_18926_22659
function reifyIrExpression(expr: o.Expression): o.Expression { if (!ir.isIrExpression(expr)) { return expr; } switch (expr.kind) { case ir.ExpressionKind.NextContext: return ng.nextContext(expr.steps); case ir.ExpressionKind.Reference: return ng.reference(expr.targetSlot.slot! + 1 + expr.offset); case ir.ExpressionKind.LexicalRead: throw new Error(`AssertionError: unresolved LexicalRead of ${expr.name}`); case ir.ExpressionKind.TwoWayBindingSet: throw new Error(`AssertionError: unresolved TwoWayBindingSet`); case ir.ExpressionKind.RestoreView: if (typeof expr.view === 'number') { throw new Error(`AssertionError: unresolved RestoreView`); } return ng.restoreView(expr.view); case ir.ExpressionKind.ResetView: return ng.resetView(expr.expr); case ir.ExpressionKind.GetCurrentView: return ng.getCurrentView(); case ir.ExpressionKind.ReadVariable: if (expr.name === null) { throw new Error(`Read of unnamed variable ${expr.xref}`); } return o.variable(expr.name); case ir.ExpressionKind.ReadTemporaryExpr: if (expr.name === null) { throw new Error(`Read of unnamed temporary ${expr.xref}`); } return o.variable(expr.name); case ir.ExpressionKind.AssignTemporaryExpr: if (expr.name === null) { throw new Error(`Assign of unnamed temporary ${expr.xref}`); } return o.variable(expr.name).set(expr.expr); case ir.ExpressionKind.PureFunctionExpr: if (expr.fn === null) { throw new Error(`AssertionError: expected PureFunctions to have been extracted`); } return ng.pureFunction(expr.varOffset!, expr.fn, expr.args); case ir.ExpressionKind.PureFunctionParameterExpr: throw new Error(`AssertionError: expected PureFunctionParameterExpr to have been extracted`); case ir.ExpressionKind.PipeBinding: return ng.pipeBind(expr.targetSlot.slot!, expr.varOffset!, expr.args); case ir.ExpressionKind.PipeBindingVariadic: return ng.pipeBindV(expr.targetSlot.slot!, expr.varOffset!, expr.args); case ir.ExpressionKind.SlotLiteralExpr: return o.literal(expr.slot.slot!); case ir.ExpressionKind.ContextLetReference: return ng.readContextLet(expr.targetSlot.slot!); case ir.ExpressionKind.StoreLet: return ng.storeLet(expr.value, expr.sourceSpan); default: throw new Error( `AssertionError: Unsupported reification of ir.Expression kind: ${ ir.ExpressionKind[(expr as ir.Expression).kind] }`, ); } } /** * Listeners get turned into a function expression, which may or may not have the `$event` * parameter defined. */ function reifyListenerHandler( unit: CompilationUnit, name: string, handlerOps: ir.OpList<ir.UpdateOp>, consumesDollarEvent: boolean, ): o.FunctionExpr { // First, reify all instruction calls within `handlerOps`. reifyUpdateOperations(unit, handlerOps); // Next, extract all the `o.Statement`s from the reified operations. We can expect that at this // point, all operations have been converted to statements. const handlerStmts: o.Statement[] = []; for (const op of handlerOps) { if (op.kind !== ir.OpKind.Statement) { throw new Error( `AssertionError: expected reified statements, but found op ${ir.OpKind[op.kind]}`, ); } handlerStmts.push(op.statement); } // If `$event` is referenced, we need to generate it as a parameter. const params: o.FnParam[] = []; if (consumesDollarEvent) { // We need the `$event` parameter. params.push(new o.FnParam('$event')); } return o.fn(params, handlerStmts, undefined, undefined, name); }
{ "end_byte": 22659, "start_byte": 18926, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/reify.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/phase_remove_content_selectors.ts_0_1453
/** * @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 ir from '../../ir'; import type {CompilationJob} from '../compilation'; import {createOpXrefMap} from '../util/elements'; /** * Attributes of `ng-content` named 'select' are specifically removed, because they control which * content matches as a property of the `projection`, and are not a plain attribute. */ export function removeContentSelectors(job: CompilationJob): void { for (const unit of job.units) { const elements = createOpXrefMap(unit); for (const op of unit.ops()) { switch (op.kind) { case ir.OpKind.Binding: const target = lookupInXrefMap(elements, op.target); if (isSelectAttribute(op.name) && target.kind === ir.OpKind.Projection) { ir.OpList.remove<ir.UpdateOp>(op); } break; } } } } function isSelectAttribute(name: string) { return name.toLowerCase() === 'select'; } /** * Looks up an element in the given map by xref ID. */ function lookupInXrefMap( map: Map<ir.XrefId, ir.ConsumesSlotOpTrait & ir.CreateOp>, xref: ir.XrefId, ): ir.ConsumesSlotOpTrait & ir.CreateOp { const el = map.get(xref); if (el === undefined) { throw new Error('All attributes should have an slottable target.'); } return el; }
{ "end_byte": 1453, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/phase_remove_content_selectors.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/wrap_icus.ts_0_1407
/** * @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 ir from '../../ir'; import {CompilationJob} from '../compilation'; /** * Wraps ICUs that do not already belong to an i18n block in a new i18n block. */ export function wrapI18nIcus(job: CompilationJob): void { for (const unit of job.units) { let currentI18nOp: ir.I18nStartOp | null = null; let addedI18nId: ir.XrefId | null = null; for (const op of unit.create) { switch (op.kind) { case ir.OpKind.I18nStart: currentI18nOp = op; break; case ir.OpKind.I18nEnd: currentI18nOp = null; break; case ir.OpKind.IcuStart: if (currentI18nOp === null) { addedI18nId = job.allocateXrefId(); // ICU i18n start/end ops should not receive source spans. ir.OpList.insertBefore<ir.CreateOp>( ir.createI18nStartOp(addedI18nId, op.message, undefined, null), op, ); } break; case ir.OpKind.IcuEnd: if (addedI18nId !== null) { ir.OpList.insertAfter<ir.CreateOp>(ir.createI18nEndOp(addedI18nId, null), op); addedI18nId = null; } break; } } } }
{ "end_byte": 1407, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/wrap_icus.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/variable_optimization.ts_0_4644
/** * @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 * as ir from '../../ir'; import {CompilationJob} from '../compilation'; /** * Optimize variables declared and used in the IR. * * Variables are eagerly generated by pipeline stages for all possible values that could be * referenced. This stage processes the list of declared variables and all variable usages, * and optimizes where possible. It performs 3 main optimizations: * * * It transforms variable declarations to side effectful expressions when the * variable is not used, but its initializer has global effects which other * operations rely upon. * * It removes variable declarations if those variables are not referenced and * either they do not have global effects, or nothing relies on them. * * It inlines variable declarations when those variables are only used once * and the inlining is semantically safe. * * To guarantee correctness, analysis of "fences" in the instruction lists is used to determine * which optimizations are safe to perform. */ export function optimizeVariables(job: CompilationJob): void { for (const unit of job.units) { inlineAlwaysInlineVariables(unit.create); inlineAlwaysInlineVariables(unit.update); for (const op of unit.create) { if (op.kind === ir.OpKind.Listener || op.kind === ir.OpKind.TwoWayListener) { inlineAlwaysInlineVariables(op.handlerOps); } } optimizeVariablesInOpList(unit.create, job.compatibility); optimizeVariablesInOpList(unit.update, job.compatibility); for (const op of unit.create) { if (op.kind === ir.OpKind.Listener || op.kind === ir.OpKind.TwoWayListener) { optimizeVariablesInOpList(op.handlerOps, job.compatibility); } } } } /** * A [fence](https://en.wikipedia.org/wiki/Memory_barrier) flag for an expression which indicates * how that expression can be optimized in relation to other expressions or instructions. * * `Fence`s are a bitfield, so multiple flags may be set on a single expression. */ enum Fence { /** * Empty flag (no fence exists). */ None = 0b000, /** * A context read fence, meaning that the expression in question reads from the "current view" * context of the runtime. */ ViewContextRead = 0b001, /** * A context write fence, meaning that the expression in question writes to the "current view" * context of the runtime. * * Note that all `ContextWrite` fences are implicitly `ContextRead` fences as operations which * change the view context do so based on the current one. */ ViewContextWrite = 0b010, /** * Indicates that a call is required for its side-effects, even if nothing reads its result. * * This is also true of `ViewContextWrite` operations **if** they are followed by a * `ViewContextRead`. */ SideEffectful = 0b100, } /** * Summary data collected for each `Op` in a list. * * Tracking this data per operation allows the optimizer to process operations at a higher level * than always scanning expressions. */ interface OpInfo { /** * A `Set` of variables referenced by expressions in this operation. */ variablesUsed: Set<ir.XrefId>; /** * Flags indicating any `Fence`s present for this operation. */ fences: Fence; } function inlineAlwaysInlineVariables(ops: ir.OpList<ir.CreateOp | ir.UpdateOp>): void { const vars = new Map<ir.XrefId, ir.VariableOp<ir.CreateOp | ir.UpdateOp>>(); for (const op of ops) { if (op.kind === ir.OpKind.Variable && op.flags & ir.VariableFlags.AlwaysInline) { ir.visitExpressionsInOp(op, (expr) => { if (ir.isIrExpression(expr) && fencesForIrExpression(expr) !== Fence.None) { throw new Error(`AssertionError: A context-sensitive variable was marked AlwaysInline`); } }); vars.set(op.xref, op); } ir.transformExpressionsInOp( op, (expr) => { if (expr instanceof ir.ReadVariableExpr && vars.has(expr.xref)) { const varOp = vars.get(expr.xref)!; // Inline by cloning, because we might inline into multiple places. return varOp.initializer.clone(); } return expr; }, ir.VisitorContextFlag.None, ); } for (const op of vars.values()) { ir.OpList.remove(op as ir.CreateOp | ir.UpdateOp); } } /** * Process a list of operations and optimize variables within that list. */
{ "end_byte": 4644, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/variable_optimization.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/variable_optimization.ts_4645_13076
function optimizeVariablesInOpList( ops: ir.OpList<ir.CreateOp | ir.UpdateOp>, compatibility: ir.CompatibilityMode, ): void { const varDecls = new Map<ir.XrefId, ir.VariableOp<ir.CreateOp | ir.UpdateOp>>(); const varUsages = new Map<ir.XrefId, number>(); // Track variables that are used outside of the immediate operation list. For example, within // `ListenerOp` handler operations of listeners in the current operation list. const varRemoteUsages = new Set<ir.XrefId>(); const opMap = new Map<ir.CreateOp | ir.UpdateOp, OpInfo>(); // First, extract information about variables declared or used within the whole list. for (const op of ops) { if (op.kind === ir.OpKind.Variable) { if (varDecls.has(op.xref) || varUsages.has(op.xref)) { throw new Error(`Should not see two declarations of the same variable: ${op.xref}`); } varDecls.set(op.xref, op); varUsages.set(op.xref, 0); } opMap.set(op, collectOpInfo(op)); countVariableUsages(op, varUsages, varRemoteUsages); } // The next step is to remove any variable declarations for variables that aren't used. The // variable initializer expressions may be side-effectful, so they may need to be retained as // expression statements. // Track whether we've seen an operation which reads from the view context yet. This is used to // determine whether a write to the view context in a variable initializer can be observed. let contextIsUsed = false; // Note that iteration through the list happens in reverse, which guarantees that we'll process // all reads of a variable prior to processing its declaration. for (const op of ops.reversed()) { const opInfo = opMap.get(op)!; if (op.kind === ir.OpKind.Variable && varUsages.get(op.xref)! === 0) { // This variable is unused and can be removed. We might need to keep the initializer around, // though, if something depends on it running. if ( (contextIsUsed && opInfo.fences & Fence.ViewContextWrite) || opInfo.fences & Fence.SideEffectful ) { // This variable initializer has a side effect which must be retained. Either: // * it writes to the view context, and we know there is a future operation which depends // on that write, or // * it's an operation which is inherently side-effectful. // We can't remove the initializer, but we can remove the variable declaration itself and // replace it with a side-effectful statement. const stmtOp = ir.createStatementOp(op.initializer.toStmt()) as ir.UpdateOp; opMap.set(stmtOp, opInfo); ir.OpList.replace(op as ir.UpdateOp, stmtOp); } else { // It's safe to delete this entire variable declaration as nothing depends on it, even // side-effectfully. Note that doing this might make other variables unused. Since we're // iterating in reverse order, we should always be processing usages before declarations // and therefore by the time we get to a declaration, all removable usages will have been // removed. uncountVariableUsages(op, varUsages); ir.OpList.remove(op as ir.UpdateOp); } opMap.delete(op); varDecls.delete(op.xref); varUsages.delete(op.xref); continue; } // Does this operation depend on the view context? if (opInfo.fences & Fence.ViewContextRead) { contextIsUsed = true; } } // Next, inline any remaining variables with exactly one usage. const toInline: ir.XrefId[] = []; for (const [id, count] of varUsages) { const decl = varDecls.get(id)!; // We can inline variables that: // - are used exactly once, and // - are not used remotely // OR // - are marked for always inlining const isAlwaysInline = !!(decl.flags & ir.VariableFlags.AlwaysInline); if (count !== 1 || isAlwaysInline) { // We can't inline this variable as it's used more than once. continue; } if (varRemoteUsages.has(id)) { // This variable is used once, but across an operation boundary, so it can't be inlined. continue; } toInline.push(id); } let candidate: ir.XrefId | undefined; while ((candidate = toInline.pop())) { // We will attempt to inline this variable. If inlining fails (due to fences for example), // no future operation will make inlining legal. const decl = varDecls.get(candidate)!; const varInfo = opMap.get(decl as ir.CreateOp | ir.UpdateOp)!; const isAlwaysInline = !!(decl.flags & ir.VariableFlags.AlwaysInline); if (isAlwaysInline) { throw new Error( `AssertionError: Found an 'AlwaysInline' variable after the always inlining pass.`, ); } // Scan operations following the variable declaration and look for the point where that variable // is used. There should only be one usage given the precondition above. for ( let targetOp = decl.next!; targetOp.kind !== ir.OpKind.ListEnd; targetOp = targetOp.next! ) { const opInfo = opMap.get(targetOp)!; // Is the variable used in this operation? if (opInfo.variablesUsed.has(candidate)) { if ( compatibility === ir.CompatibilityMode.TemplateDefinitionBuilder && !allowConservativeInlining(decl, targetOp) ) { // We're in conservative mode, and this variable is not eligible for inlining into the // target operation in this mode. break; } // Yes, try to inline it. Inlining may not be successful if fences in this operation before // the variable's usage cannot be safely crossed. if (tryInlineVariableInitializer(candidate, decl.initializer, targetOp, varInfo.fences)) { // Inlining was successful! Update the tracking structures to reflect the inlined // variable. opInfo.variablesUsed.delete(candidate); // Add all variables used in the variable's initializer to its new usage site. for (const id of varInfo.variablesUsed) { opInfo.variablesUsed.add(id); } // Merge fences in the variable's initializer into its new usage site. opInfo.fences |= varInfo.fences; // Delete tracking info related to the declaration. varDecls.delete(candidate); varUsages.delete(candidate); opMap.delete(decl as ir.CreateOp | ir.UpdateOp); // And finally, delete the original declaration from the operation list. ir.OpList.remove(decl as ir.UpdateOp); } // Whether inlining succeeded or failed, we're done processing this variable. break; } // If the variable is not used in this operation, then we'd need to inline across it. Check if // that's safe to do. if (!safeToInlinePastFences(opInfo.fences, varInfo.fences)) { // We can't safely inline this variable beyond this operation, so don't proceed with // inlining this variable. break; } } } } /** * Given an `ir.Expression`, returns the `Fence` flags for that expression type. */ function fencesForIrExpression(expr: ir.Expression): Fence { switch (expr.kind) { case ir.ExpressionKind.NextContext: return Fence.ViewContextRead | Fence.ViewContextWrite; case ir.ExpressionKind.RestoreView: return Fence.ViewContextRead | Fence.ViewContextWrite | Fence.SideEffectful; case ir.ExpressionKind.StoreLet: return Fence.SideEffectful; case ir.ExpressionKind.Reference: case ir.ExpressionKind.ContextLetReference: return Fence.ViewContextRead; default: return Fence.None; } } /** * Build the `OpInfo` structure for the given `op`. This performs two operations: * * * It tracks which variables are used in the operation's expressions. * * It rolls up fence flags for expressions within the operation. */ function collectOpInfo(op: ir.CreateOp | ir.UpdateOp): OpInfo { let fences = Fence.None; const variablesUsed = new Set<ir.XrefId>(); ir.visitExpressionsInOp(op, (expr) => { if (!ir.isIrExpression(expr)) { return; } switch (expr.kind) { case ir.ExpressionKind.ReadVariable: variablesUsed.add(expr.xref); break; default: fences |= fencesForIrExpression(expr); } }); return {fences, variablesUsed}; }
{ "end_byte": 13076, "start_byte": 4645, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/variable_optimization.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/variable_optimization.ts_13078_18713
/** * Count the number of usages of each variable, being careful to track whether those usages are * local or remote. */ function countVariableUsages( op: ir.CreateOp | ir.UpdateOp, varUsages: Map<ir.XrefId, number>, varRemoteUsage: Set<ir.XrefId>, ): void { ir.visitExpressionsInOp(op, (expr, flags) => { if (!ir.isIrExpression(expr)) { return; } if (expr.kind !== ir.ExpressionKind.ReadVariable) { return; } const count = varUsages.get(expr.xref); if (count === undefined) { // This variable is declared outside the current scope of optimization. return; } varUsages.set(expr.xref, count + 1); if (flags & ir.VisitorContextFlag.InChildOperation) { varRemoteUsage.add(expr.xref); } }); } /** * Remove usages of a variable in `op` from the `varUsages` tracking. */ function uncountVariableUsages( op: ir.CreateOp | ir.UpdateOp, varUsages: Map<ir.XrefId, number>, ): void { ir.visitExpressionsInOp(op, (expr) => { if (!ir.isIrExpression(expr)) { return; } if (expr.kind !== ir.ExpressionKind.ReadVariable) { return; } const count = varUsages.get(expr.xref); if (count === undefined) { // This variable is declared outside the current scope of optimization. return; } else if (count === 0) { throw new Error( `Inaccurate variable count: ${expr.xref} - found another read but count is already 0`, ); } varUsages.set(expr.xref, count - 1); }); } /** * Checks whether it's safe to inline a variable across a particular operation. * * @param fences the fences of the operation which the inlining will cross * @param declFences the fences of the variable being inlined. */ function safeToInlinePastFences(fences: Fence, declFences: Fence): boolean { if (fences & Fence.ViewContextWrite) { // It's not safe to inline context reads across context writes. if (declFences & Fence.ViewContextRead) { return false; } } else if (fences & Fence.ViewContextRead) { // It's not safe to inline context writes across context reads. if (declFences & Fence.ViewContextWrite) { return false; } } return true; } /** * Attempt to inline the initializer of a variable into a target operation's expressions. * * This may or may not be safe to do. For example, the variable could be read following the * execution of an expression with fences that don't permit the variable to be inlined across them. */ function tryInlineVariableInitializer( id: ir.XrefId, initializer: o.Expression, target: ir.CreateOp | ir.UpdateOp, declFences: Fence, ): boolean { // We use `ir.transformExpressionsInOp` to walk the expressions and inline the variable if // possible. Since this operation is callback-based, once inlining succeeds or fails we can't // "stop" the expression processing, and have to keep track of whether inlining has succeeded or // is no longer allowed. let inlined = false; let inliningAllowed = true; ir.transformExpressionsInOp( target, (expr, flags) => { if (!ir.isIrExpression(expr)) { return expr; } if (inlined || !inliningAllowed) { // Either the inlining has already succeeded, or we've passed a fence that disallows inlining // at this point, so don't try. return expr; } else if ( flags & ir.VisitorContextFlag.InChildOperation && declFences & Fence.ViewContextRead ) { // We cannot inline variables that are sensitive to the current context across operation // boundaries. return expr; } switch (expr.kind) { case ir.ExpressionKind.ReadVariable: if (expr.xref === id) { // This is the usage site of the variable. Since nothing has disallowed inlining, it's // safe to inline the initializer here. inlined = true; return initializer; } break; default: // For other types of `ir.Expression`s, whether inlining is allowed depends on their fences. const exprFences = fencesForIrExpression(expr); inliningAllowed = inliningAllowed && safeToInlinePastFences(exprFences, declFences); break; } return expr; }, ir.VisitorContextFlag.None, ); return inlined; } /** * Determines whether inlining of `decl` should be allowed in "conservative" mode. * * In conservative mode, inlining behavior is limited to those operations which the * `TemplateDefinitionBuilder` supported, with the goal of producing equivalent output. */ function allowConservativeInlining( decl: ir.VariableOp<ir.CreateOp | ir.UpdateOp>, target: ir.Op<ir.CreateOp | ir.UpdateOp>, ): boolean { // TODO(alxhub): understand exactly how TemplateDefinitionBuilder approaches inlining, and record // that behavior here. switch (decl.variable.kind) { case ir.SemanticVariableKind.Identifier: if (decl.initializer instanceof o.ReadVarExpr && decl.initializer.name === 'ctx') { // Although TemplateDefinitionBuilder is cautious about inlining, we still want to do so // when the variable is the context, to imitate its behavior with aliases in control flow // blocks. This quirky behavior will become dead code once compatibility mode is no longer // supported. return true; } return false; case ir.SemanticVariableKind.Context: // Context can only be inlined into other variables. return target.kind === ir.OpKind.Variable; default: return true; } }
{ "end_byte": 18713, "start_byte": 13078, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/variable_optimization.ts" }
angular/packages/compiler/src/template/pipeline/src/phases/resolve_i18n_expression_placeholders.ts_0_3109
/** * @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 ir from '../../ir'; import {ComponentCompilationJob} from '../compilation'; /** * Resolve the i18n expression placeholders in i18n messages. */ export function resolveI18nExpressionPlaceholders(job: ComponentCompilationJob) { // Record all of the i18n context ops, and the sub-template index for each i18n op. const subTemplateIndices = new Map<ir.XrefId, number | null>(); const i18nContexts = new Map<ir.XrefId, ir.I18nContextOp>(); const icuPlaceholders = new Map<ir.XrefId, ir.IcuPlaceholderOp>(); for (const unit of job.units) { for (const op of unit.create) { switch (op.kind) { case ir.OpKind.I18nStart: subTemplateIndices.set(op.xref, op.subTemplateIndex); break; case ir.OpKind.I18nContext: i18nContexts.set(op.xref, op); break; case ir.OpKind.IcuPlaceholder: icuPlaceholders.set(op.xref, op); break; } } } // Keep track of the next available expression index for each i18n message. const expressionIndices = new Map<ir.XrefId, number>(); // Keep track of a reference index for each expression. // We use different references for normal i18n expressio and attribute i18n expressions. This is // because child i18n blocks in templates don't get their own context, since they're rolled into // the translated message of the parent, but they may target a different slot. const referenceIndex = (op: ir.I18nExpressionOp): ir.XrefId => op.usage === ir.I18nExpressionFor.I18nText ? op.i18nOwner : op.context; for (const unit of job.units) { for (const op of unit.update) { if (op.kind === ir.OpKind.I18nExpression) { const index = expressionIndices.get(referenceIndex(op)) || 0; const subTemplateIndex = subTemplateIndices.get(op.i18nOwner) ?? null; const value: ir.I18nParamValue = { value: index, subTemplateIndex: subTemplateIndex, flags: ir.I18nParamValueFlags.ExpressionIndex, }; updatePlaceholder(op, value, i18nContexts, icuPlaceholders); expressionIndices.set(referenceIndex(op), index + 1); } } } } function updatePlaceholder( op: ir.I18nExpressionOp, value: ir.I18nParamValue, i18nContexts: Map<ir.XrefId, ir.I18nContextOp>, icuPlaceholders: Map<ir.XrefId, ir.IcuPlaceholderOp>, ) { if (op.i18nPlaceholder !== null) { const i18nContext = i18nContexts.get(op.context)!; const params = op.resolutionTime === ir.I18nParamResolutionTime.Creation ? i18nContext.params : i18nContext.postprocessingParams; const values = params.get(op.i18nPlaceholder) || []; values.push(value); params.set(op.i18nPlaceholder, values); } if (op.icuPlaceholder !== null) { const icuPlaceholderOp = icuPlaceholders.get(op.icuPlaceholder); icuPlaceholderOp?.expressionPlaceholders.push(value); } }
{ "end_byte": 3109, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/resolve_i18n_expression_placeholders.ts" }
angular/packages/compiler/src/output/output_ast.ts_0_4310
/** * @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 {computeMsgId} from '../i18n/digest'; import {Message} from '../i18n/i18n_ast'; import {ParseSourceSpan} from '../parse_util'; import {I18nMeta} from '../render3/view/i18n/meta'; //// Types export enum TypeModifier { None = 0, Const = 1 << 0, } export abstract class Type { constructor(public modifiers: TypeModifier = TypeModifier.None) {} abstract visitType(visitor: TypeVisitor, context: any): any; hasModifier(modifier: TypeModifier): boolean { return (this.modifiers & modifier) !== 0; } } export enum BuiltinTypeName { Dynamic, Bool, String, Int, Number, Function, Inferred, None, } export class BuiltinType extends Type { constructor( public name: BuiltinTypeName, modifiers?: TypeModifier, ) { super(modifiers); } override visitType(visitor: TypeVisitor, context: any): any { return visitor.visitBuiltinType(this, context); } } export class ExpressionType extends Type { constructor( public value: Expression, modifiers?: TypeModifier, public typeParams: Type[] | null = null, ) { super(modifiers); } override visitType(visitor: TypeVisitor, context: any): any { return visitor.visitExpressionType(this, context); } } export class ArrayType extends Type { constructor( public of: Type, modifiers?: TypeModifier, ) { super(modifiers); } override visitType(visitor: TypeVisitor, context: any): any { return visitor.visitArrayType(this, context); } } export class MapType extends Type { public valueType: Type | null; constructor(valueType: Type | null | undefined, modifiers?: TypeModifier) { super(modifiers); this.valueType = valueType || null; } override visitType(visitor: TypeVisitor, context: any): any { return visitor.visitMapType(this, context); } } export class TransplantedType<T> extends Type { constructor( readonly type: T, modifiers?: TypeModifier, ) { super(modifiers); } override visitType(visitor: TypeVisitor, context: any): any { return visitor.visitTransplantedType(this, context); } } export const DYNAMIC_TYPE = new BuiltinType(BuiltinTypeName.Dynamic); export const INFERRED_TYPE = new BuiltinType(BuiltinTypeName.Inferred); export const BOOL_TYPE = new BuiltinType(BuiltinTypeName.Bool); export const INT_TYPE = new BuiltinType(BuiltinTypeName.Int); export const NUMBER_TYPE = new BuiltinType(BuiltinTypeName.Number); export const STRING_TYPE = new BuiltinType(BuiltinTypeName.String); export const FUNCTION_TYPE = new BuiltinType(BuiltinTypeName.Function); export const NONE_TYPE = new BuiltinType(BuiltinTypeName.None); export interface TypeVisitor { visitBuiltinType(type: BuiltinType, context: any): any; visitExpressionType(type: ExpressionType, context: any): any; visitArrayType(type: ArrayType, context: any): any; visitMapType(type: MapType, context: any): any; visitTransplantedType(type: TransplantedType<unknown>, context: any): any; } ///// Expressions export enum UnaryOperator { Minus, Plus, } export enum BinaryOperator { Equals, NotEquals, Identical, NotIdentical, Minus, Plus, Divide, Multiply, Modulo, And, Or, BitwiseOr, BitwiseAnd, Lower, LowerEquals, Bigger, BiggerEquals, NullishCoalesce, } export function nullSafeIsEquivalent<T extends {isEquivalent(other: T): boolean}>( base: T | null, other: T | null, ) { if (base == null || other == null) { return base == other; } return base.isEquivalent(other); } function areAllEquivalentPredicate<T>( base: T[], other: T[], equivalentPredicate: (baseElement: T, otherElement: T) => boolean, ) { const len = base.length; if (len !== other.length) { return false; } for (let i = 0; i < len; i++) { if (!equivalentPredicate(base[i], other[i])) { return false; } } return true; } export function areAllEquivalent<T extends {isEquivalent(other: T): boolean}>( base: T[], other: T[], ) { return areAllEquivalentPredicate(base, other, (baseElement: T, otherElement: T) => baseElement.isEquivalent(otherElement), ); }
{ "end_byte": 4310, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/output_ast.ts" }
angular/packages/compiler/src/output/output_ast.ts_4312_12574
export abstract class Expression { public type: Type | null; public sourceSpan: ParseSourceSpan | null; constructor(type: Type | null | undefined, sourceSpan?: ParseSourceSpan | null) { this.type = type || null; this.sourceSpan = sourceSpan || null; } abstract visitExpression(visitor: ExpressionVisitor, context: any): any; /** * Calculates whether this expression produces the same value as the given expression. * Note: We don't check Types nor ParseSourceSpans nor function arguments. */ abstract isEquivalent(e: Expression): boolean; /** * Return true if the expression is constant. */ abstract isConstant(): boolean; abstract clone(): Expression; prop(name: string, sourceSpan?: ParseSourceSpan | null): ReadPropExpr { return new ReadPropExpr(this, name, null, sourceSpan); } key(index: Expression, type?: Type | null, sourceSpan?: ParseSourceSpan | null): ReadKeyExpr { return new ReadKeyExpr(this, index, type, sourceSpan); } callFn( params: Expression[], sourceSpan?: ParseSourceSpan | null, pure?: boolean, ): InvokeFunctionExpr { return new InvokeFunctionExpr(this, params, null, sourceSpan, pure); } instantiate( params: Expression[], type?: Type | null, sourceSpan?: ParseSourceSpan | null, ): InstantiateExpr { return new InstantiateExpr(this, params, type, sourceSpan); } conditional( trueCase: Expression, falseCase: Expression | null = null, sourceSpan?: ParseSourceSpan | null, ): ConditionalExpr { return new ConditionalExpr(this, trueCase, falseCase, null, sourceSpan); } equals(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.Equals, this, rhs, null, sourceSpan); } notEquals(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.NotEquals, this, rhs, null, sourceSpan); } identical(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.Identical, this, rhs, null, sourceSpan); } notIdentical(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.NotIdentical, this, rhs, null, sourceSpan); } minus(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.Minus, this, rhs, null, sourceSpan); } plus(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.Plus, this, rhs, null, sourceSpan); } divide(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.Divide, this, rhs, null, sourceSpan); } multiply(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.Multiply, this, rhs, null, sourceSpan); } modulo(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.Modulo, this, rhs, null, sourceSpan); } and(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.And, this, rhs, null, sourceSpan); } bitwiseOr( rhs: Expression, sourceSpan?: ParseSourceSpan | null, parens: boolean = true, ): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.BitwiseOr, this, rhs, null, sourceSpan, parens); } bitwiseAnd( rhs: Expression, sourceSpan?: ParseSourceSpan | null, parens: boolean = true, ): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.BitwiseAnd, this, rhs, null, sourceSpan, parens); } or(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.Or, this, rhs, null, sourceSpan); } lower(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.Lower, this, rhs, null, sourceSpan); } lowerEquals(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.LowerEquals, this, rhs, null, sourceSpan); } bigger(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.Bigger, this, rhs, null, sourceSpan); } biggerEquals(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.BiggerEquals, this, rhs, null, sourceSpan); } isBlank(sourceSpan?: ParseSourceSpan | null): Expression { // Note: We use equals by purpose here to compare to null and undefined in JS. // We use the typed null to allow strictNullChecks to narrow types. return this.equals(TYPED_NULL_EXPR, sourceSpan); } nullishCoalesce(rhs: Expression, sourceSpan?: ParseSourceSpan | null): BinaryOperatorExpr { return new BinaryOperatorExpr(BinaryOperator.NullishCoalesce, this, rhs, null, sourceSpan); } toStmt(): Statement { return new ExpressionStatement(this, null); } } export class ReadVarExpr extends Expression { constructor( public name: string, type?: Type | null, sourceSpan?: ParseSourceSpan | null, ) { super(type, sourceSpan); } override isEquivalent(e: Expression): boolean { return e instanceof ReadVarExpr && this.name === e.name; } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitReadVarExpr(this, context); } override clone(): ReadVarExpr { return new ReadVarExpr(this.name, this.type, this.sourceSpan); } set(value: Expression): WriteVarExpr { return new WriteVarExpr(this.name, value, null, this.sourceSpan); } } export class TypeofExpr extends Expression { constructor( public expr: Expression, type?: Type | null, sourceSpan?: ParseSourceSpan | null, ) { super(type, sourceSpan); } override visitExpression(visitor: ExpressionVisitor, context: any) { return visitor.visitTypeofExpr(this, context); } override isEquivalent(e: Expression): boolean { return e instanceof TypeofExpr && e.expr.isEquivalent(this.expr); } override isConstant(): boolean { return this.expr.isConstant(); } override clone(): TypeofExpr { return new TypeofExpr(this.expr.clone()); } } export class WrappedNodeExpr<T> extends Expression { constructor( public node: T, type?: Type | null, sourceSpan?: ParseSourceSpan | null, ) { super(type, sourceSpan); } override isEquivalent(e: Expression): boolean { return e instanceof WrappedNodeExpr && this.node === e.node; } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitWrappedNodeExpr(this, context); } override clone(): WrappedNodeExpr<T> { return new WrappedNodeExpr(this.node, this.type, this.sourceSpan); } } export class WriteVarExpr extends Expression { public value: Expression; constructor( public name: string, value: Expression, type?: Type | null, sourceSpan?: ParseSourceSpan | null, ) { super(type || value.type, sourceSpan); this.value = value; } override isEquivalent(e: Expression): boolean { return e instanceof WriteVarExpr && this.name === e.name && this.value.isEquivalent(e.value); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitWriteVarExpr(this, context); } override clone(): WriteVarExpr { return new WriteVarExpr(this.name, this.value.clone(), this.type, this.sourceSpan); } toDeclStmt(type?: Type | null, modifiers?: StmtModifier): DeclareVarStmt { return new DeclareVarStmt(this.name, this.value, type, modifiers, this.sourceSpan); } toConstDecl(): DeclareVarStmt { return this.toDeclStmt(INFERRED_TYPE, StmtModifier.Final); } }
{ "end_byte": 12574, "start_byte": 4312, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/output_ast.ts" }
angular/packages/compiler/src/output/output_ast.ts_12576_20005
export class WriteKeyExpr extends Expression { public value: Expression; constructor( public receiver: Expression, public index: Expression, value: Expression, type?: Type | null, sourceSpan?: ParseSourceSpan | null, ) { super(type || value.type, sourceSpan); this.value = value; } override isEquivalent(e: Expression): boolean { return ( e instanceof WriteKeyExpr && this.receiver.isEquivalent(e.receiver) && this.index.isEquivalent(e.index) && this.value.isEquivalent(e.value) ); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitWriteKeyExpr(this, context); } override clone(): WriteKeyExpr { return new WriteKeyExpr( this.receiver.clone(), this.index.clone(), this.value.clone(), this.type, this.sourceSpan, ); } } export class WritePropExpr extends Expression { public value: Expression; constructor( public receiver: Expression, public name: string, value: Expression, type?: Type | null, sourceSpan?: ParseSourceSpan | null, ) { super(type || value.type, sourceSpan); this.value = value; } override isEquivalent(e: Expression): boolean { return ( e instanceof WritePropExpr && this.receiver.isEquivalent(e.receiver) && this.name === e.name && this.value.isEquivalent(e.value) ); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitWritePropExpr(this, context); } override clone(): WritePropExpr { return new WritePropExpr( this.receiver.clone(), this.name, this.value.clone(), this.type, this.sourceSpan, ); } } export class InvokeFunctionExpr extends Expression { constructor( public fn: Expression, public args: Expression[], type?: Type | null, sourceSpan?: ParseSourceSpan | null, public pure = false, ) { super(type, sourceSpan); } // An alias for fn, which allows other logic to handle calls and property reads together. get receiver(): Expression { return this.fn; } override isEquivalent(e: Expression): boolean { return ( e instanceof InvokeFunctionExpr && this.fn.isEquivalent(e.fn) && areAllEquivalent(this.args, e.args) && this.pure === e.pure ); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitInvokeFunctionExpr(this, context); } override clone(): InvokeFunctionExpr { return new InvokeFunctionExpr( this.fn.clone(), this.args.map((arg) => arg.clone()), this.type, this.sourceSpan, this.pure, ); } } export class TaggedTemplateExpr extends Expression { constructor( public tag: Expression, public template: TemplateLiteral, type?: Type | null, sourceSpan?: ParseSourceSpan | null, ) { super(type, sourceSpan); } override isEquivalent(e: Expression): boolean { return ( e instanceof TaggedTemplateExpr && this.tag.isEquivalent(e.tag) && areAllEquivalentPredicate( this.template.elements, e.template.elements, (a, b) => a.text === b.text, ) && areAllEquivalent(this.template.expressions, e.template.expressions) ); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitTaggedTemplateExpr(this, context); } override clone(): TaggedTemplateExpr { return new TaggedTemplateExpr( this.tag.clone(), this.template.clone(), this.type, this.sourceSpan, ); } } export class InstantiateExpr extends Expression { constructor( public classExpr: Expression, public args: Expression[], type?: Type | null, sourceSpan?: ParseSourceSpan | null, ) { super(type, sourceSpan); } override isEquivalent(e: Expression): boolean { return ( e instanceof InstantiateExpr && this.classExpr.isEquivalent(e.classExpr) && areAllEquivalent(this.args, e.args) ); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitInstantiateExpr(this, context); } override clone(): InstantiateExpr { return new InstantiateExpr( this.classExpr.clone(), this.args.map((arg) => arg.clone()), this.type, this.sourceSpan, ); } } export class LiteralExpr extends Expression { constructor( public value: number | string | boolean | null | undefined, type?: Type | null, sourceSpan?: ParseSourceSpan | null, ) { super(type, sourceSpan); } override isEquivalent(e: Expression): boolean { return e instanceof LiteralExpr && this.value === e.value; } override isConstant() { return true; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitLiteralExpr(this, context); } override clone(): LiteralExpr { return new LiteralExpr(this.value, this.type, this.sourceSpan); } } export class TemplateLiteral { constructor( public elements: TemplateLiteralElement[], public expressions: Expression[], ) {} clone(): TemplateLiteral { return new TemplateLiteral( this.elements.map((el) => el.clone()), this.expressions.map((expr) => expr.clone()), ); } } export class TemplateLiteralElement { rawText: string; constructor( public text: string, public sourceSpan?: ParseSourceSpan, rawText?: string, ) { // If `rawText` is not provided, try to extract the raw string from its // associated `sourceSpan`. If that is also not available, "fake" the raw // string instead by escaping the following control sequences: // - "\" would otherwise indicate that the next character is a control character. // - "`" and "${" are template string control sequences that would otherwise prematurely // indicate the end of the template literal element. this.rawText = rawText ?? sourceSpan?.toString() ?? escapeForTemplateLiteral(escapeSlashes(text)); } clone(): TemplateLiteralElement { return new TemplateLiteralElement(this.text, this.sourceSpan, this.rawText); } } export class LiteralPiece { constructor( public text: string, public sourceSpan: ParseSourceSpan, ) {} } export class PlaceholderPiece { /** * Create a new instance of a `PlaceholderPiece`. * * @param text the name of this placeholder (e.g. `PH_1`). * @param sourceSpan the location of this placeholder in its localized message the source code. * @param associatedMessage reference to another message that this placeholder is associated with. * The `associatedMessage` is mainly used to provide a relationship to an ICU message that has * been extracted out from the message containing the placeholder. */ constructor( public text: string, public sourceSpan: ParseSourceSpan, public associatedMessage?: Message, ) {} } export type MessagePiece = LiteralPiece | PlaceholderPiece; const MEANING_SEPARATOR = '|'; const ID_SEPARATOR = '@@'; const LEGACY_ID_INDICATOR = '␟';
{ "end_byte": 20005, "start_byte": 12576, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/output_ast.ts" }
angular/packages/compiler/src/output/output_ast.ts_20007_28394
port class LocalizedString extends Expression { constructor( readonly metaBlock: I18nMeta, readonly messageParts: LiteralPiece[], readonly placeHolderNames: PlaceholderPiece[], readonly expressions: Expression[], sourceSpan?: ParseSourceSpan | null, ) { super(STRING_TYPE, sourceSpan); } override isEquivalent(e: Expression): boolean { // return e instanceof LocalizedString && this.message === e.message; return false; } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitLocalizedString(this, context); } override clone(): LocalizedString { return new LocalizedString( this.metaBlock, this.messageParts, this.placeHolderNames, this.expressions.map((expr) => expr.clone()), this.sourceSpan, ); } /** * Serialize the given `meta` and `messagePart` into "cooked" and "raw" strings that can be used * in a `$localize` tagged string. The format of the metadata is the same as that parsed by * `parseI18nMeta()`. * * @param meta The metadata to serialize * @param messagePart The first part of the tagged string */ serializeI18nHead(): CookedRawString { let metaBlock = this.metaBlock.description || ''; if (this.metaBlock.meaning) { metaBlock = `${this.metaBlock.meaning}${MEANING_SEPARATOR}${metaBlock}`; } if (this.metaBlock.customId) { metaBlock = `${metaBlock}${ID_SEPARATOR}${this.metaBlock.customId}`; } if (this.metaBlock.legacyIds) { this.metaBlock.legacyIds.forEach((legacyId) => { metaBlock = `${metaBlock}${LEGACY_ID_INDICATOR}${legacyId}`; }); } return createCookedRawString( metaBlock, this.messageParts[0].text, this.getMessagePartSourceSpan(0), ); } getMessagePartSourceSpan(i: number): ParseSourceSpan | null { return this.messageParts[i]?.sourceSpan ?? this.sourceSpan; } getPlaceholderSourceSpan(i: number): ParseSourceSpan { return ( this.placeHolderNames[i]?.sourceSpan ?? this.expressions[i]?.sourceSpan ?? this.sourceSpan ); } /** * Serialize the given `placeholderName` and `messagePart` into "cooked" and "raw" strings that * can be used in a `$localize` tagged string. * * The format is `:<placeholder-name>[@@<associated-id>]:`. * * The `associated-id` is the message id of the (usually an ICU) message to which this placeholder * refers. * * @param partIndex The index of the message part to serialize. */ serializeI18nTemplatePart(partIndex: number): CookedRawString { const placeholder = this.placeHolderNames[partIndex - 1]; const messagePart = this.messageParts[partIndex]; let metaBlock = placeholder.text; if (placeholder.associatedMessage?.legacyIds.length === 0) { metaBlock += `${ID_SEPARATOR}${computeMsgId( placeholder.associatedMessage.messageString, placeholder.associatedMessage.meaning, )}`; } return createCookedRawString( metaBlock, messagePart.text, this.getMessagePartSourceSpan(partIndex), ); } } /** * A structure to hold the cooked and raw strings of a template literal element, along with its * source-span range. */ export interface CookedRawString { cooked: string; raw: string; range: ParseSourceSpan | null; } const escapeSlashes = (str: string): string => str.replace(/\\/g, '\\\\'); const escapeStartingColon = (str: string): string => str.replace(/^:/, '\\:'); const escapeColons = (str: string): string => str.replace(/:/g, '\\:'); const escapeForTemplateLiteral = (str: string): string => str.replace(/`/g, '\\`').replace(/\${/g, '$\\{'); /** * Creates a `{cooked, raw}` object from the `metaBlock` and `messagePart`. * * The `raw` text must have various character sequences escaped: * * "\" would otherwise indicate that the next character is a control character. * * "`" and "${" are template string control sequences that would otherwise prematurely indicate * the end of a message part. * * ":" inside a metablock would prematurely indicate the end of the metablock. * * ":" at the start of a messagePart with no metablock would erroneously indicate the start of a * metablock. * * @param metaBlock Any metadata that should be prepended to the string * @param messagePart The message part of the string */ function createCookedRawString( metaBlock: string, messagePart: string, range: ParseSourceSpan | null, ): CookedRawString { if (metaBlock === '') { return { cooked: messagePart, raw: escapeForTemplateLiteral(escapeStartingColon(escapeSlashes(messagePart))), range, }; } else { return { cooked: `:${metaBlock}:${messagePart}`, raw: escapeForTemplateLiteral( `:${escapeColons(escapeSlashes(metaBlock))}:${escapeSlashes(messagePart)}`, ), range, }; } } export class ExternalExpr extends Expression { constructor( public value: ExternalReference, type?: Type | null, public typeParams: Type[] | null = null, sourceSpan?: ParseSourceSpan | null, ) { super(type, sourceSpan); } override isEquivalent(e: Expression): boolean { return ( e instanceof ExternalExpr && this.value.name === e.value.name && this.value.moduleName === e.value.moduleName && this.value.runtime === e.value.runtime ); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitExternalExpr(this, context); } override clone(): ExternalExpr { return new ExternalExpr(this.value, this.type, this.typeParams, this.sourceSpan); } } export class ExternalReference { constructor( public moduleName: string | null, public name: string | null, public runtime?: any | null, ) {} // Note: no isEquivalent method here as we use this as an interface too. } export class ConditionalExpr extends Expression { public trueCase: Expression; constructor( public condition: Expression, trueCase: Expression, public falseCase: Expression | null = null, type?: Type | null, sourceSpan?: ParseSourceSpan | null, ) { super(type || trueCase.type, sourceSpan); this.trueCase = trueCase; } override isEquivalent(e: Expression): boolean { return ( e instanceof ConditionalExpr && this.condition.isEquivalent(e.condition) && this.trueCase.isEquivalent(e.trueCase) && nullSafeIsEquivalent(this.falseCase, e.falseCase) ); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitConditionalExpr(this, context); } override clone(): ConditionalExpr { return new ConditionalExpr( this.condition.clone(), this.trueCase.clone(), this.falseCase?.clone(), this.type, this.sourceSpan, ); } } export class DynamicImportExpr extends Expression { constructor( public url: string | Expression, sourceSpan?: ParseSourceSpan | null, public urlComment?: string, ) { super(null, sourceSpan); } override isEquivalent(e: Expression): boolean { return e instanceof DynamicImportExpr && this.url === e.url && this.urlComment === e.urlComment; } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitDynamicImportExpr(this, context); } override clone(): DynamicImportExpr { return new DynamicImportExpr( typeof this.url === 'string' ? this.url : this.url.clone(), this.sourceSpan, this.urlComment, ); } } export class NotExpr extends Expression { constructor( public condition: Expression, sourceSpan?: ParseSourceSpan | null, ) { super(BOOL_TYPE, sourceSpan); } override isEquivalent(e: Expression): boolean { return e instanceof NotExpr && this.condition.isEquivalent(e.condition); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitNotExpr(this, context); } override clone(): NotExpr { return new NotExpr(this.condition.clone(), this.sourceSpan); } }
{ "end_byte": 28394, "start_byte": 20007, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/output_ast.ts" }
angular/packages/compiler/src/output/output_ast.ts_28396_37011
port class FnParam { constructor( public name: string, public type: Type | null = null, ) {} isEquivalent(param: FnParam): boolean { return this.name === param.name; } clone(): FnParam { return new FnParam(this.name, this.type); } } export class FunctionExpr extends Expression { constructor( public params: FnParam[], public statements: Statement[], type?: Type | null, sourceSpan?: ParseSourceSpan | null, public name?: string | null, ) { super(type, sourceSpan); } override isEquivalent(e: Expression | Statement): boolean { return ( (e instanceof FunctionExpr || e instanceof DeclareFunctionStmt) && areAllEquivalent(this.params, e.params) && areAllEquivalent(this.statements, e.statements) ); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitFunctionExpr(this, context); } toDeclStmt(name: string, modifiers?: StmtModifier): DeclareFunctionStmt { return new DeclareFunctionStmt( name, this.params, this.statements, this.type, modifiers, this.sourceSpan, ); } override clone(): FunctionExpr { // TODO: Should we deep clone statements? return new FunctionExpr( this.params.map((p) => p.clone()), this.statements, this.type, this.sourceSpan, this.name, ); } } export class ArrowFunctionExpr extends Expression { // Note that `body: Expression` represents `() => expr` whereas // `body: Statement[]` represents `() => { expr }`. constructor( public params: FnParam[], public body: Expression | Statement[], type?: Type | null, sourceSpan?: ParseSourceSpan | null, ) { super(type, sourceSpan); } override isEquivalent(e: Expression): boolean { if (!(e instanceof ArrowFunctionExpr) || !areAllEquivalent(this.params, e.params)) { return false; } if (this.body instanceof Expression && e.body instanceof Expression) { return this.body.isEquivalent(e.body); } if (Array.isArray(this.body) && Array.isArray(e.body)) { return areAllEquivalent(this.body, e.body); } return false; } override isConstant(): boolean { return false; } override visitExpression(visitor: ExpressionVisitor, context: any) { return visitor.visitArrowFunctionExpr(this, context); } override clone(): Expression { // TODO: Should we deep clone statements? return new ArrowFunctionExpr( this.params.map((p) => p.clone()), Array.isArray(this.body) ? this.body : this.body.clone(), this.type, this.sourceSpan, ); } toDeclStmt(name: string, modifiers?: StmtModifier): DeclareVarStmt { return new DeclareVarStmt(name, this, INFERRED_TYPE, modifiers, this.sourceSpan); } } export class UnaryOperatorExpr extends Expression { constructor( public operator: UnaryOperator, public expr: Expression, type?: Type | null, sourceSpan?: ParseSourceSpan | null, public parens: boolean = true, ) { super(type || NUMBER_TYPE, sourceSpan); } override isEquivalent(e: Expression): boolean { return ( e instanceof UnaryOperatorExpr && this.operator === e.operator && this.expr.isEquivalent(e.expr) ); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitUnaryOperatorExpr(this, context); } override clone(): UnaryOperatorExpr { return new UnaryOperatorExpr( this.operator, this.expr.clone(), this.type, this.sourceSpan, this.parens, ); } } export class BinaryOperatorExpr extends Expression { public lhs: Expression; constructor( public operator: BinaryOperator, lhs: Expression, public rhs: Expression, type?: Type | null, sourceSpan?: ParseSourceSpan | null, public parens: boolean = true, ) { super(type || lhs.type, sourceSpan); this.lhs = lhs; } override isEquivalent(e: Expression): boolean { return ( e instanceof BinaryOperatorExpr && this.operator === e.operator && this.lhs.isEquivalent(e.lhs) && this.rhs.isEquivalent(e.rhs) ); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitBinaryOperatorExpr(this, context); } override clone(): BinaryOperatorExpr { return new BinaryOperatorExpr( this.operator, this.lhs.clone(), this.rhs.clone(), this.type, this.sourceSpan, this.parens, ); } } export class ReadPropExpr extends Expression { constructor( public receiver: Expression, public name: string, type?: Type | null, sourceSpan?: ParseSourceSpan | null, ) { super(type, sourceSpan); } // An alias for name, which allows other logic to handle property reads and keyed reads together. get index() { return this.name; } override isEquivalent(e: Expression): boolean { return ( e instanceof ReadPropExpr && this.receiver.isEquivalent(e.receiver) && this.name === e.name ); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitReadPropExpr(this, context); } set(value: Expression): WritePropExpr { return new WritePropExpr(this.receiver, this.name, value, null, this.sourceSpan); } override clone(): ReadPropExpr { return new ReadPropExpr(this.receiver.clone(), this.name, this.type, this.sourceSpan); } } export class ReadKeyExpr extends Expression { constructor( public receiver: Expression, public index: Expression, type?: Type | null, sourceSpan?: ParseSourceSpan | null, ) { super(type, sourceSpan); } override isEquivalent(e: Expression): boolean { return ( e instanceof ReadKeyExpr && this.receiver.isEquivalent(e.receiver) && this.index.isEquivalent(e.index) ); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitReadKeyExpr(this, context); } set(value: Expression): WriteKeyExpr { return new WriteKeyExpr(this.receiver, this.index, value, null, this.sourceSpan); } override clone(): ReadKeyExpr { return new ReadKeyExpr(this.receiver.clone(), this.index.clone(), this.type, this.sourceSpan); } } export class LiteralArrayExpr extends Expression { public entries: Expression[]; constructor(entries: Expression[], type?: Type | null, sourceSpan?: ParseSourceSpan | null) { super(type, sourceSpan); this.entries = entries; } override isConstant() { return this.entries.every((e) => e.isConstant()); } override isEquivalent(e: Expression): boolean { return e instanceof LiteralArrayExpr && areAllEquivalent(this.entries, e.entries); } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitLiteralArrayExpr(this, context); } override clone(): LiteralArrayExpr { return new LiteralArrayExpr( this.entries.map((e) => e.clone()), this.type, this.sourceSpan, ); } } export class LiteralMapEntry { constructor( public key: string, public value: Expression, public quoted: boolean, ) {} isEquivalent(e: LiteralMapEntry): boolean { return this.key === e.key && this.value.isEquivalent(e.value); } clone(): LiteralMapEntry { return new LiteralMapEntry(this.key, this.value.clone(), this.quoted); } } export class LiteralMapExpr extends Expression { public valueType: Type | null = null; constructor( public entries: LiteralMapEntry[], type?: MapType | null, sourceSpan?: ParseSourceSpan | null, ) { super(type, sourceSpan); if (type) { this.valueType = type.valueType; } } override isEquivalent(e: Expression): boolean { return e instanceof LiteralMapExpr && areAllEquivalent(this.entries, e.entries); } override isConstant() { return this.entries.every((e) => e.value.isConstant()); } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitLiteralMapExpr(this, context); } override clone(): LiteralMapExpr { const entriesClone = this.entries.map((entry) => entry.clone()); return new LiteralMapExpr(entriesClone, this.type as MapType | null, this.sourceSpan); } }
{ "end_byte": 37011, "start_byte": 28396, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/output_ast.ts" }
angular/packages/compiler/src/output/output_ast.ts_37013_44343
port class CommaExpr extends Expression { constructor( public parts: Expression[], sourceSpan?: ParseSourceSpan | null, ) { super(parts[parts.length - 1].type, sourceSpan); } override isEquivalent(e: Expression): boolean { return e instanceof CommaExpr && areAllEquivalent(this.parts, e.parts); } override isConstant() { return false; } override visitExpression(visitor: ExpressionVisitor, context: any): any { return visitor.visitCommaExpr(this, context); } override clone(): CommaExpr { return new CommaExpr(this.parts.map((p) => p.clone())); } } export interface ExpressionVisitor { visitReadVarExpr(ast: ReadVarExpr, context: any): any; visitWriteVarExpr(expr: WriteVarExpr, context: any): any; visitWriteKeyExpr(expr: WriteKeyExpr, context: any): any; visitWritePropExpr(expr: WritePropExpr, context: any): any; visitInvokeFunctionExpr(ast: InvokeFunctionExpr, context: any): any; visitTaggedTemplateExpr(ast: TaggedTemplateExpr, context: any): any; visitInstantiateExpr(ast: InstantiateExpr, context: any): any; visitLiteralExpr(ast: LiteralExpr, context: any): any; visitLocalizedString(ast: LocalizedString, context: any): any; visitExternalExpr(ast: ExternalExpr, context: any): any; visitConditionalExpr(ast: ConditionalExpr, context: any): any; visitDynamicImportExpr(ast: DynamicImportExpr, context: any): any; visitNotExpr(ast: NotExpr, context: any): any; visitFunctionExpr(ast: FunctionExpr, context: any): any; visitUnaryOperatorExpr(ast: UnaryOperatorExpr, context: any): any; visitBinaryOperatorExpr(ast: BinaryOperatorExpr, context: any): any; visitReadPropExpr(ast: ReadPropExpr, context: any): any; visitReadKeyExpr(ast: ReadKeyExpr, context: any): any; visitLiteralArrayExpr(ast: LiteralArrayExpr, context: any): any; visitLiteralMapExpr(ast: LiteralMapExpr, context: any): any; visitCommaExpr(ast: CommaExpr, context: any): any; visitWrappedNodeExpr(ast: WrappedNodeExpr<any>, context: any): any; visitTypeofExpr(ast: TypeofExpr, context: any): any; visitArrowFunctionExpr(ast: ArrowFunctionExpr, context: any): any; } export const NULL_EXPR = new LiteralExpr(null, null, null); export const TYPED_NULL_EXPR = new LiteralExpr(null, INFERRED_TYPE, null); //// Statements export enum StmtModifier { None = 0, Final = 1 << 0, Private = 1 << 1, Exported = 1 << 2, Static = 1 << 3, } export class LeadingComment { constructor( public text: string, public multiline: boolean, public trailingNewline: boolean, ) {} toString() { return this.multiline ? ` ${this.text} ` : this.text; } } export class JSDocComment extends LeadingComment { constructor(public tags: JSDocTag[]) { super('', /* multiline */ true, /* trailingNewline */ true); } override toString(): string { return serializeTags(this.tags); } } export abstract class Statement { constructor( public modifiers: StmtModifier = StmtModifier.None, public sourceSpan: ParseSourceSpan | null = null, public leadingComments?: LeadingComment[], ) {} /** * Calculates whether this statement produces the same value as the given statement. * Note: We don't check Types nor ParseSourceSpans nor function arguments. */ abstract isEquivalent(stmt: Statement): boolean; abstract visitStatement(visitor: StatementVisitor, context: any): any; hasModifier(modifier: StmtModifier): boolean { return (this.modifiers & modifier) !== 0; } addLeadingComment(leadingComment: LeadingComment): void { this.leadingComments = this.leadingComments ?? []; this.leadingComments.push(leadingComment); } } export class DeclareVarStmt extends Statement { public type: Type | null; constructor( public name: string, public value?: Expression, type?: Type | null, modifiers?: StmtModifier, sourceSpan?: ParseSourceSpan | null, leadingComments?: LeadingComment[], ) { super(modifiers, sourceSpan, leadingComments); this.type = type || (value && value.type) || null; } override isEquivalent(stmt: Statement): boolean { return ( stmt instanceof DeclareVarStmt && this.name === stmt.name && (this.value ? !!stmt.value && this.value.isEquivalent(stmt.value) : !stmt.value) ); } override visitStatement(visitor: StatementVisitor, context: any): any { return visitor.visitDeclareVarStmt(this, context); } } export class DeclareFunctionStmt extends Statement { public type: Type | null; constructor( public name: string, public params: FnParam[], public statements: Statement[], type?: Type | null, modifiers?: StmtModifier, sourceSpan?: ParseSourceSpan | null, leadingComments?: LeadingComment[], ) { super(modifiers, sourceSpan, leadingComments); this.type = type || null; } override isEquivalent(stmt: Statement): boolean { return ( stmt instanceof DeclareFunctionStmt && areAllEquivalent(this.params, stmt.params) && areAllEquivalent(this.statements, stmt.statements) ); } override visitStatement(visitor: StatementVisitor, context: any): any { return visitor.visitDeclareFunctionStmt(this, context); } } export class ExpressionStatement extends Statement { constructor( public expr: Expression, sourceSpan?: ParseSourceSpan | null, leadingComments?: LeadingComment[], ) { super(StmtModifier.None, sourceSpan, leadingComments); } override isEquivalent(stmt: Statement): boolean { return stmt instanceof ExpressionStatement && this.expr.isEquivalent(stmt.expr); } override visitStatement(visitor: StatementVisitor, context: any): any { return visitor.visitExpressionStmt(this, context); } } export class ReturnStatement extends Statement { constructor( public value: Expression, sourceSpan: ParseSourceSpan | null = null, leadingComments?: LeadingComment[], ) { super(StmtModifier.None, sourceSpan, leadingComments); } override isEquivalent(stmt: Statement): boolean { return stmt instanceof ReturnStatement && this.value.isEquivalent(stmt.value); } override visitStatement(visitor: StatementVisitor, context: any): any { return visitor.visitReturnStmt(this, context); } } export class IfStmt extends Statement { constructor( public condition: Expression, public trueCase: Statement[], public falseCase: Statement[] = [], sourceSpan?: ParseSourceSpan | null, leadingComments?: LeadingComment[], ) { super(StmtModifier.None, sourceSpan, leadingComments); } override isEquivalent(stmt: Statement): boolean { return ( stmt instanceof IfStmt && this.condition.isEquivalent(stmt.condition) && areAllEquivalent(this.trueCase, stmt.trueCase) && areAllEquivalent(this.falseCase, stmt.falseCase) ); } override visitStatement(visitor: StatementVisitor, context: any): any { return visitor.visitIfStmt(this, context); } } export interface StatementVisitor { visitDeclareVarStmt(stmt: DeclareVarStmt, context: any): any; visitDeclareFunctionStmt(stmt: DeclareFunctionStmt, context: any): any; visitExpressionStmt(stmt: ExpressionStatement, context: any): any; visitReturnStmt(stmt: ReturnStatement, context: any): any; visitIfStmt(stmt: IfStmt, context: any): any; }
{ "end_byte": 44343, "start_byte": 37013, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/output_ast.ts" }
angular/packages/compiler/src/output/output_ast.ts_44345_52759
port class RecursiveAstVisitor implements StatementVisitor, ExpressionVisitor { visitType(ast: Type, context: any): any { return ast; } visitExpression(ast: Expression, context: any): any { if (ast.type) { ast.type.visitType(this, context); } return ast; } visitBuiltinType(type: BuiltinType, context: any): any { return this.visitType(type, context); } visitExpressionType(type: ExpressionType, context: any): any { type.value.visitExpression(this, context); if (type.typeParams !== null) { type.typeParams.forEach((param) => this.visitType(param, context)); } return this.visitType(type, context); } visitArrayType(type: ArrayType, context: any): any { return this.visitType(type, context); } visitMapType(type: MapType, context: any): any { return this.visitType(type, context); } visitTransplantedType(type: TransplantedType<unknown>, context: any): any { return type; } visitWrappedNodeExpr(ast: WrappedNodeExpr<any>, context: any): any { return ast; } visitTypeofExpr(ast: TypeofExpr, context: any): any { return this.visitExpression(ast, context); } visitReadVarExpr(ast: ReadVarExpr, context: any): any { return this.visitExpression(ast, context); } visitWriteVarExpr(ast: WriteVarExpr, context: any): any { ast.value.visitExpression(this, context); return this.visitExpression(ast, context); } visitWriteKeyExpr(ast: WriteKeyExpr, context: any): any { ast.receiver.visitExpression(this, context); ast.index.visitExpression(this, context); ast.value.visitExpression(this, context); return this.visitExpression(ast, context); } visitWritePropExpr(ast: WritePropExpr, context: any): any { ast.receiver.visitExpression(this, context); ast.value.visitExpression(this, context); return this.visitExpression(ast, context); } visitDynamicImportExpr(ast: DynamicImportExpr, context: any) { return this.visitExpression(ast, context); } visitInvokeFunctionExpr(ast: InvokeFunctionExpr, context: any): any { ast.fn.visitExpression(this, context); this.visitAllExpressions(ast.args, context); return this.visitExpression(ast, context); } visitTaggedTemplateExpr(ast: TaggedTemplateExpr, context: any): any { ast.tag.visitExpression(this, context); this.visitAllExpressions(ast.template.expressions, context); return this.visitExpression(ast, context); } visitInstantiateExpr(ast: InstantiateExpr, context: any): any { ast.classExpr.visitExpression(this, context); this.visitAllExpressions(ast.args, context); return this.visitExpression(ast, context); } visitLiteralExpr(ast: LiteralExpr, context: any): any { return this.visitExpression(ast, context); } visitLocalizedString(ast: LocalizedString, context: any): any { return this.visitExpression(ast, context); } visitExternalExpr(ast: ExternalExpr, context: any): any { if (ast.typeParams) { ast.typeParams.forEach((type) => type.visitType(this, context)); } return this.visitExpression(ast, context); } visitConditionalExpr(ast: ConditionalExpr, context: any): any { ast.condition.visitExpression(this, context); ast.trueCase.visitExpression(this, context); ast.falseCase!.visitExpression(this, context); return this.visitExpression(ast, context); } visitNotExpr(ast: NotExpr, context: any): any { ast.condition.visitExpression(this, context); return this.visitExpression(ast, context); } visitFunctionExpr(ast: FunctionExpr, context: any): any { this.visitAllStatements(ast.statements, context); return this.visitExpression(ast, context); } visitArrowFunctionExpr(ast: ArrowFunctionExpr, context: any): any { if (Array.isArray(ast.body)) { this.visitAllStatements(ast.body, context); } else { // Note: `body.visitExpression`, rather than `this.visitExpressiont(body)`, // because the latter won't recurse into the sub-expressions. ast.body.visitExpression(this, context); } return this.visitExpression(ast, context); } visitUnaryOperatorExpr(ast: UnaryOperatorExpr, context: any): any { ast.expr.visitExpression(this, context); return this.visitExpression(ast, context); } visitBinaryOperatorExpr(ast: BinaryOperatorExpr, context: any): any { ast.lhs.visitExpression(this, context); ast.rhs.visitExpression(this, context); return this.visitExpression(ast, context); } visitReadPropExpr(ast: ReadPropExpr, context: any): any { ast.receiver.visitExpression(this, context); return this.visitExpression(ast, context); } visitReadKeyExpr(ast: ReadKeyExpr, context: any): any { ast.receiver.visitExpression(this, context); ast.index.visitExpression(this, context); return this.visitExpression(ast, context); } visitLiteralArrayExpr(ast: LiteralArrayExpr, context: any): any { this.visitAllExpressions(ast.entries, context); return this.visitExpression(ast, context); } visitLiteralMapExpr(ast: LiteralMapExpr, context: any): any { ast.entries.forEach((entry) => entry.value.visitExpression(this, context)); return this.visitExpression(ast, context); } visitCommaExpr(ast: CommaExpr, context: any): any { this.visitAllExpressions(ast.parts, context); return this.visitExpression(ast, context); } visitAllExpressions(exprs: Expression[], context: any): void { exprs.forEach((expr) => expr.visitExpression(this, context)); } visitDeclareVarStmt(stmt: DeclareVarStmt, context: any): any { if (stmt.value) { stmt.value.visitExpression(this, context); } if (stmt.type) { stmt.type.visitType(this, context); } return stmt; } visitDeclareFunctionStmt(stmt: DeclareFunctionStmt, context: any): any { this.visitAllStatements(stmt.statements, context); if (stmt.type) { stmt.type.visitType(this, context); } return stmt; } visitExpressionStmt(stmt: ExpressionStatement, context: any): any { stmt.expr.visitExpression(this, context); return stmt; } visitReturnStmt(stmt: ReturnStatement, context: any): any { stmt.value.visitExpression(this, context); return stmt; } visitIfStmt(stmt: IfStmt, context: any): any { stmt.condition.visitExpression(this, context); this.visitAllStatements(stmt.trueCase, context); this.visitAllStatements(stmt.falseCase, context); return stmt; } visitAllStatements(stmts: Statement[], context: any): void { stmts.forEach((stmt) => stmt.visitStatement(this, context)); } } export function leadingComment( text: string, multiline: boolean = false, trailingNewline: boolean = true, ): LeadingComment { return new LeadingComment(text, multiline, trailingNewline); } export function jsDocComment(tags: JSDocTag[] = []): JSDocComment { return new JSDocComment(tags); } export function variable( name: string, type?: Type | null, sourceSpan?: ParseSourceSpan | null, ): ReadVarExpr { return new ReadVarExpr(name, type, sourceSpan); } export function importExpr( id: ExternalReference, typeParams: Type[] | null = null, sourceSpan?: ParseSourceSpan | null, ): ExternalExpr { return new ExternalExpr(id, null, typeParams, sourceSpan); } export function importType( id: ExternalReference, typeParams?: Type[] | null, typeModifiers?: TypeModifier, ): ExpressionType | null { return id != null ? expressionType(importExpr(id, typeParams, null), typeModifiers) : null; } export function expressionType( expr: Expression, typeModifiers?: TypeModifier, typeParams?: Type[] | null, ): ExpressionType { return new ExpressionType(expr, typeModifiers, typeParams); } export function transplantedType<T>(type: T, typeModifiers?: TypeModifier): TransplantedType<T> { return new TransplantedType(type, typeModifiers); } export function typeofExpr(expr: Expression) { return new TypeofExpr(expr); } export function literalArr( values: Expression[], type?: Type | null, sourceSpan?: ParseSourceSpan | null, ): LiteralArrayExpr { return new LiteralArrayExpr(values, type, sourceSpan); } export function literalMap( values: {key: string; quoted: boolean; value: Expression}[], type: MapType | null = null, ): LiteralMapExpr { return new LiteralMapExpr( values.map((e) => new LiteralMapEntry(e.key, e.value, e.quoted)), type, null, ); }
{ "end_byte": 52759, "start_byte": 44345, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/output_ast.ts" }
angular/packages/compiler/src/output/output_ast.ts_52761_56442
port function unary( operator: UnaryOperator, expr: Expression, type?: Type, sourceSpan?: ParseSourceSpan | null, ): UnaryOperatorExpr { return new UnaryOperatorExpr(operator, expr, type, sourceSpan); } export function not(expr: Expression, sourceSpan?: ParseSourceSpan | null): NotExpr { return new NotExpr(expr, sourceSpan); } export function fn( params: FnParam[], body: Statement[], type?: Type | null, sourceSpan?: ParseSourceSpan | null, name?: string | null, ): FunctionExpr { return new FunctionExpr(params, body, type, sourceSpan, name); } export function arrowFn( params: FnParam[], body: Expression | Statement[], type?: Type | null, sourceSpan?: ParseSourceSpan | null, ) { return new ArrowFunctionExpr(params, body, type, sourceSpan); } export function ifStmt( condition: Expression, thenClause: Statement[], elseClause?: Statement[], sourceSpan?: ParseSourceSpan, leadingComments?: LeadingComment[], ) { return new IfStmt(condition, thenClause, elseClause, sourceSpan, leadingComments); } export function taggedTemplate( tag: Expression, template: TemplateLiteral, type?: Type | null, sourceSpan?: ParseSourceSpan | null, ): TaggedTemplateExpr { return new TaggedTemplateExpr(tag, template, type, sourceSpan); } export function literal( value: any, type?: Type | null, sourceSpan?: ParseSourceSpan | null, ): LiteralExpr { return new LiteralExpr(value, type, sourceSpan); } export function localizedString( metaBlock: I18nMeta, messageParts: LiteralPiece[], placeholderNames: PlaceholderPiece[], expressions: Expression[], sourceSpan?: ParseSourceSpan | null, ): LocalizedString { return new LocalizedString(metaBlock, messageParts, placeholderNames, expressions, sourceSpan); } export function isNull(exp: Expression): boolean { return exp instanceof LiteralExpr && exp.value === null; } // The list of JSDoc tags that we currently support. Extend it if needed. export const enum JSDocTagName { Desc = 'desc', Id = 'id', Meaning = 'meaning', Suppress = 'suppress', } /* * TypeScript has an API for JSDoc already, but it's not exposed. * https://github.com/Microsoft/TypeScript/issues/7393 * For now we create types that are similar to theirs so that migrating * to their API will be easier. See e.g. `ts.JSDocTag` and `ts.JSDocComment`. */ export type JSDocTag = | { // `tagName` is e.g. "param" in an `@param` declaration tagName: JSDocTagName | string; // Any remaining text on the tag, e.g. the description text?: string; } | { // no `tagName` for plain text documentation that occurs before any `@param` lines tagName?: undefined; text: string; }; /* * Serializes a `Tag` into a string. * Returns a string like " @foo {bar} baz" (note the leading whitespace before `@foo`). */ function tagToString(tag: JSDocTag): string { let out = ''; if (tag.tagName) { out += ` @${tag.tagName}`; } if (tag.text) { if (tag.text.match(/\/\*|\*\//)) { throw new Error('JSDoc text cannot contain "/*" and "*/"'); } out += ' ' + tag.text.replace(/@/g, '\\@'); } return out; } function serializeTags(tags: JSDocTag[]): string { if (tags.length === 0) return ''; if (tags.length === 1 && tags[0].tagName && !tags[0].text) { // The JSDOC comment is a single simple tag: e.g `/** @tagname */`. return `*${tagToString(tags[0])} `; } let out = '*\n'; for (const tag of tags) { out += ' *'; // If the tagToString is multi-line, insert " * " prefixes on lines. out += tagToString(tag).replace(/\n/g, '\n * '); out += '\n'; } out += ' '; return out; }
{ "end_byte": 56442, "start_byte": 52761, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/output_ast.ts" }
angular/packages/compiler/src/output/abstract_emitter.ts_0_5087
/** * @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'; import * as o from './output_ast'; import {SourceMapGenerator} from './source_map'; const _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g; const _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i; const _INDENT_WITH = ' '; class _EmittedLine { partsLength = 0; parts: string[] = []; srcSpans: (ParseSourceSpan | null)[] = []; constructor(public indent: number) {} } export class EmitterVisitorContext { static createRoot(): EmitterVisitorContext { return new EmitterVisitorContext(0); } private _lines: _EmittedLine[]; constructor(private _indent: number) { this._lines = [new _EmittedLine(_indent)]; } /** * @internal strip this from published d.ts files due to * https://github.com/microsoft/TypeScript/issues/36216 */ private get _currentLine(): _EmittedLine { return this._lines[this._lines.length - 1]; } println(from?: {sourceSpan: ParseSourceSpan | null} | null, lastPart: string = ''): void { this.print(from || null, lastPart, true); } lineIsEmpty(): boolean { return this._currentLine.parts.length === 0; } lineLength(): number { return this._currentLine.indent * _INDENT_WITH.length + this._currentLine.partsLength; } print(from: {sourceSpan: ParseSourceSpan | null} | null, part: string, newLine: boolean = false) { if (part.length > 0) { this._currentLine.parts.push(part); this._currentLine.partsLength += part.length; this._currentLine.srcSpans.push((from && from.sourceSpan) || null); } if (newLine) { this._lines.push(new _EmittedLine(this._indent)); } } removeEmptyLastLine() { if (this.lineIsEmpty()) { this._lines.pop(); } } incIndent() { this._indent++; if (this.lineIsEmpty()) { this._currentLine.indent = this._indent; } } decIndent() { this._indent--; if (this.lineIsEmpty()) { this._currentLine.indent = this._indent; } } toSource(): string { return this.sourceLines .map((l) => (l.parts.length > 0 ? _createIndent(l.indent) + l.parts.join('') : '')) .join('\n'); } toSourceMapGenerator(genFilePath: string, startsAtLine: number = 0): SourceMapGenerator { const map = new SourceMapGenerator(genFilePath); let firstOffsetMapped = false; const mapFirstOffsetIfNeeded = () => { if (!firstOffsetMapped) { // Add a single space so that tools won't try to load the file from disk. // Note: We are using virtual urls like `ng:///`, so we have to // provide a content here. map.addSource(genFilePath, ' ').addMapping(0, genFilePath, 0, 0); firstOffsetMapped = true; } }; for (let i = 0; i < startsAtLine; i++) { map.addLine(); mapFirstOffsetIfNeeded(); } this.sourceLines.forEach((line, lineIdx) => { map.addLine(); const spans = line.srcSpans; const parts = line.parts; let col0 = line.indent * _INDENT_WITH.length; let spanIdx = 0; // skip leading parts without source spans while (spanIdx < spans.length && !spans[spanIdx]) { col0 += parts[spanIdx].length; spanIdx++; } if (spanIdx < spans.length && lineIdx === 0 && col0 === 0) { firstOffsetMapped = true; } else { mapFirstOffsetIfNeeded(); } while (spanIdx < spans.length) { const span = spans[spanIdx]!; const source = span.start.file; const sourceLine = span.start.line; const sourceCol = span.start.col; map .addSource(source.url, source.content) .addMapping(col0, source.url, sourceLine, sourceCol); col0 += parts[spanIdx].length; spanIdx++; // assign parts without span or the same span to the previous segment while (spanIdx < spans.length && (span === spans[spanIdx] || !spans[spanIdx])) { col0 += parts[spanIdx].length; spanIdx++; } } }); return map; } spanOf(line: number, column: number): ParseSourceSpan | null { const emittedLine = this._lines[line]; if (emittedLine) { let columnsLeft = column - _createIndent(emittedLine.indent).length; for (let partIndex = 0; partIndex < emittedLine.parts.length; partIndex++) { const part = emittedLine.parts[partIndex]; if (part.length > columnsLeft) { return emittedLine.srcSpans[partIndex]; } columnsLeft -= part.length; } } return null; } /** * @internal strip this from published d.ts files due to * https://github.com/microsoft/TypeScript/issues/36216 */ private get sourceLines(): _EmittedLine[] { if (this._lines.length && this._lines[this._lines.length - 1].parts.length === 0) { return this._lines.slice(0, -1); } return this._lines; } }
{ "end_byte": 5087, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/abstract_emitter.ts" }
angular/packages/compiler/src/output/abstract_emitter.ts_5089_12299
export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.ExpressionVisitor { constructor(private _escapeDollarInStrings: boolean) {} protected printLeadingComments(stmt: o.Statement, ctx: EmitterVisitorContext): void { if (stmt.leadingComments === undefined) { return; } for (const comment of stmt.leadingComments) { if (comment instanceof o.JSDocComment) { ctx.print(stmt, `/*${comment.toString()}*/`, comment.trailingNewline); } else { if (comment.multiline) { ctx.print(stmt, `/* ${comment.text} */`, comment.trailingNewline); } else { comment.text.split('\n').forEach((line) => { ctx.println(stmt, `// ${line}`); }); } } } } visitExpressionStmt(stmt: o.ExpressionStatement, ctx: EmitterVisitorContext): any { this.printLeadingComments(stmt, ctx); stmt.expr.visitExpression(this, ctx); ctx.println(stmt, ';'); return null; } visitReturnStmt(stmt: o.ReturnStatement, ctx: EmitterVisitorContext): any { this.printLeadingComments(stmt, ctx); ctx.print(stmt, `return `); stmt.value.visitExpression(this, ctx); ctx.println(stmt, ';'); return null; } visitIfStmt(stmt: o.IfStmt, ctx: EmitterVisitorContext): any { this.printLeadingComments(stmt, ctx); ctx.print(stmt, `if (`); stmt.condition.visitExpression(this, ctx); ctx.print(stmt, `) {`); const hasElseCase = stmt.falseCase != null && stmt.falseCase.length > 0; if (stmt.trueCase.length <= 1 && !hasElseCase) { ctx.print(stmt, ` `); this.visitAllStatements(stmt.trueCase, ctx); ctx.removeEmptyLastLine(); ctx.print(stmt, ` `); } else { ctx.println(); ctx.incIndent(); this.visitAllStatements(stmt.trueCase, ctx); ctx.decIndent(); if (hasElseCase) { ctx.println(stmt, `} else {`); ctx.incIndent(); this.visitAllStatements(stmt.falseCase, ctx); ctx.decIndent(); } } ctx.println(stmt, `}`); return null; } abstract visitDeclareVarStmt(stmt: o.DeclareVarStmt, ctx: EmitterVisitorContext): any; visitWriteVarExpr(expr: o.WriteVarExpr, ctx: EmitterVisitorContext): any { const lineWasEmpty = ctx.lineIsEmpty(); if (!lineWasEmpty) { ctx.print(expr, '('); } ctx.print(expr, `${expr.name} = `); expr.value.visitExpression(this, ctx); if (!lineWasEmpty) { ctx.print(expr, ')'); } return null; } visitWriteKeyExpr(expr: o.WriteKeyExpr, ctx: EmitterVisitorContext): any { const lineWasEmpty = ctx.lineIsEmpty(); if (!lineWasEmpty) { ctx.print(expr, '('); } expr.receiver.visitExpression(this, ctx); ctx.print(expr, `[`); expr.index.visitExpression(this, ctx); ctx.print(expr, `] = `); expr.value.visitExpression(this, ctx); if (!lineWasEmpty) { ctx.print(expr, ')'); } return null; } visitWritePropExpr(expr: o.WritePropExpr, ctx: EmitterVisitorContext): any { const lineWasEmpty = ctx.lineIsEmpty(); if (!lineWasEmpty) { ctx.print(expr, '('); } expr.receiver.visitExpression(this, ctx); ctx.print(expr, `.${expr.name} = `); expr.value.visitExpression(this, ctx); if (!lineWasEmpty) { ctx.print(expr, ')'); } return null; } visitInvokeFunctionExpr(expr: o.InvokeFunctionExpr, ctx: EmitterVisitorContext): any { const shouldParenthesize = expr.fn instanceof o.ArrowFunctionExpr; if (shouldParenthesize) { ctx.print(expr.fn, '('); } expr.fn.visitExpression(this, ctx); if (shouldParenthesize) { ctx.print(expr.fn, ')'); } ctx.print(expr, `(`); this.visitAllExpressions(expr.args, ctx, ','); ctx.print(expr, `)`); return null; } visitTaggedTemplateExpr(expr: o.TaggedTemplateExpr, ctx: EmitterVisitorContext): any { expr.tag.visitExpression(this, ctx); ctx.print(expr, '`' + expr.template.elements[0].rawText); for (let i = 1; i < expr.template.elements.length; i++) { ctx.print(expr, '${'); expr.template.expressions[i - 1].visitExpression(this, ctx); ctx.print(expr, `}${expr.template.elements[i].rawText}`); } ctx.print(expr, '`'); return null; } visitWrappedNodeExpr(ast: o.WrappedNodeExpr<any>, ctx: EmitterVisitorContext): any { throw new Error('Abstract emitter cannot visit WrappedNodeExpr.'); } visitTypeofExpr(expr: o.TypeofExpr, ctx: EmitterVisitorContext): any { ctx.print(expr, 'typeof '); expr.expr.visitExpression(this, ctx); } visitReadVarExpr(ast: o.ReadVarExpr, ctx: EmitterVisitorContext): any { ctx.print(ast, ast.name); return null; } visitInstantiateExpr(ast: o.InstantiateExpr, ctx: EmitterVisitorContext): any { ctx.print(ast, `new `); ast.classExpr.visitExpression(this, ctx); ctx.print(ast, `(`); this.visitAllExpressions(ast.args, ctx, ','); ctx.print(ast, `)`); return null; } visitLiteralExpr(ast: o.LiteralExpr, ctx: EmitterVisitorContext): any { const value = ast.value; if (typeof value === 'string') { ctx.print(ast, escapeIdentifier(value, this._escapeDollarInStrings)); } else { ctx.print(ast, `${value}`); } return null; } visitLocalizedString(ast: o.LocalizedString, ctx: EmitterVisitorContext): any { const head = ast.serializeI18nHead(); ctx.print(ast, '$localize `' + head.raw); for (let i = 1; i < ast.messageParts.length; i++) { ctx.print(ast, '${'); ast.expressions[i - 1].visitExpression(this, ctx); ctx.print(ast, `}${ast.serializeI18nTemplatePart(i).raw}`); } ctx.print(ast, '`'); return null; } abstract visitExternalExpr(ast: o.ExternalExpr, ctx: EmitterVisitorContext): any; visitConditionalExpr(ast: o.ConditionalExpr, ctx: EmitterVisitorContext): any { ctx.print(ast, `(`); ast.condition.visitExpression(this, ctx); ctx.print(ast, '? '); ast.trueCase.visitExpression(this, ctx); ctx.print(ast, ': '); ast.falseCase!.visitExpression(this, ctx); ctx.print(ast, `)`); return null; } visitDynamicImportExpr(ast: o.DynamicImportExpr, ctx: EmitterVisitorContext) { ctx.print(ast, `import(${ast.url})`); } visitNotExpr(ast: o.NotExpr, ctx: EmitterVisitorContext): any { ctx.print(ast, '!'); ast.condition.visitExpression(this, ctx); return null; } abstract visitFunctionExpr(ast: o.FunctionExpr, ctx: EmitterVisitorContext): any; abstract visitArrowFunctionExpr(ast: o.ArrowFunctionExpr, context: any): any; abstract visitDeclareFunctionStmt(stmt: o.DeclareFunctionStmt, context: any): any; visitUnaryOperatorExpr(ast: o.UnaryOperatorExpr, ctx: EmitterVisitorContext): any { let opStr: string; switch (ast.operator) { case o.UnaryOperator.Plus: opStr = '+'; break; case o.UnaryOperator.Minus: opStr = '-'; break; default: throw new Error(`Unknown operator ${ast.operator}`); } if (ast.parens) ctx.print(ast, `(`); ctx.print(ast, opStr); ast.expr.visitExpression(this, ctx); if (ast.parens) ctx.print(ast, `)`); return null; }
{ "end_byte": 12299, "start_byte": 5089, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/abstract_emitter.ts" }
angular/packages/compiler/src/output/abstract_emitter.ts_12303_17255
visitBinaryOperatorExpr(ast: o.BinaryOperatorExpr, ctx: EmitterVisitorContext): any { let opStr: string; switch (ast.operator) { case o.BinaryOperator.Equals: opStr = '=='; break; case o.BinaryOperator.Identical: opStr = '==='; break; case o.BinaryOperator.NotEquals: opStr = '!='; break; case o.BinaryOperator.NotIdentical: opStr = '!=='; break; case o.BinaryOperator.And: opStr = '&&'; break; case o.BinaryOperator.BitwiseOr: opStr = '|'; break; case o.BinaryOperator.BitwiseAnd: opStr = '&'; break; case o.BinaryOperator.Or: opStr = '||'; break; case o.BinaryOperator.Plus: opStr = '+'; break; case o.BinaryOperator.Minus: opStr = '-'; break; case o.BinaryOperator.Divide: opStr = '/'; break; case o.BinaryOperator.Multiply: opStr = '*'; break; case o.BinaryOperator.Modulo: opStr = '%'; break; case o.BinaryOperator.Lower: opStr = '<'; break; case o.BinaryOperator.LowerEquals: opStr = '<='; break; case o.BinaryOperator.Bigger: opStr = '>'; break; case o.BinaryOperator.BiggerEquals: opStr = '>='; break; case o.BinaryOperator.NullishCoalesce: opStr = '??'; break; default: throw new Error(`Unknown operator ${ast.operator}`); } if (ast.parens) ctx.print(ast, `(`); ast.lhs.visitExpression(this, ctx); ctx.print(ast, ` ${opStr} `); ast.rhs.visitExpression(this, ctx); if (ast.parens) ctx.print(ast, `)`); return null; } visitReadPropExpr(ast: o.ReadPropExpr, ctx: EmitterVisitorContext): any { ast.receiver.visitExpression(this, ctx); ctx.print(ast, `.`); ctx.print(ast, ast.name); return null; } visitReadKeyExpr(ast: o.ReadKeyExpr, ctx: EmitterVisitorContext): any { ast.receiver.visitExpression(this, ctx); ctx.print(ast, `[`); ast.index.visitExpression(this, ctx); ctx.print(ast, `]`); return null; } visitLiteralArrayExpr(ast: o.LiteralArrayExpr, ctx: EmitterVisitorContext): any { ctx.print(ast, `[`); this.visitAllExpressions(ast.entries, ctx, ','); ctx.print(ast, `]`); return null; } visitLiteralMapExpr(ast: o.LiteralMapExpr, ctx: EmitterVisitorContext): any { ctx.print(ast, `{`); this.visitAllObjects( (entry) => { ctx.print( ast, `${escapeIdentifier(entry.key, this._escapeDollarInStrings, entry.quoted)}:`, ); entry.value.visitExpression(this, ctx); }, ast.entries, ctx, ',', ); ctx.print(ast, `}`); return null; } visitCommaExpr(ast: o.CommaExpr, ctx: EmitterVisitorContext): any { ctx.print(ast, '('); this.visitAllExpressions(ast.parts, ctx, ','); ctx.print(ast, ')'); return null; } visitAllExpressions( expressions: o.Expression[], ctx: EmitterVisitorContext, separator: string, ): void { this.visitAllObjects((expr) => expr.visitExpression(this, ctx), expressions, ctx, separator); } visitAllObjects<T>( handler: (t: T) => void, expressions: T[], ctx: EmitterVisitorContext, separator: string, ): void { let incrementedIndent = false; for (let i = 0; i < expressions.length; i++) { if (i > 0) { if (ctx.lineLength() > 80) { ctx.print(null, separator, true); if (!incrementedIndent) { // continuation are marked with double indent. ctx.incIndent(); ctx.incIndent(); incrementedIndent = true; } } else { ctx.print(null, separator, false); } } handler(expressions[i]); } if (incrementedIndent) { // continuation are marked with double indent. ctx.decIndent(); ctx.decIndent(); } } visitAllStatements(statements: o.Statement[], ctx: EmitterVisitorContext): void { statements.forEach((stmt) => stmt.visitStatement(this, ctx)); } } export function escapeIdentifier( input: string, escapeDollar: boolean, alwaysQuote: boolean = true, ): any { if (input == null) { return null; } const body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, (...match: string[]) => { if (match[0] == '$') { return escapeDollar ? '\\$' : '$'; } else if (match[0] == '\n') { return '\\n'; } else if (match[0] == '\r') { return '\\r'; } else { return `\\${match[0]}`; } }); const requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body); return requiresQuotes ? `'${body}'` : body; } function _createIndent(count: number): string { let res = ''; for (let i = 0; i < count; i++) { res += _INDENT_WITH; } return res; }
{ "end_byte": 17255, "start_byte": 12303, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/abstract_emitter.ts" }
angular/packages/compiler/src/output/map_util.ts_0_711
/** * @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_ast'; export type MapEntry = { key: string; quoted: boolean; value: o.Expression; }; export type MapLiteral = MapEntry[]; export function mapEntry(key: string, value: o.Expression): MapEntry { return {key, value, quoted: false}; } export function mapLiteral( obj: {[key: string]: o.Expression}, quoted: boolean = false, ): o.Expression { return o.literalMap( Object.keys(obj).map((key) => ({ key, quoted, value: obj[key], })), ); }
{ "end_byte": 711, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/map_util.ts" }
angular/packages/compiler/src/output/output_jit_trusted_types.ts_0_5579
/** * @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 */ /** * @fileoverview * A module to facilitate use of a Trusted Types policy within the JIT * compiler. It lazily constructs the Trusted Types policy, providing helper * utilities for promoting strings to Trusted Types. When Trusted Types are not * available, strings are used as a fallback. * @security All use of this module is security-sensitive and should go through * security review. */ import {global} from '../util'; /** * While Angular only uses Trusted Types internally for the time being, * references to Trusted Types could leak into our core.d.ts, which would force * anyone compiling against @angular/core to provide the @types/trusted-types * package in their compilation unit. * * Until https://github.com/microsoft/TypeScript/issues/30024 is resolved, we * will keep Angular's public API surface free of references to Trusted Types. * For internal and semi-private APIs that need to reference Trusted Types, the * minimal type definitions for the Trusted Types API provided by this module * should be used instead. They are marked as "declare" to prevent them from * being renamed by compiler optimization. * * Adapted from * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/trusted-types/index.d.ts * but restricted to the API surface used within Angular. */ export declare interface TrustedScript { __brand__: 'TrustedScript'; } export declare interface TrustedTypePolicyFactory { createPolicy( policyName: string, policyOptions: { createScript?: (input: string) => string; }, ): TrustedTypePolicy; } export declare interface TrustedTypePolicy { createScript(input: string): TrustedScript; } /** * The Trusted Types policy, or null if Trusted Types are not * enabled/supported, or undefined if the policy has not been created yet. */ let policy: TrustedTypePolicy | null | undefined; /** * Returns the Trusted Types policy, or null if Trusted Types are not * enabled/supported. The first call to this function will create the policy. */ function getPolicy(): TrustedTypePolicy | null { if (policy === undefined) { const trustedTypes = global['trustedTypes'] as TrustedTypePolicyFactory | undefined; policy = null; if (trustedTypes) { try { policy = trustedTypes.createPolicy('angular#unsafe-jit', { createScript: (s: string) => s, }); } catch { // trustedTypes.createPolicy throws if called with a name that is // already registered, even in report-only mode. Until the API changes, // catch the error not to break the applications functionally. In such // cases, the code will fall back to using strings. } } } return policy; } /** * Unsafely promote a string to a TrustedScript, falling back to strings when * Trusted Types are not available. * @security In particular, it must be assured that the provided string will * never cause an XSS vulnerability if used in a context that will be * interpreted and executed as a script by a browser, e.g. when calling eval. */ function trustedScriptFromString(script: string): TrustedScript | string { return getPolicy()?.createScript(script) || script; } /** * Unsafely call the Function constructor with the given string arguments. * @security This is a security-sensitive function; any use of this function * must go through security review. In particular, it must be assured that it * is only called from the JIT compiler, as use in other code can lead to XSS * vulnerabilities. */ export function newTrustedFunctionForJIT(...args: string[]): Function { if (!global['trustedTypes']) { // In environments that don't support Trusted Types, fall back to the most // straightforward implementation: return new Function(...args); } // Chrome currently does not support passing TrustedScript to the Function // constructor. The following implements the workaround proposed on the page // below, where the Chromium bug is also referenced: // https://github.com/w3c/webappsec-trusted-types/wiki/Trusted-Types-for-function-constructor const fnArgs = args.slice(0, -1).join(','); const fnBody = args[args.length - 1]; const body = `(function anonymous(${fnArgs} ) { ${fnBody} })`; // Using eval directly confuses the compiler and prevents this module from // being stripped out of JS binaries even if not used. The global['eval'] // indirection fixes that. const fn = global['eval'](trustedScriptFromString(body) as string) as Function; if (fn.bind === undefined) { // Workaround for a browser bug that only exists in Chrome 83, where passing // a TrustedScript to eval just returns the TrustedScript back without // evaluating it. In that case, fall back to the most straightforward // implementation: return new Function(...args); } // To completely mimic the behavior of calling "new Function", two more // things need to happen: // 1. Stringifying the resulting function should return its source code fn.toString = () => body; // 2. When calling the resulting function, `this` should refer to `global` return fn.bind(global); // When Trusted Types support in Function constructors is widely available, // the implementation of this function can be simplified to: // return new Function(...args.map(a => trustedScriptFromString(a))); }
{ "end_byte": 5579, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/output_jit_trusted_types.ts" }
angular/packages/compiler/src/output/abstract_js_emitter.ts_0_5094
/** * @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 {AbstractEmitterVisitor, EmitterVisitorContext, escapeIdentifier} from './abstract_emitter'; import * as o from './output_ast'; /** * In TypeScript, tagged template functions expect a "template object", which is an array of * "cooked" strings plus a `raw` property that contains an array of "raw" strings. This is * typically constructed with a function called `__makeTemplateObject(cooked, raw)`, but it may not * be available in all environments. * * This is a JavaScript polyfill that uses __makeTemplateObject when it's available, but otherwise * creates an inline helper with the same functionality. * * In the inline function, if `Object.defineProperty` is available we use that to attach the `raw` * array. */ const makeTemplateObjectPolyfill = '(this&&this.__makeTemplateObject||function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e})'; export abstract class AbstractJsEmitterVisitor extends AbstractEmitterVisitor { constructor() { super(false); } override visitWrappedNodeExpr(ast: o.WrappedNodeExpr<any>, ctx: EmitterVisitorContext): any { throw new Error('Cannot emit a WrappedNodeExpr in Javascript.'); } override visitDeclareVarStmt(stmt: o.DeclareVarStmt, ctx: EmitterVisitorContext): any { ctx.print(stmt, `var ${stmt.name}`); if (stmt.value) { ctx.print(stmt, ' = '); stmt.value.visitExpression(this, ctx); } ctx.println(stmt, `;`); return null; } override visitTaggedTemplateExpr(ast: o.TaggedTemplateExpr, ctx: EmitterVisitorContext): any { // The following convoluted piece of code is effectively the downlevelled equivalent of // ``` // tag`...` // ``` // which is effectively like: // ``` // tag(__makeTemplateObject(cooked, raw), expression1, expression2, ...); // ``` const elements = ast.template.elements; ast.tag.visitExpression(this, ctx); ctx.print(ast, `(${makeTemplateObjectPolyfill}(`); ctx.print(ast, `[${elements.map((part) => escapeIdentifier(part.text, false)).join(', ')}], `); ctx.print( ast, `[${elements.map((part) => escapeIdentifier(part.rawText, false)).join(', ')}])`, ); ast.template.expressions.forEach((expression) => { ctx.print(ast, ', '); expression.visitExpression(this, ctx); }); ctx.print(ast, ')'); return null; } override visitFunctionExpr(ast: o.FunctionExpr, ctx: EmitterVisitorContext): any { ctx.print(ast, `function${ast.name ? ' ' + ast.name : ''}(`); this._visitParams(ast.params, ctx); ctx.println(ast, `) {`); ctx.incIndent(); this.visitAllStatements(ast.statements, ctx); ctx.decIndent(); ctx.print(ast, `}`); return null; } override visitArrowFunctionExpr(ast: o.ArrowFunctionExpr, ctx: EmitterVisitorContext): any { ctx.print(ast, '('); this._visitParams(ast.params, ctx); ctx.print(ast, ') =>'); if (Array.isArray(ast.body)) { ctx.println(ast, `{`); ctx.incIndent(); this.visitAllStatements(ast.body, ctx); ctx.decIndent(); ctx.print(ast, `}`); } else { const isObjectLiteral = ast.body instanceof o.LiteralMapExpr; if (isObjectLiteral) { ctx.print(ast, '('); } ast.body.visitExpression(this, ctx); if (isObjectLiteral) { ctx.print(ast, ')'); } } return null; } override visitDeclareFunctionStmt(stmt: o.DeclareFunctionStmt, ctx: EmitterVisitorContext): any { ctx.print(stmt, `function ${stmt.name}(`); this._visitParams(stmt.params, ctx); ctx.println(stmt, `) {`); ctx.incIndent(); this.visitAllStatements(stmt.statements, ctx); ctx.decIndent(); ctx.println(stmt, `}`); return null; } override visitLocalizedString(ast: o.LocalizedString, ctx: EmitterVisitorContext): any { // The following convoluted piece of code is effectively the downlevelled equivalent of // ``` // $localize `...` // ``` // which is effectively like: // ``` // $localize(__makeTemplateObject(cooked, raw), expression1, expression2, ...); // ``` ctx.print(ast, `$localize(${makeTemplateObjectPolyfill}(`); const parts = [ast.serializeI18nHead()]; for (let i = 1; i < ast.messageParts.length; i++) { parts.push(ast.serializeI18nTemplatePart(i)); } ctx.print(ast, `[${parts.map((part) => escapeIdentifier(part.cooked, false)).join(', ')}], `); ctx.print(ast, `[${parts.map((part) => escapeIdentifier(part.raw, false)).join(', ')}])`); ast.expressions.forEach((expression) => { ctx.print(ast, ', '); expression.visitExpression(this, ctx); }); ctx.print(ast, ')'); return null; } private _visitParams(params: o.FnParam[], ctx: EmitterVisitorContext): void { this.visitAllObjects((param) => ctx.print(null, param.name), params, ctx, ','); } }
{ "end_byte": 5094, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/abstract_js_emitter.ts" }
angular/packages/compiler/src/output/source_map.ts_0_5592
/** * @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 {utf8Encode} from '../util'; // https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit const VERSION = 3; const JS_B64_PREFIX = '# sourceMappingURL=data:application/json;base64,'; type Segment = { col0: number; sourceUrl?: string; sourceLine0?: number; sourceCol0?: number; }; export type SourceMap = { version: number; file?: string; sourceRoot: string; sources: string[]; sourcesContent: (string | null)[]; mappings: string; }; export class SourceMapGenerator { private sourcesContent: Map<string, string | null> = new Map(); private lines: Segment[][] = []; private lastCol0: number = 0; private hasMappings = false; constructor(private file: string | null = null) {} // The content is `null` when the content is expected to be loaded using the URL addSource(url: string, content: string | null = null): this { if (!this.sourcesContent.has(url)) { this.sourcesContent.set(url, content); } return this; } addLine(): this { this.lines.push([]); this.lastCol0 = 0; return this; } addMapping(col0: number, sourceUrl?: string, sourceLine0?: number, sourceCol0?: number): this { if (!this.currentLine) { throw new Error(`A line must be added before mappings can be added`); } if (sourceUrl != null && !this.sourcesContent.has(sourceUrl)) { throw new Error(`Unknown source file "${sourceUrl}"`); } if (col0 == null) { throw new Error(`The column in the generated code must be provided`); } if (col0 < this.lastCol0) { throw new Error(`Mapping should be added in output order`); } if (sourceUrl && (sourceLine0 == null || sourceCol0 == null)) { throw new Error(`The source location must be provided when a source url is provided`); } this.hasMappings = true; this.lastCol0 = col0; this.currentLine.push({col0, sourceUrl, sourceLine0, sourceCol0}); return this; } /** * @internal strip this from published d.ts files due to * https://github.com/microsoft/TypeScript/issues/36216 */ private get currentLine(): Segment[] | null { return this.lines.slice(-1)[0]; } toJSON(): SourceMap | null { if (!this.hasMappings) { return null; } const sourcesIndex = new Map<string, number>(); const sources: string[] = []; const sourcesContent: (string | null)[] = []; Array.from(this.sourcesContent.keys()).forEach((url: string, i: number) => { sourcesIndex.set(url, i); sources.push(url); sourcesContent.push(this.sourcesContent.get(url) || null); }); let mappings: string = ''; let lastCol0: number = 0; let lastSourceIndex: number = 0; let lastSourceLine0: number = 0; let lastSourceCol0: number = 0; this.lines.forEach((segments) => { lastCol0 = 0; mappings += segments .map((segment) => { // zero-based starting column of the line in the generated code let segAsStr = toBase64VLQ(segment.col0 - lastCol0); lastCol0 = segment.col0; if (segment.sourceUrl != null) { // zero-based index into the “sources” list segAsStr += toBase64VLQ(sourcesIndex.get(segment.sourceUrl)! - lastSourceIndex); lastSourceIndex = sourcesIndex.get(segment.sourceUrl)!; // the zero-based starting line in the original source segAsStr += toBase64VLQ(segment.sourceLine0! - lastSourceLine0); lastSourceLine0 = segment.sourceLine0!; // the zero-based starting column in the original source segAsStr += toBase64VLQ(segment.sourceCol0! - lastSourceCol0); lastSourceCol0 = segment.sourceCol0!; } return segAsStr; }) .join(','); mappings += ';'; }); mappings = mappings.slice(0, -1); return { 'file': this.file || '', 'version': VERSION, 'sourceRoot': '', 'sources': sources, 'sourcesContent': sourcesContent, 'mappings': mappings, }; } toJsComment(): string { return this.hasMappings ? '//' + JS_B64_PREFIX + toBase64String(JSON.stringify(this, null, 0)) : ''; } } export function toBase64String(value: string): string { let b64 = ''; const encoded = utf8Encode(value); for (let i = 0; i < encoded.length; ) { const i1 = encoded[i++]; const i2 = i < encoded.length ? encoded[i++] : null; const i3 = i < encoded.length ? encoded[i++] : null; b64 += toBase64Digit(i1 >> 2); b64 += toBase64Digit(((i1 & 3) << 4) | (i2 === null ? 0 : i2 >> 4)); b64 += i2 === null ? '=' : toBase64Digit(((i2 & 15) << 2) | (i3 === null ? 0 : i3 >> 6)); b64 += i2 === null || i3 === null ? '=' : toBase64Digit(i3 & 63); } return b64; } function toBase64VLQ(value: number): string { value = value < 0 ? (-value << 1) + 1 : value << 1; let out = ''; do { let digit = value & 31; value = value >> 5; if (value > 0) { digit = digit | 32; } out += toBase64Digit(digit); } while (value > 0); return out; } const B64_DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function toBase64Digit(value: number): string { if (value < 0 || value >= 64) { throw new Error(`Can only encode value in the range [0, 63]`); } return B64_DIGITS[value]; }
{ "end_byte": 5592, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/source_map.ts" }
angular/packages/compiler/src/output/output_jit.ts_0_6199
/** * @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 {identifierName} from '../parse_util'; import {EmitterVisitorContext} from './abstract_emitter'; import {AbstractJsEmitterVisitor} from './abstract_js_emitter'; import * as o from './output_ast'; import {newTrustedFunctionForJIT} from './output_jit_trusted_types'; export interface ExternalReferenceResolver { resolveExternalReference(ref: o.ExternalReference): unknown; } /** * A helper class to manage the evaluation of JIT generated code. */ export class JitEvaluator { /** * * @param sourceUrl The URL of the generated code. * @param statements An array of Angular statement AST nodes to be evaluated. * @param refResolver Resolves `o.ExternalReference`s into values. * @param createSourceMaps If true then create a source-map for the generated code and include it * inline as a source-map comment. * @returns A map of all the variables in the generated code. */ evaluateStatements( sourceUrl: string, statements: o.Statement[], refResolver: ExternalReferenceResolver, createSourceMaps: boolean, ): {[key: string]: any} { const converter = new JitEmitterVisitor(refResolver); const ctx = EmitterVisitorContext.createRoot(); // Ensure generated code is in strict mode if (statements.length > 0 && !isUseStrictStatement(statements[0])) { statements = [o.literal('use strict').toStmt(), ...statements]; } converter.visitAllStatements(statements, ctx); converter.createReturnStmt(ctx); return this.evaluateCode(sourceUrl, ctx, converter.getArgs(), createSourceMaps); } /** * Evaluate a piece of JIT generated code. * @param sourceUrl The URL of this generated code. * @param ctx A context object that contains an AST of the code to be evaluated. * @param vars A map containing the names and values of variables that the evaluated code might * reference. * @param createSourceMap If true then create a source-map for the generated code and include it * inline as a source-map comment. * @returns The result of evaluating the code. */ evaluateCode( sourceUrl: string, ctx: EmitterVisitorContext, vars: {[key: string]: any}, createSourceMap: boolean, ): any { let fnBody = `"use strict";${ctx.toSource()}\n//# sourceURL=${sourceUrl}`; const fnArgNames: string[] = []; const fnArgValues: any[] = []; for (const argName in vars) { fnArgValues.push(vars[argName]); fnArgNames.push(argName); } if (createSourceMap) { // using `new Function(...)` generates a header, 1 line of no arguments, 2 lines otherwise // E.g. ``` // function anonymous(a,b,c // /**/) { ... }``` // We don't want to hard code this fact, so we auto detect it via an empty function first. const emptyFn = newTrustedFunctionForJIT(...fnArgNames.concat('return null;')).toString(); const headerLines = emptyFn.slice(0, emptyFn.indexOf('return null;')).split('\n').length - 1; fnBody += `\n${ctx.toSourceMapGenerator(sourceUrl, headerLines).toJsComment()}`; } const fn = newTrustedFunctionForJIT(...fnArgNames.concat(fnBody)); return this.executeFunction(fn, fnArgValues); } /** * Execute a JIT generated function by calling it. * * This method can be overridden in tests to capture the functions that are generated * by this `JitEvaluator` class. * * @param fn A function to execute. * @param args The arguments to pass to the function being executed. * @returns The return value of the executed function. */ executeFunction(fn: Function, args: any[]) { return fn(...args); } } /** * An Angular AST visitor that converts AST nodes into executable JavaScript code. */ export class JitEmitterVisitor extends AbstractJsEmitterVisitor { private _evalArgNames: string[] = []; private _evalArgValues: any[] = []; private _evalExportedVars: string[] = []; constructor(private refResolver: ExternalReferenceResolver) { super(); } createReturnStmt(ctx: EmitterVisitorContext) { const stmt = new o.ReturnStatement( new o.LiteralMapExpr( this._evalExportedVars.map( (resultVar) => new o.LiteralMapEntry(resultVar, o.variable(resultVar), false), ), ), ); stmt.visitStatement(this, ctx); } getArgs(): {[key: string]: any} { const result: {[key: string]: any} = {}; for (let i = 0; i < this._evalArgNames.length; i++) { result[this._evalArgNames[i]] = this._evalArgValues[i]; } return result; } override visitExternalExpr(ast: o.ExternalExpr, ctx: EmitterVisitorContext): any { this._emitReferenceToExternal(ast, this.refResolver.resolveExternalReference(ast.value), ctx); return null; } override visitWrappedNodeExpr(ast: o.WrappedNodeExpr<any>, ctx: EmitterVisitorContext): any { this._emitReferenceToExternal(ast, ast.node, ctx); return null; } override visitDeclareVarStmt(stmt: o.DeclareVarStmt, ctx: EmitterVisitorContext): any { if (stmt.hasModifier(o.StmtModifier.Exported)) { this._evalExportedVars.push(stmt.name); } return super.visitDeclareVarStmt(stmt, ctx); } override visitDeclareFunctionStmt(stmt: o.DeclareFunctionStmt, ctx: EmitterVisitorContext): any { if (stmt.hasModifier(o.StmtModifier.Exported)) { this._evalExportedVars.push(stmt.name); } return super.visitDeclareFunctionStmt(stmt, ctx); } private _emitReferenceToExternal( ast: o.Expression, value: any, ctx: EmitterVisitorContext, ): void { let id = this._evalArgValues.indexOf(value); if (id === -1) { id = this._evalArgValues.length; this._evalArgValues.push(value); const name = identifierName({reference: value}) || 'val'; this._evalArgNames.push(`jit_${name}_${id}`); } ctx.print(ast, this._evalArgNames[id]); } } function isUseStrictStatement(statement: o.Statement): boolean { return statement.isEquivalent(o.literal('use strict').toStmt()); }
{ "end_byte": 6199, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/output/output_jit.ts" }
angular/packages/compiler/src/template_parser/binding_parser.ts_0_1546
/** * @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 { AbsoluteSourceSpan, AST, ASTWithSource, Binary, BindingPipe, BindingType, BoundElementProperty, Conditional, EmptyExpr, KeyedRead, NonNullAssert, ParsedEvent, ParsedEventType, ParsedProperty, ParsedPropertyType, ParsedVariable, ParserError, PrefixNot, PropertyRead, RecursiveAstVisitor, TemplateBinding, VariableBinding, } from '../expression_parser/ast'; import {Parser} from '../expression_parser/parser'; import {InterpolationConfig} from '../ml_parser/defaults'; import {mergeNsAndName} from '../ml_parser/tags'; import {InterpolatedAttributeToken, InterpolatedTextToken} from '../ml_parser/tokens'; import {ParseError, ParseErrorLevel, ParseSourceSpan} from '../parse_util'; import {ElementSchemaRegistry} from '../schema/element_schema_registry'; import {CssSelector} from '../selector'; import {splitAtColon, splitAtPeriod} from '../util'; const PROPERTY_PARTS_SEPARATOR = '.'; const ATTRIBUTE_PREFIX = 'attr'; const CLASS_PREFIX = 'class'; const STYLE_PREFIX = 'style'; const TEMPLATE_ATTR_PREFIX = '*'; const ANIMATE_PROP_PREFIX = 'animate-'; export interface HostProperties { [key: string]: string; } export interface HostListeners { [key: string]: string; } /** * Parses bindings in templates and in the directive host area. */
{ "end_byte": 1546, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template_parser/binding_parser.ts" }
angular/packages/compiler/src/template_parser/binding_parser.ts_1547_10142
export class BindingParser { constructor( private _exprParser: Parser, private _interpolationConfig: InterpolationConfig, private _schemaRegistry: ElementSchemaRegistry, public errors: ParseError[], private _allowInvalidAssignmentEvents = false, ) {} get interpolationConfig(): InterpolationConfig { return this._interpolationConfig; } createBoundHostProperties( properties: HostProperties, sourceSpan: ParseSourceSpan, ): ParsedProperty[] | null { const boundProps: ParsedProperty[] = []; for (const propName of Object.keys(properties)) { const expression = properties[propName]; if (typeof expression === 'string') { this.parsePropertyBinding( propName, expression, true, false, sourceSpan, sourceSpan.start.offset, undefined, [], // Use the `sourceSpan` for `keySpan`. This isn't really accurate, but neither is the // sourceSpan, as it represents the sourceSpan of the host itself rather than the // source of the host binding (which doesn't exist in the template). Regardless, // neither of these values are used in Ivy but are only here to satisfy the function // signature. This should likely be refactored in the future so that `sourceSpan` // isn't being used inaccurately. boundProps, sourceSpan, ); } else { this._reportError( `Value of the host property binding "${propName}" needs to be a string representing an expression but got "${expression}" (${typeof expression})`, sourceSpan, ); } } return boundProps; } createDirectiveHostEventAsts( hostListeners: HostListeners, sourceSpan: ParseSourceSpan, ): ParsedEvent[] | null { const targetEvents: ParsedEvent[] = []; for (const propName of Object.keys(hostListeners)) { const expression = hostListeners[propName]; if (typeof expression === 'string') { // Use the `sourceSpan` for `keySpan` and `handlerSpan`. This isn't really accurate, but // neither is the `sourceSpan`, as it represents the `sourceSpan` of the host itself // rather than the source of the host binding (which doesn't exist in the template). // Regardless, neither of these values are used in Ivy but are only here to satisfy the // function signature. This should likely be refactored in the future so that `sourceSpan` // isn't being used inaccurately. this.parseEvent( propName, expression, /* isAssignmentEvent */ false, sourceSpan, sourceSpan, [], targetEvents, sourceSpan, ); } else { this._reportError( `Value of the host listener "${propName}" needs to be a string representing an expression but got "${expression}" (${typeof expression})`, sourceSpan, ); } } return targetEvents; } parseInterpolation( value: string, sourceSpan: ParseSourceSpan, interpolatedTokens: InterpolatedAttributeToken[] | InterpolatedTextToken[] | null, ): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); const absoluteOffset = sourceSpan.fullStart.offset; try { const ast = this._exprParser.parseInterpolation( value, sourceInfo, absoluteOffset, interpolatedTokens, this._interpolationConfig, )!; if (ast) this._reportExpressionParserErrors(ast.errors, sourceSpan); return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, 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, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); const absoluteOffset = sourceSpan.start.offset; try { const ast = this._exprParser.parseInterpolationExpression( expression, sourceInfo, absoluteOffset, ); if (ast) this._reportExpressionParserErrors(ast.errors, sourceSpan); return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset); } } /** * Parses the bindings in a microsyntax expression, and converts them to * `ParsedProperty` or `ParsedVariable`. * * @param tplKey template binding name * @param tplValue template binding value * @param sourceSpan span of template binding relative to entire the template * @param absoluteValueOffset start of the tplValue relative to the entire template * @param targetMatchableAttrs potential attributes to match in the template * @param targetProps target property bindings in the template * @param targetVars target variables in the template */ parseInlineTemplateBinding( tplKey: string, tplValue: string, sourceSpan: ParseSourceSpan, absoluteValueOffset: number, targetMatchableAttrs: string[][], targetProps: ParsedProperty[], targetVars: ParsedVariable[], isIvyAst: boolean, ) { const absoluteKeyOffset = sourceSpan.start.offset + TEMPLATE_ATTR_PREFIX.length; const bindings = this._parseTemplateBindings( tplKey, tplValue, sourceSpan, absoluteKeyOffset, absoluteValueOffset, ); for (const binding of bindings) { // sourceSpan is for the entire HTML attribute. bindingSpan is for a particular // binding within the microsyntax expression so it's more narrow than sourceSpan. const bindingSpan = moveParseSourceSpan(sourceSpan, binding.sourceSpan); const key = binding.key.source; const keySpan = moveParseSourceSpan(sourceSpan, binding.key.span); if (binding instanceof VariableBinding) { const value = binding.value ? binding.value.source : '$implicit'; const valueSpan = binding.value ? moveParseSourceSpan(sourceSpan, binding.value.span) : undefined; targetVars.push(new ParsedVariable(key, value, bindingSpan, keySpan, valueSpan)); } else if (binding.value) { const srcSpan = isIvyAst ? bindingSpan : sourceSpan; const valueSpan = moveParseSourceSpan(sourceSpan, binding.value.ast.sourceSpan); this._parsePropertyAst( key, binding.value, false, srcSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps, ); } else { targetMatchableAttrs.push([key, '' /* value */]); // Since this is a literal attribute with no RHS, source span should be // just the key span. this.parseLiteralAttr( key, null /* value */, keySpan, absoluteValueOffset, undefined /* valueSpan */, targetMatchableAttrs, targetProps, keySpan, ); } } } /** * Parses the bindings in a microsyntax expression, e.g. * ``` * <tag *tplKey="let value1 = prop; let value2 = localVar"> * ``` * * @param tplKey template binding name * @param tplValue template binding value * @param sourceSpan span of template binding relative to entire the template * @param absoluteKeyOffset start of the `tplKey` * @param absoluteValueOffset start of the `tplValue` */ private _parseTemplateBindings( tplKey: string, tplValue: string, sourceSpan: ParseSourceSpan, absoluteKeyOffset: number, absoluteValueOffset: number, ): TemplateBinding[] { const sourceInfo = sourceSpan.start.toString(); try { const bindingsResult = this._exprParser.parseTemplateBindings( tplKey, tplValue, sourceInfo, absoluteKeyOffset, absoluteValueOffset, ); this._reportExpressionParserErrors(bindingsResult.errors, sourceSpan); bindingsResult.warnings.forEach((warning) => { this._reportError(warning, sourceSpan, ParseErrorLevel.WARNING); }); return bindingsResult.templateBindings; } catch (e) { this._reportError(`${e}`, sourceSpan); return []; } }
{ "end_byte": 10142, "start_byte": 1547, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template_parser/binding_parser.ts" }
angular/packages/compiler/src/template_parser/binding_parser.ts_10146_16317
parseLiteralAttr( name: string, value: string | null, sourceSpan: ParseSourceSpan, absoluteOffset: number, valueSpan: ParseSourceSpan | undefined, targetMatchableAttrs: string[][], targetProps: ParsedProperty[], keySpan: ParseSourceSpan, ) { if (isAnimationLabel(name)) { name = name.substring(1); if (keySpan !== undefined) { keySpan = moveParseSourceSpan( keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset), ); } if (value) { this._reportError( `Assigning animation triggers via @prop="exp" attributes with an expression is invalid.` + ` Use property bindings (e.g. [@prop]="exp") or use an attribute without a value (e.g. @prop) instead.`, sourceSpan, ParseErrorLevel.ERROR, ); } this._parseAnimation( name, value, sourceSpan, absoluteOffset, keySpan, valueSpan, targetMatchableAttrs, targetProps, ); } else { targetProps.push( new ParsedProperty( name, this._exprParser.wrapLiteralPrimitive(value, '', absoluteOffset), ParsedPropertyType.LITERAL_ATTR, sourceSpan, keySpan, valueSpan, ), ); } } parsePropertyBinding( name: string, expression: string, isHost: boolean, isPartOfAssignmentBinding: boolean, sourceSpan: ParseSourceSpan, absoluteOffset: number, valueSpan: ParseSourceSpan | undefined, targetMatchableAttrs: string[][], targetProps: ParsedProperty[], keySpan: ParseSourceSpan, ) { if (name.length === 0) { this._reportError(`Property name is missing in binding`, sourceSpan); } let isAnimationProp = false; if (name.startsWith(ANIMATE_PROP_PREFIX)) { isAnimationProp = true; name = name.substring(ANIMATE_PROP_PREFIX.length); if (keySpan !== undefined) { keySpan = moveParseSourceSpan( keySpan, new AbsoluteSourceSpan( keySpan.start.offset + ANIMATE_PROP_PREFIX.length, keySpan.end.offset, ), ); } } else if (isAnimationLabel(name)) { isAnimationProp = true; name = name.substring(1); if (keySpan !== undefined) { keySpan = moveParseSourceSpan( keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset), ); } } if (isAnimationProp) { this._parseAnimation( name, expression, sourceSpan, absoluteOffset, keySpan, valueSpan, targetMatchableAttrs, targetProps, ); } else { this._parsePropertyAst( name, this.parseBinding(expression, isHost, valueSpan || sourceSpan, absoluteOffset), isPartOfAssignmentBinding, sourceSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps, ); } } parsePropertyInterpolation( name: string, value: string, sourceSpan: ParseSourceSpan, valueSpan: ParseSourceSpan | undefined, targetMatchableAttrs: string[][], targetProps: ParsedProperty[], keySpan: ParseSourceSpan, interpolatedTokens: InterpolatedAttributeToken[] | InterpolatedTextToken[] | null, ): boolean { const expr = this.parseInterpolation(value, valueSpan || sourceSpan, interpolatedTokens); if (expr) { this._parsePropertyAst( name, expr, false, sourceSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps, ); return true; } return false; } private _parsePropertyAst( name: string, ast: ASTWithSource, isPartOfAssignmentBinding: boolean, sourceSpan: ParseSourceSpan, keySpan: ParseSourceSpan, valueSpan: ParseSourceSpan | undefined, targetMatchableAttrs: string[][], targetProps: ParsedProperty[], ) { targetMatchableAttrs.push([name, ast.source!]); targetProps.push( new ParsedProperty( name, ast, isPartOfAssignmentBinding ? ParsedPropertyType.TWO_WAY : ParsedPropertyType.DEFAULT, sourceSpan, keySpan, valueSpan, ), ); } private _parseAnimation( name: string, expression: string | null, sourceSpan: ParseSourceSpan, absoluteOffset: number, keySpan: ParseSourceSpan, valueSpan: ParseSourceSpan | undefined, targetMatchableAttrs: string[][], targetProps: ParsedProperty[], ) { if (name.length === 0) { this._reportError('Animation trigger is missing', sourceSpan); } // This will occur when a @trigger is not paired with an expression. // For animations it is valid to not have an expression since */void // states will be applied by angular when the element is attached/detached const ast = this.parseBinding( expression || 'undefined', false, valueSpan || sourceSpan, absoluteOffset, ); targetMatchableAttrs.push([name, ast.source!]); targetProps.push( new ParsedProperty(name, ast, ParsedPropertyType.ANIMATION, sourceSpan, keySpan, valueSpan), ); } parseBinding( value: string, isHostBinding: boolean, sourceSpan: ParseSourceSpan, absoluteOffset: number, ): ASTWithSource { const sourceInfo = ((sourceSpan && sourceSpan.start) || '(unknown)').toString(); try { const ast = isHostBinding ? this._exprParser.parseSimpleBinding( value, sourceInfo, absoluteOffset, this._interpolationConfig, ) : this._exprParser.parseBinding( value, sourceInfo, absoluteOffset, this._interpolationConfig, ); if (ast) this._reportExpressionParserErrors(ast.errors, sourceSpan); return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset); } }
{ "end_byte": 16317, "start_byte": 10146, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template_parser/binding_parser.ts" }
angular/packages/compiler/src/template_parser/binding_parser.ts_16321_24921
createBoundElementProperty( elementSelector: string, boundProp: ParsedProperty, skipValidation: boolean = false, mapPropertyName: boolean = true, ): BoundElementProperty { if (boundProp.isAnimation) { return new BoundElementProperty( boundProp.name, BindingType.Animation, SecurityContext.NONE, boundProp.expression, null, boundProp.sourceSpan, boundProp.keySpan, boundProp.valueSpan, ); } let unit: string | null = null; let bindingType: BindingType = undefined!; let boundPropertyName: string | null = null; const parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR); let securityContexts: SecurityContext[] = undefined!; // Check for special cases (prefix style, attr, class) if (parts.length > 1) { if (parts[0] == ATTRIBUTE_PREFIX) { boundPropertyName = parts.slice(1).join(PROPERTY_PARTS_SEPARATOR); if (!skipValidation) { this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, true); } securityContexts = calcPossibleSecurityContexts( this._schemaRegistry, elementSelector, boundPropertyName, true, ); const nsSeparatorIdx = boundPropertyName.indexOf(':'); if (nsSeparatorIdx > -1) { const ns = boundPropertyName.substring(0, nsSeparatorIdx); const name = boundPropertyName.substring(nsSeparatorIdx + 1); boundPropertyName = mergeNsAndName(ns, name); } bindingType = BindingType.Attribute; } else if (parts[0] == CLASS_PREFIX) { boundPropertyName = parts[1]; bindingType = BindingType.Class; securityContexts = [SecurityContext.NONE]; } else if (parts[0] == STYLE_PREFIX) { unit = parts.length > 2 ? parts[2] : null; boundPropertyName = parts[1]; bindingType = BindingType.Style; securityContexts = [SecurityContext.STYLE]; } } // If not a special case, use the full property name if (boundPropertyName === null) { const mappedPropName = this._schemaRegistry.getMappedPropName(boundProp.name); boundPropertyName = mapPropertyName ? mappedPropName : boundProp.name; securityContexts = calcPossibleSecurityContexts( this._schemaRegistry, elementSelector, mappedPropName, false, ); bindingType = boundProp.type === ParsedPropertyType.TWO_WAY ? BindingType.TwoWay : BindingType.Property; if (!skipValidation) { this._validatePropertyOrAttributeName(mappedPropName, boundProp.sourceSpan, false); } } return new BoundElementProperty( boundPropertyName, bindingType, securityContexts[0], boundProp.expression, unit, boundProp.sourceSpan, boundProp.keySpan, boundProp.valueSpan, ); } // TODO: keySpan should be required but was made optional to avoid changing VE parser. parseEvent( name: string, expression: string, isAssignmentEvent: boolean, sourceSpan: ParseSourceSpan, handlerSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetEvents: ParsedEvent[], keySpan: ParseSourceSpan, ) { if (name.length === 0) { this._reportError(`Event name is missing in binding`, sourceSpan); } if (isAnimationLabel(name)) { name = name.slice(1); if (keySpan !== undefined) { keySpan = moveParseSourceSpan( keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset), ); } this._parseAnimationEvent(name, expression, sourceSpan, handlerSpan, targetEvents, keySpan); } else { this._parseRegularEvent( name, expression, isAssignmentEvent, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents, keySpan, ); } } calcPossibleSecurityContexts( selector: string, propName: string, isAttribute: boolean, ): SecurityContext[] { const prop = this._schemaRegistry.getMappedPropName(propName); return calcPossibleSecurityContexts(this._schemaRegistry, selector, prop, isAttribute); } private _parseAnimationEvent( name: string, expression: string, sourceSpan: ParseSourceSpan, handlerSpan: ParseSourceSpan, targetEvents: ParsedEvent[], keySpan: ParseSourceSpan, ) { const matches = splitAtPeriod(name, [name, '']); const eventName = matches[0]; const phase = matches[1].toLowerCase(); const ast = this._parseAction(expression, handlerSpan); targetEvents.push( new ParsedEvent( eventName, phase, ParsedEventType.Animation, ast, sourceSpan, handlerSpan, keySpan, ), ); if (eventName.length === 0) { this._reportError(`Animation event name is missing in binding`, sourceSpan); } if (phase) { if (phase !== 'start' && phase !== 'done') { this._reportError( `The provided animation output phase value "${phase}" for "@${eventName}" is not supported (use start or done)`, sourceSpan, ); } } else { this._reportError( `The animation trigger output event (@${eventName}) is missing its phase value name (start or done are currently supported)`, sourceSpan, ); } } private _parseRegularEvent( name: string, expression: string, isAssignmentEvent: boolean, sourceSpan: ParseSourceSpan, handlerSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetEvents: ParsedEvent[], keySpan: ParseSourceSpan, ): void { // long format: 'target: eventName' const [target, eventName] = splitAtColon(name, [null!, name]); const prevErrorCount = this.errors.length; const ast = this._parseAction(expression, handlerSpan); const isValid = this.errors.length === prevErrorCount; targetMatchableAttrs.push([name!, ast.source!]); // Don't try to validate assignment events if there were other // parsing errors to avoid adding more noise to the error logs. if (isAssignmentEvent && isValid && !this._isAllowedAssignmentEvent(ast)) { this._reportError('Unsupported expression in a two-way binding', sourceSpan); } targetEvents.push( new ParsedEvent( eventName, target, isAssignmentEvent ? ParsedEventType.TwoWay : ParsedEventType.Regular, ast, sourceSpan, handlerSpan, keySpan, ), ); // Don't detect directives for event names for now, // so don't add the event name to the matchableAttrs } private _parseAction(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = ((sourceSpan && sourceSpan.start) || '(unknown').toString(); const absoluteOffset = sourceSpan && sourceSpan.start ? sourceSpan.start.offset : 0; try { const ast = this._exprParser.parseAction( value, sourceInfo, absoluteOffset, this._interpolationConfig, ); if (ast) { this._reportExpressionParserErrors(ast.errors, sourceSpan); } if (!ast || ast.ast instanceof EmptyExpr) { this._reportError(`Empty expressions are not allowed`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset); } return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset); } } private _reportError( message: string, sourceSpan: ParseSourceSpan, level: ParseErrorLevel = ParseErrorLevel.ERROR, ) { this.errors.push(new ParseError(sourceSpan, message, level)); } private _reportExpressionParserErrors(errors: ParserError[], sourceSpan: ParseSourceSpan) { for (const error of errors) { this._reportError(error.message, sourceSpan); } } /** * @param propName the name of the property / attribute * @param sourceSpan * @param isAttr true when binding to an attribute */ private _validatePropertyOrAttributeName( propName: string, sourceSpan: ParseSourceSpan, isAttr: boolean, ): void { const report = isAttr ? this._schemaRegistry.validateAttribute(propName) : this._schemaRegistry.validateProperty(propName); if (report.error) { this._reportError(report.msg!, sourceSpan, ParseErrorLevel.ERROR); } }
{ "end_byte": 24921, "start_byte": 16321, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template_parser/binding_parser.ts" }
angular/packages/compiler/src/template_parser/binding_parser.ts_24925_27984
/** * Returns whether a parsed AST is allowed to be used within the event side of a two-way binding. * @param ast Parsed AST to be checked. */ private _isAllowedAssignmentEvent(ast: AST): boolean { if (ast instanceof ASTWithSource) { return this._isAllowedAssignmentEvent(ast.ast); } if (ast instanceof NonNullAssert) { return this._isAllowedAssignmentEvent(ast.expression); } if (ast instanceof PropertyRead || ast instanceof KeyedRead) { return true; } // TODO(crisbeto): this logic is only here to support the automated migration away // from invalid bindings. It should be removed once the migration is deleted. if (!this._allowInvalidAssignmentEvents) { return false; } if (ast instanceof Binary) { return ( (ast.operation === '&&' || ast.operation === '||' || ast.operation === '??') && (ast.right instanceof PropertyRead || ast.right instanceof KeyedRead) ); } return ast instanceof Conditional || ast instanceof PrefixNot; } } export class PipeCollector extends RecursiveAstVisitor { pipes = new Map<string, BindingPipe>(); override visitPipe(ast: BindingPipe, context: any): any { this.pipes.set(ast.name, ast); ast.exp.visit(this); this.visitAll(ast.args, context); return null; } } function isAnimationLabel(name: string): boolean { return name[0] == '@'; } export function calcPossibleSecurityContexts( registry: ElementSchemaRegistry, selector: string, propName: string, isAttribute: boolean, ): SecurityContext[] { const ctxs: SecurityContext[] = []; CssSelector.parse(selector).forEach((selector) => { const elementNames = selector.element ? [selector.element] : registry.allKnownElementNames(); const notElementNames = new Set( selector.notSelectors .filter((selector) => selector.isElementSelector()) .map((selector) => selector.element), ); const possibleElementNames = elementNames.filter( (elementName) => !notElementNames.has(elementName), ); ctxs.push( ...possibleElementNames.map((elementName) => registry.securityContext(elementName, propName, isAttribute), ), ); }); return ctxs.length === 0 ? [SecurityContext.NONE] : Array.from(new Set(ctxs)).sort(); } /** * Compute a new ParseSourceSpan based off an original `sourceSpan` by using * absolute offsets from the specified `absoluteSpan`. * * @param sourceSpan original source span * @param absoluteSpan absolute source span to move to */ function moveParseSourceSpan( sourceSpan: ParseSourceSpan, absoluteSpan: AbsoluteSourceSpan, ): ParseSourceSpan { // The difference of two absolute offsets provide the relative offset const startDiff = absoluteSpan.start - sourceSpan.start.offset; const endDiff = absoluteSpan.end - sourceSpan.end.offset; return new ParseSourceSpan( sourceSpan.start.moveBy(startDiff), sourceSpan.end.moveBy(endDiff), sourceSpan.fullStart.moveBy(startDiff), sourceSpan.details, ); }
{ "end_byte": 27984, "start_byte": 24925, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template_parser/binding_parser.ts" }
angular/packages/compiler/src/template_parser/template_preparser.ts_0_2469
/** * @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 {isNgContent} from '../ml_parser/tags'; const NG_CONTENT_SELECT_ATTR = 'select'; const LINK_ELEMENT = 'link'; const LINK_STYLE_REL_ATTR = 'rel'; const LINK_STYLE_HREF_ATTR = 'href'; const LINK_STYLE_REL_VALUE = 'stylesheet'; const STYLE_ELEMENT = 'style'; const SCRIPT_ELEMENT = 'script'; const NG_NON_BINDABLE_ATTR = 'ngNonBindable'; const NG_PROJECT_AS = 'ngProjectAs'; export function preparseElement(ast: html.Element): PreparsedElement { let selectAttr: string | null = null; let hrefAttr: string | null = null; let relAttr: string | null = null; let nonBindable = false; let projectAs = ''; ast.attrs.forEach((attr) => { const lcAttrName = attr.name.toLowerCase(); if (lcAttrName == NG_CONTENT_SELECT_ATTR) { selectAttr = attr.value; } else if (lcAttrName == LINK_STYLE_HREF_ATTR) { hrefAttr = attr.value; } else if (lcAttrName == LINK_STYLE_REL_ATTR) { relAttr = attr.value; } else if (attr.name == NG_NON_BINDABLE_ATTR) { nonBindable = true; } else if (attr.name == NG_PROJECT_AS) { if (attr.value.length > 0) { projectAs = attr.value; } } }); selectAttr = normalizeNgContentSelect(selectAttr); const nodeName = ast.name.toLowerCase(); let type = PreparsedElementType.OTHER; if (isNgContent(nodeName)) { type = PreparsedElementType.NG_CONTENT; } else if (nodeName == STYLE_ELEMENT) { type = PreparsedElementType.STYLE; } else if (nodeName == SCRIPT_ELEMENT) { type = PreparsedElementType.SCRIPT; } else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) { type = PreparsedElementType.STYLESHEET; } return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs); } export enum PreparsedElementType { NG_CONTENT, STYLE, STYLESHEET, SCRIPT, OTHER, } export class PreparsedElement { constructor( public type: PreparsedElementType, public selectAttr: string, public hrefAttr: string | null, public nonBindable: boolean, public projectAs: string, ) {} } function normalizeNgContentSelect(selectAttr: string | null): string { if (selectAttr === null || selectAttr.length === 0) { return '*'; } return selectAttr; }
{ "end_byte": 2469, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template_parser/template_preparser.ts" }
angular/packages/compiler/src/schema/trusted_types_sinks.ts_0_1592
/** * @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 */ /** * Set of tagName|propertyName corresponding to Trusted Types sinks. Properties applying to all * tags use '*'. * * Extracted from, and should be kept in sync with * https://w3c.github.io/webappsec-trusted-types/dist/spec/#integrations */ const TRUSTED_TYPES_SINKS = new Set<string>([ // NOTE: All strings in this set *must* be lowercase! // TrustedHTML 'iframe|srcdoc', '*|innerhtml', '*|outerhtml', // NB: no TrustedScript here, as the corresponding tags are stripped by the compiler. // TrustedScriptURL 'embed|src', 'object|codebase', 'object|data', ]); /** * isTrustedTypesSink returns true if the given property on the given DOM tag is a Trusted Types * sink. In that case, use `ElementSchemaRegistry.securityContext` to determine which particular * Trusted Type is required for values passed to the sink: * - SecurityContext.HTML corresponds to TrustedHTML * - SecurityContext.RESOURCE_URL corresponds to TrustedScriptURL */ export function isTrustedTypesSink(tagName: string, propName: string): boolean { // Make sure comparisons are case insensitive, so that case differences between attribute and // property names do not have a security impact. tagName = tagName.toLowerCase(); propName = propName.toLowerCase(); return ( TRUSTED_TYPES_SINKS.has(tagName + '|' + propName) || TRUSTED_TYPES_SINKS.has('*|' + propName) ); }
{ "end_byte": 1592, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/schema/trusted_types_sinks.ts" }
angular/packages/compiler/src/schema/element_schema_registry.ts_0_1148
/** * @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 {SchemaMetadata, SecurityContext} from '../core'; export abstract class ElementSchemaRegistry { abstract hasProperty(tagName: string, propName: string, schemaMetas: SchemaMetadata[]): boolean; abstract hasElement(tagName: string, schemaMetas: SchemaMetadata[]): boolean; abstract securityContext( elementName: string, propName: string, isAttribute: boolean, ): SecurityContext; abstract allKnownElementNames(): string[]; abstract getMappedPropName(propName: string): string; abstract getDefaultComponentElementName(): string; abstract validateProperty(name: string): {error: boolean; msg?: string}; abstract validateAttribute(name: string): {error: boolean; msg?: string}; abstract normalizeAnimationStyleProperty(propName: string): string; abstract normalizeAnimationStyleValue( camelCaseProp: string, userProvidedProp: string, val: string | number, ): {error: string; value: string}; }
{ "end_byte": 1148, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/schema/element_schema_registry.ts" }
angular/packages/compiler/src/schema/dom_element_schema_registry.ts_0_3072
/** * @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 {CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA, SchemaMetadata, SecurityContext} from '../core'; import {isNgContainer, isNgContent} from '../ml_parser/tags'; import {dashCaseToCamelCase} from '../util'; import {SECURITY_SCHEMA} from './dom_security_schema'; import {ElementSchemaRegistry} from './element_schema_registry'; const BOOLEAN = 'boolean'; const NUMBER = 'number'; const STRING = 'string'; const OBJECT = 'object'; /** * This array represents the DOM schema. It encodes inheritance, properties, and events. * * ## Overview * * Each line represents one kind of element. The `element_inheritance` and properties are joined * using `element_inheritance|properties` syntax. * * ## Element Inheritance * * The `element_inheritance` can be further subdivided as `element1,element2,...^parentElement`. * Here the individual elements are separated by `,` (commas). Every element in the list * has identical properties. * * An `element` may inherit additional properties from `parentElement` If no `^parentElement` is * specified then `""` (blank) element is assumed. * * NOTE: The blank element inherits from root `[Element]` element, the super element of all * elements. * * NOTE an element prefix such as `:svg:` has no special meaning to the schema. * * ## Properties * * Each element has a set of properties separated by `,` (commas). Each property can be prefixed * by a special character designating its type: * * - (no prefix): property is a string. * - `*`: property represents an event. * - `!`: property is a boolean. * - `#`: property is a number. * - `%`: property is an object. * * ## Query * * The class creates an internal squas representation which allows to easily answer the query of * if a given property exist on a given element. * * NOTE: We don't yet support querying for types or events. * NOTE: This schema is auto extracted from `schema_extractor.ts` located in the test folder, * see dom_element_schema_registry_spec.ts */ // ================================================================================================= // ================================================================================================= // =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P =========== // ================================================================================================= // ================================================================================================= // // DO NOT EDIT THIS DOM SCHEMA WITHOUT A SECURITY REVIEW! // // Newly added properties must be security reviewed and assigned an appropriate SecurityContext in // dom_security_schema.ts. Reach out to mprobst & rjamet for details. // // =================================================================================================
{ "end_byte": 3072, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/schema/dom_element_schema_registry.ts" }
angular/packages/compiler/src/schema/dom_element_schema_registry.ts_3074_10720
const SCHEMA: string[] = [ '[Element]|textContent,%ariaAtomic,%ariaAutoComplete,%ariaBusy,%ariaChecked,%ariaColCount,%ariaColIndex,%ariaColSpan,%ariaCurrent,%ariaDescription,%ariaDisabled,%ariaExpanded,%ariaHasPopup,%ariaHidden,%ariaKeyShortcuts,%ariaLabel,%ariaLevel,%ariaLive,%ariaModal,%ariaMultiLine,%ariaMultiSelectable,%ariaOrientation,%ariaPlaceholder,%ariaPosInSet,%ariaPressed,%ariaReadOnly,%ariaRelevant,%ariaRequired,%ariaRoleDescription,%ariaRowCount,%ariaRowIndex,%ariaRowSpan,%ariaSelected,%ariaSetSize,%ariaSort,%ariaValueMax,%ariaValueMin,%ariaValueNow,%ariaValueText,%classList,className,elementTiming,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*fullscreenchange,*fullscreenerror,*search,*webkitfullscreenchange,*webkitfullscreenerror,outerHTML,%part,#scrollLeft,#scrollTop,slot' + /* added manually to avoid breaking changes */ ',*message,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored', '[HTMLElement]^[Element]|accessKey,autocapitalize,!autofocus,contentEditable,dir,!draggable,enterKeyHint,!hidden,!inert,innerText,inputMode,lang,nonce,*abort,*animationend,*animationiteration,*animationstart,*auxclick,*beforexrselect,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*formdata,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*paste,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerrawupdate,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*securitypolicyviolation,*seeked,*seeking,*select,*selectionchange,*selectstart,*slotchange,*stalled,*submit,*suspend,*timeupdate,*toggle,*transitioncancel,*transitionend,*transitionrun,*transitionstart,*volumechange,*waiting,*webkitanimationend,*webkitanimationiteration,*webkitanimationstart,*webkittransitionend,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate,virtualKeyboardPolicy', 'abbr,address,article,aside,b,bdi,bdo,cite,content,code,dd,dfn,dt,em,figcaption,figure,footer,header,hgroup,i,kbd,main,mark,nav,noscript,rb,rp,rt,rtc,ruby,s,samp,section,small,strong,sub,sup,u,var,wbr^[HTMLElement]|accessKey,autocapitalize,!autofocus,contentEditable,dir,!draggable,enterKeyHint,!hidden,innerText,inputMode,lang,nonce,*abort,*animationend,*animationiteration,*animationstart,*auxclick,*beforexrselect,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*formdata,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*paste,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerrawupdate,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*securitypolicyviolation,*seeked,*seeking,*select,*selectionchange,*selectstart,*slotchange,*stalled,*submit,*suspend,*timeupdate,*toggle,*transitioncancel,*transitionend,*transitionrun,*transitionstart,*volumechange,*waiting,*webkitanimationend,*webkitanimationiteration,*webkitanimationstart,*webkittransitionend,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate,virtualKeyboardPolicy', 'media^[HTMLElement]|!autoplay,!controls,%controlsList,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,*waitingforkey,#playbackRate,preload,!preservesPitch,src,%srcObject,#volume', ':svg:^[HTMLElement]|!autofocus,nonce,*abort,*animationend,*animationiteration,*animationstart,*auxclick,*beforexrselect,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*formdata,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*paste,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerrawupdate,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*securitypolicyviolation,*seeked,*seeking,*select,*selectionchange,*selectstart,*slotchange,*stalled,*submit,*suspend,*timeupdate,*toggle,*transitioncancel,*transitionend,*transitionrun,*transitionstart,*volumechange,*waiting,*webkitanimationend,*webkitanimationiteration,*webkitanimationstart,*webkittransitionend,*wheel,%style,#tabIndex', ':svg:graphics^:svg:|', ':svg:animation^:svg:|*begin,*end,*repeat', ':svg:geometry^:svg:|', ':svg:componentTransferFunction^:svg:|', ':svg:gradient^:svg:|', ':svg:textContent^:svg:graphics|', ':svg:textPositioning^:svg:textContent|', 'a^[HTMLElement]|charset,coords,download,hash,host,hostname,href,hreflang,name,password,pathname,ping,port,protocol,referrerPolicy,rel,%relList,rev,search,shape,target,text,type,username', 'area^[HTMLElement]|alt,coords,download,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,rel,%relList,search,shape,target,username', 'audio^media|', 'br^[HTMLElement]|clear', 'base^[HTMLElement]|href,target', 'body^[HTMLElement]|aLink,background,bgColor,link,*afterprint,*beforeprint,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*messageerror,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,text,vLink', 'button^[HTMLElement]|!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value', 'canvas^[HTMLElement]|#height,#width', 'content^[HTMLElement]|select', 'dl^[HTMLElement]|!compact', 'data^[HTMLElement]|value', 'datalist^[HTMLElement]|', 'details^[HTMLElement]|!open', 'dialog^[HTMLElement]|!open,returnValue', 'dir^[HTMLElement]|!compact', 'div^[HTMLElement]|align', 'embed^[HTMLElement]|align,height,name,src,type,width', 'fieldset^[HTMLElement]|!disabled,name', 'font^[HTMLElement]|color,face,size', 'form^[HTMLElement]|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target', 'frame^[HTMLElement]|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src', 'frameset^[HTMLElement]|cols,*afterprint,*beforeprint,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*messageerror,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows', 'hr^[HTMLElement]|align,color,!noShade,size,width', 'head^[HTMLElement]|', 'h1,h2,h3,h4,h5,h6^[HTMLElement]|align', 'html^[HTMLElement]|version', 'iframe^[HTMLElement]|align,allow,!allowFullscreen,!allowPaymentRequest,csp,frameBorder,height,loading,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width', 'img^[HTMLElement]|align,alt,border,%crossOrigin,decoding,#height,#hspace,!isMap,loading,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width',
{ "end_byte": 10720, "start_byte": 3074, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/schema/dom_element_schema_registry.ts" }
angular/packages/compiler/src/schema/dom_element_schema_registry.ts_10723_17287
'input^[HTMLElement]|accept,align,alt,autocomplete,!checked,!defaultChecked,defaultValue,dirName,!disabled,%files,formAction,formEnctype,formMethod,!formNoValidate,formTarget,#height,!incremental,!indeterminate,max,#maxLength,min,#minLength,!multiple,name,pattern,placeholder,!readOnly,!required,selectionDirection,#selectionEnd,#selectionStart,#size,src,step,type,useMap,value,%valueAsDate,#valueAsNumber,#width', 'li^[HTMLElement]|type,#value', 'label^[HTMLElement]|htmlFor', 'legend^[HTMLElement]|align', 'link^[HTMLElement]|as,charset,%crossOrigin,!disabled,href,hreflang,imageSizes,imageSrcset,integrity,media,referrerPolicy,rel,%relList,rev,%sizes,target,type', 'map^[HTMLElement]|name', 'marquee^[HTMLElement]|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width', 'menu^[HTMLElement]|!compact', 'meta^[HTMLElement]|content,httpEquiv,media,name,scheme', 'meter^[HTMLElement]|#high,#low,#max,#min,#optimum,#value', 'ins,del^[HTMLElement]|cite,dateTime', 'ol^[HTMLElement]|!compact,!reversed,#start,type', 'object^[HTMLElement]|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width', 'optgroup^[HTMLElement]|!disabled,label', 'option^[HTMLElement]|!defaultSelected,!disabled,label,!selected,text,value', 'output^[HTMLElement]|defaultValue,%htmlFor,name,value', 'p^[HTMLElement]|align', 'param^[HTMLElement]|name,type,value,valueType', 'picture^[HTMLElement]|', 'pre^[HTMLElement]|#width', 'progress^[HTMLElement]|#max,#value', 'q,blockquote,cite^[HTMLElement]|', 'script^[HTMLElement]|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,!noModule,%referrerPolicy,src,text,type', 'select^[HTMLElement]|autocomplete,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value', 'slot^[HTMLElement]|name', 'source^[HTMLElement]|#height,media,sizes,src,srcset,type,#width', 'span^[HTMLElement]|', 'style^[HTMLElement]|!disabled,media,type', 'caption^[HTMLElement]|align', 'th,td^[HTMLElement]|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width', 'col,colgroup^[HTMLElement]|align,ch,chOff,#span,vAlign,width', 'table^[HTMLElement]|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width', 'tr^[HTMLElement]|align,bgColor,ch,chOff,vAlign', 'tfoot,thead,tbody^[HTMLElement]|align,ch,chOff,vAlign', 'template^[HTMLElement]|', 'textarea^[HTMLElement]|autocomplete,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap', 'time^[HTMLElement]|dateTime', 'title^[HTMLElement]|text', 'track^[HTMLElement]|!default,kind,label,src,srclang', 'ul^[HTMLElement]|!compact,type', 'unknown^[HTMLElement]|', 'video^media|!disablePictureInPicture,#height,*enterpictureinpicture,*leavepictureinpicture,!playsInline,poster,#width', ':svg:a^:svg:graphics|', ':svg:animate^:svg:animation|', ':svg:animateMotion^:svg:animation|', ':svg:animateTransform^:svg:animation|', ':svg:circle^:svg:geometry|', ':svg:clipPath^:svg:graphics|', ':svg:defs^:svg:graphics|', ':svg:desc^:svg:|', ':svg:discard^:svg:|', ':svg:ellipse^:svg:geometry|', ':svg:feBlend^:svg:|', ':svg:feColorMatrix^:svg:|', ':svg:feComponentTransfer^:svg:|', ':svg:feComposite^:svg:|', ':svg:feConvolveMatrix^:svg:|', ':svg:feDiffuseLighting^:svg:|', ':svg:feDisplacementMap^:svg:|', ':svg:feDistantLight^:svg:|', ':svg:feDropShadow^:svg:|', ':svg:feFlood^:svg:|', ':svg:feFuncA^:svg:componentTransferFunction|', ':svg:feFuncB^:svg:componentTransferFunction|', ':svg:feFuncG^:svg:componentTransferFunction|', ':svg:feFuncR^:svg:componentTransferFunction|', ':svg:feGaussianBlur^:svg:|', ':svg:feImage^:svg:|', ':svg:feMerge^:svg:|', ':svg:feMergeNode^:svg:|', ':svg:feMorphology^:svg:|', ':svg:feOffset^:svg:|', ':svg:fePointLight^:svg:|', ':svg:feSpecularLighting^:svg:|', ':svg:feSpotLight^:svg:|', ':svg:feTile^:svg:|', ':svg:feTurbulence^:svg:|', ':svg:filter^:svg:|', ':svg:foreignObject^:svg:graphics|', ':svg:g^:svg:graphics|', ':svg:image^:svg:graphics|decoding', ':svg:line^:svg:geometry|', ':svg:linearGradient^:svg:gradient|', ':svg:mpath^:svg:|', ':svg:marker^:svg:|', ':svg:mask^:svg:|', ':svg:metadata^:svg:|', ':svg:path^:svg:geometry|', ':svg:pattern^:svg:|', ':svg:polygon^:svg:geometry|', ':svg:polyline^:svg:geometry|', ':svg:radialGradient^:svg:gradient|', ':svg:rect^:svg:geometry|', ':svg:svg^:svg:graphics|#currentScale,#zoomAndPan', ':svg:script^:svg:|type', ':svg:set^:svg:animation|', ':svg:stop^:svg:|', ':svg:style^:svg:|!disabled,media,title,type', ':svg:switch^:svg:graphics|', ':svg:symbol^:svg:|', ':svg:tspan^:svg:textPositioning|', ':svg:text^:svg:textPositioning|', ':svg:textPath^:svg:textContent|', ':svg:title^:svg:|', ':svg:use^:svg:graphics|', ':svg:view^:svg:|#zoomAndPan', 'data^[HTMLElement]|value', 'keygen^[HTMLElement]|!autofocus,challenge,!disabled,form,keytype,name', 'menuitem^[HTMLElement]|type,label,icon,!disabled,!checked,radiogroup,!default', 'summary^[HTMLElement]|', 'time^[HTMLElement]|dateTime', ':svg:cursor^:svg:|', ':math:^[HTMLElement]|!autofocus,nonce,*abort,*animationend,*animationiteration,*animationstart,*auxclick,*beforeinput,*beforematch,*beforetoggle,*beforexrselect,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contentvisibilityautostatechange,*contextlost,*contextmenu,*contextrestored,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*formdata,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*paste,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerrawupdate,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*scrollend,*securitypolicyviolation,*seeked,*seeking,*select,*selectionchange,*selectstart,*slotchange,*stalled,*submit,*suspend,*timeupdate,*toggle,*transitioncancel,*transitionend,*transitionrun,*transitionstart,*volumechange,*waiting,*webkitanimationend,*webkitanimationiteration,*webkitanimationstart,*webkittransitionend,*wheel,%style,#tabIndex',
{ "end_byte": 17287, "start_byte": 10723, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/schema/dom_element_schema_registry.ts" }
angular/packages/compiler/src/schema/dom_element_schema_registry.ts_17290_18493
':math:math^:math:|', ':math:maction^:math:|', ':math:menclose^:math:|', ':math:merror^:math:|', ':math:mfenced^:math:|', ':math:mfrac^:math:|', ':math:mi^:math:|', ':math:mmultiscripts^:math:|', ':math:mn^:math:|', ':math:mo^:math:|', ':math:mover^:math:|', ':math:mpadded^:math:|', ':math:mphantom^:math:|', ':math:mroot^:math:|', ':math:mrow^:math:|', ':math:ms^:math:|', ':math:mspace^:math:|', ':math:msqrt^:math:|', ':math:mstyle^:math:|', ':math:msub^:math:|', ':math:msubsup^:math:|', ':math:msup^:math:|', ':math:mtable^:math:|', ':math:mtd^:math:|', ':math:mtext^:math:|', ':math:mtr^:math:|', ':math:munder^:math:|', ':math:munderover^:math:|', ':math:semantics^:math:|', ]; const _ATTR_TO_PROP = new Map( Object.entries({ 'class': 'className', 'for': 'htmlFor', 'formaction': 'formAction', 'innerHtml': 'innerHTML', 'readonly': 'readOnly', 'tabindex': 'tabIndex', }), ); // Invert _ATTR_TO_PROP. const _PROP_TO_ATTR = Array.from(_ATTR_TO_PROP).reduce( (inverted, [propertyName, attributeName]) => { inverted.set(propertyName, attributeName); return inverted; }, new Map<string, string>(), );
{ "end_byte": 18493, "start_byte": 17290, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/schema/dom_element_schema_registry.ts" }
angular/packages/compiler/src/schema/dom_element_schema_registry.ts_18495_26064
export class DomElementSchemaRegistry extends ElementSchemaRegistry { private _schema = new Map<string, Map<string, string>>(); // We don't allow binding to events for security reasons. Allowing event bindings would almost // certainly introduce bad XSS vulnerabilities. Instead, we store events in a separate schema. private _eventSchema = new Map<string, Set<string>>(); constructor() { super(); SCHEMA.forEach((encodedType) => { const type = new Map<string, string>(); const events: Set<string> = new Set(); const [strType, strProperties] = encodedType.split('|'); const properties = strProperties.split(','); const [typeNames, superName] = strType.split('^'); typeNames.split(',').forEach((tag) => { this._schema.set(tag.toLowerCase(), type); this._eventSchema.set(tag.toLowerCase(), events); }); const superType = superName && this._schema.get(superName.toLowerCase()); if (superType) { for (const [prop, value] of superType) { type.set(prop, value); } for (const superEvent of this._eventSchema.get(superName.toLowerCase())!) { events.add(superEvent); } } properties.forEach((property: string) => { if (property.length > 0) { switch (property[0]) { case '*': events.add(property.substring(1)); break; case '!': type.set(property.substring(1), BOOLEAN); break; case '#': type.set(property.substring(1), NUMBER); break; case '%': type.set(property.substring(1), OBJECT); break; default: type.set(property, STRING); } } }); }); } override hasProperty(tagName: string, propName: string, schemaMetas: SchemaMetadata[]): boolean { if (schemaMetas.some((schema) => schema.name === NO_ERRORS_SCHEMA.name)) { return true; } if (tagName.indexOf('-') > -1) { if (isNgContainer(tagName) || isNgContent(tagName)) { return false; } if (schemaMetas.some((schema) => schema.name === CUSTOM_ELEMENTS_SCHEMA.name)) { // Can't tell now as we don't know which properties a custom element will get // once it is instantiated return true; } } const elementProperties = this._schema.get(tagName.toLowerCase()) || this._schema.get('unknown')!; return elementProperties.has(propName); } override hasElement(tagName: string, schemaMetas: SchemaMetadata[]): boolean { if (schemaMetas.some((schema) => schema.name === NO_ERRORS_SCHEMA.name)) { return true; } if (tagName.indexOf('-') > -1) { if (isNgContainer(tagName) || isNgContent(tagName)) { return true; } if (schemaMetas.some((schema) => schema.name === CUSTOM_ELEMENTS_SCHEMA.name)) { // Allow any custom elements return true; } } return this._schema.has(tagName.toLowerCase()); } /** * securityContext returns the security context for the given property on the given DOM tag. * * Tag and property name are statically known and cannot change at runtime, i.e. it is not * possible to bind a value into a changing attribute or tag name. * * The filtering is based on a list of allowed tags|attributes. All attributes in the schema * above are assumed to have the 'NONE' security context, i.e. that they are safe inert * string values. Only specific well known attack vectors are assigned their appropriate context. */ override securityContext( tagName: string, propName: string, isAttribute: boolean, ): SecurityContext { if (isAttribute) { // NB: For security purposes, use the mapped property name, not the attribute name. propName = this.getMappedPropName(propName); } // Make sure comparisons are case insensitive, so that case differences between attribute and // property names do not have a security impact. tagName = tagName.toLowerCase(); propName = propName.toLowerCase(); let ctx = SECURITY_SCHEMA()[tagName + '|' + propName]; if (ctx) { return ctx; } ctx = SECURITY_SCHEMA()['*|' + propName]; return ctx ? ctx : SecurityContext.NONE; } override getMappedPropName(propName: string): string { return _ATTR_TO_PROP.get(propName) ?? propName; } override getDefaultComponentElementName(): string { return 'ng-component'; } override validateProperty(name: string): {error: boolean; msg?: string} { if (name.toLowerCase().startsWith('on')) { const msg = `Binding to event property '${name}' is disallowed for security reasons, ` + `please use (${name.slice(2)})=...` + `\nIf '${name}' is a directive input, make sure the directive is imported by the` + ` current module.`; return {error: true, msg: msg}; } else { return {error: false}; } } override validateAttribute(name: string): {error: boolean; msg?: string} { if (name.toLowerCase().startsWith('on')) { const msg = `Binding to event attribute '${name}' is disallowed for security reasons, ` + `please use (${name.slice(2)})=...`; return {error: true, msg: msg}; } else { return {error: false}; } } override allKnownElementNames(): string[] { return Array.from(this._schema.keys()); } allKnownAttributesOfElement(tagName: string): string[] { const elementProperties = this._schema.get(tagName.toLowerCase()) || this._schema.get('unknown')!; // Convert properties to attributes. return Array.from(elementProperties.keys()).map((prop) => _PROP_TO_ATTR.get(prop) ?? prop); } allKnownEventsOfElement(tagName: string): string[] { return Array.from(this._eventSchema.get(tagName.toLowerCase()) ?? []); } override normalizeAnimationStyleProperty(propName: string): string { return dashCaseToCamelCase(propName); } override normalizeAnimationStyleValue( camelCaseProp: string, userProvidedProp: string, val: string | number, ): {error: string; value: string} { let unit: string = ''; const strVal = val.toString().trim(); let errorMsg: string = null!; if (_isPixelDimensionStyle(camelCaseProp) && val !== 0 && val !== '0') { if (typeof val === 'number') { unit = 'px'; } else { const valAndSuffixMatch = val.match(/^[+-]?[\d\.]+([a-z]*)$/); if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) { errorMsg = `Please provide a CSS unit value for ${userProvidedProp}:${val}`; } } } return {error: errorMsg, value: strVal + unit}; } } function _isPixelDimensionStyle(prop: string): boolean { switch (prop) { case 'width': case 'height': case 'minWidth': case 'minHeight': case 'maxWidth': case 'maxHeight': case 'left': case 'top': case 'bottom': case 'right': case 'fontSize': case 'outlineWidth': case 'outlineOffset': case 'paddingTop': case 'paddingLeft': case 'paddingBottom': case 'paddingRight': case 'marginTop': case 'marginLeft': case 'marginBottom': case 'marginRight': case 'borderRadius': case 'borderWidth': case 'borderTopWidth': case 'borderLeftWidth': case 'borderRightWidth': case 'borderBottomWidth': case 'textIndent': return true; default: return false; } }
{ "end_byte": 26064, "start_byte": 18495, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/schema/dom_element_schema_registry.ts" }
angular/packages/compiler/src/schema/dom_security_schema.ts_0_3484
/** * @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'; // ================================================================================================= // ================================================================================================= // =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P =========== // ================================================================================================= // ================================================================================================= // // DO NOT EDIT THIS LIST OF SECURITY SENSITIVE PROPERTIES WITHOUT A SECURITY REVIEW! // Reach out to mprobst for details. // // ================================================================================================= /** Map from tagName|propertyName to SecurityContext. Properties applying to all tags use '*'. */ let _SECURITY_SCHEMA!: {[k: string]: SecurityContext}; export function SECURITY_SCHEMA(): {[k: string]: SecurityContext} { if (!_SECURITY_SCHEMA) { _SECURITY_SCHEMA = {}; // Case is insignificant below, all element and attribute names are lower-cased for lookup. registerContext(SecurityContext.HTML, ['iframe|srcdoc', '*|innerHTML', '*|outerHTML']); registerContext(SecurityContext.STYLE, ['*|style']); // NB: no SCRIPT contexts here, they are never allowed due to the parser stripping them. registerContext(SecurityContext.URL, [ '*|formAction', 'area|href', 'area|ping', 'audio|src', 'a|href', 'a|ping', 'blockquote|cite', 'body|background', 'del|cite', 'form|action', 'img|src', 'input|src', 'ins|cite', 'q|cite', 'source|src', 'track|src', 'video|poster', 'video|src', ]); registerContext(SecurityContext.RESOURCE_URL, [ 'applet|code', 'applet|codebase', 'base|href', 'embed|src', 'frame|src', 'head|profile', 'html|manifest', 'iframe|src', 'link|href', 'media|src', 'object|codebase', 'object|data', 'script|src', ]); } return _SECURITY_SCHEMA; } function registerContext(ctx: SecurityContext, specs: string[]) { for (const spec of specs) _SECURITY_SCHEMA[spec.toLowerCase()] = ctx; } /** * The set of security-sensitive attributes of an `<iframe>` that *must* be * applied as a static attribute only. This ensures that all security-sensitive * attributes are taken into account while creating an instance of an `<iframe>` * at runtime. * * Note: avoid using this set directly, use the `isIframeSecuritySensitiveAttr` function * in the code instead. */ export const IFRAME_SECURITY_SENSITIVE_ATTRS = new Set([ 'sandbox', 'allow', 'allowfullscreen', 'referrerpolicy', 'csp', 'fetchpriority', ]); /** * Checks whether a given attribute name might represent a security-sensitive * attribute of an <iframe>. */ export function isIframeSecuritySensitiveAttr(attrName: string): boolean { // The `setAttribute` DOM API is case-insensitive, so we lowercase the value // before checking it against a known security-sensitive attributes. return IFRAME_SECURITY_SENSITIVE_ATTRS.has(attrName.toLowerCase()); }
{ "end_byte": 3484, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/schema/dom_security_schema.ts" }
angular/packages/compiler/src/render3/r3_ast.ts_0_8271
/** * @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 { AST, ASTWithSource, BindingType, BoundElementProperty, ParsedEvent, ParsedEventType, } from '../expression_parser/ast'; import {I18nMeta} from '../i18n/i18n_ast'; import {ParseSourceSpan} from '../parse_util'; export interface Node { sourceSpan: ParseSourceSpan; visit<Result>(visitor: Visitor<Result>): Result; } /** * This is an R3 `Node`-like wrapper for a raw `html.Comment` node. We do not currently * require the implementation of a visitor for Comments as they are only collected at * the top-level of the R3 AST, and only if `Render3ParseOptions['collectCommentNodes']` * is true. */ export class Comment implements Node { constructor( public value: string, public sourceSpan: ParseSourceSpan, ) {} visit<Result>(_visitor: Visitor<Result>): Result { throw new Error('visit() not implemented for Comment'); } } export class Text implements Node { constructor( public value: string, public sourceSpan: ParseSourceSpan, ) {} visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitText(this); } } export class BoundText implements Node { constructor( public value: AST, public sourceSpan: ParseSourceSpan, public i18n?: I18nMeta, ) {} visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitBoundText(this); } } /** * Represents a text attribute in the template. * * `valueSpan` may not be present in cases where there is no value `<div a></div>`. * `keySpan` may also not be present for synthetic attributes from ICU expansions. */ export class TextAttribute implements Node { constructor( public name: string, public value: string, public sourceSpan: ParseSourceSpan, readonly keySpan: ParseSourceSpan | undefined, public valueSpan?: ParseSourceSpan, public i18n?: I18nMeta, ) {} visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitTextAttribute(this); } } export class BoundAttribute implements Node { constructor( public name: string, public type: BindingType, public securityContext: SecurityContext, public value: AST, public unit: string | null, public sourceSpan: ParseSourceSpan, readonly keySpan: ParseSourceSpan, public valueSpan: ParseSourceSpan | undefined, public i18n: I18nMeta | undefined, ) {} static fromBoundElementProperty(prop: BoundElementProperty, i18n?: I18nMeta): BoundAttribute { if (prop.keySpan === undefined) { throw new Error( `Unexpected state: keySpan must be defined for bound attributes but was not for ${prop.name}: ${prop.sourceSpan}`, ); } return new BoundAttribute( prop.name, prop.type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan, prop.keySpan, prop.valueSpan, i18n, ); } visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitBoundAttribute(this); } } export class BoundEvent implements Node { constructor( public name: string, public type: ParsedEventType, public handler: AST, public target: string | null, public phase: string | null, public sourceSpan: ParseSourceSpan, public handlerSpan: ParseSourceSpan, readonly keySpan: ParseSourceSpan, ) {} static fromParsedEvent(event: ParsedEvent) { const target: string | null = event.type === ParsedEventType.Regular ? event.targetOrPhase : null; const phase: string | null = event.type === ParsedEventType.Animation ? event.targetOrPhase : null; if (event.keySpan === undefined) { throw new Error( `Unexpected state: keySpan must be defined for bound event but was not for ${event.name}: ${event.sourceSpan}`, ); } return new BoundEvent( event.name, event.type, event.handler, target, phase, event.sourceSpan, event.handlerSpan, event.keySpan, ); } visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitBoundEvent(this); } } export class Element implements Node { constructor( public name: string, public attributes: TextAttribute[], public inputs: BoundAttribute[], public outputs: BoundEvent[], public children: Node[], public references: Reference[], public sourceSpan: ParseSourceSpan, public startSourceSpan: ParseSourceSpan, public endSourceSpan: ParseSourceSpan | null, public i18n?: I18nMeta, ) {} visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitElement(this); } } export abstract class DeferredTrigger implements Node { constructor( public nameSpan: ParseSourceSpan | null, public sourceSpan: ParseSourceSpan, public prefetchSpan: ParseSourceSpan | null, public whenOrOnSourceSpan: ParseSourceSpan | null, public hydrateSpan: ParseSourceSpan | null, ) {} visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitDeferredTrigger(this); } } export class BoundDeferredTrigger extends DeferredTrigger { constructor( public value: AST, sourceSpan: ParseSourceSpan, prefetchSpan: ParseSourceSpan | null, whenSourceSpan: ParseSourceSpan, hydrateSpan: ParseSourceSpan | null, ) { // BoundDeferredTrigger is for 'when' triggers. These aren't really "triggers" and don't have a // nameSpan. Trigger names are the built in event triggers like hover, interaction, etc. super(/** nameSpan */ null, sourceSpan, prefetchSpan, whenSourceSpan, hydrateSpan); } } export class NeverDeferredTrigger extends DeferredTrigger {} export class IdleDeferredTrigger extends DeferredTrigger {} export class ImmediateDeferredTrigger extends DeferredTrigger {} export class HoverDeferredTrigger extends DeferredTrigger { constructor( public reference: string | null, nameSpan: ParseSourceSpan, sourceSpan: ParseSourceSpan, prefetchSpan: ParseSourceSpan | null, onSourceSpan: ParseSourceSpan | null, hydrateSpan: ParseSourceSpan | null, ) { super(nameSpan, sourceSpan, prefetchSpan, onSourceSpan, hydrateSpan); } } export class TimerDeferredTrigger extends DeferredTrigger { constructor( public delay: number, nameSpan: ParseSourceSpan, sourceSpan: ParseSourceSpan, prefetchSpan: ParseSourceSpan | null, onSourceSpan: ParseSourceSpan | null, hydrateSpan: ParseSourceSpan | null, ) { super(nameSpan, sourceSpan, prefetchSpan, onSourceSpan, hydrateSpan); } } export class InteractionDeferredTrigger extends DeferredTrigger { constructor( public reference: string | null, nameSpan: ParseSourceSpan, sourceSpan: ParseSourceSpan, prefetchSpan: ParseSourceSpan | null, onSourceSpan: ParseSourceSpan | null, hydrateSpan: ParseSourceSpan | null, ) { super(nameSpan, sourceSpan, prefetchSpan, onSourceSpan, hydrateSpan); } } export class ViewportDeferredTrigger extends DeferredTrigger { constructor( public reference: string | null, nameSpan: ParseSourceSpan, sourceSpan: ParseSourceSpan, prefetchSpan: ParseSourceSpan | null, onSourceSpan: ParseSourceSpan | null, hydrateSpan: ParseSourceSpan | null, ) { super(nameSpan, sourceSpan, prefetchSpan, onSourceSpan, hydrateSpan); } } export class BlockNode { constructor( public nameSpan: ParseSourceSpan, public sourceSpan: ParseSourceSpan, public startSourceSpan: ParseSourceSpan, public endSourceSpan: ParseSourceSpan | null, ) {} } export class DeferredBlockPlaceholder extends BlockNode implements Node { constructor( public children: Node[], public minimumTime: number | null, nameSpan: ParseSourceSpan, sourceSpan: ParseSourceSpan, startSourceSpan: ParseSourceSpan, endSourceSpan: ParseSourceSpan | null, public i18n?: I18nMeta, ) { super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan); } visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitDeferredBlockPlaceholder(this); } }
{ "end_byte": 8271, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_ast.ts" }
angular/packages/compiler/src/render3/r3_ast.ts_8273_16073
export class DeferredBlockLoading extends BlockNode implements Node { constructor( public children: Node[], public afterTime: number | null, public minimumTime: number | null, nameSpan: ParseSourceSpan, sourceSpan: ParseSourceSpan, startSourceSpan: ParseSourceSpan, endSourceSpan: ParseSourceSpan | null, public i18n?: I18nMeta, ) { super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan); } visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitDeferredBlockLoading(this); } } export class DeferredBlockError extends BlockNode implements Node { constructor( public children: Node[], nameSpan: ParseSourceSpan, sourceSpan: ParseSourceSpan, startSourceSpan: ParseSourceSpan, endSourceSpan: ParseSourceSpan | null, public i18n?: I18nMeta, ) { super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan); } visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitDeferredBlockError(this); } } export interface DeferredBlockTriggers { when?: BoundDeferredTrigger; idle?: IdleDeferredTrigger; immediate?: ImmediateDeferredTrigger; hover?: HoverDeferredTrigger; timer?: TimerDeferredTrigger; interaction?: InteractionDeferredTrigger; viewport?: ViewportDeferredTrigger; never?: NeverDeferredTrigger; } export class DeferredBlock extends BlockNode implements Node { readonly triggers: Readonly<DeferredBlockTriggers>; readonly prefetchTriggers: Readonly<DeferredBlockTriggers>; readonly hydrateTriggers: Readonly<DeferredBlockTriggers>; private readonly definedTriggers: (keyof DeferredBlockTriggers)[]; private readonly definedPrefetchTriggers: (keyof DeferredBlockTriggers)[]; private readonly definedHydrateTriggers: (keyof DeferredBlockTriggers)[]; constructor( public children: Node[], triggers: DeferredBlockTriggers, prefetchTriggers: DeferredBlockTriggers, hydrateTriggers: DeferredBlockTriggers, public placeholder: DeferredBlockPlaceholder | null, public loading: DeferredBlockLoading | null, public error: DeferredBlockError | null, nameSpan: ParseSourceSpan, sourceSpan: ParseSourceSpan, public mainBlockSpan: ParseSourceSpan, startSourceSpan: ParseSourceSpan, endSourceSpan: ParseSourceSpan | null, public i18n?: I18nMeta, ) { super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan); this.triggers = triggers; this.prefetchTriggers = prefetchTriggers; this.hydrateTriggers = hydrateTriggers; // We cache the keys since we know that they won't change and we // don't want to enumarate them every time we're traversing the AST. this.definedTriggers = Object.keys(triggers) as (keyof DeferredBlockTriggers)[]; this.definedPrefetchTriggers = Object.keys(prefetchTriggers) as (keyof DeferredBlockTriggers)[]; this.definedHydrateTriggers = Object.keys(hydrateTriggers) as (keyof DeferredBlockTriggers)[]; } visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitDeferredBlock(this); } visitAll(visitor: Visitor<unknown>): void { // Visit the hydrate triggers first to match their insertion order. this.visitTriggers(this.definedHydrateTriggers, this.hydrateTriggers, visitor); this.visitTriggers(this.definedTriggers, this.triggers, visitor); this.visitTriggers(this.definedPrefetchTriggers, this.prefetchTriggers, visitor); visitAll(visitor, this.children); const remainingBlocks = [this.placeholder, this.loading, this.error].filter( (x) => x !== null, ) as Array<Node>; visitAll(visitor, remainingBlocks); } private visitTriggers( keys: (keyof DeferredBlockTriggers)[], triggers: DeferredBlockTriggers, visitor: Visitor, ) { visitAll( visitor, keys.map((k) => triggers[k]!), ); } } export class SwitchBlock extends BlockNode implements Node { constructor( public expression: AST, public cases: SwitchBlockCase[], /** * These blocks are only captured to allow for autocompletion in the language service. They * aren't meant to be processed in any other way. */ public unknownBlocks: UnknownBlock[], sourceSpan: ParseSourceSpan, startSourceSpan: ParseSourceSpan, endSourceSpan: ParseSourceSpan | null, nameSpan: ParseSourceSpan, ) { super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan); } visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitSwitchBlock(this); } } export class SwitchBlockCase extends BlockNode implements Node { constructor( public expression: AST | null, public children: Node[], sourceSpan: ParseSourceSpan, startSourceSpan: ParseSourceSpan, endSourceSpan: ParseSourceSpan | null, nameSpan: ParseSourceSpan, public i18n?: I18nMeta, ) { super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan); } visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitSwitchBlockCase(this); } } export class ForLoopBlock extends BlockNode implements Node { constructor( public item: Variable, public expression: ASTWithSource, public trackBy: ASTWithSource, public trackKeywordSpan: ParseSourceSpan, public contextVariables: Variable[], public children: Node[], public empty: ForLoopBlockEmpty | null, sourceSpan: ParseSourceSpan, public mainBlockSpan: ParseSourceSpan, startSourceSpan: ParseSourceSpan, endSourceSpan: ParseSourceSpan | null, nameSpan: ParseSourceSpan, public i18n?: I18nMeta, ) { super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan); } visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitForLoopBlock(this); } } export class ForLoopBlockEmpty extends BlockNode implements Node { constructor( public children: Node[], sourceSpan: ParseSourceSpan, startSourceSpan: ParseSourceSpan, endSourceSpan: ParseSourceSpan | null, nameSpan: ParseSourceSpan, public i18n?: I18nMeta, ) { super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan); } visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitForLoopBlockEmpty(this); } } export class IfBlock extends BlockNode implements Node { constructor( public branches: IfBlockBranch[], sourceSpan: ParseSourceSpan, startSourceSpan: ParseSourceSpan, endSourceSpan: ParseSourceSpan | null, nameSpan: ParseSourceSpan, ) { super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan); } visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitIfBlock(this); } } export class IfBlockBranch extends BlockNode implements Node { constructor( public expression: AST | null, public children: Node[], public expressionAlias: Variable | null, sourceSpan: ParseSourceSpan, startSourceSpan: ParseSourceSpan, endSourceSpan: ParseSourceSpan | null, nameSpan: ParseSourceSpan, public i18n?: I18nMeta, ) { super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan); } visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitIfBlockBranch(this); } } export class UnknownBlock implements Node { constructor( public name: string, public sourceSpan: ParseSourceSpan, public nameSpan: ParseSourceSpan, ) {} visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitUnknownBlock(this); } } export class LetDeclaration implements Node { constructor( public name: string, public value: AST, public sourceSpan: ParseSourceSpan, public nameSpan: ParseSourceSpan, public valueSpan: ParseSourceSpan, ) {} visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitLetDeclaration(this); } }
{ "end_byte": 16073, "start_byte": 8273, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_ast.ts" }
angular/packages/compiler/src/render3/r3_ast.ts_16075_22574
export class Template implements Node { constructor( // tagName is the name of the container element, if applicable. // `null` is a special case for when there is a structural directive on an `ng-template` so // the renderer can differentiate between the synthetic template and the one written in the // file. public tagName: string | null, public attributes: TextAttribute[], public inputs: BoundAttribute[], public outputs: BoundEvent[], public templateAttrs: (BoundAttribute | TextAttribute)[], public children: Node[], public references: Reference[], public variables: Variable[], public sourceSpan: ParseSourceSpan, public startSourceSpan: ParseSourceSpan, public endSourceSpan: ParseSourceSpan | null, public i18n?: I18nMeta, ) {} visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitTemplate(this); } } export class Content implements Node { readonly name = 'ng-content'; constructor( public selector: string, public attributes: TextAttribute[], public children: Node[], public sourceSpan: ParseSourceSpan, public i18n?: I18nMeta, ) {} visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitContent(this); } } export class Variable implements Node { constructor( public name: string, public value: string, public sourceSpan: ParseSourceSpan, readonly keySpan: ParseSourceSpan, public valueSpan?: ParseSourceSpan, ) {} visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitVariable(this); } } export class Reference implements Node { constructor( public name: string, public value: string, public sourceSpan: ParseSourceSpan, readonly keySpan: ParseSourceSpan, public valueSpan?: ParseSourceSpan, ) {} visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitReference(this); } } export class Icu implements Node { constructor( public vars: {[name: string]: BoundText}, public placeholders: {[name: string]: Text | BoundText}, public sourceSpan: ParseSourceSpan, public i18n?: I18nMeta, ) {} visit<Result>(visitor: Visitor<Result>): Result { return visitor.visitIcu(this); } } export interface Visitor<Result = any> { // Returning a truthy value from `visit()` will prevent `visitAll()` from the call to the typed // method and result returned will become the result included in `visitAll()`s result array. visit?(node: Node): Result; visitElement(element: Element): Result; visitTemplate(template: Template): Result; visitContent(content: Content): Result; visitVariable(variable: Variable): Result; visitReference(reference: Reference): Result; visitTextAttribute(attribute: TextAttribute): Result; visitBoundAttribute(attribute: BoundAttribute): Result; visitBoundEvent(attribute: BoundEvent): Result; visitText(text: Text): Result; visitBoundText(text: BoundText): Result; visitIcu(icu: Icu): Result; visitDeferredBlock(deferred: DeferredBlock): Result; visitDeferredBlockPlaceholder(block: DeferredBlockPlaceholder): Result; visitDeferredBlockError(block: DeferredBlockError): Result; visitDeferredBlockLoading(block: DeferredBlockLoading): Result; visitDeferredTrigger(trigger: DeferredTrigger): Result; visitSwitchBlock(block: SwitchBlock): Result; visitSwitchBlockCase(block: SwitchBlockCase): Result; visitForLoopBlock(block: ForLoopBlock): Result; visitForLoopBlockEmpty(block: ForLoopBlockEmpty): Result; visitIfBlock(block: IfBlock): Result; visitIfBlockBranch(block: IfBlockBranch): Result; visitUnknownBlock(block: UnknownBlock): Result; visitLetDeclaration(decl: LetDeclaration): Result; } export class RecursiveVisitor implements Visitor<void> { visitElement(element: Element): void { visitAll(this, element.attributes); visitAll(this, element.inputs); visitAll(this, element.outputs); visitAll(this, element.children); visitAll(this, element.references); } visitTemplate(template: Template): void { visitAll(this, template.attributes); visitAll(this, template.inputs); visitAll(this, template.outputs); visitAll(this, template.children); visitAll(this, template.references); visitAll(this, template.variables); } visitDeferredBlock(deferred: DeferredBlock): void { deferred.visitAll(this); } visitDeferredBlockPlaceholder(block: DeferredBlockPlaceholder): void { visitAll(this, block.children); } visitDeferredBlockError(block: DeferredBlockError): void { visitAll(this, block.children); } visitDeferredBlockLoading(block: DeferredBlockLoading): void { visitAll(this, block.children); } visitSwitchBlock(block: SwitchBlock): void { visitAll(this, block.cases); } visitSwitchBlockCase(block: SwitchBlockCase): void { visitAll(this, block.children); } visitForLoopBlock(block: ForLoopBlock): void { const blockItems = [block.item, ...block.contextVariables, ...block.children]; block.empty && blockItems.push(block.empty); visitAll(this, blockItems); } visitForLoopBlockEmpty(block: ForLoopBlockEmpty): void { visitAll(this, block.children); } visitIfBlock(block: IfBlock): void { visitAll(this, block.branches); } visitIfBlockBranch(block: IfBlockBranch): void { const blockItems = block.children; block.expressionAlias && blockItems.push(block.expressionAlias); visitAll(this, blockItems); } visitContent(content: Content): void { visitAll(this, content.children); } visitVariable(variable: Variable): void {} visitReference(reference: Reference): void {} visitTextAttribute(attribute: TextAttribute): void {} visitBoundAttribute(attribute: BoundAttribute): void {} visitBoundEvent(attribute: BoundEvent): void {} visitText(text: Text): void {} visitBoundText(text: BoundText): void {} visitIcu(icu: Icu): void {} visitDeferredTrigger(trigger: DeferredTrigger): void {} visitUnknownBlock(block: UnknownBlock): void {} visitLetDeclaration(decl: LetDeclaration): void {} } export function visitAll<Result>(visitor: Visitor<Result>, nodes: Node[]): Result[] { const result: Result[] = []; if (visitor.visit) { for (const node of nodes) { visitor.visit(node) || node.visit(visitor); } } else { for (const node of nodes) { const newNode = node.visit(visitor); if (newNode) { result.push(newNode); } } } return result; }
{ "end_byte": 22574, "start_byte": 16075, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_ast.ts" }
angular/packages/compiler/src/render3/r3_factory.ts_0_7576
/** * @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 {InjectFlags} from '../core'; import * as o from '../output/output_ast'; import {Identifiers as R3} from '../render3/r3_identifiers'; import {R3CompiledExpression, R3Reference, typeWithParameters} from './util'; /** * Metadata required by the factory generator to generate a `factory` function for a type. */ export interface R3ConstructorFactoryMetadata { /** * String name of the type being generated (used to name the factory function). */ name: string; /** * An expression representing the interface type being constructed. */ type: R3Reference; /** Number of arguments for the `type`. */ typeArgumentCount: number; /** * Regardless of whether `fnOrClass` is a constructor function or a user-defined factory, it * may have 0 or more parameters, which will be injected according to the `R3DependencyMetadata` * for those parameters. If this is `null`, then the type's constructor is nonexistent and will * be inherited from `fnOrClass` which is interpreted as the current 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: R3DependencyMetadata[] | 'invalid' | null; /** * Type of the target being created by the factory. */ target: FactoryTarget; } export enum R3FactoryDelegateType { Class = 0, Function = 1, } export interface R3DelegatedFnOrClassMetadata extends R3ConstructorFactoryMetadata { delegate: o.Expression; delegateType: R3FactoryDelegateType; delegateDeps: R3DependencyMetadata[]; } export interface R3ExpressionFactoryMetadata extends R3ConstructorFactoryMetadata { expression: o.Expression; } export type R3FactoryMetadata = | R3ConstructorFactoryMetadata | R3DelegatedFnOrClassMetadata | R3ExpressionFactoryMetadata; export enum FactoryTarget { Directive = 0, Component = 1, Injectable = 2, Pipe = 3, NgModule = 4, } export interface R3DependencyMetadata { /** * An expression representing the token or value to be injected. * Or `null` if the dependency could not be resolved - making it invalid. */ token: o.Expression | null; /** * If an @Attribute decorator is present, this is the literal type of the attribute name, or * the unknown type if no literal type is available (e.g. the attribute name is an expression). * Otherwise it is null; */ attributeNameType: o.Expression | null; /** * Whether the dependency has an @Host qualifier. */ host: boolean; /** * Whether the dependency has an @Optional qualifier. */ optional: boolean; /** * Whether the dependency has an @Self qualifier. */ self: boolean; /** * Whether the dependency has an @SkipSelf qualifier. */ skipSelf: boolean; } /** * Construct a factory function expression for the given `R3FactoryMetadata`. */ export function compileFactoryFunction(meta: R3FactoryMetadata): R3CompiledExpression { const t = o.variable('__ngFactoryType__'); let baseFactoryVar: o.ReadVarExpr | null = null; // The type to instantiate via constructor invocation. If there is no delegated factory, meaning // this type is always created by constructor invocation, then this is the type-to-create // parameter provided by the user (t) if specified, or the current type if not. If there is a // delegated factory (which is used to create the current type) then this is only the type-to- // create parameter (t). const typeForCtor = !isDelegatedFactoryMetadata(meta) ? new o.BinaryOperatorExpr(o.BinaryOperator.Or, t, meta.type.value) : t; let ctorExpr: o.Expression | null = null; if (meta.deps !== null) { // There is a constructor (either explicitly or implicitly defined). if (meta.deps !== 'invalid') { ctorExpr = new o.InstantiateExpr(typeForCtor, injectDependencies(meta.deps, meta.target)); } } else { // There is no constructor, use the base class' factory to construct typeForCtor. baseFactoryVar = o.variable(`ɵ${meta.name}_BaseFactory`); ctorExpr = baseFactoryVar.callFn([typeForCtor]); } const body: o.Statement[] = []; let retExpr: o.Expression | null = null; function makeConditionalFactory(nonCtorExpr: o.Expression): o.ReadVarExpr { const r = o.variable('__ngConditionalFactory__'); body.push(r.set(o.NULL_EXPR).toDeclStmt()); const ctorStmt = ctorExpr !== null ? r.set(ctorExpr).toStmt() : o.importExpr(R3.invalidFactory).callFn([]).toStmt(); body.push(o.ifStmt(t, [ctorStmt], [r.set(nonCtorExpr).toStmt()])); return r; } if (isDelegatedFactoryMetadata(meta)) { // This type is created with a delegated factory. If a type parameter is not specified, call // the factory instead. const delegateArgs = injectDependencies(meta.delegateDeps, meta.target); // Either call `new delegate(...)` or `delegate(...)` depending on meta.delegateType. const factoryExpr = new ( meta.delegateType === R3FactoryDelegateType.Class ? o.InstantiateExpr : o.InvokeFunctionExpr )(meta.delegate, delegateArgs); retExpr = makeConditionalFactory(factoryExpr); } else if (isExpressionFactoryMetadata(meta)) { // TODO(alxhub): decide whether to lower the value here or in the caller retExpr = makeConditionalFactory(meta.expression); } else { retExpr = ctorExpr; } if (retExpr === null) { // The expression cannot be formed so render an `ɵɵinvalidFactory()` call. body.push(o.importExpr(R3.invalidFactory).callFn([]).toStmt()); } else if (baseFactoryVar !== null) { // This factory uses a base factory, so call `ɵɵgetInheritedFactory()` to compute it. const getInheritedFactoryCall = o.importExpr(R3.getInheritedFactory).callFn([meta.type.value]); // Memoize the base factoryFn: `baseFactory || (baseFactory = ɵɵgetInheritedFactory(...))` const baseFactory = new o.BinaryOperatorExpr( o.BinaryOperator.Or, baseFactoryVar, baseFactoryVar.set(getInheritedFactoryCall), ); body.push(new o.ReturnStatement(baseFactory.callFn([typeForCtor]))); } else { // This is straightforward factory, just return it. body.push(new o.ReturnStatement(retExpr)); } let factoryFn: o.Expression = o.fn( [new o.FnParam(t.name, o.DYNAMIC_TYPE)], body, o.INFERRED_TYPE, undefined, `${meta.name}_Factory`, ); if (baseFactoryVar !== null) { // There is a base factory variable so wrap its declaration along with the factory function into // an IIFE. factoryFn = o .arrowFn([], [new o.DeclareVarStmt(baseFactoryVar.name!), new o.ReturnStatement(factoryFn)]) .callFn([], /* sourceSpan */ undefined, /* pure */ true); } return { expression: factoryFn, statements: [], type: createFactoryType(meta), }; } export function createFactoryType(meta: R3FactoryMetadata) { const ctorDepsType = meta.deps !== null && meta.deps !== 'invalid' ? createCtorDepsType(meta.deps) : o.NONE_TYPE; return o.expressionType( o.importExpr(R3.FactoryDeclaration, [ typeWithParameters(meta.type.type, meta.typeArgumentCount), ctorDepsType, ]), ); } function injectDependencies(deps: R3DependencyMetadata[], target: FactoryTarget): o.Expression[] { return deps.map((dep, index) => compileInjectDependency(dep, target, index)); } funct
{ "end_byte": 7576, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_factory.ts" }
angular/packages/compiler/src/render3/r3_factory.ts_7578_11233
n compileInjectDependency( dep: R3DependencyMetadata, target: FactoryTarget, index: number, ): o.Expression { // Interpret the dependency according to its resolved type. if (dep.token === null) { return o.importExpr(R3.invalidFactoryDep).callFn([o.literal(index)]); } else if (dep.attributeNameType === null) { // Build up the injection flags according to the metadata. const flags = InjectFlags.Default | (dep.self ? InjectFlags.Self : 0) | (dep.skipSelf ? InjectFlags.SkipSelf : 0) | (dep.host ? InjectFlags.Host : 0) | (dep.optional ? InjectFlags.Optional : 0) | (target === FactoryTarget.Pipe ? InjectFlags.ForPipe : 0); // If this dependency is optional or otherwise has non-default flags, then additional // parameters describing how to inject the dependency must be passed to the inject function // that's being used. let flagsParam: o.LiteralExpr | null = flags !== InjectFlags.Default || dep.optional ? o.literal(flags) : null; // Build up the arguments to the injectFn call. const injectArgs = [dep.token]; if (flagsParam) { injectArgs.push(flagsParam); } const injectFn = getInjectFn(target); return o.importExpr(injectFn).callFn(injectArgs); } else { // The `dep.attributeTypeName` value is defined, which indicates that this is an `@Attribute()` // type dependency. For the generated JS we still want to use the `dep.token` value in case the // name given for the attribute is not a string literal. For example given `@Attribute(foo())`, // we want to generate `ɵɵinjectAttribute(foo())`. // // The `dep.attributeTypeName` is only actually used (in `createCtorDepType()`) to generate // typings. return o.importExpr(R3.injectAttribute).callFn([dep.token]); } } function createCtorDepsType(deps: R3DependencyMetadata[]): o.Type { let hasTypes = false; const attributeTypes = deps.map((dep) => { const type = createCtorDepType(dep); if (type !== null) { hasTypes = true; return type; } else { return o.literal(null); } }); if (hasTypes) { return o.expressionType(o.literalArr(attributeTypes)); } else { return o.NONE_TYPE; } } function createCtorDepType(dep: R3DependencyMetadata): o.LiteralMapExpr | null { const entries: {key: string; quoted: boolean; value: o.Expression}[] = []; if (dep.attributeNameType !== null) { entries.push({key: 'attribute', value: dep.attributeNameType, quoted: false}); } if (dep.optional) { entries.push({key: 'optional', value: o.literal(true), quoted: false}); } if (dep.host) { entries.push({key: 'host', value: o.literal(true), quoted: false}); } if (dep.self) { entries.push({key: 'self', value: o.literal(true), quoted: false}); } if (dep.skipSelf) { entries.push({key: 'skipSelf', value: o.literal(true), quoted: false}); } return entries.length > 0 ? o.literalMap(entries) : null; } export function isDelegatedFactoryMetadata( meta: R3FactoryMetadata, ): meta is R3DelegatedFnOrClassMetadata { return (meta as any).delegateType !== undefined; } export function isExpressionFactoryMetadata( meta: R3FactoryMetadata, ): meta is R3ExpressionFactoryMetadata { return (meta as any).expression !== undefined; } function getInjectFn(target: FactoryTarget): o.ExternalReference { switch (target) { case FactoryTarget.Component: case FactoryTarget.Directive: case FactoryTarget.Pipe: return R3.directiveInject; case FactoryTarget.NgModule: case FactoryTarget.Injectable: default: return R3.inject; } }
{ "end_byte": 11233, "start_byte": 7578, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_factory.ts" }
angular/packages/compiler/src/render3/r3_pipe_compiler.ts_0_2260
/** * @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 {Identifiers as R3} from './r3_identifiers'; import {R3CompiledExpression, R3Reference, typeWithParameters} from './util'; export interface R3PipeMetadata { /** * Name of the pipe type. */ name: string; /** * An expression representing a reference to the pipe itself. */ type: R3Reference; /** * Number of generic type parameters of the type itself. */ typeArgumentCount: number; /** * Name of the pipe. */ pipeName: string; /** * Dependencies of the pipe's constructor. */ deps: R3DependencyMetadata[] | null; /** * Whether the pipe is marked as pure. */ pure: boolean; /** * Whether the pipe is standalone. */ isStandalone: boolean; } export function compilePipeFromMetadata(metadata: R3PipeMetadata): R3CompiledExpression { const definitionMapValues: {key: string; quoted: boolean; value: o.Expression}[] = []; // e.g. `name: 'myPipe'` definitionMapValues.push({key: 'name', value: o.literal(metadata.pipeName), quoted: false}); // e.g. `type: MyPipe` definitionMapValues.push({key: 'type', value: metadata.type.value, quoted: false}); // e.g. `pure: true` definitionMapValues.push({key: 'pure', value: o.literal(metadata.pure), quoted: false}); if (metadata.isStandalone === false) { definitionMapValues.push({key: 'standalone', value: o.literal(false), quoted: false}); } const expression = o .importExpr(R3.definePipe) .callFn([o.literalMap(definitionMapValues)], undefined, true); const type = createPipeType(metadata); return {expression, type, statements: []}; } export function createPipeType(metadata: R3PipeMetadata): o.Type { return new o.ExpressionType( o.importExpr(R3.PipeDeclaration, [ typeWithParameters(metadata.type.type, metadata.typeArgumentCount), new o.ExpressionType(new o.LiteralExpr(metadata.pipeName)), new o.ExpressionType(new o.LiteralExpr(metadata.isStandalone)), ]), ); }
{ "end_byte": 2260, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_pipe_compiler.ts" }
angular/packages/compiler/src/render3/r3_identifiers.ts_0_277
/** * @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'; const CORE = '@angular/core';
{ "end_byte": 277, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_identifiers.ts" }
angular/packages/compiler/src/render3/r3_identifiers.ts_279_7625
export class Identifiers { /* Methods */ static NEW_METHOD = 'factory'; static TRANSFORM_METHOD = 'transform'; static PATCH_DEPS = 'patchedDeps'; static core: o.ExternalReference = {name: null, moduleName: CORE}; /* Instructions */ static namespaceHTML: o.ExternalReference = {name: 'ɵɵnamespaceHTML', moduleName: CORE}; static namespaceMathML: o.ExternalReference = {name: 'ɵɵnamespaceMathML', moduleName: CORE}; static namespaceSVG: o.ExternalReference = {name: 'ɵɵnamespaceSVG', moduleName: CORE}; static element: o.ExternalReference = {name: 'ɵɵelement', moduleName: CORE}; static elementStart: o.ExternalReference = {name: 'ɵɵelementStart', moduleName: CORE}; static elementEnd: o.ExternalReference = {name: 'ɵɵelementEnd', moduleName: CORE}; static advance: o.ExternalReference = {name: 'ɵɵadvance', moduleName: CORE}; static syntheticHostProperty: o.ExternalReference = { name: 'ɵɵsyntheticHostProperty', moduleName: CORE, }; static syntheticHostListener: o.ExternalReference = { name: 'ɵɵsyntheticHostListener', moduleName: CORE, }; static attribute: o.ExternalReference = {name: 'ɵɵattribute', moduleName: CORE}; static attributeInterpolate1: o.ExternalReference = { name: 'ɵɵattributeInterpolate1', moduleName: CORE, }; static attributeInterpolate2: o.ExternalReference = { name: 'ɵɵattributeInterpolate2', moduleName: CORE, }; static attributeInterpolate3: o.ExternalReference = { name: 'ɵɵattributeInterpolate3', moduleName: CORE, }; static attributeInterpolate4: o.ExternalReference = { name: 'ɵɵattributeInterpolate4', moduleName: CORE, }; static attributeInterpolate5: o.ExternalReference = { name: 'ɵɵattributeInterpolate5', moduleName: CORE, }; static attributeInterpolate6: o.ExternalReference = { name: 'ɵɵattributeInterpolate6', moduleName: CORE, }; static attributeInterpolate7: o.ExternalReference = { name: 'ɵɵattributeInterpolate7', moduleName: CORE, }; static attributeInterpolate8: o.ExternalReference = { name: 'ɵɵattributeInterpolate8', moduleName: CORE, }; static attributeInterpolateV: o.ExternalReference = { name: 'ɵɵattributeInterpolateV', moduleName: CORE, }; static classProp: o.ExternalReference = {name: 'ɵɵclassProp', moduleName: CORE}; static elementContainerStart: o.ExternalReference = { name: 'ɵɵelementContainerStart', moduleName: CORE, }; static elementContainerEnd: o.ExternalReference = { name: 'ɵɵelementContainerEnd', moduleName: CORE, }; static elementContainer: o.ExternalReference = {name: 'ɵɵelementContainer', moduleName: CORE}; static styleMap: o.ExternalReference = {name: 'ɵɵstyleMap', moduleName: CORE}; static styleMapInterpolate1: o.ExternalReference = { name: 'ɵɵstyleMapInterpolate1', moduleName: CORE, }; static styleMapInterpolate2: o.ExternalReference = { name: 'ɵɵstyleMapInterpolate2', moduleName: CORE, }; static styleMapInterpolate3: o.ExternalReference = { name: 'ɵɵstyleMapInterpolate3', moduleName: CORE, }; static styleMapInterpolate4: o.ExternalReference = { name: 'ɵɵstyleMapInterpolate4', moduleName: CORE, }; static styleMapInterpolate5: o.ExternalReference = { name: 'ɵɵstyleMapInterpolate5', moduleName: CORE, }; static styleMapInterpolate6: o.ExternalReference = { name: 'ɵɵstyleMapInterpolate6', moduleName: CORE, }; static styleMapInterpolate7: o.ExternalReference = { name: 'ɵɵstyleMapInterpolate7', moduleName: CORE, }; static styleMapInterpolate8: o.ExternalReference = { name: 'ɵɵstyleMapInterpolate8', moduleName: CORE, }; static styleMapInterpolateV: o.ExternalReference = { name: 'ɵɵstyleMapInterpolateV', moduleName: CORE, }; static classMap: o.ExternalReference = {name: 'ɵɵclassMap', moduleName: CORE}; static classMapInterpolate1: o.ExternalReference = { name: 'ɵɵclassMapInterpolate1', moduleName: CORE, }; static classMapInterpolate2: o.ExternalReference = { name: 'ɵɵclassMapInterpolate2', moduleName: CORE, }; static classMapInterpolate3: o.ExternalReference = { name: 'ɵɵclassMapInterpolate3', moduleName: CORE, }; static classMapInterpolate4: o.ExternalReference = { name: 'ɵɵclassMapInterpolate4', moduleName: CORE, }; static classMapInterpolate5: o.ExternalReference = { name: 'ɵɵclassMapInterpolate5', moduleName: CORE, }; static classMapInterpolate6: o.ExternalReference = { name: 'ɵɵclassMapInterpolate6', moduleName: CORE, }; static classMapInterpolate7: o.ExternalReference = { name: 'ɵɵclassMapInterpolate7', moduleName: CORE, }; static classMapInterpolate8: o.ExternalReference = { name: 'ɵɵclassMapInterpolate8', moduleName: CORE, }; static classMapInterpolateV: o.ExternalReference = { name: 'ɵɵclassMapInterpolateV', moduleName: CORE, }; static styleProp: o.ExternalReference = {name: 'ɵɵstyleProp', moduleName: CORE}; static stylePropInterpolate1: o.ExternalReference = { name: 'ɵɵstylePropInterpolate1', moduleName: CORE, }; static stylePropInterpolate2: o.ExternalReference = { name: 'ɵɵstylePropInterpolate2', moduleName: CORE, }; static stylePropInterpolate3: o.ExternalReference = { name: 'ɵɵstylePropInterpolate3', moduleName: CORE, }; static stylePropInterpolate4: o.ExternalReference = { name: 'ɵɵstylePropInterpolate4', moduleName: CORE, }; static stylePropInterpolate5: o.ExternalReference = { name: 'ɵɵstylePropInterpolate5', moduleName: CORE, }; static stylePropInterpolate6: o.ExternalReference = { name: 'ɵɵstylePropInterpolate6', moduleName: CORE, }; static stylePropInterpolate7: o.ExternalReference = { name: 'ɵɵstylePropInterpolate7', moduleName: CORE, }; static stylePropInterpolate8: o.ExternalReference = { name: 'ɵɵstylePropInterpolate8', moduleName: CORE, }; static stylePropInterpolateV: o.ExternalReference = { name: 'ɵɵstylePropInterpolateV', moduleName: CORE, }; static nextContext: o.ExternalReference = {name: 'ɵɵnextContext', moduleName: CORE}; static resetView: o.ExternalReference = {name: 'ɵɵresetView', moduleName: CORE}; static templateCreate: o.ExternalReference = {name: 'ɵɵtemplate', moduleName: CORE}; static defer: o.ExternalReference = {name: 'ɵɵdefer', moduleName: CORE}; static deferWhen: o.ExternalReference = {name: 'ɵɵdeferWhen', moduleName: CORE}; static deferOnIdle: o.ExternalReference = {name: 'ɵɵdeferOnIdle', moduleName: CORE}; static deferOnImmediate: o.ExternalReference = {name: 'ɵɵdeferOnImmediate', moduleName: CORE}; static deferOnTimer: o.ExternalReference = {name: 'ɵɵdeferOnTimer', moduleName: CORE}; static deferOnHover: o.ExternalReference = {name: 'ɵɵdeferOnHover', moduleName: CORE}; static deferOnInteraction: o.ExternalReference = {name: 'ɵɵdeferOnInteraction', moduleName: CORE}; static deferOnViewport: o.ExternalReference = {name: 'ɵɵdeferOnViewport', moduleName: CORE}; static deferPrefetchWhen: o.ExternalReference = {name: 'ɵɵdeferPrefetchWhen', moduleName: CORE}; static deferPrefetchOnIdle: o.ExternalReference = { name: 'ɵɵdeferPrefetchOnIdle', moduleName: CORE, }; static defe
{ "end_byte": 7625, "start_byte": 279, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_identifiers.ts" }
angular/packages/compiler/src/render3/r3_identifiers.ts_7628_14728
efetchOnImmediate: o.ExternalReference = { name: 'ɵɵdeferPrefetchOnImmediate', moduleName: CORE, }; static deferPrefetchOnTimer: o.ExternalReference = { name: 'ɵɵdeferPrefetchOnTimer', moduleName: CORE, }; static deferPrefetchOnHover: o.ExternalReference = { name: 'ɵɵdeferPrefetchOnHover', moduleName: CORE, }; static deferPrefetchOnInteraction: o.ExternalReference = { name: 'ɵɵdeferPrefetchOnInteraction', moduleName: CORE, }; static deferPrefetchOnViewport: o.ExternalReference = { name: 'ɵɵdeferPrefetchOnViewport', moduleName: CORE, }; static deferHydrateWhen: o.ExternalReference = {name: 'ɵɵdeferHydrateWhen', moduleName: CORE}; static deferHydrateNever: o.ExternalReference = {name: 'ɵɵdeferHydrateNever', moduleName: CORE}; static deferHydrateOnIdle: o.ExternalReference = { name: 'ɵɵdeferHydrateOnIdle', moduleName: CORE, }; static deferHydrateOnImmediate: o.ExternalReference = { name: 'ɵɵdeferHydrateOnImmediate', moduleName: CORE, }; static deferHydrateOnTimer: o.ExternalReference = { name: 'ɵɵdeferHydrateOnTimer', moduleName: CORE, }; static deferHydrateOnHover: o.ExternalReference = { name: 'ɵɵdeferHydrateOnHover', moduleName: CORE, }; static deferHydrateOnInteraction: o.ExternalReference = { name: 'ɵɵdeferHydrateOnInteraction', moduleName: CORE, }; static deferHydrateOnViewport: o.ExternalReference = { name: 'ɵɵdeferHydrateOnViewport', moduleName: CORE, }; static deferEnableTimerScheduling: o.ExternalReference = { name: 'ɵɵdeferEnableTimerScheduling', moduleName: CORE, }; static conditional: o.ExternalReference = {name: 'ɵɵconditional', moduleName: CORE}; static repeater: o.ExternalReference = {name: 'ɵɵrepeater', moduleName: CORE}; static repeaterCreate: o.ExternalReference = {name: 'ɵɵrepeaterCreate', moduleName: CORE}; static repeaterTrackByIndex: o.ExternalReference = { name: 'ɵɵrepeaterTrackByIndex', moduleName: CORE, }; static repeaterTrackByIdentity: o.ExternalReference = { name: 'ɵɵrepeaterTrackByIdentity', moduleName: CORE, }; static componentInstance: o.ExternalReference = {name: 'ɵɵcomponentInstance', moduleName: CORE}; static text: o.ExternalReference = {name: 'ɵɵtext', moduleName: CORE}; static enableBindings: o.ExternalReference = {name: 'ɵɵenableBindings', moduleName: CORE}; static disableBindings: o.ExternalReference = {name: 'ɵɵdisableBindings', moduleName: CORE}; static getCurrentView: o.ExternalReference = {name: 'ɵɵgetCurrentView', moduleName: CORE}; static textInterpolate: o.ExternalReference = {name: 'ɵɵtextInterpolate', moduleName: CORE}; static textInterpolate1: o.ExternalReference = {name: 'ɵɵtextInterpolate1', moduleName: CORE}; static textInterpolate2: o.ExternalReference = {name: 'ɵɵtextInterpolate2', moduleName: CORE}; static textInterpolate3: o.ExternalReference = {name: 'ɵɵtextInterpolate3', moduleName: CORE}; static textInterpolate4: o.ExternalReference = {name: 'ɵɵtextInterpolate4', moduleName: CORE}; static textInterpolate5: o.ExternalReference = {name: 'ɵɵtextInterpolate5', moduleName: CORE}; static textInterpolate6: o.ExternalReference = {name: 'ɵɵtextInterpolate6', moduleName: CORE}; static textInterpolate7: o.ExternalReference = {name: 'ɵɵtextInterpolate7', moduleName: CORE}; static textInterpolate8: o.ExternalReference = {name: 'ɵɵtextInterpolate8', moduleName: CORE}; static textInterpolateV: o.ExternalReference = {name: 'ɵɵtextInterpolateV', moduleName: CORE}; static restoreView: o.ExternalReference = {name: 'ɵɵrestoreView', moduleName: CORE}; static pureFunction0: o.ExternalReference = {name: 'ɵɵpureFunction0', moduleName: CORE}; static pureFunction1: o.ExternalReference = {name: 'ɵɵpureFunction1', moduleName: CORE}; static pureFunction2: o.ExternalReference = {name: 'ɵɵpureFunction2', moduleName: CORE}; static pureFunction3: o.ExternalReference = {name: 'ɵɵpureFunction3', moduleName: CORE}; static pureFunction4: o.ExternalReference = {name: 'ɵɵpureFunction4', moduleName: CORE}; static pureFunction5: o.ExternalReference = {name: 'ɵɵpureFunction5', moduleName: CORE}; static pureFunction6: o.ExternalReference = {name: 'ɵɵpureFunction6', moduleName: CORE}; static pureFunction7: o.ExternalReference = {name: 'ɵɵpureFunction7', moduleName: CORE}; static pureFunction8: o.ExternalReference = {name: 'ɵɵpureFunction8', moduleName: CORE}; static pureFunctionV: o.ExternalReference = {name: 'ɵɵpureFunctionV', moduleName: CORE}; static pipeBind1: o.ExternalReference = {name: 'ɵɵpipeBind1', moduleName: CORE}; static pipeBind2: o.ExternalReference = {name: 'ɵɵpipeBind2', moduleName: CORE}; static pipeBind3: o.ExternalReference = {name: 'ɵɵpipeBind3', moduleName: CORE}; static pipeBind4: o.ExternalReference = {name: 'ɵɵpipeBind4', moduleName: CORE}; static pipeBindV: o.ExternalReference = {name: 'ɵɵpipeBindV', moduleName: CORE}; static hostProperty: o.ExternalReference = {name: 'ɵɵhostProperty', moduleName: CORE}; static property: o.ExternalReference = {name: 'ɵɵproperty', moduleName: CORE}; static propertyInterpolate: o.ExternalReference = { name: 'ɵɵpropertyInterpolate', moduleName: CORE, }; static propertyInterpolate1: o.ExternalReference = { name: 'ɵɵpropertyInterpolate1', moduleName: CORE, }; static propertyInterpolate2: o.ExternalReference = { name: 'ɵɵpropertyInterpolate2', moduleName: CORE, }; static propertyInterpolate3: o.ExternalReference = { name: 'ɵɵpropertyInterpolate3', moduleName: CORE, }; static propertyInterpolate4: o.ExternalReference = { name: 'ɵɵpropertyInterpolate4', moduleName: CORE, }; static propertyInterpolate5: o.ExternalReference = { name: 'ɵɵpropertyInterpolate5', moduleName: CORE, }; static propertyInterpolate6: o.ExternalReference = { name: 'ɵɵpropertyInterpolate6', moduleName: CORE, }; static propertyInterpolate7: o.ExternalReference = { name: 'ɵɵpropertyInterpolate7', moduleName: CORE, }; static propertyInterpolate8: o.ExternalReference = { name: 'ɵɵpropertyInterpolate8', moduleName: CORE, }; static propertyInterpolateV: o.ExternalReference = { name: 'ɵɵpropertyInterpolateV', moduleName: CORE, }; static i18n: o.ExternalReference = {name: 'ɵɵi18n', moduleName: CORE}; static i18nAttributes: o.ExternalReference = {name: 'ɵɵi18nAttributes', moduleName: CORE}; static i18nExp: o.ExternalReference = {name: 'ɵɵi18nExp', moduleName: CORE}; static i18nStart: o.ExternalReference = {name: 'ɵɵi18nStart', moduleName: CORE}; static i18nEnd: o.ExternalReference = {name: 'ɵɵi18nEnd', moduleName: CORE}; static i18nApply: o.ExternalReference = {name: 'ɵɵi18nApply', moduleName: CORE}; static i18nPostprocess: o.ExternalReference = {name: 'ɵɵi18nPostprocess', moduleName: CORE}; static pipe: o.ExternalReference = {name: 'ɵɵpipe', moduleName: CORE}; static projection: o.ExternalReference = {name: 'ɵɵprojection', moduleName: CORE}; static pro
{ "end_byte": 14728, "start_byte": 7628, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_identifiers.ts" }
angular/packages/compiler/src/render3/r3_identifiers.ts_14731_22575
tionDef: o.ExternalReference = {name: 'ɵɵprojectionDef', moduleName: CORE}; static reference: o.ExternalReference = {name: 'ɵɵreference', moduleName: CORE}; static inject: o.ExternalReference = {name: 'ɵɵinject', moduleName: CORE}; static injectAttribute: o.ExternalReference = {name: 'ɵɵinjectAttribute', moduleName: CORE}; static directiveInject: o.ExternalReference = {name: 'ɵɵdirectiveInject', moduleName: CORE}; static invalidFactory: o.ExternalReference = {name: 'ɵɵinvalidFactory', moduleName: CORE}; static invalidFactoryDep: o.ExternalReference = {name: 'ɵɵinvalidFactoryDep', moduleName: CORE}; static templateRefExtractor: o.ExternalReference = { name: 'ɵɵtemplateRefExtractor', moduleName: CORE, }; static forwardRef: o.ExternalReference = {name: 'forwardRef', moduleName: CORE}; static resolveForwardRef: o.ExternalReference = {name: 'resolveForwardRef', moduleName: CORE}; static replaceMetadata: o.ExternalReference = {name: 'ɵɵreplaceMetadata', moduleName: CORE}; static ɵɵdefineInjectable: o.ExternalReference = {name: 'ɵɵdefineInjectable', moduleName: CORE}; static declareInjectable: o.ExternalReference = {name: 'ɵɵngDeclareInjectable', moduleName: CORE}; static InjectableDeclaration: o.ExternalReference = { name: 'ɵɵInjectableDeclaration', moduleName: CORE, }; static resolveWindow: o.ExternalReference = {name: 'ɵɵresolveWindow', moduleName: CORE}; static resolveDocument: o.ExternalReference = {name: 'ɵɵresolveDocument', moduleName: CORE}; static resolveBody: o.ExternalReference = {name: 'ɵɵresolveBody', moduleName: CORE}; static getComponentDepsFactory: o.ExternalReference = { name: 'ɵɵgetComponentDepsFactory', moduleName: CORE, }; static defineComponent: o.ExternalReference = {name: 'ɵɵdefineComponent', moduleName: CORE}; static declareComponent: o.ExternalReference = {name: 'ɵɵngDeclareComponent', moduleName: CORE}; static setComponentScope: o.ExternalReference = {name: 'ɵɵsetComponentScope', moduleName: CORE}; static ChangeDetectionStrategy: o.ExternalReference = { name: 'ChangeDetectionStrategy', moduleName: CORE, }; static ViewEncapsulation: o.ExternalReference = { name: 'ViewEncapsulation', moduleName: CORE, }; static ComponentDeclaration: o.ExternalReference = { name: 'ɵɵComponentDeclaration', moduleName: CORE, }; static FactoryDeclaration: o.ExternalReference = { name: 'ɵɵFactoryDeclaration', moduleName: CORE, }; static declareFactory: o.ExternalReference = {name: 'ɵɵngDeclareFactory', moduleName: CORE}; static FactoryTarget: o.ExternalReference = {name: 'ɵɵFactoryTarget', moduleName: CORE}; static defineDirective: o.ExternalReference = {name: 'ɵɵdefineDirective', moduleName: CORE}; static declareDirective: o.ExternalReference = {name: 'ɵɵngDeclareDirective', moduleName: CORE}; static DirectiveDeclaration: o.ExternalReference = { name: 'ɵɵDirectiveDeclaration', moduleName: CORE, }; static InjectorDef: o.ExternalReference = {name: 'ɵɵInjectorDef', moduleName: CORE}; static InjectorDeclaration: o.ExternalReference = { name: 'ɵɵInjectorDeclaration', moduleName: CORE, }; static defineInjector: o.ExternalReference = {name: 'ɵɵdefineInjector', moduleName: CORE}; static declareInjector: o.ExternalReference = {name: 'ɵɵngDeclareInjector', moduleName: CORE}; static NgModuleDeclaration: o.ExternalReference = { name: 'ɵɵNgModuleDeclaration', moduleName: CORE, }; static ModuleWithProviders: o.ExternalReference = { name: 'ModuleWithProviders', moduleName: CORE, }; static defineNgModule: o.ExternalReference = {name: 'ɵɵdefineNgModule', moduleName: CORE}; static declareNgModule: o.ExternalReference = {name: 'ɵɵngDeclareNgModule', moduleName: CORE}; static setNgModuleScope: o.ExternalReference = {name: 'ɵɵsetNgModuleScope', moduleName: CORE}; static registerNgModuleType: o.ExternalReference = { name: 'ɵɵregisterNgModuleType', moduleName: CORE, }; static PipeDeclaration: o.ExternalReference = {name: 'ɵɵPipeDeclaration', moduleName: CORE}; static definePipe: o.ExternalReference = {name: 'ɵɵdefinePipe', moduleName: CORE}; static declarePipe: o.ExternalReference = {name: 'ɵɵngDeclarePipe', moduleName: CORE}; static declareClassMetadata: o.ExternalReference = { name: 'ɵɵngDeclareClassMetadata', moduleName: CORE, }; static declareClassMetadataAsync: o.ExternalReference = { name: 'ɵɵngDeclareClassMetadataAsync', moduleName: CORE, }; static setClassMetadata: o.ExternalReference = {name: 'ɵsetClassMetadata', moduleName: CORE}; static setClassMetadataAsync: o.ExternalReference = { name: 'ɵsetClassMetadataAsync', moduleName: CORE, }; static setClassDebugInfo: o.ExternalReference = {name: 'ɵsetClassDebugInfo', moduleName: CORE}; static queryRefresh: o.ExternalReference = {name: 'ɵɵqueryRefresh', moduleName: CORE}; static viewQuery: o.ExternalReference = {name: 'ɵɵviewQuery', moduleName: CORE}; static loadQuery: o.ExternalReference = {name: 'ɵɵloadQuery', moduleName: CORE}; static contentQuery: o.ExternalReference = {name: 'ɵɵcontentQuery', moduleName: CORE}; // Signal queries static viewQuerySignal: o.ExternalReference = {name: 'ɵɵviewQuerySignal', moduleName: CORE}; static contentQuerySignal: o.ExternalReference = {name: 'ɵɵcontentQuerySignal', moduleName: CORE}; static queryAdvance: o.ExternalReference = {name: 'ɵɵqueryAdvance', moduleName: CORE}; // Two-way bindings static twoWayProperty: o.ExternalReference = {name: 'ɵɵtwoWayProperty', moduleName: CORE}; static twoWayBindingSet: o.ExternalReference = {name: 'ɵɵtwoWayBindingSet', moduleName: CORE}; static twoWayListener: o.ExternalReference = {name: 'ɵɵtwoWayListener', moduleName: CORE}; static declareLet: o.ExternalReference = {name: 'ɵɵdeclareLet', moduleName: CORE}; static storeLet: o.ExternalReference = {name: 'ɵɵstoreLet', moduleName: CORE}; static readContextLet: o.ExternalReference = {name: 'ɵɵreadContextLet', moduleName: CORE}; static NgOnChangesFeature: o.ExternalReference = {name: 'ɵɵNgOnChangesFeature', moduleName: CORE}; static InheritDefinitionFeature: o.ExternalReference = { name: 'ɵɵInheritDefinitionFeature', moduleName: CORE, }; static CopyDefinitionFeature: o.ExternalReference = { name: 'ɵɵCopyDefinitionFeature', moduleName: CORE, }; static ProvidersFeature: o.ExternalReference = {name: 'ɵɵProvidersFeature', moduleName: CORE}; static HostDirectivesFeature: o.ExternalReference = { name: 'ɵɵHostDirectivesFeature', moduleName: CORE, }; static InputTransformsFeatureFeature: o.ExternalReference = { name: 'ɵɵInputTransformsFeature', moduleName: CORE, }; static ExternalStylesFeature: o.ExternalReference = { name: 'ɵɵExternalStylesFeature', moduleName: CORE, }; static listener: o.ExternalReference = {name: 'ɵɵlistener', moduleName: CORE}; static getInheritedFactory: o.ExternalReference = { name: 'ɵɵgetInheritedFactory', moduleName: CORE, }; // sanitization-related functions static sanitizeHtml: o.ExternalReference = {name: 'ɵɵsanitizeHtml', moduleName: CORE}; static sanitizeStyle: o.ExternalReference = {name: 'ɵɵsanitizeStyle', moduleName: CORE}; static sanitizeResourceUrl: o.ExternalReference = { name: 'ɵɵsanitizeResourceUrl', moduleName: CORE, }; static sanitizeScript: o.ExternalReference = {name: 'ɵɵsanitizeScript', moduleName: CORE}; static sanitizeUrl: o.ExternalReference = {name: 'ɵɵsanitizeUrl', moduleName: CORE}; static sanitizeUrlOrResourceUrl: o.ExternalReference = { name: 'ɵɵsanitizeUrlOrResourceUrl', moduleName: CORE, }; static trustConstantHtml: o.ExternalReference = {name: 'ɵɵtrustConstantHtml', moduleName: CORE}; s
{ "end_byte": 22575, "start_byte": 14731, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_identifiers.ts" }
angular/packages/compiler/src/render3/r3_identifiers.ts_22578_23544
ic trustConstantResourceUrl: o.ExternalReference = { name: 'ɵɵtrustConstantResourceUrl', moduleName: CORE, }; static validateIframeAttribute: o.ExternalReference = { name: 'ɵɵvalidateIframeAttribute', moduleName: CORE, }; // type-checking static InputSignalBrandWriteType = {name: 'ɵINPUT_SIGNAL_BRAND_WRITE_TYPE', moduleName: CORE}; static UnwrapDirectiveSignalInputs = {name: 'ɵUnwrapDirectiveSignalInputs', moduleName: CORE}; static unwrapWritableSignal = {name: 'ɵunwrapWritableSignal', moduleName: CORE}; }
{ "end_byte": 23544, "start_byte": 22578, "url": "https://github.com/angular/angular/blob/main/packages/compiler/src/render3/r3_identifiers.ts" }