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

Method getConstLiteral

packages/compiler/src/constant_pool.ts:94–147  ·  view source on GitHub ↗
(literal: o.Expression, forceShared?: boolean)

Source from the content-addressed store, hash-verified

92 constructor(private readonly isClosureCompilerEnabled: boolean = false) {}
93
94 getConstLiteral(literal: o.Expression, forceShared?: boolean): o.Expression {
95 if (
96 (literal instanceof o.LiteralExpr && !isLongStringLiteral(literal)) ||
97 literal instanceof FixupExpression
98 ) {
99 // Do no put simple literals into the constant pool or try to produce a constant for a
100 // reference to a constant.
101 return literal;
102 }
103 const key = GenericKeyFn.INSTANCE.keyOf(literal);
104 let fixup = this.literals.get(key);
105 let newValue = false;
106 if (!fixup) {
107 fixup = new FixupExpression(literal);
108 this.literals.set(key, fixup);
109 newValue = true;
110 }
111
112 if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
113 // Replace the expression with a variable
114 const name = this.freshName();
115 let value: o.Expression;
116 let usage: o.Expression;
117 if (this.isClosureCompilerEnabled && isLongStringLiteral(literal)) {
118 // For string literals, Closure will **always** inline the string at
119 // **all** usages, duplicating it each time. For large strings, this
120 // unnecessarily bloats bundle size. To work around this restriction, we
121 // wrap the string in a function, and call that function for each usage.
122 // This tricks Closure into using inline logic for functions instead of
123 // string literals. Function calls are only inlined if the body is small
124 // enough to be worth it. By doing this, very large strings will be
125 // shared across multiple usages, rather than duplicating the string at
126 // each usage site.
127 //
128 // const myStr = function() { return "very very very long string"; };
129 // const usage1 = myStr();
130 // const usage2 = myStr();
131 value = new o.FunctionExpr([], [new o.ReturnStatement(literal)], o.DYNAMIC_TYPE);
132 usage = o.variable(name).callFn([]);
133 } else {
134 // Just declare and use the variable directly, without a function call
135 // indirection. This saves a few bytes and avoids an unnecessary call.
136 value = literal;
137 usage = o.variable(name);
138 }
139
140 this.statements.push(
141 new o.DeclareVarStmt(name, value, o.INFERRED_TYPE, o.StmtModifier.Final),
142 );
143 fixup.fixup(usage);
144 }
145
146 return fixup;
147 }
148
149 getSharedConstant(def: SharedConstantDefinition, expr: o.Expression): o.Expression {
150 const key = def.keyOf(expr);

Calls 7

freshNameMethod · 0.95
isLongStringLiteralFunction · 0.85
fixupMethod · 0.80
keyOfMethod · 0.65
getMethod · 0.65
setMethod · 0.65
pushMethod · 0.45

Tested by

no test coverage detected