Debian Codegraph @

src/com/google/javascript/jscomp/RuntimeTypeCheck.java

raw symbols SCIP
1 /*
2 * Copyright 2010 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.Iterables;
21 import com.google.common.collect.Sets;
22 import com.google.javascript.rhino.IR;
23 import com.google.javascript.rhino.Node;
24 import com.google.javascript.rhino.jstype.FunctionType;
25 import com.google.javascript.rhino.jstype.JSType;
26 import com.google.javascript.rhino.jstype.ObjectType;
27 import com.google.javascript.rhino.jstype.StaticSourceFile;
28
29 import java.util.Collection;
30 import java.util.Comparator;
31 import java.util.TreeSet;
32
33 import javax.annotation.Nullable;
34
35 /**
36 * Inserts run-time type assertions.
37 *
38 * <p>We add markers to user-defined interfaces and classes in order to check if
39 * an object conforms to that type.
40 *
41 * <p>For each function, we insert a run-time type assertion for each parameter
42 * and return value for which the compiler has a type.
43 *
44 * <p>The JavaScript code which implements the type assertions is in
45 * js/runtime-type-check.js.
46 *
47 */
48 class RuntimeTypeCheck implements CompilerPass {
49
50 private static final Comparator<JSType> ALPHA = new Comparator<JSType>() {
51 @Override
52 public int compare(JSType t1, JSType t2) {
53 return getName(t1).compareTo(getName(t2));
54 }
55
56 private String getName(JSType type) {
57 if (type.isInstanceType()) {
58 return ((ObjectType) type).getReferenceName();
59 } else if (type.isNullType()
60 || type.isBooleanValueType()
61 || type.isNumberValueType()
62 || type.isStringValueType()
63 || type.isVoidType()) {
64 return type.toString();
65 } else {
66 // Type unchecked at runtime, so we don't care about the sorting order.
67 return "";
68 }
69 }
70 };
71
72 private final AbstractCompiler compiler;
73 private final String logFunction;
74
75 RuntimeTypeCheck(AbstractCompiler compiler, @Nullable String logFunction) {
76 this.compiler = compiler;
77 this.logFunction = logFunction;
78 }
79
80 @Override
81 public void process(Node externs, Node root) {
82 NodeTraversal.traverse(compiler, root, new AddMarkers(compiler));
83 NodeTraversal.traverse(compiler, root, new AddChecks());
84 addBoilerplateCode();
85 }
86
87 /**
88 * Inserts marker properties for user-defined interfaces and classes.
89 *
90 * <p>For example, for a class C, we add
91 * {@code C.prototype['instance_of__C']}, and for each interface I it
92 * implements , we add {@code C.prototype['implements__I']}.
93 *
94 * <p>Since interfaces are not a run-time JS concept, we use these markers to
95 * recognize an interface implementation at runtime. We also use markers for
96 * user-defined classes, so that we can easily recognize them independently of
97 * which module they are defined in and whether the module is loaded.
98 */
99 private static class AddMarkers
100 extends NodeTraversal.AbstractPostOrderCallback {
101
102 private final AbstractCompiler compiler;
103
104 private AddMarkers(AbstractCompiler compiler) {
105 this.compiler = compiler;
106 }
107
108 @Override
109 public void visit(NodeTraversal t, Node n, Node parent) {
110 if (n.isFunction()) {
111 visitFunction(n);
112 }
113 }
114
115 private void visitFunction(Node n) {
116 FunctionType funType = n.getJSType().toMaybeFunctionType();
117 if (funType != null && !funType.isConstructor()) {
118 return;
119 }
120
121 Node nodeToInsertAfter = findNodeToInsertAfter(n);
122
123 nodeToInsertAfter = addMarker(funType, nodeToInsertAfter, null);
124
125 TreeSet<ObjectType> stuff = Sets.newTreeSet(ALPHA);
126 Iterables.addAll(stuff, funType.getAllImplementedInterfaces());
127 for (ObjectType interfaceType : stuff) {
128 nodeToInsertAfter =
129 addMarker(funType, nodeToInsertAfter, interfaceType);
130 }
131 }
132
133 private Node addMarker(
134 FunctionType funType,
135 Node nodeToInsertAfter,
136 @Nullable ObjectType interfaceType) {
137
138 if (funType.getSource() == null) {
139 return nodeToInsertAfter;
140 }
141
142 String className = NodeUtil.getFunctionName(funType.getSource());
143
144 // This can happen with anonymous classes declared with the type
145 // {@code Function}.
146 if (className == null) {
147 return nodeToInsertAfter;
148 }
149
150 Node classNode = NodeUtil.newQualifiedNameNode(
151 compiler.getCodingConvention(), className);
152
153 Node marker = IR.string(
154 interfaceType == null ?
155 "instance_of__" + className :
156 "implements__" + interfaceType.getReferenceName());
157
158 Node assign = IR.exprResult(IR.assign(
159 IR.getelem(
160 IR.getprop(
161 classNode,
162 IR.string("prototype")), marker),
163 IR.trueNode()));
164
165 nodeToInsertAfter.getParent().addChildAfter(assign, nodeToInsertAfter);
166 compiler.reportCodeChange();
167 nodeToInsertAfter = assign;
168 return nodeToInsertAfter;
169 }
170
171 /**
172 * Find the node to insert the markers after. Typically, this node
173 * corresponds to the constructor declaration, but we want to skip any of
174 * the white-listed function calls.
175 *
176 * @param n the constructor function node
177 * @return the node to insert after
178 */
179 private Node findNodeToInsertAfter(Node n) {
180 Node nodeToInsertAfter = findEnclosingConstructorDeclaration(n);
181
182 Node next = nodeToInsertAfter.getNext();
183 while (next != null && isClassDefiningCall(next)) {
184 nodeToInsertAfter = next;
185 next = nodeToInsertAfter.getNext();
186 }
187
188 return nodeToInsertAfter;
189 }
190
191 private Node findEnclosingConstructorDeclaration(Node n) {
192 while (!n.getParent().isScript() && !n.getParent().isBlock()) {
193 n = n.getParent();
194 }
195 return n;
196 }
197
198 private boolean isClassDefiningCall(Node next) {
199 return NodeUtil.isExprCall(next) &&
200 compiler.getCodingConvention().getClassesDefinedByCall(
201 next.getFirstChild()) != null;
202 }
203 }
204
205 /**
206 * Insert calls to the run-time type checking function {@code checkType}, which
207 * takes an expression to check and a list of checkers (one of which must
208 * match). It returns the expression back to facilitate checking of return
209 * values. We have checkers for value types, class types (user-defined and
210 * externed), and interface types.
211 */
212 private class AddChecks
213 extends NodeTraversal.AbstractPostOrderCallback {
214
215 private AddChecks() {
216 }
217
218 @Override
219 public void visit(NodeTraversal t, Node n, Node parent) {
220 if (n.isFunction()) {
221 visitFunction(n);
222 } else if (n.isReturn()) {
223 visitReturn(t, n);
224 }
225 }
226
227 /**
228 * Insert checks for the parameters of the function.
229 */
230 private void visitFunction(Node n) {
231 FunctionType funType = JSType.toMaybeFunctionType(n.getJSType());
232 Node block = n.getLastChild();
233 Node paramName = NodeUtil.getFunctionParameters(n).getFirstChild();
234 Node insertionPoint = null;
235
236 // To satisfy normalization constraints, the type checking must be
237 // added after any inner function declarations.
238 for (Node next = block.getFirstChild();
239 next != null && NodeUtil.isFunctionDeclaration(next);
240 next = next.getNext()) {
241 insertionPoint = next;
242 }
243
244 for (Node paramType : funType.getParameters()) {
245 // Can this ever happen?
246 if (paramName == null) {
247 return;
248 }
249
250 Node checkNode = createCheckTypeCallNode(
251 paramType.getJSType(), paramName.cloneTree());
252
253 if (checkNode == null) {
254 // We don't know how to check this parameter type.
255 paramName = paramName.getNext();
256 continue;
257 }
258
259 checkNode = IR.exprResult(checkNode);
260 if (insertionPoint == null) {
261 block.addChildToFront(checkNode);
262 } else {
263 block.addChildAfter(checkNode, insertionPoint);
264 }
265
266 compiler.reportCodeChange();
267 paramName = paramName.getNext();
268 insertionPoint = checkNode;
269 }
270 }
271
272 private void visitReturn(NodeTraversal t, Node n) {
273 Node function = t.getEnclosingFunction();
274 FunctionType funType = function.getJSType().toMaybeFunctionType();
275
276 Node retValue = n.getFirstChild();
277 if (retValue == null) {
278 return;
279 }
280
281 Node checkNode = createCheckTypeCallNode(
282 funType.getReturnType(), retValue.cloneTree());
283
284 if (checkNode == null) {
285 return;
286 }
287
288 n.replaceChild(retValue, checkNode);
289 compiler.reportCodeChange();
290 }
291
292 /**
293 * Creates a function call to check that the given expression matches the
294 * given type at runtime.
295 *
296 * <p>For example, if the type is {@code (string|Foo)}, the function call is
297 * {@code checkType(expr, [valueChecker('string'), classChecker('Foo')])}.
298 *
299 * @return the function call node or {@code null} if the type is not checked
300 */
301 private Node createCheckTypeCallNode(JSType type, Node expr) {
302 Node arrayNode = IR.arraylit();
303 Collection<JSType> alternates;
304 if (type.isUnionType()) {
305 alternates = Sets.newTreeSet(ALPHA);
306 Iterables.addAll(alternates, type.toMaybeUnionType().getAlternates());
307 } else {
308 alternates = ImmutableList.of(type);
309 }
310 for (JSType alternate : alternates) {
311 Node checkerNode = createCheckerNode(alternate);
312 if (checkerNode == null) {
313 return null;
314 }
315 arrayNode.addChildToBack(checkerNode);
316 }
317 return IR.call(jsCode("checkType"), expr, arrayNode);
318 }
319
320 /**
321 * Creates a node which evaluates to a checker for the given type (which
322 * must not be a union). We have checkers for value types, classes and
323 * interfaces.
324 *
325 * @return the checker node or {@code null} if the type is not checked
326 */
327 private Node createCheckerNode(JSType type) {
328 if (type.isNullType()) {
329 return jsCode("nullChecker");
330
331 } else if (type.isBooleanValueType()
332 || type.isNumberValueType()
333 || type.isStringValueType()
334 || type.isVoidType()) {
335 return IR.call(
336 jsCode("valueChecker"),
337 IR.string(type.toString()));
338
339 } else if (type.isInstanceType()) {
340 ObjectType objType = (ObjectType) type;
341
342 String refName = objType.getReferenceName();
343
344 StaticSourceFile sourceFile =
345 NodeUtil.getSourceFile(objType.getConstructor().getSource());
346 if (sourceFile == null || sourceFile.isExtern()) {
347 return IR.call(
348 jsCode("externClassChecker"),
349 IR.string(refName));
350 }
351
352 return IR.call(
353 jsCode(objType.getConstructor().isInterface() ?
354 "interfaceChecker" : "classChecker"),
355 IR.string(refName));
356
357 } else {
358 // We don't check this type (e.g. unknown & all types).
359 return null;
360 }
361 }
362 }
363
364 private void addBoilerplateCode() {
365 Node newNode = compiler.ensureLibraryInjected("runtime_type_check");
366 if (newNode != null && logFunction != null) {
367 // Inject the custom log function.
368 Node logOverride = IR.exprResult(
369 IR.assign(
370 NodeUtil.newQualifiedNameNode(
371 compiler.getCodingConvention(),
372 "$jscomp.typecheck.log"),
373 NodeUtil.newQualifiedNameNode(
374 compiler.getCodingConvention(),
375 logFunction)));
376 newNode.getParent().addChildAfter(logOverride, newNode);
377 compiler.reportCodeChange();
378 }
379 }
380
381 private Node jsCode(String prop) {
382 return NodeUtil.newQualifiedNameNode(
383 compiler.getCodingConvention(), "$jscomp.typecheck." + prop);
384 }
385 }