Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2007 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.ImmutableList;
21 import com.google.common.collect.ImmutableSet;
22 import com.google.common.collect.Lists;
23 import com.google.common.collect.Sets;
24 import com.google.javascript.rhino.Node;
25 import com.google.javascript.rhino.jstype.FunctionType;
26 import com.google.javascript.rhino.jstype.JSType;
27 import com.google.javascript.rhino.jstype.JSTypeNative;
28 import com.google.javascript.rhino.jstype.JSTypeRegistry;
29 import com.google.javascript.rhino.jstype.ObjectType;
30
31 import java.util.Collection;
32 import java.util.List;
33 import java.util.Set;
34
35 /**
36 * This describes the Closure-specific JavaScript coding conventions.
37 *
38 */
39 public class ClosureCodingConvention extends CodingConventions.Proxy {
40
41 private static final long serialVersionUID = 1L;
42
43 static final DiagnosticType OBJECTLIT_EXPECTED = DiagnosticType.warning(
44 "JSC_REFLECT_OBJECTLIT_EXPECTED",
45 "Object literal expected as second argument");
46
47 private final Set<String> indirectlyDeclaredProperties;
48
49 public ClosureCodingConvention() {
50 this(CodingConventions.getDefault());
51 }
52
53 public ClosureCodingConvention(CodingConvention wrapped) {
54 super(wrapped);
55
56 Set<String> props = Sets.newHashSet(
57 "superClass_",
58 "instance_",
59 "getInstance");
60 props.addAll(wrapped.getIndirectlyDeclaredProperties());
61 indirectlyDeclaredProperties = ImmutableSet.copyOf(props);
62 }
63
64 /**
65 * Closure's goog.inherits adds a {@code superClass_} property to the
66 * subclass, and a {@code constructor} property.
67 */
68 @Override
69 public void applySubclassRelationship(FunctionType parentCtor,
70 FunctionType childCtor, SubclassType type) {
71 super.applySubclassRelationship(parentCtor, childCtor, type);
72 if (type == SubclassType.INHERITS) {
73 childCtor.defineDeclaredProperty("superClass_",
74 parentCtor.getPrototype(), childCtor.getSource());
75 childCtor.getPrototype().defineDeclaredProperty("constructor",
76 // Notice that constructor functions do not need to be covariant
77 // on the superclass.
78 // So if G extends F, new G() and new F() can accept completely
79 // different argument types, but G.prototype.constructor needs
80 // to be covariant on F.prototype.constructor.
81 // To get around this, we just turn off type-checking on arguments
82 // and return types of G.prototype.constructor.
83 childCtor.cloneWithoutArrowType(),
84 childCtor.getSource());
85 }
86 }
87
88 /**
89 * {@inheritDoc}
90 *
91 * <p>Understands several different inheritance patterns that occur in
92 * Google code (various uses of {@code inherits} and {@code mixin}).
93 */
94 @Override
95 public SubclassRelationship getClassesDefinedByCall(Node callNode) {
96 SubclassRelationship relationship =
97 super.getClassesDefinedByCall(callNode);
98 if (relationship != null) return relationship;
99
100 Node callName = callNode.getFirstChild();
101 SubclassType type = typeofClassDefiningName(callName);
102 if (type != null) {
103 Node subclass = null;
104 Node superclass = callNode.getLastChild();
105
106 // There are six possible syntaxes for a class-defining method:
107 // SubClass.inherits(SuperClass)
108 // goog.inherits(SubClass, SuperClass)
109 // goog$inherits(SubClass, SuperClass)
110 // SubClass.mixin(SuperClass.prototype)
111 // goog.mixin(SubClass.prototype, SuperClass.prototype)
112 // goog$mixin(SubClass.prototype, SuperClass.prototype)
113 boolean isDeprecatedCall = callNode.getChildCount() == 2 &&
114 callName.isGetProp();
115 if (isDeprecatedCall) {
116 // SubClass.inherits(SuperClass)
117 subclass = callName.getFirstChild();
118 } else if (callNode.getChildCount() == 3) {
119 // goog.inherits(SubClass, SuperClass)
120 subclass = callName.getNext();
121 } else {
122 return null;
123 }
124
125 if (type == SubclassType.MIXIN) {
126 // Only consider mixins that mix two prototypes as related to
127 // inheritance.
128 if (!endsWithPrototype(superclass)) {
129 return null;
130 }
131 if (!isDeprecatedCall) {
132 if (!endsWithPrototype(subclass)) {
133 return null;
134 }
135 // Strip off the prototype from the name.
136 subclass = subclass.getFirstChild();
137 }
138 superclass = superclass.getFirstChild();
139 }
140
141 // bail out if either of the side of the "inherits"
142 // isn't a real class name. This prevents us from
143 // doing something weird in cases like:
144 // goog.inherits(MySubClass, cond ? SuperClass1 : BaseClass2)
145 if (subclass != null &&
146 subclass.isUnscopedQualifiedName() &&
147 superclass.isUnscopedQualifiedName()) {
148 return new SubclassRelationship(type, subclass, superclass);
149 }
150 }
151
152 return null;
153 }
154
155 /**
156 * Determines whether the given node is a class-defining name, like
157 * "inherits" or "mixin."
158 * @return The type of class-defining name, or null.
159 */
160 private SubclassType typeofClassDefiningName(Node callName) {
161 // Check if the method name matches one of the class-defining methods.
162 String methodName = null;
163 if (callName.isGetProp()) {
164 methodName = callName.getLastChild().getString();
165 } else if (callName.isName()) {
166 String name = callName.getString();
167 int dollarIndex = name.lastIndexOf('$');
168 if (dollarIndex != -1) {
169 methodName = name.substring(dollarIndex + 1);
170 }
171 }
172
173 if (methodName != null) {
174 if (methodName.equals("inherits")) {
175 return SubclassType.INHERITS;
176 } else if (methodName.equals("mixin")) {
177 return SubclassType.MIXIN;
178 }
179 }
180 return null;
181 }
182
183 @Override
184 public boolean isSuperClassReference(String propertyName) {
185 return "superClass_".equals(propertyName) ||
186 super.isSuperClassReference(propertyName);
187 }
188
189 /**
190 * Given a qualified name node, returns whether "prototype" is at the end.
191 * For example:
192 * a.b.c => false
193 * a.b.c.prototype => true
194 */
195 private boolean endsWithPrototype(Node qualifiedName) {
196 return qualifiedName.isGetProp() &&
197 qualifiedName.getLastChild().getString().equals("prototype");
198 }
199
200 /**
201 * Extracts X from goog.provide('X'), if the applied Node is goog.
202 *
203 * @return The extracted class name, or null.
204 */
205 @Override
206 public String extractClassNameIfProvide(Node node, Node parent){
207 return extractClassNameIfGoog(node, parent, "goog.provide");
208 }
209
210 /**
211 * Extracts X from goog.require('X'), if the applied Node is goog.
212 *
213 * @return The extracted class name, or null.
214 */
215 @Override
216 public String extractClassNameIfRequire(Node node, Node parent){
217 return extractClassNameIfGoog(node, parent, "goog.require");
218 }
219
220 private static String extractClassNameIfGoog(Node node, Node parent,
221 String functionName){
222 String className = null;
223 if (NodeUtil.isExprCall(parent)) {
224 Node callee = node.getFirstChild();
225 if (callee != null && callee.isGetProp()) {
226 String qualifiedName = callee.getQualifiedName();
227 if (functionName.equals(qualifiedName)) {
228 Node target = callee.getNext();
229 if (target != null && target.isString()) {
230 className = target.getString();
231 }
232 }
233 }
234 }
235 return className;
236 }
237
238 /**
239 * Use closure's implementation.
240 * @return closure's function name for exporting properties.
241 */
242 @Override
243 public String getExportPropertyFunction() {
244 return "goog.exportProperty";
245 }
246
247 /**
248 * Use closure's implementation.
249 * @return closure's function name for exporting symbols.
250 */
251 @Override
252 public String getExportSymbolFunction() {
253 return "goog.exportSymbol";
254 }
255
256 @Override
257 public List<String> identifyTypeDeclarationCall(Node n) {
258 Node callName = n.getFirstChild();
259 if ("goog.addDependency".equals(callName.getQualifiedName()) &&
260 n.getChildCount() >= 3) {
261 Node typeArray = callName.getNext().getNext();
262 if (typeArray.isArrayLit()) {
263 List<String> typeNames = Lists.newArrayList();
264 for (Node name = typeArray.getFirstChild(); name != null;
265 name = name.getNext()) {
266 if (name.isString()) {
267 typeNames.add(name.getString());
268 }
269 }
270 return typeNames;
271 }
272 }
273 return super.identifyTypeDeclarationCall(n);
274 }
275
276 @Override
277 public String getAbstractMethodName() {
278 return "goog.abstractMethod";
279 }
280
281 @Override
282 public String getSingletonGetterClassName(Node callNode) {
283 Node callArg = callNode.getFirstChild();
284 String callName = callArg.getQualifiedName();
285
286 // Use both the original name and the post-CollapseProperties name.
287 if (!("goog.addSingletonGetter".equals(callName) ||
288 "goog$addSingletonGetter".equals(callName)) ||
289 callNode.getChildCount() != 2) {
290 return super.getSingletonGetterClassName(callNode);
291 }
292
293 return callArg.getNext().getQualifiedName();
294 }
295
296 @Override
297 public void applySingletonGetter(FunctionType functionType,
298 FunctionType getterType, ObjectType objectType) {
299 super.applySingletonGetter(functionType, getterType, objectType);
300 functionType.defineDeclaredProperty("getInstance", getterType,
301 functionType.getSource());
302 functionType.defineDeclaredProperty("instance_", objectType,
303 functionType.getSource());
304 }
305
306 @Override
307 public String getGlobalObject() {
308 return "goog.global";
309 }
310
311 private final Set<String> propertyTestFunctions = ImmutableSet.of(
312 "goog.isDef", "goog.isNull", "goog.isDefAndNotNull",
313 "goog.isString", "goog.isNumber", "goog.isBoolean",
314 "goog.isFunction", "goog.isArray", "goog.isObject");
315
316 @Override
317 public boolean isPropertyTestFunction(Node call) {
318 Preconditions.checkArgument(call.isCall());
319 return propertyTestFunctions.contains(
320 call.getFirstChild().getQualifiedName()) ||
321 super.isPropertyTestFunction(call);
322 }
323
324 @Override
325 public ObjectLiteralCast getObjectLiteralCast(Node callNode) {
326 Preconditions.checkArgument(callNode.isCall());
327 ObjectLiteralCast proxyCast = super.getObjectLiteralCast(callNode);
328 if (proxyCast != null) {
329 return proxyCast;
330 }
331
332 Node callName = callNode.getFirstChild();
333 if (!"goog.reflect.object".equals(callName.getQualifiedName()) ||
334 callNode.getChildCount() != 3) {
335 return null;
336 }
337
338 Node typeNode = callName.getNext();
339 if (!typeNode.isQualifiedName()) {
340 return null;
341 }
342
343 Node objectNode = typeNode.getNext();
344 if (!objectNode.isObjectLit()) {
345 return new ObjectLiteralCast(null, null, OBJECTLIT_EXPECTED);
346 }
347
348 return new ObjectLiteralCast(
349 typeNode.getQualifiedName(), typeNode.getNext(), null);
350 }
351
352 @Override
353 public boolean isOptionalParameter(Node parameter) {
354 return false;
355 }
356
357 @Override
358 public boolean isVarArgsParameter(Node parameter) {
359 return false;
360 }
361
362 @Override
363 public boolean isPrivate(String name) {
364 return false;
365 }
366
367 @Override
368 public Collection<AssertionFunctionSpec> getAssertionFunctions() {
369 return ImmutableList.<AssertionFunctionSpec>of(
370 new AssertionFunctionSpec("goog.asserts.assert"),
371 new AssertionFunctionSpec("goog.asserts.assertNumber",
372 JSTypeNative.NUMBER_TYPE),
373 new AssertionFunctionSpec("goog.asserts.assertString",
374 JSTypeNative.STRING_TYPE),
375 new AssertionFunctionSpec("goog.asserts.assertFunction",
376 JSTypeNative.FUNCTION_INSTANCE_TYPE),
377 new AssertionFunctionSpec("goog.asserts.assertObject",
378 JSTypeNative.OBJECT_TYPE),
379 new AssertionFunctionSpec("goog.asserts.assertArray",
380 JSTypeNative.ARRAY_TYPE),
381 new AssertInstanceofSpec("goog.asserts.assertInstanceof")
382 );
383 }
384
385 @Override
386 public Bind describeFunctionBind(Node n, boolean useTypeInfo) {
387 Bind result = super.describeFunctionBind(n, useTypeInfo);
388 if (result != null) {
389 return result;
390 }
391
392 if (!n.isCall()) {
393 return null;
394 }
395
396 Node callTarget = n.getFirstChild();
397 String name = callTarget.getQualifiedName();
398 if (name != null) {
399 if (name.equals("goog.bind")
400 || name.equals("goog$bind")) {
401 // goog.bind(fn, self, args...);
402 Node fn = callTarget.getNext();
403 if (fn == null) {
404 return null;
405 }
406 Node thisValue = safeNext(fn);
407 Node parameters = safeNext(thisValue);
408 return new Bind(fn, thisValue, parameters);
409 }
410
411 if (name.equals("goog.partial") || name.equals("goog$partial")) {
412 // goog.partial(fn, args...);
413 Node fn = callTarget.getNext();
414 if (fn == null) {
415 return null;
416 }
417 Node thisValue = null;
418 Node parameters = safeNext(fn);
419 return new Bind(fn, thisValue, parameters);
420 }
421 }
422
423 return null;
424 }
425
426 @Override
427 public Collection<String> getIndirectlyDeclaredProperties() {
428 return indirectlyDeclaredProperties;
429 }
430
431 private Node safeNext(Node n) {
432 if (n != null) {
433 return n.getNext();
434 }
435 return null;
436 }
437
438 /**
439 * A function that will throw an exception when if the value is not
440 * an instanceof a specific type.
441 */
442 public static class AssertInstanceofSpec extends AssertionFunctionSpec {
443 public AssertInstanceofSpec(String functionName) {
444 super(functionName, JSTypeNative.OBJECT_TYPE);
445 }
446
447 /**
448 * Returns the type for a type assertion, or null if the function asserts
449 * that the node must not be null or undefined.
450 */
451 @Override
452 public JSType getAssertedType(Node call, JSTypeRegistry registry) {
453 if (call.getChildCount() > 2) {
454 Node constructor = call.getFirstChild().getNext().getNext();
455 if (constructor != null) {
456 JSType ownerType = constructor.getJSType();
457 if (ownerType != null
458 && ownerType.isFunctionType()
459 && ownerType.isConstructor()) {
460 FunctionType functionType = ((FunctionType) ownerType);
461 return functionType.getInstanceType();
462 }
463 }
464 }
465 return super.getAssertedType(call, registry);
466 }
467 }
468
469
470 }