For functions that use template types, specialize the function type for the call target based
on the call-site specific arguments. Specifically, this enables inference to set the type of
any function literal parameters based on these inferred types.
161389
private boolean inferTemplatedTypesForCall(Node n, FunctionType fnType, FlowScope scope) {
    ImmutableList<TemplateType> keys = fnType.getTemplateTypeMap().getTemplateKeys();
    if (keys.isEmpty()) {
      return false;
    }

    // Try to infer the template types
    Map<TemplateType, JSType> rawInferrence = inferTemplateTypesFromParameters(fnType, n, scope);
    Map<TemplateType, JSType> inferred = Maps.newIdentityHashMap();
    for (TemplateType key : keys) {
      JSType type = rawInferrence.get(key);
      if (type == null) {
        type = unknownType;
      }
      inferred.put(key, type);
    }

    // Try to infer the template types using the type transformations
    Map<TemplateType, JSType> typeTransformations =
        evaluateTypeTransformations(keys, inferred, scope);
    if (typeTransformations != null) {
      inferred.putAll(typeTransformations);
    }

    // Replace all template types. If we couldn't find a replacement, we
    // replace it with UNKNOWN.
    TemplateTypeReplacer replacer = new TemplateTypeReplacer(registry, inferred);
    Node callTarget = n.getFirstChild();

    FunctionType replacementFnType = fnType.visit(replacer).toMaybeFunctionType();
    checkNotNull(replacementFnType);
    callTarget.setJSType(replacementFnType);
    n.setJSType(replacementFnType.getReturnType());

    return replacer.madeChanges;
  }
623794
private Argument functionArgument(Data data, boolean varKeyUpperCase) throws TemplateException {
	return functionArgument(data, null, varKeyUpperCase);
    }
967003
def set_function(self, f):
        

        def samples(self):
            return (('', {}, float(f())),)

        self._child_samples = types.MethodType(samples, self)
13449
def is_function_variadic(self):
        """"""
        assert self.kind == TypeKind.FUNCTIONPROTO

        return conf.lib.clang_isFunctionTypeVariadic(self)
46394
def infer_call_result(self, caller=None, context=None):
        
        if self.is_generator():
            if isinstance(self, AsyncFunctionDef):
                generator_cls = bases.AsyncGenerator
            else:
                generator_cls = bases.Generator
            result = generator_cls(self)
            yield result
            return
        # This is really a gigantic hack to work around metaclass generators
        # that return transient class-generating functions. Pylint's AST structure
        # cannot handle a base class object that is only used for calling __new__,
        # but does not contribute to the inheritance structure itself. We inject
        # a fake class into the hierarchy here for several well-known metaclass
        # generators, and filter it out later.
        if (
            self.name == "with_metaclass"
            and len(self.args.args) == 1
            and self.args.vararg is not None
        ):
            metaclass = next(caller.args[0].infer(context))
            if isinstance(metaclass, ClassDef):
                class_bases = [next(arg.infer(context)) for arg in caller.args[1:]]
                new_class = ClassDef(name="temporary_class")
                new_class.hide = True
                new_class.parent = self
                new_class.postinit(
                    bases=[base for base in class_bases if base != util.Uninferable],
                    body=[],
                    decorators=[],
                    metaclass=metaclass,
                )
                yield new_class
                return
        returns = self._get_return_nodes_skip_functions()

        first_return = next(returns, None)
        if not first_return:
            raise exceptions.InferenceError("Empty return iterator")

        for returnnode in itertools.chain((first_return,), returns):
            if returnnode.value is None:
                yield node_classes.Const(None)
            else:
                try:
                    yield from returnnode.value.infer(context)
                except exceptions.InferenceError:
                    yield util.Uninferable
945627
private String genParamsRecordType(TemplateNode node) {
    Set<String> paramNames = new HashSet<>();

    // Generate members for explicit params.
    Map<String, String> record = new LinkedHashMap<>();
    for (TemplateParam param : node.getParams()) {
      JsType jsType = getJsTypeForParamForDeclaration(param.type());
      record.put(
          param.name(), jsType.typeExprForRecordMember(/* isOptional= */ !param.isRequired()));
      for (GoogRequire require : jsType.getGoogRequires()) {
        // TODO(lukes): switch these to requireTypes
        jsCodeBuilder.addGoogRequire(require);
      }
      paramNames.add(param.name());
    }

    // Do the same for indirect params, if we can find them.
    // If there's a conflict between the explicitly-declared type, and the type
    // inferred from the indirect params, then the explicit type wins.
    // Also note that indirect param types may not be inferrable if the target
    // is not in the current compilation file set.
    IndirectParamsInfo ipi =
        new IndirectParamsCalculator(templateRegistry)
            .calculateIndirectParams(templateRegistry.getMetadata(node));
    // If there are any calls outside of the file set, then we can't know
    // the complete types of any indirect params. In such a case, we can simply
    // omit the indirect params from the function type signature, since record
    // types in JS allow additional undeclared fields to be present.
    if (!ipi.mayHaveIndirectParamsInExternalCalls && !ipi.mayHaveIndirectParamsInExternalDelCalls) {
      for (String indirectParamName : ipi.indirectParamTypes.keySet()) {
        if (paramNames.contains(indirectParamName)) {
          continue;
        }
        Collection<SoyType> paramTypes = ipi.indirectParamTypes.get(indirectParamName);
        SoyType combinedType = SoyTypes.computeLowestCommonType(typeRegistry, paramTypes);
        // Note that Union folds duplicate types and flattens unions, so if
        // the combinedType is already a union this will do the right thing.
        // TODO: detect cases where nullable is not needed (requires flow
        // analysis to determine if the template is always called.)
        SoyType indirectParamType =
            typeRegistry.getOrCreateUnionType(combinedType, NullType.getInstance());
        JsType jsType = getJsTypeForParamForDeclaration(indirectParamType);
        // NOTE: we do not add goog.requires for indirect types.  This is because it might introduce
        // strict deps errors.  This should be fine though since the transitive soy template that
        // actually has the param will add them.
        record.put(indirectParamName, jsType.typeExprForRecordMember(/* isOptional= */ true));
      }
    }
    StringBuilder sb = new StringBuilder();
    sb.append("{\n *  ");
    Joiner.on(",\n *  ").withKeyValueSeparator(": ").appendTo(sb, record);
    // trailing comma in record is important in case the last record member is the
    // unknown type
    sb.append(",\n * }");
    return sb.toString();
  }
507766
def set_c_prototype(self, c_decl):
        

        parsed = parse_file(c_decl)
        parsed_decl = parsed[0]
        if not parsed_decl:
            raise ValueError('Cannot parse the function prototype.')
        func_name, func_proto = next(iter(parsed_decl.items()))

        self.set_prototype(func_name, func_proto)

        return func_name, func_proto
666755
function (newPrototype, memberName, value) {
            if (typeof value === "function") {
                this._addMethodToPrototype(newPrototype, memberName, value);
            } else {
                newPrototype[memberName] = value;
            }
        }
484812
protected JvmTypeReference inferFunctionReturnType(XtendFunction source, JvmOperation target, JvmOperation overriddenOperation) {
		// The return type is explicitly given
		if (source.getReturnType() != null) {
			return ensureValidType(source.eResource(), source.getReturnType());
		}

		// An super operation was detected => reuse its return type.
		if (overriddenOperation != null) {
			final JvmTypeReference type = overriddenOperation.getReturnType();
			//return cloneWithProxiesFromOtherResource(type, target);
			return this.typeReferences.createDelegateTypeReference(type);
		}

		// Return type is inferred from the operation's expression.
		final XExpression expression = source.getExpression();
		JvmTypeReference returnType = null;
		if (expression != null
				&& ((!(expression instanceof XBlockExpression))
						|| (!((XBlockExpression) expression).getExpressions().isEmpty()))) {
			returnType = inferFunctionReturnType(expression);
		}
		return ensureValidType(source.eResource(), returnType);
	}
204188
function findType (node, typeInfo, nestedCall) {
  typeInfo = typeInfo || { noNull: false, isArray: false, noNullArrayValues: false }
  if (!node) {
    return typeInfo
  }

  // Validate nested call, the parser will check first if the array can be null
  // then it will check if the values inside can be null
  if (!nestedCall && node.kind === 'NonNullType') {
    typeInfo.noNull = true
  }

  // If it is an array, validate if the values inside can be null
  if (nestedCall && typeInfo.isArray && node.kind === 'NonNullType') {
    typeInfo.noNullArrayValues = true
  }

  if (node.kind === 'ListType') {
    typeInfo.isArray = true
  }

  if (node.name) {
    typeInfo.type = node.name.value
  }

  return findType(node.type, typeInfo, true)
}
490435
def enable_fundamental_type_wrappers(self):
        
        # 2015-01 reactivating header templates
        #log.warning('enable_fundamental_type_wrappers deprecated - replaced by generate_headers')
        # return # FIXME ignore
        self.enable_fundamental_type_wrappers = lambda: True
        import pkgutil
        headers = pkgutil.get_data(
            'ctypeslib',
            'data/fundamental_type_name.tpl').decode()
        from clang.cindex import TypeKind
        size = str(self.parser.get_ctypes_size(TypeKind.LONGDOUBLE) // 8)
        headers = headers.replace('__LONG_DOUBLE_SIZE__', size)
        print(headers, file=self.imports)
        return
61849
def infer_typing_typevar_or_newtype(node, context=None):
    """"""
    try:
        func = next(node.func.infer(context=context))
    except InferenceError as exc:
        raise UseInferenceDefault from exc

    if func.qname() not in TYPING_TYPEVARS_QUALIFIED:
        raise UseInferenceDefault
    if not node.args:
        raise UseInferenceDefault

    typename = node.args[0].as_string().strip("'")
    node = extract_node(TYPING_TYPE_TEMPLATE.format(typename))
    return node.infer(context=context)
734029
def change_return_type(f):
    
    @wraps(f)
    def wrapper(*args, **kwargs):
        if kwargs.has_key('return_type'):
            return_type = kwargs['return_type']
            kwargs.pop('return_type')
            return return_type(f(*args, **kwargs))
        elif len(args) > 0:
            return_type = type(args[0])
            return return_type(f(*args, **kwargs))
        else:
            return f(*args, **kwargs)
    return wrapper
871353
public boolean hasParameterizedArguments()
    {
        for (ParameterDeclaration paramDecl : _methodDecl.getParameters())
        {
            TypeMirror paramType = paramDecl.getType();
            if (paramType instanceof ReferenceType || paramType instanceof WildcardType)
                return true;
        }
        return false;
    }
596919
private function initType()
    {
        if ($this->getCallable() instanceof \Closure) {
            $this->setType(self::CLOSURE_TYPE);

        } else {
            $callable = $this->explodeCallable();
            if (count($callable) === 1) {
                if (is_object($callable[0])) {
                    $this->setType(self::INVOKED_OBJECT_TYPE);

                } else {
                    $this->setType(self::FUNCTION_TYPE);
                }

            } elseif (count($callable) === 2) {
                if (is_object($callable[0])) {
                    $this->setType(self::INSTANCE_METHOD_TYPE);

                } else {
                    $this->setType(self::STATIC_METHOD_TYPE);
                }

            } else {
                $this->setType(self::ERROR_TYPE);
                throw new \LogicException('Type not found for callable');
            }
        }
    }
1329764
FunctionTypeBuilder inferTemplateTypeName(@Nullable JSDocInfo info, @Nullable JSType ownerType) {
    // NOTE: these template type names may override a list
    // of inherited ones from an overridden function.

    if (info != null && !maybeUseNativeClassTemplateNames(info)) {
      ImmutableList<TemplateType> templates =
          buildTemplateTypesFromJSDocInfo(info, !(isConstructor || isInterface));
      if (!templates.isEmpty()) {
        this.templateTypeNames = templates;
      }
    }

    ImmutableList<TemplateType> ownerTypeKeys =
        ownerType != null ? ownerType.getTemplateTypeMap().getTemplateKeys() : ImmutableList.of();

    if (!templateTypeNames.isEmpty() || !ownerTypeKeys.isEmpty()) {
      // TODO(sdh): The order of these should be switched to avoid class templates shadowing
      // method templates, but this currently loosens type checking of arrays more than we'd like.
      // See http://github.com/google/closure-compiler/issues/2973
      registerTemplates(
          Iterables.concat(templateTypeNames, ownerTypeKeys), contents.getSourceNode());
    }

    return this;
  }
117186
public void setDeclType(int declType) {
        if (!(declType == Token.FUNCTION
              || declType == Token.LP
              || declType == Token.VAR
              || declType == Token.LET
              || declType == Token.CONST))
            throw new IllegalArgumentException("Invalid declType: " + declType);
        this.declType = declType;
    }