UNPKG

19.3 kBTypeScriptView Raw
1/**
2 * @license
3 * Copyright Google LLC All Rights Reserved.
4 *
5 * Use of this source code is governed by an MIT-style license that can be
6 * found in the LICENSE file at https://angular.io/license
7 */
8import { LocalResolver } from '../../compiler_util/expression_converter';
9import { ConstantPool } from '../../constant_pool';
10import * as core from '../../core';
11import { AST, AstMemoryEfficientTransformer, BindingPipe, LiteralArray, LiteralMap } from '../../expression_parser/ast';
12import * as i18n from '../../i18n/i18n_ast';
13import { InterpolationConfig } from '../../ml_parser/interpolation_config';
14import { LexerRange } from '../../ml_parser/lexer';
15import * as o from '../../output/output_ast';
16import { ParseError } from '../../parse_util';
17import { CssSelector } from '../../selector';
18import { BindingParser } from '../../template_parser/binding_parser';
19import * as t from '../r3_ast';
20import { I18nContext } from './i18n/context';
21import { invalid } from './util';
22export declare const LEADING_TRIVIA_CHARS: string[];
23export declare function renderFlagCheckIfStmt(flags: core.RenderFlags, statements: o.Statement[]): o.IfStmt;
24export declare function prepareEventListenerParameters(eventAst: t.BoundEvent, handlerName?: string | null, scope?: BindingScope | null): o.Expression[];
25export interface ComponentDefConsts {
26 /**
27 * When a constant requires some pre-processing (e.g. i18n translation block that includes
28 * goog.getMsg and $localize calls), the `prepareStatements` section contains corresponding
29 * statements.
30 */
31 prepareStatements: o.Statement[];
32 /**
33 * Actual expressions that represent constants.
34 */
35 constExpressions: o.Expression[];
36 /**
37 * Cache to avoid generating duplicated i18n translation blocks.
38 */
39 i18nVarRefsCache: Map<i18n.I18nMeta, o.ReadVarExpr>;
40}
41export declare class TemplateDefinitionBuilder implements t.Visitor<void>, LocalResolver {
42 private constantPool;
43 private level;
44 private contextName;
45 private i18nContext;
46 private templateIndex;
47 private templateName;
48 private _namespace;
49 private i18nUseExternalIds;
50 private _constants;
51 private _dataIndex;
52 private _bindingContext;
53 private _prefixCode;
54 /**
55 * List of callbacks to generate creation mode instructions. We store them here as we process
56 * the template so bindings in listeners are resolved only once all nodes have been visited.
57 * This ensures all local refs and context variables are available for matching.
58 */
59 private _creationCodeFns;
60 /**
61 * List of callbacks to generate update mode instructions. We store them here as we process
62 * the template so bindings are resolved only once all nodes have been visited. This ensures
63 * all local refs and context variables are available for matching.
64 */
65 private _updateCodeFns;
66 /** Index of the currently-selected node. */
67 private _currentIndex;
68 /** Temporary variable declarations generated from visiting pipes, literals, etc. */
69 private _tempVariables;
70 /**
71 * List of callbacks to build nested templates. Nested templates must not be visited until
72 * after the parent template has finished visiting all of its nodes. This ensures that all
73 * local ref bindings in nested templates are able to find local ref values if the refs
74 * are defined after the template declaration.
75 */
76 private _nestedTemplateFns;
77 /**
78 * This scope contains local variables declared in the update mode block of the template.
79 * (e.g. refs and context vars in bindings)
80 */
81 private _bindingScope;
82 private _valueConverter;
83 private i18n;
84 private _pureFunctionSlots;
85 private _bindingSlots;
86 private fileBasedI18nSuffix;
87 private _ngContentReservedSlots;
88 private _ngContentSelectorsOffset;
89 private _implicitReceiverExpr;
90 constructor(constantPool: ConstantPool, parentBindingScope: BindingScope, level: number, contextName: string | null, i18nContext: I18nContext | null, templateIndex: number | null, templateName: string | null, _namespace: o.ExternalReference, relativeContextFilePath: string, i18nUseExternalIds: boolean, _constants?: ComponentDefConsts);
91 buildTemplateFunction(nodes: t.Node[], variables: t.Variable[], ngContentSelectorsOffset?: number, i18n?: i18n.I18nMeta): o.FunctionExpr;
92 getLocal(name: string): o.Expression | null;
93 notifyImplicitReceiverUse(): void;
94 maybeRestoreView(): void;
95 private i18nTranslate;
96 private registerContextVariables;
97 private i18nAppendBindings;
98 private i18nBindProps;
99 private i18nGenerateMainBlockVar;
100 private i18nGenerateClosureVar;
101 private i18nUpdateRef;
102 private i18nStart;
103 private i18nEnd;
104 private i18nAttributesInstruction;
105 private getNamespaceInstruction;
106 private addNamespaceInstruction;
107 /**
108 * Adds an update instruction for an interpolated property or attribute, such as
109 * `prop="{{value}}"` or `attr.title="{{value}}"`
110 */
111 private interpolatedUpdateInstruction;
112 visitContent(ngContent: t.Content): void;
113 visitElement(element: t.Element): void;
114 visitTemplate(template: t.Template): void;
115 readonly visitReference: typeof invalid;
116 readonly visitVariable: typeof invalid;
117 readonly visitTextAttribute: typeof invalid;
118 readonly visitBoundAttribute: typeof invalid;
119 readonly visitBoundEvent: typeof invalid;
120 visitBoundText(text: t.BoundText): void;
121 visitText(text: t.Text): void;
122 visitIcu(icu: t.Icu): null;
123 private allocateDataSlot;
124 getConstCount(): number;
125 getVarCount(): number;
126 getConsts(): ComponentDefConsts;
127 getNgContentSelectors(): o.Expression | null;
128 private bindingContext;
129 private templatePropertyBindings;
130 private instructionFn;
131 private processStylingUpdateInstruction;
132 private creationInstruction;
133 private updateInstructionWithAdvance;
134 private updateInstruction;
135 private addAdvanceInstructionIfNecessary;
136 private allocatePureFunctionSlots;
137 private allocateBindingSlots;
138 /**
139 * Gets an expression that refers to the implicit receiver. The implicit
140 * receiver is always the root level context.
141 */
142 private getImplicitReceiverExpr;
143 private convertPropertyBinding;
144 /**
145 * Gets a list of argument expressions to pass to an update instruction expression. Also updates
146 * the temp variables state with temp variables that were identified as needing to be created
147 * while visiting the arguments.
148 * @param value The original expression we will be resolving an arguments list from.
149 */
150 private getUpdateInstructionArguments;
151 /**
152 * Prepares all attribute expression values for the `TAttributes` array.
153 *
154 * The purpose of this function is to properly construct an attributes array that
155 * is passed into the `elementStart` (or just `element`) functions. Because there
156 * are many different types of attributes, the array needs to be constructed in a
157 * special way so that `elementStart` can properly evaluate them.
158 *
159 * The format looks like this:
160 *
161 * ```
162 * attrs = [prop, value, prop2, value2,
163 * PROJECT_AS, selector,
164 * CLASSES, class1, class2,
165 * STYLES, style1, value1, style2, value2,
166 * BINDINGS, name1, name2, name3,
167 * TEMPLATE, name4, name5, name6,
168 * I18N, name7, name8, ...]
169 * ```
170 *
171 * Note that this function will fully ignore all synthetic (@foo) attribute values
172 * because those values are intended to always be generated as property instructions.
173 */
174 private getAttributeExpressions;
175 private addToConsts;
176 private addAttrsToConsts;
177 private prepareRefsArray;
178 private prepareListenerParameter;
179}
180export declare class ValueConverter extends AstMemoryEfficientTransformer {
181 private constantPool;
182 private allocateSlot;
183 private allocatePureFunctionSlots;
184 private definePipe;
185 private _pipeBindExprs;
186 constructor(constantPool: ConstantPool, allocateSlot: () => number, allocatePureFunctionSlots: (numSlots: number) => number, definePipe: (name: string, localName: string, slot: number, value: o.Expression) => void);
187 visitPipe(pipe: BindingPipe, context: any): AST;
188 updatePipeSlotOffsets(bindingSlots: number): void;
189 visitLiteralArray(array: LiteralArray, context: any): AST;
190 visitLiteralMap(map: LiteralMap, context: any): AST;
191}
192/**
193 * Function which is executed whenever a variable is referenced for the first time in a given
194 * scope.
195 *
196 * It is expected that the function creates the `const localName = expression`; statement.
197 */
198export declare type DeclareLocalVarCallback = (scope: BindingScope, relativeLevel: number) => o.Statement[];
199/**
200 * This is used when one refers to variable such as: 'let abc = nextContext(2).$implicit`.
201 * - key to the map is the string literal `"abc"`.
202 * - value `retrievalLevel` is the level from which this value can be retrieved, which is 2 levels
203 * up in example.
204 * - value `lhs` is the left hand side which is an AST representing `abc`.
205 * - value `declareLocalCallback` is a callback that is invoked when declaring the local.
206 * - value `declare` is true if this value needs to be declared.
207 * - value `localRef` is true if we are storing a local reference
208 * - value `priority` dictates the sorting priority of this var declaration compared
209 * to other var declarations on the same retrieval level. For example, if there is a
210 * context variable and a local ref accessing the same parent view, the context var
211 * declaration should always come before the local ref declaration.
212 */
213declare type BindingData = {
214 retrievalLevel: number;
215 lhs: o.Expression;
216 declareLocalCallback?: DeclareLocalVarCallback;
217 declare: boolean;
218 priority: number;
219};
220export declare class BindingScope implements LocalResolver {
221 bindingLevel: number;
222 private parent;
223 globals?: Set<string> | undefined;
224 /** Keeps a map from local variables to their BindingData. */
225 private map;
226 private referenceNameIndex;
227 private restoreViewVariable;
228 private usesRestoredViewContext;
229 static createRootScope(): BindingScope;
230 private constructor();
231 get(name: string): o.Expression | null;
232 /**
233 * Create a local variable for later reference.
234 *
235 * @param retrievalLevel The level from which this value can be retrieved
236 * @param name Name of the variable.
237 * @param lhs AST representing the left hand side of the `let lhs = rhs;`.
238 * @param priority The sorting priority of this var
239 * @param declareLocalCallback The callback to invoke when declaring this local var
240 * @param localRef Whether or not this is a local ref
241 */
242 set(retrievalLevel: number, name: string, lhs: o.Expression, priority?: number, declareLocalCallback?: DeclareLocalVarCallback, localRef?: true): BindingScope;
243 getLocal(name: string): (o.Expression | null);
244 notifyImplicitReceiverUse(): void;
245 nestedScope(level: number, globals?: Set<string>): BindingScope;
246 /**
247 * Gets or creates a shared context variable and returns its expression. Note that
248 * this does not mean that the shared variable will be declared. Variables in the
249 * binding scope will be only declared if they are used.
250 */
251 getOrCreateSharedContextVar(retrievalLevel: number): o.ReadVarExpr;
252 getSharedContextName(retrievalLevel: number): o.ReadVarExpr | null;
253 maybeGenerateSharedContextVar(value: BindingData): void;
254 generateSharedContextVar(retrievalLevel: number): void;
255 getComponentProperty(name: string): o.Expression;
256 maybeRestoreView(): void;
257 restoreViewStatement(): o.Statement[];
258 viewSnapshotStatements(): o.Statement[];
259 isListenerScope(): boolean | null;
260 variableDeclarations(): o.Statement[];
261 freshReferenceName(): string;
262 hasRestoreViewVariable(): boolean;
263 notifyRestoredViewContextUse(): void;
264}
265/**
266 * Creates a `CssSelector` given a tag name and a map of attributes
267 */
268export declare function createCssSelector(elementName: string, attributes: {
269 [name: string]: string;
270}): CssSelector;
271/**
272 * Options that can be used to modify how a template is parsed by `parseTemplate()`.
273 */
274export interface ParseTemplateOptions {
275 /**
276 * Include whitespace nodes in the parsed output.
277 */
278 preserveWhitespaces?: boolean;
279 /**
280 * Preserve original line endings instead of normalizing '\r\n' endings to '\n'.
281 */
282 preserveLineEndings?: boolean;
283 /**
284 * How to parse interpolation markers.
285 */
286 interpolationConfig?: InterpolationConfig;
287 /**
288 * The start and end point of the text to parse within the `source` string.
289 * The entire `source` string is parsed if this is not provided.
290 * */
291 range?: LexerRange;
292 /**
293 * If this text is stored in a JavaScript string, then we have to deal with escape sequences.
294 *
295 * **Example 1:**
296 *
297 * ```
298 * "abc\"def\nghi"
299 * ```
300 *
301 * - The `\"` must be converted to `"`.
302 * - The `\n` must be converted to a new line character in a token,
303 * but it should not increment the current line for source mapping.
304 *
305 * **Example 2:**
306 *
307 * ```
308 * "abc\
309 * def"
310 * ```
311 *
312 * The line continuation (`\` followed by a newline) should be removed from a token
313 * but the new line should increment the current line for source mapping.
314 */
315 escapedString?: boolean;
316 /**
317 * An array of characters that should be considered as leading trivia.
318 * Leading trivia are characters that are not important to the developer, and so should not be
319 * included in source-map segments. A common example is whitespace.
320 */
321 leadingTriviaChars?: string[];
322 /**
323 * Render `$localize` message ids with additional legacy message ids.
324 *
325 * This option defaults to `true` but in the future the defaul will be flipped.
326 *
327 * For now set this option to false if you have migrated the translation files to use the new
328 * `$localize` message id format and you are not using compile time translation merging.
329 */
330 enableI18nLegacyMessageIdFormat?: boolean;
331 /**
332 * If this text is stored in an external template (e.g. via `templateUrl`) then we need to decide
333 * whether or not to normalize the line-endings (from `\r\n` to `\n`) when processing ICU
334 * expressions.
335 *
336 * If `true` then we will normalize ICU expression line endings.
337 * The default is `false`, but this will be switched in a future major release.
338 */
339 i18nNormalizeLineEndingsInICUs?: boolean;
340 /**
341 * Whether to always attempt to convert the parsed HTML AST to an R3 AST, despite HTML or i18n
342 * Meta parse errors.
343 *
344 *
345 * This option is useful in the context of the language service, where we want to get as much
346 * information as possible, despite any errors in the HTML. As an example, a user may be adding
347 * a new tag and expecting autocomplete on that tag. In this scenario, the HTML is in an errored
348 * state, as there is an incomplete open tag. However, we're still able to convert the HTML AST
349 * nodes to R3 AST nodes in order to provide information for the language service.
350 *
351 * Note that even when `true` the HTML parse and i18n errors are still appended to the errors
352 * output, but this is done after converting the HTML AST to R3 AST.
353 */
354 alwaysAttemptHtmlToR3AstConversion?: boolean;
355 /**
356 * Include HTML Comment nodes in a top-level comments array on the returned R3 AST.
357 *
358 * This option is required by tooling that needs to know the location of comment nodes within the
359 * AST. A concrete example is @angular-eslint which requires this in order to enable
360 * "eslint-disable" comments within HTML templates, which then allows users to turn off specific
361 * rules on a case by case basis, instead of for their whole project within a configuration file.
362 */
363 collectCommentNodes?: boolean;
364}
365/**
366 * Parse a template into render3 `Node`s and additional metadata, with no other dependencies.
367 *
368 * @param template text of the template to parse
369 * @param templateUrl URL to use for source mapping of the parsed template
370 * @param options options to modify how the template is parsed
371 */
372export declare function parseTemplate(template: string, templateUrl: string, options?: ParseTemplateOptions): ParsedTemplate;
373/**
374 * Construct a `BindingParser` with a default configuration.
375 */
376export declare function makeBindingParser(interpolationConfig?: InterpolationConfig): BindingParser;
377export declare function resolveSanitizationFn(context: core.SecurityContext, isAttribute?: boolean): o.ExternalExpr | null;
378/**
379 * Generate statements that define a given translation message.
380 *
381 * ```
382 * var I18N_1;
383 * if (typeof ngI18nClosureMode !== undefined && ngI18nClosureMode) {
384 * var MSG_EXTERNAL_XXX = goog.getMsg(
385 * "Some message with {$interpolation}!",
386 * { "interpolation": "\uFFFD0\uFFFD" }
387 * );
388 * I18N_1 = MSG_EXTERNAL_XXX;
389 * }
390 * else {
391 * I18N_1 = $localize`Some message with ${'\uFFFD0\uFFFD'}!`;
392 * }
393 * ```
394 *
395 * @param message The original i18n AST message node
396 * @param variable The variable that will be assigned the translation, e.g. `I18N_1`.
397 * @param closureVar The variable for Closure `goog.getMsg` calls, e.g. `MSG_EXTERNAL_XXX`.
398 * @param params Object mapping placeholder names to their values (e.g.
399 * `{ "interpolation": "\uFFFD0\uFFFD" }`).
400 * @param transformFn Optional transformation function that will be applied to the translation (e.g.
401 * post-processing).
402 * @returns An array of statements that defined a given translation.
403 */
404export declare function getTranslationDeclStmts(message: i18n.Message, variable: o.ReadVarExpr, closureVar: o.ReadVarExpr, params?: {
405 [name: string]: o.Expression;
406}, transformFn?: (raw: o.ReadVarExpr) => o.Expression): o.Statement[];
407/**
408 * Information about the template which was extracted during parsing.
409 *
410 * This contains the actual parsed template as well as any metadata collected during its parsing,
411 * some of which might be useful for re-parsing the template with different options.
412 */
413export interface ParsedTemplate {
414 /**
415 * Include whitespace nodes in the parsed output.
416 */
417 preserveWhitespaces?: boolean;
418 /**
419 * How to parse interpolation markers.
420 */
421 interpolationConfig?: InterpolationConfig;
422 /**
423 * Any errors from parsing the template the first time.
424 *
425 * `null` if there are no errors. Otherwise, the array of errors is guaranteed to be non-empty.
426 */
427 errors: ParseError[] | null;
428 /**
429 * The template AST, parsed from the template.
430 */
431 nodes: t.Node[];
432 /**
433 * Any styleUrls extracted from the metadata.
434 */
435 styleUrls: string[];
436 /**
437 * Any inline styles extracted from the metadata.
438 */
439 styles: string[];
440 /**
441 * Any ng-content selectors extracted from the template.
442 */
443 ngContentSelectors: string[];
444 /**
445 * Any R3 Comment Nodes extracted from the template when the `collectCommentNodes` parse template
446 * option is enabled.
447 */
448 commentNodes?: t.Comment[];
449}
450export {};