_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/compiler/test/ml_parser/lexer_spec.ts_112339_119778 | ribe('(processing escaped strings)', () => {
it('should unescape standard escape sequences', () => {
expect(tokenizeAndHumanizeParts("\\' \\' \\'", {escapedString: true})).toEqual([
[TokenType.TEXT, "' ' '"],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\" \\" \\"', {escapedString: true})).toEqual([
[TokenType.TEXT, '" " "'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\` \\` \\`', {escapedString: true})).toEqual([
[TokenType.TEXT, '` ` `'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\\\ \\\\ \\\\', {escapedString: true})).toEqual([
[TokenType.TEXT, '\\ \\ \\'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\n \\n \\n', {escapedString: true})).toEqual([
[TokenType.TEXT, '\n \n \n'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\r{{\\r}}\\r', {escapedString: true})).toEqual([
// post processing converts `\r` to `\n`
[TokenType.TEXT, '\n'],
[TokenType.INTERPOLATION, '{{', '\n', '}}'],
[TokenType.TEXT, '\n'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\v \\v \\v', {escapedString: true})).toEqual([
[TokenType.TEXT, '\v \v \v'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\t \\t \\t', {escapedString: true})).toEqual([
[TokenType.TEXT, '\t \t \t'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\b \\b \\b', {escapedString: true})).toEqual([
[TokenType.TEXT, '\b \b \b'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\f \\f \\f', {escapedString: true})).toEqual([
[TokenType.TEXT, '\f \f \f'],
[TokenType.EOF],
]);
expect(
tokenizeAndHumanizeParts('\\\' \\" \\` \\\\ \\n \\r \\v \\t \\b \\f', {
escapedString: true,
}),
).toEqual([[TokenType.TEXT, '\' " ` \\ \n \n \v \t \b \f'], [TokenType.EOF]]);
});
it('should unescape null sequences', () => {
expect(tokenizeAndHumanizeParts('\\0', {escapedString: true})).toEqual([[TokenType.EOF]]);
// \09 is not an octal number so the \0 is taken as EOF
expect(tokenizeAndHumanizeParts('\\09', {escapedString: true})).toEqual([[TokenType.EOF]]);
});
it('should unescape octal sequences', () => {
// \19 is read as an octal `\1` followed by a normal char `9`
// \1234 is read as an octal `\123` followed by a normal char `4`
// \999 is not an octal number so its backslash just gets removed.
expect(
tokenizeAndHumanizeParts('\\001 \\01 \\1 \\12 \\223 \\19 \\2234 \\999', {
escapedString: true,
}),
).toEqual([[TokenType.TEXT, '\x01 \x01 \x01 \x0A \x93 \x019 \x934 999'], [TokenType.EOF]]);
});
it('should unescape hex sequences', () => {
expect(tokenizeAndHumanizeParts('\\x12 \\x4F \\xDC', {escapedString: true})).toEqual([
[TokenType.TEXT, '\x12 \x4F \xDC'],
[TokenType.EOF],
]);
});
it('should report an error on an invalid hex sequence', () => {
expect(tokenizeAndHumanizeErrors('\\xGG', {escapedString: true})).toEqual([
[null, 'Invalid hexadecimal escape sequence', '0:2'],
]);
expect(tokenizeAndHumanizeErrors('abc \\x xyz', {escapedString: true})).toEqual([
[TokenType.TEXT, 'Invalid hexadecimal escape sequence', '0:6'],
]);
expect(tokenizeAndHumanizeErrors('abc\\x', {escapedString: true})).toEqual([
[TokenType.TEXT, 'Unexpected character "EOF"', '0:5'],
]);
});
it('should unescape fixed length Unicode sequences', () => {
expect(tokenizeAndHumanizeParts('\\u0123 \\uABCD', {escapedString: true})).toEqual([
[TokenType.TEXT, '\u0123 \uABCD'],
[TokenType.EOF],
]);
});
it('should error on an invalid fixed length Unicode sequence', () => {
expect(tokenizeAndHumanizeErrors('\\uGGGG', {escapedString: true})).toEqual([
[null, 'Invalid hexadecimal escape sequence', '0:2'],
]);
});
it('should unescape variable length Unicode sequences', () => {
expect(
tokenizeAndHumanizeParts('\\u{01} \\u{ABC} \\u{1234} \\u{123AB}', {escapedString: true}),
).toEqual([[TokenType.TEXT, '\u{01} \u{ABC} \u{1234} \u{123AB}'], [TokenType.EOF]]);
});
it('should error on an invalid variable length Unicode sequence', () => {
expect(tokenizeAndHumanizeErrors('\\u{GG}', {escapedString: true})).toEqual([
[null, 'Invalid hexadecimal escape sequence', '0:3'],
]);
});
it('should unescape line continuations', () => {
expect(tokenizeAndHumanizeParts('abc\\\ndef', {escapedString: true})).toEqual([
[TokenType.TEXT, 'abcdef'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('\\\nx\\\ny\\\n', {escapedString: true})).toEqual([
[TokenType.TEXT, 'xy'],
[TokenType.EOF],
]);
});
it('should remove backslash from "non-escape" sequences', () => {
expect(tokenizeAndHumanizeParts('a g ~', {escapedString: true})).toEqual([
[TokenType.TEXT, 'a g ~'],
[TokenType.EOF],
]);
});
it('should unescape sequences in plain text', () => {
expect(
tokenizeAndHumanizeParts('abc\ndef\\nghi\\tjkl\\`\\\'\\"mno', {escapedString: true}),
).toEqual([[TokenType.TEXT, 'abc\ndef\nghi\tjkl`\'"mno'], [TokenType.EOF]]);
});
it('should unescape sequences in raw text', () => {
expect(
tokenizeAndHumanizeParts('<script>abc\ndef\\nghi\\tjkl\\`\\\'\\"mno</script>', {
escapedString: true,
}),
).toEqual([
[TokenType.TAG_OPEN_START, '', 'script'],
[TokenType.TAG_OPEN_END],
[TokenType.RAW_TEXT, 'abc\ndef\nghi\tjkl`\'"mno'],
[TokenType.TAG_CLOSE, '', 'script'],
[TokenType.EOF],
]);
});
it('should unescape sequences in escapable raw text', () => {
expect(
tokenizeAndHumanizeParts('<title>abc\ndef\\nghi\\tjkl\\`\\\'\\"mno</title>', {
escapedString: true,
}),
).toEqual([
[TokenType.TAG_OPEN_START, '', 'title'],
[TokenType.TAG_OPEN_END],
[TokenType.ESCAPABLE_RAW_TEXT, 'abc\ndef\nghi\tjkl`\'"mno'],
[TokenType.TAG_CLOSE, '', 'title'],
[TokenType.EOF],
]);
});
it('should parse over escape sequences in tag definitions', () => {
expect(
tokenizeAndHumanizeParts('<t a=\\"b\\" \\n c=\\\'d\\\'>', {escapedString: true}),
).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, 'b'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_NAME, '', 'c'],
[TokenType.ATTR_QUOTE, "'"],
[TokenType.ATTR_VALUE_TEXT, 'd'],
[TokenType.ATTR_QUOTE, "'"],
[TokenType.TAG_OPEN_END],
[TokenType.EOF],
]);
});
it('should parse over escaped new line in tag definitions', () => {
const text = '<t\\n></t>';
expect(tokenizeAndHumanizeParts(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_CLOSE, '', 't'],
[TokenType.EOF],
]);
});
| {
"end_byte": 119778,
"start_byte": 112339,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_119784_124781 | should parse over escaped characters in tag definitions', () => {
const text = '<t\u{000013}></t>';
expect(tokenizeAndHumanizeParts(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_CLOSE, '', 't'],
[TokenType.EOF],
]);
});
it('should unescape characters in tag names', () => {
const text = '<t\\x64></t\\x64>';
expect(tokenizeAndHumanizeParts(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '', 'td'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_CLOSE, '', 'td'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeSourceSpans(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '<t\\x64'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.TAG_CLOSE, '</t\\x64>'],
[TokenType.EOF, ''],
]);
});
it('should unescape characters in attributes', () => {
const text = '<t \\x64="\\x65"></t>';
expect(tokenizeAndHumanizeParts(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'd'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, 'e'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_CLOSE, '', 't'],
[TokenType.EOF],
]);
});
it('should parse over escaped new line in attribute values', () => {
const text = '<t a=b\\n></t>';
expect(tokenizeAndHumanizeParts(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_VALUE_TEXT, 'b'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_CLOSE, '', 't'],
[TokenType.EOF],
]);
});
it('should tokenize the correct span when there are escape sequences', () => {
const text = 'selector: "app-root",\ntemplate: "line 1\\n\\"line 2\\"\\nline 3",\ninputs: []';
const range = {
startPos: 33,
startLine: 1,
startCol: 10,
endPos: 59,
};
expect(tokenizeAndHumanizeParts(text, {range, escapedString: true})).toEqual([
[TokenType.TEXT, 'line 1\n"line 2"\nline 3'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeSourceSpans(text, {range, escapedString: true})).toEqual([
[TokenType.TEXT, 'line 1\\n\\"line 2\\"\\nline 3'],
[TokenType.EOF, ''],
]);
});
it('should account for escape sequences when computing source spans ', () => {
const text =
'<t>line 1</t>\n' + // <- unescaped line break
'<t>line 2</t>\\n' + // <- escaped line break
'<t>line 3\\\n' + // <- line continuation
'</t>';
expect(tokenizeAndHumanizeParts(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, 'line 1'],
[TokenType.TAG_CLOSE, '', 't'],
[TokenType.TEXT, '\n'],
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, 'line 2'],
[TokenType.TAG_CLOSE, '', 't'],
[TokenType.TEXT, '\n'],
[TokenType.TAG_OPEN_START, '', 't'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, 'line 3'], // <- line continuation does not appear in token
[TokenType.TAG_CLOSE, '', 't'],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeLineColumn(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '0:0'],
[TokenType.TAG_OPEN_END, '0:2'],
[TokenType.TEXT, '0:3'],
[TokenType.TAG_CLOSE, '0:9'],
[TokenType.TEXT, '0:13'], // <- real newline increments the row
[TokenType.TAG_OPEN_START, '1:0'],
[TokenType.TAG_OPEN_END, '1:2'],
[TokenType.TEXT, '1:3'],
[TokenType.TAG_CLOSE, '1:9'],
[TokenType.TEXT, '1:13'], // <- escaped newline does not increment the row
[TokenType.TAG_OPEN_START, '1:15'],
[TokenType.TAG_OPEN_END, '1:17'],
[TokenType.TEXT, '1:18'], // <- the line continuation increments the row
[TokenType.TAG_CLOSE, '2:0'],
[TokenType.EOF, '2:4'],
]);
expect(tokenizeAndHumanizeSourceSpans(text, {escapedString: true})).toEqual([
[TokenType.TAG_OPEN_START, '<t'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.TEXT, 'line 1'],
[TokenType.TAG_CLOSE, '</t>'],
[TokenType.TEXT, '\n'],
[TokenType.TAG_OPEN_START, '<t'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.TEXT, 'line 2'],
[TokenType.TAG_CLOSE, '</t>'],
[TokenType.TEXT, '\\n'],
[TokenType.TAG_OPEN_START, '<t'],
[TokenType.TAG_OPEN_END, '>'],
[TokenType.TEXT, 'line 3\\\n'],
[TokenType.TAG_CLOSE, '</t>'],
[TokenType.EOF, ''],
]);
});
});
| {
"end_byte": 124781,
"start_byte": 119784,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_124785_132850 | ribe('blocks', () => {
it('should parse a block without parameters', () => {
const expected = [
[TokenType.BLOCK_OPEN_START, 'foo'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
];
expect(tokenizeAndHumanizeParts('@foo {hello}')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@foo () {hello}')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@foo(){hello}')).toEqual(expected);
});
it('should parse a block with parameters', () => {
expect(tokenizeAndHumanizeParts('@for (item of items; track item.id) {hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'for'],
[TokenType.BLOCK_PARAMETER, 'item of items'],
[TokenType.BLOCK_PARAMETER, 'track item.id'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse a block with a trailing semicolon after the parameters', () => {
expect(tokenizeAndHumanizeParts('@for (item of items;) {hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'for'],
[TokenType.BLOCK_PARAMETER, 'item of items'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse a block with a space in its name', () => {
expect(tokenizeAndHumanizeParts('@else if {hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'else if'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
expect(tokenizeAndHumanizeParts('@else if (foo !== 2) {hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'else if'],
[TokenType.BLOCK_PARAMETER, 'foo !== 2'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse a block with an arbitrary amount of spaces around the parentheses', () => {
const expected = [
[TokenType.BLOCK_OPEN_START, 'foo'],
[TokenType.BLOCK_PARAMETER, 'a'],
[TokenType.BLOCK_PARAMETER, 'b'],
[TokenType.BLOCK_PARAMETER, 'c'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
];
expect(tokenizeAndHumanizeParts('@foo(a; b; c){hello}')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@foo (a; b; c) {hello}')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@foo(a; b; c) {hello}')).toEqual(expected);
expect(tokenizeAndHumanizeParts('@foo (a; b; c){hello}')).toEqual(expected);
});
it('should parse a block with multiple trailing semicolons', () => {
expect(tokenizeAndHumanizeParts('@for (item of items;;;;;) {hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'for'],
[TokenType.BLOCK_PARAMETER, 'item of items'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse a block with trailing whitespace', () => {
expect(tokenizeAndHumanizeParts('@foo {hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'foo'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse a block with no trailing semicolon', () => {
expect(tokenizeAndHumanizeParts('@for (item of items){hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'for'],
[TokenType.BLOCK_PARAMETER, 'item of items'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should handle semicolons, braces and parentheses used in a block parameter', () => {
const input = `@foo (a === ";"; b === ')'; c === "("; d === '}'; e === "{") {hello}`;
expect(tokenizeAndHumanizeParts(input)).toEqual([
[TokenType.BLOCK_OPEN_START, 'foo'],
[TokenType.BLOCK_PARAMETER, `a === ";"`],
[TokenType.BLOCK_PARAMETER, `b === ')'`],
[TokenType.BLOCK_PARAMETER, `c === "("`],
[TokenType.BLOCK_PARAMETER, `d === '}'`],
[TokenType.BLOCK_PARAMETER, `e === "{"`],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should handle object literals and function calls in block parameters', () => {
expect(
tokenizeAndHumanizeParts(
`@foo (on a({a: 1, b: 2}, false, {c: 3}); when b({d: 4})) {hello}`,
),
).toEqual([
[TokenType.BLOCK_OPEN_START, 'foo'],
[TokenType.BLOCK_PARAMETER, 'on a({a: 1, b: 2}, false, {c: 3})'],
[TokenType.BLOCK_PARAMETER, 'when b({d: 4})'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse block with unclosed parameters', () => {
expect(tokenizeAndHumanizeParts(`@foo (a === b {hello}`)).toEqual([
[TokenType.INCOMPLETE_BLOCK_OPEN, 'foo'],
[TokenType.BLOCK_PARAMETER, 'a === b {hello}'],
[TokenType.EOF],
]);
});
it('should parse block with stray parentheses in the parameter position', () => {
expect(tokenizeAndHumanizeParts(`@foo a === b) {hello}`)).toEqual([
[TokenType.INCOMPLETE_BLOCK_OPEN, 'foo a'],
[TokenType.TEXT, '=== b) {hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should report invalid quotes in a parameter', () => {
expect(tokenizeAndHumanizeErrors(`@foo (a === ") {hello}`)).toEqual([
[TokenType.BLOCK_PARAMETER, 'Unexpected character "EOF"', '0:22'],
]);
expect(tokenizeAndHumanizeErrors(`@foo (a === "hi') {hello}`)).toEqual([
[TokenType.BLOCK_PARAMETER, 'Unexpected character "EOF"', '0:25'],
]);
});
it('should report unclosed object literal inside a parameter', () => {
expect(tokenizeAndHumanizeParts(`@foo ({invalid: true) hello}`)).toEqual([
[TokenType.INCOMPLETE_BLOCK_OPEN, 'foo'],
[TokenType.BLOCK_PARAMETER, '{invalid: true'],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should handle a semicolon used in a nested string inside a block parameter', () => {
expect(tokenizeAndHumanizeParts(`@if (condition === "';'") {hello}`)).toEqual([
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_PARAMETER, `condition === "';'"`],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should handle a semicolon next to an escaped quote used in a block parameter', () => {
expect(tokenizeAndHumanizeParts('@if (condition === "\\";") {hello}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_PARAMETER, 'condition === "\\";"'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse mixed text and html content in a block', () => {
expect(tokenizeAndHumanizeParts('@if (a === 1) {foo <b>bar</b> baz}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_PARAMETER, 'a === 1'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'foo '],
[TokenType.TAG_OPEN_START, '', 'b'],
[TokenType.TAG_OPEN_END],
[TokenType.TEXT, 'bar'],
[TokenType.TAG_CLOSE, '', 'b'],
[TokenType.TEXT, ' baz'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
| {
"end_byte": 132850,
"start_byte": 124785,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/lexer_spec.ts_132856_140026 | should parse HTML tags with attributes containing curly braces inside blocks', () => {
expect(tokenizeAndHumanizeParts('@if (a === 1) {<div a="}" b="{"></div>}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_PARAMETER, 'a === 1'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TAG_OPEN_START, '', 'div'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, '}'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_NAME, '', 'b'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, '{'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_CLOSE, '', 'div'],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse HTML tags with attribute containing block syntax', () => {
expect(tokenizeAndHumanizeParts('<div a="@if (foo) {}"></div>')).toEqual([
[TokenType.TAG_OPEN_START, '', 'div'],
[TokenType.ATTR_NAME, '', 'a'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.ATTR_VALUE_TEXT, '@if (foo) {}'],
[TokenType.ATTR_QUOTE, '"'],
[TokenType.TAG_OPEN_END],
[TokenType.TAG_CLOSE, '', 'div'],
[TokenType.EOF],
]);
});
it('should parse nested blocks', () => {
expect(
tokenizeAndHumanizeParts(
'@if (a) {' +
'hello a' +
'@if {' +
'hello unnamed' +
'@if (b) {' +
'hello b' +
'@if (c) {' +
'hello c' +
'}' +
'}' +
'}' +
'}',
),
).toEqual([
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_PARAMETER, 'a'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello a'],
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello unnamed'],
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_PARAMETER, 'b'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello b'],
[TokenType.BLOCK_OPEN_START, 'if'],
[TokenType.BLOCK_PARAMETER, 'c'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, 'hello c'],
[TokenType.BLOCK_CLOSE],
[TokenType.BLOCK_CLOSE],
[TokenType.BLOCK_CLOSE],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse a block containing an expansion', () => {
const result = tokenizeAndHumanizeParts(
'@foo {{one.two, three, =4 {four} =5 {five} foo {bar} }}',
{tokenizeExpansionForms: true},
);
expect(result).toEqual([
[TokenType.BLOCK_OPEN_START, 'foo'],
[TokenType.BLOCK_OPEN_END],
[TokenType.EXPANSION_FORM_START],
[TokenType.RAW_TEXT, 'one.two'],
[TokenType.RAW_TEXT, 'three'],
[TokenType.EXPANSION_CASE_VALUE, '=4'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'four'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, '=5'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'five'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_CASE_VALUE, 'foo'],
[TokenType.EXPANSION_CASE_EXP_START],
[TokenType.TEXT, 'bar'],
[TokenType.EXPANSION_CASE_EXP_END],
[TokenType.EXPANSION_FORM_END],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse a block containing an interpolation', () => {
expect(tokenizeAndHumanizeParts('@foo {{{message}}}')).toEqual([
[TokenType.BLOCK_OPEN_START, 'foo'],
[TokenType.BLOCK_OPEN_END],
[TokenType.TEXT, ''],
[TokenType.INTERPOLATION, '{{', 'message', '}}'],
[TokenType.TEXT, ''],
[TokenType.BLOCK_CLOSE],
[TokenType.EOF],
]);
});
it('should parse an incomplete block start without parameters with surrounding text', () => {
expect(tokenizeAndHumanizeParts('My email frodo@baggins.com')).toEqual([
[TokenType.TEXT, 'My email frodo'],
[TokenType.INCOMPLETE_BLOCK_OPEN, 'baggins'],
[TokenType.TEXT, '.com'],
[TokenType.EOF],
]);
});
it('should parse an incomplete block start at the end of the input', () => {
expect(tokenizeAndHumanizeParts('My username is @frodo')).toEqual([
[TokenType.TEXT, 'My username is '],
[TokenType.INCOMPLETE_BLOCK_OPEN, 'frodo'],
[TokenType.EOF],
]);
});
it('should parse an incomplete block start with parentheses but without params', () => {
expect(tokenizeAndHumanizeParts('Use the @Input() decorator')).toEqual([
[TokenType.TEXT, 'Use the '],
[TokenType.INCOMPLETE_BLOCK_OPEN, 'Input'],
[TokenType.TEXT, 'decorator'],
[TokenType.EOF],
]);
});
it('should parse an incomplete block start with parentheses and params', () => {
expect(tokenizeAndHumanizeParts('Use @Input({alias: "foo"}) to alias the input')).toEqual([
[TokenType.TEXT, 'Use '],
[TokenType.INCOMPLETE_BLOCK_OPEN, 'Input'],
[TokenType.BLOCK_PARAMETER, '{alias: "foo"}'],
[TokenType.TEXT, 'to alias the input'],
[TokenType.EOF],
]);
});
});
});
function tokenizeWithoutErrors(input: string, options?: TokenizeOptions): TokenizeResult {
const tokenizeResult = tokenize(input, 'someUrl', getHtmlTagDefinition, options);
if (tokenizeResult.errors.length > 0) {
const errorString = tokenizeResult.errors.join('\n');
throw new Error(`Unexpected parse errors:\n${errorString}`);
}
return tokenizeResult;
}
function humanizeParts(tokens: Token[]) {
return tokens.map((token) => [token.type, ...token.parts]);
}
function tokenizeAndHumanizeParts(input: string, options?: TokenizeOptions): any[] {
return humanizeParts(tokenizeWithoutErrors(input, options).tokens);
}
function tokenizeAndHumanizeSourceSpans(input: string, options?: TokenizeOptions): any[] {
return tokenizeWithoutErrors(input, options).tokens.map((token) => [
<any>token.type,
token.sourceSpan.toString(),
]);
}
function humanizeLineColumn(location: ParseLocation): string {
return `${location.line}:${location.col}`;
}
function tokenizeAndHumanizeLineColumn(input: string, options?: TokenizeOptions): any[] {
return tokenizeWithoutErrors(input, options).tokens.map((token) => [
<any>token.type,
humanizeLineColumn(token.sourceSpan.start),
]);
}
function tokenizeAndHumanizeFullStart(input: string, options?: TokenizeOptions): any[] {
return tokenizeWithoutErrors(input, options).tokens.map((token) => [
<any>token.type,
humanizeLineColumn(token.sourceSpan.start),
humanizeLineColumn(token.sourceSpan.fullStart),
]);
}
function tokenizeAndHumanizeErrors(input: string, options?: TokenizeOptions): any[] {
return tokenize(input, 'someUrl', getHtmlTagDefinition, options).errors.map((e) => [
<any>e.tokenType,
e.msg,
humanizeLineColumn(e.span.start),
]);
}
| {
"end_byte": 140026,
"start_byte": 132856,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/lexer_spec.ts"
} |
angular/packages/compiler/test/ml_parser/util/util.ts_0_2211 | /**
* @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 '@angular/compiler/src/ml_parser/ast';
import {getHtmlTagDefinition} from '@angular/compiler/src/ml_parser/html_tags';
class _SerializerVisitor implements html.Visitor {
visitElement(element: html.Element, context: any): any {
if (getHtmlTagDefinition(element.name).isVoid) {
return `<${element.name}${this._visitAll(element.attrs, ' ', ' ')}/>`;
}
return `<${element.name}${this._visitAll(element.attrs, ' ', ' ')}>${this._visitAll(
element.children,
)}</${element.name}>`;
}
visitAttribute(attribute: html.Attribute, context: any): any {
return `${attribute.name}="${attribute.value}"`;
}
visitText(text: html.Text, context: any): any {
return text.value;
}
visitComment(comment: html.Comment, context: any): any {
return `<!--${comment.value}-->`;
}
visitExpansion(expansion: html.Expansion, context: any): any {
return `{${expansion.switchValue}, ${expansion.type},${this._visitAll(expansion.cases)}}`;
}
visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any {
return ` ${expansionCase.value} {${this._visitAll(expansionCase.expression)}}`;
}
visitBlock(block: html.Block, context: any) {
const params =
block.parameters.length === 0 ? ' ' : ` (${this._visitAll(block.parameters, ';', ' ')}) `;
return `@${block.name}${params}{${this._visitAll(block.children)}}`;
}
visitBlockParameter(parameter: html.BlockParameter, context: any) {
return parameter.expression;
}
visitLetDeclaration(decl: html.LetDeclaration, context: any) {
return `@let ${decl.name} = ${decl.value};`;
}
private _visitAll(nodes: html.Node[], separator = '', prefix = ''): string {
return nodes.length > 0 ? prefix + nodes.map((a) => a.visit(this, null)).join(separator) : '';
}
}
const serializerVisitor = new _SerializerVisitor();
export function serializeNodes(nodes: html.Node[]): string[] {
return nodes.map((node) => node.visit(serializerVisitor, null));
}
| {
"end_byte": 2211,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/util/util.ts"
} |
angular/packages/compiler/test/ml_parser/util/BUILD.bazel_0_249 | load("//tools:defaults.bzl", "ts_library")
ts_library(
name = "util",
testonly = True,
srcs = glob(["**/*.ts"]),
visibility = ["//visibility:public"],
deps = [
"//packages:types",
"//packages/compiler",
],
)
| {
"end_byte": 249,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/test/ml_parser/util/BUILD.bazel"
} |
angular/packages/compiler/src/injectable_compiler_2.ts_0_6167 | /**
* @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 {
compileFactoryFunction,
FactoryTarget,
R3DependencyMetadata,
R3FactoryDelegateType,
R3FactoryMetadata,
} from './render3/r3_factory';
import {Identifiers} from './render3/r3_identifiers';
import {
convertFromMaybeForwardRefExpression,
MaybeForwardRefExpression,
R3CompiledExpression,
R3Reference,
typeWithParameters,
} from './render3/util';
import {DefinitionMap} from './render3/view/util';
export interface R3InjectableMetadata {
name: string;
type: R3Reference;
typeArgumentCount: number;
providedIn: MaybeForwardRefExpression;
useClass?: MaybeForwardRefExpression;
useFactory?: o.Expression;
useExisting?: MaybeForwardRefExpression;
useValue?: MaybeForwardRefExpression;
deps?: R3DependencyMetadata[];
}
export function compileInjectable(
meta: R3InjectableMetadata,
resolveForwardRefs: boolean,
): R3CompiledExpression {
let result: {expression: o.Expression; statements: o.Statement[]} | null = null;
const factoryMeta: R3FactoryMetadata = {
name: meta.name,
type: meta.type,
typeArgumentCount: meta.typeArgumentCount,
deps: [],
target: FactoryTarget.Injectable,
};
if (meta.useClass !== undefined) {
// meta.useClass has two modes of operation. Either deps are specified, in which case `new` is
// used to instantiate the class with dependencies injected, or deps are not specified and
// the factory of the class is used to instantiate it.
//
// A special case exists for useClass: Type where Type is the injectable type itself and no
// deps are specified, in which case 'useClass' is effectively ignored.
const useClassOnSelf = meta.useClass.expression.isEquivalent(meta.type.value);
let deps: R3DependencyMetadata[] | undefined = undefined;
if (meta.deps !== undefined) {
deps = meta.deps;
}
if (deps !== undefined) {
// factory: () => new meta.useClass(...deps)
result = compileFactoryFunction({
...factoryMeta,
delegate: meta.useClass.expression,
delegateDeps: deps,
delegateType: R3FactoryDelegateType.Class,
});
} else if (useClassOnSelf) {
result = compileFactoryFunction(factoryMeta);
} else {
result = {
statements: [],
expression: delegateToFactory(
meta.type.value as o.WrappedNodeExpr<any>,
meta.useClass.expression as o.WrappedNodeExpr<any>,
resolveForwardRefs,
),
};
}
} else if (meta.useFactory !== undefined) {
if (meta.deps !== undefined) {
result = compileFactoryFunction({
...factoryMeta,
delegate: meta.useFactory,
delegateDeps: meta.deps || [],
delegateType: R3FactoryDelegateType.Function,
});
} else {
result = {statements: [], expression: o.arrowFn([], meta.useFactory.callFn([]))};
}
} else if (meta.useValue !== undefined) {
// Note: it's safe to use `meta.useValue` instead of the `USE_VALUE in meta` check used for
// client code because meta.useValue is an Expression which will be defined even if the actual
// value is undefined.
result = compileFactoryFunction({
...factoryMeta,
expression: meta.useValue.expression,
});
} else if (meta.useExisting !== undefined) {
// useExisting is an `inject` call on the existing token.
result = compileFactoryFunction({
...factoryMeta,
expression: o.importExpr(Identifiers.inject).callFn([meta.useExisting.expression]),
});
} else {
result = {
statements: [],
expression: delegateToFactory(
meta.type.value as o.WrappedNodeExpr<any>,
meta.type.value as o.WrappedNodeExpr<any>,
resolveForwardRefs,
),
};
}
const token = meta.type.value;
const injectableProps = new DefinitionMap<{
token: o.Expression;
factory: o.Expression;
providedIn: o.Expression;
}>();
injectableProps.set('token', token);
injectableProps.set('factory', result.expression);
// Only generate providedIn property if it has a non-null value
if ((meta.providedIn.expression as o.LiteralExpr).value !== null) {
injectableProps.set('providedIn', convertFromMaybeForwardRefExpression(meta.providedIn));
}
const expression = o
.importExpr(Identifiers.ɵɵdefineInjectable)
.callFn([injectableProps.toLiteralMap()], undefined, true);
return {
expression,
type: createInjectableType(meta),
statements: result.statements,
};
}
export function createInjectableType(meta: R3InjectableMetadata) {
return new o.ExpressionType(
o.importExpr(Identifiers.InjectableDeclaration, [
typeWithParameters(meta.type.type, meta.typeArgumentCount),
]),
);
}
function delegateToFactory(
type: o.WrappedNodeExpr<any>,
useType: o.WrappedNodeExpr<any>,
unwrapForwardRefs: boolean,
): o.Expression {
if (type.node === useType.node) {
// The types are the same, so we can simply delegate directly to the type's factory.
// ```
// factory: type.ɵfac
// ```
return useType.prop('ɵfac');
}
if (!unwrapForwardRefs) {
// The type is not wrapped in a `forwardRef()`, so we create a simple factory function that
// accepts a sub-type as an argument.
// ```
// factory: function(t) { return useType.ɵfac(t); }
// ```
return createFactoryFunction(useType);
}
// The useType is actually wrapped in a `forwardRef()` so we need to resolve that before
// calling its factory.
// ```
// factory: function(t) { return core.resolveForwardRef(type).ɵfac(t); }
// ```
const unwrappedType = o.importExpr(Identifiers.resolveForwardRef).callFn([useType]);
return createFactoryFunction(unwrappedType);
}
function createFactoryFunction(type: o.Expression): o.ArrowFunctionExpr {
const t = new o.FnParam('__ngFactoryType__', o.DYNAMIC_TYPE);
return o.arrowFn([t], type.prop('ɵfac').callFn([o.variable(t.name)]));
}
| {
"end_byte": 6167,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/injectable_compiler_2.ts"
} |
angular/packages/compiler/src/style_url_resolver.ts_0_683 | /**
* @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
*/
// Some of the code comes from WebComponents.JS
// https://github.com/webcomponents/webcomponentsjs/blob/master/src/HTMLImports/path.js
export function isStyleUrlResolvable(url: string | null): url is string {
if (url == null || url.length === 0 || url[0] == '/') return false;
const schemeMatch = url.match(URL_WITH_SCHEMA_REGEXP);
return schemeMatch === null || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset';
}
const URL_WITH_SCHEMA_REGEXP = /^([^:/?#]+):/;
| {
"end_byte": 683,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/style_url_resolver.ts"
} |
angular/packages/compiler/src/chars.ts_0_2476 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export const $EOF = 0;
export const $BSPACE = 8;
export const $TAB = 9;
export const $LF = 10;
export const $VTAB = 11;
export const $FF = 12;
export const $CR = 13;
export const $SPACE = 32;
export const $BANG = 33;
export const $DQ = 34;
export const $HASH = 35;
export const $$ = 36;
export const $PERCENT = 37;
export const $AMPERSAND = 38;
export const $SQ = 39;
export const $LPAREN = 40;
export const $RPAREN = 41;
export const $STAR = 42;
export const $PLUS = 43;
export const $COMMA = 44;
export const $MINUS = 45;
export const $PERIOD = 46;
export const $SLASH = 47;
export const $COLON = 58;
export const $SEMICOLON = 59;
export const $LT = 60;
export const $EQ = 61;
export const $GT = 62;
export const $QUESTION = 63;
export const $0 = 48;
export const $7 = 55;
export const $9 = 57;
export const $A = 65;
export const $E = 69;
export const $F = 70;
export const $X = 88;
export const $Z = 90;
export const $LBRACKET = 91;
export const $BACKSLASH = 92;
export const $RBRACKET = 93;
export const $CARET = 94;
export const $_ = 95;
export const $a = 97;
export const $b = 98;
export const $e = 101;
export const $f = 102;
export const $n = 110;
export const $r = 114;
export const $t = 116;
export const $u = 117;
export const $v = 118;
export const $x = 120;
export const $z = 122;
export const $LBRACE = 123;
export const $BAR = 124;
export const $RBRACE = 125;
export const $NBSP = 160;
export const $PIPE = 124;
export const $TILDA = 126;
export const $AT = 64;
export const $BT = 96;
export function isWhitespace(code: number): boolean {
return (code >= $TAB && code <= $SPACE) || code == $NBSP;
}
export function isDigit(code: number): boolean {
return $0 <= code && code <= $9;
}
export function isAsciiLetter(code: number): boolean {
return (code >= $a && code <= $z) || (code >= $A && code <= $Z);
}
export function isAsciiHexDigit(code: number): boolean {
return (code >= $a && code <= $f) || (code >= $A && code <= $F) || isDigit(code);
}
export function isNewLine(code: number): boolean {
return code === $LF || code === $CR;
}
export function isOctalDigit(code: number): boolean {
return $0 <= code && code <= $7;
}
export function isQuote(code: number): boolean {
return code === $SQ || code === $DQ || code === $BT;
}
| {
"end_byte": 2476,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/chars.ts"
} |
angular/packages/compiler/src/resource_loader.ts_0_506 | /**
* @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
*/
/**
* An interface for retrieving documents by URL that the compiler uses to
* load templates.
*
* This is an abstract class, rather than an interface, so that it can be used
* as injection token.
*/
export abstract class ResourceLoader {
abstract get(url: string): Promise<string> | string;
}
| {
"end_byte": 506,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/resource_loader.ts"
} |
angular/packages/compiler/src/assertions.ts_0_1030 | /**
* @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
*/
const UNUSABLE_INTERPOLATION_REGEXPS = [
/@/, // control flow reserved symbol
/^\s*$/, // empty
/[<>]/, // html tag
/^[{}]$/, // i18n expansion
/&(#|[a-z])/i, // character reference,
/^\/\//, // comment
];
export function assertInterpolationSymbols(identifier: string, value: any): void {
if (value != null && !(Array.isArray(value) && value.length == 2)) {
throw new Error(`Expected '${identifier}' to be an array, [start, end].`);
} else if (value != null) {
const start = value[0] as string;
const end = value[1] as string;
// Check for unusable interpolation symbols
UNUSABLE_INTERPOLATION_REGEXPS.forEach((regexp) => {
if (regexp.test(start) || regexp.test(end)) {
throw new Error(`['${start}', '${end}'] contains unusable interpolation symbol.`);
}
});
}
}
| {
"end_byte": 1030,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/assertions.ts"
} |
angular/packages/compiler/src/constant_pool.ts_0_2765 | /**
* @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 CONSTANT_PREFIX = '_c';
/**
* `ConstantPool` tries to reuse literal factories when two or more literals are identical.
* We determine whether literals are identical by creating a key out of their AST using the
* `KeyVisitor`. This constant is used to replace dynamic expressions which can't be safely
* converted into a key. E.g. given an expression `{foo: bar()}`, since we don't know what
* the result of `bar` will be, we create a key that looks like `{foo: <unknown>}`. Note
* that we use a variable, rather than something like `null` in order to avoid collisions.
*/
const UNKNOWN_VALUE_KEY = o.variable('<unknown>');
/**
* Context to use when producing a key.
*
* This ensures we see the constant not the reference variable when producing
* a key.
*/
const KEY_CONTEXT = {};
/**
* Generally all primitive values are excluded from the `ConstantPool`, but there is an exclusion
* for strings that reach a certain length threshold. This constant defines the length threshold for
* strings.
*/
const POOL_INCLUSION_LENGTH_THRESHOLD_FOR_STRINGS = 50;
/**
* A node that is a place-holder that allows the node to be replaced when the actual
* node is known.
*
* This allows the constant pool to change an expression from a direct reference to
* a constant to a shared constant. It returns a fix-up node that is later allowed to
* change the referenced expression.
*/
class FixupExpression extends o.Expression {
private original: o.Expression;
shared = false;
constructor(public resolved: o.Expression) {
super(resolved.type);
this.original = resolved;
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): any {
if (context === KEY_CONTEXT) {
// When producing a key we want to traverse the constant not the
// variable used to refer to it.
return this.original.visitExpression(visitor, context);
} else {
return this.resolved.visitExpression(visitor, context);
}
}
override isEquivalent(e: o.Expression): boolean {
return e instanceof FixupExpression && this.resolved.isEquivalent(e.resolved);
}
override isConstant() {
return true;
}
override clone(): FixupExpression {
throw new Error(`Not supported.`);
}
fixup(expression: o.Expression) {
this.resolved = expression;
this.shared = true;
}
}
/**
* A constant pool allows a code emitter to share constant in an output context.
*
* The constant pool also supports sharing access to ivy definitions references.
*/ | {
"end_byte": 2765,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/constant_pool.ts"
} |
angular/packages/compiler/src/constant_pool.ts_2766_10877 | export class ConstantPool {
statements: o.Statement[] = [];
private literals = new Map<string, FixupExpression>();
private literalFactories = new Map<string, o.Expression>();
private sharedConstants = new Map<string, o.Expression>();
/**
* Constant pool also tracks claimed names from {@link uniqueName}.
* This is useful to avoid collisions if variables are intended to be
* named a certain way- but may conflict. We wouldn't want to always suffix
* them with unique numbers.
*/
private _claimedNames = new Map<string, number>();
private nextNameIndex = 0;
constructor(private readonly isClosureCompilerEnabled: boolean = false) {}
getConstLiteral(literal: o.Expression, forceShared?: boolean): o.Expression {
if (
(literal instanceof o.LiteralExpr && !isLongStringLiteral(literal)) ||
literal instanceof FixupExpression
) {
// Do no put simple literals into the constant pool or try to produce a constant for a
// reference to a constant.
return literal;
}
const key = GenericKeyFn.INSTANCE.keyOf(literal);
let fixup = this.literals.get(key);
let newValue = false;
if (!fixup) {
fixup = new FixupExpression(literal);
this.literals.set(key, fixup);
newValue = true;
}
if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
// Replace the expression with a variable
const name = this.freshName();
let definition: o.WriteVarExpr;
let usage: o.Expression;
if (this.isClosureCompilerEnabled && isLongStringLiteral(literal)) {
// For string literals, Closure will **always** inline the string at
// **all** usages, duplicating it each time. For large strings, this
// unnecessarily bloats bundle size. To work around this restriction, we
// wrap the string in a function, and call that function for each usage.
// This tricks Closure into using inline logic for functions instead of
// string literals. Function calls are only inlined if the body is small
// enough to be worth it. By doing this, very large strings will be
// shared across multiple usages, rather than duplicating the string at
// each usage site.
//
// const myStr = function() { return "very very very long string"; };
// const usage1 = myStr();
// const usage2 = myStr();
definition = o.variable(name).set(
new o.FunctionExpr(
[], // Params.
[
// Statements.
new o.ReturnStatement(literal),
],
),
);
usage = o.variable(name).callFn([]);
} else {
// Just declare and use the variable directly, without a function call
// indirection. This saves a few bytes and avoids an unnecessary call.
definition = o.variable(name).set(literal);
usage = o.variable(name);
}
this.statements.push(definition.toDeclStmt(o.INFERRED_TYPE, o.StmtModifier.Final));
fixup.fixup(usage);
}
return fixup;
}
getSharedConstant(def: SharedConstantDefinition, expr: o.Expression): o.Expression {
const key = def.keyOf(expr);
if (!this.sharedConstants.has(key)) {
const id = this.freshName();
this.sharedConstants.set(key, o.variable(id));
this.statements.push(def.toSharedConstantDeclaration(id, expr));
}
return this.sharedConstants.get(key)!;
}
getLiteralFactory(literal: o.LiteralArrayExpr | o.LiteralMapExpr): {
literalFactory: o.Expression;
literalFactoryArguments: o.Expression[];
} {
// Create a pure function that builds an array of a mix of constant and variable expressions
if (literal instanceof o.LiteralArrayExpr) {
const argumentsForKey = literal.entries.map((e) => (e.isConstant() ? e : UNKNOWN_VALUE_KEY));
const key = GenericKeyFn.INSTANCE.keyOf(o.literalArr(argumentsForKey));
return this._getLiteralFactory(key, literal.entries, (entries) => o.literalArr(entries));
} else {
const expressionForKey = o.literalMap(
literal.entries.map((e) => ({
key: e.key,
value: e.value.isConstant() ? e.value : UNKNOWN_VALUE_KEY,
quoted: e.quoted,
})),
);
const key = GenericKeyFn.INSTANCE.keyOf(expressionForKey);
return this._getLiteralFactory(
key,
literal.entries.map((e) => e.value),
(entries) =>
o.literalMap(
entries.map((value, index) => ({
key: literal.entries[index].key,
value,
quoted: literal.entries[index].quoted,
})),
),
);
}
}
// TODO: useUniqueName(false) is necessary for naming compatibility with
// TemplateDefinitionBuilder, but should be removed once Template Pipeline is the default.
getSharedFunctionReference(
fn: o.Expression,
prefix: string,
useUniqueName: boolean = true,
): o.Expression {
const isArrow = fn instanceof o.ArrowFunctionExpr;
for (const current of this.statements) {
// Arrow functions are saved as variables so we check if the
// value of the variable is the same as the arrow function.
if (isArrow && current instanceof o.DeclareVarStmt && current.value?.isEquivalent(fn)) {
return o.variable(current.name);
}
// Function declarations are saved as function statements
// so we compare them directly to the passed-in function.
if (
!isArrow &&
current instanceof o.DeclareFunctionStmt &&
fn instanceof o.FunctionExpr &&
fn.isEquivalent(current)
) {
return o.variable(current.name);
}
}
// Otherwise declare the function.
const name = useUniqueName ? this.uniqueName(prefix) : prefix;
this.statements.push(
fn instanceof o.FunctionExpr
? fn.toDeclStmt(name, o.StmtModifier.Final)
: new o.DeclareVarStmt(name, fn, o.INFERRED_TYPE, o.StmtModifier.Final, fn.sourceSpan),
);
return o.variable(name);
}
private _getLiteralFactory(
key: string,
values: o.Expression[],
resultMap: (parameters: o.Expression[]) => o.Expression,
): {literalFactory: o.Expression; literalFactoryArguments: o.Expression[]} {
let literalFactory = this.literalFactories.get(key);
const literalFactoryArguments = values.filter((e) => !e.isConstant());
if (!literalFactory) {
const resultExpressions = values.map((e, index) =>
e.isConstant() ? this.getConstLiteral(e, true) : o.variable(`a${index}`),
);
const parameters = resultExpressions
.filter(isVariable)
.map((e) => new o.FnParam(e.name!, o.DYNAMIC_TYPE));
const pureFunctionDeclaration = o.arrowFn(
parameters,
resultMap(resultExpressions),
o.INFERRED_TYPE,
);
const name = this.freshName();
this.statements.push(
o
.variable(name)
.set(pureFunctionDeclaration)
.toDeclStmt(o.INFERRED_TYPE, o.StmtModifier.Final),
);
literalFactory = o.variable(name);
this.literalFactories.set(key, literalFactory);
}
return {literalFactory, literalFactoryArguments};
}
/**
* Produce a unique name in the context of this pool.
*
* The name might be unique among different prefixes if any of the prefixes end in
* a digit so the prefix should be a constant string (not based on user input) and
* must not end in a digit.
*/
uniqueName(name: string, alwaysIncludeSuffix = true): string {
const count = this._claimedNames.get(name) ?? 0;
const result = count === 0 && !alwaysIncludeSuffix ? `${name}` : `${name}${count}`;
this._claimedNames.set(name, count + 1);
return result;
}
private freshName(): string {
return this.uniqueName(CONSTANT_PREFIX);
}
}
export interface ExpressionKeyFn {
keyOf(expr: o.Expression): string;
}
export interface SharedConstantDefinition extends ExpressionKeyFn {
toSharedConstantDeclaration(declName: string, keyExpr: o.Expression): o.Statement;
} | {
"end_byte": 10877,
"start_byte": 2766,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/constant_pool.ts"
} |
angular/packages/compiler/src/constant_pool.ts_10879_12533 | export class GenericKeyFn implements ExpressionKeyFn {
static readonly INSTANCE = new GenericKeyFn();
keyOf(expr: o.Expression): string {
if (expr instanceof o.LiteralExpr && typeof expr.value === 'string') {
return `"${expr.value}"`;
} else if (expr instanceof o.LiteralExpr) {
return String(expr.value);
} else if (expr instanceof o.LiteralArrayExpr) {
const entries: string[] = [];
for (const entry of expr.entries) {
entries.push(this.keyOf(entry));
}
return `[${entries.join(',')}]`;
} else if (expr instanceof o.LiteralMapExpr) {
const entries: string[] = [];
for (const entry of expr.entries) {
let key = entry.key;
if (entry.quoted) {
key = `"${key}"`;
}
entries.push(key + ':' + this.keyOf(entry.value));
}
return `{${entries.join(',')}}`;
} else if (expr instanceof o.ExternalExpr) {
return `import("${expr.value.moduleName}", ${expr.value.name})`;
} else if (expr instanceof o.ReadVarExpr) {
return `read(${expr.name})`;
} else if (expr instanceof o.TypeofExpr) {
return `typeof(${this.keyOf(expr.expr)})`;
} else {
throw new Error(
`${this.constructor.name} does not handle expressions of type ${expr.constructor.name}`,
);
}
}
}
function isVariable(e: o.Expression): e is o.ReadVarExpr {
return e instanceof o.ReadVarExpr;
}
function isLongStringLiteral(expr: o.Expression): boolean {
return (
expr instanceof o.LiteralExpr &&
typeof expr.value === 'string' &&
expr.value.length >= POOL_INCLUSION_LENGTH_THRESHOLD_FOR_STRINGS
);
} | {
"end_byte": 12533,
"start_byte": 10879,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/constant_pool.ts"
} |
angular/packages/compiler/src/core.ts_0_5945 | /**
* @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
*/
// Attention:
// This file duplicates types and values from @angular/core
// so that we are able to make @angular/compiler independent of @angular/core.
// This is important to prevent a build cycle, as @angular/core needs to
// be compiled with the compiler.
import {CssSelector} from './selector';
// Stores the default value of `emitDistinctChangesOnly` when the `emitDistinctChangesOnly` is not
// explicitly set.
export const emitDistinctChangesOnlyDefaultValue = true;
export enum ViewEncapsulation {
Emulated = 0,
// Historically the 1 value was for `Native` encapsulation which has been removed as of v11.
None = 2,
ShadowDom = 3,
}
export enum ChangeDetectionStrategy {
OnPush = 0,
Default = 1,
}
export interface Input {
alias?: string;
required?: boolean;
transform?: (value: any) => any;
// Note: This field is marked as `internal` in `@angular/core`, but in the compiler
// we rely on it for JIT processing at runtime.
isSignal: boolean;
}
/** Flags describing an input for a directive. */
export enum InputFlags {
None = 0,
SignalBased = 1 << 0,
HasDecoratorInputTransform = 1 << 1,
}
export interface Output {
alias?: string;
}
export interface HostBinding {
hostPropertyName?: string;
}
export interface HostListener {
eventName?: string;
args?: string[];
}
export interface SchemaMetadata {
name: string;
}
export const CUSTOM_ELEMENTS_SCHEMA: SchemaMetadata = {
name: 'custom-elements',
};
export const NO_ERRORS_SCHEMA: SchemaMetadata = {
name: 'no-errors-schema',
};
export interface Type extends Function {
new (...args: any[]): any;
}
export const Type = Function;
export enum SecurityContext {
NONE = 0,
HTML = 1,
STYLE = 2,
SCRIPT = 3,
URL = 4,
RESOURCE_URL = 5,
}
/**
* Injection flags for DI.
*/
export const enum InjectFlags {
Default = 0,
/**
* Specifies that an injector should retrieve a dependency from any injector until reaching the
* host element of the current component. (Only used with Element Injector)
*/
Host = 1 << 0,
/** Don't descend into ancestors of the node requesting injection. */
Self = 1 << 1,
/** Skip the node that is requesting injection. */
SkipSelf = 1 << 2,
/** Inject `defaultValue` instead if token not found. */
Optional = 1 << 3,
/**
* This token is being injected into a pipe.
* @internal
*/
ForPipe = 1 << 4,
}
export enum MissingTranslationStrategy {
Error = 0,
Warning = 1,
Ignore = 2,
}
/**
* Flags used to generate R3-style CSS Selectors. They are pasted from
* core/src/render3/projection.ts because they cannot be referenced directly.
*/
export const enum SelectorFlags {
/** Indicates this is the beginning of a new negative selector */
NOT = 0b0001,
/** Mode for matching attributes */
ATTRIBUTE = 0b0010,
/** Mode for matching tag names */
ELEMENT = 0b0100,
/** Mode for matching class names */
CLASS = 0b1000,
}
// These are a copy the CSS types from core/src/render3/interfaces/projection.ts
// They are duplicated here as they cannot be directly referenced from core.
export type R3CssSelector = (string | SelectorFlags)[];
export type R3CssSelectorList = R3CssSelector[];
function parserSelectorToSimpleSelector(selector: CssSelector): R3CssSelector {
const classes =
selector.classNames && selector.classNames.length
? [SelectorFlags.CLASS, ...selector.classNames]
: [];
const elementName = selector.element && selector.element !== '*' ? selector.element : '';
return [elementName, ...selector.attrs, ...classes];
}
function parserSelectorToNegativeSelector(selector: CssSelector): R3CssSelector {
const classes =
selector.classNames && selector.classNames.length
? [SelectorFlags.CLASS, ...selector.classNames]
: [];
if (selector.element) {
return [
SelectorFlags.NOT | SelectorFlags.ELEMENT,
selector.element,
...selector.attrs,
...classes,
];
} else if (selector.attrs.length) {
return [SelectorFlags.NOT | SelectorFlags.ATTRIBUTE, ...selector.attrs, ...classes];
} else {
return selector.classNames && selector.classNames.length
? [SelectorFlags.NOT | SelectorFlags.CLASS, ...selector.classNames]
: [];
}
}
function parserSelectorToR3Selector(selector: CssSelector): R3CssSelector {
const positive = parserSelectorToSimpleSelector(selector);
const negative: R3CssSelectorList =
selector.notSelectors && selector.notSelectors.length
? selector.notSelectors.map((notSelector) => parserSelectorToNegativeSelector(notSelector))
: [];
return positive.concat(...negative);
}
export function parseSelectorToR3Selector(selector: string | null): R3CssSelectorList {
return selector ? CssSelector.parse(selector).map(parserSelectorToR3Selector) : [];
}
// Pasted from render3/interfaces/definition since it cannot be referenced directly
/**
* Flags passed into template functions to determine which blocks (i.e. creation, update)
* should be executed.
*
* Typically, a template runs both the creation block and the update block on initialization and
* subsequent runs only execute the update block. However, dynamically created views require that
* the creation block be executed separately from the update block (for backwards compat).
*/
export const enum RenderFlags {
/* Whether to run the creation block (e.g. create elements and directives) */
Create = 0b01,
/* Whether to run the update block (e.g. refresh bindings) */
Update = 0b10,
}
// Pasted from render3/interfaces/node.ts
/**
* A set of marker values to be used in the attributes arrays. These markers indicate that some
* items are not regular attributes and the processing should be adapted accordingly.
*/ | {
"end_byte": 5945,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/core.ts"
} |
angular/packages/compiler/src/core.ts_5946_8797 | export const enum AttributeMarker {
/**
* Marker indicates that the following 3 values in the attributes array are:
* namespaceUri, attributeName, attributeValue
* in that order.
*/
NamespaceURI = 0,
/**
* Signals class declaration.
*
* Each value following `Classes` designates a class name to include on the element.
* ## Example:
*
* Given:
* ```
* <div class="foo bar baz">...<d/vi>
* ```
*
* the generated code is:
* ```
* var _c1 = [AttributeMarker.Classes, 'foo', 'bar', 'baz'];
* ```
*/
Classes = 1,
/**
* Signals style declaration.
*
* Each pair of values following `Styles` designates a style name and value to include on the
* element.
* ## Example:
*
* Given:
* ```
* <div style="width:100px; height:200px; color:red">...</div>
* ```
*
* the generated code is:
* ```
* var _c1 = [AttributeMarker.Styles, 'width', '100px', 'height'. '200px', 'color', 'red'];
* ```
*/
Styles = 2,
/**
* Signals that the following attribute names were extracted from input or output bindings.
*
* For example, given the following HTML:
*
* ```
* <div moo="car" [foo]="exp" (bar)="doSth()">
* ```
*
* the generated code is:
*
* ```
* var _c1 = ['moo', 'car', AttributeMarker.Bindings, 'foo', 'bar'];
* ```
*/
Bindings = 3,
/**
* Signals that the following attribute names were hoisted from an inline-template declaration.
*
* For example, given the following HTML:
*
* ```
* <div *ngFor="let value of values; trackBy:trackBy" dirA [dirB]="value">
* ```
*
* the generated code for the `template()` instruction would include:
*
* ```
* ['dirA', '', AttributeMarker.Bindings, 'dirB', AttributeMarker.Template, 'ngFor', 'ngForOf',
* 'ngForTrackBy', 'let-value']
* ```
*
* while the generated code for the `element()` instruction inside the template function would
* include:
*
* ```
* ['dirA', '', AttributeMarker.Bindings, 'dirB']
* ```
*/
Template = 4,
/**
* Signals that the following attribute is `ngProjectAs` and its value is a parsed `CssSelector`.
*
* For example, given the following HTML:
*
* ```
* <h1 attr="value" ngProjectAs="[title]">
* ```
*
* the generated code for the `element()` instruction would include:
*
* ```
* ['attr', 'value', AttributeMarker.ProjectAs, ['', 'title', '']]
* ```
*/
ProjectAs = 5,
/**
* Signals that the following attribute will be translated by runtime i18n
*
* For example, given the following HTML:
*
* ```
* <div moo="car" foo="value" i18n-foo [bar]="binding" i18n-bar>
* ```
*
* the generated code is:
*
* ```
* var _c1 = ['moo', 'car', AttributeMarker.I18n, 'foo', 'bar'];
*/
I18n = 6,
} | {
"end_byte": 8797,
"start_byte": 5946,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/core.ts"
} |
angular/packages/compiler/src/selector.ts_0_6277 | /**
* @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
*/
const _SELECTOR_REGEXP = new RegExp(
'(\\:not\\()|' + // 1: ":not("
'(([\\.\\#]?)[-\\w]+)|' + // 2: "tag"; 3: "."/"#";
// "-" should appear first in the regexp below as FF31 parses "[.-\w]" as a range
// 4: attribute; 5: attribute_string; 6: attribute_value
'(?:\\[([-.\\w*\\\\$]+)(?:=(["\']?)([^\\]"\']*)\\5)?\\])|' + // "[name]", "[name=value]",
// "[name="value"]",
// "[name='value']"
'(\\))|' + // 7: ")"
'(\\s*,\\s*)', // 8: ","
'g',
);
/**
* These offsets should match the match-groups in `_SELECTOR_REGEXP` offsets.
*/
const enum SelectorRegexp {
ALL = 0, // The whole match
NOT = 1,
TAG = 2,
PREFIX = 3,
ATTRIBUTE = 4,
ATTRIBUTE_STRING = 5,
ATTRIBUTE_VALUE = 6,
NOT_END = 7,
SEPARATOR = 8,
}
/**
* A css selector contains an element name,
* css classes and attribute/value pairs with the purpose
* of selecting subsets out of them.
*/
export class CssSelector {
element: string | null = null;
classNames: string[] = [];
/**
* The selectors are encoded in pairs where:
* - even locations are attribute names
* - odd locations are attribute values.
*
* Example:
* Selector: `[key1=value1][key2]` would parse to:
* ```
* ['key1', 'value1', 'key2', '']
* ```
*/
attrs: string[] = [];
notSelectors: CssSelector[] = [];
static parse(selector: string): CssSelector[] {
const results: CssSelector[] = [];
const _addResult = (res: CssSelector[], cssSel: CssSelector) => {
if (
cssSel.notSelectors.length > 0 &&
!cssSel.element &&
cssSel.classNames.length == 0 &&
cssSel.attrs.length == 0
) {
cssSel.element = '*';
}
res.push(cssSel);
};
let cssSelector = new CssSelector();
let match: string[] | null;
let current = cssSelector;
let inNot = false;
_SELECTOR_REGEXP.lastIndex = 0;
while ((match = _SELECTOR_REGEXP.exec(selector))) {
if (match[SelectorRegexp.NOT]) {
if (inNot) {
throw new Error('Nesting :not in a selector is not allowed');
}
inNot = true;
current = new CssSelector();
cssSelector.notSelectors.push(current);
}
const tag = match[SelectorRegexp.TAG];
if (tag) {
const prefix = match[SelectorRegexp.PREFIX];
if (prefix === '#') {
// #hash
current.addAttribute('id', tag.slice(1));
} else if (prefix === '.') {
// Class
current.addClassName(tag.slice(1));
} else {
// Element
current.setElement(tag);
}
}
const attribute = match[SelectorRegexp.ATTRIBUTE];
if (attribute) {
current.addAttribute(
current.unescapeAttribute(attribute),
match[SelectorRegexp.ATTRIBUTE_VALUE],
);
}
if (match[SelectorRegexp.NOT_END]) {
inNot = false;
current = cssSelector;
}
if (match[SelectorRegexp.SEPARATOR]) {
if (inNot) {
throw new Error('Multiple selectors in :not are not supported');
}
_addResult(results, cssSelector);
cssSelector = current = new CssSelector();
}
}
_addResult(results, cssSelector);
return results;
}
/**
* Unescape `\$` sequences from the CSS attribute selector.
*
* This is needed because `$` can have a special meaning in CSS selectors,
* but we might want to match an attribute that contains `$`.
* [MDN web link for more
* info](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors).
* @param attr the attribute to unescape.
* @returns the unescaped string.
*/
unescapeAttribute(attr: string): string {
let result = '';
let escaping = false;
for (let i = 0; i < attr.length; i++) {
const char = attr.charAt(i);
if (char === '\\') {
escaping = true;
continue;
}
if (char === '$' && !escaping) {
throw new Error(
`Error in attribute selector "${attr}". ` +
`Unescaped "$" is not supported. Please escape with "\\$".`,
);
}
escaping = false;
result += char;
}
return result;
}
/**
* Escape `$` sequences from the CSS attribute selector.
*
* This is needed because `$` can have a special meaning in CSS selectors,
* with this method we are escaping `$` with `\$'.
* [MDN web link for more
* info](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors).
* @param attr the attribute to escape.
* @returns the escaped string.
*/
escapeAttribute(attr: string): string {
return attr.replace(/\\/g, '\\\\').replace(/\$/g, '\\$');
}
isElementSelector(): boolean {
return (
this.hasElementSelector() &&
this.classNames.length == 0 &&
this.attrs.length == 0 &&
this.notSelectors.length === 0
);
}
hasElementSelector(): boolean {
return !!this.element;
}
setElement(element: string | null = null) {
this.element = element;
}
getAttrs(): string[] {
const result: string[] = [];
if (this.classNames.length > 0) {
result.push('class', this.classNames.join(' '));
}
return result.concat(this.attrs);
}
addAttribute(name: string, value: string = '') {
this.attrs.push(name, (value && value.toLowerCase()) || '');
}
addClassName(name: string) {
this.classNames.push(name.toLowerCase());
}
toString(): string {
let res: string = this.element || '';
if (this.classNames) {
this.classNames.forEach((klass) => (res += `.${klass}`));
}
if (this.attrs) {
for (let i = 0; i < this.attrs.length; i += 2) {
const name = this.escapeAttribute(this.attrs[i]);
const value = this.attrs[i + 1];
res += `[${name}${value ? '=' + value : ''}]`;
}
}
this.notSelectors.forEach((notSelector) => (res += `:not(${notSelector})`));
return res;
}
}
/**
* Reads a list of CssSelectors and allows to calculate which ones
* are contained in a given CssSelector.
*/ | {
"end_byte": 6277,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/selector.ts"
} |
angular/packages/compiler/src/selector.ts_6278_13945 | export class SelectorMatcher<T = any> {
static createNotMatcher(notSelectors: CssSelector[]): SelectorMatcher<null> {
const notMatcher = new SelectorMatcher<null>();
notMatcher.addSelectables(notSelectors, null);
return notMatcher;
}
private _elementMap = new Map<string, SelectorContext<T>[]>();
private _elementPartialMap = new Map<string, SelectorMatcher<T>>();
private _classMap = new Map<string, SelectorContext<T>[]>();
private _classPartialMap = new Map<string, SelectorMatcher<T>>();
private _attrValueMap = new Map<string, Map<string, SelectorContext<T>[]>>();
private _attrValuePartialMap = new Map<string, Map<string, SelectorMatcher<T>>>();
private _listContexts: SelectorListContext[] = [];
addSelectables(cssSelectors: CssSelector[], callbackCtxt?: T) {
let listContext: SelectorListContext = null!;
if (cssSelectors.length > 1) {
listContext = new SelectorListContext(cssSelectors);
this._listContexts.push(listContext);
}
for (let i = 0; i < cssSelectors.length; i++) {
this._addSelectable(cssSelectors[i], callbackCtxt as T, listContext);
}
}
/**
* Add an object that can be found later on by calling `match`.
* @param cssSelector A css selector
* @param callbackCtxt An opaque object that will be given to the callback of the `match` function
*/
private _addSelectable(
cssSelector: CssSelector,
callbackCtxt: T,
listContext: SelectorListContext,
) {
let matcher: SelectorMatcher<T> = this;
const element = cssSelector.element;
const classNames = cssSelector.classNames;
const attrs = cssSelector.attrs;
const selectable = new SelectorContext(cssSelector, callbackCtxt, listContext);
if (element) {
const isTerminal = attrs.length === 0 && classNames.length === 0;
if (isTerminal) {
this._addTerminal(matcher._elementMap, element, selectable);
} else {
matcher = this._addPartial(matcher._elementPartialMap, element);
}
}
if (classNames) {
for (let i = 0; i < classNames.length; i++) {
const isTerminal = attrs.length === 0 && i === classNames.length - 1;
const className = classNames[i];
if (isTerminal) {
this._addTerminal(matcher._classMap, className, selectable);
} else {
matcher = this._addPartial(matcher._classPartialMap, className);
}
}
}
if (attrs) {
for (let i = 0; i < attrs.length; i += 2) {
const isTerminal = i === attrs.length - 2;
const name = attrs[i];
const value = attrs[i + 1];
if (isTerminal) {
const terminalMap = matcher._attrValueMap;
let terminalValuesMap = terminalMap.get(name);
if (!terminalValuesMap) {
terminalValuesMap = new Map<string, SelectorContext<T>[]>();
terminalMap.set(name, terminalValuesMap);
}
this._addTerminal(terminalValuesMap, value, selectable);
} else {
const partialMap = matcher._attrValuePartialMap;
let partialValuesMap = partialMap.get(name);
if (!partialValuesMap) {
partialValuesMap = new Map<string, SelectorMatcher<T>>();
partialMap.set(name, partialValuesMap);
}
matcher = this._addPartial(partialValuesMap, value);
}
}
}
}
private _addTerminal(
map: Map<string, SelectorContext<T>[]>,
name: string,
selectable: SelectorContext<T>,
) {
let terminalList = map.get(name);
if (!terminalList) {
terminalList = [];
map.set(name, terminalList);
}
terminalList.push(selectable);
}
private _addPartial(map: Map<string, SelectorMatcher<T>>, name: string): SelectorMatcher<T> {
let matcher = map.get(name);
if (!matcher) {
matcher = new SelectorMatcher<T>();
map.set(name, matcher);
}
return matcher;
}
/**
* Find the objects that have been added via `addSelectable`
* whose css selector is contained in the given css selector.
* @param cssSelector A css selector
* @param matchedCallback This callback will be called with the object handed into `addSelectable`
* @return boolean true if a match was found
*/
match(
cssSelector: CssSelector,
matchedCallback: ((c: CssSelector, a: T) => void) | null,
): boolean {
let result = false;
const element = cssSelector.element!;
const classNames = cssSelector.classNames;
const attrs = cssSelector.attrs;
for (let i = 0; i < this._listContexts.length; i++) {
this._listContexts[i].alreadyMatched = false;
}
result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result;
result =
this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) || result;
if (classNames) {
for (let i = 0; i < classNames.length; i++) {
const className = classNames[i];
result =
this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result;
result =
this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) ||
result;
}
}
if (attrs) {
for (let i = 0; i < attrs.length; i += 2) {
const name = attrs[i];
const value = attrs[i + 1];
const terminalValuesMap = this._attrValueMap.get(name)!;
if (value) {
result =
this._matchTerminal(terminalValuesMap, '', cssSelector, matchedCallback) || result;
}
result =
this._matchTerminal(terminalValuesMap, value, cssSelector, matchedCallback) || result;
const partialValuesMap = this._attrValuePartialMap.get(name)!;
if (value) {
result = this._matchPartial(partialValuesMap, '', cssSelector, matchedCallback) || result;
}
result =
this._matchPartial(partialValuesMap, value, cssSelector, matchedCallback) || result;
}
}
return result;
}
/** @internal */
_matchTerminal(
map: Map<string, SelectorContext<T>[]>,
name: string,
cssSelector: CssSelector,
matchedCallback: ((c: CssSelector, a: any) => void) | null,
): boolean {
if (!map || typeof name !== 'string') {
return false;
}
let selectables: SelectorContext<T>[] = map.get(name) || [];
const starSelectables: SelectorContext<T>[] = map.get('*')!;
if (starSelectables) {
selectables = selectables.concat(starSelectables);
}
if (selectables.length === 0) {
return false;
}
let selectable: SelectorContext<T>;
let result = false;
for (let i = 0; i < selectables.length; i++) {
selectable = selectables[i];
result = selectable.finalize(cssSelector, matchedCallback) || result;
}
return result;
}
/** @internal */
_matchPartial(
map: Map<string, SelectorMatcher<T>>,
name: string,
cssSelector: CssSelector,
matchedCallback: ((c: CssSelector, a: any) => void) | null,
): boolean {
if (!map || typeof name !== 'string') {
return false;
}
const nestedSelector = map.get(name);
if (!nestedSelector) {
return false;
}
// TODO(perf): get rid of recursion and measure again
// TODO(perf): don't pass the whole selector into the recursion,
// but only the not processed parts
return nestedSelector.match(cssSelector, matchedCallback);
}
}
export class SelectorListContext {
alreadyMatched: boolean = false;
constructor(public selectors: CssSelector[]) {}
}
// Store context to pass back selector and context when a selector is matched | {
"end_byte": 13945,
"start_byte": 6278,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/selector.ts"
} |
angular/packages/compiler/src/selector.ts_13946_14805 | export class SelectorContext<T = any> {
notSelectors: CssSelector[];
constructor(
public selector: CssSelector,
public cbContext: T,
public listContext: SelectorListContext,
) {
this.notSelectors = selector.notSelectors;
}
finalize(cssSelector: CssSelector, callback: ((c: CssSelector, a: T) => void) | null): boolean {
let result = true;
if (this.notSelectors.length > 0 && (!this.listContext || !this.listContext.alreadyMatched)) {
const notMatcher = SelectorMatcher.createNotMatcher(this.notSelectors);
result = !notMatcher.match(cssSelector, null);
}
if (result && callback && (!this.listContext || !this.listContext.alreadyMatched)) {
if (this.listContext) {
this.listContext.alreadyMatched = true;
}
callback(this.selector, this.cbContext);
}
return result;
}
} | {
"end_byte": 14805,
"start_byte": 13946,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/selector.ts"
} |
angular/packages/compiler/src/parse_util.ts_0_6440 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import * as chars from './chars';
import {stringify} from './util';
export class ParseLocation {
constructor(
public file: ParseSourceFile,
public offset: number,
public line: number,
public col: number,
) {}
toString(): string {
return this.offset != null ? `${this.file.url}@${this.line}:${this.col}` : this.file.url;
}
moveBy(delta: number): ParseLocation {
const source = this.file.content;
const len = source.length;
let offset = this.offset;
let line = this.line;
let col = this.col;
while (offset > 0 && delta < 0) {
offset--;
delta++;
const ch = source.charCodeAt(offset);
if (ch == chars.$LF) {
line--;
const priorLine = source
.substring(0, offset - 1)
.lastIndexOf(String.fromCharCode(chars.$LF));
col = priorLine > 0 ? offset - priorLine : offset;
} else {
col--;
}
}
while (offset < len && delta > 0) {
const ch = source.charCodeAt(offset);
offset++;
delta--;
if (ch == chars.$LF) {
line++;
col = 0;
} else {
col++;
}
}
return new ParseLocation(this.file, offset, line, col);
}
// Return the source around the location
// Up to `maxChars` or `maxLines` on each side of the location
getContext(maxChars: number, maxLines: number): {before: string; after: string} | null {
const content = this.file.content;
let startOffset = this.offset;
if (startOffset != null) {
if (startOffset > content.length - 1) {
startOffset = content.length - 1;
}
let endOffset = startOffset;
let ctxChars = 0;
let ctxLines = 0;
while (ctxChars < maxChars && startOffset > 0) {
startOffset--;
ctxChars++;
if (content[startOffset] == '\n') {
if (++ctxLines == maxLines) {
break;
}
}
}
ctxChars = 0;
ctxLines = 0;
while (ctxChars < maxChars && endOffset < content.length - 1) {
endOffset++;
ctxChars++;
if (content[endOffset] == '\n') {
if (++ctxLines == maxLines) {
break;
}
}
}
return {
before: content.substring(startOffset, this.offset),
after: content.substring(this.offset, endOffset + 1),
};
}
return null;
}
}
export class ParseSourceFile {
constructor(
public content: string,
public url: string,
) {}
}
export class ParseSourceSpan {
/**
* Create an object that holds information about spans of tokens/nodes captured during
* lexing/parsing of text.
*
* @param start
* The location of the start of the span (having skipped leading trivia).
* Skipping leading trivia makes source-spans more "user friendly", since things like HTML
* elements will appear to begin at the start of the opening tag, rather than at the start of any
* leading trivia, which could include newlines.
*
* @param end
* The location of the end of the span.
*
* @param fullStart
* The start of the token without skipping the leading trivia.
* This is used by tooling that splits tokens further, such as extracting Angular interpolations
* from text tokens. Such tooling creates new source-spans relative to the original token's
* source-span. If leading trivia characters have been skipped then the new source-spans may be
* incorrectly offset.
*
* @param details
* Additional information (such as identifier names) that should be associated with the span.
*/
constructor(
public start: ParseLocation,
public end: ParseLocation,
public fullStart: ParseLocation = start,
public details: string | null = null,
) {}
toString(): string {
return this.start.file.content.substring(this.start.offset, this.end.offset);
}
}
export enum ParseErrorLevel {
WARNING,
ERROR,
}
export class ParseError {
constructor(
public span: ParseSourceSpan,
public msg: string,
public level: ParseErrorLevel = ParseErrorLevel.ERROR,
) {}
contextualMessage(): string {
const ctx = this.span.start.getContext(100, 3);
return ctx
? `${this.msg} ("${ctx.before}[${ParseErrorLevel[this.level]} ->]${ctx.after}")`
: this.msg;
}
toString(): string {
const details = this.span.details ? `, ${this.span.details}` : '';
return `${this.contextualMessage()}: ${this.span.start}${details}`;
}
}
/**
* Generates Source Span object for a given R3 Type for JIT mode.
*
* @param kind Component or Directive.
* @param typeName name of the Component or Directive.
* @param sourceUrl reference to Component or Directive source.
* @returns instance of ParseSourceSpan that represent a given Component or Directive.
*/
export function r3JitTypeSourceSpan(
kind: string,
typeName: string,
sourceUrl: string,
): ParseSourceSpan {
const sourceFileName = `in ${kind} ${typeName} in ${sourceUrl}`;
const sourceFile = new ParseSourceFile('', sourceFileName);
return new ParseSourceSpan(
new ParseLocation(sourceFile, -1, -1, -1),
new ParseLocation(sourceFile, -1, -1, -1),
);
}
let _anonymousTypeIndex = 0;
export function identifierName(
compileIdentifier: CompileIdentifierMetadata | null | undefined,
): string | null {
if (!compileIdentifier || !compileIdentifier.reference) {
return null;
}
const ref = compileIdentifier.reference;
if (ref['__anonymousType']) {
return ref['__anonymousType'];
}
if (ref['__forward_ref__']) {
// We do not want to try to stringify a `forwardRef()` function because that would cause the
// inner function to be evaluated too early, defeating the whole point of the `forwardRef`.
return '__forward_ref__';
}
let identifier = stringify(ref);
if (identifier.indexOf('(') >= 0) {
// case: anonymous functions!
identifier = `anonymous_${_anonymousTypeIndex++}`;
ref['__anonymousType'] = identifier;
} else {
identifier = sanitizeIdentifier(identifier);
}
return identifier;
}
export interface CompileIdentifierMetadata {
reference: any;
}
export function sanitizeIdentifier(name: string): string {
return name.replace(/\W/g, '_');
}
| {
"end_byte": 6440,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/parse_util.ts"
} |
angular/packages/compiler/src/util.ts_0_4969 | /**
* @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
*/
const DASH_CASE_REGEXP = /-+([a-z0-9])/g;
export function dashCaseToCamelCase(input: string): string {
return input.replace(DASH_CASE_REGEXP, (...m: any[]) => m[1].toUpperCase());
}
export function splitAtColon(input: string, defaultValues: string[]): string[] {
return _splitAt(input, ':', defaultValues);
}
export function splitAtPeriod(input: string, defaultValues: string[]): string[] {
return _splitAt(input, '.', defaultValues);
}
function _splitAt(input: string, character: string, defaultValues: string[]): string[] {
const characterIndex = input.indexOf(character);
if (characterIndex == -1) return defaultValues;
return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()];
}
export function noUndefined<T>(val: T | undefined): T {
return val === undefined ? null! : val;
}
export function error(msg: string): never {
throw new Error(`Internal Error: ${msg}`);
}
// Escape characters that have a special meaning in Regular Expressions
export function escapeRegExp(s: string): string {
return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
export type Byte = number;
export function utf8Encode(str: string): Byte[] {
let encoded: Byte[] = [];
for (let index = 0; index < str.length; index++) {
let codePoint = str.charCodeAt(index);
// decode surrogate
// see https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
if (codePoint >= 0xd800 && codePoint <= 0xdbff && str.length > index + 1) {
const low = str.charCodeAt(index + 1);
if (low >= 0xdc00 && low <= 0xdfff) {
index++;
codePoint = ((codePoint - 0xd800) << 10) + low - 0xdc00 + 0x10000;
}
}
if (codePoint <= 0x7f) {
encoded.push(codePoint);
} else if (codePoint <= 0x7ff) {
encoded.push(((codePoint >> 6) & 0x1f) | 0xc0, (codePoint & 0x3f) | 0x80);
} else if (codePoint <= 0xffff) {
encoded.push(
(codePoint >> 12) | 0xe0,
((codePoint >> 6) & 0x3f) | 0x80,
(codePoint & 0x3f) | 0x80,
);
} else if (codePoint <= 0x1fffff) {
encoded.push(
((codePoint >> 18) & 0x07) | 0xf0,
((codePoint >> 12) & 0x3f) | 0x80,
((codePoint >> 6) & 0x3f) | 0x80,
(codePoint & 0x3f) | 0x80,
);
}
}
return encoded;
}
export function stringify(token: any): string {
if (typeof token === 'string') {
return token;
}
if (Array.isArray(token)) {
return '[' + token.map(stringify).join(', ') + ']';
}
if (token == null) {
return '' + token;
}
if (token.overriddenName) {
return `${token.overriddenName}`;
}
if (token.name) {
return `${token.name}`;
}
if (!token.toString) {
return 'object';
}
// WARNING: do not try to `JSON.stringify(token)` here
// see https://github.com/angular/angular/issues/23440
const res = token.toString();
if (res == null) {
return '' + res;
}
const newLineIndex = res.indexOf('\n');
return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
}
export class Version {
public readonly major: string;
public readonly minor: string;
public readonly patch: string;
constructor(public full: string) {
const splits = full.split('.');
this.major = splits[0];
this.minor = splits[1];
this.patch = splits.slice(2).join('.');
}
}
export interface Console {
log(message: string): void;
warn(message: string): void;
}
const _global: {[name: string]: any} = globalThis;
export {_global as global};
export function newArray<T = any>(size: number): T[];
export function newArray<T>(size: number, value: T): T[];
export function newArray<T>(size: number, value?: T): T[] {
const list: T[] = [];
for (let i = 0; i < size; i++) {
list.push(value!);
}
return list;
}
/**
* Partitions a given array into 2 arrays, based on a boolean value returned by the condition
* function.
*
* @param arr Input array that should be partitioned
* @param conditionFn Condition function that is called for each item in a given array and returns a
* boolean value.
*/
export function partitionArray<T, F = T>(
arr: (T | F)[],
conditionFn: (value: T | F) => boolean,
): [T[], F[]] {
const truthy: T[] = [];
const falsy: F[] = [];
for (const item of arr) {
(conditionFn(item) ? truthy : falsy).push(item as any);
}
return [truthy, falsy];
}
const V1_TO_18 = /^([1-9]|1[0-8])\./;
export function getJitStandaloneDefaultForVersion(version: string): boolean {
if (version.startsWith('0.')) {
// 0.0.0 is always "latest", default is true.
return true;
}
if (V1_TO_18.test(version)) {
// Angular v2 - v18 default is false.
return false;
}
// All other Angular versions (v19+) default to true.
return true;
}
| {
"end_byte": 4969,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/util.ts"
} |
angular/packages/compiler/src/shadow_css.ts_0_4751 | /**
* @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
*/
/**
* The following set contains all keywords that can be used in the animation css shorthand
* property and is used during the scoping of keyframes to make sure such keywords
* are not modified.
*/
const animationKeywords = new Set([
// global values
'inherit',
'initial',
'revert',
'unset',
// animation-direction
'alternate',
'alternate-reverse',
'normal',
'reverse',
// animation-fill-mode
'backwards',
'both',
'forwards',
'none',
// animation-play-state
'paused',
'running',
// animation-timing-function
'ease',
'ease-in',
'ease-in-out',
'ease-out',
'linear',
'step-start',
'step-end',
// `steps()` function
'end',
'jump-both',
'jump-end',
'jump-none',
'jump-start',
'start',
]);
/**
* The following array contains all of the CSS at-rule identifiers which are scoped.
*/
const scopedAtRuleIdentifiers = [
'@media',
'@supports',
'@document',
'@layer',
'@container',
'@scope',
'@starting-style',
];
/**
* The following class has its origin from a port of shadowCSS from webcomponents.js to TypeScript.
* It has since diverge in many ways to tailor Angular's needs.
*
* Source:
* https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js
*
* The original file level comment is reproduced below
*/
/*
This is a limited shim for ShadowDOM css styling.
https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#styles
The intention here is to support only the styling features which can be
relatively simply implemented. The goal is to allow users to avoid the
most obvious pitfalls and do so without compromising performance significantly.
For ShadowDOM styling that's not covered here, a set of best practices
can be provided that should allow users to accomplish more complex styling.
The following is a list of specific ShadowDOM styling features and a brief
discussion of the approach used to shim.
Shimmed features:
* :host, :host-context: ShadowDOM allows styling of the shadowRoot's host
element using the :host rule. To shim this feature, the :host styles are
reformatted and prefixed with a given scope name and promoted to a
document level stylesheet.
For example, given a scope name of .foo, a rule like this:
:host {
background: red;
}
}
becomes:
.foo {
background: red;
}
* encapsulation: Styles defined within ShadowDOM, apply only to
dom inside the ShadowDOM.
The selectors are scoped by adding an attribute selector suffix to each
simple selector that contains the host element tag name. Each element
in the element's ShadowDOM template is also given the scope attribute.
Thus, these rules match only elements that have the scope attribute.
For example, given a scope name of x-foo, a rule like this:
div {
font-weight: bold;
}
becomes:
div[x-foo] {
font-weight: bold;
}
Note that elements that are dynamically added to a scope must have the scope
selector added to them manually.
* upper/lower bound encapsulation: Styles which are defined outside a
shadowRoot should not cross the ShadowDOM boundary and should not apply
inside a shadowRoot.
This styling behavior is not emulated. Some possible ways to do this that
were rejected due to complexity and/or performance concerns include: (1) reset
every possible property for every possible selector for a given scope name;
(2) re-implement css in javascript.
As an alternative, users should make sure to use selectors
specific to the scope in which they are working.
* ::distributed: This behavior is not emulated. It's often not necessary
to style the contents of a specific insertion point and instead, descendants
of the host element can be styled selectively. Users can also create an
extra node around an insertion point and style that node's contents
via descendent selectors. For example, with a shadowRoot like this:
<style>
::content(div) {
background: red;
}
</style>
<content></content>
could become:
<style>
/ *@polyfill .content-container div * /
::content(div) {
background: red;
}
</style>
<div class="content-container">
<content></content>
</div>
Note the use of @polyfill in the comment above a ShadowDOM specific style
declaration. This is a directive to the styling shim to use the selector
in comments in lieu of the next selector when running under polyfill.
*/ | {
"end_byte": 4751,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/shadow_css.ts"
} |
angular/packages/compiler/src/shadow_css.ts_4752_11503 | export class ShadowCss {
/*
* Shim some cssText with the given selector. Returns cssText that can be included in the document
*
* The selector is the attribute added to all elements inside the host,
* The hostSelector is the attribute added to the host itself.
*/
shimCssText(cssText: string, selector: string, hostSelector: string = ''): string {
// **NOTE**: Do not strip comments as this will cause component sourcemaps to break
// due to shift in lines.
// Collect comments and replace them with a placeholder, this is done to avoid complicating
// the rule parsing RegExp and keep it safer.
const comments: string[] = [];
cssText = cssText.replace(_commentRe, (m) => {
if (m.match(_commentWithHashRe)) {
comments.push(m);
} else {
// Replace non hash comments with empty lines.
// This is done so that we do not leak any sensitive data in comments.
const newLinesMatches = m.match(_newLinesRe);
comments.push((newLinesMatches?.join('') ?? '') + '\n');
}
return COMMENT_PLACEHOLDER;
});
cssText = this._insertDirectives(cssText);
const scopedCssText = this._scopeCssText(cssText, selector, hostSelector);
// Add back comments at the original position.
let commentIdx = 0;
return scopedCssText.replace(_commentWithHashPlaceHolderRe, () => comments[commentIdx++]);
}
private _insertDirectives(cssText: string): string {
cssText = this._insertPolyfillDirectivesInCssText(cssText);
return this._insertPolyfillRulesInCssText(cssText);
}
/**
* Process styles to add scope to keyframes.
*
* Modify both the names of the keyframes defined in the component styles and also the css
* animation rules using them.
*
* Animation rules using keyframes defined elsewhere are not modified to allow for globally
* defined keyframes.
*
* For example, we convert this css:
*
* ```
* .box {
* animation: box-animation 1s forwards;
* }
*
* @keyframes box-animation {
* to {
* background-color: green;
* }
* }
* ```
*
* to this:
*
* ```
* .box {
* animation: scopeName_box-animation 1s forwards;
* }
*
* @keyframes scopeName_box-animation {
* to {
* background-color: green;
* }
* }
* ```
*
* @param cssText the component's css text that needs to be scoped.
* @param scopeSelector the component's scope selector.
*
* @returns the scoped css text.
*/
private _scopeKeyframesRelatedCss(cssText: string, scopeSelector: string): string {
const unscopedKeyframesSet = new Set<string>();
const scopedKeyframesCssText = processRules(cssText, (rule) =>
this._scopeLocalKeyframeDeclarations(rule, scopeSelector, unscopedKeyframesSet),
);
return processRules(scopedKeyframesCssText, (rule) =>
this._scopeAnimationRule(rule, scopeSelector, unscopedKeyframesSet),
);
}
/**
* Scopes local keyframes names, returning the updated css rule and it also
* adds the original keyframe name to a provided set to collect all keyframes names
* so that it can later be used to scope the animation rules.
*
* For example, it takes a rule such as:
*
* ```
* @keyframes box-animation {
* to {
* background-color: green;
* }
* }
* ```
*
* and returns:
*
* ```
* @keyframes scopeName_box-animation {
* to {
* background-color: green;
* }
* }
* ```
* and as a side effect it adds "box-animation" to the `unscopedKeyframesSet` set
*
* @param cssRule the css rule to process.
* @param scopeSelector the component's scope selector.
* @param unscopedKeyframesSet the set of unscoped keyframes names (which can be
* modified as a side effect)
*
* @returns the css rule modified with the scoped keyframes name.
*/
private _scopeLocalKeyframeDeclarations(
rule: CssRule,
scopeSelector: string,
unscopedKeyframesSet: Set<string>,
): CssRule {
return {
...rule,
selector: rule.selector.replace(
/(^@(?:-webkit-)?keyframes(?:\s+))(['"]?)(.+)\2(\s*)$/,
(_, start, quote, keyframeName, endSpaces) => {
unscopedKeyframesSet.add(unescapeQuotes(keyframeName, quote));
return `${start}${quote}${scopeSelector}_${keyframeName}${quote}${endSpaces}`;
},
),
};
}
/**
* Function used to scope a keyframes name (obtained from an animation declaration)
* using an existing set of unscopedKeyframes names to discern if the scoping needs to be
* performed (keyframes names of keyframes not defined in the component's css need not to be
* scoped).
*
* @param keyframe the keyframes name to check.
* @param scopeSelector the component's scope selector.
* @param unscopedKeyframesSet the set of unscoped keyframes names.
*
* @returns the scoped name of the keyframe, or the original name is the name need not to be
* scoped.
*/
private _scopeAnimationKeyframe(
keyframe: string,
scopeSelector: string,
unscopedKeyframesSet: ReadonlySet<string>,
): string {
return keyframe.replace(/^(\s*)(['"]?)(.+?)\2(\s*)$/, (_, spaces1, quote, name, spaces2) => {
name = `${
unscopedKeyframesSet.has(unescapeQuotes(name, quote)) ? scopeSelector + '_' : ''
}${name}`;
return `${spaces1}${quote}${name}${quote}${spaces2}`;
});
}
/**
* Regular expression used to extrapolate the possible keyframes from an
* animation declaration (with possibly multiple animation definitions)
*
* The regular expression can be divided in three parts
* - (^|\s+|,)
* captures how many (if any) leading whitespaces are present or a comma
* - (?:(?:(['"])((?:\\\\|\\\2|(?!\2).)+)\2)|(-?[A-Za-z][\w\-]*))
* captures two different possible keyframes, ones which are quoted or ones which are valid css
* indents (custom properties excluded)
* - (?=[,\s;]|$)
* simply matches the end of the possible keyframe, valid endings are: a comma, a space, a
* semicolon or the end of the string
*/
private _animationDeclarationKeyframesRe =
/(^|\s+|,)(?:(?:(['"])((?:\\\\|\\\2|(?!\2).)+)\2)|(-?[A-Za-z][\w\-]*))(?=[,\s]|$)/g;
/**
* Scope an animation rule so that the keyframes mentioned in such rule
* are scoped if defined in the component's css and left untouched otherwise.
*
* It can scope values of both the 'animation' and 'animation-name' properties.
*
* @param rule css rule to scope.
* @param scopeSelector the component's scope selector.
* @param unscopedKeyframesSet the set of unscoped keyframes names.
*
* @returns the updated css rule.
**/ | {
"end_byte": 11503,
"start_byte": 4752,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/shadow_css.ts"
} |
angular/packages/compiler/src/shadow_css.ts_11506_16862 | private _scopeAnimationRule(
rule: CssRule,
scopeSelector: string,
unscopedKeyframesSet: ReadonlySet<string>,
): CssRule {
let content = rule.content.replace(
/((?:^|\s+|;)(?:-webkit-)?animation\s*:\s*),*([^;]+)/g,
(_, start, animationDeclarations) =>
start +
animationDeclarations.replace(
this._animationDeclarationKeyframesRe,
(
original: string,
leadingSpaces: string,
quote = '',
quotedName: string,
nonQuotedName: string,
) => {
if (quotedName) {
return `${leadingSpaces}${this._scopeAnimationKeyframe(
`${quote}${quotedName}${quote}`,
scopeSelector,
unscopedKeyframesSet,
)}`;
} else {
return animationKeywords.has(nonQuotedName)
? original
: `${leadingSpaces}${this._scopeAnimationKeyframe(
nonQuotedName,
scopeSelector,
unscopedKeyframesSet,
)}`;
}
},
),
);
content = content.replace(
/((?:^|\s+|;)(?:-webkit-)?animation-name(?:\s*):(?:\s*))([^;]+)/g,
(_match, start, commaSeparatedKeyframes) =>
`${start}${commaSeparatedKeyframes
.split(',')
.map((keyframe: string) =>
this._scopeAnimationKeyframe(keyframe, scopeSelector, unscopedKeyframesSet),
)
.join(',')}`,
);
return {...rule, content};
}
/*
* Process styles to convert native ShadowDOM rules that will trip
* up the css parser; we rely on decorating the stylesheet with inert rules.
*
* For example, we convert this rule:
*
* polyfill-next-selector { content: ':host menu-item'; }
* ::content menu-item {
*
* to this:
*
* scopeName menu-item {
*
**/
private _insertPolyfillDirectivesInCssText(cssText: string): string {
return cssText.replace(_cssContentNextSelectorRe, function (...m: string[]) {
return m[2] + '{';
});
}
/*
* Process styles to add rules which will only apply under the polyfill
*
* For example, we convert this rule:
*
* polyfill-rule {
* content: ':host menu-item';
* ...
* }
*
* to this:
*
* scopeName menu-item {...}
*
**/
private _insertPolyfillRulesInCssText(cssText: string): string {
return cssText.replace(_cssContentRuleRe, (...m: string[]) => {
const rule = m[0].replace(m[1], '').replace(m[2], '');
return m[4] + rule;
});
}
/* Ensure styles are scoped. Pseudo-scoping takes a rule like:
*
* .foo {... }
*
* and converts this to
*
* scopeName .foo { ... }
*/
private _scopeCssText(cssText: string, scopeSelector: string, hostSelector: string): string {
const unscopedRules = this._extractUnscopedRulesFromCssText(cssText);
// replace :host and :host-context with -shadowcsshost and -shadowcsshostcontext respectively
cssText = this._insertPolyfillHostInCssText(cssText);
cssText = this._convertColonHost(cssText);
cssText = this._convertColonHostContext(cssText);
cssText = this._convertShadowDOMSelectors(cssText);
if (scopeSelector) {
cssText = this._scopeKeyframesRelatedCss(cssText, scopeSelector);
cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector);
}
cssText = cssText + '\n' + unscopedRules;
return cssText.trim();
}
/*
* Process styles to add rules which will only apply under the polyfill
* and do not process via CSSOM. (CSSOM is destructive to rules on rare
* occasions, e.g. -webkit-calc on Safari.)
* For example, we convert this rule:
*
* @polyfill-unscoped-rule {
* content: 'menu-item';
* ... }
*
* to this:
*
* menu-item {...}
*
**/
private _extractUnscopedRulesFromCssText(cssText: string): string {
let r = '';
let m: RegExpExecArray | null;
_cssContentUnscopedRuleRe.lastIndex = 0;
while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) {
const rule = m[0].replace(m[2], '').replace(m[1], m[4]);
r += rule + '\n\n';
}
return r;
}
/*
* convert a rule like :host(.foo) > .bar { }
*
* to
*
* .foo<scopeName> > .bar
*/
private _convertColonHost(cssText: string): string {
return cssText.replace(_cssColonHostRe, (_, hostSelectors: string, otherSelectors: string) => {
if (hostSelectors) {
const convertedSelectors: string[] = [];
const hostSelectorArray = hostSelectors.split(',').map((p) => p.trim());
for (const hostSelector of hostSelectorArray) {
if (!hostSelector) break;
const convertedSelector =
_polyfillHostNoCombinator + hostSelector.replace(_polyfillHost, '') + otherSelectors;
convertedSelectors.push(convertedSelector);
}
return convertedSelectors.join(',');
} else {
return _polyfillHostNoCombinator + otherSelectors;
}
});
}
/*
* convert a rule like :host-context(.foo) > .bar { }
*
* to
*
* .foo<scopeName> > .bar, .foo <scopeName> > .bar { }
*
* and
*
* :host-context(.foo:host) .bar { ... }
*
* to
*
* .foo<scopeName> .bar { ... }
*/ | {
"end_byte": 16862,
"start_byte": 11506,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/shadow_css.ts"
} |
angular/packages/compiler/src/shadow_css.ts_16865_25126 | private _convertColonHostContext(cssText: string): string {
return cssText.replace(_cssColonHostContextReGlobal, (selectorText, pseudoPrefix) => {
// We have captured a selector that contains a `:host-context` rule.
// For backward compatibility `:host-context` may contain a comma separated list of selectors.
// Each context selector group will contain a list of host-context selectors that must match
// an ancestor of the host.
// (Normally `contextSelectorGroups` will only contain a single array of context selectors.)
const contextSelectorGroups: string[][] = [[]];
// There may be more than `:host-context` in this selector so `selectorText` could look like:
// `:host-context(.one):host-context(.two)`.
// Execute `_cssColonHostContextRe` over and over until we have extracted all the
// `:host-context` selectors from this selector.
let match: RegExpExecArray | null;
while ((match = _cssColonHostContextRe.exec(selectorText))) {
// `match` = [':host-context(<selectors>)<rest>', <selectors>, <rest>]
// The `<selectors>` could actually be a comma separated list: `:host-context(.one, .two)`.
const newContextSelectors = (match[1] ?? '')
.trim()
.split(',')
.map((m) => m.trim())
.filter((m) => m !== '');
// We must duplicate the current selector group for each of these new selectors.
// For example if the current groups are:
// ```
// [
// ['a', 'b', 'c'],
// ['x', 'y', 'z'],
// ]
// ```
// And we have a new set of comma separated selectors: `:host-context(m,n)` then the new
// groups are:
// ```
// [
// ['a', 'b', 'c', 'm'],
// ['x', 'y', 'z', 'm'],
// ['a', 'b', 'c', 'n'],
// ['x', 'y', 'z', 'n'],
// ]
// ```
const contextSelectorGroupsLength = contextSelectorGroups.length;
repeatGroups(contextSelectorGroups, newContextSelectors.length);
for (let i = 0; i < newContextSelectors.length; i++) {
for (let j = 0; j < contextSelectorGroupsLength; j++) {
contextSelectorGroups[j + i * contextSelectorGroupsLength].push(newContextSelectors[i]);
}
}
// Update the `selectorText` and see repeat to see if there are more `:host-context`s.
selectorText = match[2];
}
// The context selectors now must be combined with each other to capture all the possible
// selectors that `:host-context` can match. See `_combineHostContextSelectors()` for more
// info about how this is done.
return contextSelectorGroups
.map((contextSelectors) =>
_combineHostContextSelectors(contextSelectors, selectorText, pseudoPrefix),
)
.join(', ');
});
}
/*
* Convert combinators like ::shadow and pseudo-elements like ::content
* by replacing with space.
*/
private _convertShadowDOMSelectors(cssText: string): string {
return _shadowDOMSelectorsRe.reduce((result, pattern) => result.replace(pattern, ' '), cssText);
}
// change a selector like 'div' to 'name div'
private _scopeSelectors(cssText: string, scopeSelector: string, hostSelector: string): string {
return processRules(cssText, (rule: CssRule) => {
let selector = rule.selector;
let content = rule.content;
if (rule.selector[0] !== '@') {
selector = this._scopeSelector({
selector,
scopeSelector,
hostSelector,
isParentSelector: true,
});
} else if (scopedAtRuleIdentifiers.some((atRule) => rule.selector.startsWith(atRule))) {
content = this._scopeSelectors(rule.content, scopeSelector, hostSelector);
} else if (rule.selector.startsWith('@font-face') || rule.selector.startsWith('@page')) {
content = this._stripScopingSelectors(rule.content);
}
return new CssRule(selector, content);
});
}
/**
* Handle a css text that is within a rule that should not contain scope selectors by simply
* removing them! An example of such a rule is `@font-face`.
*
* `@font-face` rules cannot contain nested selectors. Nor can they be nested under a selector.
* Normally this would be a syntax error by the author of the styles. But in some rare cases, such
* as importing styles from a library, and applying `:host ::ng-deep` to the imported styles, we
* can end up with broken css if the imported styles happen to contain @font-face rules.
*
* For example:
*
* ```
* :host ::ng-deep {
* import 'some/lib/containing/font-face';
* }
*
* Similar logic applies to `@page` rules which can contain a particular set of properties,
* as well as some specific at-rules. Since they can't be encapsulated, we have to strip
* any scoping selectors from them. For more information: https://www.w3.org/TR/css-page-3
* ```
*/
private _stripScopingSelectors(cssText: string): string {
return processRules(cssText, (rule) => {
const selector = rule.selector
.replace(_shadowDeepSelectors, ' ')
.replace(_polyfillHostNoCombinatorRe, ' ');
return new CssRule(selector, rule.content);
});
}
private _safeSelector: SafeSelector | undefined;
private _shouldScopeIndicator: boolean | undefined;
// `isParentSelector` is used to distinguish the selectors which are coming from
// the initial selector string and any nested selectors, parsed recursively,
// for example `selector = 'a:where(.one)'` could be the parent, while recursive call
// would have `selector = '.one'`.
private _scopeSelector({
selector,
scopeSelector,
hostSelector,
isParentSelector = false,
}: {
selector: string;
scopeSelector: string;
hostSelector: string;
isParentSelector?: boolean;
}): string {
// Split the selector into independent parts by `,` (comma) unless
// comma is within parenthesis, for example `:is(.one, two)`.
// Negative lookup after comma allows not splitting inside nested parenthesis,
// up to three levels (((,))).
const selectorSplitRe =
/ ?,(?!(?:[^)(]*(?:\([^)(]*(?:\([^)(]*(?:\([^)(]*\)[^)(]*)*\)[^)(]*)*\)[^)(]*)*\))) ?/;
return selector
.split(selectorSplitRe)
.map((part) => part.split(_shadowDeepSelectors))
.map((deepParts) => {
const [shallowPart, ...otherParts] = deepParts;
const applyScope = (shallowPart: string) => {
if (this._selectorNeedsScoping(shallowPart, scopeSelector)) {
return this._applySelectorScope({
selector: shallowPart,
scopeSelector,
hostSelector,
isParentSelector,
});
} else {
return shallowPart;
}
};
return [applyScope(shallowPart), ...otherParts].join(' ');
})
.join(', ');
}
private _selectorNeedsScoping(selector: string, scopeSelector: string): boolean {
const re = this._makeScopeMatcher(scopeSelector);
return !re.test(selector);
}
private _makeScopeMatcher(scopeSelector: string): RegExp {
const lre = /\[/g;
const rre = /\]/g;
scopeSelector = scopeSelector.replace(lre, '\\[').replace(rre, '\\]');
return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
}
// scope via name and [is=name]
private _applySimpleSelectorScope(
selector: string,
scopeSelector: string,
hostSelector: string,
): string {
// In Android browser, the lastIndex is not reset when the regex is used in String.replace()
_polyfillHostRe.lastIndex = 0;
if (_polyfillHostRe.test(selector)) {
const replaceBy = `[${hostSelector}]`;
return selector
.replace(_polyfillHostNoCombinatorReGlobal, (_hnc, selector) => {
return selector.replace(
/([^:\)]*)(:*)(.*)/,
(_: string, before: string, colon: string, after: string) => {
return before + replaceBy + colon + after;
},
);
})
.replace(_polyfillHostRe, replaceBy + ' ');
}
return scopeSelector + ' ' + selector;
} | {
"end_byte": 25126,
"start_byte": 16865,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/shadow_css.ts"
} |
angular/packages/compiler/src/shadow_css.ts_25130_31481 | // return a selector with [name] suffix on each simple selector
// e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name] /** @internal */
private _applySelectorScope({
selector,
scopeSelector,
hostSelector,
isParentSelector,
}: {
selector: string;
scopeSelector: string;
hostSelector: string;
isParentSelector?: boolean;
}): string {
const isRe = /\[is=([^\]]*)\]/g;
scopeSelector = scopeSelector.replace(isRe, (_: string, ...parts: string[]) => parts[0]);
const attrName = '[' + scopeSelector + ']';
const _scopeSelectorPart = (p: string) => {
let scopedP = p.trim();
if (!scopedP) {
return p;
}
if (p.includes(_polyfillHostNoCombinator)) {
scopedP = this._applySimpleSelectorScope(p, scopeSelector, hostSelector);
if (_polyfillHostNoCombinatorWithinPseudoFunction.test(p)) {
const [_, before, colon, after] = scopedP.match(/([^:]*)(:*)(.*)/)!;
scopedP = before + attrName + colon + after;
}
} else {
// remove :host since it should be unnecessary
const t = p.replace(_polyfillHostRe, '');
if (t.length > 0) {
const matches = t.match(/([^:]*)(:*)(.*)/);
if (matches) {
scopedP = matches[1] + attrName + matches[2] + matches[3];
}
}
}
return scopedP;
};
// Wraps `_scopeSelectorPart()` to not use it directly on selectors with
// pseudo selector functions like `:where()`. Selectors within pseudo selector
// functions are recursively sent to `_scopeSelector()`.
const _pseudoFunctionAwareScopeSelectorPart = (selectorPart: string) => {
let scopedPart = '';
const cssPrefixWithPseudoSelectorFunctionMatch = selectorPart.match(
_cssPrefixWithPseudoSelectorFunction,
);
if (cssPrefixWithPseudoSelectorFunctionMatch) {
const [cssPseudoSelectorFunction] = cssPrefixWithPseudoSelectorFunctionMatch;
// Unwrap the pseudo selector to scope its contents.
// For example,
// - `:where(selectorToScope)` -> `selectorToScope`;
// - `:is(.foo, .bar)` -> `.foo, .bar`.
const selectorToScope = selectorPart.slice(cssPseudoSelectorFunction.length, -1);
if (selectorToScope.includes(_polyfillHostNoCombinator)) {
this._shouldScopeIndicator = true;
}
const scopedInnerPart = this._scopeSelector({
selector: selectorToScope,
scopeSelector,
hostSelector,
});
// Put the result back into the pseudo selector function.
scopedPart = `${cssPseudoSelectorFunction}${scopedInnerPart})`;
} else {
this._shouldScopeIndicator =
this._shouldScopeIndicator || selectorPart.includes(_polyfillHostNoCombinator);
scopedPart = this._shouldScopeIndicator ? _scopeSelectorPart(selectorPart) : selectorPart;
}
return scopedPart;
};
if (isParentSelector) {
this._safeSelector = new SafeSelector(selector);
selector = this._safeSelector.content();
}
let scopedSelector = '';
let startIndex = 0;
let res: RegExpExecArray | null;
// Combinators aren't used as a delimiter if they are within parenthesis,
// for example `:where(.one .two)` stays intact.
// Similarly to selector separation by comma initially, negative lookahead
// is used here to not break selectors within nested parenthesis up to three
// nested layers.
const sep =
/( |>|\+|~(?!=))(?!([^)(]*(?:\([^)(]*(?:\([^)(]*(?:\([^)(]*\)[^)(]*)*\)[^)(]*)*\)[^)(]*)*\)))\s*/g;
// If a selector appears before :host it should not be shimmed as it
// matches on ancestor elements and not on elements in the host's shadow
// `:host-context(div)` is transformed to
// `-shadowcsshost-no-combinatordiv, div -shadowcsshost-no-combinator`
// the `div` is not part of the component in the 2nd selectors and should not be scoped.
// Historically `component-tag:host` was matching the component so we also want to preserve
// this behavior to avoid breaking legacy apps (it should not match).
// The behavior should be:
// - `tag:host` -> `tag[h]` (this is to avoid breaking legacy apps, should not match anything)
// - `tag :host` -> `tag [h]` (`tag` is not scoped because it's considered part of a
// `:host-context(tag)`)
const hasHost = selector.includes(_polyfillHostNoCombinator);
// Only scope parts after or on the same level as the first `-shadowcsshost-no-combinator`
// when it is present. The selector has the same level when it is a part of a pseudo
// selector, like `:where()`, for example `:where(:host, .foo)` would result in `.foo`
// being scoped.
if (isParentSelector || this._shouldScopeIndicator) {
this._shouldScopeIndicator = !hasHost;
}
while ((res = sep.exec(selector)) !== null) {
const separator = res[1];
// Do not trim the selector, as otherwise this will break sourcemaps
// when they are defined on multiple lines
// Example:
// div,
// p { color: red}
const part = selector.slice(startIndex, res.index);
// A space following an escaped hex value and followed by another hex character
// (ie: ".\fc ber" for ".über") is not a separator between 2 selectors
// also keep in mind that backslashes are replaced by a placeholder by SafeSelector
// These escaped selectors happen for example when esbuild runs with optimization.minify.
if (part.match(/__esc-ph-(\d+)__/) && selector[res.index + 1]?.match(/[a-fA-F\d]/)) {
continue;
}
const scopedPart = _pseudoFunctionAwareScopeSelectorPart(part);
scopedSelector += `${scopedPart} ${separator} `;
startIndex = sep.lastIndex;
}
const part = selector.substring(startIndex);
scopedSelector += _pseudoFunctionAwareScopeSelectorPart(part);
// replace the placeholders with their original values
// using values stored inside the `safeSelector` instance.
return this._safeSelector!.restore(scopedSelector);
}
private _insertPolyfillHostInCssText(selector: string): string {
return selector
.replace(_colonHostContextRe, _polyfillHostContext)
.replace(_colonHostRe, _polyfillHost);
}
}
| {
"end_byte": 31481,
"start_byte": 25130,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/shadow_css.ts"
} |
angular/packages/compiler/src/shadow_css.ts_31483_37421 | lass SafeSelector {
private placeholders: string[] = [];
private index = 0;
private _content: string;
constructor(selector: string) {
// Replaces attribute selectors with placeholders.
// The WS in [attr="va lue"] would otherwise be interpreted as a selector separator.
selector = this._escapeRegexMatches(selector, /(\[[^\]]*\])/g);
// CSS allows for certain special characters to be used in selectors if they're escaped.
// E.g. `.foo:blue` won't match a class called `foo:blue`, because the colon denotes a
// pseudo-class, but writing `.foo\:blue` will match, because the colon was escaped.
// Replace all escape sequences (`\` followed by a character) with a placeholder so
// that our handling of pseudo-selectors doesn't mess with them.
// Escaped characters have a specific placeholder so they can be detected separately.
selector = selector.replace(/(\\.)/g, (_, keep) => {
const replaceBy = `__esc-ph-${this.index}__`;
this.placeholders.push(keep);
this.index++;
return replaceBy;
});
// Replaces the expression in `:nth-child(2n + 1)` with a placeholder.
// WS and "+" would otherwise be interpreted as selector separators.
this._content = selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, (_, pseudo, exp) => {
const replaceBy = `__ph-${this.index}__`;
this.placeholders.push(exp);
this.index++;
return pseudo + replaceBy;
});
}
restore(content: string): string {
return content.replace(/__(?:ph|esc-ph)-(\d+)__/g, (_ph, index) => this.placeholders[+index]);
}
content(): string {
return this._content;
}
/**
* Replaces all of the substrings that match a regex within a
* special string (e.g. `__ph-0__`, `__ph-1__`, etc).
*/
private _escapeRegexMatches(content: string, pattern: RegExp): string {
return content.replace(pattern, (_, keep) => {
const replaceBy = `__ph-${this.index}__`;
this.placeholders.push(keep);
this.index++;
return replaceBy;
});
}
}
const _cssScopedPseudoFunctionPrefix = '(:(where|is)\\()?';
const _cssPrefixWithPseudoSelectorFunction = /^:(where|is)\(/i;
const _cssContentNextSelectorRe =
/polyfill-next-selector[^}]*content:[\s]*?(['"])(.*?)\1[;\s]*}([^{]*?){/gim;
const _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
const _cssContentUnscopedRuleRe =
/(polyfill-unscoped-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
const _polyfillHost = '-shadowcsshost';
// note: :host-context pre-processed to -shadowcsshostcontext.
const _polyfillHostContext = '-shadowcsscontext';
const _parenSuffix = '(?:\\((' + '(?:\\([^)(]*\\)|[^)(]*)+?' + ')\\))?([^,{]*)';
const _cssColonHostRe = new RegExp(_polyfillHost + _parenSuffix, 'gim');
const _cssColonHostContextReGlobal = new RegExp(
_cssScopedPseudoFunctionPrefix + '(' + _polyfillHostContext + _parenSuffix + ')',
'gim',
);
const _cssColonHostContextRe = new RegExp(_polyfillHostContext + _parenSuffix, 'im');
const _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
const _polyfillHostNoCombinatorWithinPseudoFunction = new RegExp(
`:.*\\(.*${_polyfillHostNoCombinator}.*\\)`,
);
const _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/;
const _polyfillHostNoCombinatorReGlobal = new RegExp(_polyfillHostNoCombinatorRe, 'g');
const _shadowDOMSelectorsRe = [
/::shadow/g,
/::content/g,
// Deprecated selectors
/\/shadow-deep\//g,
/\/shadow\//g,
];
// The deep combinator is deprecated in the CSS spec
// Support for `>>>`, `deep`, `::ng-deep` is then also deprecated and will be removed in the future.
// see https://github.com/angular/angular/pull/17677
const _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)|(?:::ng-deep)/g;
const _selectorReSuffix = '([>\\s~+[.,{:][\\s\\S]*)?$';
const _polyfillHostRe = /-shadowcsshost/gim;
const _colonHostRe = /:host/gim;
const _colonHostContextRe = /:host-context/gim;
const _newLinesRe = /\r?\n/g;
const _commentRe = /\/\*[\s\S]*?\*\//g;
const _commentWithHashRe = /\/\*\s*#\s*source(Mapping)?URL=/g;
const COMMENT_PLACEHOLDER = '%COMMENT%';
const _commentWithHashPlaceHolderRe = new RegExp(COMMENT_PLACEHOLDER, 'g');
const BLOCK_PLACEHOLDER = '%BLOCK%';
const _ruleRe = new RegExp(
`(\\s*(?:${COMMENT_PLACEHOLDER}\\s*)*)([^;\\{\\}]+?)(\\s*)((?:{%BLOCK%}?\\s*;?)|(?:\\s*;))`,
'g',
);
const CONTENT_PAIRS = new Map([['{', '}']]);
const COMMA_IN_PLACEHOLDER = '%COMMA_IN_PLACEHOLDER%';
const SEMI_IN_PLACEHOLDER = '%SEMI_IN_PLACEHOLDER%';
const COLON_IN_PLACEHOLDER = '%COLON_IN_PLACEHOLDER%';
const _cssCommaInPlaceholderReGlobal = new RegExp(COMMA_IN_PLACEHOLDER, 'g');
const _cssSemiInPlaceholderReGlobal = new RegExp(SEMI_IN_PLACEHOLDER, 'g');
const _cssColonInPlaceholderReGlobal = new RegExp(COLON_IN_PLACEHOLDER, 'g');
export class CssRule {
constructor(
public selector: string,
public content: string,
) {}
}
export function processRules(input: string, ruleCallback: (rule: CssRule) => CssRule): string {
const escaped = escapeInStrings(input);
const inputWithEscapedBlocks = escapeBlocks(escaped, CONTENT_PAIRS, BLOCK_PLACEHOLDER);
let nextBlockIndex = 0;
const escapedResult = inputWithEscapedBlocks.escapedString.replace(_ruleRe, (...m: string[]) => {
const selector = m[2];
let content = '';
let suffix = m[4];
let contentPrefix = '';
if (suffix && suffix.startsWith('{' + BLOCK_PLACEHOLDER)) {
content = inputWithEscapedBlocks.blocks[nextBlockIndex++];
suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1);
contentPrefix = '{';
}
const rule = ruleCallback(new CssRule(selector, content));
return `${m[1]}${rule.selector}${m[3]}${contentPrefix}${rule.content}${suffix}`;
});
return unescapeInStrings(escapedResult);
}
class StringWithEscapedBlocks {
constructor(
public escapedString: string,
public blocks: string[],
) {}
}
| {
"end_byte": 37421,
"start_byte": 31483,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/shadow_css.ts"
} |
angular/packages/compiler/src/shadow_css.ts_37423_45330 | unction escapeBlocks(
input: string,
charPairs: Map<string, string>,
placeholder: string,
): StringWithEscapedBlocks {
const resultParts: string[] = [];
const escapedBlocks: string[] = [];
let openCharCount = 0;
let nonBlockStartIndex = 0;
let blockStartIndex = -1;
let openChar: string | undefined;
let closeChar: string | undefined;
for (let i = 0; i < input.length; i++) {
const char = input[i];
if (char === '\\') {
i++;
} else if (char === closeChar) {
openCharCount--;
if (openCharCount === 0) {
escapedBlocks.push(input.substring(blockStartIndex, i));
resultParts.push(placeholder);
nonBlockStartIndex = i;
blockStartIndex = -1;
openChar = closeChar = undefined;
}
} else if (char === openChar) {
openCharCount++;
} else if (openCharCount === 0 && charPairs.has(char)) {
openChar = char;
closeChar = charPairs.get(char);
openCharCount = 1;
blockStartIndex = i + 1;
resultParts.push(input.substring(nonBlockStartIndex, blockStartIndex));
}
}
if (blockStartIndex !== -1) {
escapedBlocks.push(input.substring(blockStartIndex));
resultParts.push(placeholder);
} else {
resultParts.push(input.substring(nonBlockStartIndex));
}
return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks);
}
/**
* Object containing as keys characters that should be substituted by placeholders
* when found in strings during the css text parsing, and as values the respective
* placeholders
*/
const ESCAPE_IN_STRING_MAP: {[key: string]: string} = {
';': SEMI_IN_PLACEHOLDER,
',': COMMA_IN_PLACEHOLDER,
':': COLON_IN_PLACEHOLDER,
};
/**
* Parse the provided css text and inside strings (meaning, inside pairs of unescaped single or
* double quotes) replace specific characters with their respective placeholders as indicated
* by the `ESCAPE_IN_STRING_MAP` map.
*
* For example convert the text
* `animation: "my-anim:at\"ion" 1s;`
* to
* `animation: "my-anim%COLON_IN_PLACEHOLDER%at\"ion" 1s;`
*
* This is necessary in order to remove the meaning of some characters when found inside strings
* (for example `;` indicates the end of a css declaration, `,` the sequence of values and `:` the
* division between property and value during a declaration, none of these meanings apply when such
* characters are within strings and so in order to prevent parsing issues they need to be replaced
* with placeholder text for the duration of the css manipulation process).
*
* @param input the original css text.
*
* @returns the css text with specific characters in strings replaced by placeholders.
**/
function escapeInStrings(input: string): string {
let result = input;
let currentQuoteChar: string | null = null;
for (let i = 0; i < result.length; i++) {
const char = result[i];
if (char === '\\') {
i++;
} else {
if (currentQuoteChar !== null) {
// index i is inside a quoted sub-string
if (char === currentQuoteChar) {
currentQuoteChar = null;
} else {
const placeholder: string | undefined = ESCAPE_IN_STRING_MAP[char];
if (placeholder) {
result = `${result.substr(0, i)}${placeholder}${result.substr(i + 1)}`;
i += placeholder.length - 1;
}
}
} else if (char === "'" || char === '"') {
currentQuoteChar = char;
}
}
}
return result;
}
/**
* Replace in a string all occurrences of keys in the `ESCAPE_IN_STRING_MAP` map with their
* original representation, this is simply used to revert the changes applied by the
* escapeInStrings function.
*
* For example it reverts the text:
* `animation: "my-anim%COLON_IN_PLACEHOLDER%at\"ion" 1s;`
* to it's original form of:
* `animation: "my-anim:at\"ion" 1s;`
*
* Note: For the sake of simplicity this function does not check that the placeholders are
* actually inside strings as it would anyway be extremely unlikely to find them outside of strings.
*
* @param input the css text containing the placeholders.
*
* @returns the css text without the placeholders.
*/
function unescapeInStrings(input: string): string {
let result = input.replace(_cssCommaInPlaceholderReGlobal, ',');
result = result.replace(_cssSemiInPlaceholderReGlobal, ';');
result = result.replace(_cssColonInPlaceholderReGlobal, ':');
return result;
}
/**
* Unescape all quotes present in a string, but only if the string was actually already
* quoted.
*
* This generates a "canonical" representation of strings which can be used to match strings
* which would otherwise only differ because of differently escaped quotes.
*
* For example it converts the string (assumed to be quoted):
* `this \\"is\\" a \\'\\\\'test`
* to:
* `this "is" a '\\\\'test`
* (note that the latter backslashes are not removed as they are not actually escaping the single
* quote)
*
*
* @param input the string possibly containing escaped quotes.
* @param isQuoted boolean indicating whether the string was quoted inside a bigger string (if not
* then it means that it doesn't represent an inner string and thus no unescaping is required)
*
* @returns the string in the "canonical" representation without escaped quotes.
*/
function unescapeQuotes(str: string, isQuoted: boolean): string {
return !isQuoted ? str : str.replace(/((?:^|[^\\])(?:\\\\)*)\\(?=['"])/g, '$1');
}
/**
* Combine the `contextSelectors` with the `hostMarker` and the `otherSelectors`
* to create a selector that matches the same as `:host-context()`.
*
* Given a single context selector `A` we need to output selectors that match on the host and as an
* ancestor of the host:
*
* ```
* A <hostMarker>, A<hostMarker> {}
* ```
*
* When there is more than one context selector we also have to create combinations of those
* selectors with each other. For example if there are `A` and `B` selectors the output is:
*
* ```
* AB<hostMarker>, AB <hostMarker>, A B<hostMarker>,
* B A<hostMarker>, A B <hostMarker>, B A <hostMarker> {}
* ```
*
* And so on...
*
* @param contextSelectors an array of context selectors that will be combined.
* @param otherSelectors the rest of the selectors that are not context selectors.
*/
function _combineHostContextSelectors(
contextSelectors: string[],
otherSelectors: string,
pseudoPrefix = '',
): string {
const hostMarker = _polyfillHostNoCombinator;
_polyfillHostRe.lastIndex = 0; // reset the regex to ensure we get an accurate test
const otherSelectorsHasHost = _polyfillHostRe.test(otherSelectors);
// If there are no context selectors then just output a host marker
if (contextSelectors.length === 0) {
return hostMarker + otherSelectors;
}
const combined: string[] = [contextSelectors.pop() || ''];
while (contextSelectors.length > 0) {
const length = combined.length;
const contextSelector = contextSelectors.pop();
for (let i = 0; i < length; i++) {
const previousSelectors = combined[i];
// Add the new selector as a descendant of the previous selectors
combined[length * 2 + i] = previousSelectors + ' ' + contextSelector;
// Add the new selector as an ancestor of the previous selectors
combined[length + i] = contextSelector + ' ' + previousSelectors;
// Add the new selector to act on the same element as the previous selectors
combined[i] = contextSelector + previousSelectors;
}
}
// Finally connect the selector to the `hostMarker`s: either acting directly on the host
// (A<hostMarker>) or as an ancestor (A <hostMarker>).
return combined
.map((s) =>
otherSelectorsHasHost
? `${pseudoPrefix}${s}${otherSelectors}`
: `${pseudoPrefix}${s}${hostMarker}${otherSelectors}, ${pseudoPrefix}${s} ${hostMarker}${otherSelectors}`,
)
.join(',');
}
| {
"end_byte": 45330,
"start_byte": 37423,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/shadow_css.ts"
} |
angular/packages/compiler/src/shadow_css.ts_45332_46036 | **
* Mutate the given `groups` array so that there are `multiples` clones of the original array
* stored.
*
* For example `repeatGroups([a, b], 3)` will result in `[a, b, a, b, a, b]` - but importantly the
* newly added groups will be clones of the original.
*
* @param groups An array of groups of strings that will be repeated. This array is mutated
* in-place.
* @param multiples The number of times the current groups should appear.
*/
export function repeatGroups(groups: string[][], multiples: number): void {
const length = groups.length;
for (let i = 1; i < multiples; i++) {
for (let j = 0; j < length; j++) {
groups[j + i * length] = groups[j].slice(0);
}
}
}
| {
"end_byte": 46036,
"start_byte": 45332,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/shadow_css.ts"
} |
angular/packages/compiler/src/compiler.ts_0_7729 | /**
* @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
*/
//////////////////////////////////////
// THIS FILE HAS GLOBAL SIDE EFFECT //
// (see bottom of file) //
//////////////////////////////////////
/**
* @module
* @description
* Entry point for all APIs of the compiler package.
*
* <div class="callout is-critical">
* <header>Unstable APIs</header>
* <p>
* All compiler apis are currently considered experimental and private!
* </p>
* <p>
* We expect the APIs in this package to keep on changing. Do not rely on them.
* </p>
* </div>
*/
import * as core from './core';
import {publishFacade} from './jit_compiler_facade';
import {global} from './util';
export {CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA, SchemaMetadata} from './core';
export {core};
export * from './version';
export {CompilerConfig, preserveWhitespacesDefault} from './config';
export * from './resource_loader';
export {ConstantPool} from './constant_pool';
export {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from './ml_parser/defaults';
export * from './schema/element_schema_registry';
export * from './i18n/index';
export * from './expression_parser/ast';
export * from './expression_parser/lexer';
export * from './expression_parser/parser';
export * from './ml_parser/ast';
export * from './ml_parser/html_parser';
export * from './ml_parser/html_tags';
export * from './ml_parser/tags';
export {ParseTreeResult, TreeError} from './ml_parser/parser';
export {LexerRange} from './ml_parser/lexer';
export * from './ml_parser/xml_parser';
export {TokenType as LexerTokenType} from './ml_parser/tokens';
export {
ArrayType,
DYNAMIC_TYPE,
BinaryOperator,
BinaryOperatorExpr,
BuiltinType,
BuiltinTypeName,
CommaExpr,
ConditionalExpr,
DeclareFunctionStmt,
DeclareVarStmt,
Expression,
ExpressionStatement,
ExpressionType,
ExpressionVisitor,
ExternalExpr,
ExternalReference,
literalMap,
FunctionExpr,
IfStmt,
InstantiateExpr,
InvokeFunctionExpr,
ArrowFunctionExpr,
LiteralArrayExpr,
LiteralExpr,
LiteralMapExpr,
MapType,
NotExpr,
NONE_TYPE,
ReadKeyExpr,
ReadPropExpr,
ReadVarExpr,
ReturnStatement,
StatementVisitor,
TaggedTemplateExpr,
TemplateLiteral,
TemplateLiteralElement,
Type,
TypeModifier,
TypeVisitor,
WrappedNodeExpr,
literal,
WriteKeyExpr,
WritePropExpr,
WriteVarExpr,
StmtModifier,
Statement,
STRING_TYPE,
TypeofExpr,
jsDocComment,
leadingComment,
LeadingComment,
JSDocComment,
UnaryOperator,
UnaryOperatorExpr,
LocalizedString,
TransplantedType,
DynamicImportExpr,
} from './output/output_ast';
export {EmitterVisitorContext} from './output/abstract_emitter';
export {JitEvaluator} from './output/output_jit';
export * from './parse_util';
export * from './schema/dom_element_schema_registry';
export * from './selector';
export {Version} from './util';
export {SourceMap} from './output/source_map';
export * from './injectable_compiler_2';
export * from './render3/partial/api';
export * from './render3/view/api';
export {
visitAll as tmplAstVisitAll,
BlockNode as TmplAstBlockNode,
BoundAttribute as TmplAstBoundAttribute,
BoundEvent as TmplAstBoundEvent,
BoundText as TmplAstBoundText,
Content as TmplAstContent,
Element as TmplAstElement,
Icu as TmplAstIcu,
Node as TmplAstNode,
Visitor as TmplAstVisitor,
RecursiveVisitor as TmplAstRecursiveVisitor,
Reference as TmplAstReference,
Template as TmplAstTemplate,
Text as TmplAstText,
TextAttribute as TmplAstTextAttribute,
Variable as TmplAstVariable,
DeferredBlock as TmplAstDeferredBlock,
DeferredBlockPlaceholder as TmplAstDeferredBlockPlaceholder,
DeferredBlockLoading as TmplAstDeferredBlockLoading,
DeferredBlockError as TmplAstDeferredBlockError,
DeferredTrigger as TmplAstDeferredTrigger,
BoundDeferredTrigger as TmplAstBoundDeferredTrigger,
IdleDeferredTrigger as TmplAstIdleDeferredTrigger,
ImmediateDeferredTrigger as TmplAstImmediateDeferredTrigger,
HoverDeferredTrigger as TmplAstHoverDeferredTrigger,
TimerDeferredTrigger as TmplAstTimerDeferredTrigger,
InteractionDeferredTrigger as TmplAstInteractionDeferredTrigger,
ViewportDeferredTrigger as TmplAstViewportDeferredTrigger,
NeverDeferredTrigger as TmplAstNeverDeferredTrigger,
SwitchBlock as TmplAstSwitchBlock,
SwitchBlockCase as TmplAstSwitchBlockCase,
ForLoopBlock as TmplAstForLoopBlock,
ForLoopBlockEmpty as TmplAstForLoopBlockEmpty,
IfBlock as TmplAstIfBlock,
IfBlockBranch as TmplAstIfBlockBranch,
DeferredBlockTriggers as TmplAstDeferredBlockTriggers,
UnknownBlock as TmplAstUnknownBlock,
LetDeclaration as TmplAstLetDeclaration,
} from './render3/r3_ast';
export * from './render3/view/t2_api';
export * from './render3/view/t2_binder';
export {createCssSelectorFromNode} from './render3/view/util';
export {Identifiers as R3Identifiers} from './render3/r3_identifiers';
export {
R3ClassMetadata,
CompileClassMetadataFn,
compileClassMetadata,
compileComponentClassMetadata,
compileOpaqueAsyncClassMetadata,
} from './render3/r3_class_metadata_compiler';
export {compileClassDebugInfo, R3ClassDebugInfo} from './render3/r3_class_debug_info_compiler';
export {
compileHmrInitializer,
compileHmrUpdateCallback,
R3HmrMetadata,
} from './render3/r3_hmr_compiler';
export {
compileFactoryFunction,
R3DependencyMetadata,
R3FactoryMetadata,
FactoryTarget,
} from './render3/r3_factory';
export {
compileNgModule,
R3NgModuleMetadata,
R3SelectorScopeMode,
R3NgModuleMetadataKind,
R3NgModuleMetadataGlobal,
} from './render3/r3_module_compiler';
export {compileInjector, R3InjectorMetadata} from './render3/r3_injector_compiler';
export {compilePipeFromMetadata, R3PipeMetadata} from './render3/r3_pipe_compiler';
export {
makeBindingParser,
ParsedTemplate,
parseTemplate,
ParseTemplateOptions,
} from './render3/view/template';
export {
ForwardRefHandling,
MaybeForwardRefExpression,
R3CompiledExpression,
R3Reference,
createMayBeForwardRefExpression,
devOnlyGuardedExpression,
getSafePropertyAccessString,
} from './render3/util';
export {
compileComponentFromMetadata,
compileDirectiveFromMetadata,
parseHostBindings,
ParsedHostBindings,
verifyHostBindings,
encapsulateStyle,
compileDeferResolverFunction,
} from './render3/view/compiler';
export {
compileDeclareClassMetadata,
compileComponentDeclareClassMetadata,
} from './render3/partial/class_metadata';
export {
compileDeclareComponentFromMetadata,
DeclareComponentTemplateInfo,
} from './render3/partial/component';
export {compileDeclareDirectiveFromMetadata} from './render3/partial/directive';
export {compileDeclareFactoryFunction} from './render3/partial/factory';
export {compileDeclareInjectableFromMetadata} from './render3/partial/injectable';
export {compileDeclareInjectorFromMetadata} from './render3/partial/injector';
export {compileDeclareNgModuleFromMetadata} from './render3/partial/ng_module';
export {compileDeclarePipeFromMetadata} from './render3/partial/pipe';
export {publishFacade} from './jit_compiler_facade';
export {
emitDistinctChangesOnlyDefaultValue,
ChangeDetectionStrategy,
ViewEncapsulation,
} from './core';
import * as outputAst from './output/output_ast';
export {outputAst};
// This file only reexports content of the `src` folder. Keep it that way.
// This function call has a global side effects and publishes the compiler into global namespace for
// the late binding of the Compiler to the @angular/core for jit compilation.
publishFacade(global);
| {
"end_byte": 7729,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/compiler.ts"
} |
angular/packages/compiler/src/version.ts_0_390 | /**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the compiler package.
*/
import {Version} from './util';
export const VERSION = new Version('0.0.0-PLACEHOLDER');
| {
"end_byte": 390,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/version.ts"
} |
angular/packages/compiler/src/config.ts_0_1198 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {MissingTranslationStrategy, ViewEncapsulation} from './core';
import {noUndefined} from './util';
export class CompilerConfig {
public defaultEncapsulation: ViewEncapsulation | null;
public preserveWhitespaces: boolean;
public strictInjectionParameters: boolean;
constructor({
defaultEncapsulation = ViewEncapsulation.Emulated,
preserveWhitespaces,
strictInjectionParameters,
}: {
defaultEncapsulation?: ViewEncapsulation;
preserveWhitespaces?: boolean;
strictInjectionParameters?: boolean;
} = {}) {
this.defaultEncapsulation = defaultEncapsulation;
this.preserveWhitespaces = preserveWhitespacesDefault(noUndefined(preserveWhitespaces));
this.strictInjectionParameters = strictInjectionParameters === true;
}
}
export function preserveWhitespacesDefault(
preserveWhitespacesOption: boolean | null,
defaultSetting = false,
): boolean {
return preserveWhitespacesOption === null ? defaultSetting : preserveWhitespacesOption;
}
| {
"end_byte": 1198,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/config.ts"
} |
angular/packages/compiler/src/compiler_facade_interface.ts_0_8243 | /**
* @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
*/
/**
* A set of interfaces which are shared between `@angular/core` and `@angular/compiler` to allow
* for late binding of `@angular/compiler` for JIT purposes.
*
* This file has two copies. Please ensure that they are in sync:
* - packages/compiler/src/compiler_facade_interface.ts (main)
* - packages/core/src/compiler/compiler_facade_interface.ts (replica)
*
* Please ensure that the two files are in sync using this command:
* ```
* cp packages/compiler/src/compiler_facade_interface.ts \
* packages/core/src/compiler/compiler_facade_interface.ts
* ```
*/
export interface ExportedCompilerFacade {
ɵcompilerFacade: CompilerFacade;
}
export interface CompilerFacade {
compilePipe(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3PipeMetadataFacade,
): any;
compilePipeDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclarePipeFacade,
): any;
compileInjectable(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3InjectableMetadataFacade,
): any;
compileInjectableDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3DeclareInjectableFacade,
): any;
compileInjector(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3InjectorMetadataFacade,
): any;
compileInjectorDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclareInjectorFacade,
): any;
compileNgModule(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3NgModuleMetadataFacade,
): any;
compileNgModuleDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclareNgModuleFacade,
): any;
compileDirective(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3DirectiveMetadataFacade,
): any;
compileDirectiveDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclareDirectiveFacade,
): any;
compileComponent(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3ComponentMetadataFacade,
): any;
compileComponentDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclareComponentFacade,
): any;
compileFactory(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3FactoryDefMetadataFacade,
): any;
compileFactoryDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3DeclareFactoryFacade,
): any;
createParseSourceSpan(kind: string, typeName: string, sourceUrl: string): ParseSourceSpan;
FactoryTarget: typeof FactoryTarget;
// Note that we do not use `{new(): ResourceLoader}` here because
// the resource loader class is abstract and not constructable.
ResourceLoader: Function & {prototype: ResourceLoader};
}
export interface CoreEnvironment {
[name: string]: unknown;
}
export type ResourceLoader = {
get(url: string): Promise<string> | string;
};
export type Provider = unknown;
export type Type = Function;
export type OpaqueValue = unknown;
export enum FactoryTarget {
Directive = 0,
Component = 1,
Injectable = 2,
Pipe = 3,
NgModule = 4,
}
export interface R3DependencyMetadataFacade {
token: OpaqueValue;
attribute: string | null;
host: boolean;
optional: boolean;
self: boolean;
skipSelf: boolean;
}
export interface R3DeclareDependencyMetadataFacade {
token: OpaqueValue;
attribute?: boolean;
host?: boolean;
optional?: boolean;
self?: boolean;
skipSelf?: boolean;
}
export interface R3PipeMetadataFacade {
name: string;
type: Type;
pipeName: string;
pure: boolean;
isStandalone: boolean;
}
export interface R3InjectableMetadataFacade {
name: string;
type: Type;
typeArgumentCount: number;
providedIn?: Type | 'root' | 'platform' | 'any' | null;
useClass?: OpaqueValue;
useFactory?: OpaqueValue;
useExisting?: OpaqueValue;
useValue?: OpaqueValue;
deps?: R3DependencyMetadataFacade[];
}
export interface R3NgModuleMetadataFacade {
type: Type;
bootstrap: Function[];
declarations: Function[];
imports: Function[];
exports: Function[];
schemas: {name: string}[] | null;
id: string | null;
}
export interface R3InjectorMetadataFacade {
name: string;
type: Type;
providers: Provider[];
imports: OpaqueValue[];
}
export interface R3HostDirectiveMetadataFacade {
directive: Type;
inputs?: string[];
outputs?: string[];
}
export interface R3DirectiveMetadataFacade {
name: string;
type: Type;
typeSourceSpan: ParseSourceSpan;
selector: string | null;
queries: R3QueryMetadataFacade[];
host: {[key: string]: string};
propMetadata: {[key: string]: OpaqueValue[]};
lifecycle: {usesOnChanges: boolean};
inputs: (string | {name: string; alias?: string; required?: boolean})[];
outputs: string[];
usesInheritance: boolean;
exportAs: string[] | null;
providers: Provider[] | null;
viewQueries: R3QueryMetadataFacade[];
isStandalone: boolean;
hostDirectives: R3HostDirectiveMetadataFacade[] | null;
isSignal: boolean;
}
export interface R3ComponentMetadataFacade extends R3DirectiveMetadataFacade {
template: string;
preserveWhitespaces: boolean;
animations: OpaqueValue[] | undefined;
declarations: R3TemplateDependencyFacade[];
styles: string[];
encapsulation: ViewEncapsulation;
viewProviders: Provider[] | null;
interpolation?: [string, string];
changeDetection?: ChangeDetectionStrategy;
}
// TODO(legacy-partial-output-inputs): Remove in v18.
// https://github.com/angular/angular/blob/d4b423690210872b5c32a322a6090beda30b05a3/packages/core/src/compiler/compiler_facade_interface.ts#L197-L199
export type LegacyInputPartialMapping =
| string
| [bindingPropertyName: string, classPropertyName: string, transformFunction?: Function];
export interface R3DeclareDirectiveFacade {
selector?: string;
type: Type;
version: string;
inputs?: {
[fieldName: string]:
| {
classPropertyName: string;
publicName: string;
isSignal: boolean;
isRequired: boolean;
transformFunction: Function | null;
}
| LegacyInputPartialMapping;
};
outputs?: {[classPropertyName: string]: string};
host?: {
attributes?: {[key: string]: OpaqueValue};
listeners?: {[key: string]: string};
properties?: {[key: string]: string};
classAttribute?: string;
styleAttribute?: string;
};
queries?: R3DeclareQueryMetadataFacade[];
viewQueries?: R3DeclareQueryMetadataFacade[];
providers?: OpaqueValue;
exportAs?: string[];
usesInheritance?: boolean;
usesOnChanges?: boolean;
isStandalone?: boolean;
isSignal?: boolean;
hostDirectives?: R3HostDirectiveMetadataFacade[] | null;
}
export interface R3DeclareComponentFacade extends R3DeclareDirectiveFacade {
template: string;
isInline?: boolean;
styles?: string[];
// Post-standalone libraries use a unified dependencies field.
dependencies?: R3DeclareTemplateDependencyFacade[];
// Pre-standalone libraries have separate component/directive/pipe fields:
components?: R3DeclareDirectiveDependencyFacade[];
directives?: R3DeclareDirectiveDependencyFacade[];
pipes?: {[pipeName: string]: OpaqueValue | (() => OpaqueValue)};
deferBlockDependencies?: (() => Promise<Type> | null)[];
viewProviders?: OpaqueValue;
animations?: OpaqueValue;
changeDetection?: ChangeDetectionStrategy;
encapsulation?: ViewEncapsulation;
interpolation?: [string, string];
preserveWhitespaces?: boolean;
}
export type R3DeclareTemplateDependencyFacade = {
kind: string;
} & (
| R3DeclareDirectiveDependencyFacade
| R3DeclarePipeDependencyFacade
| R3DeclareNgModuleDependencyFacade
);
export interface R3DeclareDirectiveDependencyFacade {
kind?: 'directive' | 'component';
selector: string;
type: OpaqueValue | (() => OpaqueValue);
inputs?: string[];
outputs?: string[];
exportAs?: string[];
}
| {
"end_byte": 8243,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/compiler_facade_interface.ts"
} |
angular/packages/compiler/src/compiler_facade_interface.ts_8245_10700 | xport interface R3DeclarePipeDependencyFacade {
kind?: 'pipe';
name: string;
type: OpaqueValue | (() => OpaqueValue);
}
export interface R3DeclareNgModuleDependencyFacade {
kind: 'ngmodule';
type: OpaqueValue | (() => OpaqueValue);
}
export enum R3TemplateDependencyKind {
Directive = 0,
Pipe = 1,
NgModule = 2,
}
export interface R3TemplateDependencyFacade {
kind: R3TemplateDependencyKind;
type: OpaqueValue | (() => OpaqueValue);
}
export interface R3FactoryDefMetadataFacade {
name: string;
type: Type;
typeArgumentCount: number;
deps: R3DependencyMetadataFacade[] | null;
target: FactoryTarget;
}
export interface R3DeclareFactoryFacade {
type: Type;
deps: R3DeclareDependencyMetadataFacade[] | 'invalid' | null;
target: FactoryTarget;
}
export interface R3DeclareInjectableFacade {
type: Type;
providedIn?: Type | 'root' | 'platform' | 'any' | null;
useClass?: OpaqueValue;
useFactory?: OpaqueValue;
useExisting?: OpaqueValue;
useValue?: OpaqueValue;
deps?: R3DeclareDependencyMetadataFacade[];
}
export enum ViewEncapsulation {
Emulated = 0,
// Historically the 1 value was for `Native` encapsulation which has been removed as of v11.
None = 2,
ShadowDom = 3,
}
export type ChangeDetectionStrategy = number;
export interface R3QueryMetadataFacade {
propertyName: string;
first: boolean;
predicate: OpaqueValue | string[];
descendants: boolean;
emitDistinctChangesOnly: boolean;
read: OpaqueValue | null;
static: boolean;
isSignal: boolean;
}
export interface R3DeclareQueryMetadataFacade {
propertyName: string;
first?: boolean;
predicate: OpaqueValue | string[];
descendants?: boolean;
read?: OpaqueValue;
static?: boolean;
emitDistinctChangesOnly?: boolean;
isSignal?: boolean;
}
export interface R3DeclareInjectorFacade {
type: Type;
imports?: OpaqueValue[];
providers?: OpaqueValue[];
}
export interface R3DeclareNgModuleFacade {
type: Type;
bootstrap?: OpaqueValue[] | (() => OpaqueValue[]);
declarations?: OpaqueValue[] | (() => OpaqueValue[]);
imports?: OpaqueValue[] | (() => OpaqueValue[]);
exports?: OpaqueValue[] | (() => OpaqueValue[]);
schemas?: OpaqueValue[];
id?: OpaqueValue;
}
export interface R3DeclarePipeFacade {
type: Type;
version: string;
name: string;
pure?: boolean;
isStandalone?: boolean;
}
export interface ParseSourceSpan {
start: any;
end: any;
details: any;
fullStart: any;
}
| {
"end_byte": 10700,
"start_byte": 8245,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/compiler_facade_interface.ts"
} |
angular/packages/compiler/src/jit_compiler_facade.ts_0_3252 | /**
* @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 {
CompilerFacade,
CoreEnvironment,
ExportedCompilerFacade,
LegacyInputPartialMapping,
OpaqueValue,
R3ComponentMetadataFacade,
R3DeclareComponentFacade,
R3DeclareDependencyMetadataFacade,
R3DeclareDirectiveDependencyFacade,
R3DeclareDirectiveFacade,
R3DeclareFactoryFacade,
R3DeclareInjectableFacade,
R3DeclareInjectorFacade,
R3DeclareNgModuleFacade,
R3DeclarePipeDependencyFacade,
R3DeclarePipeFacade,
R3DeclareQueryMetadataFacade,
R3DependencyMetadataFacade,
R3DirectiveMetadataFacade,
R3FactoryDefMetadataFacade,
R3InjectableMetadataFacade,
R3InjectorMetadataFacade,
R3NgModuleMetadataFacade,
R3PipeMetadataFacade,
R3QueryMetadataFacade,
R3TemplateDependencyFacade,
} from './compiler_facade_interface';
import {ConstantPool} from './constant_pool';
import {
ChangeDetectionStrategy,
HostBinding,
HostListener,
Input,
Output,
ViewEncapsulation,
} from './core';
import {compileInjectable} from './injectable_compiler_2';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from './ml_parser/defaults';
import {
DeclareVarStmt,
Expression,
literal,
LiteralExpr,
Statement,
StmtModifier,
WrappedNodeExpr,
} from './output/output_ast';
import {JitEvaluator} from './output/output_jit';
import {ParseError, ParseSourceSpan, r3JitTypeSourceSpan} from './parse_util';
import {DeferredBlock} from './render3/r3_ast';
import {compileFactoryFunction, FactoryTarget, R3DependencyMetadata} from './render3/r3_factory';
import {compileInjector, R3InjectorMetadata} from './render3/r3_injector_compiler';
import {R3JitReflector} from './render3/r3_jit';
import {
compileNgModule,
compileNgModuleDeclarationExpression,
R3NgModuleMetadata,
R3NgModuleMetadataKind,
R3SelectorScopeMode,
} from './render3/r3_module_compiler';
import {compilePipeFromMetadata, R3PipeMetadata} from './render3/r3_pipe_compiler';
import {
createMayBeForwardRefExpression,
ForwardRefHandling,
getSafePropertyAccessString,
MaybeForwardRefExpression,
wrapReference,
} from './render3/util';
import {
DeclarationListEmitMode,
DeferBlockDepsEmitMode,
R3ComponentDeferMetadata,
R3ComponentMetadata,
R3DirectiveDependencyMetadata,
R3DirectiveMetadata,
R3HostDirectiveMetadata,
R3HostMetadata,
R3InputMetadata,
R3PipeDependencyMetadata,
R3QueryMetadata,
R3TemplateDependency,
R3TemplateDependencyKind,
R3TemplateDependencyMetadata,
} from './render3/view/api';
import {
compileComponentFromMetadata,
compileDirectiveFromMetadata,
ParsedHostBindings,
parseHostBindings,
verifyHostBindings,
} from './render3/view/compiler';
import type {BoundTarget} from './render3/view/t2_api';
import {R3TargetBinder} from './render3/view/t2_binder';
import {makeBindingParser, parseTemplate} from './render3/view/template';
import {ResourceLoader} from './resource_loader';
import {DomElementSchemaRegistry} from './schema/dom_element_schema_registry';
import {SelectorMatcher} from './selector';
import {getJitStandaloneDefaultForVersion} from './util'; | {
"end_byte": 3252,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/jit_compiler_facade.ts"
} |
angular/packages/compiler/src/jit_compiler_facade.ts_3254_11824 | export class CompilerFacadeImpl implements CompilerFacade {
FactoryTarget = FactoryTarget;
ResourceLoader = ResourceLoader;
private elementSchemaRegistry = new DomElementSchemaRegistry();
constructor(private jitEvaluator = new JitEvaluator()) {}
compilePipe(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
facade: R3PipeMetadataFacade,
): any {
const metadata: R3PipeMetadata = {
name: facade.name,
type: wrapReference(facade.type),
typeArgumentCount: 0,
deps: null,
pipeName: facade.pipeName,
pure: facade.pure,
isStandalone: facade.isStandalone,
};
const res = compilePipeFromMetadata(metadata);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
}
compilePipeDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclarePipeFacade,
): any {
const meta = convertDeclarePipeFacadeToMetadata(declaration);
const res = compilePipeFromMetadata(meta);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
}
compileInjectable(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
facade: R3InjectableMetadataFacade,
): any {
const {expression, statements} = compileInjectable(
{
name: facade.name,
type: wrapReference(facade.type),
typeArgumentCount: facade.typeArgumentCount,
providedIn: computeProvidedIn(facade.providedIn),
useClass: convertToProviderExpression(facade, 'useClass'),
useFactory: wrapExpression(facade, 'useFactory'),
useValue: convertToProviderExpression(facade, 'useValue'),
useExisting: convertToProviderExpression(facade, 'useExisting'),
deps: facade.deps?.map(convertR3DependencyMetadata),
},
/* resolveForwardRefs */ true,
);
return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, statements);
}
compileInjectableDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
facade: R3DeclareInjectableFacade,
): any {
const {expression, statements} = compileInjectable(
{
name: facade.type.name,
type: wrapReference(facade.type),
typeArgumentCount: 0,
providedIn: computeProvidedIn(facade.providedIn),
useClass: convertToProviderExpression(facade, 'useClass'),
useFactory: wrapExpression(facade, 'useFactory'),
useValue: convertToProviderExpression(facade, 'useValue'),
useExisting: convertToProviderExpression(facade, 'useExisting'),
deps: facade.deps?.map(convertR3DeclareDependencyMetadata),
},
/* resolveForwardRefs */ true,
);
return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, statements);
}
compileInjector(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
facade: R3InjectorMetadataFacade,
): any {
const meta: R3InjectorMetadata = {
name: facade.name,
type: wrapReference(facade.type),
providers:
facade.providers && facade.providers.length > 0
? new WrappedNodeExpr(facade.providers)
: null,
imports: facade.imports.map((i) => new WrappedNodeExpr(i)),
};
const res = compileInjector(meta);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
}
compileInjectorDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclareInjectorFacade,
): any {
const meta = convertDeclareInjectorFacadeToMetadata(declaration);
const res = compileInjector(meta);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
}
compileNgModule(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
facade: R3NgModuleMetadataFacade,
): any {
const meta: R3NgModuleMetadata = {
kind: R3NgModuleMetadataKind.Global,
type: wrapReference(facade.type),
bootstrap: facade.bootstrap.map(wrapReference),
declarations: facade.declarations.map(wrapReference),
publicDeclarationTypes: null, // only needed for types in AOT
imports: facade.imports.map(wrapReference),
includeImportTypes: true,
exports: facade.exports.map(wrapReference),
selectorScopeMode: R3SelectorScopeMode.Inline,
containsForwardDecls: false,
schemas: facade.schemas ? facade.schemas.map(wrapReference) : null,
id: facade.id ? new WrappedNodeExpr(facade.id) : null,
};
const res = compileNgModule(meta);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
}
compileNgModuleDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclareNgModuleFacade,
): any {
const expression = compileNgModuleDeclarationExpression(declaration);
return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, []);
}
compileDirective(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
facade: R3DirectiveMetadataFacade,
): any {
const meta: R3DirectiveMetadata = convertDirectiveFacadeToMetadata(facade);
return this.compileDirectiveFromMeta(angularCoreEnv, sourceMapUrl, meta);
}
compileDirectiveDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclareDirectiveFacade,
): any {
const typeSourceSpan = this.createParseSourceSpan(
'Directive',
declaration.type.name,
sourceMapUrl,
);
const meta = convertDeclareDirectiveFacadeToMetadata(declaration, typeSourceSpan);
return this.compileDirectiveFromMeta(angularCoreEnv, sourceMapUrl, meta);
}
private compileDirectiveFromMeta(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3DirectiveMetadata,
): any {
const constantPool = new ConstantPool();
const bindingParser = makeBindingParser();
const res = compileDirectiveFromMetadata(meta, constantPool, bindingParser);
return this.jitExpression(
res.expression,
angularCoreEnv,
sourceMapUrl,
constantPool.statements,
);
}
compileComponent(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
facade: R3ComponentMetadataFacade,
): any {
// Parse the template and check for errors.
const {template, interpolation, defer} = parseJitTemplate(
facade.template,
facade.name,
sourceMapUrl,
facade.preserveWhitespaces,
facade.interpolation,
undefined,
);
// Compile the component metadata, including template, into an expression.
const meta: R3ComponentMetadata<R3TemplateDependency> = {
...facade,
...convertDirectiveFacadeToMetadata(facade),
selector: facade.selector || this.elementSchemaRegistry.getDefaultComponentElementName(),
template,
declarations: facade.declarations.map(convertDeclarationFacadeToMetadata),
declarationListEmitMode: DeclarationListEmitMode.Direct,
defer,
styles: [...facade.styles, ...template.styles],
encapsulation: facade.encapsulation,
interpolation,
changeDetection: facade.changeDetection ?? null,
animations: facade.animations != null ? new WrappedNodeExpr(facade.animations) : null,
viewProviders:
facade.viewProviders != null ? new WrappedNodeExpr(facade.viewProviders) : null,
relativeContextFilePath: '',
i18nUseExternalIds: true,
};
const jitExpressionSourceMap = `ng:///${facade.name}.js`;
return this.compileComponentFromMeta(angularCoreEnv, jitExpressionSourceMap, meta);
}
compileComponentDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclareComponentFacade,
): any {
const typeSourceSpan = this.createParseSourceSpan(
'Component',
declaration.type.name,
sourceMapUrl,
);
const meta = convertDeclareComponentFacadeToMetadata(declaration, typeSourceSpan, sourceMapUrl);
return this.compileComponentFromMeta(angularCoreEnv, sourceMapUrl, meta);
}
private compileComponentFromMeta(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3ComponentMetadata<R3TemplateDependency>,
): any {
const constantPool = new ConstantPool();
const bindingParser = makeBindingParser(meta.interpolation);
const res = compileComponentFromMetadata(meta, constantPool, bindingParser);
return this.jitExpression(
res.expression,
angularCoreEnv,
sourceMapUrl,
constantPool.statements,
);
} | {
"end_byte": 11824,
"start_byte": 3254,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/jit_compiler_facade.ts"
} |
angular/packages/compiler/src/jit_compiler_facade.ts_11828_20739 | compileFactory(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3FactoryDefMetadataFacade,
) {
const factoryRes = compileFactoryFunction({
name: meta.name,
type: wrapReference(meta.type),
typeArgumentCount: meta.typeArgumentCount,
deps: convertR3DependencyMetadataArray(meta.deps),
target: meta.target,
});
return this.jitExpression(
factoryRes.expression,
angularCoreEnv,
sourceMapUrl,
factoryRes.statements,
);
}
compileFactoryDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3DeclareFactoryFacade,
) {
const factoryRes = compileFactoryFunction({
name: meta.type.name,
type: wrapReference(meta.type),
typeArgumentCount: 0,
deps: Array.isArray(meta.deps)
? meta.deps.map(convertR3DeclareDependencyMetadata)
: meta.deps,
target: meta.target,
});
return this.jitExpression(
factoryRes.expression,
angularCoreEnv,
sourceMapUrl,
factoryRes.statements,
);
}
createParseSourceSpan(kind: string, typeName: string, sourceUrl: string): ParseSourceSpan {
return r3JitTypeSourceSpan(kind, typeName, sourceUrl);
}
/**
* JIT compiles an expression and returns the result of executing that expression.
*
* @param def the definition which will be compiled and executed to get the value to patch
* @param context an object map of @angular/core symbol names to symbols which will be available
* in the context of the compiled expression
* @param sourceUrl a URL to use for the source map of the compiled expression
* @param preStatements a collection of statements that should be evaluated before the expression.
*/
private jitExpression(
def: Expression,
context: {[key: string]: any},
sourceUrl: string,
preStatements: Statement[],
): any {
// The ConstantPool may contain Statements which declare variables used in the final expression.
// Therefore, its statements need to precede the actual JIT operation. The final statement is a
// declaration of $def which is set to the expression being compiled.
const statements: Statement[] = [
...preStatements,
new DeclareVarStmt('$def', def, undefined, StmtModifier.Exported),
];
const res = this.jitEvaluator.evaluateStatements(
sourceUrl,
statements,
new R3JitReflector(context),
/* enableSourceMaps */ true,
);
return res['$def'];
}
}
function convertToR3QueryMetadata(facade: R3QueryMetadataFacade): R3QueryMetadata {
return {
...facade,
isSignal: facade.isSignal,
predicate: convertQueryPredicate(facade.predicate),
read: facade.read ? new WrappedNodeExpr(facade.read) : null,
static: facade.static,
emitDistinctChangesOnly: facade.emitDistinctChangesOnly,
};
}
function convertQueryDeclarationToMetadata(
declaration: R3DeclareQueryMetadataFacade,
): R3QueryMetadata {
return {
propertyName: declaration.propertyName,
first: declaration.first ?? false,
predicate: convertQueryPredicate(declaration.predicate),
descendants: declaration.descendants ?? false,
read: declaration.read ? new WrappedNodeExpr(declaration.read) : null,
static: declaration.static ?? false,
emitDistinctChangesOnly: declaration.emitDistinctChangesOnly ?? true,
isSignal: !!declaration.isSignal,
};
}
function convertQueryPredicate(
predicate: OpaqueValue | string[],
): MaybeForwardRefExpression | string[] {
return Array.isArray(predicate)
? // The predicate is an array of strings so pass it through.
predicate
: // The predicate is a type - assume that we will need to unwrap any `forwardRef()` calls.
createMayBeForwardRefExpression(new WrappedNodeExpr(predicate), ForwardRefHandling.Wrapped);
}
function convertDirectiveFacadeToMetadata(facade: R3DirectiveMetadataFacade): R3DirectiveMetadata {
const inputsFromMetadata = parseInputsArray(facade.inputs || []);
const outputsFromMetadata = parseMappingStringArray(facade.outputs || []);
const propMetadata = facade.propMetadata;
const inputsFromType: Record<string, R3InputMetadata> = {};
const outputsFromType: Record<string, string> = {};
for (const field in propMetadata) {
if (propMetadata.hasOwnProperty(field)) {
propMetadata[field].forEach((ann) => {
if (isInput(ann)) {
inputsFromType[field] = {
bindingPropertyName: ann.alias || field,
classPropertyName: field,
required: ann.required || false,
// For JIT, decorators are used to declare signal inputs. That is because of
// a technical limitation where it's not possible to statically reflect class
// members of a directive/component at runtime before instantiating the class.
isSignal: !!ann.isSignal,
transformFunction: ann.transform != null ? new WrappedNodeExpr(ann.transform) : null,
};
} else if (isOutput(ann)) {
outputsFromType[field] = ann.alias || field;
}
});
}
}
const hostDirectives = facade.hostDirectives?.length
? facade.hostDirectives.map((hostDirective) => {
return typeof hostDirective === 'function'
? {
directive: wrapReference(hostDirective),
inputs: null,
outputs: null,
isForwardReference: false,
}
: {
directive: wrapReference(hostDirective.directive),
isForwardReference: false,
inputs: hostDirective.inputs ? parseMappingStringArray(hostDirective.inputs) : null,
outputs: hostDirective.outputs
? parseMappingStringArray(hostDirective.outputs)
: null,
};
})
: null;
return {
...facade,
typeArgumentCount: 0,
typeSourceSpan: facade.typeSourceSpan,
type: wrapReference(facade.type),
deps: null,
host: {
...extractHostBindings(facade.propMetadata, facade.typeSourceSpan, facade.host),
},
inputs: {...inputsFromMetadata, ...inputsFromType},
outputs: {...outputsFromMetadata, ...outputsFromType},
queries: facade.queries.map(convertToR3QueryMetadata),
providers: facade.providers != null ? new WrappedNodeExpr(facade.providers) : null,
viewQueries: facade.viewQueries.map(convertToR3QueryMetadata),
fullInheritance: false,
hostDirectives,
};
}
function convertDeclareDirectiveFacadeToMetadata(
declaration: R3DeclareDirectiveFacade,
typeSourceSpan: ParseSourceSpan,
): R3DirectiveMetadata {
const hostDirectives = declaration.hostDirectives?.length
? declaration.hostDirectives.map((dir) => ({
directive: wrapReference(dir.directive),
isForwardReference: false,
inputs: dir.inputs ? getHostDirectiveBindingMapping(dir.inputs) : null,
outputs: dir.outputs ? getHostDirectiveBindingMapping(dir.outputs) : null,
}))
: null;
return {
name: declaration.type.name,
type: wrapReference(declaration.type),
typeSourceSpan,
selector: declaration.selector ?? null,
inputs: declaration.inputs ? inputsPartialMetadataToInputMetadata(declaration.inputs) : {},
outputs: declaration.outputs ?? {},
host: convertHostDeclarationToMetadata(declaration.host),
queries: (declaration.queries ?? []).map(convertQueryDeclarationToMetadata),
viewQueries: (declaration.viewQueries ?? []).map(convertQueryDeclarationToMetadata),
providers:
declaration.providers !== undefined ? new WrappedNodeExpr(declaration.providers) : null,
exportAs: declaration.exportAs ?? null,
usesInheritance: declaration.usesInheritance ?? false,
lifecycle: {usesOnChanges: declaration.usesOnChanges ?? false},
deps: null,
typeArgumentCount: 0,
fullInheritance: false,
isStandalone:
declaration.isStandalone ?? getJitStandaloneDefaultForVersion(declaration.version),
isSignal: declaration.isSignal ?? false,
hostDirectives,
};
}
function convertHostDeclarationToMetadata(
host: R3DeclareDirectiveFacade['host'] = {},
): R3HostMetadata {
return {
attributes: convertOpaqueValuesToExpressions(host.attributes ?? {}),
listeners: host.listeners ?? {},
properties: host.properties ?? {},
specialAttributes: {
classAttr: host.classAttribute,
styleAttr: host.styleAttribute,
},
};
}
/**
* Parses a host directive mapping where each odd array key is the name of an input/output
* and each even key is its public name, e.g. `['one', 'oneAlias', 'two', 'two']`.
*/
function getHostDirectiveBindingMapping(array: string[]) {
let result: {[publicName: string]: string} | null = null;
for (let i = 1; i < array.length; i += 2) {
result = result || {};
result[array[i - 1]] = array[i];
}
return result;
} | {
"end_byte": 20739,
"start_byte": 11828,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/jit_compiler_facade.ts"
} |
angular/packages/compiler/src/jit_compiler_facade.ts_20741_29277 | function convertOpaqueValuesToExpressions(obj: {[key: string]: OpaqueValue}): {
[key: string]: WrappedNodeExpr<unknown>;
} {
const result: {[key: string]: WrappedNodeExpr<unknown>} = {};
for (const key of Object.keys(obj)) {
result[key] = new WrappedNodeExpr(obj[key]);
}
return result;
}
function convertDeclareComponentFacadeToMetadata(
decl: R3DeclareComponentFacade,
typeSourceSpan: ParseSourceSpan,
sourceMapUrl: string,
): R3ComponentMetadata<R3TemplateDependencyMetadata> {
const {template, interpolation, defer} = parseJitTemplate(
decl.template,
decl.type.name,
sourceMapUrl,
decl.preserveWhitespaces ?? false,
decl.interpolation,
decl.deferBlockDependencies,
);
const declarations: R3TemplateDependencyMetadata[] = [];
if (decl.dependencies) {
for (const innerDep of decl.dependencies) {
switch (innerDep.kind) {
case 'directive':
case 'component':
declarations.push(convertDirectiveDeclarationToMetadata(innerDep));
break;
case 'pipe':
declarations.push(convertPipeDeclarationToMetadata(innerDep));
break;
}
}
} else if (decl.components || decl.directives || decl.pipes) {
// Existing declarations on NPM may not be using the new `dependencies` merged field, and may
// have separate fields for dependencies instead. Unify them for JIT compilation.
decl.components &&
declarations.push(
...decl.components.map((dir) =>
convertDirectiveDeclarationToMetadata(dir, /* isComponent */ true),
),
);
decl.directives &&
declarations.push(
...decl.directives.map((dir) => convertDirectiveDeclarationToMetadata(dir)),
);
decl.pipes && declarations.push(...convertPipeMapToMetadata(decl.pipes));
}
return {
...convertDeclareDirectiveFacadeToMetadata(decl, typeSourceSpan),
template,
styles: decl.styles ?? [],
declarations,
viewProviders:
decl.viewProviders !== undefined ? new WrappedNodeExpr(decl.viewProviders) : null,
animations: decl.animations !== undefined ? new WrappedNodeExpr(decl.animations) : null,
defer,
changeDetection: decl.changeDetection ?? ChangeDetectionStrategy.Default,
encapsulation: decl.encapsulation ?? ViewEncapsulation.Emulated,
interpolation,
declarationListEmitMode: DeclarationListEmitMode.ClosureResolved,
relativeContextFilePath: '',
i18nUseExternalIds: true,
};
}
function convertDeclarationFacadeToMetadata(
declaration: R3TemplateDependencyFacade,
): R3TemplateDependency {
return {
...declaration,
type: new WrappedNodeExpr(declaration.type),
};
}
function convertDirectiveDeclarationToMetadata(
declaration: R3DeclareDirectiveDependencyFacade,
isComponent: true | null = null,
): R3DirectiveDependencyMetadata {
return {
kind: R3TemplateDependencyKind.Directive,
isComponent: isComponent || declaration.kind === 'component',
selector: declaration.selector,
type: new WrappedNodeExpr(declaration.type),
inputs: declaration.inputs ?? [],
outputs: declaration.outputs ?? [],
exportAs: declaration.exportAs ?? null,
};
}
function convertPipeMapToMetadata(
pipes: R3DeclareComponentFacade['pipes'],
): R3PipeDependencyMetadata[] {
if (!pipes) {
return [];
}
return Object.keys(pipes).map((name) => {
return {
kind: R3TemplateDependencyKind.Pipe,
name,
type: new WrappedNodeExpr(pipes[name]),
};
});
}
function convertPipeDeclarationToMetadata(
pipe: R3DeclarePipeDependencyFacade,
): R3PipeDependencyMetadata {
return {
kind: R3TemplateDependencyKind.Pipe,
name: pipe.name,
type: new WrappedNodeExpr(pipe.type),
};
}
function parseJitTemplate(
template: string,
typeName: string,
sourceMapUrl: string,
preserveWhitespaces: boolean,
interpolation: [string, string] | undefined,
deferBlockDependencies: (() => Promise<unknown> | null)[] | undefined,
) {
const interpolationConfig = interpolation
? InterpolationConfig.fromArray(interpolation)
: DEFAULT_INTERPOLATION_CONFIG;
// Parse the template and check for errors.
const parsed = parseTemplate(template, sourceMapUrl, {
preserveWhitespaces,
interpolationConfig,
});
if (parsed.errors !== null) {
const errors = parsed.errors.map((err) => err.toString()).join(', ');
throw new Error(`Errors during JIT compilation of template for ${typeName}: ${errors}`);
}
const binder = new R3TargetBinder(new SelectorMatcher());
const boundTarget = binder.bind({template: parsed.nodes});
return {
template: parsed,
interpolation: interpolationConfig,
defer: createR3ComponentDeferMetadata(boundTarget, deferBlockDependencies),
};
}
/**
* Convert the expression, if present to an `R3ProviderExpression`.
*
* In JIT mode we do not want the compiler to wrap the expression in a `forwardRef()` call because,
* if it is referencing a type that has not yet been defined, it will have already been wrapped in
* a `forwardRef()` - either by the application developer or during partial-compilation. Thus we can
* use `ForwardRefHandling.None`.
*/
function convertToProviderExpression(
obj: any,
property: string,
): MaybeForwardRefExpression | undefined {
if (obj.hasOwnProperty(property)) {
return createMayBeForwardRefExpression(
new WrappedNodeExpr(obj[property]),
ForwardRefHandling.None,
);
} else {
return undefined;
}
}
function wrapExpression(obj: any, property: string): WrappedNodeExpr<any> | undefined {
if (obj.hasOwnProperty(property)) {
return new WrappedNodeExpr(obj[property]);
} else {
return undefined;
}
}
function computeProvidedIn(
providedIn: Function | string | null | undefined,
): MaybeForwardRefExpression {
const expression =
typeof providedIn === 'function'
? new WrappedNodeExpr(providedIn)
: new LiteralExpr(providedIn ?? null);
// See `convertToProviderExpression()` for why this uses `ForwardRefHandling.None`.
return createMayBeForwardRefExpression(expression, ForwardRefHandling.None);
}
function convertR3DependencyMetadataArray(
facades: R3DependencyMetadataFacade[] | null | undefined,
): R3DependencyMetadata[] | null {
return facades == null ? null : facades.map(convertR3DependencyMetadata);
}
function convertR3DependencyMetadata(facade: R3DependencyMetadataFacade): R3DependencyMetadata {
const isAttributeDep = facade.attribute != null; // both `null` and `undefined`
const rawToken = facade.token === null ? null : new WrappedNodeExpr(facade.token);
// In JIT mode, if the dep is an `@Attribute()` then we use the attribute name given in
// `attribute` rather than the `token`.
const token = isAttributeDep ? new WrappedNodeExpr(facade.attribute) : rawToken;
return createR3DependencyMetadata(
token,
isAttributeDep,
facade.host,
facade.optional,
facade.self,
facade.skipSelf,
);
}
function convertR3DeclareDependencyMetadata(
facade: R3DeclareDependencyMetadataFacade,
): R3DependencyMetadata {
const isAttributeDep = facade.attribute ?? false;
const token = facade.token === null ? null : new WrappedNodeExpr(facade.token);
return createR3DependencyMetadata(
token,
isAttributeDep,
facade.host ?? false,
facade.optional ?? false,
facade.self ?? false,
facade.skipSelf ?? false,
);
}
function createR3DependencyMetadata(
token: WrappedNodeExpr<unknown> | null,
isAttributeDep: boolean,
host: boolean,
optional: boolean,
self: boolean,
skipSelf: boolean,
): R3DependencyMetadata {
// If the dep is an `@Attribute()` the `attributeNameType` ought to be the `unknown` type.
// But types are not available at runtime so we just use a literal `"<unknown>"` string as a dummy
// marker.
const attributeNameType = isAttributeDep ? literal('unknown') : null;
return {token, attributeNameType, host, optional, self, skipSelf};
}
function createR3ComponentDeferMetadata(
boundTarget: BoundTarget<any>,
deferBlockDependencies: (() => Promise<unknown> | null)[] | undefined,
): R3ComponentDeferMetadata {
const deferredBlocks = boundTarget.getDeferBlocks();
const blocks = new Map<DeferredBlock, Expression | null>();
for (let i = 0; i < deferredBlocks.length; i++) {
const dependencyFn = deferBlockDependencies?.[i];
blocks.set(deferredBlocks[i], dependencyFn ? new WrappedNodeExpr(dependencyFn) : null);
}
return {mode: DeferBlockDepsEmitMode.PerBlock, blocks};
} | {
"end_byte": 29277,
"start_byte": 20741,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/jit_compiler_facade.ts"
} |
angular/packages/compiler/src/jit_compiler_facade.ts_29279_35389 | function extractHostBindings(
propMetadata: {[key: string]: any[]},
sourceSpan: ParseSourceSpan,
host?: {[key: string]: string},
): ParsedHostBindings {
// First parse the declarations from the metadata.
const bindings = parseHostBindings(host || {});
// After that check host bindings for errors
const errors = verifyHostBindings(bindings, sourceSpan);
if (errors.length) {
throw new Error(errors.map((error: ParseError) => error.msg).join('\n'));
}
// Next, loop over the properties of the object, looking for @HostBinding and @HostListener.
for (const field in propMetadata) {
if (propMetadata.hasOwnProperty(field)) {
propMetadata[field].forEach((ann) => {
if (isHostBinding(ann)) {
// Since this is a decorator, we know that the value is a class member. Always access it
// through `this` so that further down the line it can't be confused for a literal value
// (e.g. if there's a property called `true`).
bindings.properties[ann.hostPropertyName || field] = getSafePropertyAccessString(
'this',
field,
);
} else if (isHostListener(ann)) {
bindings.listeners[ann.eventName || field] = `${field}(${(ann.args || []).join(',')})`;
}
});
}
}
return bindings;
}
function isHostBinding(value: any): value is HostBinding {
return value.ngMetadataName === 'HostBinding';
}
function isHostListener(value: any): value is HostListener {
return value.ngMetadataName === 'HostListener';
}
function isInput(value: any): value is Input {
return value.ngMetadataName === 'Input';
}
function isOutput(value: any): value is Output {
return value.ngMetadataName === 'Output';
}
function inputsPartialMetadataToInputMetadata(
inputs: NonNullable<R3DeclareDirectiveFacade['inputs']>,
) {
return Object.keys(inputs).reduce<Record<string, R3InputMetadata>>(
(result, minifiedClassName) => {
const value = inputs[minifiedClassName];
// Handle legacy partial input output.
if (typeof value === 'string' || Array.isArray(value)) {
result[minifiedClassName] = parseLegacyInputPartialOutput(value);
} else {
result[minifiedClassName] = {
bindingPropertyName: value.publicName,
classPropertyName: minifiedClassName,
transformFunction:
value.transformFunction !== null ? new WrappedNodeExpr(value.transformFunction) : null,
required: value.isRequired,
isSignal: value.isSignal,
};
}
return result;
},
{},
);
}
/**
* Parses the legacy input partial output. For more details see `partial/directive.ts`.
* TODO(legacy-partial-output-inputs): Remove in v18.
*/
function parseLegacyInputPartialOutput(value: LegacyInputPartialMapping): R3InputMetadata {
if (typeof value === 'string') {
return {
bindingPropertyName: value,
classPropertyName: value,
transformFunction: null,
required: false,
// legacy partial output does not capture signal inputs.
isSignal: false,
};
}
return {
bindingPropertyName: value[0],
classPropertyName: value[1],
transformFunction: value[2] ? new WrappedNodeExpr(value[2]) : null,
required: false,
// legacy partial output does not capture signal inputs.
isSignal: false,
};
}
function parseInputsArray(
values: (string | {name: string; alias?: string; required?: boolean; transform?: Function})[],
) {
return values.reduce<Record<string, R3InputMetadata>>((results, value) => {
if (typeof value === 'string') {
const [bindingPropertyName, classPropertyName] = parseMappingString(value);
results[classPropertyName] = {
bindingPropertyName,
classPropertyName,
required: false,
// Signal inputs not supported for the inputs array.
isSignal: false,
transformFunction: null,
};
} else {
results[value.name] = {
bindingPropertyName: value.alias || value.name,
classPropertyName: value.name,
required: value.required || false,
// Signal inputs not supported for the inputs array.
isSignal: false,
transformFunction: value.transform != null ? new WrappedNodeExpr(value.transform) : null,
};
}
return results;
}, {});
}
function parseMappingStringArray(values: string[]): Record<string, string> {
return values.reduce<Record<string, string>>((results, value) => {
const [alias, fieldName] = parseMappingString(value);
results[fieldName] = alias;
return results;
}, {});
}
function parseMappingString(value: string): [alias: string, fieldName: string] {
// Either the value is 'field' or 'field: property'. In the first case, `property` will
// be undefined, in which case the field name should also be used as the property name.
const [fieldName, bindingPropertyName] = value.split(':', 2).map((str) => str.trim());
return [bindingPropertyName ?? fieldName, fieldName];
}
function convertDeclarePipeFacadeToMetadata(declaration: R3DeclarePipeFacade): R3PipeMetadata {
return {
name: declaration.type.name,
type: wrapReference(declaration.type),
typeArgumentCount: 0,
pipeName: declaration.name,
deps: null,
pure: declaration.pure ?? true,
isStandalone:
declaration.isStandalone ?? getJitStandaloneDefaultForVersion(declaration.version),
};
}
function convertDeclareInjectorFacadeToMetadata(
declaration: R3DeclareInjectorFacade,
): R3InjectorMetadata {
return {
name: declaration.type.name,
type: wrapReference(declaration.type),
providers:
declaration.providers !== undefined && declaration.providers.length > 0
? new WrappedNodeExpr(declaration.providers)
: null,
imports:
declaration.imports !== undefined
? declaration.imports.map((i) => new WrappedNodeExpr(i))
: [],
};
}
export function publishFacade(global: any) {
const ng: ExportedCompilerFacade = global.ng || (global.ng = {});
ng.ɵcompilerFacade = new CompilerFacadeImpl();
}
| {
"end_byte": 35389,
"start_byte": 29279,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/jit_compiler_facade.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/index.ts_0_527 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './src/enums';
export * from './src/expression';
export * from './src/operations';
export * from './src/ops/create';
export * from './src/ops/host';
export * from './src/ops/shared';
export * from './src/ops/update';
export * from './src/handle';
export * from './src/traits';
export * from './src/variable';
| {
"end_byte": 527,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/index.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/expression.ts_0_8039 | /**
* @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 type {ParseSourceSpan} from '../../../../parse_util';
import * as t from '../../../../render3/r3_ast';
import {ExpressionKind, OpKind} from './enums';
import {SlotHandle} from './handle';
import type {XrefId} from './operations';
import type {CreateOp} from './ops/create';
import {Interpolation, type UpdateOp} from './ops/update';
import {
ConsumesVarsTrait,
DependsOnSlotContext,
DependsOnSlotContextOpTrait,
UsesVarOffset,
UsesVarOffsetTrait,
} from './traits';
/**
* An `o.Expression` subtype representing a logical expression in the intermediate representation.
*/
export type Expression =
| LexicalReadExpr
| ReferenceExpr
| ContextExpr
| NextContextExpr
| GetCurrentViewExpr
| RestoreViewExpr
| ResetViewExpr
| ReadVariableExpr
| PureFunctionExpr
| PureFunctionParameterExpr
| PipeBindingExpr
| PipeBindingVariadicExpr
| SafePropertyReadExpr
| SafeKeyedReadExpr
| SafeInvokeFunctionExpr
| EmptyExpr
| AssignTemporaryExpr
| ReadTemporaryExpr
| SlotLiteralExpr
| ConditionalCaseExpr
| ConstCollectedExpr
| TwoWayBindingSetExpr
| ContextLetReferenceExpr
| StoreLetExpr;
/**
* Transformer type which converts expressions into general `o.Expression`s (which may be an
* identity transformation).
*/
export type ExpressionTransform = (expr: o.Expression, flags: VisitorContextFlag) => o.Expression;
/**
* Check whether a given `o.Expression` is a logical IR expression type.
*/
export function isIrExpression(expr: o.Expression): expr is Expression {
return expr instanceof ExpressionBase;
}
/**
* Base type used for all logical IR expressions.
*/
export abstract class ExpressionBase extends o.Expression {
abstract readonly kind: ExpressionKind;
constructor(sourceSpan: ParseSourceSpan | null = null) {
super(null, sourceSpan);
}
/**
* Run the transformer against any nested expressions which may be present in this IR expression
* subtype.
*/
abstract transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void;
}
/**
* Logical expression representing a lexical read of a variable name.
*/
export class LexicalReadExpr extends ExpressionBase {
override readonly kind = ExpressionKind.LexicalRead;
constructor(readonly name: string) {
super();
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): void {}
override isEquivalent(other: LexicalReadExpr): boolean {
// We assume that the lexical reads are in the same context, which must be true for parent
// expressions to be equivalent.
// TODO: is this generally safe?
return this.name === other.name;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(): void {}
override clone(): LexicalReadExpr {
return new LexicalReadExpr(this.name);
}
}
/**
* Runtime operation to retrieve the value of a local reference.
*/
export class ReferenceExpr extends ExpressionBase {
override readonly kind = ExpressionKind.Reference;
constructor(
readonly target: XrefId,
readonly targetSlot: SlotHandle,
readonly offset: number,
) {
super();
}
override visitExpression(): void {}
override isEquivalent(e: o.Expression): boolean {
return e instanceof ReferenceExpr && e.target === this.target;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(): void {}
override clone(): ReferenceExpr {
return new ReferenceExpr(this.target, this.targetSlot, this.offset);
}
}
export class StoreLetExpr
extends ExpressionBase
implements ConsumesVarsTrait, DependsOnSlotContextOpTrait
{
override readonly kind = ExpressionKind.StoreLet;
readonly [ConsumesVarsTrait] = true;
readonly [DependsOnSlotContext] = true;
constructor(
readonly target: XrefId,
public value: o.Expression,
override sourceSpan: ParseSourceSpan,
) {
super();
}
override visitExpression(): void {}
override isEquivalent(e: o.Expression): boolean {
return (
e instanceof StoreLetExpr && e.target === this.target && e.value.isEquivalent(this.value)
);
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
this.value = transformExpressionsInExpression(this.value, transform, flags);
}
override clone(): StoreLetExpr {
return new StoreLetExpr(this.target, this.value, this.sourceSpan);
}
}
export class ContextLetReferenceExpr extends ExpressionBase {
override readonly kind = ExpressionKind.ContextLetReference;
constructor(
readonly target: XrefId,
readonly targetSlot: SlotHandle,
) {
super();
}
override visitExpression(): void {}
override isEquivalent(e: o.Expression): boolean {
return e instanceof ContextLetReferenceExpr && e.target === this.target;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(): void {}
override clone(): ContextLetReferenceExpr {
return new ContextLetReferenceExpr(this.target, this.targetSlot);
}
}
/**
* A reference to the current view context (usually the `ctx` variable in a template function).
*/
export class ContextExpr extends ExpressionBase {
override readonly kind = ExpressionKind.Context;
constructor(readonly view: XrefId) {
super();
}
override visitExpression(): void {}
override isEquivalent(e: o.Expression): boolean {
return e instanceof ContextExpr && e.view === this.view;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(): void {}
override clone(): ContextExpr {
return new ContextExpr(this.view);
}
}
/**
* A reference to the current view context inside a track function.
*/
export class TrackContextExpr extends ExpressionBase {
override readonly kind = ExpressionKind.TrackContext;
constructor(readonly view: XrefId) {
super();
}
override visitExpression(): void {}
override isEquivalent(e: o.Expression): boolean {
return e instanceof TrackContextExpr && e.view === this.view;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(): void {}
override clone(): TrackContextExpr {
return new TrackContextExpr(this.view);
}
}
/**
* Runtime operation to navigate to the next view context in the view hierarchy.
*/
export class NextContextExpr extends ExpressionBase {
override readonly kind = ExpressionKind.NextContext;
steps = 1;
constructor() {
super();
}
override visitExpression(): void {}
override isEquivalent(e: o.Expression): boolean {
return e instanceof NextContextExpr && e.steps === this.steps;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(): void {}
override clone(): NextContextExpr {
const expr = new NextContextExpr();
expr.steps = this.steps;
return expr;
}
}
/**
* Runtime operation to snapshot the current view context.
*
* The result of this operation can be stored in a variable and later used with the `RestoreView`
* operation.
*/
export class GetCurrentViewExpr extends ExpressionBase {
override readonly kind = ExpressionKind.GetCurrentView;
constructor() {
super();
}
override visitExpression(): void {}
override isEquivalent(e: o.Expression): boolean {
return e instanceof GetCurrentViewExpr;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(): void {}
override clone(): GetCurrentViewExpr {
return new GetCurrentViewExpr();
}
}
/**
* Runtime operation to restore a snapshotted view.
*/ | {
"end_byte": 8039,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/expression.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/expression.ts_8040_16134 | export class RestoreViewExpr extends ExpressionBase {
override readonly kind = ExpressionKind.RestoreView;
constructor(public view: XrefId | o.Expression) {
super();
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): void {
if (typeof this.view !== 'number') {
this.view.visitExpression(visitor, context);
}
}
override isEquivalent(e: o.Expression): boolean {
if (!(e instanceof RestoreViewExpr) || typeof e.view !== typeof this.view) {
return false;
}
if (typeof this.view === 'number') {
return this.view === e.view;
} else {
return this.view.isEquivalent(e.view as o.Expression);
}
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
if (typeof this.view !== 'number') {
this.view = transformExpressionsInExpression(this.view, transform, flags);
}
}
override clone(): RestoreViewExpr {
return new RestoreViewExpr(this.view instanceof o.Expression ? this.view.clone() : this.view);
}
}
/**
* Runtime operation to reset the current view context after `RestoreView`.
*/
export class ResetViewExpr extends ExpressionBase {
override readonly kind = ExpressionKind.ResetView;
constructor(public expr: o.Expression) {
super();
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): any {
this.expr.visitExpression(visitor, context);
}
override isEquivalent(e: o.Expression): boolean {
return e instanceof ResetViewExpr && this.expr.isEquivalent(e.expr);
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
this.expr = transformExpressionsInExpression(this.expr, transform, flags);
}
override clone(): ResetViewExpr {
return new ResetViewExpr(this.expr.clone());
}
}
export class TwoWayBindingSetExpr extends ExpressionBase {
override readonly kind = ExpressionKind.TwoWayBindingSet;
constructor(
public target: o.Expression,
public value: o.Expression,
) {
super();
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): void {
this.target.visitExpression(visitor, context);
this.value.visitExpression(visitor, context);
}
override isEquivalent(other: TwoWayBindingSetExpr): boolean {
return this.target.isEquivalent(other.target) && this.value.isEquivalent(other.value);
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(transform: ExpressionTransform, flags: VisitorContextFlag) {
this.target = transformExpressionsInExpression(this.target, transform, flags);
this.value = transformExpressionsInExpression(this.value, transform, flags);
}
override clone(): TwoWayBindingSetExpr {
return new TwoWayBindingSetExpr(this.target, this.value);
}
}
/**
* Read of a variable declared as an `ir.VariableOp` and referenced through its `ir.XrefId`.
*/
export class ReadVariableExpr extends ExpressionBase {
override readonly kind = ExpressionKind.ReadVariable;
name: string | null = null;
constructor(readonly xref: XrefId) {
super();
}
override visitExpression(): void {}
override isEquivalent(other: o.Expression): boolean {
return other instanceof ReadVariableExpr && other.xref === this.xref;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(): void {}
override clone(): ReadVariableExpr {
const expr = new ReadVariableExpr(this.xref);
expr.name = this.name;
return expr;
}
}
export class PureFunctionExpr
extends ExpressionBase
implements ConsumesVarsTrait, UsesVarOffsetTrait
{
override readonly kind = ExpressionKind.PureFunctionExpr;
readonly [ConsumesVarsTrait] = true;
readonly [UsesVarOffset] = true;
varOffset: number | null = null;
/**
* The expression which should be memoized as a pure computation.
*
* This expression contains internal `PureFunctionParameterExpr`s, which are placeholders for the
* positional argument expressions in `args.
*/
body: o.Expression | null;
/**
* Positional arguments to the pure function which will memoize the `body` expression, which act
* as memoization keys.
*/
args: o.Expression[];
/**
* Once extracted to the `ConstantPool`, a reference to the function which defines the computation
* of `body`.
*/
fn: o.Expression | null = null;
constructor(expression: o.Expression | null, args: o.Expression[]) {
super();
this.body = expression;
this.args = args;
}
override visitExpression(visitor: o.ExpressionVisitor, context: any) {
this.body?.visitExpression(visitor, context);
for (const arg of this.args) {
arg.visitExpression(visitor, context);
}
}
override isEquivalent(other: o.Expression): boolean {
if (!(other instanceof PureFunctionExpr) || other.args.length !== this.args.length) {
return false;
}
return (
other.body !== null &&
this.body !== null &&
other.body.isEquivalent(this.body) &&
other.args.every((arg, idx) => arg.isEquivalent(this.args[idx]))
);
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
if (this.body !== null) {
// TODO: figure out if this is the right flag to pass here.
this.body = transformExpressionsInExpression(
this.body,
transform,
flags | VisitorContextFlag.InChildOperation,
);
} else if (this.fn !== null) {
this.fn = transformExpressionsInExpression(this.fn, transform, flags);
}
for (let i = 0; i < this.args.length; i++) {
this.args[i] = transformExpressionsInExpression(this.args[i], transform, flags);
}
}
override clone(): PureFunctionExpr {
const expr = new PureFunctionExpr(
this.body?.clone() ?? null,
this.args.map((arg) => arg.clone()),
);
expr.fn = this.fn?.clone() ?? null;
expr.varOffset = this.varOffset;
return expr;
}
}
export class PureFunctionParameterExpr extends ExpressionBase {
override readonly kind = ExpressionKind.PureFunctionParameterExpr;
constructor(public index: number) {
super();
}
override visitExpression(): void {}
override isEquivalent(other: o.Expression): boolean {
return other instanceof PureFunctionParameterExpr && other.index === this.index;
}
override isConstant(): boolean {
return true;
}
override transformInternalExpressions(): void {}
override clone(): PureFunctionParameterExpr {
return new PureFunctionParameterExpr(this.index);
}
}
export class PipeBindingExpr
extends ExpressionBase
implements ConsumesVarsTrait, UsesVarOffsetTrait
{
override readonly kind = ExpressionKind.PipeBinding;
readonly [ConsumesVarsTrait] = true;
readonly [UsesVarOffset] = true;
varOffset: number | null = null;
constructor(
readonly target: XrefId,
readonly targetSlot: SlotHandle,
readonly name: string,
readonly args: o.Expression[],
) {
super();
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): void {
for (const arg of this.args) {
arg.visitExpression(visitor, context);
}
}
override isEquivalent(): boolean {
return false;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
for (let idx = 0; idx < this.args.length; idx++) {
this.args[idx] = transformExpressionsInExpression(this.args[idx], transform, flags);
}
}
override clone() {
const r = new PipeBindingExpr(
this.target,
this.targetSlot,
this.name,
this.args.map((a) => a.clone()),
);
r.varOffset = this.varOffset;
return r;
}
} | {
"end_byte": 16134,
"start_byte": 8040,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/expression.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/expression.ts_16136_25102 | export class PipeBindingVariadicExpr
extends ExpressionBase
implements ConsumesVarsTrait, UsesVarOffsetTrait
{
override readonly kind = ExpressionKind.PipeBindingVariadic;
readonly [ConsumesVarsTrait] = true;
readonly [UsesVarOffset] = true;
varOffset: number | null = null;
constructor(
readonly target: XrefId,
readonly targetSlot: SlotHandle,
readonly name: string,
public args: o.Expression,
public numArgs: number,
) {
super();
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): void {
this.args.visitExpression(visitor, context);
}
override isEquivalent(): boolean {
return false;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
this.args = transformExpressionsInExpression(this.args, transform, flags);
}
override clone(): PipeBindingVariadicExpr {
const r = new PipeBindingVariadicExpr(
this.target,
this.targetSlot,
this.name,
this.args.clone(),
this.numArgs,
);
r.varOffset = this.varOffset;
return r;
}
}
export class SafePropertyReadExpr extends ExpressionBase {
override readonly kind = ExpressionKind.SafePropertyRead;
constructor(
public receiver: o.Expression,
public name: string,
) {
super();
}
// An alias for name, which allows other logic to handle property reads and keyed reads together.
get index() {
return this.name;
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): any {
this.receiver.visitExpression(visitor, context);
}
override isEquivalent(): boolean {
return false;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
this.receiver = transformExpressionsInExpression(this.receiver, transform, flags);
}
override clone(): SafePropertyReadExpr {
return new SafePropertyReadExpr(this.receiver.clone(), this.name);
}
}
export class SafeKeyedReadExpr extends ExpressionBase {
override readonly kind = ExpressionKind.SafeKeyedRead;
constructor(
public receiver: o.Expression,
public index: o.Expression,
sourceSpan: ParseSourceSpan | null,
) {
super(sourceSpan);
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): any {
this.receiver.visitExpression(visitor, context);
this.index.visitExpression(visitor, context);
}
override isEquivalent(): boolean {
return false;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
this.receiver = transformExpressionsInExpression(this.receiver, transform, flags);
this.index = transformExpressionsInExpression(this.index, transform, flags);
}
override clone(): SafeKeyedReadExpr {
return new SafeKeyedReadExpr(this.receiver.clone(), this.index.clone(), this.sourceSpan);
}
}
export class SafeInvokeFunctionExpr extends ExpressionBase {
override readonly kind = ExpressionKind.SafeInvokeFunction;
constructor(
public receiver: o.Expression,
public args: o.Expression[],
) {
super();
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): any {
this.receiver.visitExpression(visitor, context);
for (const a of this.args) {
a.visitExpression(visitor, context);
}
}
override isEquivalent(): boolean {
return false;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
this.receiver = transformExpressionsInExpression(this.receiver, transform, flags);
for (let i = 0; i < this.args.length; i++) {
this.args[i] = transformExpressionsInExpression(this.args[i], transform, flags);
}
}
override clone(): SafeInvokeFunctionExpr {
return new SafeInvokeFunctionExpr(
this.receiver.clone(),
this.args.map((a) => a.clone()),
);
}
}
export class SafeTernaryExpr extends ExpressionBase {
override readonly kind = ExpressionKind.SafeTernaryExpr;
constructor(
public guard: o.Expression,
public expr: o.Expression,
) {
super();
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): any {
this.guard.visitExpression(visitor, context);
this.expr.visitExpression(visitor, context);
}
override isEquivalent(): boolean {
return false;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
this.guard = transformExpressionsInExpression(this.guard, transform, flags);
this.expr = transformExpressionsInExpression(this.expr, transform, flags);
}
override clone(): SafeTernaryExpr {
return new SafeTernaryExpr(this.guard.clone(), this.expr.clone());
}
}
export class EmptyExpr extends ExpressionBase {
override readonly kind = ExpressionKind.EmptyExpr;
override visitExpression(visitor: o.ExpressionVisitor, context: any): any {}
override isEquivalent(e: Expression): boolean {
return e instanceof EmptyExpr;
}
override isConstant() {
return true;
}
override clone(): EmptyExpr {
return new EmptyExpr();
}
override transformInternalExpressions(): void {}
}
export class AssignTemporaryExpr extends ExpressionBase {
override readonly kind = ExpressionKind.AssignTemporaryExpr;
public name: string | null = null;
constructor(
public expr: o.Expression,
public xref: XrefId,
) {
super();
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): any {
this.expr.visitExpression(visitor, context);
}
override isEquivalent(): boolean {
return false;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
this.expr = transformExpressionsInExpression(this.expr, transform, flags);
}
override clone(): AssignTemporaryExpr {
const a = new AssignTemporaryExpr(this.expr.clone(), this.xref);
a.name = this.name;
return a;
}
}
export class ReadTemporaryExpr extends ExpressionBase {
override readonly kind = ExpressionKind.ReadTemporaryExpr;
public name: string | null = null;
constructor(public xref: XrefId) {
super();
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): any {}
override isEquivalent(): boolean {
return this.xref === this.xref;
}
override isConstant(): boolean {
return false;
}
override transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {}
override clone(): ReadTemporaryExpr {
const r = new ReadTemporaryExpr(this.xref);
r.name = this.name;
return r;
}
}
export class SlotLiteralExpr extends ExpressionBase {
override readonly kind = ExpressionKind.SlotLiteralExpr;
constructor(readonly slot: SlotHandle) {
super();
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): any {}
override isEquivalent(e: Expression): boolean {
return e instanceof SlotLiteralExpr && e.slot === this.slot;
}
override isConstant() {
return true;
}
override clone(): SlotLiteralExpr {
return new SlotLiteralExpr(this.slot);
}
override transformInternalExpressions(): void {}
}
export class ConditionalCaseExpr extends ExpressionBase {
override readonly kind = ExpressionKind.ConditionalCase;
/**
* Create an expression for one branch of a conditional.
* @param expr The expression to be tested for this case. Might be null, as in an `else` case.
* @param target The Xref of the view to be displayed if this condition is true.
*/
constructor(
public expr: o.Expression | null,
readonly target: XrefId,
readonly targetSlot: SlotHandle,
readonly alias: t.Variable | null = null,
) {
super();
}
override visitExpression(visitor: o.ExpressionVisitor, context: any): any {
if (this.expr !== null) {
this.expr.visitExpression(visitor, context);
}
}
override isEquivalent(e: Expression): boolean {
return e instanceof ConditionalCaseExpr && e.expr === this.expr;
}
override isConstant() {
return true;
}
override clone(): ConditionalCaseExpr {
return new ConditionalCaseExpr(this.expr, this.target, this.targetSlot);
}
override transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
if (this.expr !== null) {
this.expr = transformExpressionsInExpression(this.expr, transform, flags);
}
}
} | {
"end_byte": 25102,
"start_byte": 16136,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/expression.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/expression.ts_25104_32439 | export class ConstCollectedExpr extends ExpressionBase {
override readonly kind = ExpressionKind.ConstCollected;
constructor(public expr: o.Expression) {
super();
}
override transformInternalExpressions(
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
this.expr = transform(this.expr, flags);
}
override visitExpression(visitor: o.ExpressionVisitor, context: any) {
this.expr.visitExpression(visitor, context);
}
override isEquivalent(e: o.Expression): boolean {
if (!(e instanceof ConstCollectedExpr)) {
return false;
}
return this.expr.isEquivalent(e.expr);
}
override isConstant(): boolean {
return this.expr.isConstant();
}
override clone(): ConstCollectedExpr {
return new ConstCollectedExpr(this.expr);
}
}
/**
* Visits all `Expression`s in the AST of `op` with the `visitor` function.
*/
export function visitExpressionsInOp(
op: CreateOp | UpdateOp,
visitor: (expr: o.Expression, flags: VisitorContextFlag) => void,
): void {
transformExpressionsInOp(
op,
(expr, flags) => {
visitor(expr, flags);
return expr;
},
VisitorContextFlag.None,
);
}
export enum VisitorContextFlag {
None = 0b0000,
InChildOperation = 0b0001,
}
function transformExpressionsInInterpolation(
interpolation: Interpolation,
transform: ExpressionTransform,
flags: VisitorContextFlag,
) {
for (let i = 0; i < interpolation.expressions.length; i++) {
interpolation.expressions[i] = transformExpressionsInExpression(
interpolation.expressions[i],
transform,
flags,
);
}
}
/**
* Transform all `Expression`s in the AST of `op` with the `transform` function.
*
* All such operations will be replaced with the result of applying `transform`, which may be an
* identity transformation.
*/
export function transformExpressionsInOp(
op: CreateOp | UpdateOp,
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
switch (op.kind) {
case OpKind.StyleProp:
case OpKind.StyleMap:
case OpKind.ClassProp:
case OpKind.ClassMap:
case OpKind.Binding:
if (op.expression instanceof Interpolation) {
transformExpressionsInInterpolation(op.expression, transform, flags);
} else {
op.expression = transformExpressionsInExpression(op.expression, transform, flags);
}
break;
case OpKind.Property:
case OpKind.HostProperty:
case OpKind.Attribute:
if (op.expression instanceof Interpolation) {
transformExpressionsInInterpolation(op.expression, transform, flags);
} else {
op.expression = transformExpressionsInExpression(op.expression, transform, flags);
}
op.sanitizer =
op.sanitizer && transformExpressionsInExpression(op.sanitizer, transform, flags);
break;
case OpKind.TwoWayProperty:
op.expression = transformExpressionsInExpression(op.expression, transform, flags);
op.sanitizer =
op.sanitizer && transformExpressionsInExpression(op.sanitizer, transform, flags);
break;
case OpKind.I18nExpression:
op.expression = transformExpressionsInExpression(op.expression, transform, flags);
break;
case OpKind.InterpolateText:
transformExpressionsInInterpolation(op.interpolation, transform, flags);
break;
case OpKind.Statement:
transformExpressionsInStatement(op.statement, transform, flags);
break;
case OpKind.Variable:
op.initializer = transformExpressionsInExpression(op.initializer, transform, flags);
break;
case OpKind.Conditional:
for (const condition of op.conditions) {
if (condition.expr === null) {
// This is a default case.
continue;
}
condition.expr = transformExpressionsInExpression(condition.expr, transform, flags);
}
if (op.processed !== null) {
op.processed = transformExpressionsInExpression(op.processed, transform, flags);
}
if (op.contextValue !== null) {
op.contextValue = transformExpressionsInExpression(op.contextValue, transform, flags);
}
break;
case OpKind.Listener:
case OpKind.TwoWayListener:
for (const innerOp of op.handlerOps) {
transformExpressionsInOp(innerOp, transform, flags | VisitorContextFlag.InChildOperation);
}
break;
case OpKind.ExtractedAttribute:
op.expression =
op.expression && transformExpressionsInExpression(op.expression, transform, flags);
op.trustedValueFn =
op.trustedValueFn && transformExpressionsInExpression(op.trustedValueFn, transform, flags);
break;
case OpKind.RepeaterCreate:
op.track = transformExpressionsInExpression(op.track, transform, flags);
if (op.trackByFn !== null) {
op.trackByFn = transformExpressionsInExpression(op.trackByFn, transform, flags);
}
break;
case OpKind.Repeater:
op.collection = transformExpressionsInExpression(op.collection, transform, flags);
break;
case OpKind.Defer:
if (op.loadingConfig !== null) {
op.loadingConfig = transformExpressionsInExpression(op.loadingConfig, transform, flags);
}
if (op.placeholderConfig !== null) {
op.placeholderConfig = transformExpressionsInExpression(
op.placeholderConfig,
transform,
flags,
);
}
if (op.resolverFn !== null) {
op.resolverFn = transformExpressionsInExpression(op.resolverFn, transform, flags);
}
break;
case OpKind.I18nMessage:
for (const [placeholder, expr] of op.params) {
op.params.set(placeholder, transformExpressionsInExpression(expr, transform, flags));
}
for (const [placeholder, expr] of op.postprocessingParams) {
op.postprocessingParams.set(
placeholder,
transformExpressionsInExpression(expr, transform, flags),
);
}
break;
case OpKind.DeferWhen:
op.expr = transformExpressionsInExpression(op.expr, transform, flags);
break;
case OpKind.StoreLet:
op.value = transformExpressionsInExpression(op.value, transform, flags);
break;
case OpKind.Advance:
case OpKind.Container:
case OpKind.ContainerEnd:
case OpKind.ContainerStart:
case OpKind.DeferOn:
case OpKind.DisableBindings:
case OpKind.Element:
case OpKind.ElementEnd:
case OpKind.ElementStart:
case OpKind.EnableBindings:
case OpKind.I18n:
case OpKind.I18nApply:
case OpKind.I18nContext:
case OpKind.I18nEnd:
case OpKind.I18nStart:
case OpKind.IcuEnd:
case OpKind.IcuStart:
case OpKind.Namespace:
case OpKind.Pipe:
case OpKind.Projection:
case OpKind.ProjectionDef:
case OpKind.Template:
case OpKind.Text:
case OpKind.I18nAttributes:
case OpKind.IcuPlaceholder:
case OpKind.DeclareLet:
// These operations contain no expressions.
break;
default:
throw new Error(`AssertionError: transformExpressionsInOp doesn't handle ${OpKind[op.kind]}`);
}
}
/**
* Transform all `Expression`s in the AST of `expr` with the `transform` function.
*
* All such operations will be replaced with the result of applying `transform`, which may be an
* identity transformation.
*/ | {
"end_byte": 32439,
"start_byte": 25104,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/expression.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/expression.ts_32440_38079 | export function transformExpressionsInExpression(
expr: o.Expression,
transform: ExpressionTransform,
flags: VisitorContextFlag,
): o.Expression {
if (expr instanceof ExpressionBase) {
expr.transformInternalExpressions(transform, flags);
} else if (expr instanceof o.BinaryOperatorExpr) {
expr.lhs = transformExpressionsInExpression(expr.lhs, transform, flags);
expr.rhs = transformExpressionsInExpression(expr.rhs, transform, flags);
} else if (expr instanceof o.UnaryOperatorExpr) {
expr.expr = transformExpressionsInExpression(expr.expr, transform, flags);
} else if (expr instanceof o.ReadPropExpr) {
expr.receiver = transformExpressionsInExpression(expr.receiver, transform, flags);
} else if (expr instanceof o.ReadKeyExpr) {
expr.receiver = transformExpressionsInExpression(expr.receiver, transform, flags);
expr.index = transformExpressionsInExpression(expr.index, transform, flags);
} else if (expr instanceof o.WritePropExpr) {
expr.receiver = transformExpressionsInExpression(expr.receiver, transform, flags);
expr.value = transformExpressionsInExpression(expr.value, transform, flags);
} else if (expr instanceof o.WriteKeyExpr) {
expr.receiver = transformExpressionsInExpression(expr.receiver, transform, flags);
expr.index = transformExpressionsInExpression(expr.index, transform, flags);
expr.value = transformExpressionsInExpression(expr.value, transform, flags);
} else if (expr instanceof o.InvokeFunctionExpr) {
expr.fn = transformExpressionsInExpression(expr.fn, transform, flags);
for (let i = 0; i < expr.args.length; i++) {
expr.args[i] = transformExpressionsInExpression(expr.args[i], transform, flags);
}
} else if (expr instanceof o.LiteralArrayExpr) {
for (let i = 0; i < expr.entries.length; i++) {
expr.entries[i] = transformExpressionsInExpression(expr.entries[i], transform, flags);
}
} else if (expr instanceof o.LiteralMapExpr) {
for (let i = 0; i < expr.entries.length; i++) {
expr.entries[i].value = transformExpressionsInExpression(
expr.entries[i].value,
transform,
flags,
);
}
} else if (expr instanceof o.ConditionalExpr) {
expr.condition = transformExpressionsInExpression(expr.condition, transform, flags);
expr.trueCase = transformExpressionsInExpression(expr.trueCase, transform, flags);
if (expr.falseCase !== null) {
expr.falseCase = transformExpressionsInExpression(expr.falseCase, transform, flags);
}
} else if (expr instanceof o.TypeofExpr) {
expr.expr = transformExpressionsInExpression(expr.expr, transform, flags);
} else if (expr instanceof o.WriteVarExpr) {
expr.value = transformExpressionsInExpression(expr.value, transform, flags);
} else if (expr instanceof o.LocalizedString) {
for (let i = 0; i < expr.expressions.length; i++) {
expr.expressions[i] = transformExpressionsInExpression(expr.expressions[i], transform, flags);
}
} else if (expr instanceof o.NotExpr) {
expr.condition = transformExpressionsInExpression(expr.condition, transform, flags);
} else if (expr instanceof o.TaggedTemplateExpr) {
expr.tag = transformExpressionsInExpression(expr.tag, transform, flags);
expr.template.expressions = expr.template.expressions.map((e) =>
transformExpressionsInExpression(e, transform, flags),
);
} else if (expr instanceof o.ArrowFunctionExpr) {
if (Array.isArray(expr.body)) {
for (let i = 0; i < expr.body.length; i++) {
transformExpressionsInStatement(expr.body[i], transform, flags);
}
} else {
expr.body = transformExpressionsInExpression(expr.body, transform, flags);
}
} else if (expr instanceof o.WrappedNodeExpr) {
// TODO: Do we need to transform any TS nodes nested inside of this expression?
} else if (
expr instanceof o.ReadVarExpr ||
expr instanceof o.ExternalExpr ||
expr instanceof o.LiteralExpr
) {
// No action for these types.
} else {
throw new Error(`Unhandled expression kind: ${expr.constructor.name}`);
}
return transform(expr, flags);
}
/**
* Transform all `Expression`s in the AST of `stmt` with the `transform` function.
*
* All such operations will be replaced with the result of applying `transform`, which may be an
* identity transformation.
*/
export function transformExpressionsInStatement(
stmt: o.Statement,
transform: ExpressionTransform,
flags: VisitorContextFlag,
): void {
if (stmt instanceof o.ExpressionStatement) {
stmt.expr = transformExpressionsInExpression(stmt.expr, transform, flags);
} else if (stmt instanceof o.ReturnStatement) {
stmt.value = transformExpressionsInExpression(stmt.value, transform, flags);
} else if (stmt instanceof o.DeclareVarStmt) {
if (stmt.value !== undefined) {
stmt.value = transformExpressionsInExpression(stmt.value, transform, flags);
}
} else if (stmt instanceof o.IfStmt) {
stmt.condition = transformExpressionsInExpression(stmt.condition, transform, flags);
for (const caseStatement of stmt.trueCase) {
transformExpressionsInStatement(caseStatement, transform, flags);
}
for (const caseStatement of stmt.falseCase) {
transformExpressionsInStatement(caseStatement, transform, flags);
}
} else {
throw new Error(`Unhandled statement kind: ${stmt.constructor.name}`);
}
}
/**
* Checks whether the given expression is a string literal.
*/
export function isStringLiteral(expr: o.Expression): expr is o.LiteralExpr & {value: string} {
return expr instanceof o.LiteralExpr && typeof expr.value === 'string';
} | {
"end_byte": 38079,
"start_byte": 32440,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/expression.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/traits.ts_0_5089 | /**
* @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 type {ParseSourceSpan} from '../../../../parse_util';
import type {Expression} from './expression';
import * as o from '../../../../output/output_ast';
import type {Op, XrefId} from './operations';
import {SlotHandle} from './handle';
/**
* Marker symbol for `ConsumesSlotOpTrait`.
*/
export const ConsumesSlot = Symbol('ConsumesSlot');
/**
* Marker symbol for `DependsOnSlotContextOpTrait`.
*/
export const DependsOnSlotContext = Symbol('DependsOnSlotContext');
/**
* Marker symbol for `ConsumesVars` trait.
*/
export const ConsumesVarsTrait = Symbol('ConsumesVars');
/**
* Marker symbol for `UsesVarOffset` trait.
*/
export const UsesVarOffset = Symbol('UsesVarOffset');
/**
* Marks an operation as requiring allocation of one or more data slots for storage.
*/
export interface ConsumesSlotOpTrait {
readonly [ConsumesSlot]: true;
/**
* Assigned data slot (the starting index, if more than one slot is needed) for this operation, or
* `null` if slots have not yet been assigned.
*/
handle: SlotHandle;
/**
* The number of slots which will be used by this operation. By default 1, but can be increased if
* necessary.
*/
numSlotsUsed: number;
/**
* `XrefId` of this operation (e.g. the element stored in the assigned slot). This `XrefId` is
* used to link this `ConsumesSlotOpTrait` operation with `DependsOnSlotContextTrait` or
* `UsesSlotIndexExprTrait` implementors and ensure that the assigned slot is propagated through
* the IR to all consumers.
*/
xref: XrefId;
}
/**
* Marks an operation as depending on the runtime's implicit slot context being set to a particular
* slot.
*
* The runtime has an implicit slot context which is adjusted using the `advance()` instruction
* during the execution of template update functions. This trait marks an operation as requiring
* this implicit context to be `advance()`'d to point at a particular slot prior to execution.
*/
export interface DependsOnSlotContextOpTrait {
readonly [DependsOnSlotContext]: true;
/**
* `XrefId` of the `ConsumesSlotOpTrait` which the implicit slot context must reference before
* this operation can be executed.
*/
target: XrefId;
sourceSpan: ParseSourceSpan;
}
/**
* Marker trait indicating that an operation or expression consumes variable storage space.
*/
export interface ConsumesVarsTrait {
[ConsumesVarsTrait]: true;
}
/**
* Marker trait indicating that an expression requires knowledge of the number of variable storage
* slots used prior to it.
*/
export interface UsesVarOffsetTrait {
[UsesVarOffset]: true;
varOffset: number | null;
}
/**
* Default values for most `ConsumesSlotOpTrait` fields (used with the spread operator to initialize
* implementors of the trait).
*/
export const TRAIT_CONSUMES_SLOT: Omit<ConsumesSlotOpTrait, 'xref' | 'handle'> = {
[ConsumesSlot]: true,
numSlotsUsed: 1,
} as const;
/**
* Default values for most `DependsOnSlotContextOpTrait` fields (used with the spread operator to
* initialize implementors of the trait).
*/
export const TRAIT_DEPENDS_ON_SLOT_CONTEXT: Omit<
DependsOnSlotContextOpTrait,
'target' | 'sourceSpan'
> = {
[DependsOnSlotContext]: true,
} as const;
/**
* Default values for `UsesVars` fields (used with the spread operator to initialize
* implementors of the trait).
*/
export const TRAIT_CONSUMES_VARS: ConsumesVarsTrait = {
[ConsumesVarsTrait]: true,
} as const;
/**
* Test whether an operation implements `ConsumesSlotOpTrait`.
*/
export function hasConsumesSlotTrait<OpT extends Op<OpT>>(
op: OpT,
): op is OpT & ConsumesSlotOpTrait {
return (op as Partial<ConsumesSlotOpTrait>)[ConsumesSlot] === true;
}
/**
* Test whether an operation implements `DependsOnSlotContextOpTrait`.
*/
export function hasDependsOnSlotContextTrait<ExprT extends o.Expression>(
expr: ExprT,
): expr is ExprT & DependsOnSlotContextOpTrait;
export function hasDependsOnSlotContextTrait<OpT extends Op<OpT>>(
op: OpT,
): op is OpT & DependsOnSlotContextOpTrait;
export function hasDependsOnSlotContextTrait(value: any): boolean {
return (value as Partial<DependsOnSlotContextOpTrait>)[DependsOnSlotContext] === true;
}
/**
* Test whether an operation implements `ConsumesVarsTrait`.
*/
export function hasConsumesVarsTrait<ExprT extends Expression>(
expr: ExprT,
): expr is ExprT & ConsumesVarsTrait;
export function hasConsumesVarsTrait<OpT extends Op<OpT>>(op: OpT): op is OpT & ConsumesVarsTrait;
export function hasConsumesVarsTrait(value: any): boolean {
return (value as Partial<ConsumesVarsTrait>)[ConsumesVarsTrait] === true;
}
/**
* Test whether an expression implements `UsesVarOffsetTrait`.
*/
export function hasUsesVarOffsetTrait<ExprT extends Expression>(
expr: ExprT,
): expr is ExprT & UsesVarOffsetTrait {
return (expr as Partial<UsesVarOffsetTrait>)[UsesVarOffset] === true;
}
| {
"end_byte": 5089,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/traits.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/operations.ts_0_1500 | /**
* @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 {OpKind} from './enums';
/**
* Branded type for a cross-reference ID. During ingest, `XrefId`s are generated to link together
* different IR operations which need to reference each other.
*/
export type XrefId = number & {__brand: 'XrefId'};
/**
* Base interface for semantic operations being performed within a template.
*
* @param OpT a specific narrower type of `Op` (for example, creation operations) which this
* specific subtype of `Op` can be linked with in a linked list.
*/
export interface Op<OpT extends Op<OpT>> {
/**
* All operations have a distinct kind.
*/
kind: OpKind;
/**
* The previous operation in the linked list, if any.
*
* This is `null` for operation nodes not currently in a list, or for the special head/tail nodes.
*/
prev: OpT | null;
/**
* The next operation in the linked list, if any.
*
* This is `null` for operation nodes not currently in a list, or for the special head/tail nodes.
*/
next: OpT | null;
/**
* Debug id of the list to which this node currently belongs, or `null` if this node is not part
* of a list.
*/
debugListId: number | null;
}
/**
* A linked list of `Op` nodes of a given subtype.
*
* @param OpT specific subtype of `Op` nodes which this list contains.
*/ | {
"end_byte": 1500,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/operations.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/operations.ts_1501_8464 | export class OpList<OpT extends Op<OpT>> {
static nextListId = 0;
/**
* Debug ID of this `OpList` instance.
*/
readonly debugListId = OpList.nextListId++;
// OpList uses static head/tail nodes of a special `ListEnd` type.
// This avoids the need for special casing of the first and last list
// elements in all list operations.
readonly head: OpT = {
kind: OpKind.ListEnd,
next: null,
prev: null,
debugListId: this.debugListId,
} as OpT;
readonly tail = {
kind: OpKind.ListEnd,
next: null,
prev: null,
debugListId: this.debugListId,
} as OpT;
constructor() {
// Link `head` and `tail` together at the start (list is empty).
this.head.next = this.tail;
this.tail.prev = this.head;
}
/**
* Push a new operation to the tail of the list.
*/
push(op: OpT | Array<OpT>): void {
if (Array.isArray(op)) {
for (const o of op) {
this.push(o);
}
return;
}
OpList.assertIsNotEnd(op);
OpList.assertIsUnowned(op);
op.debugListId = this.debugListId;
// The old "previous" node (which might be the head, if the list is empty).
const oldLast = this.tail.prev!;
// Insert `op` following the old last node.
op.prev = oldLast;
oldLast.next = op;
// Connect `op` with the list tail.
op.next = this.tail;
this.tail.prev = op;
}
/**
* Prepend one or more nodes to the start of the list.
*/
prepend(ops: OpT[]): void {
if (ops.length === 0) {
return;
}
for (const op of ops) {
OpList.assertIsNotEnd(op);
OpList.assertIsUnowned(op);
op.debugListId = this.debugListId;
}
const first = this.head.next!;
let prev = this.head;
for (const op of ops) {
prev.next = op;
op.prev = prev;
prev = op;
}
prev.next = first;
first.prev = prev;
}
/**
* `OpList` is iterable via the iteration protocol.
*
* It's safe to mutate the part of the list that has already been returned by the iterator, up to
* and including the last operation returned. Mutations beyond that point _may_ be safe, but may
* also corrupt the iteration position and should be avoided.
*/
*[Symbol.iterator](): Generator<OpT> {
let current = this.head.next!;
while (current !== this.tail) {
// Guards against corruption of the iterator state by mutations to the tail of the list during
// iteration.
OpList.assertIsOwned(current, this.debugListId);
const next = current.next!;
yield current;
current = next;
}
}
*reversed(): Generator<OpT> {
let current = this.tail.prev!;
while (current !== this.head) {
OpList.assertIsOwned(current, this.debugListId);
const prev = current.prev!;
yield current;
current = prev;
}
}
/**
* Replace `oldOp` with `newOp` in the list.
*/
static replace<OpT extends Op<OpT>>(oldOp: OpT, newOp: OpT): void {
OpList.assertIsNotEnd(oldOp);
OpList.assertIsNotEnd(newOp);
OpList.assertIsOwned(oldOp);
OpList.assertIsUnowned(newOp);
newOp.debugListId = oldOp.debugListId;
if (oldOp.prev !== null) {
oldOp.prev.next = newOp;
newOp.prev = oldOp.prev;
}
if (oldOp.next !== null) {
oldOp.next.prev = newOp;
newOp.next = oldOp.next;
}
oldOp.debugListId = null;
oldOp.prev = null;
oldOp.next = null;
}
/**
* Replace `oldOp` with some number of new operations in the list (which may include `oldOp`).
*/
static replaceWithMany<OpT extends Op<OpT>>(oldOp: OpT, newOps: OpT[]): void {
if (newOps.length === 0) {
// Replacing with an empty list -> pure removal.
OpList.remove(oldOp);
return;
}
OpList.assertIsNotEnd(oldOp);
OpList.assertIsOwned(oldOp);
const listId = oldOp.debugListId;
oldOp.debugListId = null;
for (const newOp of newOps) {
OpList.assertIsNotEnd(newOp);
// `newOp` might be `oldOp`, but at this point it's been marked as unowned.
OpList.assertIsUnowned(newOp);
}
// It should be safe to reuse `oldOp` in the `newOps` list - maybe you want to sandwich an
// operation between two new ops.
const {prev: oldPrev, next: oldNext} = oldOp;
oldOp.prev = null;
oldOp.next = null;
let prev: OpT = oldPrev!;
for (const newOp of newOps) {
this.assertIsUnowned(newOp);
newOp.debugListId = listId;
prev!.next = newOp;
newOp.prev = prev;
// This _should_ be the case, but set it just in case.
newOp.next = null;
prev = newOp;
}
// At the end of iteration, `prev` holds the last node in the list.
const first = newOps[0]!;
const last = prev!;
// Replace `oldOp` with the chain `first` -> `last`.
if (oldPrev !== null) {
oldPrev.next = first;
first.prev = oldPrev;
}
if (oldNext !== null) {
oldNext.prev = last;
last.next = oldNext;
}
}
/**
* Remove the given node from the list which contains it.
*/
static remove<OpT extends Op<OpT>>(op: OpT): void {
OpList.assertIsNotEnd(op);
OpList.assertIsOwned(op);
op.prev!.next = op.next;
op.next!.prev = op.prev;
// Break any link between the node and this list to safeguard against its usage in future
// operations.
op.debugListId = null;
op.prev = null;
op.next = null;
}
/**
* Insert `op` before `target`.
*/
static insertBefore<OpT extends Op<OpT>>(op: OpT | OpT[], target: OpT): void {
if (Array.isArray(op)) {
for (const o of op) {
this.insertBefore(o, target);
}
return;
}
OpList.assertIsOwned(target);
if (target.prev === null) {
throw new Error(`AssertionError: illegal operation on list start`);
}
OpList.assertIsNotEnd(op);
OpList.assertIsUnowned(op);
op.debugListId = target.debugListId;
// Just in case.
op.prev = null;
target.prev!.next = op;
op.prev = target.prev;
op.next = target;
target.prev = op;
}
/**
* Insert `op` after `target`.
*/
static insertAfter<OpT extends Op<OpT>>(op: OpT, target: OpT): void {
OpList.assertIsOwned(target);
if (target.next === null) {
throw new Error(`AssertionError: illegal operation on list end`);
}
OpList.assertIsNotEnd(op);
OpList.assertIsUnowned(op);
op.debugListId = target.debugListId;
target.next.prev = op;
op.next = target.next;
op.prev = target;
target.next = op;
}
/**
* Asserts that `op` does not currently belong to a list.
*/
static assertIsUnowned<OpT extends Op<OpT>>(op: OpT): void {
if (op.debugListId !== null) {
throw new Error(`AssertionError: illegal operation on owned node: ${OpKind[op.kind]}`);
}
}
/**
* Asserts that `op` currently belongs to a list. If `byList` is passed, `op` is asserted to
* specifically belong to that list.
*/ | {
"end_byte": 8464,
"start_byte": 1501,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/operations.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/operations.ts_8467_9150 | static assertIsOwned<OpT extends Op<OpT>>(op: OpT, byList?: number): void {
if (op.debugListId === null) {
throw new Error(`AssertionError: illegal operation on unowned node: ${OpKind[op.kind]}`);
} else if (byList !== undefined && op.debugListId !== byList) {
throw new Error(
`AssertionError: node belongs to the wrong list (expected ${byList}, actual ${op.debugListId})`,
);
}
}
/**
* Asserts that `op` is not a special `ListEnd` node.
*/
static assertIsNotEnd<OpT extends Op<OpT>>(op: OpT): void {
if (op.kind === OpKind.ListEnd) {
throw new Error(`AssertionError: illegal operation on list head or tail`);
}
}
} | {
"end_byte": 9150,
"start_byte": 8467,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/operations.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/variable.ts_0_2147 | /**
* @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 type {SemanticVariableKind} from './enums';
import type {XrefId} from './operations';
/**
* Union type for the different kinds of variables.
*/
export type SemanticVariable =
| ContextVariable
| IdentifierVariable
| SavedViewVariable
| AliasVariable;
export interface SemanticVariableBase {
kind: SemanticVariableKind;
/**
* Name assigned to this variable in generated code, or `null` if not yet assigned.
*/
name: string | null;
}
/**
* When referenced in the template's context parameters, this indicates a reference to the entire
* context object, rather than a specific parameter.
*/
export const CTX_REF = 'CTX_REF_MARKER';
/**
* A variable that represents the context of a particular view.
*/
export interface ContextVariable extends SemanticVariableBase {
kind: SemanticVariableKind.Context;
/**
* `XrefId` of the view that this variable represents.
*/
view: XrefId;
}
/**
* A variable that represents a specific identifier within a template.
*/
export interface IdentifierVariable extends SemanticVariableBase {
kind: SemanticVariableKind.Identifier;
/**
* The identifier whose value in the template is tracked in this variable.
*/
identifier: string;
/**
* Whether the variable was declared locally within the same view or somewhere else.
*/
local: boolean;
}
/**
* A variable that represents a saved view context.
*/
export interface SavedViewVariable extends SemanticVariableBase {
kind: SemanticVariableKind.SavedView;
/**
* The view context saved in this variable.
*/
view: XrefId;
}
/**
* A variable that will be inlined at every location it is used. An alias is also allowed to depend
* on the value of a semantic variable.
*/
export interface AliasVariable extends SemanticVariableBase {
kind: SemanticVariableKind.Alias;
identifier: string;
expression: o.Expression;
}
| {
"end_byte": 2147,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/variable.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/handle.ts_0_262 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export class SlotHandle {
slot: number | null = null;
}
| {
"end_byte": 262,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/handle.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/enums.ts_0_7873 | /**
* @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
*/
/**
* Distinguishes different kinds of IR operations.
*
* Includes both creation and update operations.
*/
export enum OpKind {
/**
* A special operation type which is used to represent the beginning and end nodes of a linked
* list of operations.
*/
ListEnd,
/**
* An operation which wraps an output AST statement.
*/
Statement,
/**
* An operation which declares and initializes a `SemanticVariable`.
*/
Variable,
/**
* An operation to begin rendering of an element.
*/
ElementStart,
/**
* An operation to render an element with no children.
*/
Element,
/**
* An operation which declares an embedded view.
*/
Template,
/**
* An operation to end rendering of an element previously started with `ElementStart`.
*/
ElementEnd,
/**
* An operation to begin an `ng-container`.
*/
ContainerStart,
/**
* An operation for an `ng-container` with no children.
*/
Container,
/**
* An operation to end an `ng-container`.
*/
ContainerEnd,
/**
* An operation disable binding for subsequent elements, which are descendants of a non-bindable
* node.
*/
DisableBindings,
/**
* An op to conditionally render a template.
*/
Conditional,
/**
* An operation to re-enable binding, after it was previously disabled.
*/
EnableBindings,
/**
* An operation to render a text node.
*/
Text,
/**
* An operation declaring an event listener for an element.
*/
Listener,
/**
* An operation to interpolate text into a text node.
*/
InterpolateText,
/**
* An intermediate binding op, that has not yet been processed into an individual property,
* attribute, style, etc.
*/
Binding,
/**
* An operation to bind an expression to a property of an element.
*/
Property,
/**
* An operation to bind an expression to a style property of an element.
*/
StyleProp,
/**
* An operation to bind an expression to a class property of an element.
*/
ClassProp,
/**
* An operation to bind an expression to the styles of an element.
*/
StyleMap,
/**
* An operation to bind an expression to the classes of an element.
*/
ClassMap,
/**
* An operation to advance the runtime's implicit slot context during the update phase of a view.
*/
Advance,
/**
* An operation to instantiate a pipe.
*/
Pipe,
/**
* An operation to associate an attribute with an element.
*/
Attribute,
/**
* An attribute that has been extracted for inclusion in the consts array.
*/
ExtractedAttribute,
/**
* An operation that configures a `@defer` block.
*/
Defer,
/**
* An operation that controls when a `@defer` loads.
*/
DeferOn,
/**
* An operation that controls when a `@defer` loads, using a custom expression as the condition.
*/
DeferWhen,
/**
* An i18n message that has been extracted for inclusion in the consts array.
*/
I18nMessage,
/**
* A host binding property.
*/
HostProperty,
/**
* A namespace change, which causes the subsequent elements to be processed as either HTML or SVG.
*/
Namespace,
/**
* Configure a content projeciton definition for the view.
*/
ProjectionDef,
/**
* Create a content projection slot.
*/
Projection,
/**
* Create a repeater creation instruction op.
*/
RepeaterCreate,
/**
* An update up for a repeater.
*/
Repeater,
/**
* An operation to bind an expression to the property side of a two-way binding.
*/
TwoWayProperty,
/**
* An operation declaring the event side of a two-way binding.
*/
TwoWayListener,
/**
* A creation-time operation that initializes the slot for a `@let` declaration.
*/
DeclareLet,
/**
* An update-time operation that stores the current value of a `@let` declaration.
*/
StoreLet,
/**
* The start of an i18n block.
*/
I18nStart,
/**
* A self-closing i18n on a single element.
*/
I18n,
/**
* The end of an i18n block.
*/
I18nEnd,
/**
* An expression in an i18n message.
*/
I18nExpression,
/**
* An instruction that applies a set of i18n expressions.
*/
I18nApply,
/**
* An instruction to create an ICU expression.
*/
IcuStart,
/**
* An instruction to update an ICU expression.
*/
IcuEnd,
/**
* An instruction representing a placeholder in an ICU expression.
*/
IcuPlaceholder,
/**
* An i18n context containing information needed to generate an i18n message.
*/
I18nContext,
/**
* A creation op that corresponds to i18n attributes on an element.
*/
I18nAttributes,
}
/**
* Distinguishes different kinds of IR expressions.
*/
export enum ExpressionKind {
/**
* Read of a variable in a lexical scope.
*/
LexicalRead,
/**
* A reference to the current view context.
*/
Context,
/**
* A reference to the view context, for use inside a track function.
*/
TrackContext,
/**
* Read of a variable declared in a `VariableOp`.
*/
ReadVariable,
/**
* Runtime operation to navigate to the next view context in the view hierarchy.
*/
NextContext,
/**
* Runtime operation to retrieve the value of a local reference.
*/
Reference,
/**
* A call storing the value of a `@let` declaration.
*/
StoreLet,
/**
* A reference to a `@let` declaration read from the context view.
*/
ContextLetReference,
/**
* Runtime operation to snapshot the current view context.
*/
GetCurrentView,
/**
* Runtime operation to restore a snapshotted view.
*/
RestoreView,
/**
* Runtime operation to reset the current view context after `RestoreView`.
*/
ResetView,
/**
* Defines and calls a function with change-detected arguments.
*/
PureFunctionExpr,
/**
* Indicates a positional parameter to a pure function definition.
*/
PureFunctionParameterExpr,
/**
* Binding to a pipe transformation.
*/
PipeBinding,
/**
* Binding to a pipe transformation with a variable number of arguments.
*/
PipeBindingVariadic,
/*
* A safe property read requiring expansion into a null check.
*/
SafePropertyRead,
/**
* A safe keyed read requiring expansion into a null check.
*/
SafeKeyedRead,
/**
* A safe function call requiring expansion into a null check.
*/
SafeInvokeFunction,
/**
* An intermediate expression that will be expanded from a safe read into an explicit ternary.
*/
SafeTernaryExpr,
/**
* An empty expression that will be stipped before generating the final output.
*/
EmptyExpr,
/*
* An assignment to a temporary variable.
*/
AssignTemporaryExpr,
/**
* A reference to a temporary variable.
*/
ReadTemporaryExpr,
/**
* An expression that will cause a literal slot index to be emitted.
*/
SlotLiteralExpr,
/**
* A test expression for a conditional op.
*/
ConditionalCase,
/**
* An expression that will be automatically extracted to the component const array.
*/
ConstCollected,
/**
* Operation that sets the value of a two-way binding.
*/
TwoWayBindingSet,
}
export enum VariableFlags {
None = 0b0000,
/**
* Always inline this variable, regardless of the number of times it's used.
* An `AlwaysInline` variable may not depend on context, because doing so may cause side effects
* that are illegal when multi-inlined. (The optimizer will enforce this constraint.)
*/
AlwaysInline = 0b0001,
}
/**
* Distinguishes between different kinds of `SemanticVariable`s.
*/ | {
"end_byte": 7873,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/enums.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/enums.ts_7874_11193 | export enum SemanticVariableKind {
/**
* Represents the context of a particular view.
*/
Context,
/**
* Represents an identifier declared in the lexical scope of a view.
*/
Identifier,
/**
* Represents a saved state that can be used to restore a view in a listener handler function.
*/
SavedView,
/**
* An alias generated by a special embedded view type (e.g. a `@for` block).
*/
Alias,
}
/**
* Whether to compile in compatibilty mode. In compatibility mode, the template pipeline will
* attempt to match the output of `TemplateDefinitionBuilder` as exactly as possible, at the cost
* of producing quirky or larger code in some cases.
*/
export enum CompatibilityMode {
Normal,
TemplateDefinitionBuilder,
}
/**
* Enumeration of the types of attributes which can be applied to an element.
*/
export enum BindingKind {
/**
* Static attributes.
*/
Attribute,
/**
* Class bindings.
*/
ClassName,
/**
* Style bindings.
*/
StyleProperty,
/**
* Dynamic property bindings.
*/
Property,
/**
* Property or attribute bindings on a template.
*/
Template,
/**
* Internationalized attributes.
*/
I18n,
/**
* Animation property bindings.
*/
Animation,
/**
* Property side of a two-way binding.
*/
TwoWayProperty,
}
/**
* Enumeration of possible times i18n params can be resolved.
*/
export enum I18nParamResolutionTime {
/**
* Param is resolved at message creation time. Most params should be resolved at message creation
* time. However, ICU params need to be handled in post-processing.
*/
Creation,
/**
* Param is resolved during post-processing. This should be used for params whose value comes from
* an ICU.
*/
Postproccessing,
}
/**
* The contexts in which an i18n expression can be used.
*/
export enum I18nExpressionFor {
/**
* This expression is used as a value (i.e. inside an i18n block).
*/
I18nText,
/**
* This expression is used in a binding.
*/
I18nAttribute,
}
/**
* Flags that describe what an i18n param value. These determine how the value is serialized into
* the final map.
*/
export enum I18nParamValueFlags {
None = 0b0000,
/**
* This value represents an element tag.
*/
ElementTag = 0b1,
/**
* This value represents a template tag.
*/
TemplateTag = 0b10,
/**
* This value represents the opening of a tag.
*/
OpenTag = 0b0100,
/**
* This value represents the closing of a tag.
*/
CloseTag = 0b1000,
/**
* This value represents an i18n expression index.
*/
ExpressionIndex = 0b10000,
}
/**
* Whether the active namespace is HTML, MathML, or SVG mode.
*/
export enum Namespace {
HTML,
SVG,
Math,
}
/**
* The type of a `@defer` trigger, for use in the ir.
*/
export enum DeferTriggerKind {
Idle,
Immediate,
Timer,
Hover,
Interaction,
Viewport,
Never,
}
/**
* Kinds of i18n contexts. They can be created because of root i18n blocks, or ICUs.
*/
export enum I18nContextKind {
RootI18n,
Icu,
Attr,
}
export enum TemplateKind {
NgTemplate,
Structural,
Block,
}
/**
* Kinds of modifiers for a defer block.
*/
export const enum DeferOpModifierKind {
NONE = 'none',
PREFETCH = 'prefetch',
HYDRATE = 'hydrate',
} | {
"end_byte": 11193,
"start_byte": 7874,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/enums.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/ops/shared.ts_0_2490 | /**
* @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 {OpKind, VariableFlags} from '../enums';
import {Op, XrefId} from '../operations';
import {SemanticVariable} from '../variable';
/**
* A special `Op` which is used internally in the `OpList` linked list to represent the head and
* tail nodes of the list.
*
* `ListEndOp` is created internally in the `OpList` and should not be instantiated directly.
*/
export interface ListEndOp<OpT extends Op<OpT>> extends Op<OpT> {
kind: OpKind.ListEnd;
}
/**
* An `Op` which directly wraps an output `Statement`.
*
* Often `StatementOp`s are the final result of IR processing.
*/
export interface StatementOp<OpT extends Op<OpT>> extends Op<OpT> {
kind: OpKind.Statement;
/**
* The output statement.
*/
statement: o.Statement;
}
/**
* Create a `StatementOp`.
*/
export function createStatementOp<OpT extends Op<OpT>>(statement: o.Statement): StatementOp<OpT> {
return {
kind: OpKind.Statement,
statement,
...NEW_OP,
};
}
/**
* Operation which declares and initializes a `SemanticVariable`, that is valid either in create or
* update IR.
*/
export interface VariableOp<OpT extends Op<OpT>> extends Op<OpT> {
kind: OpKind.Variable;
/**
* `XrefId` which identifies this specific variable, and is used to reference this variable from
* other parts of the IR.
*/
xref: XrefId;
/**
* The `SemanticVariable` which describes the meaning behind this variable.
*/
variable: SemanticVariable;
/**
* Expression representing the value of the variable.
*/
initializer: o.Expression;
flags: VariableFlags;
}
/**
* Create a `VariableOp`.
*/
export function createVariableOp<OpT extends Op<OpT>>(
xref: XrefId,
variable: SemanticVariable,
initializer: o.Expression,
flags: VariableFlags,
): VariableOp<OpT> {
return {
kind: OpKind.Variable,
xref,
variable,
initializer,
flags,
...NEW_OP,
};
}
/**
* Static structure shared by all operations.
*
* Used as a convenience via the spread operator (`...NEW_OP`) when creating new operations, and
* ensures the fields are always in the same order.
*/
export const NEW_OP: Pick<Op<any>, 'debugListId' | 'prev' | 'next'> = {
debugListId: null,
prev: null,
next: null,
};
| {
"end_byte": 2490,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/ops/shared.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/ops/host.ts_0_1538 | /**
* @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 '../../../../../../src/output/output_ast';
import {ParseSourceSpan} from '../../../../../../src/parse_util';
import {SecurityContext} from '../../../../../core';
import {OpKind} from '../enums';
import {Op, XrefId} from '../operations';
import {ConsumesVarsTrait, TRAIT_CONSUMES_VARS} from '../traits';
import {NEW_OP} from './shared';
import type {Interpolation, UpdateOp} from './update';
/**
* Logical operation representing a host binding to a property.
*/
export interface HostPropertyOp extends Op<UpdateOp>, ConsumesVarsTrait {
kind: OpKind.HostProperty;
name: string;
expression: o.Expression | Interpolation;
isAnimationTrigger: boolean;
i18nContext: XrefId | null;
securityContext: SecurityContext | SecurityContext[];
sanitizer: o.Expression | null;
sourceSpan: ParseSourceSpan | null;
}
export function createHostPropertyOp(
name: string,
expression: o.Expression | Interpolation,
isAnimationTrigger: boolean,
i18nContext: XrefId | null,
securityContext: SecurityContext | SecurityContext[],
sourceSpan: ParseSourceSpan | null,
): HostPropertyOp {
return {
kind: OpKind.HostProperty,
name,
expression,
isAnimationTrigger,
i18nContext,
securityContext,
sanitizer: null,
sourceSpan,
...TRAIT_CONSUMES_VARS,
...NEW_OP,
};
}
| {
"end_byte": 1538,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/ops/host.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/ops/create.ts_0_6886 | /**
* @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 i18n from '../../../../../i18n/i18n_ast';
import * as o from '../../../../../output/output_ast';
import {ParseSourceSpan} from '../../../../../parse_util';
import {
BindingKind,
DeferOpModifierKind,
DeferTriggerKind,
I18nContextKind,
I18nParamValueFlags,
Namespace,
OpKind,
TemplateKind,
} from '../enums';
import {SlotHandle} from '../handle';
import {Op, OpList, XrefId} from '../operations';
import {
ConsumesSlotOpTrait,
ConsumesVarsTrait,
TRAIT_CONSUMES_SLOT,
TRAIT_CONSUMES_VARS,
} from '../traits';
import {ListEndOp, NEW_OP, StatementOp, VariableOp} from './shared';
import type {UpdateOp} from './update';
/**
* An operation usable on the creation side of the IR.
*/
export type CreateOp =
| ListEndOp<CreateOp>
| StatementOp<CreateOp>
| ElementOp
| ElementStartOp
| ElementEndOp
| ContainerOp
| ContainerStartOp
| ContainerEndOp
| TemplateOp
| EnableBindingsOp
| DisableBindingsOp
| TextOp
| ListenerOp
| TwoWayListenerOp
| PipeOp
| VariableOp<CreateOp>
| NamespaceOp
| ProjectionDefOp
| ProjectionOp
| ExtractedAttributeOp
| DeferOp
| DeferOnOp
| RepeaterCreateOp
| I18nMessageOp
| I18nOp
| I18nStartOp
| I18nEndOp
| IcuStartOp
| IcuEndOp
| IcuPlaceholderOp
| I18nContextOp
| I18nAttributesOp
| DeclareLetOp;
/**
* An operation representing the creation of an element or container.
*/
export type ElementOrContainerOps =
| ElementOp
| ElementStartOp
| ContainerOp
| ContainerStartOp
| TemplateOp
| RepeaterCreateOp;
/**
* The set of OpKinds that represent the creation of an element or container
*/
const elementContainerOpKinds = new Set([
OpKind.Element,
OpKind.ElementStart,
OpKind.Container,
OpKind.ContainerStart,
OpKind.Template,
OpKind.RepeaterCreate,
]);
/**
* Checks whether the given operation represents the creation of an element or container.
*/
export function isElementOrContainerOp(op: CreateOp): op is ElementOrContainerOps {
return elementContainerOpKinds.has(op.kind);
}
/**
* Representation of a local reference on an element.
*/
export interface LocalRef {
/**
* User-defined name of the local ref variable.
*/
name: string;
/**
* Target of the local reference variable (often `''`).
*/
target: string;
}
/**
* Base interface for `Element`, `ElementStart`, and `Template` operations, containing common fields
* used to represent their element-like nature.
*/
export interface ElementOrContainerOpBase extends Op<CreateOp>, ConsumesSlotOpTrait {
kind: ElementOrContainerOps['kind'];
/**
* `XrefId` allocated for this element.
*
* This ID is used to reference this element from other IR structures.
*/
xref: XrefId;
/**
* Attributes of various kinds on this element. Represented as a `ConstIndex` pointer into the
* shared `consts` array of the component compilation.
*/
attributes: ConstIndex | null;
/**
* Local references to this element.
*
* Before local ref processing, this is an array of `LocalRef` declarations.
*
* After processing, it's a `ConstIndex` pointer into the shared `consts` array of the component
* compilation.
*/
localRefs: LocalRef[] | ConstIndex | null;
/**
* Whether this container is marked `ngNonBindable`, which disabled Angular binding for itself and
* all descendants.
*/
nonBindable: boolean;
/**
* The span of the element's start tag.
*/
startSourceSpan: ParseSourceSpan;
/**
* The whole source span of the element, including children.
*/
wholeSourceSpan: ParseSourceSpan;
}
export interface ElementOpBase extends ElementOrContainerOpBase {
kind: OpKind.Element | OpKind.ElementStart | OpKind.Template | OpKind.RepeaterCreate;
/**
* The HTML tag name for this element.
*/
tag: string | null;
/**
* The namespace of this element, which controls the preceding namespace instruction.
*/
namespace: Namespace;
}
/**
* Logical operation representing the start of an element in the creation IR.
*/
export interface ElementStartOp extends ElementOpBase {
kind: OpKind.ElementStart;
/**
* The i18n placeholder data associated with this element.
*/
i18nPlaceholder?: i18n.TagPlaceholder;
}
/**
* Create an `ElementStartOp`.
*/
export function createElementStartOp(
tag: string,
xref: XrefId,
namespace: Namespace,
i18nPlaceholder: i18n.TagPlaceholder | undefined,
startSourceSpan: ParseSourceSpan,
wholeSourceSpan: ParseSourceSpan,
): ElementStartOp {
return {
kind: OpKind.ElementStart,
xref,
tag,
handle: new SlotHandle(),
attributes: null,
localRefs: [],
nonBindable: false,
namespace,
i18nPlaceholder,
startSourceSpan,
wholeSourceSpan,
...TRAIT_CONSUMES_SLOT,
...NEW_OP,
};
}
/**
* Logical operation representing an element with no children in the creation IR.
*/
export interface ElementOp extends ElementOpBase {
kind: OpKind.Element;
/**
* The i18n placeholder data associated with this element.
*/
i18nPlaceholder?: i18n.TagPlaceholder;
}
/**
* Logical operation representing an embedded view declaration in the creation IR.
*/
export interface TemplateOp extends ElementOpBase {
kind: OpKind.Template;
templateKind: TemplateKind;
/**
* The number of declaration slots used by this template, or `null` if slots have not yet been
* assigned.
*/
decls: number | null;
/**
* The number of binding variable slots used by this template, or `null` if binding variables have
* not yet been counted.
*/
vars: number | null;
/**
* Suffix to add to the name of the generated template function.
*/
functionNameSuffix: string;
/**
* The i18n placeholder data associated with this template.
*/
i18nPlaceholder?: i18n.TagPlaceholder | i18n.BlockPlaceholder;
}
/**
* Create a `TemplateOp`.
*/
export function createTemplateOp(
xref: XrefId,
templateKind: TemplateKind,
tag: string | null,
functionNameSuffix: string,
namespace: Namespace,
i18nPlaceholder: i18n.TagPlaceholder | i18n.BlockPlaceholder | undefined,
startSourceSpan: ParseSourceSpan,
wholeSourceSpan: ParseSourceSpan,
): TemplateOp {
return {
kind: OpKind.Template,
xref,
templateKind,
attributes: null,
tag,
handle: new SlotHandle(),
functionNameSuffix,
decls: null,
vars: null,
localRefs: [],
nonBindable: false,
namespace,
i18nPlaceholder,
startSourceSpan,
wholeSourceSpan,
...TRAIT_CONSUMES_SLOT,
...NEW_OP,
};
}
/**
* An op that creates a repeater (e.g. a for loop).
*/ | {
"end_byte": 6886,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/ops/create.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/ops/create.ts_6887_14085 | export interface RepeaterCreateOp extends ElementOpBase, ConsumesVarsTrait {
kind: OpKind.RepeaterCreate;
/**
* The number of declaration slots used by this repeater's template, or `null` if slots have not
* yet been assigned.
*/
decls: number | null;
/**
* The number of binding variable slots used by this repeater's, or `null` if binding variables
* have not yet been counted.
*/
vars: number | null;
/**
* The Xref of the empty view function. (For the primary view function, use the `xref` property).
*/
emptyView: XrefId | null;
/**
* The track expression to use while iterating.
*/
track: o.Expression;
/**
* `null` initially, then an `o.Expression`. Might be a track expression, or might be a reference
* into the constant pool.
*/
trackByFn: o.Expression | null;
/**
* Context variables avaialable in this block.
*/
varNames: RepeaterVarNames;
/**
* Whether the repeater track function relies on the component instance.
*/
usesComponentInstance: boolean;
/**
* Suffix to add to the name of the generated template function.
*/
functionNameSuffix: string;
/**
* Tag name for the empty block.
*/
emptyTag: string | null;
/**
* Attributes of various kinds on the empty block. Represented as a `ConstIndex` pointer into the
* shared `consts` array of the component compilation.
*/
emptyAttributes: ConstIndex | null;
/**
* The i18n placeholder for the repeated item template.
*/
i18nPlaceholder: i18n.BlockPlaceholder | undefined;
/**
* The i18n placeholder for the empty template.
*/
emptyI18nPlaceholder: i18n.BlockPlaceholder | undefined;
}
// TODO: add source spans?
export interface RepeaterVarNames {
$index: Set<string>;
$implicit: string;
}
export function createRepeaterCreateOp(
primaryView: XrefId,
emptyView: XrefId | null,
tag: string | null,
track: o.Expression,
varNames: RepeaterVarNames,
emptyTag: string | null,
i18nPlaceholder: i18n.BlockPlaceholder | undefined,
emptyI18nPlaceholder: i18n.BlockPlaceholder | undefined,
startSourceSpan: ParseSourceSpan,
wholeSourceSpan: ParseSourceSpan,
): RepeaterCreateOp {
return {
kind: OpKind.RepeaterCreate,
attributes: null,
xref: primaryView,
handle: new SlotHandle(),
emptyView,
track,
trackByFn: null,
tag,
emptyTag,
emptyAttributes: null,
functionNameSuffix: 'For',
namespace: Namespace.HTML,
nonBindable: false,
localRefs: [],
decls: null,
vars: null,
varNames,
usesComponentInstance: false,
i18nPlaceholder,
emptyI18nPlaceholder,
startSourceSpan,
wholeSourceSpan,
...TRAIT_CONSUMES_SLOT,
...NEW_OP,
...TRAIT_CONSUMES_VARS,
numSlotsUsed: emptyView === null ? 2 : 3,
};
}
/**
* Logical operation representing the end of an element structure in the creation IR.
*
* Pairs with an `ElementStart` operation.
*/
export interface ElementEndOp extends Op<CreateOp> {
kind: OpKind.ElementEnd;
/**
* The `XrefId` of the element declared via `ElementStart`.
*/
xref: XrefId;
sourceSpan: ParseSourceSpan | null;
}
/**
* Create an `ElementEndOp`.
*/
export function createElementEndOp(xref: XrefId, sourceSpan: ParseSourceSpan | null): ElementEndOp {
return {
kind: OpKind.ElementEnd,
xref,
sourceSpan,
...NEW_OP,
};
}
/**
* Logical operation representing the start of a container in the creation IR.
*/
export interface ContainerStartOp extends ElementOrContainerOpBase {
kind: OpKind.ContainerStart;
}
/**
* Logical operation representing an empty container in the creation IR.
*/
export interface ContainerOp extends ElementOrContainerOpBase {
kind: OpKind.Container;
}
/**
* Logical operation representing the end of a container structure in the creation IR.
*
* Pairs with an `ContainerStart` operation.
*/
export interface ContainerEndOp extends Op<CreateOp> {
kind: OpKind.ContainerEnd;
/**
* The `XrefId` of the element declared via `ContainerStart`.
*/
xref: XrefId;
sourceSpan: ParseSourceSpan;
}
/**
* Logical operation causing binding to be disabled in descendents of a non-bindable container.
*/
export interface DisableBindingsOp extends Op<CreateOp> {
kind: OpKind.DisableBindings;
/**
* `XrefId` of the element that was marked non-bindable.
*/
xref: XrefId;
}
export function createDisableBindingsOp(xref: XrefId): DisableBindingsOp {
return {
kind: OpKind.DisableBindings,
xref,
...NEW_OP,
};
}
/**
* Logical operation causing binding to be re-enabled after visiting descendants of a
* non-bindable container.
*/
export interface EnableBindingsOp extends Op<CreateOp> {
kind: OpKind.EnableBindings;
/**
* `XrefId` of the element that was marked non-bindable.
*/
xref: XrefId;
}
export function createEnableBindingsOp(xref: XrefId): EnableBindingsOp {
return {
kind: OpKind.EnableBindings,
xref,
...NEW_OP,
};
}
/**
* Logical operation representing a text node in the creation IR.
*/
export interface TextOp extends Op<CreateOp>, ConsumesSlotOpTrait {
kind: OpKind.Text;
/**
* `XrefId` used to reference this text node in other IR structures.
*/
xref: XrefId;
/**
* The static initial value of the text node.
*/
initialValue: string;
/**
* The placeholder for this text in its parent ICU. If this text is not part of an ICU, the
* placeholder is null.
*/
icuPlaceholder: string | null;
sourceSpan: ParseSourceSpan | null;
}
/**
* Create a `TextOp`.
*/
export function createTextOp(
xref: XrefId,
initialValue: string,
icuPlaceholder: string | null,
sourceSpan: ParseSourceSpan | null,
): TextOp {
return {
kind: OpKind.Text,
xref,
handle: new SlotHandle(),
initialValue,
icuPlaceholder,
sourceSpan,
...TRAIT_CONSUMES_SLOT,
...NEW_OP,
};
}
/**
* Logical operation representing an event listener on an element in the creation IR.
*/
export interface ListenerOp extends Op<CreateOp> {
kind: OpKind.Listener;
target: XrefId;
targetSlot: SlotHandle;
/**
* Whether this listener is from a host binding.
*/
hostListener: boolean;
/**
* Name of the event which is being listened to.
*/
name: string;
/**
* Tag name of the element on which this listener is placed. Might be null, if this listener
* belongs to a host binding.
*/
tag: string | null;
/**
* A list of `UpdateOp`s representing the body of the event listener.
*/
handlerOps: OpList<UpdateOp>;
/**
* Name of the function
*/
handlerFnName: string | null;
/**
* Whether this listener is known to consume `$event` in its body.
*/
consumesDollarEvent: boolean;
/**
* Whether the listener is listening for an animation event.
*/
isAnimationListener: boolean;
/**
* The animation phase of the listener.
*/
animationPhase: string | null;
/**
* Some event listeners can have a target, e.g. in `document:dragover`.
*/
eventTarget: string | null;
sourceSpan: ParseSourceSpan;
}
/**
* Create a `ListenerOp`. Host bindings reuse all the listener logic.
*/ | {
"end_byte": 14085,
"start_byte": 6887,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/ops/create.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/ops/create.ts_14086_21025 | export function createListenerOp(
target: XrefId,
targetSlot: SlotHandle,
name: string,
tag: string | null,
handlerOps: Array<UpdateOp>,
animationPhase: string | null,
eventTarget: string | null,
hostListener: boolean,
sourceSpan: ParseSourceSpan,
): ListenerOp {
const handlerList = new OpList<UpdateOp>();
handlerList.push(handlerOps);
return {
kind: OpKind.Listener,
target,
targetSlot,
tag,
hostListener,
name,
handlerOps: handlerList,
handlerFnName: null,
consumesDollarEvent: false,
isAnimationListener: animationPhase !== null,
animationPhase,
eventTarget,
sourceSpan,
...NEW_OP,
};
}
/**
* Logical operation representing the event side of a two-way binding on an element
* in the creation IR.
*/
export interface TwoWayListenerOp extends Op<CreateOp> {
kind: OpKind.TwoWayListener;
target: XrefId;
targetSlot: SlotHandle;
/**
* Name of the event which is being listened to.
*/
name: string;
/**
* Tag name of the element on which this listener is placed.
*/
tag: string | null;
/**
* A list of `UpdateOp`s representing the body of the event listener.
*/
handlerOps: OpList<UpdateOp>;
/**
* Name of the function
*/
handlerFnName: string | null;
sourceSpan: ParseSourceSpan;
}
/**
* Create a `TwoWayListenerOp`.
*/
export function createTwoWayListenerOp(
target: XrefId,
targetSlot: SlotHandle,
name: string,
tag: string | null,
handlerOps: Array<UpdateOp>,
sourceSpan: ParseSourceSpan,
): TwoWayListenerOp {
const handlerList = new OpList<UpdateOp>();
handlerList.push(handlerOps);
return {
kind: OpKind.TwoWayListener,
target,
targetSlot,
tag,
name,
handlerOps: handlerList,
handlerFnName: null,
sourceSpan,
...NEW_OP,
};
}
export interface PipeOp extends Op<CreateOp>, ConsumesSlotOpTrait {
kind: OpKind.Pipe;
xref: XrefId;
name: string;
}
export function createPipeOp(xref: XrefId, slot: SlotHandle, name: string): PipeOp {
return {
kind: OpKind.Pipe,
xref,
handle: slot,
name,
...NEW_OP,
...TRAIT_CONSUMES_SLOT,
};
}
/**
* An op corresponding to a namespace instruction, for switching between HTML, SVG, and MathML.
*/
export interface NamespaceOp extends Op<CreateOp> {
kind: OpKind.Namespace;
active: Namespace;
}
export function createNamespaceOp(namespace: Namespace): NamespaceOp {
return {
kind: OpKind.Namespace,
active: namespace,
...NEW_OP,
};
}
/**
* An op that creates a content projection slot.
*/
export interface ProjectionDefOp extends Op<CreateOp> {
kind: OpKind.ProjectionDef;
// The parsed selector information for this projection def.
def: o.Expression | null;
}
export function createProjectionDefOp(def: o.Expression | null): ProjectionDefOp {
return {
kind: OpKind.ProjectionDef,
def,
...NEW_OP,
};
}
/**
* An op that creates a content projection slot.
*/
export interface ProjectionOp extends Op<CreateOp>, ConsumesSlotOpTrait {
kind: OpKind.Projection;
xref: XrefId;
projectionSlotIndex: number;
attributes: null | o.LiteralArrayExpr;
localRefs: string[];
selector: string;
i18nPlaceholder?: i18n.TagPlaceholder;
sourceSpan: ParseSourceSpan;
fallbackView: XrefId | null;
}
export function createProjectionOp(
xref: XrefId,
selector: string,
i18nPlaceholder: i18n.TagPlaceholder | undefined,
fallbackView: XrefId | null,
sourceSpan: ParseSourceSpan,
): ProjectionOp {
return {
kind: OpKind.Projection,
xref,
handle: new SlotHandle(),
selector,
i18nPlaceholder,
fallbackView,
projectionSlotIndex: 0,
attributes: null,
localRefs: [],
sourceSpan,
...NEW_OP,
...TRAIT_CONSUMES_SLOT,
numSlotsUsed: fallbackView === null ? 1 : 2,
};
}
/**
* Represents an attribute that has been extracted for inclusion in the consts array.
*/
export interface ExtractedAttributeOp extends Op<CreateOp> {
kind: OpKind.ExtractedAttribute;
/**
* The `XrefId` of the template-like element the extracted attribute will belong to.
*/
target: XrefId;
/**
* The kind of binding represented by this extracted attribute.
*/
bindingKind: BindingKind;
/**
* The namespace of the attribute (or null if none).
*/
namespace: string | null;
/**
* The name of the extracted attribute.
*/
name: string;
/**
* The value expression of the extracted attribute.
*/
expression: o.Expression | null;
/**
* If this attribute has a corresponding i18n attribute (e.g. `i18n-foo="m:d"`), then this is the
* i18n context for it.
*/
i18nContext: XrefId | null;
/**
* The security context of the binding.
*/
securityContext: SecurityContext | SecurityContext[];
/**
* The trusted value function for this property.
*/
trustedValueFn: o.Expression | null;
i18nMessage: i18n.Message | null;
}
/**
* Create an `ExtractedAttributeOp`.
*/
export function createExtractedAttributeOp(
target: XrefId,
bindingKind: BindingKind,
namespace: string | null,
name: string,
expression: o.Expression | null,
i18nContext: XrefId | null,
i18nMessage: i18n.Message | null,
securityContext: SecurityContext | SecurityContext[],
): ExtractedAttributeOp {
return {
kind: OpKind.ExtractedAttribute,
target,
bindingKind,
namespace,
name,
expression,
i18nContext,
i18nMessage,
securityContext,
trustedValueFn: null,
...NEW_OP,
};
}
export interface DeferOp extends Op<CreateOp>, ConsumesSlotOpTrait {
kind: OpKind.Defer;
/**
* The xref of this defer op.
*/
xref: XrefId;
/**
* The xref of the main view.
*/
mainView: XrefId;
mainSlot: SlotHandle;
/**
* Secondary loading block associated with this defer op.
*/
loadingView: XrefId | null;
loadingSlot: SlotHandle | null;
/**
* Secondary placeholder block associated with this defer op.
*/
placeholderView: XrefId | null;
placeholderSlot: SlotHandle | null;
/**
* Secondary error block associated with this defer op.
*/
errorView: XrefId | null;
errorSlot: SlotHandle | null;
placeholderMinimumTime: number | null;
loadingMinimumTime: number | null;
loadingAfterTime: number | null;
placeholderConfig: o.Expression | null;
loadingConfig: o.Expression | null;
/**
* Depending on the compilation mode, there can be either one dependency resolution function
* per deferred block or one for the entire template. This field contains the function that
* belongs specifically to the current deferred block.
*/
ownResolverFn: o.Expression | null;
/**
* After processing, the resolver function for the defer deps will be extracted to the constant
* pool, and a reference to that function will be populated here.
*/
resolverFn: o.Expression | null;
sourceSpan: ParseSourceSpan;
} | {
"end_byte": 21025,
"start_byte": 14086,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/ops/create.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/ops/create.ts_21027_28315 | export function createDeferOp(
xref: XrefId,
main: XrefId,
mainSlot: SlotHandle,
ownResolverFn: o.Expression | null,
resolverFn: o.Expression | null,
sourceSpan: ParseSourceSpan,
): DeferOp {
return {
kind: OpKind.Defer,
xref,
handle: new SlotHandle(),
mainView: main,
mainSlot,
loadingView: null,
loadingSlot: null,
loadingConfig: null,
loadingMinimumTime: null,
loadingAfterTime: null,
placeholderView: null,
placeholderSlot: null,
placeholderConfig: null,
placeholderMinimumTime: null,
errorView: null,
errorSlot: null,
ownResolverFn,
resolverFn,
sourceSpan,
...NEW_OP,
...TRAIT_CONSUMES_SLOT,
numSlotsUsed: 2,
};
}
interface DeferTriggerBase {
kind: DeferTriggerKind;
}
interface DeferTriggerWithTargetBase extends DeferTriggerBase {
targetName: string | null;
/**
* The Xref of the targeted name. May be in a different view.
*/
targetXref: XrefId | null;
/**
* The slot index of the named reference, inside the view provided below. This slot may not be
* inside the current view, and is handled specially as a result.
*/
targetSlot: SlotHandle | null;
targetView: XrefId | null;
/**
* Number of steps to walk up or down the view tree to find the target localRef.
*/
targetSlotViewSteps: number | null;
}
interface DeferIdleTrigger extends DeferTriggerBase {
kind: DeferTriggerKind.Idle;
}
interface DeferImmediateTrigger extends DeferTriggerBase {
kind: DeferTriggerKind.Immediate;
}
interface DeferNeverTrigger extends DeferTriggerBase {
kind: DeferTriggerKind.Never;
}
interface DeferHoverTrigger extends DeferTriggerWithTargetBase {
kind: DeferTriggerKind.Hover;
}
interface DeferTimerTrigger extends DeferTriggerBase {
kind: DeferTriggerKind.Timer;
delay: number;
}
interface DeferInteractionTrigger extends DeferTriggerWithTargetBase {
kind: DeferTriggerKind.Interaction;
}
interface DeferViewportTrigger extends DeferTriggerWithTargetBase {
kind: DeferTriggerKind.Viewport;
}
/**
* The union type of all defer trigger interfaces.
*/
export type DeferTrigger =
| DeferIdleTrigger
| DeferImmediateTrigger
| DeferTimerTrigger
| DeferHoverTrigger
| DeferInteractionTrigger
| DeferViewportTrigger
| DeferNeverTrigger;
export interface DeferOnOp extends Op<CreateOp> {
kind: OpKind.DeferOn;
defer: XrefId;
/**
* The trigger for this defer op (e.g. idle, hover, etc).
*/
trigger: DeferTrigger;
/**
* Modifier set on the trigger by the user (e.g. `hydrate`, `prefetch` etc).
*/
modifier: DeferOpModifierKind;
sourceSpan: ParseSourceSpan;
}
export function createDeferOnOp(
defer: XrefId,
trigger: DeferTrigger,
modifier: DeferOpModifierKind,
sourceSpan: ParseSourceSpan,
): DeferOnOp {
return {
kind: OpKind.DeferOn,
defer,
trigger,
modifier,
sourceSpan,
...NEW_OP,
};
}
/**
* Op that reserves a slot during creation time for a `@let` declaration.
*/
export interface DeclareLetOp extends Op<CreateOp>, ConsumesSlotOpTrait {
kind: OpKind.DeclareLet;
xref: XrefId;
sourceSpan: ParseSourceSpan;
declaredName: string;
}
/**
* Creates a `DeclareLetOp`.
*/
export function createDeclareLetOp(
xref: XrefId,
declaredName: string,
sourceSpan: ParseSourceSpan,
): DeclareLetOp {
return {
kind: OpKind.DeclareLet,
xref,
declaredName,
sourceSpan,
handle: new SlotHandle(),
...TRAIT_CONSUMES_SLOT,
...NEW_OP,
};
}
/**
* Represents a single value in an i18n param map. Each placeholder in the map may have multiple of
* these values associated with it.
*/
export interface I18nParamValue {
/**
* The value. This can be either a slot number, special string, or compound-value consisting of an
* element slot number and template slot number.
*/
value: string | number | {element: number; template: number};
/**
* The sub-template index associated with the value.
*/
subTemplateIndex: number | null;
/**
* Flags associated with the value.
*/
flags: I18nParamValueFlags;
}
/**
* Represents an i18n message that has been extracted for inclusion in the consts array.
*/
export interface I18nMessageOp extends Op<CreateOp> {
kind: OpKind.I18nMessage;
/**
* An id used to reference this message.
*/
xref: XrefId;
/**
* The context from which this message was extracted
* TODO: remove this, and add another property here instead to match ExtractedAttributes
*/
i18nContext: XrefId;
/**
* A reference to the i18n op this message was extracted from.
*
* This might be null, which means this message is not associated with a block. This probably
* means it is an i18n attribute's message.
*/
i18nBlock: XrefId | null;
/**
* The i18n message represented by this op.
*/
message: i18n.Message;
/**
* The placeholder used for this message when it is referenced in another message.
* For a top-level message that isn't referenced from another message, this will be null.
*/
messagePlaceholder: string | null;
/**
* Whether this message needs post-processing.
*/
needsPostprocessing: boolean;
/**
* The param map, with placeholders represented as an `Expression`.
*/
params: Map<string, o.Expression>;
/**
* The post-processing param map, with placeholders represented as an `Expression`.
*/
postprocessingParams: Map<string, o.Expression>;
/**
* A list of sub-messages that are referenced by this message.
*/
subMessages: XrefId[];
}
/**
* Create an `ExtractedMessageOp`.
*/
export function createI18nMessageOp(
xref: XrefId,
i18nContext: XrefId,
i18nBlock: XrefId | null,
message: i18n.Message,
messagePlaceholder: string | null,
params: Map<string, o.Expression>,
postprocessingParams: Map<string, o.Expression>,
needsPostprocessing: boolean,
): I18nMessageOp {
return {
kind: OpKind.I18nMessage,
xref,
i18nContext,
i18nBlock,
message,
messagePlaceholder,
params,
postprocessingParams,
needsPostprocessing,
subMessages: [],
...NEW_OP,
};
}
export interface I18nOpBase extends Op<CreateOp>, ConsumesSlotOpTrait {
kind: OpKind.I18nStart | OpKind.I18n;
/**
* `XrefId` allocated for this i18n block.
*/
xref: XrefId;
/**
* A reference to the root i18n block that this one belongs to. For a root i18n block, this is
* the same as xref.
*/
root: XrefId;
/**
* The i18n metadata associated with this op.
*/
message: i18n.Message;
/**
* The index in the consts array where the message i18n message is stored.
*/
messageIndex: ConstIndex | null;
/**
* The index of this sub-block in the i18n message. For a root i18n block, this is null.
*/
subTemplateIndex: number | null;
/**
* The i18n context generated from this block. Initially null, until the context is created.
*/
context: XrefId | null;
sourceSpan: ParseSourceSpan | null;
}
/**
* Represents an empty i18n block.
*/
export interface I18nOp extends I18nOpBase {
kind: OpKind.I18n;
}
/**
* Represents the start of an i18n block.
*/
export interface I18nStartOp extends I18nOpBase {
kind: OpKind.I18nStart;
}
/**
* Create an `I18nStartOp`.
*/ | {
"end_byte": 28315,
"start_byte": 21027,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/ops/create.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/ops/create.ts_28316_34589 | export function createI18nStartOp(
xref: XrefId,
message: i18n.Message,
root: XrefId | undefined,
sourceSpan: ParseSourceSpan | null,
): I18nStartOp {
return {
kind: OpKind.I18nStart,
xref,
handle: new SlotHandle(),
root: root ?? xref,
message,
messageIndex: null,
subTemplateIndex: null,
context: null,
sourceSpan,
...NEW_OP,
...TRAIT_CONSUMES_SLOT,
};
}
/**
* Represents the end of an i18n block.
*/
export interface I18nEndOp extends Op<CreateOp> {
kind: OpKind.I18nEnd;
/**
* The `XrefId` of the `I18nStartOp` that created this block.
*/
xref: XrefId;
sourceSpan: ParseSourceSpan | null;
}
/**
* Create an `I18nEndOp`.
*/
export function createI18nEndOp(xref: XrefId, sourceSpan: ParseSourceSpan | null): I18nEndOp {
return {
kind: OpKind.I18nEnd,
xref,
sourceSpan,
...NEW_OP,
};
}
/**
* An op that represents the start of an ICU expression.
*/
export interface IcuStartOp extends Op<CreateOp> {
kind: OpKind.IcuStart;
/**
* The ID of the ICU.
*/
xref: XrefId;
/**
* The i18n message for this ICU.
*/
message: i18n.Message;
/**
* Placeholder used to reference this ICU in other i18n messages.
*/
messagePlaceholder: string;
/**
* A reference to the i18n context for this op. Initially null, until the context is created.
*/
context: XrefId | null;
sourceSpan: ParseSourceSpan;
}
/**
* Creates an ICU start op.
*/
export function createIcuStartOp(
xref: XrefId,
message: i18n.Message,
messagePlaceholder: string,
sourceSpan: ParseSourceSpan,
): IcuStartOp {
return {
kind: OpKind.IcuStart,
xref,
message,
messagePlaceholder,
context: null,
sourceSpan,
...NEW_OP,
};
}
/**
* An op that represents the end of an ICU expression.
*/
export interface IcuEndOp extends Op<CreateOp> {
kind: OpKind.IcuEnd;
/**
* The ID of the corresponding IcuStartOp.
*/
xref: XrefId;
}
/**
* Creates an ICU end op.
*/
export function createIcuEndOp(xref: XrefId): IcuEndOp {
return {
kind: OpKind.IcuEnd,
xref,
...NEW_OP,
};
}
/**
* An op that represents a placeholder in an ICU expression.
*/
export interface IcuPlaceholderOp extends Op<CreateOp> {
kind: OpKind.IcuPlaceholder;
/**
* The ID of the ICU placeholder.
*/
xref: XrefId;
/**
* The name of the placeholder in the ICU expression.
*/
name: string;
/**
* The static strings to be combined with dynamic expression values to form the text. This works
* like interpolation, but the strings are combined at compile time, using special placeholders
* for the dynamic expressions, and put into the translated message.
*/
strings: string[];
/**
* Placeholder values for the i18n expressions to be combined with the static strings to form the
* full placeholder value.
*/
expressionPlaceholders: I18nParamValue[];
}
/**
* Creates an ICU placeholder op.
*/
export function createIcuPlaceholderOp(
xref: XrefId,
name: string,
strings: string[],
): IcuPlaceholderOp {
return {
kind: OpKind.IcuPlaceholder,
xref,
name,
strings,
expressionPlaceholders: [],
...NEW_OP,
};
}
/**
* An i18n context that is used to generate a translated i18n message. A separate context is created
* for three different scenarios:
*
* 1. For each top-level i18n block.
* 2. For each ICU referenced as a sub-message. ICUs that are referenced as a sub-message will be
* used to generate a separate i18n message, but will not be extracted directly into the consts
* array. Instead they will be pulled in as part of the initialization statements for the message
* that references them.
* 3. For each i18n attribute.
*
* Child i18n blocks, resulting from the use of an ng-template inside of a parent i18n block, do not
* generate a separate context. Instead their content is included in the translated message for
* their root block.
*/
export interface I18nContextOp extends Op<CreateOp> {
kind: OpKind.I18nContext;
contextKind: I18nContextKind;
/**
* The id of this context.
*/
xref: XrefId;
/**
* A reference to the I18nStartOp or I18nOp this context belongs to.
*
* It is possible for multiple contexts to belong to the same block, since both the block and any
* ICUs inside the block will each get their own context.
*
* This might be `null`, in which case the context is not associated with an i18n block. This
* probably means that it belongs to an i18n attribute.
*/
i18nBlock: XrefId | null;
/**
* The i18n message associated with this context.
*/
message: i18n.Message;
/**
* The param map for this context.
*/
params: Map<string, I18nParamValue[]>;
/**
* The post-processing param map for this context.
*/
postprocessingParams: Map<string, I18nParamValue[]>;
sourceSpan: ParseSourceSpan;
}
export function createI18nContextOp(
contextKind: I18nContextKind,
xref: XrefId,
i18nBlock: XrefId | null,
message: i18n.Message,
sourceSpan: ParseSourceSpan,
): I18nContextOp {
if (i18nBlock === null && contextKind !== I18nContextKind.Attr) {
throw new Error('AssertionError: i18nBlock must be provided for non-attribute contexts.');
}
return {
kind: OpKind.I18nContext,
contextKind,
xref,
i18nBlock,
message,
sourceSpan,
params: new Map(),
postprocessingParams: new Map(),
...NEW_OP,
};
}
export interface I18nAttributesOp extends Op<CreateOp>, ConsumesSlotOpTrait {
kind: OpKind.I18nAttributes;
/**
* The element targeted by these attributes.
*/
target: XrefId;
/**
* I18nAttributes instructions correspond to a const array with configuration information.
*/
i18nAttributesConfig: ConstIndex | null;
}
export function createI18nAttributesOp(
xref: XrefId,
handle: SlotHandle,
target: XrefId,
): I18nAttributesOp {
return {
kind: OpKind.I18nAttributes,
xref,
handle,
target,
i18nAttributesConfig: null,
...NEW_OP,
...TRAIT_CONSUMES_SLOT,
};
}
/**
* An index into the `consts` array which is shared across the compilation of all views in a
* component.
*/
export type ConstIndex = number & {__brand: 'ConstIndex'}; | {
"end_byte": 34589,
"start_byte": 28316,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/ops/create.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/ops/update.ts_0_7750 | /**
* @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 i18n from '../../../../../i18n/i18n_ast';
import * as o from '../../../../../output/output_ast';
import {ParseSourceSpan} from '../../../../../parse_util';
import {
BindingKind,
DeferOpModifierKind,
I18nExpressionFor,
I18nParamResolutionTime,
OpKind,
TemplateKind,
} from '../enums';
import type {ConditionalCaseExpr} from '../expression';
import {SlotHandle} from '../handle';
import {Op, XrefId} from '../operations';
import {
ConsumesVarsTrait,
DependsOnSlotContextOpTrait,
TRAIT_CONSUMES_VARS,
TRAIT_DEPENDS_ON_SLOT_CONTEXT,
} from '../traits';
import type {HostPropertyOp} from './host';
import {ListEndOp, NEW_OP, StatementOp, VariableOp} from './shared';
/**
* An operation usable on the update side of the IR.
*/
export type UpdateOp =
| ListEndOp<UpdateOp>
| StatementOp<UpdateOp>
| PropertyOp
| TwoWayPropertyOp
| AttributeOp
| StylePropOp
| ClassPropOp
| StyleMapOp
| ClassMapOp
| InterpolateTextOp
| AdvanceOp
| VariableOp<UpdateOp>
| BindingOp
| HostPropertyOp
| ConditionalOp
| I18nExpressionOp
| I18nApplyOp
| RepeaterOp
| DeferWhenOp
| StoreLetOp;
/**
* A logical operation to perform string interpolation on a text node.
*
* Interpolation inputs are stored as static `string`s and dynamic `o.Expression`s, in separate
* arrays. Thus, the interpolation `A{{b}}C{{d}}E` is stored as 3 static strings `['A', 'C', 'E']`
* and 2 dynamic expressions `[b, d]`.
*/
export interface InterpolateTextOp extends Op<UpdateOp>, ConsumesVarsTrait {
kind: OpKind.InterpolateText;
/**
* Reference to the text node to which the interpolation is bound.
*/
target: XrefId;
/**
* The interpolated value.
*/
interpolation: Interpolation;
sourceSpan: ParseSourceSpan;
}
/**
* Create an `InterpolationTextOp`.
*/
export function createInterpolateTextOp(
xref: XrefId,
interpolation: Interpolation,
sourceSpan: ParseSourceSpan,
): InterpolateTextOp {
return {
kind: OpKind.InterpolateText,
target: xref,
interpolation,
sourceSpan,
...TRAIT_DEPENDS_ON_SLOT_CONTEXT,
...TRAIT_CONSUMES_VARS,
...NEW_OP,
};
}
export class Interpolation {
constructor(
readonly strings: string[],
readonly expressions: o.Expression[],
readonly i18nPlaceholders: string[],
) {
if (i18nPlaceholders.length !== 0 && i18nPlaceholders.length !== expressions.length) {
throw new Error(
`Expected ${expressions.length} placeholders to match interpolation expression count, but got ${i18nPlaceholders.length}`,
);
}
}
}
/**
* An intermediate binding op, that has not yet been processed into an individual property,
* attribute, style, etc.
*/
export interface BindingOp extends Op<UpdateOp> {
kind: OpKind.Binding;
/**
* Reference to the element on which the property is bound.
*/
target: XrefId;
/**
* The kind of binding represented by this op.
*/
bindingKind: BindingKind;
/**
* The name of this binding.
*/
name: string;
/**
* Expression which is bound to the property.
*/
expression: o.Expression | Interpolation;
/**
* The unit of the bound value.
*/
unit: string | null;
/**
* The security context of the binding.
*/
securityContext: SecurityContext | SecurityContext[];
/**
* Whether the binding is a TextAttribute (e.g. `some-attr="some-value"`).
*
* This needs to be tracked for compatibility with `TemplateDefinitionBuilder` which treats
* `style` and `class` TextAttributes differently from `[attr.style]` and `[attr.class]`.
*/
isTextAttribute: boolean;
isStructuralTemplateAttribute: boolean;
/**
* Whether this binding is on a structural template.
*/
templateKind: TemplateKind | null;
i18nContext: XrefId | null;
i18nMessage: i18n.Message | null;
sourceSpan: ParseSourceSpan;
}
/**
* Create a `BindingOp`, not yet transformed into a particular type of binding.
*/
export function createBindingOp(
target: XrefId,
kind: BindingKind,
name: string,
expression: o.Expression | Interpolation,
unit: string | null,
securityContext: SecurityContext | SecurityContext[],
isTextAttribute: boolean,
isStructuralTemplateAttribute: boolean,
templateKind: TemplateKind | null,
i18nMessage: i18n.Message | null,
sourceSpan: ParseSourceSpan,
): BindingOp {
return {
kind: OpKind.Binding,
bindingKind: kind,
target,
name,
expression,
unit,
securityContext,
isTextAttribute,
isStructuralTemplateAttribute,
templateKind,
i18nContext: null,
i18nMessage,
sourceSpan,
...NEW_OP,
};
}
/**
* A logical operation representing binding to a property in the update IR.
*/
export interface PropertyOp extends Op<UpdateOp>, ConsumesVarsTrait, DependsOnSlotContextOpTrait {
kind: OpKind.Property;
/**
* Reference to the element on which the property is bound.
*/
target: XrefId;
/**
* Name of the bound property.
*/
name: string;
/**
* Expression which is bound to the property.
*/
expression: o.Expression | Interpolation;
/**
* Whether this property is an animation trigger.
*/
isAnimationTrigger: boolean;
/**
* The security context of the binding.
*/
securityContext: SecurityContext | SecurityContext[];
/**
* The sanitizer for this property.
*/
sanitizer: o.Expression | null;
isStructuralTemplateAttribute: boolean;
/**
* The kind of template targeted by the binding, or null if this binding does not target a
* template.
*/
templateKind: TemplateKind | null;
i18nContext: XrefId | null;
i18nMessage: i18n.Message | null;
sourceSpan: ParseSourceSpan;
}
/**
* Create a `PropertyOp`.
*/
export function createPropertyOp(
target: XrefId,
name: string,
expression: o.Expression | Interpolation,
isAnimationTrigger: boolean,
securityContext: SecurityContext | SecurityContext[],
isStructuralTemplateAttribute: boolean,
templateKind: TemplateKind | null,
i18nContext: XrefId | null,
i18nMessage: i18n.Message | null,
sourceSpan: ParseSourceSpan,
): PropertyOp {
return {
kind: OpKind.Property,
target,
name,
expression,
isAnimationTrigger,
securityContext,
sanitizer: null,
isStructuralTemplateAttribute,
templateKind,
i18nContext,
i18nMessage,
sourceSpan,
...TRAIT_DEPENDS_ON_SLOT_CONTEXT,
...TRAIT_CONSUMES_VARS,
...NEW_OP,
};
}
/**
* A logical operation representing the property binding side of a two-way binding in the update IR.
*/
export interface TwoWayPropertyOp
extends Op<UpdateOp>,
ConsumesVarsTrait,
DependsOnSlotContextOpTrait {
kind: OpKind.TwoWayProperty;
/**
* Reference to the element on which the property is bound.
*/
target: XrefId;
/**
* Name of the property.
*/
name: string;
/**
* Expression which is bound to the property.
*/
expression: o.Expression;
/**
* The security context of the binding.
*/
securityContext: SecurityContext | SecurityContext[];
/**
* The sanitizer for this property.
*/
sanitizer: o.Expression | null;
isStructuralTemplateAttribute: boolean;
/**
* The kind of template targeted by the binding, or null if this binding does not target a
* template.
*/
templateKind: TemplateKind | null;
i18nContext: XrefId | null;
i18nMessage: i18n.Message | null;
sourceSpan: ParseSourceSpan;
}
/**
* Create a `TwoWayPropertyOp`.
*/ | {
"end_byte": 7750,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/ops/update.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/ops/update.ts_7751_14669 | export function createTwoWayPropertyOp(
target: XrefId,
name: string,
expression: o.Expression,
securityContext: SecurityContext | SecurityContext[],
isStructuralTemplateAttribute: boolean,
templateKind: TemplateKind | null,
i18nContext: XrefId | null,
i18nMessage: i18n.Message | null,
sourceSpan: ParseSourceSpan,
): TwoWayPropertyOp {
return {
kind: OpKind.TwoWayProperty,
target,
name,
expression,
securityContext,
sanitizer: null,
isStructuralTemplateAttribute,
templateKind,
i18nContext,
i18nMessage,
sourceSpan,
...TRAIT_DEPENDS_ON_SLOT_CONTEXT,
...TRAIT_CONSUMES_VARS,
...NEW_OP,
};
}
/**
* A logical operation representing binding to a style property in the update IR.
*/
export interface StylePropOp extends Op<UpdateOp>, ConsumesVarsTrait, DependsOnSlotContextOpTrait {
kind: OpKind.StyleProp;
/**
* Reference to the element on which the property is bound.
*/
target: XrefId;
/**
* Name of the bound property.
*/
name: string;
/**
* Expression which is bound to the property.
*/
expression: o.Expression | Interpolation;
/**
* The unit of the bound value.
*/
unit: string | null;
sourceSpan: ParseSourceSpan;
}
/** Create a `StylePropOp`. */
export function createStylePropOp(
xref: XrefId,
name: string,
expression: o.Expression | Interpolation,
unit: string | null,
sourceSpan: ParseSourceSpan,
): StylePropOp {
return {
kind: OpKind.StyleProp,
target: xref,
name,
expression,
unit,
sourceSpan,
...TRAIT_DEPENDS_ON_SLOT_CONTEXT,
...TRAIT_CONSUMES_VARS,
...NEW_OP,
};
}
/**
* A logical operation representing binding to a class property in the update IR.
*/
export interface ClassPropOp extends Op<UpdateOp>, ConsumesVarsTrait, DependsOnSlotContextOpTrait {
kind: OpKind.ClassProp;
/**
* Reference to the element on which the property is bound.
*/
target: XrefId;
/**
* Name of the bound property.
*/
name: string;
/**
* Expression which is bound to the property.
*/
expression: o.Expression;
sourceSpan: ParseSourceSpan;
}
/**
* Create a `ClassPropOp`.
*/
export function createClassPropOp(
xref: XrefId,
name: string,
expression: o.Expression,
sourceSpan: ParseSourceSpan,
): ClassPropOp {
return {
kind: OpKind.ClassProp,
target: xref,
name,
expression,
sourceSpan,
...TRAIT_DEPENDS_ON_SLOT_CONTEXT,
...TRAIT_CONSUMES_VARS,
...NEW_OP,
};
}
/**
* A logical operation representing binding to a style map in the update IR.
*/
export interface StyleMapOp extends Op<UpdateOp>, ConsumesVarsTrait, DependsOnSlotContextOpTrait {
kind: OpKind.StyleMap;
/**
* Reference to the element on which the property is bound.
*/
target: XrefId;
/**
* Expression which is bound to the property.
*/
expression: o.Expression | Interpolation;
sourceSpan: ParseSourceSpan;
}
/** Create a `StyleMapOp`. */
export function createStyleMapOp(
xref: XrefId,
expression: o.Expression | Interpolation,
sourceSpan: ParseSourceSpan,
): StyleMapOp {
return {
kind: OpKind.StyleMap,
target: xref,
expression,
sourceSpan,
...TRAIT_DEPENDS_ON_SLOT_CONTEXT,
...TRAIT_CONSUMES_VARS,
...NEW_OP,
};
}
/**
* A logical operation representing binding to a style map in the update IR.
*/
export interface ClassMapOp extends Op<UpdateOp>, ConsumesVarsTrait, DependsOnSlotContextOpTrait {
kind: OpKind.ClassMap;
/**
* Reference to the element on which the property is bound.
*/
target: XrefId;
/**
* Expression which is bound to the property.
*/
expression: o.Expression | Interpolation;
sourceSpan: ParseSourceSpan;
}
/**
* Create a `ClassMapOp`.
*/
export function createClassMapOp(
xref: XrefId,
expression: o.Expression | Interpolation,
sourceSpan: ParseSourceSpan,
): ClassMapOp {
return {
kind: OpKind.ClassMap,
target: xref,
expression,
sourceSpan,
...TRAIT_DEPENDS_ON_SLOT_CONTEXT,
...TRAIT_CONSUMES_VARS,
...NEW_OP,
};
}
/**
* A logical operation representing setting an attribute on an element in the update IR.
*/
export interface AttributeOp extends Op<UpdateOp> {
kind: OpKind.Attribute;
/**
* The `XrefId` of the template-like element the attribute will belong to.
*/
target: XrefId;
/**
* The namespace of the attribute (or null if none).
*/
namespace: string | null;
/**
* The name of the attribute.
*/
name: string;
/**
* The value of the attribute.
*/
expression: o.Expression | Interpolation;
/**
* The security context of the binding.
*/
securityContext: SecurityContext | SecurityContext[];
/**
* The sanitizer for this attribute.
*/
sanitizer: o.Expression | null;
/**
* Whether the binding is a TextAttribute (e.g. `some-attr="some-value"`).
*
* This needs to be tracked for compatibility with `TemplateDefinitionBuilder` which treats
* `style` and `class` TextAttributes differently from `[attr.style]` and `[attr.class]`.
*/
isTextAttribute: boolean;
isStructuralTemplateAttribute: boolean;
/**
* The kind of template targeted by the binding, or null if this binding does not target a
* template.
*/
templateKind: TemplateKind | null;
/**
* The i18n context, if this is an i18n attribute.
*/
i18nContext: XrefId | null;
i18nMessage: i18n.Message | null;
sourceSpan: ParseSourceSpan;
}
/**
* Create an `AttributeOp`.
*/
export function createAttributeOp(
target: XrefId,
namespace: string | null,
name: string,
expression: o.Expression | Interpolation,
securityContext: SecurityContext | SecurityContext[],
isTextAttribute: boolean,
isStructuralTemplateAttribute: boolean,
templateKind: TemplateKind | null,
i18nMessage: i18n.Message | null,
sourceSpan: ParseSourceSpan,
): AttributeOp {
return {
kind: OpKind.Attribute,
target,
namespace,
name,
expression,
securityContext,
sanitizer: null,
isTextAttribute,
isStructuralTemplateAttribute,
templateKind,
i18nContext: null,
i18nMessage,
sourceSpan,
...TRAIT_DEPENDS_ON_SLOT_CONTEXT,
...TRAIT_CONSUMES_VARS,
...NEW_OP,
};
}
/**
* Logical operation to advance the runtime's internal slot pointer in the update IR.
*/
export interface AdvanceOp extends Op<UpdateOp> {
kind: OpKind.Advance;
/**
* Delta by which to advance the pointer.
*/
delta: number;
// Source span of the binding that caused the advance
sourceSpan: ParseSourceSpan;
}
/**
* Create an `AdvanceOp`.
*/
export function createAdvanceOp(delta: number, sourceSpan: ParseSourceSpan): AdvanceOp {
return {
kind: OpKind.Advance,
delta,
sourceSpan,
...NEW_OP,
};
}
/**
* Logical operation representing a conditional expression in the update IR.
*/ | {
"end_byte": 14669,
"start_byte": 7751,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/ops/update.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/ops/update.ts_14670_22264 | export interface ConditionalOp
extends Op<ConditionalOp>,
DependsOnSlotContextOpTrait,
ConsumesVarsTrait {
kind: OpKind.Conditional;
/**
* The insertion point, which is the first template in the creation block belonging to this
* condition.
*/
target: XrefId;
/**
* The main test expression (for a switch), or `null` (for an if, which has no test
* expression).
*/
test: o.Expression | null;
/**
* Each possible embedded view that could be displayed has a condition (or is default). This
* structure maps each view xref to its corresponding condition.
*/
conditions: Array<ConditionalCaseExpr>;
/**
* After processing, this will be a single collapsed Joost-expression that evaluates the
* conditions, and yields the slot number of the template which should be displayed.
*/
processed: o.Expression | null;
/**
* Control flow conditionals can accept a context value (this is a result of specifying an
* alias). This expression will be passed to the conditional instruction's context parameter.
*/
contextValue: o.Expression | null;
sourceSpan: ParseSourceSpan;
}
/**
* Create a conditional op, which will display an embedded view according to a condtion.
*/
export function createConditionalOp(
target: XrefId,
test: o.Expression | null,
conditions: Array<ConditionalCaseExpr>,
sourceSpan: ParseSourceSpan,
): ConditionalOp {
return {
kind: OpKind.Conditional,
target,
test,
conditions,
processed: null,
sourceSpan,
contextValue: null,
...NEW_OP,
...TRAIT_DEPENDS_ON_SLOT_CONTEXT,
...TRAIT_CONSUMES_VARS,
};
}
export interface RepeaterOp extends Op<UpdateOp>, DependsOnSlotContextOpTrait {
kind: OpKind.Repeater;
/**
* The RepeaterCreate op associated with this repeater.
*/
target: XrefId;
targetSlot: SlotHandle;
/**
* The collection provided to the for loop as its expression.
*/
collection: o.Expression;
sourceSpan: ParseSourceSpan;
}
export function createRepeaterOp(
repeaterCreate: XrefId,
targetSlot: SlotHandle,
collection: o.Expression,
sourceSpan: ParseSourceSpan,
): RepeaterOp {
return {
kind: OpKind.Repeater,
target: repeaterCreate,
targetSlot,
collection,
sourceSpan,
...NEW_OP,
...TRAIT_DEPENDS_ON_SLOT_CONTEXT,
};
}
export interface DeferWhenOp extends Op<UpdateOp>, DependsOnSlotContextOpTrait, ConsumesVarsTrait {
kind: OpKind.DeferWhen;
/**
* The `defer` create op associated with this when condition.
*/
target: XrefId;
/**
* A user-provided expression that triggers the defer op.
*/
expr: o.Expression;
/**
* Modifier set on the trigger by the user (e.g. `hydrate`, `prefetch` etc).
*/
modifier: DeferOpModifierKind;
sourceSpan: ParseSourceSpan;
}
export function createDeferWhenOp(
target: XrefId,
expr: o.Expression,
modifier: DeferOpModifierKind,
sourceSpan: ParseSourceSpan,
): DeferWhenOp {
return {
kind: OpKind.DeferWhen,
target,
expr,
modifier,
sourceSpan,
...NEW_OP,
...TRAIT_DEPENDS_ON_SLOT_CONTEXT,
...TRAIT_CONSUMES_VARS,
};
}
/**
* An op that represents an expression in an i18n message.
*
* TODO: This can represent expressions used in both i18n attributes and normal i18n content. We
* may want to split these into two different op types, deriving from the same base class.
*/
export interface I18nExpressionOp
extends Op<UpdateOp>,
ConsumesVarsTrait,
DependsOnSlotContextOpTrait {
kind: OpKind.I18nExpression;
/**
* The i18n context that this expression belongs to.
*/
context: XrefId;
/**
* The Xref of the op that we need to `advance` to.
*
* In an i18n block, this is initially the i18n start op, but will eventually correspond to
* the final slot consumer in the owning i18n block.
* TODO: We should make text i18nExpressions target the i18nEnd instruction, instead the last
* slot consumer in the i18n block. This makes them resilient to that last consumer being
* deleted. (Or new slot consumers being added!)
*
* In an i18n attribute, this is the xref of the corresponding elementStart/element.
*/
target: XrefId;
/**
* In an i18n block, this should be the i18n start op.
*
* In an i18n attribute, this will be the xref of the attribute configuration instruction.
*/
i18nOwner: XrefId;
/**
* A handle for the slot that this expression modifies.
* - In an i18n block, this is the handle of the block.
* - In an i18n attribute, this is the handle of the corresponding i18nAttributes instruction.
*/
handle: SlotHandle;
/**
* The expression value.
*/
expression: o.Expression;
icuPlaceholder: XrefId | null;
/**
* The i18n placeholder associated with this expression. This can be null if the expression is
* part of an ICU placeholder. In this case it gets combined with the string literal value and
* other expressions in the ICU placeholder and assigned to the translated message under the ICU
* placeholder name.
*/
i18nPlaceholder: string | null;
/**
* The time that this expression is resolved.
*/
resolutionTime: I18nParamResolutionTime;
/**
* Whether this i18n expression applies to a template or to a binding.
*/
usage: I18nExpressionFor;
/**
* If this is an I18nExpressionContext.Binding, this expression is associated with a named
* attribute. That name is stored here.
*/
name: string;
sourceSpan: ParseSourceSpan;
}
/**
* Create an i18n expression op.
*/
export function createI18nExpressionOp(
context: XrefId,
target: XrefId,
i18nOwner: XrefId,
handle: SlotHandle,
expression: o.Expression,
icuPlaceholder: XrefId | null,
i18nPlaceholder: string | null,
resolutionTime: I18nParamResolutionTime,
usage: I18nExpressionFor,
name: string,
sourceSpan: ParseSourceSpan,
): I18nExpressionOp {
return {
kind: OpKind.I18nExpression,
context,
target,
i18nOwner,
handle,
expression,
icuPlaceholder,
i18nPlaceholder,
resolutionTime,
usage,
name,
sourceSpan,
...NEW_OP,
...TRAIT_CONSUMES_VARS,
...TRAIT_DEPENDS_ON_SLOT_CONTEXT,
};
}
/**
* An op that represents applying a set of i18n expressions.
*/
export interface I18nApplyOp extends Op<UpdateOp> {
kind: OpKind.I18nApply;
/**
* In an i18n block, this should be the i18n start op.
*
* In an i18n attribute, this will be the xref of the attribute configuration instruction.
*/
owner: XrefId;
/**
* A handle for the slot that i18n apply instruction should apply to. In an i18n block, this
* is the slot of the i18n block this expression belongs to. In an i18n attribute, this is the
* slot of the corresponding i18nAttributes instruction.
*/
handle: SlotHandle;
sourceSpan: ParseSourceSpan;
}
/**
* Creates an op to apply i18n expression ops.
*/
export function createI18nApplyOp(
owner: XrefId,
handle: SlotHandle,
sourceSpan: ParseSourceSpan,
): I18nApplyOp {
return {
kind: OpKind.I18nApply,
owner,
handle,
sourceSpan,
...NEW_OP,
};
}
/**
* Op to store the current value of a `@let` declaration.
*/
export interface StoreLetOp extends Op<UpdateOp>, ConsumesVarsTrait {
kind: OpKind.StoreLet;
sourceSpan: ParseSourceSpan;
/** Name that the user set when declaring the `@let`. */
declaredName: string;
/** XrefId of the slot in which the call may write its value. */
target: XrefId;
/** Value of the `@let` declaration. */
value: o.Expression;
} | {
"end_byte": 22264,
"start_byte": 14670,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/ops/update.ts"
} |
angular/packages/compiler/src/template/pipeline/ir/src/ops/update.ts_22266_22629 | /**
* Creates a `StoreLetOp`.
*/
export function createStoreLetOp(
target: XrefId,
declaredName: string,
value: o.Expression,
sourceSpan: ParseSourceSpan,
): StoreLetOp {
return {
kind: OpKind.StoreLet,
target,
declaredName,
value,
sourceSpan,
...TRAIT_DEPENDS_ON_SLOT_CONTEXT,
...TRAIT_CONSUMES_VARS,
...NEW_OP,
};
} | {
"end_byte": 22629,
"start_byte": 22266,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/ir/src/ops/update.ts"
} |
angular/packages/compiler/src/template/pipeline/src/emit.ts_0_5102 | /**
*
* @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 '../../../../src/output/output_ast';
import {ConstantPool} from '../../../constant_pool';
import * as ir from '../ir';
import {
CompilationJob,
CompilationJobKind as Kind,
type ComponentCompilationJob,
type HostBindingCompilationJob,
type ViewCompilationUnit,
} from './compilation';
import {deleteAnyCasts} from './phases/any_cast';
import {applyI18nExpressions} from './phases/apply_i18n_expressions';
import {assignI18nSlotDependencies} from './phases/assign_i18n_slot_dependencies';
import {extractAttributes} from './phases/attribute_extraction';
import {specializeBindings} from './phases/binding_specialization';
import {chain} from './phases/chaining';
import {collapseSingletonInterpolations} from './phases/collapse_singleton_interpolations';
import {generateConditionalExpressions} from './phases/conditionals';
import {collectElementConsts} from './phases/const_collection';
import {convertI18nBindings} from './phases/convert_i18n_bindings';
import {resolveDeferDepsFns} from './phases/resolve_defer_deps_fns';
import {createI18nContexts} from './phases/create_i18n_contexts';
import {deduplicateTextBindings} from './phases/deduplicate_text_bindings';
import {configureDeferInstructions} from './phases/defer_configs';
import {resolveDeferTargetNames} from './phases/defer_resolve_targets';
import {collapseEmptyInstructions} from './phases/empty_elements';
import {expandSafeReads} from './phases/expand_safe_reads';
import {extractI18nMessages} from './phases/extract_i18n_messages';
import {generateAdvance} from './phases/generate_advance';
import {generateProjectionDefs} from './phases/generate_projection_def';
import {generateVariables} from './phases/generate_variables';
import {collectConstExpressions} from './phases/has_const_expression_collection';
import {parseHostStyleProperties} from './phases/host_style_property_parsing';
import {collectI18nConsts} from './phases/i18n_const_collection';
import {convertI18nText} from './phases/i18n_text_extraction';
import {liftLocalRefs} from './phases/local_refs';
import {emitNamespaceChanges} from './phases/namespace';
import {nameFunctionsAndVariables} from './phases/naming';
import {mergeNextContextExpressions} from './phases/next_context_merging';
import {generateNgContainerOps} from './phases/ng_container';
import {disableBindings} from './phases/nonbindable';
import {generateNullishCoalesceExpressions} from './phases/nullish_coalescing';
import {orderOps} from './phases/ordering';
import {parseExtractedStyles} from './phases/parse_extracted_styles';
import {removeContentSelectors} from './phases/phase_remove_content_selectors';
import {createPipes} from './phases/pipe_creation';
import {createVariadicPipes} from './phases/pipe_variadic';
import {propagateI18nBlocks} from './phases/propagate_i18n_blocks';
import {extractPureFunctions} from './phases/pure_function_extraction';
import {generatePureLiteralStructures} from './phases/pure_literal_structures';
import {reify} from './phases/reify';
import {removeEmptyBindings} from './phases/remove_empty_bindings';
import {removeI18nContexts} from './phases/remove_i18n_contexts';
import {removeUnusedI18nAttributesOps} from './phases/remove_unused_i18n_attrs';
import {resolveContexts} from './phases/resolve_contexts';
import {resolveDollarEvent} from './phases/resolve_dollar_event';
import {resolveI18nElementPlaceholders} from './phases/resolve_i18n_element_placeholders';
import {resolveI18nExpressionPlaceholders} from './phases/resolve_i18n_expression_placeholders';
import {resolveNames} from './phases/resolve_names';
import {resolveSanitizers} from './phases/resolve_sanitizers';
import {transformTwoWayBindingSet} from './phases/transform_two_way_binding_set';
import {saveAndRestoreView} from './phases/save_restore_view';
import {allocateSlots} from './phases/slot_allocation';
import {specializeStyleBindings} from './phases/style_binding_specialization';
import {generateTemporaryVariables} from './phases/temporary_variables';
import {generateTrackFns} from './phases/track_fn_generation';
import {optimizeTrackFns} from './phases/track_fn_optimization';
import {generateTrackVariables} from './phases/track_variables';
import {countVariables} from './phases/var_counting';
import {optimizeVariables} from './phases/variable_optimization';
import {wrapI18nIcus} from './phases/wrap_icus';
import {optimizeStoreLet} from './phases/store_let_optimization';
import {removeIllegalLetReferences} from './phases/remove_illegal_let_references';
import {generateLocalLetReferences} from './phases/generate_local_let_references';
type Phase =
| {
fn: (job: CompilationJob) => void;
kind: Kind.Both | Kind.Host | Kind.Tmpl;
}
| {
fn: (job: ComponentCompilationJob) => void;
kind: Kind.Tmpl;
}
| {
fn: (job: HostBindingCompilationJob) => void;
kind: Kind.Host;
}; | {
"end_byte": 5102,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/emit.ts"
} |
angular/packages/compiler/src/template/pipeline/src/emit.ts_5104_12258 | const phases: Phase[] = [
{kind: Kind.Tmpl, fn: removeContentSelectors},
{kind: Kind.Host, fn: parseHostStyleProperties},
{kind: Kind.Tmpl, fn: emitNamespaceChanges},
{kind: Kind.Tmpl, fn: propagateI18nBlocks},
{kind: Kind.Tmpl, fn: wrapI18nIcus},
{kind: Kind.Both, fn: deduplicateTextBindings},
{kind: Kind.Both, fn: specializeStyleBindings},
{kind: Kind.Both, fn: specializeBindings},
{kind: Kind.Both, fn: extractAttributes},
{kind: Kind.Tmpl, fn: createI18nContexts},
{kind: Kind.Both, fn: parseExtractedStyles},
{kind: Kind.Tmpl, fn: removeEmptyBindings},
{kind: Kind.Both, fn: collapseSingletonInterpolations},
{kind: Kind.Both, fn: orderOps},
{kind: Kind.Tmpl, fn: generateConditionalExpressions},
{kind: Kind.Tmpl, fn: createPipes},
{kind: Kind.Tmpl, fn: configureDeferInstructions},
{kind: Kind.Tmpl, fn: convertI18nText},
{kind: Kind.Tmpl, fn: convertI18nBindings},
{kind: Kind.Tmpl, fn: removeUnusedI18nAttributesOps},
{kind: Kind.Tmpl, fn: assignI18nSlotDependencies},
{kind: Kind.Tmpl, fn: applyI18nExpressions},
{kind: Kind.Tmpl, fn: createVariadicPipes},
{kind: Kind.Both, fn: generatePureLiteralStructures},
{kind: Kind.Tmpl, fn: generateProjectionDefs},
{kind: Kind.Tmpl, fn: generateLocalLetReferences},
{kind: Kind.Tmpl, fn: generateVariables},
{kind: Kind.Tmpl, fn: saveAndRestoreView},
{kind: Kind.Both, fn: deleteAnyCasts},
{kind: Kind.Both, fn: resolveDollarEvent},
{kind: Kind.Tmpl, fn: generateTrackVariables},
{kind: Kind.Tmpl, fn: removeIllegalLetReferences},
{kind: Kind.Both, fn: resolveNames},
{kind: Kind.Tmpl, fn: resolveDeferTargetNames},
{kind: Kind.Tmpl, fn: transformTwoWayBindingSet},
{kind: Kind.Tmpl, fn: optimizeTrackFns},
{kind: Kind.Both, fn: resolveContexts},
{kind: Kind.Both, fn: resolveSanitizers},
{kind: Kind.Tmpl, fn: liftLocalRefs},
{kind: Kind.Both, fn: generateNullishCoalesceExpressions},
{kind: Kind.Both, fn: expandSafeReads},
{kind: Kind.Both, fn: generateTemporaryVariables},
{kind: Kind.Both, fn: optimizeVariables},
{kind: Kind.Both, fn: optimizeStoreLet},
{kind: Kind.Tmpl, fn: allocateSlots},
{kind: Kind.Tmpl, fn: resolveI18nElementPlaceholders},
{kind: Kind.Tmpl, fn: resolveI18nExpressionPlaceholders},
{kind: Kind.Tmpl, fn: extractI18nMessages},
{kind: Kind.Tmpl, fn: generateTrackFns},
{kind: Kind.Tmpl, fn: collectI18nConsts},
{kind: Kind.Tmpl, fn: collectConstExpressions},
{kind: Kind.Both, fn: collectElementConsts},
{kind: Kind.Tmpl, fn: removeI18nContexts},
{kind: Kind.Both, fn: countVariables},
{kind: Kind.Tmpl, fn: generateAdvance},
{kind: Kind.Both, fn: nameFunctionsAndVariables},
{kind: Kind.Tmpl, fn: resolveDeferDepsFns},
{kind: Kind.Tmpl, fn: mergeNextContextExpressions},
{kind: Kind.Tmpl, fn: generateNgContainerOps},
{kind: Kind.Tmpl, fn: collapseEmptyInstructions},
{kind: Kind.Tmpl, fn: disableBindings},
{kind: Kind.Both, fn: extractPureFunctions},
{kind: Kind.Both, fn: reify},
{kind: Kind.Both, fn: chain},
];
/**
* Run all transformation phases in the correct order against a compilation job. After this
* processing, the compilation should be in a state where it can be emitted.
*/
export function transform(job: CompilationJob, kind: Kind): void {
for (const phase of phases) {
if (phase.kind === kind || phase.kind === Kind.Both) {
// The type of `Phase` above ensures it is impossible to call a phase that doesn't support the
// job kind.
phase.fn(job as CompilationJob & ComponentCompilationJob & HostBindingCompilationJob);
}
}
}
/**
* Compile all views in the given `ComponentCompilation` into the final template function, which may
* reference constants defined in a `ConstantPool`.
*/
export function emitTemplateFn(tpl: ComponentCompilationJob, pool: ConstantPool): o.FunctionExpr {
const rootFn = emitView(tpl.root);
emitChildViews(tpl.root, pool);
return rootFn;
}
function emitChildViews(parent: ViewCompilationUnit, pool: ConstantPool): void {
for (const unit of parent.job.units) {
if (unit.parent !== parent.xref) {
continue;
}
// Child views are emitted depth-first.
emitChildViews(unit, pool);
const viewFn = emitView(unit);
pool.statements.push(viewFn.toDeclStmt(viewFn.name!));
}
}
/**
* Emit a template function for an individual `ViewCompilation` (which may be either the root view
* or an embedded view).
*/
function emitView(view: ViewCompilationUnit): o.FunctionExpr {
if (view.fnName === null) {
throw new Error(`AssertionError: view ${view.xref} is unnamed`);
}
const createStatements: o.Statement[] = [];
for (const op of view.create) {
if (op.kind !== ir.OpKind.Statement) {
throw new Error(
`AssertionError: expected all create ops to have been compiled, but got ${
ir.OpKind[op.kind]
}`,
);
}
createStatements.push(op.statement);
}
const updateStatements: o.Statement[] = [];
for (const op of view.update) {
if (op.kind !== ir.OpKind.Statement) {
throw new Error(
`AssertionError: expected all update ops to have been compiled, but got ${
ir.OpKind[op.kind]
}`,
);
}
updateStatements.push(op.statement);
}
const createCond = maybeGenerateRfBlock(1, createStatements);
const updateCond = maybeGenerateRfBlock(2, updateStatements);
return o.fn(
[new o.FnParam('rf'), new o.FnParam('ctx')],
[...createCond, ...updateCond],
/* type */ undefined,
/* sourceSpan */ undefined,
view.fnName,
);
}
function maybeGenerateRfBlock(flag: number, statements: o.Statement[]): o.Statement[] {
if (statements.length === 0) {
return [];
}
return [
o.ifStmt(
new o.BinaryOperatorExpr(o.BinaryOperator.BitwiseAnd, o.variable('rf'), o.literal(flag)),
statements,
),
];
}
export function emitHostBindingFunction(job: HostBindingCompilationJob): o.FunctionExpr | null {
if (job.root.fnName === null) {
throw new Error(`AssertionError: host binding function is unnamed`);
}
const createStatements: o.Statement[] = [];
for (const op of job.root.create) {
if (op.kind !== ir.OpKind.Statement) {
throw new Error(
`AssertionError: expected all create ops to have been compiled, but got ${
ir.OpKind[op.kind]
}`,
);
}
createStatements.push(op.statement);
}
const updateStatements: o.Statement[] = [];
for (const op of job.root.update) {
if (op.kind !== ir.OpKind.Statement) {
throw new Error(
`AssertionError: expected all update ops to have been compiled, but got ${
ir.OpKind[op.kind]
}`,
);
}
updateStatements.push(op.statement);
}
if (createStatements.length === 0 && updateStatements.length === 0) {
return null;
}
const createCond = maybeGenerateRfBlock(1, createStatements);
const updateCond = maybeGenerateRfBlock(2, updateStatements);
return o.fn(
[new o.FnParam('rf'), new o.FnParam('ctx')],
[...createCond, ...updateCond],
/* type */ undefined,
/* sourceSpan */ undefined,
job.root.fnName,
);
} | {
"end_byte": 12258,
"start_byte": 5104,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/emit.ts"
} |
angular/packages/compiler/src/template/pipeline/src/instruction.ts_0_7119 | /**
* @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 {ParseSourceSpan} from '../../../parse_util';
import {Identifiers} from '../../../render3/r3_identifiers';
import * as ir from '../ir';
// This file contains helpers for generating calls to Ivy instructions. In particular, each
// instruction type is represented as a function, which may select a specific instruction variant
// depending on the exact arguments.
export function element(
slot: number,
tag: string,
constIndex: number | null,
localRefIndex: number | null,
sourceSpan: ParseSourceSpan,
): ir.CreateOp {
return elementOrContainerBase(
Identifiers.element,
slot,
tag,
constIndex,
localRefIndex,
sourceSpan,
);
}
export function elementStart(
slot: number,
tag: string,
constIndex: number | null,
localRefIndex: number | null,
sourceSpan: ParseSourceSpan,
): ir.CreateOp {
return elementOrContainerBase(
Identifiers.elementStart,
slot,
tag,
constIndex,
localRefIndex,
sourceSpan,
);
}
function elementOrContainerBase(
instruction: o.ExternalReference,
slot: number,
tag: string | null,
constIndex: number | null,
localRefIndex: number | null,
sourceSpan: ParseSourceSpan,
): ir.CreateOp {
const args: o.Expression[] = [o.literal(slot)];
if (tag !== null) {
args.push(o.literal(tag));
}
if (localRefIndex !== null) {
args.push(
o.literal(constIndex), // might be null, but that's okay.
o.literal(localRefIndex),
);
} else if (constIndex !== null) {
args.push(o.literal(constIndex));
}
return call(instruction, args, sourceSpan);
}
export function elementEnd(sourceSpan: ParseSourceSpan | null): ir.CreateOp {
return call(Identifiers.elementEnd, [], sourceSpan);
}
export function elementContainerStart(
slot: number,
constIndex: number | null,
localRefIndex: number | null,
sourceSpan: ParseSourceSpan,
): ir.CreateOp {
return elementOrContainerBase(
Identifiers.elementContainerStart,
slot,
/* tag */ null,
constIndex,
localRefIndex,
sourceSpan,
);
}
export function elementContainer(
slot: number,
constIndex: number | null,
localRefIndex: number | null,
sourceSpan: ParseSourceSpan,
): ir.CreateOp {
return elementOrContainerBase(
Identifiers.elementContainer,
slot,
/* tag */ null,
constIndex,
localRefIndex,
sourceSpan,
);
}
export function elementContainerEnd(): ir.CreateOp {
return call(Identifiers.elementContainerEnd, [], null);
}
export function template(
slot: number,
templateFnRef: o.Expression,
decls: number,
vars: number,
tag: string | null,
constIndex: number | null,
localRefs: number | null,
sourceSpan: ParseSourceSpan,
): ir.CreateOp {
const args = [
o.literal(slot),
templateFnRef,
o.literal(decls),
o.literal(vars),
o.literal(tag),
o.literal(constIndex),
];
if (localRefs !== null) {
args.push(o.literal(localRefs));
args.push(o.importExpr(Identifiers.templateRefExtractor));
}
while (args[args.length - 1].isEquivalent(o.NULL_EXPR)) {
args.pop();
}
return call(Identifiers.templateCreate, args, sourceSpan);
}
export function disableBindings(): ir.CreateOp {
return call(Identifiers.disableBindings, [], null);
}
export function enableBindings(): ir.CreateOp {
return call(Identifiers.enableBindings, [], null);
}
export function listener(
name: string,
handlerFn: o.Expression,
eventTargetResolver: o.ExternalReference | null,
syntheticHost: boolean,
sourceSpan: ParseSourceSpan,
): ir.CreateOp {
const args = [o.literal(name), handlerFn];
if (eventTargetResolver !== null) {
args.push(o.literal(false)); // `useCapture` flag, defaults to `false`
args.push(o.importExpr(eventTargetResolver));
}
return call(
syntheticHost ? Identifiers.syntheticHostListener : Identifiers.listener,
args,
sourceSpan,
);
}
export function twoWayBindingSet(target: o.Expression, value: o.Expression): o.Expression {
return o.importExpr(Identifiers.twoWayBindingSet).callFn([target, value]);
}
export function twoWayListener(
name: string,
handlerFn: o.Expression,
sourceSpan: ParseSourceSpan,
): ir.CreateOp {
return call(Identifiers.twoWayListener, [o.literal(name), handlerFn], sourceSpan);
}
export function pipe(slot: number, name: string): ir.CreateOp {
return call(Identifiers.pipe, [o.literal(slot), o.literal(name)], null);
}
export function namespaceHTML(): ir.CreateOp {
return call(Identifiers.namespaceHTML, [], null);
}
export function namespaceSVG(): ir.CreateOp {
return call(Identifiers.namespaceSVG, [], null);
}
export function namespaceMath(): ir.CreateOp {
return call(Identifiers.namespaceMathML, [], null);
}
export function advance(delta: number, sourceSpan: ParseSourceSpan): ir.UpdateOp {
return call(Identifiers.advance, delta > 1 ? [o.literal(delta)] : [], sourceSpan);
}
export function reference(slot: number): o.Expression {
return o.importExpr(Identifiers.reference).callFn([o.literal(slot)]);
}
export function nextContext(steps: number): o.Expression {
return o.importExpr(Identifiers.nextContext).callFn(steps === 1 ? [] : [o.literal(steps)]);
}
export function getCurrentView(): o.Expression {
return o.importExpr(Identifiers.getCurrentView).callFn([]);
}
export function restoreView(savedView: o.Expression): o.Expression {
return o.importExpr(Identifiers.restoreView).callFn([savedView]);
}
export function resetView(returnValue: o.Expression): o.Expression {
return o.importExpr(Identifiers.resetView).callFn([returnValue]);
}
export function text(
slot: number,
initialValue: string,
sourceSpan: ParseSourceSpan | null,
): ir.CreateOp {
const args: o.Expression[] = [o.literal(slot, null)];
if (initialValue !== '') {
args.push(o.literal(initialValue));
}
return call(Identifiers.text, args, sourceSpan);
}
export function defer(
selfSlot: number,
primarySlot: number,
dependencyResolverFn: o.Expression | null,
loadingSlot: number | null,
placeholderSlot: number | null,
errorSlot: number | null,
loadingConfig: o.Expression | null,
placeholderConfig: o.Expression | null,
enableTimerScheduling: boolean,
sourceSpan: ParseSourceSpan | null,
): ir.CreateOp {
const args: Array<o.Expression> = [
o.literal(selfSlot),
o.literal(primarySlot),
dependencyResolverFn ?? o.literal(null),
o.literal(loadingSlot),
o.literal(placeholderSlot),
o.literal(errorSlot),
loadingConfig ?? o.literal(null),
placeholderConfig ?? o.literal(null),
enableTimerScheduling ? o.importExpr(Identifiers.deferEnableTimerScheduling) : o.literal(null),
];
let expr: o.Expression;
while (
(expr = args[args.length - 1]) !== null &&
expr instanceof o.LiteralExpr &&
expr.value === null
) {
args.pop();
}
return call(Identifiers.defer, args, sourceSpan);
} | {
"end_byte": 7119,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/instruction.ts"
} |
angular/packages/compiler/src/template/pipeline/src/instruction.ts_7121_14372 | const deferTriggerToR3TriggerInstructionsMap = new Map([
[
ir.DeferTriggerKind.Idle,
{
[ir.DeferOpModifierKind.NONE]: Identifiers.deferOnIdle,
[ir.DeferOpModifierKind.PREFETCH]: Identifiers.deferPrefetchOnIdle,
[ir.DeferOpModifierKind.HYDRATE]: Identifiers.deferHydrateOnIdle,
},
],
[
ir.DeferTriggerKind.Immediate,
{
[ir.DeferOpModifierKind.NONE]: Identifiers.deferOnImmediate,
[ir.DeferOpModifierKind.PREFETCH]: Identifiers.deferPrefetchOnImmediate,
[ir.DeferOpModifierKind.HYDRATE]: Identifiers.deferHydrateOnImmediate,
},
],
[
ir.DeferTriggerKind.Timer,
{
[ir.DeferOpModifierKind.NONE]: Identifiers.deferOnTimer,
[ir.DeferOpModifierKind.PREFETCH]: Identifiers.deferPrefetchOnTimer,
[ir.DeferOpModifierKind.HYDRATE]: Identifiers.deferHydrateOnTimer,
},
],
[
ir.DeferTriggerKind.Hover,
{
[ir.DeferOpModifierKind.NONE]: Identifiers.deferOnHover,
[ir.DeferOpModifierKind.PREFETCH]: Identifiers.deferPrefetchOnHover,
[ir.DeferOpModifierKind.HYDRATE]: Identifiers.deferHydrateOnHover,
},
],
[
ir.DeferTriggerKind.Interaction,
{
[ir.DeferOpModifierKind.NONE]: Identifiers.deferOnInteraction,
[ir.DeferOpModifierKind.PREFETCH]: Identifiers.deferPrefetchOnInteraction,
[ir.DeferOpModifierKind.HYDRATE]: Identifiers.deferHydrateOnInteraction,
},
],
[
ir.DeferTriggerKind.Viewport,
{
[ir.DeferOpModifierKind.NONE]: Identifiers.deferOnViewport,
[ir.DeferOpModifierKind.PREFETCH]: Identifiers.deferPrefetchOnViewport,
[ir.DeferOpModifierKind.HYDRATE]: Identifiers.deferHydrateOnViewport,
},
],
[
ir.DeferTriggerKind.Never,
{
[ir.DeferOpModifierKind.NONE]: Identifiers.deferHydrateNever,
[ir.DeferOpModifierKind.PREFETCH]: Identifiers.deferHydrateNever,
[ir.DeferOpModifierKind.HYDRATE]: Identifiers.deferHydrateNever,
},
],
]);
export function deferOn(
trigger: ir.DeferTriggerKind,
args: number[],
modifier: ir.DeferOpModifierKind,
sourceSpan: ParseSourceSpan | null,
): ir.CreateOp {
const instructionToCall = deferTriggerToR3TriggerInstructionsMap.get(trigger)?.[modifier];
if (instructionToCall === undefined) {
throw new Error(`Unable to determine instruction for trigger ${trigger}`);
}
return call(
instructionToCall,
args.map((a) => o.literal(a)),
sourceSpan,
);
}
export function projectionDef(def: o.Expression | null): ir.CreateOp {
return call(Identifiers.projectionDef, def ? [def] : [], null);
}
export function projection(
slot: number,
projectionSlotIndex: number,
attributes: o.LiteralArrayExpr | null,
fallbackFnName: string | null,
fallbackDecls: number | null,
fallbackVars: number | null,
sourceSpan: ParseSourceSpan,
): ir.CreateOp {
const args: o.Expression[] = [o.literal(slot)];
if (projectionSlotIndex !== 0 || attributes !== null || fallbackFnName !== null) {
args.push(o.literal(projectionSlotIndex));
if (attributes !== null) {
args.push(attributes);
}
if (fallbackFnName !== null) {
if (attributes === null) {
args.push(o.literal(null));
}
args.push(o.variable(fallbackFnName), o.literal(fallbackDecls), o.literal(fallbackVars));
}
}
return call(Identifiers.projection, args, sourceSpan);
}
export function i18nStart(
slot: number,
constIndex: number,
subTemplateIndex: number,
sourceSpan: ParseSourceSpan | null,
): ir.CreateOp {
const args = [o.literal(slot), o.literal(constIndex)];
if (subTemplateIndex !== null) {
args.push(o.literal(subTemplateIndex));
}
return call(Identifiers.i18nStart, args, sourceSpan);
}
export function repeaterCreate(
slot: number,
viewFnName: string,
decls: number,
vars: number,
tag: string | null,
constIndex: number | null,
trackByFn: o.Expression,
trackByUsesComponentInstance: boolean,
emptyViewFnName: string | null,
emptyDecls: number | null,
emptyVars: number | null,
emptyTag: string | null,
emptyConstIndex: number | null,
sourceSpan: ParseSourceSpan | null,
): ir.CreateOp {
const args = [
o.literal(slot),
o.variable(viewFnName),
o.literal(decls),
o.literal(vars),
o.literal(tag),
o.literal(constIndex),
trackByFn,
];
if (trackByUsesComponentInstance || emptyViewFnName !== null) {
args.push(o.literal(trackByUsesComponentInstance));
if (emptyViewFnName !== null) {
args.push(o.variable(emptyViewFnName), o.literal(emptyDecls), o.literal(emptyVars));
if (emptyTag !== null || emptyConstIndex !== null) {
args.push(o.literal(emptyTag));
}
if (emptyConstIndex !== null) {
args.push(o.literal(emptyConstIndex));
}
}
}
return call(Identifiers.repeaterCreate, args, sourceSpan);
}
export function repeater(
collection: o.Expression,
sourceSpan: ParseSourceSpan | null,
): ir.UpdateOp {
return call(Identifiers.repeater, [collection], sourceSpan);
}
export function deferWhen(
modifier: ir.DeferOpModifierKind,
expr: o.Expression,
sourceSpan: ParseSourceSpan | null,
): ir.UpdateOp {
if (modifier === ir.DeferOpModifierKind.PREFETCH) {
return call(Identifiers.deferPrefetchWhen, [expr], sourceSpan);
} else if (modifier === ir.DeferOpModifierKind.HYDRATE) {
return call(Identifiers.deferHydrateWhen, [expr], sourceSpan);
}
return call(Identifiers.deferWhen, [expr], sourceSpan);
}
export function declareLet(slot: number, sourceSpan: ParseSourceSpan): ir.CreateOp {
return call(Identifiers.declareLet, [o.literal(slot)], sourceSpan);
}
export function storeLet(value: o.Expression, sourceSpan: ParseSourceSpan): o.Expression {
return o.importExpr(Identifiers.storeLet).callFn([value], sourceSpan);
}
export function readContextLet(slot: number): o.Expression {
return o.importExpr(Identifiers.readContextLet).callFn([o.literal(slot)]);
}
export function i18n(
slot: number,
constIndex: number,
subTemplateIndex: number,
sourceSpan: ParseSourceSpan | null,
): ir.CreateOp {
const args = [o.literal(slot), o.literal(constIndex)];
if (subTemplateIndex) {
args.push(o.literal(subTemplateIndex));
}
return call(Identifiers.i18n, args, sourceSpan);
}
export function i18nEnd(endSourceSpan: ParseSourceSpan | null): ir.CreateOp {
return call(Identifiers.i18nEnd, [], endSourceSpan);
}
export function i18nAttributes(slot: number, i18nAttributesConfig: number): ir.CreateOp {
const args = [o.literal(slot), o.literal(i18nAttributesConfig)];
return call(Identifiers.i18nAttributes, args, null);
}
export function property(
name: string,
expression: o.Expression,
sanitizer: o.Expression | null,
sourceSpan: ParseSourceSpan,
): ir.UpdateOp {
const args = [o.literal(name), expression];
if (sanitizer !== null) {
args.push(sanitizer);
}
return call(Identifiers.property, args, sourceSpan);
}
export function twoWayProperty(
name: string,
expression: o.Expression,
sanitizer: o.Expression | null,
sourceSpan: ParseSourceSpan,
): ir.UpdateOp {
const args = [o.literal(name), expression];
if (sanitizer !== null) {
args.push(sanitizer);
}
return call(Identifiers.twoWayProperty, args, sourceSpan);
} | {
"end_byte": 14372,
"start_byte": 7121,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/instruction.ts"
} |
angular/packages/compiler/src/template/pipeline/src/instruction.ts_14374_22496 | export function attribute(
name: string,
expression: o.Expression,
sanitizer: o.Expression | null,
namespace: string | null,
): ir.UpdateOp {
const args = [o.literal(name), expression];
if (sanitizer !== null || namespace !== null) {
args.push(sanitizer ?? o.literal(null));
}
if (namespace !== null) {
args.push(o.literal(namespace));
}
return call(Identifiers.attribute, args, null);
}
export function styleProp(
name: string,
expression: o.Expression,
unit: string | null,
sourceSpan: ParseSourceSpan,
): ir.UpdateOp {
const args = [o.literal(name), expression];
if (unit !== null) {
args.push(o.literal(unit));
}
return call(Identifiers.styleProp, args, sourceSpan);
}
export function classProp(
name: string,
expression: o.Expression,
sourceSpan: ParseSourceSpan,
): ir.UpdateOp {
return call(Identifiers.classProp, [o.literal(name), expression], sourceSpan);
}
export function styleMap(expression: o.Expression, sourceSpan: ParseSourceSpan): ir.UpdateOp {
return call(Identifiers.styleMap, [expression], sourceSpan);
}
export function classMap(expression: o.Expression, sourceSpan: ParseSourceSpan): ir.UpdateOp {
return call(Identifiers.classMap, [expression], sourceSpan);
}
const PIPE_BINDINGS: o.ExternalReference[] = [
Identifiers.pipeBind1,
Identifiers.pipeBind2,
Identifiers.pipeBind3,
Identifiers.pipeBind4,
];
export function pipeBind(slot: number, varOffset: number, args: o.Expression[]): o.Expression {
if (args.length < 1 || args.length > PIPE_BINDINGS.length) {
throw new Error(`pipeBind() argument count out of bounds`);
}
const instruction = PIPE_BINDINGS[args.length - 1];
return o.importExpr(instruction).callFn([o.literal(slot), o.literal(varOffset), ...args]);
}
export function pipeBindV(slot: number, varOffset: number, args: o.Expression): o.Expression {
return o.importExpr(Identifiers.pipeBindV).callFn([o.literal(slot), o.literal(varOffset), args]);
}
export function textInterpolate(
strings: string[],
expressions: o.Expression[],
sourceSpan: ParseSourceSpan,
): ir.UpdateOp {
const interpolationArgs = collateInterpolationArgs(strings, expressions);
return callVariadicInstruction(TEXT_INTERPOLATE_CONFIG, [], interpolationArgs, [], sourceSpan);
}
export function i18nExp(expr: o.Expression, sourceSpan: ParseSourceSpan | null): ir.UpdateOp {
return call(Identifiers.i18nExp, [expr], sourceSpan);
}
export function i18nApply(slot: number, sourceSpan: ParseSourceSpan | null): ir.UpdateOp {
return call(Identifiers.i18nApply, [o.literal(slot)], sourceSpan);
}
export function propertyInterpolate(
name: string,
strings: string[],
expressions: o.Expression[],
sanitizer: o.Expression | null,
sourceSpan: ParseSourceSpan,
): ir.UpdateOp {
const interpolationArgs = collateInterpolationArgs(strings, expressions);
const extraArgs = [];
if (sanitizer !== null) {
extraArgs.push(sanitizer);
}
return callVariadicInstruction(
PROPERTY_INTERPOLATE_CONFIG,
[o.literal(name)],
interpolationArgs,
extraArgs,
sourceSpan,
);
}
export function attributeInterpolate(
name: string,
strings: string[],
expressions: o.Expression[],
sanitizer: o.Expression | null,
sourceSpan: ParseSourceSpan,
): ir.UpdateOp {
const interpolationArgs = collateInterpolationArgs(strings, expressions);
const extraArgs = [];
if (sanitizer !== null) {
extraArgs.push(sanitizer);
}
return callVariadicInstruction(
ATTRIBUTE_INTERPOLATE_CONFIG,
[o.literal(name)],
interpolationArgs,
extraArgs,
sourceSpan,
);
}
export function stylePropInterpolate(
name: string,
strings: string[],
expressions: o.Expression[],
unit: string | null,
sourceSpan: ParseSourceSpan,
): ir.UpdateOp {
const interpolationArgs = collateInterpolationArgs(strings, expressions);
const extraArgs: o.Expression[] = [];
if (unit !== null) {
extraArgs.push(o.literal(unit));
}
return callVariadicInstruction(
STYLE_PROP_INTERPOLATE_CONFIG,
[o.literal(name)],
interpolationArgs,
extraArgs,
sourceSpan,
);
}
export function styleMapInterpolate(
strings: string[],
expressions: o.Expression[],
sourceSpan: ParseSourceSpan,
): ir.UpdateOp {
const interpolationArgs = collateInterpolationArgs(strings, expressions);
return callVariadicInstruction(
STYLE_MAP_INTERPOLATE_CONFIG,
[],
interpolationArgs,
[],
sourceSpan,
);
}
export function classMapInterpolate(
strings: string[],
expressions: o.Expression[],
sourceSpan: ParseSourceSpan,
): ir.UpdateOp {
const interpolationArgs = collateInterpolationArgs(strings, expressions);
return callVariadicInstruction(
CLASS_MAP_INTERPOLATE_CONFIG,
[],
interpolationArgs,
[],
sourceSpan,
);
}
export function hostProperty(
name: string,
expression: o.Expression,
sanitizer: o.Expression | null,
sourceSpan: ParseSourceSpan | null,
): ir.UpdateOp {
const args = [o.literal(name), expression];
if (sanitizer !== null) {
args.push(sanitizer);
}
return call(Identifiers.hostProperty, args, sourceSpan);
}
export function syntheticHostProperty(
name: string,
expression: o.Expression,
sourceSpan: ParseSourceSpan | null,
): ir.UpdateOp {
return call(Identifiers.syntheticHostProperty, [o.literal(name), expression], sourceSpan);
}
export function pureFunction(
varOffset: number,
fn: o.Expression,
args: o.Expression[],
): o.Expression {
return callVariadicInstructionExpr(
PURE_FUNCTION_CONFIG,
[o.literal(varOffset), fn],
args,
[],
null,
);
}
/**
* Collates the string an expression arguments for an interpolation instruction.
*/
function collateInterpolationArgs(strings: string[], expressions: o.Expression[]): o.Expression[] {
if (strings.length < 1 || expressions.length !== strings.length - 1) {
throw new Error(
`AssertionError: expected specific shape of args for strings/expressions in interpolation`,
);
}
const interpolationArgs: o.Expression[] = [];
if (expressions.length === 1 && strings[0] === '' && strings[1] === '') {
interpolationArgs.push(expressions[0]);
} else {
let idx: number;
for (idx = 0; idx < expressions.length; idx++) {
interpolationArgs.push(o.literal(strings[idx]), expressions[idx]);
}
// idx points at the last string.
interpolationArgs.push(o.literal(strings[idx]));
}
return interpolationArgs;
}
function call<OpT extends ir.CreateOp | ir.UpdateOp>(
instruction: o.ExternalReference,
args: o.Expression[],
sourceSpan: ParseSourceSpan | null,
): OpT {
const expr = o.importExpr(instruction).callFn(args, sourceSpan);
return ir.createStatementOp(new o.ExpressionStatement(expr, sourceSpan)) as OpT;
}
export function conditional(
condition: o.Expression,
contextValue: o.Expression | null,
sourceSpan: ParseSourceSpan | null,
): ir.UpdateOp {
const args = [condition];
if (contextValue !== null) {
args.push(contextValue);
}
return call(Identifiers.conditional, args, sourceSpan);
}
/**
* Describes a specific flavor of instruction used to represent variadic instructions, which
* have some number of variants for specific argument counts.
*/
interface VariadicInstructionConfig {
constant: o.ExternalReference[];
variable: o.ExternalReference | null;
mapping: (argCount: number) => number;
}
/**
* `InterpolationConfig` for the `textInterpolate` instruction.
*/
const TEXT_INTERPOLATE_CONFIG: VariadicInstructionConfig = {
constant: [
Identifiers.textInterpolate,
Identifiers.textInterpolate1,
Identifiers.textInterpolate2,
Identifiers.textInterpolate3,
Identifiers.textInterpolate4,
Identifiers.textInterpolate5,
Identifiers.textInterpolate6,
Identifiers.textInterpolate7,
Identifiers.textInterpolate8,
],
variable: Identifiers.textInterpolateV,
mapping: (n) => {
if (n % 2 === 0) {
throw new Error(`Expected odd number of arguments`);
}
return (n - 1) / 2;
},
};
/**
* `InterpolationConfig` for the `propertyInterpolate` instruction.
*/ | {
"end_byte": 22496,
"start_byte": 14374,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/instruction.ts"
} |
angular/packages/compiler/src/template/pipeline/src/instruction.ts_22497_27439 | const PROPERTY_INTERPOLATE_CONFIG: VariadicInstructionConfig = {
constant: [
Identifiers.propertyInterpolate,
Identifiers.propertyInterpolate1,
Identifiers.propertyInterpolate2,
Identifiers.propertyInterpolate3,
Identifiers.propertyInterpolate4,
Identifiers.propertyInterpolate5,
Identifiers.propertyInterpolate6,
Identifiers.propertyInterpolate7,
Identifiers.propertyInterpolate8,
],
variable: Identifiers.propertyInterpolateV,
mapping: (n) => {
if (n % 2 === 0) {
throw new Error(`Expected odd number of arguments`);
}
return (n - 1) / 2;
},
};
/**
* `InterpolationConfig` for the `stylePropInterpolate` instruction.
*/
const STYLE_PROP_INTERPOLATE_CONFIG: VariadicInstructionConfig = {
constant: [
Identifiers.styleProp,
Identifiers.stylePropInterpolate1,
Identifiers.stylePropInterpolate2,
Identifiers.stylePropInterpolate3,
Identifiers.stylePropInterpolate4,
Identifiers.stylePropInterpolate5,
Identifiers.stylePropInterpolate6,
Identifiers.stylePropInterpolate7,
Identifiers.stylePropInterpolate8,
],
variable: Identifiers.stylePropInterpolateV,
mapping: (n) => {
if (n % 2 === 0) {
throw new Error(`Expected odd number of arguments`);
}
return (n - 1) / 2;
},
};
/**
* `InterpolationConfig` for the `attributeInterpolate` instruction.
*/
const ATTRIBUTE_INTERPOLATE_CONFIG: VariadicInstructionConfig = {
constant: [
Identifiers.attribute,
Identifiers.attributeInterpolate1,
Identifiers.attributeInterpolate2,
Identifiers.attributeInterpolate3,
Identifiers.attributeInterpolate4,
Identifiers.attributeInterpolate5,
Identifiers.attributeInterpolate6,
Identifiers.attributeInterpolate7,
Identifiers.attributeInterpolate8,
],
variable: Identifiers.attributeInterpolateV,
mapping: (n) => {
if (n % 2 === 0) {
throw new Error(`Expected odd number of arguments`);
}
return (n - 1) / 2;
},
};
/**
* `InterpolationConfig` for the `styleMapInterpolate` instruction.
*/
const STYLE_MAP_INTERPOLATE_CONFIG: VariadicInstructionConfig = {
constant: [
Identifiers.styleMap,
Identifiers.styleMapInterpolate1,
Identifiers.styleMapInterpolate2,
Identifiers.styleMapInterpolate3,
Identifiers.styleMapInterpolate4,
Identifiers.styleMapInterpolate5,
Identifiers.styleMapInterpolate6,
Identifiers.styleMapInterpolate7,
Identifiers.styleMapInterpolate8,
],
variable: Identifiers.styleMapInterpolateV,
mapping: (n) => {
if (n % 2 === 0) {
throw new Error(`Expected odd number of arguments`);
}
return (n - 1) / 2;
},
};
/**
* `InterpolationConfig` for the `classMapInterpolate` instruction.
*/
const CLASS_MAP_INTERPOLATE_CONFIG: VariadicInstructionConfig = {
constant: [
Identifiers.classMap,
Identifiers.classMapInterpolate1,
Identifiers.classMapInterpolate2,
Identifiers.classMapInterpolate3,
Identifiers.classMapInterpolate4,
Identifiers.classMapInterpolate5,
Identifiers.classMapInterpolate6,
Identifiers.classMapInterpolate7,
Identifiers.classMapInterpolate8,
],
variable: Identifiers.classMapInterpolateV,
mapping: (n) => {
if (n % 2 === 0) {
throw new Error(`Expected odd number of arguments`);
}
return (n - 1) / 2;
},
};
const PURE_FUNCTION_CONFIG: VariadicInstructionConfig = {
constant: [
Identifiers.pureFunction0,
Identifiers.pureFunction1,
Identifiers.pureFunction2,
Identifiers.pureFunction3,
Identifiers.pureFunction4,
Identifiers.pureFunction5,
Identifiers.pureFunction6,
Identifiers.pureFunction7,
Identifiers.pureFunction8,
],
variable: Identifiers.pureFunctionV,
mapping: (n) => n,
};
function callVariadicInstructionExpr(
config: VariadicInstructionConfig,
baseArgs: o.Expression[],
interpolationArgs: o.Expression[],
extraArgs: o.Expression[],
sourceSpan: ParseSourceSpan | null,
): o.Expression {
const n = config.mapping(interpolationArgs.length);
if (n < config.constant.length) {
// Constant calling pattern.
return o
.importExpr(config.constant[n])
.callFn([...baseArgs, ...interpolationArgs, ...extraArgs], sourceSpan);
} else if (config.variable !== null) {
// Variable calling pattern.
return o
.importExpr(config.variable)
.callFn([...baseArgs, o.literalArr(interpolationArgs), ...extraArgs], sourceSpan);
} else {
throw new Error(`AssertionError: unable to call variadic function`);
}
}
function callVariadicInstruction(
config: VariadicInstructionConfig,
baseArgs: o.Expression[],
interpolationArgs: o.Expression[],
extraArgs: o.Expression[],
sourceSpan: ParseSourceSpan | null,
): ir.UpdateOp {
return ir.createStatementOp(
callVariadicInstructionExpr(
config,
baseArgs,
interpolationArgs,
extraArgs,
sourceSpan,
).toStmt(),
);
} | {
"end_byte": 27439,
"start_byte": 22497,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/instruction.ts"
} |
angular/packages/compiler/src/template/pipeline/src/compilation.ts_0_7401 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ConstantPool} from '../../../constant_pool';
import * as o from '../../../output/output_ast';
import {R3ComponentDeferMetadata} from '../../../render3/view/api';
import * as ir from '../ir';
export enum CompilationJobKind {
Tmpl,
Host,
Both, // A special value used to indicate that some logic applies to both compilation types
}
/**
* An entire ongoing compilation, which will result in one or more template functions when complete.
* Contains one or more corresponding compilation units.
*/
export abstract class CompilationJob {
constructor(
readonly componentName: string,
readonly pool: ConstantPool,
readonly compatibility: ir.CompatibilityMode,
) {}
kind: CompilationJobKind = CompilationJobKind.Both;
/**
* A compilation job will contain one or more compilation units.
*/
abstract get units(): Iterable<CompilationUnit>;
/**
* The root compilation unit, such as the component's template, or the host binding's compilation
* unit.
*/
abstract root: CompilationUnit;
/**
* A unique string used to identify this kind of job, and generate the template function (as a
* suffix of the name).
*/
abstract fnSuffix: string;
/**
* Generate a new unique `ir.XrefId` in this job.
*/
allocateXrefId(): ir.XrefId {
return this.nextXrefId++ as ir.XrefId;
}
/**
* Tracks the next `ir.XrefId` which can be assigned as template structures are ingested.
*/
private nextXrefId: ir.XrefId = 0 as ir.XrefId;
}
/**
* Compilation-in-progress of a whole component's template, including the main template and any
* embedded views or host bindings.
*/
export class ComponentCompilationJob extends CompilationJob {
constructor(
componentName: string,
pool: ConstantPool,
compatibility: ir.CompatibilityMode,
readonly relativeContextFilePath: string,
readonly i18nUseExternalIds: boolean,
readonly deferMeta: R3ComponentDeferMetadata,
readonly allDeferrableDepsFn: o.ReadVarExpr | null,
) {
super(componentName, pool, compatibility);
this.root = new ViewCompilationUnit(this, this.allocateXrefId(), null);
this.views.set(this.root.xref, this.root);
}
override kind = CompilationJobKind.Tmpl;
override readonly fnSuffix: string = 'Template';
/**
* The root view, representing the component's template.
*/
override readonly root: ViewCompilationUnit;
readonly views = new Map<ir.XrefId, ViewCompilationUnit>();
/**
* Causes ngContentSelectors to be emitted, for content projection slots in the view. Possibly a
* reference into the constant pool.
*/
public contentSelectors: o.Expression | null = null;
/**
* Add a `ViewCompilation` for a new embedded view to this compilation.
*/
allocateView(parent: ir.XrefId): ViewCompilationUnit {
const view = new ViewCompilationUnit(this, this.allocateXrefId(), parent);
this.views.set(view.xref, view);
return view;
}
override get units(): Iterable<ViewCompilationUnit> {
return this.views.values();
}
/**
* Add a constant `o.Expression` to the compilation and return its index in the `consts` array.
*/
addConst(newConst: o.Expression, initializers?: o.Statement[]): ir.ConstIndex {
for (let idx = 0; idx < this.consts.length; idx++) {
if (this.consts[idx].isEquivalent(newConst)) {
return idx as ir.ConstIndex;
}
}
const idx = this.consts.length;
this.consts.push(newConst);
if (initializers) {
this.constsInitializers.push(...initializers);
}
return idx as ir.ConstIndex;
}
/**
* Constant expressions used by operations within this component's compilation.
*
* This will eventually become the `consts` array in the component definition.
*/
readonly consts: o.Expression[] = [];
/**
* Initialization statements needed to set up the consts.
*/
readonly constsInitializers: o.Statement[] = [];
}
/**
* A compilation unit is compiled into a template function. Some example units are views and host
* bindings.
*/
export abstract class CompilationUnit {
constructor(readonly xref: ir.XrefId) {}
/**
* List of creation operations for this view.
*
* Creation operations may internally contain other operations, including update operations.
*/
readonly create = new ir.OpList<ir.CreateOp>();
/**
* List of update operations for this view.
*/
readonly update = new ir.OpList<ir.UpdateOp>();
/**
* The enclosing job, which might contain several individual compilation units.
*/
abstract readonly job: CompilationJob;
/**
* Name of the function which will be generated for this unit.
*
* May be `null` if not yet determined.
*/
fnName: string | null = null;
/**
* Number of variable slots used within this view, or `null` if variables have not yet been
* counted.
*/
vars: number | null = null;
/**
* Iterate over all `ir.Op`s within this view.
*
* Some operations may have child operations, which this iterator will visit.
*/
*ops(): Generator<ir.CreateOp | ir.UpdateOp> {
for (const op of this.create) {
yield op;
if (op.kind === ir.OpKind.Listener || op.kind === ir.OpKind.TwoWayListener) {
for (const listenerOp of op.handlerOps) {
yield listenerOp;
}
}
}
for (const op of this.update) {
yield op;
}
}
}
/**
* Compilation-in-progress of an individual view within a template.
*/
export class ViewCompilationUnit extends CompilationUnit {
constructor(
readonly job: ComponentCompilationJob,
xref: ir.XrefId,
readonly parent: ir.XrefId | null,
) {
super(xref);
}
/**
* Map of declared variables available within this view to the property on the context object
* which they alias.
*/
readonly contextVariables = new Map<string, string>();
/**
* Set of aliases available within this view. An alias is a variable whose provided expression is
* inlined at every location it is used. It may also depend on context variables, by name.
*/
readonly aliases = new Set<ir.AliasVariable>();
/**
* Number of declaration slots used within this view, or `null` if slots have not yet been
* allocated.
*/
decls: number | null = null;
}
/**
* Compilation-in-progress of a host binding, which contains a single unit for that host binding.
*/
export class HostBindingCompilationJob extends CompilationJob {
constructor(componentName: string, pool: ConstantPool, compatibility: ir.CompatibilityMode) {
super(componentName, pool, compatibility);
this.root = new HostBindingCompilationUnit(this);
}
override kind = CompilationJobKind.Host;
override readonly fnSuffix: string = 'HostBindings';
override readonly root: HostBindingCompilationUnit;
override get units(): Iterable<HostBindingCompilationUnit> {
return [this.root];
}
}
export class HostBindingCompilationUnit extends CompilationUnit {
constructor(readonly job: HostBindingCompilationJob) {
super(0 as ir.XrefId);
}
/**
* Much like an element can have attributes, so can a host binding function.
*/
attributes: o.LiteralArrayExpr | null = null;
}
| {
"end_byte": 7401,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/compilation.ts"
} |
angular/packages/compiler/src/template/pipeline/src/conversion.ts_0_2132 | /**
* @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';
export const BINARY_OPERATORS = new Map([
['&&', o.BinaryOperator.And],
['>', o.BinaryOperator.Bigger],
['>=', o.BinaryOperator.BiggerEquals],
['|', o.BinaryOperator.BitwiseOr],
['&', o.BinaryOperator.BitwiseAnd],
['/', o.BinaryOperator.Divide],
['==', o.BinaryOperator.Equals],
['===', o.BinaryOperator.Identical],
['<', o.BinaryOperator.Lower],
['<=', o.BinaryOperator.LowerEquals],
['-', o.BinaryOperator.Minus],
['%', o.BinaryOperator.Modulo],
['*', o.BinaryOperator.Multiply],
['!=', o.BinaryOperator.NotEquals],
['!==', o.BinaryOperator.NotIdentical],
['??', o.BinaryOperator.NullishCoalesce],
['||', o.BinaryOperator.Or],
['+', o.BinaryOperator.Plus],
]);
export function namespaceForKey(namespacePrefixKey: string | null): ir.Namespace {
const NAMESPACES = new Map([
['svg', ir.Namespace.SVG],
['math', ir.Namespace.Math],
]);
if (namespacePrefixKey === null) {
return ir.Namespace.HTML;
}
return NAMESPACES.get(namespacePrefixKey) ?? ir.Namespace.HTML;
}
export function keyForNamespace(namespace: ir.Namespace): string | null {
const NAMESPACES = new Map([
['svg', ir.Namespace.SVG],
['math', ir.Namespace.Math],
]);
for (const [k, n] of NAMESPACES.entries()) {
if (n === namespace) {
return k;
}
}
return null; // No namespace prefix for HTML
}
export function prefixWithNamespace(strippedTag: string, namespace: ir.Namespace): string {
if (namespace === ir.Namespace.HTML) {
return strippedTag;
}
return `:${keyForNamespace(namespace)}:${strippedTag}`;
}
export type LiteralType = string | number | boolean | null | Array<LiteralType>;
export function literalOrArrayLiteral(value: LiteralType): o.Expression {
if (Array.isArray(value)) {
return o.literalArr(value.map(literalOrArrayLiteral));
}
return o.literal(value);
}
| {
"end_byte": 2132,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/conversion.ts"
} |
angular/packages/compiler/src/template/pipeline/src/ingest.ts_0_7620 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ConstantPool} from '../../../constant_pool';
import {SecurityContext} from '../../../core';
import * as e from '../../../expression_parser/ast';
import * as i18n from '../../../i18n/i18n_ast';
import {splitNsName} from '../../../ml_parser/tags';
import * as o from '../../../output/output_ast';
import {ParseSourceSpan} from '../../../parse_util';
import * as t from '../../../render3/r3_ast';
import {DeferBlockDepsEmitMode, R3ComponentDeferMetadata} from '../../../render3/view/api';
import {icuFromI18nMessage} from '../../../render3/view/i18n/util';
import {DomElementSchemaRegistry} from '../../../schema/dom_element_schema_registry';
import {BindingParser} from '../../../template_parser/binding_parser';
import * as ir from '../ir';
import {
CompilationUnit,
ComponentCompilationJob,
HostBindingCompilationJob,
type CompilationJob,
type ViewCompilationUnit,
} from './compilation';
import {BINARY_OPERATORS, namespaceForKey, prefixWithNamespace} from './conversion';
const compatibilityMode = ir.CompatibilityMode.TemplateDefinitionBuilder;
// Schema containing DOM elements and their properties.
const domSchema = new DomElementSchemaRegistry();
// Tag name of the `ng-template` element.
const NG_TEMPLATE_TAG_NAME = 'ng-template';
export function isI18nRootNode(meta?: i18n.I18nMeta): meta is i18n.Message {
return meta instanceof i18n.Message;
}
export function isSingleI18nIcu(meta?: i18n.I18nMeta): meta is i18n.I18nMeta & {nodes: [i18n.Icu]} {
return isI18nRootNode(meta) && meta.nodes.length === 1 && meta.nodes[0] instanceof i18n.Icu;
}
/**
* Process a template AST and convert it into a `ComponentCompilation` in the intermediate
* representation.
* TODO: Refactor more of the ingestion code into phases.
*/
export function ingestComponent(
componentName: string,
template: t.Node[],
constantPool: ConstantPool,
relativeContextFilePath: string,
i18nUseExternalIds: boolean,
deferMeta: R3ComponentDeferMetadata,
allDeferrableDepsFn: o.ReadVarExpr | null,
): ComponentCompilationJob {
const job = new ComponentCompilationJob(
componentName,
constantPool,
compatibilityMode,
relativeContextFilePath,
i18nUseExternalIds,
deferMeta,
allDeferrableDepsFn,
);
ingestNodes(job.root, template);
return job;
}
export interface HostBindingInput {
componentName: string;
componentSelector: string;
properties: e.ParsedProperty[] | null;
attributes: {[key: string]: o.Expression};
events: e.ParsedEvent[] | null;
}
/**
* Process a host binding AST and convert it into a `HostBindingCompilationJob` in the intermediate
* representation.
*/
export function ingestHostBinding(
input: HostBindingInput,
bindingParser: BindingParser,
constantPool: ConstantPool,
): HostBindingCompilationJob {
const job = new HostBindingCompilationJob(input.componentName, constantPool, compatibilityMode);
for (const property of input.properties ?? []) {
let bindingKind = ir.BindingKind.Property;
// TODO: this should really be handled in the parser.
if (property.name.startsWith('attr.')) {
property.name = property.name.substring('attr.'.length);
bindingKind = ir.BindingKind.Attribute;
}
if (property.isAnimation) {
bindingKind = ir.BindingKind.Animation;
}
const securityContexts = bindingParser
.calcPossibleSecurityContexts(
input.componentSelector,
property.name,
bindingKind === ir.BindingKind.Attribute,
)
.filter((context) => context !== SecurityContext.NONE);
ingestHostProperty(job, property, bindingKind, securityContexts);
}
for (const [name, expr] of Object.entries(input.attributes) ?? []) {
const securityContexts = bindingParser
.calcPossibleSecurityContexts(input.componentSelector, name, true)
.filter((context) => context !== SecurityContext.NONE);
ingestHostAttribute(job, name, expr, securityContexts);
}
for (const event of input.events ?? []) {
ingestHostEvent(job, event);
}
return job;
}
// TODO: We should refactor the parser to use the same types and structures for host bindings as
// with ordinary components. This would allow us to share a lot more ingestion code.
export function ingestHostProperty(
job: HostBindingCompilationJob,
property: e.ParsedProperty,
bindingKind: ir.BindingKind,
securityContexts: SecurityContext[],
): void {
let expression: o.Expression | ir.Interpolation;
const ast = property.expression.ast;
if (ast instanceof e.Interpolation) {
expression = new ir.Interpolation(
ast.strings,
ast.expressions.map((expr) => convertAst(expr, job, property.sourceSpan)),
[],
);
} else {
expression = convertAst(ast, job, property.sourceSpan);
}
job.root.update.push(
ir.createBindingOp(
job.root.xref,
bindingKind,
property.name,
expression,
null,
securityContexts,
false,
false,
null,
/* TODO: How do Host bindings handle i18n attrs? */ null,
property.sourceSpan,
),
);
}
export function ingestHostAttribute(
job: HostBindingCompilationJob,
name: string,
value: o.Expression,
securityContexts: SecurityContext[],
): void {
const attrBinding = ir.createBindingOp(
job.root.xref,
ir.BindingKind.Attribute,
name,
value,
null,
securityContexts,
/* Host attributes should always be extracted to const hostAttrs, even if they are not
*strictly* text literals */
true,
false,
null,
/* TODO */ null,
/** TODO: May be null? */ value.sourceSpan!,
);
job.root.update.push(attrBinding);
}
export function ingestHostEvent(job: HostBindingCompilationJob, event: e.ParsedEvent) {
const [phase, target] =
event.type !== e.ParsedEventType.Animation
? [null, event.targetOrPhase]
: [event.targetOrPhase, null];
const eventBinding = ir.createListenerOp(
job.root.xref,
new ir.SlotHandle(),
event.name,
null,
makeListenerHandlerOps(job.root, event.handler, event.handlerSpan),
phase,
target,
true,
event.sourceSpan,
);
job.root.create.push(eventBinding);
}
/**
* Ingest the nodes of a template AST into the given `ViewCompilation`.
*/
function ingestNodes(unit: ViewCompilationUnit, template: t.Node[]): void {
for (const node of template) {
if (node instanceof t.Element) {
ingestElement(unit, node);
} else if (node instanceof t.Template) {
ingestTemplate(unit, node);
} else if (node instanceof t.Content) {
ingestContent(unit, node);
} else if (node instanceof t.Text) {
ingestText(unit, node, null);
} else if (node instanceof t.BoundText) {
ingestBoundText(unit, node, null);
} else if (node instanceof t.IfBlock) {
ingestIfBlock(unit, node);
} else if (node instanceof t.SwitchBlock) {
ingestSwitchBlock(unit, node);
} else if (node instanceof t.DeferredBlock) {
ingestDeferBlock(unit, node);
} else if (node instanceof t.Icu) {
ingestIcu(unit, node);
} else if (node instanceof t.ForLoopBlock) {
ingestForBlock(unit, node);
} else if (node instanceof t.LetDeclaration) {
ingestLetDeclaration(unit, node);
} else {
throw new Error(`Unsupported template node: ${node.constructor.name}`);
}
}
}
/**
* Ingest an element AST from the template into the given `ViewCompilation`.
*/ | {
"end_byte": 7620,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/ingest.ts"
} |
angular/packages/compiler/src/template/pipeline/src/ingest.ts_7621_15676 | function ingestElement(unit: ViewCompilationUnit, element: t.Element): void {
if (
element.i18n !== undefined &&
!(element.i18n instanceof i18n.Message || element.i18n instanceof i18n.TagPlaceholder)
) {
throw Error(`Unhandled i18n metadata type for element: ${element.i18n.constructor.name}`);
}
const id = unit.job.allocateXrefId();
const [namespaceKey, elementName] = splitNsName(element.name);
const startOp = ir.createElementStartOp(
elementName,
id,
namespaceForKey(namespaceKey),
element.i18n instanceof i18n.TagPlaceholder ? element.i18n : undefined,
element.startSourceSpan,
element.sourceSpan,
);
unit.create.push(startOp);
ingestElementBindings(unit, startOp, element);
ingestReferences(startOp, element);
// Start i18n, if needed, goes after the element create and bindings, but before the nodes
let i18nBlockId: ir.XrefId | null = null;
if (element.i18n instanceof i18n.Message) {
i18nBlockId = unit.job.allocateXrefId();
unit.create.push(
ir.createI18nStartOp(i18nBlockId, element.i18n, undefined, element.startSourceSpan),
);
}
ingestNodes(unit, element.children);
// The source span for the end op is typically the element closing tag. However, if no closing tag
// exists, such as in `<input>`, we use the start source span instead. Usually the start and end
// instructions will be collapsed into one `element` instruction, negating the purpose of this
// fallback, but in cases when it is not collapsed (such as an input with a binding), we still
// want to map the end instruction to the main element.
const endOp = ir.createElementEndOp(id, element.endSourceSpan ?? element.startSourceSpan);
unit.create.push(endOp);
// If there is an i18n message associated with this element, insert i18n start and end ops.
if (i18nBlockId !== null) {
ir.OpList.insertBefore<ir.CreateOp>(
ir.createI18nEndOp(i18nBlockId, element.endSourceSpan ?? element.startSourceSpan),
endOp,
);
}
}
/**
* Ingest an `ng-template` node from the AST into the given `ViewCompilation`.
*/
function ingestTemplate(unit: ViewCompilationUnit, tmpl: t.Template): void {
if (
tmpl.i18n !== undefined &&
!(tmpl.i18n instanceof i18n.Message || tmpl.i18n instanceof i18n.TagPlaceholder)
) {
throw Error(`Unhandled i18n metadata type for template: ${tmpl.i18n.constructor.name}`);
}
const childView = unit.job.allocateView(unit.xref);
let tagNameWithoutNamespace = tmpl.tagName;
let namespacePrefix: string | null = '';
if (tmpl.tagName) {
[namespacePrefix, tagNameWithoutNamespace] = splitNsName(tmpl.tagName);
}
const i18nPlaceholder = tmpl.i18n instanceof i18n.TagPlaceholder ? tmpl.i18n : undefined;
const namespace = namespaceForKey(namespacePrefix);
const functionNameSuffix =
tagNameWithoutNamespace === null ? '' : prefixWithNamespace(tagNameWithoutNamespace, namespace);
const templateKind = isPlainTemplate(tmpl)
? ir.TemplateKind.NgTemplate
: ir.TemplateKind.Structural;
const templateOp = ir.createTemplateOp(
childView.xref,
templateKind,
tagNameWithoutNamespace,
functionNameSuffix,
namespace,
i18nPlaceholder,
tmpl.startSourceSpan,
tmpl.sourceSpan,
);
unit.create.push(templateOp);
ingestTemplateBindings(unit, templateOp, tmpl, templateKind);
ingestReferences(templateOp, tmpl);
ingestNodes(childView, tmpl.children);
for (const {name, value} of tmpl.variables) {
childView.contextVariables.set(name, value !== '' ? value : '$implicit');
}
// If this is a plain template and there is an i18n message associated with it, insert i18n start
// and end ops. For structural directive templates, the i18n ops will be added when ingesting the
// element/template the directive is placed on.
if (templateKind === ir.TemplateKind.NgTemplate && tmpl.i18n instanceof i18n.Message) {
const id = unit.job.allocateXrefId();
ir.OpList.insertAfter(
ir.createI18nStartOp(id, tmpl.i18n, undefined, tmpl.startSourceSpan),
childView.create.head,
);
ir.OpList.insertBefore(
ir.createI18nEndOp(id, tmpl.endSourceSpan ?? tmpl.startSourceSpan),
childView.create.tail,
);
}
}
/**
* Ingest a content node from the AST into the given `ViewCompilation`.
*/
function ingestContent(unit: ViewCompilationUnit, content: t.Content): void {
if (content.i18n !== undefined && !(content.i18n instanceof i18n.TagPlaceholder)) {
throw Error(`Unhandled i18n metadata type for element: ${content.i18n.constructor.name}`);
}
let fallbackView: ViewCompilationUnit | null = null;
// Don't capture default content that's only made up of empty text nodes and comments.
// Note that we process the default content before the projection in order to match the
// insertion order at runtime.
if (
content.children.some(
(child) =>
!(child instanceof t.Comment) &&
(!(child instanceof t.Text) || child.value.trim().length > 0),
)
) {
fallbackView = unit.job.allocateView(unit.xref);
ingestNodes(fallbackView, content.children);
}
const id = unit.job.allocateXrefId();
const op = ir.createProjectionOp(
id,
content.selector,
content.i18n,
fallbackView?.xref ?? null,
content.sourceSpan,
);
for (const attr of content.attributes) {
const securityContext = domSchema.securityContext(content.name, attr.name, true);
unit.update.push(
ir.createBindingOp(
op.xref,
ir.BindingKind.Attribute,
attr.name,
o.literal(attr.value),
null,
securityContext,
true,
false,
null,
asMessage(attr.i18n),
attr.sourceSpan,
),
);
}
unit.create.push(op);
}
/**
* Ingest a literal text node from the AST into the given `ViewCompilation`.
*/
function ingestText(unit: ViewCompilationUnit, text: t.Text, icuPlaceholder: string | null): void {
unit.create.push(
ir.createTextOp(unit.job.allocateXrefId(), text.value, icuPlaceholder, text.sourceSpan),
);
}
/**
* Ingest an interpolated text node from the AST into the given `ViewCompilation`.
*/
function ingestBoundText(
unit: ViewCompilationUnit,
text: t.BoundText,
icuPlaceholder: string | null,
): void {
let value = text.value;
if (value instanceof e.ASTWithSource) {
value = value.ast;
}
if (!(value instanceof e.Interpolation)) {
throw new Error(
`AssertionError: expected Interpolation for BoundText node, got ${value.constructor.name}`,
);
}
if (text.i18n !== undefined && !(text.i18n instanceof i18n.Container)) {
throw Error(
`Unhandled i18n metadata type for text interpolation: ${text.i18n?.constructor.name}`,
);
}
const i18nPlaceholders =
text.i18n instanceof i18n.Container
? text.i18n.children
.filter((node): node is i18n.Placeholder => node instanceof i18n.Placeholder)
.map((placeholder) => placeholder.name)
: [];
if (i18nPlaceholders.length > 0 && i18nPlaceholders.length !== value.expressions.length) {
throw Error(
`Unexpected number of i18n placeholders (${value.expressions.length}) for BoundText with ${value.expressions.length} expressions`,
);
}
const textXref = unit.job.allocateXrefId();
unit.create.push(ir.createTextOp(textXref, '', icuPlaceholder, text.sourceSpan));
// TemplateDefinitionBuilder does not generate source maps for sub-expressions inside an
// interpolation. We copy that behavior in compatibility mode.
// TODO: is it actually correct to generate these extra maps in modern mode?
const baseSourceSpan = unit.job.compatibility ? null : text.sourceSpan;
unit.update.push(
ir.createInterpolateTextOp(
textXref,
new ir.Interpolation(
value.strings,
value.expressions.map((expr) => convertAst(expr, unit.job, baseSourceSpan)),
i18nPlaceholders,
),
text.sourceSpan,
),
);
}
/**
* Ingest an `@if` block into the given `ViewCompilation`.
*/ | {
"end_byte": 15676,
"start_byte": 7621,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/ingest.ts"
} |
angular/packages/compiler/src/template/pipeline/src/ingest.ts_15677_23161 | function ingestIfBlock(unit: ViewCompilationUnit, ifBlock: t.IfBlock): void {
let firstXref: ir.XrefId | null = null;
let conditions: Array<ir.ConditionalCaseExpr> = [];
for (let i = 0; i < ifBlock.branches.length; i++) {
const ifCase = ifBlock.branches[i];
const cView = unit.job.allocateView(unit.xref);
const tagName = ingestControlFlowInsertionPoint(unit, cView.xref, ifCase);
if (ifCase.expressionAlias !== null) {
cView.contextVariables.set(ifCase.expressionAlias.name, ir.CTX_REF);
}
let ifCaseI18nMeta: i18n.BlockPlaceholder | undefined = undefined;
if (ifCase.i18n !== undefined) {
if (!(ifCase.i18n instanceof i18n.BlockPlaceholder)) {
throw Error(`Unhandled i18n metadata type for if block: ${ifCase.i18n?.constructor.name}`);
}
ifCaseI18nMeta = ifCase.i18n;
}
const templateOp = ir.createTemplateOp(
cView.xref,
ir.TemplateKind.Block,
tagName,
'Conditional',
ir.Namespace.HTML,
ifCaseI18nMeta,
ifCase.startSourceSpan,
ifCase.sourceSpan,
);
unit.create.push(templateOp);
if (firstXref === null) {
firstXref = cView.xref;
}
const caseExpr = ifCase.expression ? convertAst(ifCase.expression, unit.job, null) : null;
const conditionalCaseExpr = new ir.ConditionalCaseExpr(
caseExpr,
templateOp.xref,
templateOp.handle,
ifCase.expressionAlias,
);
conditions.push(conditionalCaseExpr);
ingestNodes(cView, ifCase.children);
}
unit.update.push(ir.createConditionalOp(firstXref!, null, conditions, ifBlock.sourceSpan));
}
/**
* Ingest an `@switch` block into the given `ViewCompilation`.
*/
function ingestSwitchBlock(unit: ViewCompilationUnit, switchBlock: t.SwitchBlock): void {
// Don't ingest empty switches since they won't render anything.
if (switchBlock.cases.length === 0) {
return;
}
let firstXref: ir.XrefId | null = null;
let conditions: Array<ir.ConditionalCaseExpr> = [];
for (const switchCase of switchBlock.cases) {
const cView = unit.job.allocateView(unit.xref);
const tagName = ingestControlFlowInsertionPoint(unit, cView.xref, switchCase);
let switchCaseI18nMeta: i18n.BlockPlaceholder | undefined = undefined;
if (switchCase.i18n !== undefined) {
if (!(switchCase.i18n instanceof i18n.BlockPlaceholder)) {
throw Error(
`Unhandled i18n metadata type for switch block: ${switchCase.i18n?.constructor.name}`,
);
}
switchCaseI18nMeta = switchCase.i18n;
}
const templateOp = ir.createTemplateOp(
cView.xref,
ir.TemplateKind.Block,
tagName,
'Case',
ir.Namespace.HTML,
switchCaseI18nMeta,
switchCase.startSourceSpan,
switchCase.sourceSpan,
);
unit.create.push(templateOp);
if (firstXref === null) {
firstXref = cView.xref;
}
const caseExpr = switchCase.expression
? convertAst(switchCase.expression, unit.job, switchBlock.startSourceSpan)
: null;
const conditionalCaseExpr = new ir.ConditionalCaseExpr(
caseExpr,
templateOp.xref,
templateOp.handle,
);
conditions.push(conditionalCaseExpr);
ingestNodes(cView, switchCase.children);
}
unit.update.push(
ir.createConditionalOp(
firstXref!,
convertAst(switchBlock.expression, unit.job, null),
conditions,
switchBlock.sourceSpan,
),
);
}
function ingestDeferView(
unit: ViewCompilationUnit,
suffix: string,
i18nMeta: i18n.I18nMeta | undefined,
children?: t.Node[],
sourceSpan?: ParseSourceSpan,
): ir.TemplateOp | null {
if (i18nMeta !== undefined && !(i18nMeta instanceof i18n.BlockPlaceholder)) {
throw Error('Unhandled i18n metadata type for defer block');
}
if (children === undefined) {
return null;
}
const secondaryView = unit.job.allocateView(unit.xref);
ingestNodes(secondaryView, children);
const templateOp = ir.createTemplateOp(
secondaryView.xref,
ir.TemplateKind.Block,
null,
`Defer${suffix}`,
ir.Namespace.HTML,
i18nMeta,
sourceSpan!,
sourceSpan!,
);
unit.create.push(templateOp);
return templateOp;
}
function ingestDeferBlock(unit: ViewCompilationUnit, deferBlock: t.DeferredBlock): void {
let ownResolverFn: o.Expression | null = null;
if (unit.job.deferMeta.mode === DeferBlockDepsEmitMode.PerBlock) {
if (!unit.job.deferMeta.blocks.has(deferBlock)) {
throw new Error(
`AssertionError: unable to find a dependency function for this deferred block`,
);
}
ownResolverFn = unit.job.deferMeta.blocks.get(deferBlock) ?? null;
}
// Generate the defer main view and all secondary views.
const main = ingestDeferView(
unit,
'',
deferBlock.i18n,
deferBlock.children,
deferBlock.sourceSpan,
)!;
const loading = ingestDeferView(
unit,
'Loading',
deferBlock.loading?.i18n,
deferBlock.loading?.children,
deferBlock.loading?.sourceSpan,
);
const placeholder = ingestDeferView(
unit,
'Placeholder',
deferBlock.placeholder?.i18n,
deferBlock.placeholder?.children,
deferBlock.placeholder?.sourceSpan,
);
const error = ingestDeferView(
unit,
'Error',
deferBlock.error?.i18n,
deferBlock.error?.children,
deferBlock.error?.sourceSpan,
);
// Create the main defer op, and ops for all secondary views.
const deferXref = unit.job.allocateXrefId();
const deferOp = ir.createDeferOp(
deferXref,
main.xref,
main.handle,
ownResolverFn,
unit.job.allDeferrableDepsFn,
deferBlock.sourceSpan,
);
deferOp.placeholderView = placeholder?.xref ?? null;
deferOp.placeholderSlot = placeholder?.handle ?? null;
deferOp.loadingSlot = loading?.handle ?? null;
deferOp.errorSlot = error?.handle ?? null;
deferOp.placeholderMinimumTime = deferBlock.placeholder?.minimumTime ?? null;
deferOp.loadingMinimumTime = deferBlock.loading?.minimumTime ?? null;
deferOp.loadingAfterTime = deferBlock.loading?.afterTime ?? null;
unit.create.push(deferOp);
// Configure all defer `on` conditions.
// TODO: refactor prefetch triggers to use a separate op type, with a shared superclass. This will
// make it easier to refactor prefetch behavior in the future.
const deferOnOps: ir.DeferOnOp[] = [];
const deferWhenOps: ir.DeferWhenOp[] = [];
// Ingest the hydrate triggers first since they set up all the other triggers during SSR.
ingestDeferTriggers(
ir.DeferOpModifierKind.HYDRATE,
deferBlock.hydrateTriggers,
deferOnOps,
deferWhenOps,
unit,
deferXref,
);
ingestDeferTriggers(
ir.DeferOpModifierKind.NONE,
deferBlock.triggers,
deferOnOps,
deferWhenOps,
unit,
deferXref,
);
ingestDeferTriggers(
ir.DeferOpModifierKind.PREFETCH,
deferBlock.prefetchTriggers,
deferOnOps,
deferWhenOps,
unit,
deferXref,
);
// If no (non-prefetching or hydrating) defer triggers were provided, default to `idle`.
const hasConcreteTrigger =
deferOnOps.some((op) => op.modifier === ir.DeferOpModifierKind.NONE) ||
deferWhenOps.some((op) => op.modifier === ir.DeferOpModifierKind.NONE);
if (!hasConcreteTrigger) {
deferOnOps.push(
ir.createDeferOnOp(
deferXref,
{kind: ir.DeferTriggerKind.Idle},
ir.DeferOpModifierKind.NONE,
null!,
),
);
}
unit.create.push(deferOnOps);
unit.update.push(deferWhenOps);
} | {
"end_byte": 23161,
"start_byte": 15677,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/ingest.ts"
} |
angular/packages/compiler/src/template/pipeline/src/ingest.ts_23163_30382 | function ingestDeferTriggers(
modifier: ir.DeferOpModifierKind,
triggers: Readonly<t.DeferredBlockTriggers>,
onOps: ir.DeferOnOp[],
whenOps: ir.DeferWhenOp[],
unit: ViewCompilationUnit,
deferXref: ir.XrefId,
) {
if (triggers.idle !== undefined) {
const deferOnOp = ir.createDeferOnOp(
deferXref,
{kind: ir.DeferTriggerKind.Idle},
modifier,
triggers.idle.sourceSpan,
);
onOps.push(deferOnOp);
}
if (triggers.immediate !== undefined) {
const deferOnOp = ir.createDeferOnOp(
deferXref,
{kind: ir.DeferTriggerKind.Immediate},
modifier,
triggers.immediate.sourceSpan,
);
onOps.push(deferOnOp);
}
if (triggers.timer !== undefined) {
const deferOnOp = ir.createDeferOnOp(
deferXref,
{kind: ir.DeferTriggerKind.Timer, delay: triggers.timer.delay},
modifier,
triggers.timer.sourceSpan,
);
onOps.push(deferOnOp);
}
if (triggers.hover !== undefined) {
const deferOnOp = ir.createDeferOnOp(
deferXref,
{
kind: ir.DeferTriggerKind.Hover,
targetName: triggers.hover.reference,
targetXref: null,
targetSlot: null,
targetView: null,
targetSlotViewSteps: null,
},
modifier,
triggers.hover.sourceSpan,
);
onOps.push(deferOnOp);
}
if (triggers.interaction !== undefined) {
const deferOnOp = ir.createDeferOnOp(
deferXref,
{
kind: ir.DeferTriggerKind.Interaction,
targetName: triggers.interaction.reference,
targetXref: null,
targetSlot: null,
targetView: null,
targetSlotViewSteps: null,
},
modifier,
triggers.interaction.sourceSpan,
);
onOps.push(deferOnOp);
}
if (triggers.viewport !== undefined) {
const deferOnOp = ir.createDeferOnOp(
deferXref,
{
kind: ir.DeferTriggerKind.Viewport,
targetName: triggers.viewport.reference,
targetXref: null,
targetSlot: null,
targetView: null,
targetSlotViewSteps: null,
},
modifier,
triggers.viewport.sourceSpan,
);
onOps.push(deferOnOp);
}
if (triggers.never !== undefined) {
const deferOnOp = ir.createDeferOnOp(
deferXref,
{kind: ir.DeferTriggerKind.Never},
modifier,
triggers.never.sourceSpan,
);
onOps.push(deferOnOp);
}
if (triggers.when !== undefined) {
if (triggers.when.value instanceof e.Interpolation) {
// TemplateDefinitionBuilder supports this case, but it's very strange to me. What would it
// even mean?
throw new Error(`Unexpected interpolation in defer block when trigger`);
}
const deferOnOp = ir.createDeferWhenOp(
deferXref,
convertAst(triggers.when.value, unit.job, triggers.when.sourceSpan),
modifier,
triggers.when.sourceSpan,
);
whenOps.push(deferOnOp);
}
}
function ingestIcu(unit: ViewCompilationUnit, icu: t.Icu) {
if (icu.i18n instanceof i18n.Message && isSingleI18nIcu(icu.i18n)) {
const xref = unit.job.allocateXrefId();
unit.create.push(ir.createIcuStartOp(xref, icu.i18n, icuFromI18nMessage(icu.i18n).name, null!));
for (const [placeholder, text] of Object.entries({...icu.vars, ...icu.placeholders})) {
if (text instanceof t.BoundText) {
ingestBoundText(unit, text, placeholder);
} else {
ingestText(unit, text, placeholder);
}
}
unit.create.push(ir.createIcuEndOp(xref));
} else {
throw Error(`Unhandled i18n metadata type for ICU: ${icu.i18n?.constructor.name}`);
}
}
/**
* Ingest an `@for` block into the given `ViewCompilation`.
*/
function ingestForBlock(unit: ViewCompilationUnit, forBlock: t.ForLoopBlock): void {
const repeaterView = unit.job.allocateView(unit.xref);
// We copy TemplateDefinitionBuilder's scheme of creating names for `$count` and `$index`
// that are suffixed with special information, to disambiguate which level of nested loop
// the below aliases refer to.
// TODO: We should refactor Template Pipeline's variable phases to gracefully handle
// shadowing, and arbitrarily many levels of variables depending on each other.
const indexName = `ɵ$index_${repeaterView.xref}`;
const countName = `ɵ$count_${repeaterView.xref}`;
const indexVarNames = new Set<string>();
// Set all the context variables and aliases available in the repeater.
repeaterView.contextVariables.set(forBlock.item.name, forBlock.item.value);
for (const variable of forBlock.contextVariables) {
if (variable.value === '$index') {
indexVarNames.add(variable.name);
}
if (variable.name === '$index') {
repeaterView.contextVariables.set('$index', variable.value).set(indexName, variable.value);
} else if (variable.name === '$count') {
repeaterView.contextVariables.set('$count', variable.value).set(countName, variable.value);
} else {
repeaterView.aliases.add({
kind: ir.SemanticVariableKind.Alias,
name: null,
identifier: variable.name,
expression: getComputedForLoopVariableExpression(variable, indexName, countName),
});
}
}
const sourceSpan = convertSourceSpan(forBlock.trackBy.span, forBlock.sourceSpan);
const track = convertAst(forBlock.trackBy, unit.job, sourceSpan);
ingestNodes(repeaterView, forBlock.children);
let emptyView: ViewCompilationUnit | null = null;
let emptyTagName: string | null = null;
if (forBlock.empty !== null) {
emptyView = unit.job.allocateView(unit.xref);
ingestNodes(emptyView, forBlock.empty.children);
emptyTagName = ingestControlFlowInsertionPoint(unit, emptyView.xref, forBlock.empty);
}
const varNames: ir.RepeaterVarNames = {
$index: indexVarNames,
$implicit: forBlock.item.name,
};
if (forBlock.i18n !== undefined && !(forBlock.i18n instanceof i18n.BlockPlaceholder)) {
throw Error('AssertionError: Unhandled i18n metadata type or @for');
}
if (
forBlock.empty?.i18n !== undefined &&
!(forBlock.empty.i18n instanceof i18n.BlockPlaceholder)
) {
throw Error('AssertionError: Unhandled i18n metadata type or @empty');
}
const i18nPlaceholder = forBlock.i18n;
const emptyI18nPlaceholder = forBlock.empty?.i18n;
const tagName = ingestControlFlowInsertionPoint(unit, repeaterView.xref, forBlock);
const repeaterCreate = ir.createRepeaterCreateOp(
repeaterView.xref,
emptyView?.xref ?? null,
tagName,
track,
varNames,
emptyTagName,
i18nPlaceholder,
emptyI18nPlaceholder,
forBlock.startSourceSpan,
forBlock.sourceSpan,
);
unit.create.push(repeaterCreate);
const expression = convertAst(
forBlock.expression,
unit.job,
convertSourceSpan(forBlock.expression.span, forBlock.sourceSpan),
);
const repeater = ir.createRepeaterOp(
repeaterCreate.xref,
repeaterCreate.handle,
expression,
forBlock.sourceSpan,
);
unit.update.push(repeater);
}
/**
* Gets an expression that represents a variable in an `@for` loop.
* @param variable AST representing the variable.
* @param indexName Loop-specific name for `$index`.
* @param countName Loop-specific name for `$count`.
*/
f | {
"end_byte": 30382,
"start_byte": 23163,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/ingest.ts"
} |
angular/packages/compiler/src/template/pipeline/src/ingest.ts_30383_38293 | nction getComputedForLoopVariableExpression(
variable: t.Variable,
indexName: string,
countName: string,
): o.Expression {
switch (variable.value) {
case '$index':
return new ir.LexicalReadExpr(indexName);
case '$count':
return new ir.LexicalReadExpr(countName);
case '$first':
return new ir.LexicalReadExpr(indexName).identical(o.literal(0));
case '$last':
return new ir.LexicalReadExpr(indexName).identical(
new ir.LexicalReadExpr(countName).minus(o.literal(1)),
);
case '$even':
return new ir.LexicalReadExpr(indexName).modulo(o.literal(2)).identical(o.literal(0));
case '$odd':
return new ir.LexicalReadExpr(indexName).modulo(o.literal(2)).notIdentical(o.literal(0));
default:
throw new Error(`AssertionError: unknown @for loop variable ${variable.value}`);
}
}
function ingestLetDeclaration(unit: ViewCompilationUnit, node: t.LetDeclaration) {
const target = unit.job.allocateXrefId();
unit.create.push(ir.createDeclareLetOp(target, node.name, node.sourceSpan));
unit.update.push(
ir.createStoreLetOp(
target,
node.name,
convertAst(node.value, unit.job, node.valueSpan),
node.sourceSpan,
),
);
}
/**
* Convert a template AST expression into an output AST expression.
*/
function convertAst(
ast: e.AST,
job: CompilationJob,
baseSourceSpan: ParseSourceSpan | null,
): o.Expression {
if (ast instanceof e.ASTWithSource) {
return convertAst(ast.ast, job, baseSourceSpan);
} else if (ast instanceof e.PropertyRead) {
// Whether this is an implicit receiver, *excluding* explicit reads of `this`.
const isImplicitReceiver =
ast.receiver instanceof e.ImplicitReceiver && !(ast.receiver instanceof e.ThisReceiver);
if (isImplicitReceiver) {
return new ir.LexicalReadExpr(ast.name);
} else {
return new o.ReadPropExpr(
convertAst(ast.receiver, job, baseSourceSpan),
ast.name,
null,
convertSourceSpan(ast.span, baseSourceSpan),
);
}
} else if (ast instanceof e.PropertyWrite) {
if (ast.receiver instanceof e.ImplicitReceiver) {
return new o.WritePropExpr(
// TODO: Is it correct to always use the root context in place of the implicit receiver?
new ir.ContextExpr(job.root.xref),
ast.name,
convertAst(ast.value, job, baseSourceSpan),
null,
convertSourceSpan(ast.span, baseSourceSpan),
);
}
return new o.WritePropExpr(
convertAst(ast.receiver, job, baseSourceSpan),
ast.name,
convertAst(ast.value, job, baseSourceSpan),
undefined,
convertSourceSpan(ast.span, baseSourceSpan),
);
} else if (ast instanceof e.KeyedWrite) {
return new o.WriteKeyExpr(
convertAst(ast.receiver, job, baseSourceSpan),
convertAst(ast.key, job, baseSourceSpan),
convertAst(ast.value, job, baseSourceSpan),
undefined,
convertSourceSpan(ast.span, baseSourceSpan),
);
} else if (ast instanceof e.Call) {
if (ast.receiver instanceof e.ImplicitReceiver) {
throw new Error(`Unexpected ImplicitReceiver`);
} else {
return new o.InvokeFunctionExpr(
convertAst(ast.receiver, job, baseSourceSpan),
ast.args.map((arg) => convertAst(arg, job, baseSourceSpan)),
undefined,
convertSourceSpan(ast.span, baseSourceSpan),
);
}
} else if (ast instanceof e.LiteralPrimitive) {
return o.literal(ast.value, undefined, convertSourceSpan(ast.span, baseSourceSpan));
} else if (ast instanceof e.Unary) {
switch (ast.operator) {
case '+':
return new o.UnaryOperatorExpr(
o.UnaryOperator.Plus,
convertAst(ast.expr, job, baseSourceSpan),
undefined,
convertSourceSpan(ast.span, baseSourceSpan),
);
case '-':
return new o.UnaryOperatorExpr(
o.UnaryOperator.Minus,
convertAst(ast.expr, job, baseSourceSpan),
undefined,
convertSourceSpan(ast.span, baseSourceSpan),
);
default:
throw new Error(`AssertionError: unknown unary operator ${ast.operator}`);
}
} else if (ast instanceof e.Binary) {
const operator = BINARY_OPERATORS.get(ast.operation);
if (operator === undefined) {
throw new Error(`AssertionError: unknown binary operator ${ast.operation}`);
}
return new o.BinaryOperatorExpr(
operator,
convertAst(ast.left, job, baseSourceSpan),
convertAst(ast.right, job, baseSourceSpan),
undefined,
convertSourceSpan(ast.span, baseSourceSpan),
);
} else if (ast instanceof e.ThisReceiver) {
// TODO: should context expressions have source maps?
return new ir.ContextExpr(job.root.xref);
} else if (ast instanceof e.KeyedRead) {
return new o.ReadKeyExpr(
convertAst(ast.receiver, job, baseSourceSpan),
convertAst(ast.key, job, baseSourceSpan),
undefined,
convertSourceSpan(ast.span, baseSourceSpan),
);
} else if (ast instanceof e.Chain) {
throw new Error(`AssertionError: Chain in unknown context`);
} else if (ast instanceof e.LiteralMap) {
const entries = ast.keys.map((key, idx) => {
const value = ast.values[idx];
// TODO: should literals have source maps, or do we just map the whole surrounding
// expression?
return new o.LiteralMapEntry(key.key, convertAst(value, job, baseSourceSpan), key.quoted);
});
return new o.LiteralMapExpr(entries, undefined, convertSourceSpan(ast.span, baseSourceSpan));
} else if (ast instanceof e.LiteralArray) {
// TODO: should literals have source maps, or do we just map the whole surrounding expression?
return new o.LiteralArrayExpr(
ast.expressions.map((expr) => convertAst(expr, job, baseSourceSpan)),
);
} else if (ast instanceof e.Conditional) {
return new o.ConditionalExpr(
convertAst(ast.condition, job, baseSourceSpan),
convertAst(ast.trueExp, job, baseSourceSpan),
convertAst(ast.falseExp, job, baseSourceSpan),
undefined,
convertSourceSpan(ast.span, baseSourceSpan),
);
} else if (ast instanceof e.NonNullAssert) {
// A non-null assertion shouldn't impact generated instructions, so we can just drop it.
return convertAst(ast.expression, job, baseSourceSpan);
} else if (ast instanceof e.BindingPipe) {
// TODO: pipes should probably have source maps; figure out details.
return new ir.PipeBindingExpr(job.allocateXrefId(), new ir.SlotHandle(), ast.name, [
convertAst(ast.exp, job, baseSourceSpan),
...ast.args.map((arg) => convertAst(arg, job, baseSourceSpan)),
]);
} else if (ast instanceof e.SafeKeyedRead) {
return new ir.SafeKeyedReadExpr(
convertAst(ast.receiver, job, baseSourceSpan),
convertAst(ast.key, job, baseSourceSpan),
convertSourceSpan(ast.span, baseSourceSpan),
);
} else if (ast instanceof e.SafePropertyRead) {
// TODO: source span
return new ir.SafePropertyReadExpr(convertAst(ast.receiver, job, baseSourceSpan), ast.name);
} else if (ast instanceof e.SafeCall) {
// TODO: source span
return new ir.SafeInvokeFunctionExpr(
convertAst(ast.receiver, job, baseSourceSpan),
ast.args.map((a) => convertAst(a, job, baseSourceSpan)),
);
} else if (ast instanceof e.EmptyExpr) {
return new ir.EmptyExpr(convertSourceSpan(ast.span, baseSourceSpan));
} else if (ast instanceof e.PrefixNot) {
return o.not(
convertAst(ast.expression, job, baseSourceSpan),
convertSourceSpan(ast.span, baseSourceSpan),
);
} else if (ast instanceof e.TypeofExpression) {
return o.typeofExpr(convertAst(ast.expression, job, baseSourceSpan));
} else {
throw new Error(
`Unhandled expression type "${ast.constructor.name}" in file "${baseSourceSpan?.start.file.url}"`,
);
}
}
| {
"end_byte": 38293,
"start_byte": 30383,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/ingest.ts"
} |
angular/packages/compiler/src/template/pipeline/src/ingest.ts_38295_44070 | nction convertAstWithInterpolation(
job: CompilationJob,
value: e.AST | string,
i18nMeta: i18n.I18nMeta | null | undefined,
sourceSpan?: ParseSourceSpan,
): o.Expression | ir.Interpolation {
let expression: o.Expression | ir.Interpolation;
if (value instanceof e.Interpolation) {
expression = new ir.Interpolation(
value.strings,
value.expressions.map((e) => convertAst(e, job, sourceSpan ?? null)),
Object.keys(asMessage(i18nMeta)?.placeholders ?? {}),
);
} else if (value instanceof e.AST) {
expression = convertAst(value, job, sourceSpan ?? null);
} else {
expression = o.literal(value);
}
return expression;
}
// TODO: Can we populate Template binding kinds in ingest?
const BINDING_KINDS = new Map<e.BindingType, ir.BindingKind>([
[e.BindingType.Property, ir.BindingKind.Property],
[e.BindingType.TwoWay, ir.BindingKind.TwoWayProperty],
[e.BindingType.Attribute, ir.BindingKind.Attribute],
[e.BindingType.Class, ir.BindingKind.ClassName],
[e.BindingType.Style, ir.BindingKind.StyleProperty],
[e.BindingType.Animation, ir.BindingKind.Animation],
]);
/**
* Checks whether the given template is a plain ng-template (as opposed to another kind of template
* such as a structural directive template or control flow template). This is checked based on the
* tagName. We can expect that only plain ng-templates will come through with a tagName of
* 'ng-template'.
*
* Here are some of the cases we expect:
*
* | Angular HTML | Template tagName |
* | ---------------------------------- | ------------------ |
* | `<ng-template>` | 'ng-template' |
* | `<div *ngIf="true">` | 'div' |
* | `<svg><ng-template>` | 'svg:ng-template' |
* | `@if (true) {` | 'Conditional' |
* | `<ng-template *ngIf>` (plain) | 'ng-template' |
* | `<ng-template *ngIf>` (structural) | null |
*/
function isPlainTemplate(tmpl: t.Template) {
return splitNsName(tmpl.tagName ?? '')[1] === NG_TEMPLATE_TAG_NAME;
}
/**
* Ensures that the i18nMeta, if provided, is an i18n.Message.
*/
function asMessage(i18nMeta: i18n.I18nMeta | null | undefined): i18n.Message | null {
if (i18nMeta == null) {
return null;
}
if (!(i18nMeta instanceof i18n.Message)) {
throw Error(`Expected i18n meta to be a Message, but got: ${i18nMeta.constructor.name}`);
}
return i18nMeta;
}
/**
* Process all of the bindings on an element in the template AST and convert them to their IR
* representation.
*/
function ingestElementBindings(
unit: ViewCompilationUnit,
op: ir.ElementOpBase,
element: t.Element,
): void {
let bindings = new Array<ir.BindingOp | ir.ExtractedAttributeOp | null>();
let i18nAttributeBindingNames = new Set<string>();
for (const attr of element.attributes) {
// Attribute literal bindings, such as `attr.foo="bar"`.
const securityContext = domSchema.securityContext(element.name, attr.name, true);
bindings.push(
ir.createBindingOp(
op.xref,
ir.BindingKind.Attribute,
attr.name,
convertAstWithInterpolation(unit.job, attr.value, attr.i18n),
null,
securityContext,
true,
false,
null,
asMessage(attr.i18n),
attr.sourceSpan,
),
);
if (attr.i18n) {
i18nAttributeBindingNames.add(attr.name);
}
}
for (const input of element.inputs) {
if (i18nAttributeBindingNames.has(input.name)) {
console.error(
`On component ${unit.job.componentName}, the binding ${input.name} is both an i18n attribute and a property. You may want to remove the property binding. This will become a compilation error in future versions of Angular.`,
);
}
// All dynamic bindings (both attribute and property bindings).
bindings.push(
ir.createBindingOp(
op.xref,
BINDING_KINDS.get(input.type)!,
input.name,
convertAstWithInterpolation(unit.job, astOf(input.value), input.i18n),
input.unit,
input.securityContext,
false,
false,
null,
asMessage(input.i18n) ?? null,
input.sourceSpan,
),
);
}
unit.create.push(
bindings.filter((b): b is ir.ExtractedAttributeOp => b?.kind === ir.OpKind.ExtractedAttribute),
);
unit.update.push(bindings.filter((b): b is ir.BindingOp => b?.kind === ir.OpKind.Binding));
for (const output of element.outputs) {
if (output.type === e.ParsedEventType.Animation && output.phase === null) {
throw Error('Animation listener should have a phase');
}
if (output.type === e.ParsedEventType.TwoWay) {
unit.create.push(
ir.createTwoWayListenerOp(
op.xref,
op.handle,
output.name,
op.tag,
makeTwoWayListenerHandlerOps(unit, output.handler, output.handlerSpan),
output.sourceSpan,
),
);
} else {
unit.create.push(
ir.createListenerOp(
op.xref,
op.handle,
output.name,
op.tag,
makeListenerHandlerOps(unit, output.handler, output.handlerSpan),
output.phase,
output.target,
false,
output.sourceSpan,
),
);
}
}
// If any of the bindings on this element have an i18n message, then an i18n attrs configuration
// op is also required.
if (bindings.some((b) => b?.i18nMessage) !== null) {
unit.create.push(
ir.createI18nAttributesOp(unit.job.allocateXrefId(), new ir.SlotHandle(), op.xref),
);
}
}
/**
* Process all of the bindings on a template in the template AST and convert them to their IR
* representation.
*/
f | {
"end_byte": 44070,
"start_byte": 38295,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/ingest.ts"
} |
angular/packages/compiler/src/template/pipeline/src/ingest.ts_44071_49945 | nction ingestTemplateBindings(
unit: ViewCompilationUnit,
op: ir.ElementOpBase,
template: t.Template,
templateKind: ir.TemplateKind | null,
): void {
let bindings = new Array<ir.BindingOp | ir.ExtractedAttributeOp | null>();
for (const attr of template.templateAttrs) {
if (attr instanceof t.TextAttribute) {
const securityContext = domSchema.securityContext(NG_TEMPLATE_TAG_NAME, attr.name, true);
bindings.push(
createTemplateBinding(
unit,
op.xref,
e.BindingType.Attribute,
attr.name,
attr.value,
null,
securityContext,
true,
templateKind,
asMessage(attr.i18n),
attr.sourceSpan,
),
);
} else {
bindings.push(
createTemplateBinding(
unit,
op.xref,
attr.type,
attr.name,
astOf(attr.value),
attr.unit,
attr.securityContext,
true,
templateKind,
asMessage(attr.i18n),
attr.sourceSpan,
),
);
}
}
for (const attr of template.attributes) {
// Attribute literal bindings, such as `attr.foo="bar"`.
const securityContext = domSchema.securityContext(NG_TEMPLATE_TAG_NAME, attr.name, true);
bindings.push(
createTemplateBinding(
unit,
op.xref,
e.BindingType.Attribute,
attr.name,
attr.value,
null,
securityContext,
false,
templateKind,
asMessage(attr.i18n),
attr.sourceSpan,
),
);
}
for (const input of template.inputs) {
// Dynamic bindings (both attribute and property bindings).
bindings.push(
createTemplateBinding(
unit,
op.xref,
input.type,
input.name,
astOf(input.value),
input.unit,
input.securityContext,
false,
templateKind,
asMessage(input.i18n),
input.sourceSpan,
),
);
}
unit.create.push(
bindings.filter((b): b is ir.ExtractedAttributeOp => b?.kind === ir.OpKind.ExtractedAttribute),
);
unit.update.push(bindings.filter((b): b is ir.BindingOp => b?.kind === ir.OpKind.Binding));
for (const output of template.outputs) {
if (output.type === e.ParsedEventType.Animation && output.phase === null) {
throw Error('Animation listener should have a phase');
}
if (templateKind === ir.TemplateKind.NgTemplate) {
if (output.type === e.ParsedEventType.TwoWay) {
unit.create.push(
ir.createTwoWayListenerOp(
op.xref,
op.handle,
output.name,
op.tag,
makeTwoWayListenerHandlerOps(unit, output.handler, output.handlerSpan),
output.sourceSpan,
),
);
} else {
unit.create.push(
ir.createListenerOp(
op.xref,
op.handle,
output.name,
op.tag,
makeListenerHandlerOps(unit, output.handler, output.handlerSpan),
output.phase,
output.target,
false,
output.sourceSpan,
),
);
}
}
if (
templateKind === ir.TemplateKind.Structural &&
output.type !== e.ParsedEventType.Animation
) {
// Animation bindings are excluded from the structural template's const array.
const securityContext = domSchema.securityContext(NG_TEMPLATE_TAG_NAME, output.name, false);
unit.create.push(
ir.createExtractedAttributeOp(
op.xref,
ir.BindingKind.Property,
null,
output.name,
null,
null,
null,
securityContext,
),
);
}
}
// TODO: Perhaps we could do this in a phase? (It likely wouldn't change the slot indices.)
if (bindings.some((b) => b?.i18nMessage) !== null) {
unit.create.push(
ir.createI18nAttributesOp(unit.job.allocateXrefId(), new ir.SlotHandle(), op.xref),
);
}
}
/**
* Helper to ingest an individual binding on a template, either an explicit `ng-template`, or an
* implicit template created via structural directive.
*
* Bindings on templates are *extremely* tricky. I have tried to isolate all of the confusing edge
* cases into this function, and to comment it well to document the behavior.
*
* Some of this behavior is intuitively incorrect, and we should consider changing it in the future.
*
* @param view The compilation unit for the view containing the template.
* @param xref The xref of the template op.
* @param type The binding type, according to the parser. This is fairly reasonable, e.g. both
* dynamic and static attributes have e.BindingType.Attribute.
* @param name The binding's name.
* @param value The bindings's value, which will either be an input AST expression, or a string
* literal. Note that the input AST expression may or may not be const -- it will only be a
* string literal if the parser considered it a text binding.
* @param unit If the binding has a unit (e.g. `px` for style bindings), then this is the unit.
* @param securityContext The security context of the binding.
* @param isStructuralTemplateAttribute Whether this binding actually applies to the structural
* ng-template. For example, an `ngFor` would actually apply to the structural template. (Most
* bindings on structural elements target the inner element, not the template.)
* @param templateKind Whether this is an explicit `ng-template` or an implicit template created by
* a structural directive. This should never be a block template.
* @param i18nMessage The i18n metadata for the binding, if any.
* @param sourceSpan The source span of the binding.
* @returns An IR binding op, or null if the binding should be skipped.
*/
f | {
"end_byte": 49945,
"start_byte": 44071,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/ingest.ts"
} |
angular/packages/compiler/src/template/pipeline/src/ingest.ts_49946_57173 | nction createTemplateBinding(
view: ViewCompilationUnit,
xref: ir.XrefId,
type: e.BindingType,
name: string,
value: e.AST | string,
unit: string | null,
securityContext: SecurityContext,
isStructuralTemplateAttribute: boolean,
templateKind: ir.TemplateKind | null,
i18nMessage: i18n.Message | null,
sourceSpan: ParseSourceSpan,
): ir.BindingOp | ir.ExtractedAttributeOp | null {
const isTextBinding = typeof value === 'string';
// If this is a structural template, then several kinds of bindings should not result in an
// update instruction.
if (templateKind === ir.TemplateKind.Structural) {
if (!isStructuralTemplateAttribute) {
switch (type) {
case e.BindingType.Property:
case e.BindingType.Class:
case e.BindingType.Style:
// Because this binding doesn't really target the ng-template, it must be a binding on an
// inner node of a structural template. We can't skip it entirely, because we still need
// it on the ng-template's consts (e.g. for the purposes of directive matching). However,
// we should not generate an update instruction for it.
return ir.createExtractedAttributeOp(
xref,
ir.BindingKind.Property,
null,
name,
null,
null,
i18nMessage,
securityContext,
);
case e.BindingType.TwoWay:
return ir.createExtractedAttributeOp(
xref,
ir.BindingKind.TwoWayProperty,
null,
name,
null,
null,
i18nMessage,
securityContext,
);
}
}
if (!isTextBinding && (type === e.BindingType.Attribute || type === e.BindingType.Animation)) {
// Again, this binding doesn't really target the ng-template; it actually targets the element
// inside the structural template. In the case of non-text attribute or animation bindings,
// the binding doesn't even show up on the ng-template const array, so we just skip it
// entirely.
return null;
}
}
let bindingType = BINDING_KINDS.get(type)!;
if (templateKind === ir.TemplateKind.NgTemplate) {
// We know we are dealing with bindings directly on an explicit ng-template.
// Static attribute bindings should be collected into the const array as k/v pairs. Property
// bindings should result in a `property` instruction, and `AttributeMarker.Bindings` const
// entries.
//
// The difficulty is with dynamic attribute, style, and class bindings. These don't really make
// sense on an `ng-template` and should probably be parser errors. However,
// TemplateDefinitionBuilder generates `property` instructions for them, and so we do that as
// well.
//
// Note that we do have a slight behavior difference with TemplateDefinitionBuilder: although
// TDB emits `property` instructions for dynamic attributes, styles, and classes, only styles
// and classes also get const collected into the `AttributeMarker.Bindings` field. Dynamic
// attribute bindings are missing from the consts entirely. We choose to emit them into the
// consts field anyway, to avoid creating special cases for something so arcane and nonsensical.
if (
type === e.BindingType.Class ||
type === e.BindingType.Style ||
(type === e.BindingType.Attribute && !isTextBinding)
) {
// TODO: These cases should be parse errors.
bindingType = ir.BindingKind.Property;
}
}
return ir.createBindingOp(
xref,
bindingType,
name,
convertAstWithInterpolation(view.job, value, i18nMessage),
unit,
securityContext,
isTextBinding,
isStructuralTemplateAttribute,
templateKind,
i18nMessage,
sourceSpan,
);
}
function makeListenerHandlerOps(
unit: CompilationUnit,
handler: e.AST,
handlerSpan: ParseSourceSpan,
): ir.UpdateOp[] {
handler = astOf(handler);
const handlerOps = new Array<ir.UpdateOp>();
let handlerExprs: e.AST[] = handler instanceof e.Chain ? handler.expressions : [handler];
if (handlerExprs.length === 0) {
throw new Error('Expected listener to have non-empty expression list.');
}
const expressions = handlerExprs.map((expr) => convertAst(expr, unit.job, handlerSpan));
const returnExpr = expressions.pop()!;
handlerOps.push(
...expressions.map((e) =>
ir.createStatementOp<ir.UpdateOp>(new o.ExpressionStatement(e, e.sourceSpan)),
),
);
handlerOps.push(ir.createStatementOp(new o.ReturnStatement(returnExpr, returnExpr.sourceSpan)));
return handlerOps;
}
function makeTwoWayListenerHandlerOps(
unit: CompilationUnit,
handler: e.AST,
handlerSpan: ParseSourceSpan,
): ir.UpdateOp[] {
handler = astOf(handler);
const handlerOps = new Array<ir.UpdateOp>();
if (handler instanceof e.Chain) {
if (handler.expressions.length === 1) {
handler = handler.expressions[0];
} else {
// This is validated during parsing already, but we do it here just in case.
throw new Error('Expected two-way listener to have a single expression.');
}
}
const handlerExpr = convertAst(handler, unit.job, handlerSpan);
const eventReference = new ir.LexicalReadExpr('$event');
const twoWaySetExpr = new ir.TwoWayBindingSetExpr(handlerExpr, eventReference);
handlerOps.push(ir.createStatementOp<ir.UpdateOp>(new o.ExpressionStatement(twoWaySetExpr)));
handlerOps.push(ir.createStatementOp(new o.ReturnStatement(eventReference)));
return handlerOps;
}
function astOf(ast: e.AST | e.ASTWithSource): e.AST {
return ast instanceof e.ASTWithSource ? ast.ast : ast;
}
/**
* Process all of the local references on an element-like structure in the template AST and
* convert them to their IR representation.
*/
function ingestReferences(op: ir.ElementOpBase, element: t.Element | t.Template): void {
assertIsArray<ir.LocalRef>(op.localRefs);
for (const {name, value} of element.references) {
op.localRefs.push({
name,
target: value,
});
}
}
/**
* Assert that the given value is an array.
*/
function assertIsArray<T>(value: any): asserts value is Array<T> {
if (!Array.isArray(value)) {
throw new Error(`AssertionError: expected an array`);
}
}
/**
* Creates an absolute `ParseSourceSpan` from the relative `ParseSpan`.
*
* `ParseSpan` objects are relative to the start of the expression.
* This method converts these to full `ParseSourceSpan` objects that
* show where the span is within the overall source file.
*
* @param span the relative span to convert.
* @param baseSourceSpan a span corresponding to the base of the expression tree.
* @returns a `ParseSourceSpan` for the given span or null if no `baseSourceSpan` was provided.
*/
function convertSourceSpan(
span: e.ParseSpan,
baseSourceSpan: ParseSourceSpan | null,
): ParseSourceSpan | null {
if (baseSourceSpan === null) {
return null;
}
const start = baseSourceSpan.start.moveBy(span.start);
const end = baseSourceSpan.start.moveBy(span.end);
const fullStart = baseSourceSpan.fullStart.moveBy(span.start);
return new ParseSourceSpan(start, end, fullStart);
}
| {
"end_byte": 57173,
"start_byte": 49946,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/ingest.ts"
} |
angular/packages/compiler/src/template/pipeline/src/ingest.ts_57175_61114 | *
* With the directive-based control flow users were able to conditionally project content using
* the `*` syntax. E.g. `<div *ngIf="expr" projectMe></div>` will be projected into
* `<ng-content select="[projectMe]"/>`, because the attributes and tag name from the `div` are
* copied to the template via the template creation instruction. With `@if` and `@for` that is
* not the case, because the conditional is placed *around* elements, rather than *on* them.
* The result is that content projection won't work in the same way if a user converts from
* `*ngIf` to `@if`.
*
* This function aims to cover the most common case by doing the same copying when a control flow
* node has *one and only one* root element or template node.
*
* This approach comes with some caveats:
* 1. As soon as any other node is added to the root, the copying behavior won't work anymore.
* A diagnostic will be added to flag cases like this and to explain how to work around it.
* 2. If `preserveWhitespaces` is enabled, it's very likely that indentation will break this
* workaround, because it'll include an additional text node as the first child. We can work
* around it here, but in a discussion it was decided not to, because the user explicitly opted
* into preserving the whitespace and we would have to drop it from the generated code.
* The diagnostic mentioned point #1 will flag such cases to users.
*
* @returns Tag name to be used for the control flow template.
*/
function ingestControlFlowInsertionPoint(
unit: ViewCompilationUnit,
xref: ir.XrefId,
node: t.IfBlockBranch | t.SwitchBlockCase | t.ForLoopBlock | t.ForLoopBlockEmpty,
): string | null {
let root: t.Element | t.Template | null = null;
for (const child of node.children) {
// Skip over comment nodes.
if (child instanceof t.Comment) {
continue;
}
// We can only infer the tag name/attributes if there's a single root node.
if (root !== null) {
return null;
}
// Root nodes can only elements or templates with a tag name (e.g. `<div *foo></div>`).
if (child instanceof t.Element || (child instanceof t.Template && child.tagName !== null)) {
root = child;
}
}
// If we've found a single root node, its tag name and attributes can be
// copied to the surrounding template to be used for content projection.
if (root !== null) {
// Collect the static attributes for content projection purposes.
for (const attr of root.attributes) {
const securityContext = domSchema.securityContext(NG_TEMPLATE_TAG_NAME, attr.name, true);
unit.update.push(
ir.createBindingOp(
xref,
ir.BindingKind.Attribute,
attr.name,
o.literal(attr.value),
null,
securityContext,
true,
false,
null,
asMessage(attr.i18n),
attr.sourceSpan,
),
);
}
// Also collect the inputs since they participate in content projection as well.
// Note that TDB used to collect the outputs as well, but it wasn't passing them into
// the template instruction. Here we just don't collect them.
for (const attr of root.inputs) {
if (attr.type !== e.BindingType.Animation && attr.type !== e.BindingType.Attribute) {
const securityContext = domSchema.securityContext(NG_TEMPLATE_TAG_NAME, attr.name, true);
unit.create.push(
ir.createExtractedAttributeOp(
xref,
ir.BindingKind.Property,
null,
attr.name,
null,
null,
null,
securityContext,
),
);
}
}
const tagName = root instanceof t.Element ? root.name : root.tagName;
// Don't pass along `ng-template` tag name since it enables directive matching.
return tagName === NG_TEMPLATE_TAG_NAME ? null : tagName;
}
return null;
}
| {
"end_byte": 61114,
"start_byte": 57175,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/ingest.ts"
} |
angular/packages/compiler/src/template/pipeline/src/util/elements.ts_0_1146 | /**
* @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 {CompilationUnit} from '../compilation';
/**
* Gets a map of all elements in the given view by their xref id.
*/
export function createOpXrefMap(
unit: CompilationUnit,
): Map<ir.XrefId, ir.ConsumesSlotOpTrait & ir.CreateOp> {
const map = new Map<ir.XrefId, ir.ConsumesSlotOpTrait & ir.CreateOp>();
for (const op of unit.create) {
if (!ir.hasConsumesSlotTrait(op)) {
continue;
}
map.set(op.xref, op);
// 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) {
map.set(op.emptyView, op);
}
}
return map;
}
| {
"end_byte": 1146,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/util/elements.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/ng_container.ts_0_1143 | /**
* @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 CONTAINER_TAG = 'ng-container';
/**
* Replace an `Element` or `ElementStart` whose tag is `ng-container` with a specific op.
*/
export function generateNgContainerOps(job: CompilationJob): void {
for (const unit of job.units) {
const updatedElementXrefs = new Set<ir.XrefId>();
for (const op of unit.create) {
if (op.kind === ir.OpKind.ElementStart && op.tag === CONTAINER_TAG) {
// Transmute the `ElementStart` instruction to `ContainerStart`.
(op as ir.Op<ir.CreateOp>).kind = ir.OpKind.ContainerStart;
updatedElementXrefs.add(op.xref);
}
if (op.kind === ir.OpKind.ElementEnd && updatedElementXrefs.has(op.xref)) {
// This `ElementEnd` is associated with an `ElementStart` we already transmuted.
(op as ir.Op<ir.CreateOp>).kind = ir.OpKind.ContainerEnd;
}
}
}
}
| {
"end_byte": 1143,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/ng_container.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/track_variables.ts_0_1320 | /**
* @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';
/**
* Inside the `track` expression on a `for` repeater, the `$index` and `$item` variables are
* ambiently available. In this phase, we find those variable usages, and replace them with the
* appropriate output read.
*/
export function generateTrackVariables(job: CompilationJob): void {
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind !== ir.OpKind.RepeaterCreate) {
continue;
}
op.track = ir.transformExpressionsInExpression(
op.track,
(expr) => {
if (expr instanceof ir.LexicalReadExpr) {
if (op.varNames.$index.has(expr.name)) {
return o.variable('$index');
} else if (expr.name === op.varNames.$implicit) {
return o.variable('$item');
}
// TODO: handle prohibited context variables (emit as globals?)
}
return expr;
},
ir.VisitorContextFlag.None,
);
}
}
}
| {
"end_byte": 1320,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/track_variables.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/collapse_singleton_interpolations.ts_0_1272 | /**
* @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';
/**
* Attribute interpolations of the form `[attr.foo]="{{foo}}""` should be "collapsed" into a plain
* attribute instruction, instead of an `attributeInterpolate` instruction.
*
* (We cannot do this for singleton property interpolations, because `propertyInterpolate`
* stringifies its expression.)
*
* The reification step is also capable of performing this transformation, but doing it early in the
* pipeline allows other phases to accurately know what instruction will be emitted.
*/
export function collapseSingletonInterpolations(job: CompilationJob): void {
for (const unit of job.units) {
for (const op of unit.update) {
const eligibleOpKind = op.kind === ir.OpKind.Attribute;
if (
eligibleOpKind &&
op.expression instanceof ir.Interpolation &&
op.expression.strings.length === 2 &&
op.expression.strings.every((s: string) => s === '')
) {
op.expression = op.expression.expressions[0];
}
}
}
}
| {
"end_byte": 1272,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/collapse_singleton_interpolations.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/expand_safe_reads.ts_0_6909 | /**
* @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';
interface SafeTransformContext {
job: CompilationJob;
}
/**
* Safe read expressions such as `a?.b` have different semantics in Angular templates as
* compared to JavaScript. In particular, they default to `null` instead of `undefined`. This phase
* finds all unresolved safe read expressions, and converts them into the appropriate output AST
* reads, guarded by null checks. We generate temporaries as needed, to avoid re-evaluating the same
* sub-expression multiple times.
*/
export function expandSafeReads(job: CompilationJob): void {
for (const unit of job.units) {
for (const op of unit.ops()) {
ir.transformExpressionsInOp(op, (e) => safeTransform(e, {job}), ir.VisitorContextFlag.None);
ir.transformExpressionsInOp(op, ternaryTransform, ir.VisitorContextFlag.None);
}
}
}
// A lookup set of all the expression kinds that require a temporary variable to be generated.
const requiresTemporary = [
o.InvokeFunctionExpr,
o.LiteralArrayExpr,
o.LiteralMapExpr,
ir.SafeInvokeFunctionExpr,
ir.PipeBindingExpr,
].map((e) => e.constructor.name);
function needsTemporaryInSafeAccess(e: o.Expression): boolean {
// TODO: We probably want to use an expression visitor to recursively visit all descendents.
// However, that would potentially do a lot of extra work (because it cannot short circuit), so we
// implement the logic ourselves for now.
if (e instanceof o.UnaryOperatorExpr) {
return needsTemporaryInSafeAccess(e.expr);
} else if (e instanceof o.BinaryOperatorExpr) {
return needsTemporaryInSafeAccess(e.lhs) || needsTemporaryInSafeAccess(e.rhs);
} else if (e instanceof o.ConditionalExpr) {
if (e.falseCase && needsTemporaryInSafeAccess(e.falseCase)) return true;
return needsTemporaryInSafeAccess(e.condition) || needsTemporaryInSafeAccess(e.trueCase);
} else if (e instanceof o.NotExpr) {
return needsTemporaryInSafeAccess(e.condition);
} else if (e instanceof ir.AssignTemporaryExpr) {
return needsTemporaryInSafeAccess(e.expr);
} else if (e instanceof o.ReadPropExpr) {
return needsTemporaryInSafeAccess(e.receiver);
} else if (e instanceof o.ReadKeyExpr) {
return needsTemporaryInSafeAccess(e.receiver) || needsTemporaryInSafeAccess(e.index);
}
// TODO: Switch to a method which is exhaustive of newly added expression subtypes.
return (
e instanceof o.InvokeFunctionExpr ||
e instanceof o.LiteralArrayExpr ||
e instanceof o.LiteralMapExpr ||
e instanceof ir.SafeInvokeFunctionExpr ||
e instanceof ir.PipeBindingExpr
);
}
function temporariesIn(e: o.Expression): Set<ir.XrefId> {
const temporaries = new Set<ir.XrefId>();
// TODO: Although it's not currently supported by the transform helper, we should be able to
// short-circuit exploring the tree to do less work. In particular, we don't have to penetrate
// into the subexpressions of temporary assignments.
ir.transformExpressionsInExpression(
e,
(e) => {
if (e instanceof ir.AssignTemporaryExpr) {
temporaries.add(e.xref);
}
return e;
},
ir.VisitorContextFlag.None,
);
return temporaries;
}
function eliminateTemporaryAssignments(
e: o.Expression,
tmps: Set<ir.XrefId>,
ctx: SafeTransformContext,
): o.Expression {
// TODO: We can be more efficient than the transform helper here. We don't need to visit any
// descendents of temporary assignments.
ir.transformExpressionsInExpression(
e,
(e) => {
if (e instanceof ir.AssignTemporaryExpr && tmps.has(e.xref)) {
const read = new ir.ReadTemporaryExpr(e.xref);
// `TemplateDefinitionBuilder` has the (accidental?) behavior of generating assignments of
// temporary variables to themselves. This happens because some subexpression that the
// temporary refers to, possibly through nested temporaries, has a function call. We copy that
// behavior here.
return ctx.job.compatibility === ir.CompatibilityMode.TemplateDefinitionBuilder
? new ir.AssignTemporaryExpr(read, read.xref)
: read;
}
return e;
},
ir.VisitorContextFlag.None,
);
return e;
}
/**
* Creates a safe ternary guarded by the input expression, and with a body generated by the provided
* callback on the input expression. Generates a temporary variable assignment if needed, and
* deduplicates nested temporary assignments if needed.
*/
function safeTernaryWithTemporary(
guard: o.Expression,
body: (e: o.Expression) => o.Expression,
ctx: SafeTransformContext,
): ir.SafeTernaryExpr {
let result: [o.Expression, o.Expression];
if (needsTemporaryInSafeAccess(guard)) {
const xref = ctx.job.allocateXrefId();
result = [new ir.AssignTemporaryExpr(guard, xref), new ir.ReadTemporaryExpr(xref)];
} else {
result = [guard, guard.clone()];
// Consider an expression like `a?.[b?.c()]?.d`. The `b?.c()` will be transformed first,
// introducing a temporary assignment into the key. Then, as part of expanding the `?.d`. That
// assignment will be duplicated into both the guard and expression sides. We de-duplicate it,
// by transforming it from an assignment into a read on the expression side.
eliminateTemporaryAssignments(result[1], temporariesIn(result[0]), ctx);
}
return new ir.SafeTernaryExpr(result[0], body(result[1]));
}
function isSafeAccessExpression(
e: o.Expression,
): e is ir.SafePropertyReadExpr | ir.SafeKeyedReadExpr | ir.SafeInvokeFunctionExpr {
return (
e instanceof ir.SafePropertyReadExpr ||
e instanceof ir.SafeKeyedReadExpr ||
e instanceof ir.SafeInvokeFunctionExpr
);
}
function isUnsafeAccessExpression(
e: o.Expression,
): e is o.ReadPropExpr | o.ReadKeyExpr | o.InvokeFunctionExpr {
return (
e instanceof o.ReadPropExpr || e instanceof o.ReadKeyExpr || e instanceof o.InvokeFunctionExpr
);
}
function isAccessExpression(
e: o.Expression,
): e is
| o.ReadPropExpr
| ir.SafePropertyReadExpr
| o.ReadKeyExpr
| ir.SafeKeyedReadExpr
| o.InvokeFunctionExpr
| ir.SafeInvokeFunctionExpr {
return isSafeAccessExpression(e) || isUnsafeAccessExpression(e);
}
function deepestSafeTernary(e: o.Expression): ir.SafeTernaryExpr | null {
if (isAccessExpression(e) && e.receiver instanceof ir.SafeTernaryExpr) {
let st = e.receiver;
while (st.expr instanceof ir.SafeTernaryExpr) {
st = st.expr;
}
return st;
}
return null;
}
// TODO: When strict compatibility with TemplateDefinitionBuilder is not required, we can use `&&`
// instead to save some code size. | {
"end_byte": 6909,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/expand_safe_reads.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/expand_safe_reads.ts_6910_8693 | function safeTransform(e: o.Expression, ctx: SafeTransformContext): o.Expression {
if (!isAccessExpression(e)) {
return e;
}
const dst = deepestSafeTernary(e);
if (dst) {
if (e instanceof o.InvokeFunctionExpr) {
dst.expr = dst.expr.callFn(e.args);
return e.receiver;
}
if (e instanceof o.ReadPropExpr) {
dst.expr = dst.expr.prop(e.name);
return e.receiver;
}
if (e instanceof o.ReadKeyExpr) {
dst.expr = dst.expr.key(e.index);
return e.receiver;
}
if (e instanceof ir.SafeInvokeFunctionExpr) {
dst.expr = safeTernaryWithTemporary(dst.expr, (r: o.Expression) => r.callFn(e.args), ctx);
return e.receiver;
}
if (e instanceof ir.SafePropertyReadExpr) {
dst.expr = safeTernaryWithTemporary(dst.expr, (r: o.Expression) => r.prop(e.name), ctx);
return e.receiver;
}
if (e instanceof ir.SafeKeyedReadExpr) {
dst.expr = safeTernaryWithTemporary(dst.expr, (r: o.Expression) => r.key(e.index), ctx);
return e.receiver;
}
} else {
if (e instanceof ir.SafeInvokeFunctionExpr) {
return safeTernaryWithTemporary(e.receiver, (r: o.Expression) => r.callFn(e.args), ctx);
}
if (e instanceof ir.SafePropertyReadExpr) {
return safeTernaryWithTemporary(e.receiver, (r: o.Expression) => r.prop(e.name), ctx);
}
if (e instanceof ir.SafeKeyedReadExpr) {
return safeTernaryWithTemporary(e.receiver, (r: o.Expression) => r.key(e.index), ctx);
}
}
return e;
}
function ternaryTransform(e: o.Expression): o.Expression {
if (!(e instanceof ir.SafeTernaryExpr)) {
return e;
}
return new o.ConditionalExpr(
new o.BinaryOperatorExpr(o.BinaryOperator.Equals, e.guard, o.NULL_EXPR),
o.NULL_EXPR,
e.expr,
);
} | {
"end_byte": 8693,
"start_byte": 6910,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/expand_safe_reads.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/i18n_const_collection.ts_0_2580 | /**
* @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 {type ConstantPool} from '../../../../constant_pool';
import * as i18n from '../../../../i18n/i18n_ast';
import {mapLiteral} from '../../../../output/map_util';
import * as o from '../../../../output/output_ast';
import {sanitizeIdentifier} from '../../../../parse_util';
import {Identifiers} from '../../../../render3/r3_identifiers';
import {createGoogleGetMsgStatements} from '../../../../render3/view/i18n/get_msg_utils';
import {createLocalizeStatements} from '../../../../render3/view/i18n/localize_utils';
import {formatI18nPlaceholderNamesInMap} from '../../../../render3/view/i18n/util';
import * as ir from '../../ir';
import {ComponentCompilationJob} from '../compilation';
/** Name of the global variable that is used to determine if we use Closure translations or not */
const NG_I18N_CLOSURE_MODE = 'ngI18nClosureMode';
/**
* Prefix for non-`goog.getMsg` i18n-related vars.
* Note: the prefix uses lowercase characters intentionally due to a Closure behavior that
* considers variables like `I18N_0` as constants and throws an error when their value changes.
*/
const TRANSLATION_VAR_PREFIX = 'i18n_';
/** Prefix of ICU expressions for post processing */
export const I18N_ICU_MAPPING_PREFIX = 'I18N_EXP_';
/**
* The escape sequence used for message param values.
*/
const ESCAPE = '\uFFFD';
/* Closure variables holding messages must be named `MSG_[A-Z0-9]+` */
const CLOSURE_TRANSLATION_VAR_PREFIX = 'MSG_';
/**
* Generates a prefix for translation const name.
*
* @param extra Additional local prefix that should be injected into translation var name
* @returns Complete translation const prefix
*/
export function getTranslationConstPrefix(extra: string): string {
return `${CLOSURE_TRANSLATION_VAR_PREFIX}${extra}`.toUpperCase();
}
/**
* Generate AST to declare a variable. E.g. `var I18N_1;`.
* @param variable the name of the variable to declare.
*/
export function declareI18nVariable(variable: o.ReadVarExpr): o.Statement {
return new o.DeclareVarStmt(
variable.name!,
undefined,
o.INFERRED_TYPE,
undefined,
variable.sourceSpan,
);
}
/**
* Lifts i18n properties into the consts array.
* TODO: Can we use `ConstCollectedExpr`?
* TODO: The way the various attributes are linked together is very complex. Perhaps we could
* simplify the process, maybe by combining the context and message ops?
*/ | {
"end_byte": 2580,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/i18n_const_collection.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/i18n_const_collection.ts_2581_9074 | export function collectI18nConsts(job: ComponentCompilationJob): void {
const fileBasedI18nSuffix =
job.relativeContextFilePath.replace(/[^A-Za-z0-9]/g, '_').toUpperCase() + '_';
// Step One: Build up various lookup maps we need to collect all the consts.
// Context Xref -> Extracted Attribute Ops
const extractedAttributesByI18nContext = new Map<ir.XrefId, ir.ExtractedAttributeOp[]>();
// Element/ElementStart Xref -> I18n Attributes config op
const i18nAttributesByElement = new Map<ir.XrefId, ir.I18nAttributesOp>();
// Element/ElementStart Xref -> All I18n Expression ops for attrs on that target
const i18nExpressionsByElement = new Map<ir.XrefId, ir.I18nExpressionOp[]>();
// I18n Message Xref -> I18n Message Op (TODO: use a central op map)
const messages = new Map<ir.XrefId, ir.I18nMessageOp>();
for (const unit of job.units) {
for (const op of unit.ops()) {
if (op.kind === ir.OpKind.ExtractedAttribute && op.i18nContext !== null) {
const attributes = extractedAttributesByI18nContext.get(op.i18nContext) ?? [];
attributes.push(op);
extractedAttributesByI18nContext.set(op.i18nContext, attributes);
} else if (op.kind === ir.OpKind.I18nAttributes) {
i18nAttributesByElement.set(op.target, op);
} else if (
op.kind === ir.OpKind.I18nExpression &&
op.usage === ir.I18nExpressionFor.I18nAttribute
) {
const expressions = i18nExpressionsByElement.get(op.target) ?? [];
expressions.push(op);
i18nExpressionsByElement.set(op.target, expressions);
} else if (op.kind === ir.OpKind.I18nMessage) {
messages.set(op.xref, op);
}
}
}
// Step Two: Serialize the extracted i18n messages for root i18n blocks and i18n attributes into
// the const array.
//
// Also, each i18n message will have a variable expression that can refer to its
// value. Store these expressions in the appropriate place:
// 1. For normal i18n content, it also goes in the const array. We save the const index to use
// later.
// 2. For extracted attributes, it becomes the value of the extracted attribute instruction.
// 3. For i18n bindings, it will go in a separate const array instruction below; for now, we just
// save it.
const i18nValuesByContext = new Map<ir.XrefId, o.Expression>();
const messageConstIndices = new Map<ir.XrefId, ir.ConstIndex>();
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind === ir.OpKind.I18nMessage) {
if (op.messagePlaceholder === null) {
const {mainVar, statements} = collectMessage(job, fileBasedI18nSuffix, messages, op);
if (op.i18nBlock !== null) {
// This is a regular i18n message with a corresponding i18n block. Collect it into the
// const array.
const i18nConst = job.addConst(mainVar, statements);
messageConstIndices.set(op.i18nBlock, i18nConst);
} else {
// This is an i18n attribute. Extract the initializers into the const pool.
job.constsInitializers.push(...statements);
// Save the i18n variable value for later.
i18nValuesByContext.set(op.i18nContext, mainVar);
// This i18n message may correspond to an individual extracted attribute. If so, The
// value of that attribute is updated to read the extracted i18n variable.
const attributesForMessage = extractedAttributesByI18nContext.get(op.i18nContext);
if (attributesForMessage !== undefined) {
for (const attr of attributesForMessage) {
attr.expression = mainVar.clone();
}
}
}
}
ir.OpList.remove<ir.CreateOp>(op);
}
}
}
// Step Three: Serialize I18nAttributes configurations into the const array. Each I18nAttributes
// instruction has a config array, which contains k-v pairs describing each binding name, and the
// i18n variable that provides the value.
for (const unit of job.units) {
for (const elem of unit.create) {
if (ir.isElementOrContainerOp(elem)) {
const i18nAttributes = i18nAttributesByElement.get(elem.xref);
if (i18nAttributes === undefined) {
// This element is not associated with an i18n attributes configuration instruction.
continue;
}
let i18nExpressions = i18nExpressionsByElement.get(elem.xref);
if (i18nExpressions === undefined) {
// Unused i18nAttributes should have already been removed.
// TODO: Should the removal of those dead instructions be merged with this phase?
throw new Error(
'AssertionError: Could not find any i18n expressions associated with an I18nAttributes instruction',
);
}
// Find expressions for all the unique property names, removing duplicates.
const seenPropertyNames = new Set<string>();
i18nExpressions = i18nExpressions.filter((i18nExpr) => {
const seen = seenPropertyNames.has(i18nExpr.name);
seenPropertyNames.add(i18nExpr.name);
return !seen;
});
const i18nAttributeConfig = i18nExpressions.flatMap((i18nExpr) => {
const i18nExprValue = i18nValuesByContext.get(i18nExpr.context);
if (i18nExprValue === undefined) {
throw new Error("AssertionError: Could not find i18n expression's value");
}
return [o.literal(i18nExpr.name), i18nExprValue];
});
i18nAttributes.i18nAttributesConfig = job.addConst(
new o.LiteralArrayExpr(i18nAttributeConfig),
);
}
}
}
// Step Four: Propagate the extracted const index into i18n ops that messages were extracted from.
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind === ir.OpKind.I18nStart) {
const msgIndex = messageConstIndices.get(op.root);
if (msgIndex === undefined) {
throw new Error(
'AssertionError: Could not find corresponding i18n block index for an i18n message op; was an i18n message incorrectly assumed to correspond to an attribute?',
);
}
op.messageIndex = msgIndex;
}
}
}
}
/**
* Collects the given message into a set of statements that can be added to the const array.
* This will recursively collect any sub-messages referenced from the parent message as well.
*/ | {
"end_byte": 9074,
"start_byte": 2581,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/i18n_const_collection.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/i18n_const_collection.ts_9075_15833 | function collectMessage(
job: ComponentCompilationJob,
fileBasedI18nSuffix: string,
messages: Map<ir.XrefId, ir.I18nMessageOp>,
messageOp: ir.I18nMessageOp,
): {mainVar: o.ReadVarExpr; statements: o.Statement[]} {
// Recursively collect any sub-messages, record each sub-message's main variable under its
// placeholder so that we can add them to the params for the parent message. It is possible
// that multiple sub-messages will share the same placeholder, so we need to track an array of
// variables for each placeholder.
const statements: o.Statement[] = [];
const subMessagePlaceholders = new Map<string, o.Expression[]>();
for (const subMessageId of messageOp.subMessages) {
const subMessage = messages.get(subMessageId)!;
const {mainVar: subMessageVar, statements: subMessageStatements} = collectMessage(
job,
fileBasedI18nSuffix,
messages,
subMessage,
);
statements.push(...subMessageStatements);
const subMessages = subMessagePlaceholders.get(subMessage.messagePlaceholder!) ?? [];
subMessages.push(subMessageVar);
subMessagePlaceholders.set(subMessage.messagePlaceholder!, subMessages);
}
addSubMessageParams(messageOp, subMessagePlaceholders);
// Sort the params for consistency with TemaplateDefinitionBuilder output.
messageOp.params = new Map([...messageOp.params.entries()].sort());
const mainVar = o.variable(job.pool.uniqueName(TRANSLATION_VAR_PREFIX));
// Closure Compiler requires const names to start with `MSG_` but disallows any other
// const to start with `MSG_`. We define a variable starting with `MSG_` just for the
// `goog.getMsg` call
const closureVar = i18nGenerateClosureVar(
job.pool,
messageOp.message.id,
fileBasedI18nSuffix,
job.i18nUseExternalIds,
);
let transformFn = undefined;
// If nescessary, add a post-processing step and resolve any placeholder params that are
// set in post-processing.
if (messageOp.needsPostprocessing || messageOp.postprocessingParams.size > 0) {
// Sort the post-processing params for consistency with TemaplateDefinitionBuilder output.
const postprocessingParams = Object.fromEntries(
[...messageOp.postprocessingParams.entries()].sort(),
);
const formattedPostprocessingParams = formatI18nPlaceholderNamesInMap(
postprocessingParams,
/* useCamelCase */ false,
);
const extraTransformFnParams: o.Expression[] = [];
if (messageOp.postprocessingParams.size > 0) {
extraTransformFnParams.push(mapLiteral(formattedPostprocessingParams, /* quoted */ true));
}
transformFn = (expr: o.ReadVarExpr) =>
o.importExpr(Identifiers.i18nPostprocess).callFn([expr, ...extraTransformFnParams]);
}
// Add the message's statements
statements.push(
...getTranslationDeclStmts(
messageOp.message,
mainVar,
closureVar,
messageOp.params,
transformFn,
),
);
return {mainVar, statements};
}
/**
* Adds the given subMessage placeholders to the given message op.
*
* If a placeholder only corresponds to a single sub-message variable, we just set that variable
* as the param value. However, if the placeholder corresponds to multiple sub-message
* variables, we need to add a special placeholder value that is handled by the post-processing
* step. We then add the array of variables as a post-processing param.
*/
function addSubMessageParams(
messageOp: ir.I18nMessageOp,
subMessagePlaceholders: Map<string, o.Expression[]>,
) {
for (const [placeholder, subMessages] of subMessagePlaceholders) {
if (subMessages.length === 1) {
messageOp.params.set(placeholder, subMessages[0]);
} else {
messageOp.params.set(
placeholder,
o.literal(`${ESCAPE}${I18N_ICU_MAPPING_PREFIX}${placeholder}${ESCAPE}`),
);
messageOp.postprocessingParams.set(placeholder, o.literalArr(subMessages));
}
}
}
/**
* Generate statements that define a given translation message.
*
* ```
* var I18N_1;
* if (typeof ngI18nClosureMode !== undefined && ngI18nClosureMode) {
* var MSG_EXTERNAL_XXX = goog.getMsg(
* "Some message with {$interpolation}!",
* { "interpolation": "\uFFFD0\uFFFD" }
* );
* I18N_1 = MSG_EXTERNAL_XXX;
* }
* else {
* I18N_1 = $localize`Some message with ${'\uFFFD0\uFFFD'}!`;
* }
* ```
*
* @param message The original i18n AST message node
* @param variable The variable that will be assigned the translation, e.g. `I18N_1`.
* @param closureVar The variable for Closure `goog.getMsg` calls, e.g. `MSG_EXTERNAL_XXX`.
* @param params Object mapping placeholder names to their values (e.g.
* `{ "interpolation": "\uFFFD0\uFFFD" }`).
* @param transformFn Optional transformation function that will be applied to the translation
* (e.g.
* post-processing).
* @returns An array of statements that defined a given translation.
*/
function getTranslationDeclStmts(
message: i18n.Message,
variable: o.ReadVarExpr,
closureVar: o.ReadVarExpr,
params: Map<string, o.Expression>,
transformFn?: (raw: o.ReadVarExpr) => o.Expression,
): o.Statement[] {
const paramsObject = Object.fromEntries(params);
const statements: o.Statement[] = [
declareI18nVariable(variable),
o.ifStmt(
createClosureModeGuard(),
createGoogleGetMsgStatements(variable, message, closureVar, paramsObject),
createLocalizeStatements(
variable,
message,
formatI18nPlaceholderNamesInMap(paramsObject, /* useCamelCase */ false),
),
),
];
if (transformFn) {
statements.push(new o.ExpressionStatement(variable.set(transformFn(variable))));
}
return statements;
}
/**
* Create the expression that will be used to guard the closure mode block
* It is equivalent to:
*
* ```
* typeof ngI18nClosureMode !== undefined && ngI18nClosureMode
* ```
*/
function createClosureModeGuard(): o.BinaryOperatorExpr {
return o
.typeofExpr(o.variable(NG_I18N_CLOSURE_MODE))
.notIdentical(o.literal('undefined', o.STRING_TYPE))
.and(o.variable(NG_I18N_CLOSURE_MODE));
}
/**
* Generates vars with Closure-specific names for i18n blocks (i.e. `MSG_XXX`).
*/
function i18nGenerateClosureVar(
pool: ConstantPool,
messageId: string,
fileBasedI18nSuffix: string,
useExternalIds: boolean,
): o.ReadVarExpr {
let name: string;
const suffix = fileBasedI18nSuffix;
if (useExternalIds) {
const prefix = getTranslationConstPrefix(`EXTERNAL_`);
const uniqueSuffix = pool.uniqueName(suffix);
name = `${prefix}${sanitizeIdentifier(messageId)}$$${uniqueSuffix}`;
} else {
const prefix = getTranslationConstPrefix(suffix);
name = pool.uniqueName(prefix);
}
return o.variable(name);
} | {
"end_byte": 15833,
"start_byte": 9075,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/i18n_const_collection.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/pure_literal_structures.ts_0_2077 | /**
* @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';
export function generatePureLiteralStructures(job: CompilationJob): void {
for (const unit of job.units) {
for (const op of unit.update) {
ir.transformExpressionsInOp(
op,
(expr, flags) => {
if (flags & ir.VisitorContextFlag.InChildOperation) {
return expr;
}
if (expr instanceof o.LiteralArrayExpr) {
return transformLiteralArray(expr);
} else if (expr instanceof o.LiteralMapExpr) {
return transformLiteralMap(expr);
}
return expr;
},
ir.VisitorContextFlag.None,
);
}
}
}
function transformLiteralArray(expr: o.LiteralArrayExpr): o.Expression {
const derivedEntries: o.Expression[] = [];
const nonConstantArgs: o.Expression[] = [];
for (const entry of expr.entries) {
if (entry.isConstant()) {
derivedEntries.push(entry);
} else {
const idx = nonConstantArgs.length;
nonConstantArgs.push(entry);
derivedEntries.push(new ir.PureFunctionParameterExpr(idx));
}
}
return new ir.PureFunctionExpr(o.literalArr(derivedEntries), nonConstantArgs);
}
function transformLiteralMap(expr: o.LiteralMapExpr): o.Expression {
let derivedEntries: o.LiteralMapEntry[] = [];
const nonConstantArgs: o.Expression[] = [];
for (const entry of expr.entries) {
if (entry.value.isConstant()) {
derivedEntries.push(entry);
} else {
const idx = nonConstantArgs.length;
nonConstantArgs.push(entry.value);
derivedEntries.push(
new o.LiteralMapEntry(entry.key, new ir.PureFunctionParameterExpr(idx), entry.quoted),
);
}
}
return new ir.PureFunctionExpr(o.literalMap(derivedEntries), nonConstantArgs);
}
| {
"end_byte": 2077,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/pure_literal_structures.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/temporary_variables.ts_0_3759 | /**
* @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';
/**
* Find all assignments and usages of temporary variables, which are linked to each other with cross
* references. Generate names for each cross-reference, and add a `DeclareVarStmt` to initialize
* them at the beginning of the update block.
*
* TODO: Sometimes, it will be possible to reuse names across different subexpressions. For example,
* in the double keyed read `a?.[f()]?.[f()]`, the two function calls have non-overlapping scopes.
* Implement an algorithm for reuse.
*/
export function generateTemporaryVariables(job: CompilationJob): void {
for (const unit of job.units) {
unit.create.prepend(generateTemporaries(unit.create) as Array<ir.StatementOp<ir.CreateOp>>);
unit.update.prepend(generateTemporaries(unit.update) as Array<ir.StatementOp<ir.UpdateOp>>);
}
}
function generateTemporaries(
ops: ir.OpList<ir.CreateOp | ir.UpdateOp>,
): Array<ir.StatementOp<ir.CreateOp | ir.UpdateOp>> {
let opCount = 0;
let generatedStatements: Array<ir.StatementOp<ir.UpdateOp>> = [];
// For each op, search for any variables that are assigned or read. For each variable, generate a
// name and produce a `DeclareVarStmt` to the beginning of the block.
for (const op of ops) {
// Identify the final time each temp var is read.
const finalReads = new Map<ir.XrefId, ir.ReadTemporaryExpr>();
ir.visitExpressionsInOp(op, (expr, flag) => {
if (flag & ir.VisitorContextFlag.InChildOperation) {
return;
}
if (expr instanceof ir.ReadTemporaryExpr) {
finalReads.set(expr.xref, expr);
}
});
// Name the temp vars, accounting for the fact that a name can be reused after it has been
// read for the final time.
let count = 0;
const assigned = new Set<ir.XrefId>();
const released = new Set<ir.XrefId>();
const defs = new Map<ir.XrefId, string>();
ir.visitExpressionsInOp(op, (expr, flag) => {
if (flag & ir.VisitorContextFlag.InChildOperation) {
return;
}
if (expr instanceof ir.AssignTemporaryExpr) {
if (!assigned.has(expr.xref)) {
assigned.add(expr.xref);
// TODO: Exactly replicate the naming scheme used by `TemplateDefinitionBuilder`.
// It seems to rely on an expression index instead of an op index.
defs.set(expr.xref, `tmp_${opCount}_${count++}`);
}
assignName(defs, expr);
} else if (expr instanceof ir.ReadTemporaryExpr) {
if (finalReads.get(expr.xref) === expr) {
released.add(expr.xref);
count--;
}
assignName(defs, expr);
}
});
// Add declarations for the temp vars.
generatedStatements.push(
...Array.from(new Set(defs.values())).map((name) =>
ir.createStatementOp<ir.UpdateOp>(new o.DeclareVarStmt(name)),
),
);
opCount++;
if (op.kind === ir.OpKind.Listener || op.kind === ir.OpKind.TwoWayListener) {
op.handlerOps.prepend(generateTemporaries(op.handlerOps) as ir.UpdateOp[]);
}
}
return generatedStatements;
}
/**
* Assigns a name to the temporary variable in the given temporary variable expression.
*/
function assignName(
names: Map<ir.XrefId, string>,
expr: ir.AssignTemporaryExpr | ir.ReadTemporaryExpr,
) {
const name = names.get(expr.xref);
if (name === undefined) {
throw new Error(`Found xref with unassigned name: ${expr.xref}`);
}
expr.name = name;
}
| {
"end_byte": 3759,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/temporary_variables.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/namespace.ts_0_826 | /**
* @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';
/**
* Change namespaces between HTML, SVG and MathML, depending on the next element.
*/
export function emitNamespaceChanges(job: CompilationJob): void {
for (const unit of job.units) {
let activeNamespace = ir.Namespace.HTML;
for (const op of unit.create) {
if (op.kind !== ir.OpKind.ElementStart) {
continue;
}
if (op.namespace !== activeNamespace) {
ir.OpList.insertBefore<ir.CreateOp>(ir.createNamespaceOp(op.namespace), op);
activeNamespace = op.namespace;
}
}
}
}
| {
"end_byte": 826,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/namespace.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/local_refs.ts_0_1431 | /**
* @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';
/**
* Lifts local reference declarations on element-like structures within each view into an entry in
* the `consts` array for the whole component.
*/
export function liftLocalRefs(job: ComponentCompilationJob): void {
for (const unit of job.units) {
for (const op of unit.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 still`);
}
op.numSlotsUsed += op.localRefs.length;
if (op.localRefs.length > 0) {
const localRefs = serializeLocalRefs(op.localRefs);
op.localRefs = job.addConst(localRefs);
} else {
op.localRefs = null;
}
break;
}
}
}
}
function serializeLocalRefs(refs: ir.LocalRef[]): o.Expression {
const constRefs: o.Expression[] = [];
for (const ref of refs) {
constRefs.push(o.literal(ref.name), o.literal(ref.target));
}
return o.literalArr(constRefs);
}
| {
"end_byte": 1431,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/local_refs.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/store_let_optimization.ts_0_1431 | /*!
* @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';
/**
* Removes any `storeLet` calls that aren't referenced outside of the current view.
*/
export function optimizeStoreLet(job: CompilationJob): void {
const letUsedExternally = new Set<ir.XrefId>();
// Since `@let` declarations can be referenced in child views, both in
// the creation block (via listeners) and in the update block, we have
// to look through all the ops to find the references.
for (const unit of job.units) {
for (const op of unit.ops()) {
ir.visitExpressionsInOp(op, (expr) => {
if (expr instanceof ir.ContextLetReferenceExpr) {
letUsedExternally.add(expr.target);
}
});
}
}
// TODO(crisbeto): potentially remove the unused calls completely, pending discussion.
for (const unit of job.units) {
for (const op of unit.update) {
ir.transformExpressionsInOp(
op,
(expression) =>
expression instanceof ir.StoreLetExpr && !letUsedExternally.has(expression.target)
? expression.value
: expression,
ir.VisitorContextFlag.None,
);
}
}
}
| {
"end_byte": 1431,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/store_let_optimization.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/save_restore_view.ts_0_2795 | /**
* @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';
/**
* When inside of a listener, we may need access to one or more enclosing views. Therefore, each
* view should save the current view, and each listener must have the ability to restore the
* appropriate view. We eagerly generate all save view variables; they will be optimized away later.
*/
export function saveAndRestoreView(job: ComponentCompilationJob): void {
for (const unit of job.units) {
unit.create.prepend([
ir.createVariableOp<ir.CreateOp>(
unit.job.allocateXrefId(),
{
kind: ir.SemanticVariableKind.SavedView,
name: null,
view: unit.xref,
},
new ir.GetCurrentViewExpr(),
ir.VariableFlags.None,
),
]);
for (const op of unit.create) {
if (op.kind !== ir.OpKind.Listener && op.kind !== ir.OpKind.TwoWayListener) {
continue;
}
// Embedded views always need the save/restore view operation.
let needsRestoreView = unit !== job.root;
if (!needsRestoreView) {
for (const handlerOp of op.handlerOps) {
ir.visitExpressionsInOp(handlerOp, (expr) => {
if (expr instanceof ir.ReferenceExpr || expr instanceof ir.ContextLetReferenceExpr) {
// Listeners that reference() a local ref need the save/restore view operation.
needsRestoreView = true;
}
});
}
}
if (needsRestoreView) {
addSaveRestoreViewOperationToListener(unit, op);
}
}
}
}
function addSaveRestoreViewOperationToListener(
unit: ViewCompilationUnit,
op: ir.ListenerOp | ir.TwoWayListenerOp,
) {
op.handlerOps.prepend([
ir.createVariableOp<ir.UpdateOp>(
unit.job.allocateXrefId(),
{
kind: ir.SemanticVariableKind.Context,
name: null,
view: unit.xref,
},
new ir.RestoreViewExpr(unit.xref),
ir.VariableFlags.None,
),
]);
// The "restore view" operation in listeners requires a call to `resetView` to reset the
// context prior to returning from the listener operation. Find any `return` statements in
// the listener body and wrap them in a call to reset the view.
for (const handlerOp of op.handlerOps) {
if (
handlerOp.kind === ir.OpKind.Statement &&
handlerOp.statement instanceof o.ReturnStatement
) {
handlerOp.statement.value = new ir.ResetViewExpr(handlerOp.statement.value);
}
}
}
| {
"end_byte": 2795,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/save_restore_view.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/propagate_i18n_blocks.ts_0_3830 | /**
* @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';
/**
* Propagate i18n blocks down through child templates that act as placeholders in the root i18n
* message. Specifically, perform an in-order traversal of all the views, and add i18nStart/i18nEnd
* op pairs into descending views. Also, assign an increasing sub-template index to each
* descending view.
*/
export function propagateI18nBlocks(job: ComponentCompilationJob): void {
propagateI18nBlocksToTemplates(job.root, 0);
}
/**
* Propagates i18n ops in the given view through to any child views recursively.
*/
function propagateI18nBlocksToTemplates(
unit: ViewCompilationUnit,
subTemplateIndex: number,
): number {
let i18nBlock: ir.I18nStartOp | null = null;
for (const op of unit.create) {
switch (op.kind) {
case ir.OpKind.I18nStart:
op.subTemplateIndex = subTemplateIndex === 0 ? null : subTemplateIndex;
i18nBlock = op;
break;
case ir.OpKind.I18nEnd:
// When we exit a root-level i18n block, reset the sub-template index counter.
if (i18nBlock!.subTemplateIndex === null) {
subTemplateIndex = 0;
}
i18nBlock = null;
break;
case ir.OpKind.Template:
subTemplateIndex = propagateI18nBlocksForView(
unit.job.views.get(op.xref)!,
i18nBlock,
op.i18nPlaceholder,
subTemplateIndex,
);
break;
case ir.OpKind.RepeaterCreate:
// Propagate i18n blocks to the @for template.
const forView = unit.job.views.get(op.xref)!;
subTemplateIndex = propagateI18nBlocksForView(
forView,
i18nBlock,
op.i18nPlaceholder,
subTemplateIndex,
);
// Then if there's an @empty template, propagate the i18n blocks for it as well.
if (op.emptyView !== null) {
subTemplateIndex = propagateI18nBlocksForView(
unit.job.views.get(op.emptyView)!,
i18nBlock,
op.emptyI18nPlaceholder,
subTemplateIndex,
);
}
break;
}
}
return subTemplateIndex;
}
/**
* Propagate i18n blocks for a view.
*/
function propagateI18nBlocksForView(
view: ViewCompilationUnit,
i18nBlock: ir.I18nStartOp | null,
i18nPlaceholder: i18n.TagPlaceholder | i18n.BlockPlaceholder | undefined,
subTemplateIndex: number,
) {
// We found an <ng-template> inside an i18n block; increment the sub-template counter and
// wrap the template's view in a child i18n block.
if (i18nPlaceholder !== undefined) {
if (i18nBlock === null) {
throw Error('Expected template with i18n placeholder to be in an i18n block.');
}
subTemplateIndex++;
wrapTemplateWithI18n(view, i18nBlock);
}
// Continue traversing inside the template's view.
return propagateI18nBlocksToTemplates(view, subTemplateIndex);
}
/**
* Wraps a template view with i18n start and end ops.
*/
function wrapTemplateWithI18n(unit: ViewCompilationUnit, parentI18n: ir.I18nStartOp) {
// Only add i18n ops if they have not already been propagated to this template.
if (unit.create.head.next?.kind !== ir.OpKind.I18nStart) {
const id = unit.job.allocateXrefId();
ir.OpList.insertAfter(
// Nested ng-template i18n start/end ops should not receive source spans.
ir.createI18nStartOp(id, parentI18n.message, parentI18n.root, null),
unit.create.head,
);
ir.OpList.insertBefore(ir.createI18nEndOp(id, null), unit.create.tail);
}
}
| {
"end_byte": 3830,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/propagate_i18n_blocks.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/parse_extracted_styles.ts_0_5936 | /**
* @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 * as ir from '../../ir';
import type {CompilationJob} from '../compilation';
// Any changes here should be ported to the Angular Domino fork.
// https://github.com/angular/domino/blob/main/lib/style_parser.js
const enum Char {
OpenParen = 40,
CloseParen = 41,
Colon = 58,
Semicolon = 59,
BackSlash = 92,
QuoteNone = 0, // indicating we are not inside a quote
QuoteDouble = 34,
QuoteSingle = 39,
}
/**
* Parses string representation of a style and converts it into object literal.
*
* @param value string representation of style as used in the `style` attribute in HTML.
* Example: `color: red; height: auto`.
* @returns An array of style property name and value pairs, e.g. `['color', 'red', 'height',
* 'auto']`
*/
export function parse(value: string): string[] {
// we use a string array here instead of a string map
// because a string-map is not guaranteed to retain the
// order of the entries whereas a string array can be
// constructed in a [key, value, key, value] format.
const styles: string[] = [];
let i = 0;
let parenDepth = 0;
let quote: Char = Char.QuoteNone;
let valueStart = 0;
let propStart = 0;
let currentProp: string | null = null;
while (i < value.length) {
const token = value.charCodeAt(i++) as Char;
switch (token) {
case Char.OpenParen:
parenDepth++;
break;
case Char.CloseParen:
parenDepth--;
break;
case Char.QuoteSingle:
// valueStart needs to be there since prop values don't
// have quotes in CSS
if (quote === Char.QuoteNone) {
quote = Char.QuoteSingle;
} else if (quote === Char.QuoteSingle && value.charCodeAt(i - 1) !== Char.BackSlash) {
quote = Char.QuoteNone;
}
break;
case Char.QuoteDouble:
// same logic as above
if (quote === Char.QuoteNone) {
quote = Char.QuoteDouble;
} else if (quote === Char.QuoteDouble && value.charCodeAt(i - 1) !== Char.BackSlash) {
quote = Char.QuoteNone;
}
break;
case Char.Colon:
if (!currentProp && parenDepth === 0 && quote === Char.QuoteNone) {
// TODO: Do not hyphenate CSS custom property names like: `--intentionallyCamelCase`
currentProp = hyphenate(value.substring(propStart, i - 1).trim());
valueStart = i;
}
break;
case Char.Semicolon:
if (currentProp && valueStart > 0 && parenDepth === 0 && quote === Char.QuoteNone) {
const styleVal = value.substring(valueStart, i - 1).trim();
styles.push(currentProp, styleVal);
propStart = i;
valueStart = 0;
currentProp = null;
}
break;
}
}
if (currentProp && valueStart) {
const styleVal = value.slice(valueStart).trim();
styles.push(currentProp, styleVal);
}
return styles;
}
export function hyphenate(value: string): string {
return value
.replace(/[a-z][A-Z]/g, (v) => {
return v.charAt(0) + '-' + v.charAt(1);
})
.toLowerCase();
}
/**
* Parses extracted style and class attributes into separate ExtractedAttributeOps per style or
* class property.
*/
export function parseExtractedStyles(job: CompilationJob) {
const elements = new Map<ir.XrefId, ir.CreateOp>();
for (const unit of job.units) {
for (const op of unit.create) {
if (ir.isElementOrContainerOp(op)) {
elements.set(op.xref, op);
}
}
}
for (const unit of job.units) {
for (const op of unit.create) {
if (
op.kind === ir.OpKind.ExtractedAttribute &&
op.bindingKind === ir.BindingKind.Attribute &&
ir.isStringLiteral(op.expression!)
) {
const target = elements.get(op.target)!;
if (
target !== undefined &&
target.kind === ir.OpKind.Template &&
target.templateKind === ir.TemplateKind.Structural
) {
// TemplateDefinitionBuilder will not apply class and style bindings to structural
// directives; instead, it will leave them as attributes.
// (It's not clear what that would mean, anyway -- classes and styles on a structural
// element should probably be a parse error.)
// TODO: We may be able to remove this once Template Pipeline is the default.
continue;
}
if (op.name === 'style') {
const parsedStyles = parse(op.expression.value);
for (let i = 0; i < parsedStyles.length - 1; i += 2) {
ir.OpList.insertBefore<ir.CreateOp>(
ir.createExtractedAttributeOp(
op.target,
ir.BindingKind.StyleProperty,
null,
parsedStyles[i],
o.literal(parsedStyles[i + 1]),
null,
null,
SecurityContext.STYLE,
),
op,
);
}
ir.OpList.remove<ir.CreateOp>(op);
} else if (op.name === 'class') {
const parsedClasses = op.expression.value.trim().split(/\s+/g);
for (const parsedClass of parsedClasses) {
ir.OpList.insertBefore<ir.CreateOp>(
ir.createExtractedAttributeOp(
op.target,
ir.BindingKind.ClassName,
null,
parsedClass,
null,
null,
null,
SecurityContext.NONE,
),
op,
);
}
ir.OpList.remove<ir.CreateOp>(op);
}
}
}
}
}
| {
"end_byte": 5936,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/parse_extracted_styles.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/remove_illegal_let_references.ts_0_1779 | /**
* @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';
/**
* It's not allowed to access a `@let` declaration before it has been defined. This is enforced
* already via template type checking, however it can trip some of the assertions in the pipeline.
* E.g. the naming phase can fail because we resolved the variable here, but the variable doesn't
* exist anymore because the optimization phase removed it since it's invalid. To avoid surfacing
* confusing errors to users in the case where template type checking isn't running (e.g. in JIT
* mode) this phase detects illegal forward references and replaces them with `undefined`.
* Eventually users will see the proper error from the template type checker.
*/
export function removeIllegalLetReferences(job: CompilationJob): void {
for (const unit of job.units) {
for (const op of unit.update) {
if (
op.kind !== ir.OpKind.Variable ||
op.variable.kind !== ir.SemanticVariableKind.Identifier ||
!(op.initializer instanceof ir.StoreLetExpr)
) {
continue;
}
const name = op.variable.identifier;
let current: ir.UpdateOp | null = op;
while (current && current.kind !== ir.OpKind.ListEnd) {
ir.transformExpressionsInOp(
current,
(expr) =>
expr instanceof ir.LexicalReadExpr && expr.name === name ? o.literal(undefined) : expr,
ir.VisitorContextFlag.None,
);
current = current.prev;
}
}
}
}
| {
"end_byte": 1779,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/remove_illegal_let_references.ts"
} |
angular/packages/compiler/src/template/pipeline/src/phases/pipe_variadic.ts_0_1203 | /**
* @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, ComponentCompilationJob} from '../compilation';
/**
* Pipes that accept more than 4 arguments are variadic, and are handled with a different runtime
* instruction.
*/
export function createVariadicPipes(job: CompilationJob): void {
for (const unit of job.units) {
for (const op of unit.update) {
ir.transformExpressionsInOp(
op,
(expr) => {
if (!(expr instanceof ir.PipeBindingExpr)) {
return expr;
}
// Pipes are variadic if they have more than 4 arguments.
if (expr.args.length <= 4) {
return expr;
}
return new ir.PipeBindingVariadicExpr(
expr.target,
expr.targetSlot,
expr.name,
o.literalArr(expr.args),
expr.args.length,
);
},
ir.VisitorContextFlag.None,
);
}
}
}
| {
"end_byte": 1203,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler/src/template/pipeline/src/phases/pipe_variadic.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.