Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2008 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.common.collect.Sets;
21 import com.google.javascript.jscomp.CheckLevel;
22 import com.google.javascript.jscomp.GlobalNamespace.Name;
23 import com.google.javascript.jscomp.GlobalNamespace.Ref;
24 import com.google.javascript.rhino.JSDocInfo;
25 import com.google.javascript.rhino.Node;
26
27 import java.util.Set;
28
29 /**
30 * Checks references to undefined properties of global variables.
31 *
32 * @author [email protected] (Nick Santos)
33 */
34 class CheckGlobalNames implements CompilerPass {
35
36 private final AbstractCompiler compiler;
37 private final CodingConvention convention;
38 private final CheckLevel level;
39
40 private GlobalNamespace namespace = null;
41 private final Set<String> objectPrototypeProps = Sets.newHashSet();
42 private final Set<String> functionPrototypeProps = Sets.newHashSet();
43
44 // Warnings
45 static final DiagnosticType UNDEFINED_NAME_WARNING = DiagnosticType.warning(
46 "JSC_UNDEFINED_NAME",
47 "{0} is never defined");
48
49 static final DiagnosticType NAME_DEFINED_LATE_WARNING =
50 DiagnosticType.warning(
51 "JSC_NAME_DEFINED_LATE",
52 "{0} defined before its owner. {1} is defined at {2}:{3}");
53
54 static final DiagnosticType STRICT_MODULE_DEP_QNAME =
55 DiagnosticType.disabled(
56 "JSC_STRICT_MODULE_DEP_QNAME",
57 "module {0} cannot reference {2}, defined in " +
58 "module {1}");
59
60 /**
61 * Creates a pass to check global name references at the given warning level.
62 */
63 CheckGlobalNames(AbstractCompiler compiler, CheckLevel level) {
64 this.compiler = compiler;
65 this.convention = compiler.getCodingConvention();
66 this.level = level;
67 }
68
69 /**
70 * Injects a pre-computed global namespace, so that the same namespace
71 * can be re-used for multiple check passes. Returns this for easy chaining.
72 */
73 CheckGlobalNames injectNamespace(GlobalNamespace namespace) {
74 Preconditions.checkArgument(namespace.hasExternsRoot());
75 this.namespace = namespace;
76 return this;
77 }
78
79 @Override
80 public void process(Node externs, Node root) {
81 if (namespace == null) {
82 namespace = new GlobalNamespace(compiler, externs, root);
83 }
84
85 // Find prototype properties that will affect our analysis.
86 Preconditions.checkState(namespace.hasExternsRoot());
87 findPrototypeProps("Object", objectPrototypeProps);
88 findPrototypeProps("Function", functionPrototypeProps);
89 objectPrototypeProps.addAll(
90 convention.getIndirectlyDeclaredProperties());
91
92 for (Name name : namespace.getNameForest()) {
93 // Skip extern names. Externs are often not runnable as real code,
94 // and will do things like:
95 // var x;
96 // x.method;
97 // which this check forbids.
98 if (name.inExterns) {
99 continue;
100 }
101
102 checkDescendantNames(name, name.globalSets + name.localSets > 0);
103 }
104 }
105
106 private void findPrototypeProps(String type, Set<String> props) {
107 Name slot = namespace.getSlot(type);
108 if (slot != null) {
109 for (Ref ref : slot.getRefs()) {
110 if (ref.type == Ref.Type.PROTOTYPE_GET) {
111 Node fullName = ref.getNode().getParent().getParent();
112 if (fullName.isGetProp()) {
113 props.add(fullName.getLastChild().getString());
114 }
115 }
116 }
117 }
118 }
119
120 /**
121 * Checks to make sure all the descendants of a name are defined if they
122 * are referenced.
123 *
124 * @param name A global name.
125 * @param nameIsDefined If true, {@code name} is defined. Otherwise, it's
126 * undefined, and any references to descendant names should emit warnings.
127 */
128 private void checkDescendantNames(Name name, boolean nameIsDefined) {
129 if (name.props != null) {
130 for (Name prop : name.props) {
131 // if the ancestor of a property is not defined, then we should emit
132 // warnings for all references to the property.
133 boolean propIsDefined = false;
134 if (nameIsDefined) {
135 // if the ancestor of a property is defined, then let's check that
136 // the property is also explicitly defined if it needs to be.
137 propIsDefined = (!propertyMustBeInitializedByFullName(prop) ||
138 prop.globalSets + prop.localSets > 0);
139 }
140
141 validateName(prop, propIsDefined);
142 checkDescendantNames(prop, propIsDefined);
143 }
144 }
145 }
146
147 private void validateName(Name name, boolean isDefined) {
148 // If the name is not defined, emit warnings for each reference. While
149 // we're looking through each reference, check all the module dependencies.
150 Ref declaration = name.getDeclaration();
151 Name parent = name.parent;
152
153 JSModuleGraph moduleGraph = compiler.getModuleGraph();
154 for (Ref ref : name.getRefs()) {
155 // Don't worry about global exprs.
156 boolean isGlobalExpr = ref.getNode().getParent().isExprResult();
157
158 if (!isDefined && !isTypedef(ref)) {
159 if (!isGlobalExpr) {
160 reportRefToUndefinedName(name, ref);
161 }
162 } else if (declaration != null &&
163 ref.getModule() != declaration.getModule() &&
164 !moduleGraph.dependsOn(
165 ref.getModule(), declaration.getModule())) {
166 reportBadModuleReference(name, ref);
167 } else {
168 // Check for late references.
169 if (ref.scope.isGlobal()) {
170 // Prototype references are special, because in our reference graph,
171 // A.prototype counts as a reference to A.
172 boolean isPrototypeGet = (ref.type == Ref.Type.PROTOTYPE_GET);
173 Name owner = isPrototypeGet ? name : parent;
174 boolean singleGlobalParentDecl =
175 owner != null &&
176 owner.getDeclaration() != null &&
177 owner.localSets == 0;
178
179 if (singleGlobalParentDecl &&
180 owner.getDeclaration().preOrderIndex > ref.preOrderIndex) {
181 String refName = isPrototypeGet
182 ? name.getFullName() + ".prototype"
183 : name.getFullName();
184 compiler.report(
185 JSError.make(ref.source.getName(), ref.node,
186 NAME_DEFINED_LATE_WARNING,
187 refName,
188 owner.getFullName(),
189 owner.getDeclaration().source.getName(),
190 String.valueOf(owner.getDeclaration().node.getLineno())));
191 }
192 }
193 }
194 }
195 }
196
197 private boolean isTypedef(Ref ref) {
198 // If this is an annotated EXPR-GET, don't do anything.
199 Node parent = ref.node.getParent();
200 if (parent.isExprResult()) {
201 JSDocInfo info = ref.node.getJSDocInfo();
202 if (info != null && info.hasTypedefType()) {
203 return true;
204 }
205 }
206 return false;
207 }
208
209 private void reportBadModuleReference(Name name, Ref ref) {
210 compiler.report(
211 JSError.make(ref.source.getName(), ref.node, STRICT_MODULE_DEP_QNAME,
212 ref.getModule().getName(),
213 name.getDeclaration().getModule().getName(),
214 name.getFullName()));
215 }
216
217 private void reportRefToUndefinedName(Name name, Ref ref) {
218 // grab the highest undefined ancestor to output in the warning message.
219 while (name.parent != null &&
220 name.parent.globalSets + name.parent.localSets == 0) {
221 name = name.parent;
222 }
223
224 compiler.report(
225 JSError.make(ref.getSourceName(), ref.node, level,
226 UNDEFINED_NAME_WARNING, name.getFullName()));
227 }
228
229 /**
230 * Checks whether the given name is a property, and whether that property
231 * must be initialized with its full qualified name.
232 */
233 private boolean propertyMustBeInitializedByFullName(Name name) {
234 // If an object or function literal in the global namespace is never
235 // aliased, then its properties can only come from one of 2 places:
236 // 1) From its prototype chain, or
237 // 2) From an assignment to its fully qualified name.
238 // If we assume #1 is not the case, then #2 implies that its
239 // properties must all be modeled in the GlobalNamespace as well.
240 //
241 // We assume that for global object literals and types (constructors and
242 // interfaces), we can find all the properties inherited from the prototype
243 // chain of functions and objects.
244 if (name.parent == null) {
245 return false;
246 }
247
248 boolean parentIsAliased = false;
249 if (name.parent.aliasingGets > 0) {
250 for (Ref ref : name.parent.getRefs()) {
251 if (ref.type == Ref.Type.ALIASING_GET) {
252 Node aliaser = ref.getNode().getParent();
253
254 // We don't need to worry about known aliased, because
255 // they're already covered by the getIndirectlyDeclaredProperties
256 // call at the top.
257 boolean isKnownAlias =
258 aliaser.isCall() &&
259 (convention.getClassesDefinedByCall(aliaser) != null ||
260 convention.getSingletonGetterClassName(aliaser) != null);
261 if (!isKnownAlias) {
262 parentIsAliased = true;
263 }
264 }
265 }
266 }
267
268 if (parentIsAliased) {
269 return false;
270 }
271
272 if (objectPrototypeProps.contains(name.getBaseName())) {
273 return false;
274 }
275
276 if (name.parent.type == Name.Type.OBJECTLIT) {
277 return true;
278 }
279
280 if (name.parent.type == Name.Type.FUNCTION &&
281 name.parent.isDeclaredType() &&
282 !functionPrototypeProps.contains(name.getBaseName())) {
283 return true;
284 }
285
286 return false;
287 }
288 }