Debian Codegraph @

src/com/google/javascript/jscomp/SourceInformationAnnotator.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.Preconditions;
20 import com.google.javascript.rhino.Node;
21 import com.google.javascript.rhino.Token;
22
23 /**
24 * Annotates nodes with information from their original input file
25 * before the compiler performs work that changes this information (such
26 * as its original location, its original name, etc).
27 *
28 * Information saved:
29 *
30 * - Annotates all NAME nodes with an ORIGINALNAME_PROP indicating its original
31 * name.
32 *
33 * - Annotates all string GET_PROP nodes with an ORIGINALNAME_PROP.
34 *
35 * - Annotates all OBJECT_LITERAL unquoted string key nodes with an
36 * ORIGINALNAME_PROP.
37 *
38 * - Annotates all FUNCTION nodes with an ORIGINALNAME_PROP indicating its
39 * nearest original name.
40 *
41 */
42 class SourceInformationAnnotator extends
43 NodeTraversal.AbstractPostOrderCallback {
44 private final String sourceFile;
45 private final boolean doSanityChecks;
46
47 public SourceInformationAnnotator(
48 String sourceFile, boolean doSanityChecks) {
49 this.sourceFile = sourceFile;
50 this.doSanityChecks = doSanityChecks;
51 }
52
53 @Override
54 public void visit(NodeTraversal t, Node n, Node parent) {
55 // Verify the source file is annotated.
56 if (doSanityChecks && sourceFile != null) {
57 Preconditions.checkState(sourceFile.equals(
58 n.getSourceFileName()));
59 }
60
61 // Annotate the original name.
62 switch (n.getType()) {
63 case Token.GETPROP:
64 Node propNode = n.getLastChild();
65 setOriginalName(n, propNode.getString());
66 break;
67
68 case Token.FUNCTION:
69 String functionName = NodeUtil.getNearestFunctionName(n);
70 if (functionName != null) {
71 setOriginalName(n, functionName);
72 }
73 break;
74
75 case Token.NAME:
76 setOriginalName(n, n.getString());
77 break;
78
79 case Token.OBJECTLIT:
80 for (Node key = n.getFirstChild(); key != null;
81 key = key.getNext()) {
82 // We only want keys were unquoted.
83 if (!key.isQuotedString()) {
84 setOriginalName(key, key.getString());
85 }
86 }
87 break;
88 }
89 }
90
91 void setOriginalName(Node n, String name) {
92 if (!name.isEmpty() && n.getProp(Node.ORIGINALNAME_PROP) == null) {
93 n.putProp(Node.ORIGINALNAME_PROP, name);
94 }
95 }
96 }