Compute a synthetic method type corresponding to the requested polymorphic
method signature. The target return type is computed from the immediately
enclosing scope surrounding the polymorphic-signature call.
487886
Type instantiatePolymorphicSignatureInstance(Env<AttrContext> env,
                                            MethodSymbol spMethod,  // sig. poly. method or null if none
                                            Resolve.MethodResolutionContext resolveContext,
                                            List<Type> argtypes) {
        final Type restype;

        //The return type for a polymorphic signature call is computed from
        //the enclosing tree E, as follows: if E is a cast, then use the
        //target type of the cast expression as a return type; if E is an
        //expression statement, the return type is 'void' - otherwise the
        //return type is simply 'Object'. A correctness check ensures that
        //env.next refers to the lexically enclosing environment in which
        //the polymorphic signature call environment is nested.

        switch (env.next.tree.getTag()) {
            case TYPECAST:
                JCTypeCast castTree = (JCTypeCast)env.next.tree;
                restype = (TreeInfo.skipParens(castTree.expr) == env.tree) ?
                    castTree.clazz.type :
                    syms.objectType;
                break;
            case EXEC:
                JCTree.JCExpressionStatement execTree =
                        (JCTree.JCExpressionStatement)env.next.tree;
                restype = (TreeInfo.skipParens(execTree.expr) == env.tree) ?
                    syms.voidType :
                    syms.objectType;
                break;
            default:
                restype = syms.objectType;
        }

        List<Type> paramtypes = Type.map(argtypes, new ImplicitArgType(spMethod, resolveContext.step));
        List<Type> exType = spMethod != null ?
            spMethod.getThrownTypes() :
            List.of(syms.throwableType); // make it throw all exceptions

        MethodType mtype = new MethodType(paramtypes,
                                          restype,
                                          exType,
                                          syms.methodClass);
        return mtype;
    }
472722
def _infer_type_new_call(self, caller, context):
        
        from astroid import node_classes

        # Verify the metaclass
        mcs = next(caller.args[0].infer(context=context))
        if mcs.__class__.__name__ != "ClassDef":
            # Not a valid first argument.
            return None
        if not mcs.is_subtype_of("%s.type" % BUILTINS):
            # Not a valid metaclass.
            return None

        # Verify the name
        name = next(caller.args[1].infer(context=context))
        if name.__class__.__name__ != "Const":
            # Not a valid name, needs to be a const.
            return None
        if not isinstance(name.value, str):
            # Needs to be a string.
            return None

        # Verify the bases
        bases = next(caller.args[2].infer(context=context))
        if bases.__class__.__name__ != "Tuple":
            # Needs to be a tuple.
            return None
        inferred_bases = [next(elt.infer(context=context)) for elt in bases.elts]
        if any(base.__class__.__name__ != "ClassDef" for base in inferred_bases):
            # All the bases needs to be Classes
            return None

        # Verify the attributes.
        attrs = next(caller.args[3].infer(context=context))
        if attrs.__class__.__name__ != "Dict":
            # Needs to be a dictionary.
            return None
        cls_locals = collections.defaultdict(list)
        for key, value in attrs.items:
            key = next(key.infer(context=context))
            value = next(value.infer(context=context))
            # Ignore non string keys
            if key.__class__.__name__ == "Const" and isinstance(key.value, str):
                cls_locals[key.value].append(value)

        # Build the class from now.
        cls = mcs.__class__(
            name=name.value,
            lineno=caller.lineno,
            col_offset=caller.col_offset,
            parent=caller,
        )
        empty = node_classes.Pass()
        cls.postinit(
            bases=bases.elts,
            body=[empty],
            decorators=[],
            newstyle=True,
            metaclass=mcs,
            keywords=[],
        )
        cls.locals = cls_locals
        return cls
1000297
private Scope findScopeForType(TypeElement type) {
    Scope scope = peekScope();
    while (scope != null) {
      if (scope.kind != ScopeKind.METHOD && type.equals(scope.type)) {
        return scope;
      }
      scope = scope.outer;
    }
    return null;
  }
1176037
def check_resolved_type(type, object, ctx = :__undefined__)
      if ctx == :__undefined__
        # Old method signature
        ctx = object
        object = type
        type = nil
      end

      if object.is_a?(GraphQL::Schema::Object)
        object = object.object
      end

      if type.respond_to?(:graphql_definition)
        type = type.graphql_definition
      end

      # Prefer a type-local function; fall back to the schema-level function
      type_proc = type && type.resolve_type_proc
      type_result = if type_proc
        type_proc.call(object, ctx)
      else
        yield(type, object, ctx)
      end

      if type_result.nil?
        nil
      else
        after_lazy(type_result) do |resolved_type_result|
          if resolved_type_result.respond_to?(:graphql_definition)
            resolved_type_result = resolved_type_result.graphql_definition
          end
          if !resolved_type_result.is_a?(GraphQL::BaseType)
            type_str = "#{resolved_type_result} (#{resolved_type_result.class.name})"
            raise "resolve_type(#{object}) returned #{type_str}, but it should return a GraphQL type"
          else
            resolved_type_result
          end
        end
      end
    end
1208487
void expectAbstractMethodsImplemented(Node n, FunctionType ctorType) {
    checkArgument(ctorType.isConstructor());

    Map<String, ObjectType> abstractMethodSuperTypeMap = new LinkedHashMap<>();
    FunctionType currSuperCtor = ctorType.getSuperClassConstructor();
    if (currSuperCtor == null || !currSuperCtor.isAbstract()) {
      return;
    }

    while (currSuperCtor != null && currSuperCtor.isAbstract()) {
      ObjectType superType = currSuperCtor.getInstanceType();
      for (String prop :
          currSuperCtor.getInstanceType().getImplicitPrototype().getOwnPropertyNames()) {
        FunctionType maybeAbstractMethod = superType.findPropertyType(prop).toMaybeFunctionType();
        if (maybeAbstractMethod != null
            && maybeAbstractMethod.isAbstract()
            && !abstractMethodSuperTypeMap.containsKey(prop)) {
          abstractMethodSuperTypeMap.put(prop, superType);
        }
      }
      currSuperCtor = currSuperCtor.getSuperClassConstructor();
    }

    ObjectType instance = ctorType.getInstanceType();
    for (Map.Entry<String, ObjectType> entry : abstractMethodSuperTypeMap.entrySet()) {
      String method = entry.getKey();
      ObjectType superType = entry.getValue();
      FunctionType abstractMethod = instance.findPropertyType(method).toMaybeFunctionType();
      if (abstractMethod == null || abstractMethod.isAbstract()) {
        String sourceName = n.getSourceFileName();
        sourceName = nullToEmpty(sourceName);
        registerMismatch(
            instance,
            superType,
            report(
                JSError.make(
                    n,
                    ABSTRACT_METHOD_NOT_IMPLEMENTED,
                    method,
                    superType.toString(),
                    instance.toString())));
      }
    }
  }
1160096
Type sigToType() {
        switch ((char) signature[sigp]) {
        case 'T':
            sigp++;
            int start = sigp;
            while (signature[sigp] != ';') sigp++;
            sigp++;
            return sigEnterPhase
                ? Type.noType
                : findTypeVar(names.fromUtf(signature, start, sigp - 1 - start));
        case '+': {
            sigp++;
            Type t = sigToType();
            return new WildcardType(t, BoundKind.EXTENDS, syms.boundClass);
        }
        case '*':
            sigp++;
            return new WildcardType(syms.objectType, BoundKind.UNBOUND,
                                    syms.boundClass);
        case '-': {
            sigp++;
            Type t = sigToType();
            return new WildcardType(t, BoundKind.SUPER, syms.boundClass);
        }
        case 'B':
            sigp++;
            return syms.byteType;
        case 'C':
            sigp++;
            return syms.charType;
        case 'D':
            sigp++;
            return syms.doubleType;
        case 'F':
            sigp++;
            return syms.floatType;
        case 'I':
            sigp++;
            return syms.intType;
        case 'J':
            sigp++;
            return syms.longType;
        case 'L':
            {
                // int oldsigp = sigp;
                Type t = classSigToType();
                if (sigp < siglimit && signature[sigp] == '.')
                    throw badClassFile("deprecated inner class signature syntax " +
                                       "(please recompile from source)");
                /*
                System.err.println(" decoded " +
                                   new String(signature, oldsigp, sigp-oldsigp) +
                                   " => " + t + " outer " + t.outer());
                */
                return t;
            }
        case 'S':
            sigp++;
            return syms.shortType;
        case 'V':
            sigp++;
            return syms.voidType;
        case 'Z':
            sigp++;
            return syms.booleanType;
        case '[':
            sigp++;
            return new ArrayType(sigToType(), syms.arrayClass);
        case '(':
            sigp++;
            List<Type> argtypes = sigToTypes(')');
            Type restype = sigToType();
            List<Type> thrown = List.nil();
            while (signature[sigp] == '^') {
                sigp++;
                thrown = thrown.prepend(sigToType());
            }
            // if there is a typevar in the throws clause we should state it.
            for (List<Type> l = thrown; l.nonEmpty(); l = l.tail) {
                if (l.head.hasTag(TYPEVAR)) {
                    l.head.tsym.flags_field |= THROWS;
                }
            }
            return new MethodType(argtypes,
                                  restype,
                                  thrown.reverse(),
                                  syms.methodClass);
        case '<':
            typevars = typevars.dup(currentOwner);
            Type poly = new ForAll(sigToTypeParams(), sigToType());
            typevars = typevars.leave();
            return poly;
        default:
            throw badClassFile("bad.signature",
                               Convert.utf2string(signature, sigp, 10));
        }
    }
643933
private MethodType callCheckMethod(
      Warner warner,
      Inliner inliner,
      Object resultInfo,
      List<Type> actualArgTypes,
      MethodSymbol methodSymbol,
      Type site,
      Env<AttrContext> env)
      throws InferException {
    try {
      Method checkMethod;
      checkMethod =
          Resolve.class.getDeclaredMethod(
              "checkMethod",
              Env.class,
              Type.class,
              Symbol.class,
              Class.forName(
                  "com.sun.tools.javac.comp.Attr$ResultInfo"), // ResultInfo is package-private
              List.class,
              List.class,
              Warner.class);
      checkMethod.setAccessible(true);
      return (MethodType)
          checkMethod.invoke(
              Resolve.instance(inliner.getContext()),
              env,
              site,
              methodSymbol,
              resultInfo,
              actualArgTypes,
              /*freeTypeVariables=*/ List.<Type>nil(),
              warner);
    } catch (InvocationTargetException e) {
      if (e.getCause() instanceof Resolve.InapplicableMethodException) {
        throw new InferException(
            ImmutableList.of(
                ((Resolve.InapplicableMethodException) e.getTargetException()).getDiagnostic()));
      }
      throw new LinkageError(e.getMessage(), e.getCause());
    } catch (ReflectiveOperationException e) {
      throw new LinkageError(e.getMessage(), e);
    }
  }
1117107
private static Type getAsynchronizedGenericType(Object targetObject) {
        if (targetObject instanceof java.util.Collection) {
            Class<? extends java.util.Collection> rawType = (Class<? extends Collection>) targetObject.getClass();
            Class<?> actualType = Object.class;
            if (((java.util.Collection<?>) targetObject).size() > 0) {
                Object element = ((java.util.Collection<?>) targetObject).iterator().next();
                actualType = element.getClass();
            }
            return new ParameterizedType() {
                private Type actualType, rawType;

                public ParameterizedType setTypes(Type actualType, Type rawType) {
                    this.actualType = actualType;
                    this.rawType = rawType;
                    return this;
                }

                @Override
                public Type[] getActualTypeArguments() {
                    return new Type[] { actualType };
                }

                @Override
                public Type getRawType() {
                    return rawType;
                }

                @Override
                public Type getOwnerType() {
                    return null;
                }
            }.setTypes(actualType, rawType);

        } else
            return targetObject.getClass();
    }
1171213
public static Type resolveGenericType(Type initialType, Class<?> targetType) {
        Class<?> rawType;
        if (initialType instanceof ParameterizedType)
            rawType = (Class<?>) ((ParameterizedType) initialType).getRawType();
        else
            rawType = (Class<?>) initialType;

        if (targetType.equals(rawType))
            return initialType;

        Type result;
        if (targetType.isInterface()) {
            for (Type superInterface : rawType.getGenericInterfaces())
                if (superInterface != null && !superInterface.equals(Object.class))
                    if ((result = resolveGenericType(superInterface, targetType)) != null)
                        return result;
        }

        Type superType = rawType.getGenericSuperclass();
        if (superType != null && !superType.equals(Object.class))
            if ((result = resolveGenericType(superType, targetType)) != null)
                return result;

        return null;
    }
636131
def type(self):
        
        # pylint: disable=no-member
        if self.args.args and self.args.args[0].name == "self":
            if isinstance(self.parent.scope(), ClassDef):
                return "method"
        return "function"
858803
private static Class<?> findTypeFromGenericInArguments(final InvocationOnMock invocation, final TypeVariable returnType) {
        final Type[] parameterTypes = invocation.getMethod().getGenericParameterTypes();
        for (int i = 0; i < parameterTypes.length; i++) {
            Type argType = parameterTypes[i];
            if (returnType.equals(argType)) {
                Object argument = invocation.getArgument(i);

                if (argument == null) {
                    return null;
                }

                return argument.getClass();
            }
            if (argType instanceof GenericArrayType) {
                argType = ((GenericArrayType) argType).getGenericComponentType();
                if (returnType.equals(argType)) {
                    return invocation.getArgument(i).getClass();
                }
            }
        }
        return null;
    }
1372064
public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope) : Type {
        $returnType = $methodReflection->getReturnType();
        $origReturnDescribe = $returnType->describe();
        $error = false;

        if ($returnType instanceof ObjectType) {
            if ($methodCall->var instanceof Variable) {
                $scopedType = $scope->getType($methodCall->var);
                if ($class = $this->findSubclass($scopedType, static::$className))
                    $returnType = new ObjectType($class.'DAO');
            } else $error = true(echoPre('(1) '.simpleClassName(static::$className).'->'.$methodCall->name.'() cannot resolve callee of instance method call: class($methodCall->var) = '.get_class($methodCall->var)));
        } else     $error = true(echoPre('(2) '.simpleClassName(static::$className).'->'.$methodCall->name.'() encountered unexpected return type: '.get_class($returnType).' => '.$returnType->describe()));

        $returnDescribe = $returnType->describe();

        if (0 || $error) echoPre('call of: '.simpleClassName(static::$className).'->'.$methodCall->name.'()  in: '.$this->getScopeDescription($scope).'  shall return: '.$returnDescribe.($returnDescribe==$origReturnDescribe ? ' (pass through)' : ' (was '.$origReturnDescribe.')'));
        return $returnType;
    }
1079668
function Return(type) {
    // 
    return function (target, propertyKey, descriptor) {
        if (!target.methodReturns) {
            target.methodReturns = {};
        }
        target.methodReturns[propertyKey] = type;
    };
}
1139011
Node createObjectDotAssignCall(Scope scope, JSType returnType, Node... args) {
    Node objAssign = createQName(scope, "Object.assign");
    Node result = createCall(objAssign, args);

    if (isAddingTypes()) {
      // Make a unique function type that returns the exact type we've inferred it to be.
      // Object.assign in the externs just returns !Object, which loses type information.
      JSType objAssignType =
          registry.createFunctionTypeWithVarArgs(
              returnType,
              registry.getNativeType(JSTypeNative.OBJECT_TYPE),
              registry.createUnionType(JSTypeNative.OBJECT_TYPE, JSTypeNative.NULL_TYPE));
      objAssign.setJSType(objAssignType);
      result.setJSType(returnType);
    }

    return result;
  }
1310955
function narrowType(type, expr, assumeTrue) {
                switch (expr.kind) {
                    case 69 /* Identifier */:
                    case 97 /* ThisKeyword */:
                    case 172 /* PropertyAccessExpression */:
                        return narrowTypeByTruthiness(type, expr, assumeTrue);
                    case 174 /* CallExpression */:
                        return narrowTypeByTypePredicate(type, expr, assumeTrue);
                    case 178 /* ParenthesizedExpression */:
                        return narrowType(type, expr.expression, assumeTrue);
                    case 187 /* BinaryExpression */:
                        return narrowTypeByBinaryExpression(type, expr, assumeTrue);
                    case 185 /* PrefixUnaryExpression */:
                        if (expr.operator === 49 /* ExclamationToken */) {
                            return narrowType(type, expr.operand, !assumeTrue);
                        }
                        break;
                }
                return type;
            }
182685
def bound_method(block)
      type = self.type
      arity = block.arity
      arity += 1 if arity >= 0 # Make sure the object gets passed
      arity += 1 if arity == 1 && type == :around # Make sure the block gets passed

      method = lambda { |object, *args| object.instance_exec(*args, &block) }


      # Proxy arity to the original block
      (
      class << method;
        self;
      end).class_eval do
        define_method(:arity) { arity }
      end

      method
    end
64894
private Type infer(
      Warner warner,
      Inliner inliner,
      List<Type> freeTypeVariables,
      List<Type> expectedArgTypes,
      Type returnType,
      List<Type> actualArgTypes)
      throws InferException {
    Symtab symtab = inliner.symtab();

    Type methodType =
        new MethodType(expectedArgTypes, returnType, List.<Type>nil(), symtab.methodClass);
    if (!freeTypeVariables.isEmpty()) {
      methodType = new ForAll(freeTypeVariables, methodType);
    }

    Enter enter = inliner.enter();
    MethodSymbol methodSymbol =
        new MethodSymbol(0, inliner.asName("__m__"), methodType, symtab.unknownSymbol);

    Type site = symtab.methodClass.type;

    Env<AttrContext> env =
        enter.getTopLevelEnv(TreeMaker.instance(inliner.getContext()).TopLevel(List.<JCTree>nil()));

    // Set up the resolution phase:
    try {
      Field field = AttrContext.class.getDeclaredField("pendingResolutionPhase");
      field.setAccessible(true);
      field.set(env.info, newMethodResolutionPhase(autoboxing()));
    } catch (ReflectiveOperationException e) {
      throw new LinkageError(e.getMessage(), e);
    }

    Object resultInfo;
    try {
      Class<?> resultInfoClass = Class.forName("com.sun.tools.javac.comp.Attr$ResultInfo");
      Constructor<?> resultInfoCtor =
          resultInfoClass.getDeclaredConstructor(Attr.class, KindSelector.class, Type.class);
      resultInfoCtor.setAccessible(true);
      resultInfo =
          resultInfoCtor.newInstance(
              Attr.instance(inliner.getContext()), KindSelector.PCK, Type.noType);
    } catch (ReflectiveOperationException e) {
      throw new LinkageError(e.getMessage(), e);
    }

    // Type inference sometimes produces diagnostics, so we need to catch them to avoid interfering
    // with the enclosing compilation.
    Log.DeferredDiagnosticHandler handler =
        new Log.DeferredDiagnosticHandler(Log.instance(inliner.getContext()));
    try {
      MethodType result =
          callCheckMethod(warner, inliner, resultInfo, actualArgTypes, methodSymbol, site, env);
      if (!handler.getDiagnostics().isEmpty()) {
        throw new InferException(handler.getDiagnostics());
      }
      return result;
    } finally {
      Log.instance(inliner.getContext()).popDiagnosticHandler(handler);
    }
  }