Debian Codegraph @

src/com/google/javascript/jscomp/FunctionTypeBuilder.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 static com.google.javascript.jscomp.TypeCheck.BAD_IMPLEMENTED_TYPE;
20 import static com.google.javascript.rhino.jstype.JSTypeNative.FUNCTION_FUNCTION_TYPE;
21 import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE;
22 import static com.google.javascript.rhino.jstype.JSTypeNative.VOID_TYPE;
23
24 import com.google.common.base.Preconditions;
25 import com.google.common.base.Predicate;
26 import com.google.common.collect.HashMultiset;
27 import com.google.common.collect.ImmutableList;
28 import com.google.common.collect.ImmutableMultiset;
29 import com.google.common.collect.ImmutableSet;
30 import com.google.common.collect.Lists;
31 import com.google.common.collect.Multiset;
32 import com.google.common.collect.Sets;
33 import com.google.javascript.jscomp.Scope.Var;
34 import com.google.javascript.rhino.IR;
35 import com.google.javascript.rhino.JSDocInfo;
36 import com.google.javascript.rhino.JSTypeExpression;
37 import com.google.javascript.rhino.Node;
38 import com.google.javascript.rhino.jstype.FunctionBuilder;
39 import com.google.javascript.rhino.jstype.FunctionParamBuilder;
40 import com.google.javascript.rhino.jstype.FunctionType;
41 import com.google.javascript.rhino.jstype.JSType;
42 import com.google.javascript.rhino.jstype.JSTypeRegistry;
43 import com.google.javascript.rhino.jstype.ObjectType;
44 import com.google.javascript.rhino.jstype.TemplateType;
45
46 import java.util.Iterator;
47 import java.util.List;
48 import java.util.Set;
49
50 import javax.annotation.Nullable;
51
52 /**
53 * A builder for FunctionTypes, because FunctionTypes are so
54 * ridiculously complex. All methods return {@code this} for ease of use.
55 *
56 * Right now, this mostly uses JSDocInfo to infer type information about
57 * functions. In the long term, developers should extend it to use other
58 * signals by overloading the various "inferXXX" methods. For example, we
59 * might want to use {@code goog.inherits} calls as a signal for inheritance, or
60 * {@code return} statements as a signal for return type.
61 *
62 * NOTE(nicksantos): Organizationally, this feels like it should be in Rhino.
63 * But it depends on some coding convention stuff that's really part
64 * of JSCompiler.
65 *
66 * @author [email protected] (Nick Santos)
67 * @author [email protected] (Pascal-Louis Perez)
68 */
69 final class FunctionTypeBuilder {
70
71 private final String fnName;
72 private final AbstractCompiler compiler;
73 private final CodingConvention codingConvention;
74 private final JSTypeRegistry typeRegistry;
75 private final Node errorRoot;
76 private final String sourceName;
77 private final Scope scope;
78
79 private FunctionContents contents = UnknownFunctionContents.get();
80
81 private JSType returnType = null;
82 private boolean returnTypeInferred = false;
83 private List<ObjectType> implementedInterfaces = null;
84 private List<ObjectType> extendedInterfaces = null;
85 private ObjectType baseType = null;
86 private JSType thisType = null;
87 private boolean isConstructor = false;
88 private boolean makesStructs = false;
89 private boolean makesDicts = false;
90 private boolean isInterface = false;
91 private Node parametersNode = null;
92 private ImmutableList<TemplateType> templateTypeNames = ImmutableList.of();
93 private ImmutableList<String> classTypeParameterNames = ImmutableList.of();;
94
95 static final DiagnosticType EXTENDS_WITHOUT_TYPEDEF = DiagnosticType.warning(
96 "JSC_EXTENDS_WITHOUT_TYPEDEF",
97 "@extends used without @constructor or @interface for {0}");
98
99 static final DiagnosticType EXTENDS_NON_OBJECT = DiagnosticType.warning(
100 "JSC_EXTENDS_NON_OBJECT",
101 "{0} @extends non-object type {1}");
102
103 static final DiagnosticType RESOLVED_TAG_EMPTY = DiagnosticType.warning(
104 "JSC_RESOLVED_TAG_EMPTY",
105 "Could not resolve type in {0} tag of {1}");
106
107 static final DiagnosticType IMPLEMENTS_WITHOUT_CONSTRUCTOR =
108 DiagnosticType.warning(
109 "JSC_IMPLEMENTS_WITHOUT_CONSTRUCTOR",
110 "@implements used without @constructor or @interface for {0}");
111
112 static final DiagnosticType CONSTRUCTOR_REQUIRED =
113 DiagnosticType.warning("JSC_CONSTRUCTOR_REQUIRED",
114 "{0} used without @constructor for {1}");
115
116 static final DiagnosticType CLASS_TEMPLATE_WITHOUT_CONSTRUCTOR =
117 DiagnosticType.warning(
118 "JSC_CLASS_TEMPLATE_WITHOUT_CONSTRUCTOR",
119 "@classTemplate used without @constructor or @interface for {0}");
120
121 static final DiagnosticType VAR_ARGS_MUST_BE_LAST = DiagnosticType.warning(
122 "JSC_VAR_ARGS_MUST_BE_LAST",
123 "variable length argument must be last");
124
125 static final DiagnosticType OPTIONAL_ARG_AT_END = DiagnosticType.warning(
126 "JSC_OPTIONAL_ARG_AT_END",
127 "optional arguments must be at the end");
128
129 static final DiagnosticType INEXISTANT_PARAM = DiagnosticType.warning(
130 "JSC_INEXISTANT_PARAM",
131 "parameter {0} does not appear in {1}''s parameter list");
132
133 static final DiagnosticType TYPE_REDEFINITION = DiagnosticType.warning(
134 "JSC_TYPE_REDEFINITION",
135 "attempted re-definition of type {0}\n"
136 + "found : {1}\n"
137 + "expected: {2}");
138
139 static final DiagnosticType TEMPLATE_TYPE_DUPLICATED = DiagnosticType.warning(
140 "JSC_TEMPLATE_TYPE_DUPLICATED",
141 "Only one parameter type must be the template type");
142
143 static final DiagnosticType TEMPLATE_TYPE_EXPECTED = DiagnosticType.warning(
144 "JSC_TEMPLATE_TYPE_EXPECTED",
145 "The template type must be a parameter type");
146
147 static final DiagnosticType THIS_TYPE_NON_OBJECT =
148 DiagnosticType.warning(
149 "JSC_THIS_TYPE_NON_OBJECT",
150 "@this type of a function must be an object\n" +
151 "Actual type: {0}");
152
153 private class ExtendedTypeValidator implements Predicate<JSType> {
154 @Override
155 public boolean apply(JSType type) {
156 ObjectType objectType = ObjectType.cast(type);
157 if (objectType == null) {
158 reportWarning(EXTENDS_NON_OBJECT, formatFnName(), type.toString());
159 return false;
160 } else if (objectType.isEmptyType()) {
161 reportWarning(RESOLVED_TAG_EMPTY, "@extends", formatFnName());
162 return false;
163 } else if (objectType.isUnknownType()) {
164 if (hasMoreTagsToResolve(objectType)) {
165 return true;
166 } else {
167 reportWarning(RESOLVED_TAG_EMPTY, "@extends", fnName);
168 return false;
169 }
170 } else {
171 return true;
172 }
173 }
174 }
175
176 private class ImplementedTypeValidator implements Predicate<JSType> {
177 @Override
178 public boolean apply(JSType type) {
179 ObjectType objectType = ObjectType.cast(type);
180 if (objectType == null) {
181 reportError(BAD_IMPLEMENTED_TYPE, fnName);
182 return false;
183 } else if (objectType.isEmptyType()) {
184 reportWarning(RESOLVED_TAG_EMPTY, "@implements", fnName);
185 return false;
186 } else if (objectType.isUnknownType()) {
187 if (hasMoreTagsToResolve(objectType)) {
188 return true;
189 } else {
190 reportWarning(RESOLVED_TAG_EMPTY, "@implements", fnName);
191 return false;
192 }
193 } else {
194 return true;
195 }
196 }
197 }
198
199 /**
200 * @param fnName The function name.
201 * @param compiler The compiler.
202 * @param errorRoot The node to associate with any warning generated by
203 * this builder.
204 * @param sourceName A source name for associating any warnings that
205 * we have to emit.
206 * @param scope The syntactic scope.
207 */
208 FunctionTypeBuilder(String fnName, AbstractCompiler compiler,
209 Node errorRoot, String sourceName, Scope scope) {
210 Preconditions.checkNotNull(errorRoot);
211
212 this.fnName = fnName == null ? "" : fnName;
213 this.codingConvention = compiler.getCodingConvention();
214 this.typeRegistry = compiler.getTypeRegistry();
215 this.errorRoot = errorRoot;
216 this.sourceName = sourceName;
217 this.compiler = compiler;
218 this.scope = scope;
219 }
220
221 /** Format the function name for use in warnings. */
222 String formatFnName() {
223 return fnName.isEmpty() ? "<anonymous>" : fnName;
224 }
225
226 /**
227 * Sets the contents of this function.
228 */
229 FunctionTypeBuilder setContents(@Nullable FunctionContents contents) {
230 if (contents != null) {
231 this.contents = contents;
232 }
233 return this;
234 }
235
236 /**
237 * Infer the parameter and return types of a function from
238 * the parameter and return types of the function it is overriding.
239 *
240 * @param oldType The function being overridden. Does nothing if this is null.
241 * @param paramsParent The LP node of the function that we're assigning to.
242 * If null, that just means we're not initializing this to a function
243 * literal.
244 */
245 FunctionTypeBuilder inferFromOverriddenFunction(
246 @Nullable FunctionType oldType, @Nullable Node paramsParent) {
247 if (oldType == null) {
248 return this;
249 }
250
251 returnType = oldType.getReturnType();
252 returnTypeInferred = oldType.isReturnTypeInferred();
253 if (paramsParent == null) {
254 // Not a function literal.
255 parametersNode = oldType.getParametersNode();
256 if (parametersNode == null) {
257 parametersNode = new FunctionParamBuilder(typeRegistry).build();
258 }
259 } else {
260 // We're overriding with a function literal. Apply type information
261 // to each parameter of the literal.
262 FunctionParamBuilder paramBuilder =
263 new FunctionParamBuilder(typeRegistry);
264 Iterator<Node> oldParams = oldType.getParameters().iterator();
265 boolean warnedAboutArgList = false;
266 boolean oldParamsListHitOptArgs = false;
267 for (Node currentParam = paramsParent.getFirstChild();
268 currentParam != null; currentParam = currentParam.getNext()) {
269 if (oldParams.hasNext()) {
270 Node oldParam = oldParams.next();
271 Node newParam = paramBuilder.newParameterFromNode(oldParam);
272
273 oldParamsListHitOptArgs = oldParamsListHitOptArgs ||
274 oldParam.isVarArgs() ||
275 oldParam.isOptionalArg();
276
277 // The subclass method might write its var_args as individual
278 // arguments.
279 if (currentParam.getNext() != null && newParam.isVarArgs()) {
280 newParam.setVarArgs(false);
281 newParam.setOptionalArg(true);
282 }
283 } else {
284 warnedAboutArgList |= addParameter(
285 paramBuilder,
286 typeRegistry.getNativeType(UNKNOWN_TYPE),
287 warnedAboutArgList,
288 codingConvention.isOptionalParameter(currentParam) ||
289 oldParamsListHitOptArgs,
290 codingConvention.isVarArgsParameter(currentParam));
291 }
292 }
293
294 // Clone any remaining params that aren't in the function literal,
295 // but make them optional.
296 while (oldParams.hasNext()) {
297 paramBuilder.newOptionalParameterFromNode(oldParams.next());
298 }
299
300 parametersNode = paramBuilder.build();
301 }
302 return this;
303 }
304
305 /**
306 * Infer the return type from JSDocInfo.
307 */
308 FunctionTypeBuilder inferReturnType(@Nullable JSDocInfo info) {
309 if (info != null && info.hasReturnType()) {
310 returnType = info.getReturnType().evaluate(scope, typeRegistry);
311 returnTypeInferred = false;
312 }
313
314 return this;
315 }
316
317 /**
318 * Infer the role of the function (whether it's a constructor or interface)
319 * and what it inherits from in JSDocInfo.
320 */
321 FunctionTypeBuilder inferInheritance(@Nullable JSDocInfo info) {
322 if (info != null) {
323 isConstructor = info.isConstructor();
324 makesStructs = info.makesStructs();
325 makesDicts = info.makesDicts();
326 isInterface = info.isInterface();
327
328 if (makesStructs && !isConstructor) {
329 reportWarning(CONSTRUCTOR_REQUIRED, "@struct", formatFnName());
330 } else if (makesDicts && !isConstructor) {
331 reportWarning(CONSTRUCTOR_REQUIRED, "@dict", formatFnName());
332 }
333
334 // base type
335 if (info.hasBaseType()) {
336 if (isConstructor) {
337 JSType maybeBaseType =
338 info.getBaseType().evaluate(scope, typeRegistry);
339 if (maybeBaseType != null &&
340 maybeBaseType.setValidator(new ExtendedTypeValidator())) {
341 baseType = (ObjectType) maybeBaseType;
342 }
343 } else {
344 reportWarning(EXTENDS_WITHOUT_TYPEDEF, formatFnName());
345 }
346 }
347
348 // Implemented interfaces (for constructors only).
349 if (info.getImplementedInterfaceCount() > 0) {
350 if (isConstructor) {
351 implementedInterfaces = Lists.newArrayList();
352 for (JSTypeExpression t : info.getImplementedInterfaces()) {
353 JSType maybeInterType = t.evaluate(scope, typeRegistry);
354 if (maybeInterType != null &&
355 maybeInterType.setValidator(new ImplementedTypeValidator())) {
356 implementedInterfaces.add((ObjectType) maybeInterType);
357 }
358 }
359 } else if (isInterface) {
360 reportWarning(
361 TypeCheck.CONFLICTING_IMPLEMENTED_TYPE, formatFnName());
362 } else {
363 reportWarning(CONSTRUCTOR_REQUIRED, "@implements", formatFnName());
364 }
365 }
366
367 // extended interfaces (for interfaces only)
368 // We've already emitted a warning if this is not an interface.
369 if (isInterface) {
370 extendedInterfaces = Lists.newArrayList();
371 for (JSTypeExpression t : info.getExtendedInterfaces()) {
372 JSType maybeInterfaceType = t.evaluate(scope, typeRegistry);
373 if (maybeInterfaceType != null &&
374 maybeInterfaceType.setValidator(new ExtendedTypeValidator())) {
375 extendedInterfaces.add((ObjectType) maybeInterfaceType);
376 }
377 }
378 }
379
380 ImmutableList<String> typeParameters = info.getClassTemplateTypeNames();
381 if (!typeParameters.isEmpty()) {
382 if (isConstructor || isInterface) {
383 this.classTypeParameterNames = typeParameters;
384 } else {
385 reportWarning(CLASS_TEMPLATE_WITHOUT_CONSTRUCTOR,
386 formatFnName());
387 }
388 }
389 }
390
391 return this;
392 }
393
394 /**
395 * Infers the type of {@code this}.
396 * @param type The type of this if the info is missing.
397 */
398 FunctionTypeBuilder inferThisType(JSDocInfo info, JSType type) {
399 // Look at the @this annotation first.
400 inferThisType(info);
401
402 if (thisType == null) {
403 ObjectType objType = ObjectType.cast(type);
404 if (objType != null && (info == null || !info.hasType())) {
405 thisType = objType;
406 }
407 }
408
409 return this;
410 }
411
412 /**
413 * Infers the type of {@code this}.
414 * @param info The JSDocInfo for this function.
415 */
416 FunctionTypeBuilder inferThisType(JSDocInfo info) {
417 JSType maybeThisType = null;
418 if (info != null && info.hasThisType()) {
419 // TODO(johnlenz): In ES5 strict mode a function can have a null or
420 // undefined "this" value, but all the existing "@this" annotations
421 // don't declare restricted types.
422 maybeThisType = info.getThisType().evaluate(scope, typeRegistry)
423 .restrictByNotNullOrUndefined();
424 }
425 if (maybeThisType != null) {
426 thisType = maybeThisType;
427 }
428
429 return this;
430 }
431
432 /**
433 * Infer the parameter types from the doc info alone.
434 */
435 FunctionTypeBuilder inferParameterTypes(JSDocInfo info) {
436 // Create a fake args parent.
437 Node lp = IR.paramList();
438 for (String name : info.getParameterNames()) {
439 lp.addChildToBack(IR.name(name));
440 }
441
442 return inferParameterTypes(lp, info);
443 }
444
445 /**
446 * Infer the parameter types from the list of argument names and
447 * the doc info.
448 */
449 FunctionTypeBuilder inferParameterTypes(@Nullable Node argsParent,
450 @Nullable JSDocInfo info) {
451 if (argsParent == null) {
452 if (info == null) {
453 return this;
454 } else {
455 return inferParameterTypes(info);
456 }
457 }
458
459 // arguments
460 Node oldParameterType = null;
461 if (parametersNode != null) {
462 oldParameterType = parametersNode.getFirstChild();
463 }
464
465 FunctionParamBuilder builder = new FunctionParamBuilder(typeRegistry);
466 boolean warnedAboutArgList = false;
467 Set<String> allJsDocParams = (info == null) ?
468 Sets.<String>newHashSet() :
469 Sets.newHashSet(info.getParameterNames());
470 boolean isVarArgs = false;
471 for (Node arg : argsParent.children()) {
472 String argumentName = arg.getString();
473 allJsDocParams.remove(argumentName);
474
475 // type from JSDocInfo
476 JSType parameterType = null;
477 boolean isOptionalParam = isOptionalParameter(arg, info);
478 isVarArgs = isVarArgsParameter(arg, info);
479
480 if (info != null && info.hasParameterType(argumentName)) {
481 parameterType =
482 info.getParameterType(argumentName).evaluate(scope, typeRegistry);
483 } else if (arg.getJSDocInfo() != null && arg.getJSDocInfo().hasType()) {
484 parameterType =
485 arg.getJSDocInfo().getType().evaluate(scope, typeRegistry);
486 } else if (oldParameterType != null &&
487 oldParameterType.getJSType() != null) {
488 parameterType = oldParameterType.getJSType();
489 isOptionalParam = oldParameterType.isOptionalArg();
490 isVarArgs = oldParameterType.isVarArgs();
491 } else {
492 parameterType = typeRegistry.getNativeType(UNKNOWN_TYPE);
493 }
494
495 warnedAboutArgList |= addParameter(
496 builder, parameterType, warnedAboutArgList,
497 isOptionalParam,
498 isVarArgs);
499
500 if (oldParameterType != null) {
501 oldParameterType = oldParameterType.getNext();
502 }
503 }
504
505 // Copy over any old parameters that aren't in the param list.
506 if (!isVarArgs) {
507 while (oldParameterType != null && !isVarArgs) {
508 builder.newParameterFromNode(oldParameterType);
509 oldParameterType = oldParameterType.getNext();
510 }
511 }
512
513 for (String inexistentName : allJsDocParams) {
514 reportWarning(INEXISTANT_PARAM, inexistentName, formatFnName());
515 }
516
517 parametersNode = builder.build();
518 return this;
519 }
520
521 /**
522 * @return Whether the given param is an optional param.
523 */
524 private boolean isOptionalParameter(
525 Node param, @Nullable JSDocInfo info) {
526 if (codingConvention.isOptionalParameter(param)) {
527 return true;
528 }
529
530 String paramName = param.getString();
531 return info != null && info.hasParameterType(paramName) &&
532 info.getParameterType(paramName).isOptionalArg();
533 }
534
535 /**
536 * Determine whether this is a var args parameter.
537 * @return Whether the given param is a var args param.
538 */
539 private boolean isVarArgsParameter(
540 Node param, @Nullable JSDocInfo info) {
541 if (codingConvention.isVarArgsParameter(param)) {
542 return true;
543 }
544
545 String paramName = param.getString();
546 return info != null && info.hasParameterType(paramName) &&
547 info.getParameterType(paramName).isVarArgs();
548 }
549
550 /**
551 * Infer the template type from the doc info.
552 */
553 FunctionTypeBuilder inferTemplateTypeName(
554 @Nullable JSDocInfo info) {
555 if (info != null && !info.getTemplateTypeNames().isEmpty()) {
556 ImmutableList.Builder<TemplateType> builder = ImmutableList.builder();
557 for (String key : info.getTemplateTypeNames()) {
558 builder.add(typeRegistry.createTemplateType(key));
559 }
560 templateTypeNames = builder.build();
561 } else {
562 templateTypeNames = ImmutableList.of();
563 }
564 typeRegistry.setTemplateTypeNames(templateTypeNames);
565 return this;
566 }
567
568 /**
569 * Add a parameter to the param list.
570 * @param builder A builder.
571 * @param paramType The parameter type.
572 * @param warnedAboutArgList Whether we've already warned about arg ordering
573 * issues (like if optional args appeared before required ones).
574 * @param isOptional Is this an optional parameter?
575 * @param isVarArgs Is this a var args parameter?
576 * @return Whether a warning was emitted.
577 */
578 private boolean addParameter(FunctionParamBuilder builder,
579 JSType paramType, boolean warnedAboutArgList,
580 boolean isOptional, boolean isVarArgs) {
581 boolean emittedWarning = false;
582 if (isOptional) {
583 // Remembering that an optional parameter has been encountered
584 // so that if a non optional param is encountered later, an
585 // error can be reported.
586 if (!builder.addOptionalParams(paramType) && !warnedAboutArgList) {
587 reportWarning(VAR_ARGS_MUST_BE_LAST);
588 emittedWarning = true;
589 }
590 } else if (isVarArgs) {
591 if (!builder.addVarArgs(paramType) && !warnedAboutArgList) {
592 reportWarning(VAR_ARGS_MUST_BE_LAST);
593 emittedWarning = true;
594 }
595 } else {
596 if (!builder.addRequiredParams(paramType) && !warnedAboutArgList) {
597 // An optional parameter was seen and this argument is not an optional
598 // or var arg so it is an error.
599 if (builder.hasVarArgs()) {
600 reportWarning(VAR_ARGS_MUST_BE_LAST);
601 } else {
602 reportWarning(OPTIONAL_ARG_AT_END);
603 }
604 emittedWarning = true;
605 }
606 }
607 return emittedWarning;
608 }
609
610 /**
611 * Builds the function type, and puts it in the registry.
612 */
613 FunctionType buildAndRegister() {
614 if (returnType == null) {
615 // Infer return types.
616 // We need to be extremely conservative about this, because of two
617 // competing needs.
618 // 1) If we infer the return type of f too widely, then we won't be able
619 // to assign f to other functions.
620 // 2) If we infer the return type of f too narrowly, then we won't be
621 // able to override f in subclasses.
622 // So we only infer in cases where the user doesn't expect to write
623 // @return annotations--when it's very obvious that the function returns
624 // nothing.
625 if (!contents.mayHaveNonEmptyReturns() &&
626 !contents.mayHaveSingleThrow() &&
627 !contents.mayBeFromExterns()) {
628 returnType = typeRegistry.getNativeType(VOID_TYPE);
629 returnTypeInferred = true;
630 }
631 }
632
633 if (returnType == null) {
634 returnType = typeRegistry.getNativeType(UNKNOWN_TYPE);
635 }
636
637 if (parametersNode == null) {
638 throw new IllegalStateException(
639 "All Function types must have params and a return type");
640 }
641
642 FunctionType fnType;
643 if (isConstructor) {
644 fnType = getOrCreateConstructor();
645 } else if (isInterface) {
646 fnType = typeRegistry.createInterfaceType(
647 fnName, contents.getSourceNode());
648 if (getScopeDeclaredIn().isGlobal() && !fnName.isEmpty()) {
649 typeRegistry.declareType(fnName, fnType.getInstanceType());
650 }
651 maybeSetBaseType(fnType);
652 } else {
653 fnType = new FunctionBuilder(typeRegistry)
654 .withName(fnName)
655 .withSourceNode(contents.getSourceNode())
656 .withParamsNode(parametersNode)
657 .withReturnType(returnType, returnTypeInferred)
658 .withTypeOfThis(thisType)
659 .withTemplateKeys(templateTypeNames)
660 .build();
661 maybeSetBaseType(fnType);
662 }
663
664 if (implementedInterfaces != null) {
665 fnType.setImplementedInterfaces(implementedInterfaces);
666 }
667
668 if (extendedInterfaces != null) {
669 fnType.setExtendedInterfaces(extendedInterfaces);
670 }
671
672 typeRegistry.clearTemplateTypeNames();
673
674 return fnType;
675 }
676
677 private void maybeSetBaseType(FunctionType fnType) {
678 if (!fnType.isInterface() && baseType != null) {
679 fnType.setPrototypeBasedOn(baseType);
680 }
681 }
682
683 /**
684 * Returns a constructor function either by returning it from the
685 * registry if it exists or creating and registering a new type. If
686 * there is already a type, then warn if the existing type is
687 * different than the one we are creating, though still return the
688 * existing function if possible. The primary purpose of this is
689 * that registering a constructor will fail for all built-in types
690 * that are initialized in {@link JSTypeRegistry}. We a) want to
691 * make sure that the type information specified in the externs file
692 * matches what is in the registry and b) annotate the externs with
693 * the {@link JSType} from the registry so that there are not two
694 * separate JSType objects for one type.
695 */
696 private FunctionType getOrCreateConstructor() {
697 FunctionType fnType = typeRegistry.createConstructorType(
698 fnName, contents.getSourceNode(), parametersNode, returnType,
699 classTypeParameterNames);
700 JSType existingType = typeRegistry.getType(fnName);
701
702 if (makesStructs) {
703 fnType.setStruct();
704 } else if (makesDicts) {
705 fnType.setDict();
706 }
707 if (existingType != null) {
708 boolean isInstanceObject = existingType.isInstanceType();
709 if (isInstanceObject || fnName.equals("Function")) {
710 FunctionType existingFn =
711 isInstanceObject ?
712 existingType.toObjectType().getConstructor() :
713 typeRegistry.getNativeFunctionType(FUNCTION_FUNCTION_TYPE);
714
715 if (existingFn.getSource() == null) {
716 existingFn.setSource(contents.getSourceNode());
717 }
718
719 if (!existingFn.hasEqualCallType(fnType)) {
720 reportWarning(TYPE_REDEFINITION, formatFnName(),
721 fnType.toString(), existingFn.toString());
722 }
723
724 return existingFn;
725 } else {
726 // We fall through and return the created type, even though it will fail
727 // to register. We have no choice as we have to return a function. We
728 // issue an error elsewhere though, so the user should fix it.
729 }
730 }
731
732 maybeSetBaseType(fnType);
733
734 if (getScopeDeclaredIn().isGlobal() && !fnName.isEmpty()) {
735 typeRegistry.declareType(fnName, fnType.getInstanceType());
736 }
737 return fnType;
738 }
739
740 private void reportWarning(DiagnosticType warning, String ... args) {
741 compiler.report(JSError.make(sourceName, errorRoot, warning, args));
742 }
743
744 private void reportError(DiagnosticType error, String ... args) {
745 compiler.report(JSError.make(sourceName, errorRoot, error, args));
746 }
747
748 /**
749 * Determines whether the given JsDoc info declares a function type.
750 */
751 static boolean isFunctionTypeDeclaration(JSDocInfo info) {
752 return info.getParameterCount() > 0 ||
753 info.hasReturnType() ||
754 info.hasThisType() ||
755 info.isConstructor() ||
756 info.isInterface();
757 }
758
759 /**
760 * The scope that we should declare this function in, if it needs
761 * to be declared in a scope. Notice that TypedScopeCreator takes
762 * care of most scope-declaring.
763 */
764 private Scope getScopeDeclaredIn() {
765 int dotIndex = fnName.indexOf(".");
766 if (dotIndex != -1) {
767 String rootVarName = fnName.substring(0, dotIndex);
768 Var rootVar = scope.getVar(rootVarName);
769 if (rootVar != null) {
770 return rootVar.getScope();
771 }
772 }
773 return scope;
774 }
775
776 /**
777 * Check whether a type is resolvable in the future
778 * If this has a supertype that hasn't been resolved yet, then we can assume
779 * this type will be OK once the super type resolves.
780 * @param objectType
781 * @return true if objectType is resolvable in the future
782 */
783 private static boolean hasMoreTagsToResolve(ObjectType objectType) {
784 Preconditions.checkArgument(objectType.isUnknownType());
785 if (objectType.getImplicitPrototype() != null) {
786 // constructor extends class
787 if (objectType.getImplicitPrototype().isResolved()) {
788 return false;
789 } else {
790 return true;
791 }
792 } else {
793 // interface extends interfaces
794 FunctionType ctor = objectType.getConstructor();
795 if (ctor != null) {
796 for (ObjectType interfaceType : ctor.getExtendedInterfaces()) {
797 if (!interfaceType.isResolved()) {
798 return true;
799 }
800 }
801 }
802 return false;
803 }
804 }
805
806 /** Holds data dynamically inferred about functions. */
807 static interface FunctionContents {
808 /** Returns the source node of this function. May be null. */
809 Node getSourceNode();
810
811 /** Returns if the function may be in externs. */
812 boolean mayBeFromExterns();
813
814 /** Returns if a return of a real value (not undefined) appears. */
815 boolean mayHaveNonEmptyReturns();
816
817 /** Returns if this consists of a single throw. */
818 boolean mayHaveSingleThrow();
819
820 /** Gets a list of variables in this scope that are escaped. */
821 Iterable<String> getEscapedVarNames();
822
823 /** Gets a list of variables whose properties are escaped. */
824 Set<String> getEscapedQualifiedNames();
825
826 /** Gets the number of times each variable has been assigned. */
827 Multiset<String> getAssignedNameCounts();
828 }
829
830 static class UnknownFunctionContents implements FunctionContents {
831 private static UnknownFunctionContents singleton =
832 new UnknownFunctionContents();
833
834 static FunctionContents get() {
835 return singleton;
836 }
837
838 @Override
839 public Node getSourceNode() {
840 return null;
841 }
842
843 @Override
844 public boolean mayBeFromExterns() {
845 return true;
846 }
847
848 @Override
849 public boolean mayHaveNonEmptyReturns() {
850 return true;
851 }
852
853 @Override
854 public boolean mayHaveSingleThrow() {
855 return true;
856 }
857
858 @Override
859 public Iterable<String> getEscapedVarNames() {
860 return ImmutableList.of();
861 }
862
863 @Override
864 public Set<String> getEscapedQualifiedNames() {
865 return ImmutableSet.of();
866 }
867
868 @Override
869 public Multiset<String> getAssignedNameCounts() {
870 return ImmutableMultiset.of();
871 }
872 }
873
874 static class AstFunctionContents implements FunctionContents {
875 private final Node n;
876 private boolean hasNonEmptyReturns = false;
877 private Set<String> escapedVarNames;
878 private Set<String> escapedQualifiedNames;
879 private final Multiset<String> assignedVarNames = HashMultiset.create();
880
881 AstFunctionContents(Node n) {
882 this.n = n;
883 }
884
885 @Override
886 public Node getSourceNode() {
887 return n;
888 }
889
890 @Override
891 public boolean mayBeFromExterns() {
892 return n.isFromExterns();
893 }
894
895 @Override
896 public boolean mayHaveNonEmptyReturns() {
897 return hasNonEmptyReturns;
898 }
899
900 void recordNonEmptyReturn() {
901 hasNonEmptyReturns = true;
902 }
903
904 @Override
905 public boolean mayHaveSingleThrow() {
906 Node block = n.getLastChild();
907 return block.hasOneChild() && block.getFirstChild().isThrow();
908 }
909
910 @Override
911 public Iterable<String> getEscapedVarNames() {
912 return escapedVarNames == null
913 ? ImmutableList.<String>of() : escapedVarNames;
914 }
915
916 void recordEscapedVarName(String name) {
917 if (escapedVarNames == null) {
918 escapedVarNames = Sets.newHashSet();
919 }
920 escapedVarNames.add(name);
921 }
922
923 @Override
924 public Set<String> getEscapedQualifiedNames() {
925 return escapedQualifiedNames == null
926 ? ImmutableSet.<String>of() : escapedQualifiedNames;
927 }
928
929 void recordEscapedQualifiedName(String name) {
930 if (escapedQualifiedNames == null) {
931 escapedQualifiedNames = Sets.newHashSet();
932 }
933 escapedQualifiedNames.add(name);
934 }
935
936 @Override
937 public Multiset<String> getAssignedNameCounts() {
938 return assignedVarNames;
939 }
940
941 void recordAssignedName(String name) {
942 assignedVarNames.add(name);
943 }
944 }
945 }