Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2009 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.base.Joiner;
20 import com.google.common.base.Preconditions;
21 import com.google.common.collect.Iterables;
22 import com.google.common.collect.Lists;
23 import com.google.common.collect.Maps;
24 import com.google.common.collect.Sets;
25 import com.google.javascript.rhino.IR;
26 import com.google.javascript.rhino.JSDocInfo;
27 import com.google.javascript.rhino.Node;
28 import com.google.javascript.rhino.Token;
29 import com.google.javascript.rhino.jstype.FunctionType;
30 import com.google.javascript.rhino.jstype.JSType;
31
32 import java.util.Comparator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Set;
36 import java.util.TreeSet;
37
38 /**
39 * Creates an externs file containing all exported symbols and properties
40 * for later consumption.
41 *
42 */
43 final class ExternExportsPass extends NodeTraversal.AbstractPostOrderCallback
44 implements CompilerPass {
45
46 static final DiagnosticType EXPORTED_FUNCTION_UNKNOWN_PARAMETER_TYPE =
47 DiagnosticType.warning(
48 "JSC_EXPORTED_FUNCTION_UNKNOWN_PARAMETER_TYPE",
49 "Unable to determine type of parameter {0} for exported function {1}");
50
51 static final DiagnosticType EXPORTED_FUNCTION_UNKNOWN_RETURN_TYPE =
52 DiagnosticType.warning(
53 "JSC_EXPORTED_FUNCTION_UNKNOWN_RETURN_TYPE",
54 "Unable to determine return type for exported function {0}");
55
56 /** The exports found. */
57 private final List<Export> exports;
58
59 /** A map of all assigns to their parent nodes. */
60 private final Map<String, Node> definitionMap;
61
62 /** The parent compiler. */
63 private final AbstractCompiler compiler;
64
65 /** The AST root which holds the externs generated. */
66 private final Node externsRoot;
67
68 /** A mapping of internal paths to exported paths. */
69 private final Map<String, String> mappedPaths;
70
71 /** A list of exported paths. */
72 private final Set<String> alreadyExportedPaths;
73
74 /** A list of function names used to export symbols. */
75 private List<String> exportSymbolFunctionNames;
76
77 /** A list of function names used to export properties. */
78 private List<String> exportPropertyFunctionNames;
79
80 private abstract class Export {
81 protected final String symbolName;
82 protected final Node value;
83
84 Export(String symbolName, Node value) {
85 this.symbolName = symbolName;
86 this.value = value;
87 }
88
89 /**
90 * Generates the externs representation of this export and appends
91 * it to the externsRoot AST.
92 */
93 void generateExterns() {
94 appendExtern(getExportedPath(), getValue(value));
95 }
96
97 /**
98 * Returns the path exported by this export.
99 */
100 abstract String getExportedPath();
101
102 /**
103 * Appends the exported function and all paths necessary for the path to be
104 * declared. For example, for a property "a.b.c", the initializers for
105 * paths "a", "a.b" will be appended (if they have not already) and a.b.c
106 * will be initialized with the exported version of the function:
107 * <pre>
108 * var a = {};
109 * a.b = {};
110 * a.b.c = function(x,y) { }
111 * </pre>
112 */
113 void appendExtern(String path, Node valueToExport) {
114 List<String> pathPrefixes = computePathPrefixes(path);
115
116 for (int i = 0; i < pathPrefixes.size(); ++i) {
117 String pathPrefix = pathPrefixes.get(i);
118
119 /* The complete path (the last path prefix) must be emitted and
120 * it gets initialized to the externed version of the value.
121 */
122 boolean isCompletePathPrefix = (i == pathPrefixes.size() - 1);
123
124 boolean skipPathPrefix = pathPrefix.endsWith(".prototype")
125 || (alreadyExportedPaths.contains(pathPrefix)
126 && !isCompletePathPrefix);
127
128 if (!skipPathPrefix) {
129 Node initializer;
130
131 /* Namespaces get initialized to {}, functions to
132 * externed versions of their value, and if we can't
133 * figure out where the value came from we initialize
134 * it to {}.
135 *
136 * Since externs are always exported in sorted order,
137 * we know that if we export a.b = function() {} and later
138 * a.b.c = function then a.b will always be in alreadyExportedPaths
139 * when we emit a.b.c and thus we will never overwrite the function
140 * exported for a.b with a namespace.
141 */
142
143 if (isCompletePathPrefix && valueToExport != null) {
144 if (valueToExport.isFunction()) {
145 initializer = createExternFunction(valueToExport);
146 } else {
147 Preconditions.checkState(valueToExport.isObjectLit());
148 initializer = createExternObjectLit(valueToExport);
149 }
150 } else {
151 initializer = IR.empty();
152 }
153
154 appendPathDefinition(pathPrefix, initializer);
155 }
156 }
157 }
158
159 /**
160 * Computes a list of the path prefixes constructed from the components
161 * of the path.
162 * <pre>
163 * E.g., if the path is:
164 * "a.b.c"
165 * then then path prefixes will be
166 * ["a","a.b","a.b.c"]:
167 * </pre>
168 */
169 private List<String> computePathPrefixes(String path) {
170 List<String> pieces = Lists.newArrayList(path.split("\\."));
171
172 List<String> pathPrefixes = Lists.newArrayList();
173
174 for (int i = 0; i < pieces.size(); i++) {
175 pathPrefixes.add(Joiner.on(".").join(Iterables.limit(pieces, i + 1)));
176 }
177
178 return pathPrefixes;
179 }
180
181 private void appendPathDefinition(String path, Node initializer) {
182 Node pathDefinition;
183
184 if (!path.contains(".")) {
185 if (initializer.isEmpty()) {
186 pathDefinition = IR.var(IR.name(path));
187 } else {
188 pathDefinition = NodeUtil.newVarNode(path, initializer);
189 }
190 } else {
191 Node qualifiedPath = NodeUtil.newQualifiedNameNode(
192 compiler.getCodingConvention(), path);
193 if (initializer.isEmpty()) {
194 pathDefinition = NodeUtil.newExpr(qualifiedPath);
195 } else {
196 pathDefinition = NodeUtil.newExpr(
197 IR.assign(qualifiedPath, initializer));
198 }
199 }
200
201 externsRoot.addChildToBack(pathDefinition);
202
203 alreadyExportedPaths.add(path);
204 }
205
206 /**
207 * Given a function to export, create the empty function that
208 * will be put in the externs file. This extern function should have
209 * the same type as the original function and the same parameter
210 * name but no function body.
211 *
212 * We create a warning here if the the function to export is missing
213 * parameter or return types.
214 */
215 private Node createExternFunction(Node exportedFunction) {
216 Node paramList = NodeUtil.getFunctionParameters(exportedFunction)
217 .cloneTree();
218 Node externFunction = IR.function(IR.name(""), paramList, IR.block());
219
220 checkForFunctionsWithUnknownTypes(exportedFunction);
221 externFunction.setJSType(exportedFunction.getJSType());
222
223 return externFunction;
224 }
225
226 /**
227 * Given an object literal to export, create an object lit with all its
228 * string properties. We don't care what the values of those properties
229 * are because they are not checked.
230 */
231 private Node createExternObjectLit(Node exportedObjectLit) {
232 Node lit = IR.objectlit();
233 lit.setJSType(exportedObjectLit.getJSType());
234
235 // This is an indirect way of telling the typed code generator
236 // "print the type of this"
237 lit.setJSDocInfo(new JSDocInfo());
238
239 int index = 1;
240 for (Node child = exportedObjectLit.getFirstChild();
241 child != null;
242 child = child.getNext()) {
243 // TODO: handle getters or setters?
244 if (child.isStringKey()) {
245 lit.addChildToBack(
246 IR.propdef(
247 IR.stringKey(child.getString()),
248 IR.number(index++)));
249 }
250 }
251 return lit;
252 }
253
254 /**
255 * Warn the user if there is an exported function for which a parameter
256 * or return type is unknown.
257 */
258 private void checkForFunctionsWithUnknownTypes(Node function) {
259 Preconditions.checkArgument(function.isFunction());
260
261 FunctionType functionType =
262 JSType.toMaybeFunctionType(function.getJSType());
263
264 if (functionType == null) {
265 // No type information is available (CheckTypes was probably not run)
266 // so just bail.
267 return;
268 }
269
270 JSType returnType = functionType.getReturnType();
271
272 /* It is OK if a constructor doesn't have a return type */
273 if (!functionType.isConstructor() &&
274 (returnType == null || returnType.isUnknownType())) {
275 reportUnknownReturnType(function);
276 }
277
278 /* We can't just use the function's type's getParameters() to get the
279 * parameter nodes because the nodes returned from that method
280 * do not have names or locations. Similarly, the function's AST parameter
281 * nodes do not have JSTypes(). So we walk both lists of parameter nodes
282 * in lock step getting parameter names from the first and types from the
283 * second.
284 */
285 Node astParameterIterator = NodeUtil.getFunctionParameters(function)
286 .getFirstChild();
287
288 Node typeParameterIterator = functionType.getParametersNode()
289 .getFirstChild();
290
291 while (astParameterIterator != null) {
292 JSType parameterType = typeParameterIterator.getJSType();
293
294 if (parameterType == null || parameterType.isUnknownType()) {
295 reportUnknownParameterType(function, astParameterIterator);
296 }
297
298 astParameterIterator = astParameterIterator.getNext();
299 typeParameterIterator = typeParameterIterator.getNext();
300 }
301 }
302
303 private void reportUnknownParameterType(Node function, Node parameter) {
304 compiler.report(JSError.make(NodeUtil.getSourceName(function),
305 parameter, CheckLevel.WARNING,
306 EXPORTED_FUNCTION_UNKNOWN_PARAMETER_TYPE,
307 NodeUtil.getFunctionName(function), parameter.getString()));
308 }
309
310 private void reportUnknownReturnType(Node function) {
311 compiler.report(JSError.make(NodeUtil.getSourceName(function),
312 function, CheckLevel.WARNING, EXPORTED_FUNCTION_UNKNOWN_RETURN_TYPE,
313 NodeUtil.getFunctionName(function)));
314 }
315
316 /**
317 * If the given value is a qualified name which refers
318 * a function or object literal, the node is returned. Otherwise,
319 * {@code null} is returned.
320 */
321 protected Node getValue(Node qualifiedNameNode) {
322 String qualifiedName = value.getQualifiedName();
323
324 if (qualifiedName == null) {
325 return null;
326 }
327
328 Node definitionParent = definitionMap.get(qualifiedName);
329 if (definitionParent == null) {
330 return null;
331 }
332
333 Node definition;
334
335 switch (definitionParent.getType()) {
336 case Token.ASSIGN:
337 definition = definitionParent.getLastChild();
338 break;
339 case Token.VAR:
340 definition = definitionParent.getLastChild().getLastChild();
341 break;
342 default:
343 return null;
344 }
345
346 if (!definition.isFunction() && !definition.isObjectLit()) {
347 return null;
348 }
349
350 return definition;
351 }
352 }
353
354 /**
355 * A symbol export.
356 */
357 private class SymbolExport extends Export {
358
359 public SymbolExport(String symbolName, Node value) {
360 super(symbolName, value);
361
362 String qualifiedName = value.getQualifiedName();
363
364 if (qualifiedName != null) {
365 mappedPaths.put(qualifiedName, symbolName);
366 }
367 }
368
369 @Override
370 String getExportedPath() {
371 return symbolName;
372 }
373 }
374
375 /**
376 * A property export.
377 */
378 private class PropertyExport extends Export {
379 private final String exportPath;
380
381 public PropertyExport(String exportPath, String symbolName, Node value) {
382 super(symbolName, value);
383
384 this.exportPath = exportPath;
385 }
386
387 @Override
388 String getExportedPath() {
389
390 // Find the longest path that has been mapped (if any).
391 List<String> pieces = Lists.newArrayList(exportPath.split("\\."));
392
393 for (int i = pieces.size(); i > 0; i--) {
394 // Find the path of the current length.
395 String cPath = Joiner.on(".").join(Iterables.limit(pieces, i));
396
397 // If this path is mapped, return the mapped path plus any remaining
398 // pieces.
399 if (mappedPaths.containsKey(cPath)) {
400 String newPath = mappedPaths.get(cPath);
401
402 if (i < pieces.size()) {
403 newPath += "." + Joiner.on(".").join(Iterables.skip(pieces, i));
404 }
405
406 return newPath + "." + symbolName;
407 }
408 }
409
410 return exportPath + "." + symbolName;
411 }
412 }
413
414 /**
415 * Creates an instance.
416 */
417 ExternExportsPass(AbstractCompiler compiler) {
418 this.exports = Lists.newArrayList();
419 this.compiler = compiler;
420 this.definitionMap = Maps.newHashMap();
421 this.externsRoot = IR.block();
422 this.externsRoot.setIsSyntheticBlock(true);
423 this.alreadyExportedPaths = Sets.newHashSet();
424 this.mappedPaths = Maps.newHashMap();
425
426 initExportMethods();
427 }
428
429 private void initExportMethods() {
430 exportSymbolFunctionNames = Lists.newArrayList();
431 exportPropertyFunctionNames = Lists.newArrayList();
432
433 // From Closure:
434 // goog.exportSymbol = function(publicName, symbol)
435 // goog.exportProperty = function(object, publicName, symbol)
436 CodingConvention convention = compiler.getCodingConvention();
437 exportSymbolFunctionNames.add(convention.getExportSymbolFunction());
438 exportPropertyFunctionNames.add(convention.getExportPropertyFunction());
439
440 // Another common one used inside google:
441 exportSymbolFunctionNames.add("google_exportSymbol");
442 exportPropertyFunctionNames.add("google_exportProperty");
443 }
444
445 @Override
446 public void process(Node externs, Node root) {
447 new NodeTraversal(compiler, this).traverse(root);
448
449 // Sort by path length to ensure that the longer
450 // paths (which may depend on the shorter ones)
451 // come later.
452 Set<Export> sorted =
453 new TreeSet<Export>(new Comparator<Export>() {
454 @Override
455 public int compare(Export e1, Export e2) {
456 return e1.getExportedPath().compareTo(e2.getExportedPath());
457 }
458 });
459
460 sorted.addAll(exports);
461
462 for (Export export : sorted) {
463 export.generateExterns();
464 }
465 }
466
467 /**
468 * Returns the generated externs.
469 */
470 public String getGeneratedExterns() {
471 CodePrinter.Builder builder = new CodePrinter.Builder(externsRoot)
472 .setPrettyPrint(true)
473 .setOutputTypes(true)
474 .setTypeRegistry(compiler.getTypeRegistry());
475
476 return builder.build();
477 }
478
479 @Override
480 public void visit(NodeTraversal t, Node n, Node parent) {
481 switch (n.getType()) {
482
483 case Token.NAME:
484 case Token.GETPROP:
485 String name = n.getQualifiedName();
486 if (name == null) {
487 return;
488 }
489
490 if (parent.isAssign() || parent.isVar()) {
491 definitionMap.put(name, parent);
492 }
493
494 // Only handle function calls. This avoids assignments
495 // that do not export items directly.
496 if (!parent.isCall()) {
497 return;
498 }
499
500 if (exportPropertyFunctionNames.contains(name)) {
501 handlePropertyExport(parent);
502 }
503
504 if (exportSymbolFunctionNames.contains(name)) {
505 handleSymbolExport(parent);
506 }
507 }
508 }
509
510 private void handleSymbolExport(Node parent) {
511 // Ensure that we only check valid calls with the 2 arguments
512 // (plus the GETPROP node itself).
513 if (parent.getChildCount() != 3) {
514 return;
515 }
516
517 Node thisNode = parent.getFirstChild();
518 Node nameArg = thisNode.getNext();
519 Node valueArg = nameArg.getNext();
520
521 // Confirm the arguments are the expected types. If they are not,
522 // then we have an export that we cannot statically identify.
523 if (!nameArg.isString()) {
524 return;
525 }
526
527 // Add the export to the list.
528 this.exports.add(new SymbolExport(nameArg.getString(), valueArg));
529 }
530
531 private void handlePropertyExport(Node parent) {
532 // Ensure that we only check valid calls with the 3 arguments
533 // (plus the GETPROP node itself).
534 if (parent.getChildCount() != 4) {
535 return;
536 }
537
538 Node thisNode = parent.getFirstChild();
539 Node objectArg = thisNode.getNext();
540 Node nameArg = objectArg.getNext();
541 Node valueArg = nameArg.getNext();
542
543 // Confirm the arguments are the expected types. If they are not,
544 // then we have an export that we cannot statically identify.
545 if (!objectArg.isQualifiedName()) {
546 return;
547 }
548
549 if (!nameArg.isString()) {
550 return;
551 }
552
553 // Add the export to the list.
554 this.exports.add(
555 new PropertyExport(objectArg.getQualifiedName(),
556 nameArg.getString(),
557 valueArg));
558 }
559 }