Static helper method that is used from within the super call in the constructor of
{@link RawResolvedFeatures}.
174249
private static LightweightTypeReference createTypeReference(JvmDeclaredType type, CommonTypeComputationServices services) {
		StandardTypeReferenceOwner owner = new StandardTypeReferenceOwner(services, type);
		return owner.newParameterizedTypeReference(type);
	}
1195884
public ImportDescr importStatement( PackageDescrBuilder pkg ) throws RecognitionException {
        ImportDescrBuilder imp = null;
        try {
            imp = helper.start( pkg,
                                ImportDescrBuilder.class,
                                null );

            // import
            match( input,
                   DRL5Lexer.ID,
                   DroolsSoftKeywords.IMPORT,
                   null,
                   DroolsEditorType.KEYWORD );
            if ( state.failed ) return null;

            String kwd;
            if ( helper.validateIdentifierKey( kwd = DroolsSoftKeywords.FUNCTION ) ||
                 helper.validateIdentifierKey( kwd = DroolsSoftKeywords.STATIC ) ) {
                // function
                match( input,
                       DRL5Lexer.ID,
                       kwd,
                       null,
                       DroolsEditorType.KEYWORD );
                if ( state.failed ) return null;
            }

            // qualifiedIdentifier
            String target = qualifiedIdentifier();
            if ( state.failed ) return null;

            if ( input.LA( 1 ) == DRL5Lexer.DOT && input.LA( 2 ) == DRL5Lexer.STAR ) {
                // .*
                match( input,
                       DRL5Lexer.DOT,
                       null,
                       null,
                       DroolsEditorType.IDENTIFIER );
                if ( state.failed ) return null;
                match( input,
                       DRL5Lexer.STAR,
                       null,
                       null,
                       DroolsEditorType.IDENTIFIER );
                if ( state.failed ) return null;
                target += ".*";
            }
            if ( state.backtracking == 0 ) imp.target( target );

        } catch ( RecognitionException re ) {
            reportError( re );
        } finally {
            helper.end( ImportDescrBuilder.class,
                        imp );
        }
        return (imp != null) ? imp.getDescr() : null;
    }
1055346
private ImmutableList<ObjectType> resolveTypeListHelper(
      ImmutableList<ObjectType> list, ErrorReporter reporter) {
    boolean changed = false;
    ImmutableList.Builder<ObjectType> resolvedList = ImmutableList.builder();
    for (ObjectType type : list) {
      JSType rt = type.resolve(reporter);
      if (!rt.isObjectType()) {
        reporter.warning(
            "not an object type: " + rt + " (at " + toString() + ")",
            source.getSourceFileName(),
            source.getLineno(),
            source.getCharno());
        continue;
      }
      ObjectType resolved = rt.toObjectType();
      resolvedList.add(resolved);
      changed |= (resolved != type);
    }
    return changed ? resolvedList.build() : null;
  }
75390
protected static Invocable resolveJavaField(
            Class<?> clas, String fieldName, boolean staticOnly )
            throws UtilEvalError {
        try {
            return resolveExpectedJavaField( clas, fieldName, staticOnly );
        } catch ( ReflectError e ) {
            return null;
        }
    }
1122921
public static Class<?> resolveCaller()
    {
        Class<?> callerClass = null;

        StackTraceElement[] stackTraces = Thread.currentThread().getStackTrace();
        int stackSize = stackTraces.length;

        // StackTrace is below. So check from 3rd element.
        // 1st:java.lang.Thread
        // 2nd:ResourceResolver#resolveCaller(this method)
        for (int stackIndex = 2; stackIndex < stackSize; stackIndex++)
        {
            StackTraceElement stackTrace = stackTraces[stackIndex];
            String callerClassName = stackTrace.getClassName();
            if (StringUtils.equals(ResourceResolver.class.getName(), callerClassName) == false)
            {
                try
                {
                    callerClass = Class.forName(callerClassName);
                    break;
                }
                catch (ClassNotFoundException ex)
                {
                    return null;
                }
            }
        }

        return callerClass;
    }
354869
public void resolveReferences() {
        // Resolve annotations to their definitions
        Map<String, AnnotationDefinition> defs = getDefinitionMap();
        final List<Annotation> annos = new ArrayList<Annotation>();

        // Get all the annotation used by the document's statement groups
        for (final StatementGroup sg : statementGroups) {
            annos.addAll(sg.getAllAnnotations());
        }

        // Resolve the references
        for (final Annotation a : annos) {
            AnnotationDefinition ad = a.getDefinition();
            // Skip annotations without definitions
            if (ad == null) {
                continue;
            }

            final String id = ad.getId();
            AnnotationDefinition documentDefinition = defs.get(id);

            // BEL document annotations must reference valid definitions...
            assert documentDefinition != null;
            // ... so sanity check that for now.

            // Resolve the reference to the instance
            a.setDefinition(documentDefinition);
        }

        // Resolve parameters to their namespaces
        Map<String, Namespace> nspcs = getNamespaceMap();
        final List<Parameter> params = new ArrayList<Parameter>();

        // Get all the parameters within the document
        for (final StatementGroup sg : statementGroups) {
            params.addAll(sg.getAllParameters());
        }

        // Get the default namespace if present
        final Namespace defaultNS = nspcs.get(DEFAULT_NAMESPACE_PREFIX);

        // Resolve the references
        for (final Parameter av : params) {
            Namespace ns = av.getNamespace();

            // Skip parameters without namespaces
            if (ns == null) {
                if (defaultNS != null) {
                    av.setNamespace(defaultNS);
                }
                continue;
            }

            final String prefix = ns.getPrefix();
            Namespace documentNamespace = nspcs.get(prefix);

            // BEL document parameters must reference valid namespaces...
            assert documentNamespace != null;
            // ... so sanity check that for now.

            // Resolve the reference to the instance
            av.setNamespace(documentNamespace);
        }
    }
1086058
@Override
    public ResourceReference parse(String rawReference)
    {
        ResourceReference parsedResourceReference = null;

        // Step 1: Find the type parser matching the specified prefix type (if any).
        int pos = rawReference.indexOf(TYPE_SEPARATOR);
        if (pos > -1) {
            String typePrefix = rawReference.substring(0, pos);
            String reference = rawReference.substring(pos + 1);

            ComponentManager componentManager = this.componentManagerProvider.get();
            if (componentManager.hasComponent(ResourceReferenceTypeParser.class, typePrefix)) {
                try {
                    ResourceReferenceTypeParser parser =
                        componentManager.getInstance(ResourceReferenceTypeParser.class, typePrefix);
                    parsedResourceReference = parser.parse(reference);
                } catch (ComponentLookupException e) {
                    this.logger.error("Failed to initialize resource type parser", e);
                }
            }
        }

        // Step 2: If there's no specific type parser found, then consider it's an Unknown type.
        if (parsedResourceReference == null) {
            parsedResourceReference = new ResourceReference(rawReference, ResourceType.UNKNOWN);
        }

        // Step 3: If we're not in wiki mode then wiki references are considered URLs.
        if (!isInWikiMode() && WIKI_REFERENCE_TYPES.contains(parsedResourceReference.getType())) {
            parsedResourceReference = new ResourceReference(rawReference, ResourceType.URL);
            parsedResourceReference.setTyped(false);
        }

        return parsedResourceReference;
    }
1181110
Type instantiateMethod( Env<AttrContext> env,
                            List<Type> tvars,
                            MethodType mt,
                            Attr.ResultInfo resultInfo,
                            MethodSymbol msym,
                            List<Type> argtypes,
                            boolean allowBoxing,
                            boolean useVarargs,
                            Resolve.MethodResolutionContext resolveContext,
                            Warner warn) throws InferenceException {
        //-System.err.println("instantiateMethod(" + tvars + ", " + mt + ", " + argtypes + ")"); //DEBUG
        final InferenceContext inferenceContext = new InferenceContext(this, tvars);  //B0
        inferenceException.clear();
        try {
            DeferredAttr.DeferredAttrContext deferredAttrContext =
                        resolveContext.deferredAttrContext(msym, inferenceContext, resultInfo, warn);

            resolveContext.methodCheck.argumentsAcceptable(env, deferredAttrContext,   //B2
                    argtypes, mt.getParameterTypes(), warn);

            if (allowGraphInference && resultInfo != null && resultInfo.pt == anyPoly) {
                doIncorporation(inferenceContext, warn);
                //we are inside method attribution - just return a partially inferred type
                return new PartiallyInferredMethodType(mt, inferenceContext, env, warn);
            } else if (allowGraphInference && resultInfo != null) {

                //inject return constraints earlier
                doIncorporation(inferenceContext, warn); //propagation

                if (!warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED)) {
                    boolean shouldPropagate = shouldPropagate(mt.getReturnType(), resultInfo, inferenceContext);

                    InferenceContext minContext = shouldPropagate ?
                            inferenceContext.min(roots(mt, deferredAttrContext), true, warn) :
                            inferenceContext;

                    Type newRestype = generateReturnConstraints(env.tree, resultInfo,  //B3
                            mt, minContext);
                    mt = (MethodType)types.createMethodTypeWithReturn(mt, newRestype);

                    //propagate outwards if needed
                    if (shouldPropagate) {
                        //propagate inference context outwards and exit
                        minContext.dupTo(resultInfo.checkContext.inferenceContext());
                        deferredAttrContext.complete();
                        return mt;
                    }
                }
            }

            deferredAttrContext.complete();

            // minimize as yet undetermined type variables
            if (allowGraphInference) {
                inferenceContext.solve(warn);
            } else {
                inferenceContext.solveLegacy(true, warn, LegacyInferenceSteps.EQ_LOWER.steps); //minimizeInst
            }

            mt = (MethodType)inferenceContext.asInstType(mt);

            if (!allowGraphInference &&
                    inferenceContext.restvars().nonEmpty() &&
                    resultInfo != null &&
                    !warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED)) {
                generateReturnConstraints(env.tree, resultInfo, mt, inferenceContext);
                inferenceContext.solveLegacy(false, warn, LegacyInferenceSteps.EQ_UPPER.steps); //maximizeInst
                mt = (MethodType)inferenceContext.asInstType(mt);
            }

            if (resultInfo != null && rs.verboseResolutionMode.contains(VerboseResolutionMode.DEFERRED_INST)) {
                log.note(env.tree.pos, "deferred.method.inst", msym, mt, resultInfo.pt);
            }

            // return instantiated version of method type
            return mt;
        } finally {
            if (resultInfo != null || !allowGraphInference) {
                inferenceContext.notifyChange();
            } else {
                inferenceContext.notifyChange(inferenceContext.boundedVars());
            }
            if (resultInfo == null) {
                /* if the is no result info then we can clear the capture types
                 * cache without affecting any result info check
                 */
                inferenceContext.captureTypeCache.clear();
            }
            dumpGraphsIfNeeded(env.tree, msym, resolveContext);
        }
    }
967902
public static ParameterizedType newParameterizedType(
      final Class<?> raw, Iterable<? extends Type> typeArgs) {
    TypeResolver resolver = new TypeResolver();
    final List<TypeVariable<?>> vars = new ArrayList<TypeVariable<?>>();
    for (Type arg : typeArgs) {
      TypeVariable<?> var = TypeVariableGenerator.freshTypeVariable("T" + vars.size());
      vars.add(var);
      resolver = resolver.where(var, arg);
    }
    checkArgument(raw.getTypeParameters().length == vars.size(),
        "%s expected %s type parameters, while %s are provied",
        raw, raw.getTypeParameters().length, typeArgs);
    return (ParameterizedType) resolver.resolveType(new ParameterizedType() {
      @Override public Class<?> getRawType() { return raw; }
      @Override public Type getOwnerType() { return null; }
      @Override public Type[] getActualTypeArguments() { return vars.toArray(new Type[0]); }
    });
  }
131815
private void addHandlerInitializerMethod(ClassFile proxyClassType, ClassMethod staticConstructor) throws Exception {
        ClassMethod classMethod = proxyClassType.addMethod(AccessFlag.PRIVATE, INIT_MH_METHOD_NAME, BytecodeUtils.VOID_CLASS_DESCRIPTOR, LJAVA_LANG_OBJECT);
        final CodeAttribute b = classMethod.getCodeAttribute();
        b.aload(0);
        StaticMethodInformation methodInfo = new StaticMethodInformation(INIT_MH_METHOD_NAME, new Class[] { Object.class }, void.class,
                classMethod.getClassFile().getName());
        invokeMethodHandler(classMethod, methodInfo, false, DEFAULT_METHOD_RESOLVER, staticConstructor);
        b.checkcast(MethodHandler.class);
        b.putfield(classMethod.getClassFile().getName(), METHOD_HANDLER_FIELD_NAME, DescriptorUtils.makeDescriptor(MethodHandler.class));
        b.returnInstruction();
        BeanLogger.LOG.createdMethodHandlerInitializerForDecoratorProxy(getBeanType());

    }
983041
void analyze(final MethodResult methodResult) {
        lock.lock();
        try {
            buildPackagePrefix(methodResult.getParentResource().getOriginalClass());

            final List<Instruction> visitedInstructions = interpretRelevantInstructions(methodResult.getInstructions());

            // find project defined methods in invoke occurrences
            final Set<ProjectMethod> projectMethods = findProjectMethods(visitedInstructions);

            // add project methods to global method pool
            projectMethods.forEach(MethodPool.getInstance()::addProjectMethod);

            Element returnedElement = new MethodSimulator().simulate(visitedInstructions);
            final String returnType = methodResult.getOriginalMethodSignature().getReturnType();

            // void resource methods are interpreted later; stop analyzing on error
            if (Types.PRIMITIVE_VOID.equals(returnType)) {
                return;
            }

            if (returnedElement == null) {
                // happens for abstract methods or if there is no return
                return;
            }

            final Set<Object> possibleObjects = returnedElement.getPossibleValues().stream().filter(o -> !(o instanceof HttpResponse))
                    .collect(Collectors.toSet());

            // for non-Response methods add a default if there are non-Response objects or none objects at all
            if (!Types.RESPONSE.equals(returnType)) {
                final HttpResponse defaultResponse = new HttpResponse();

                if (Types.OBJECT.equals(returnType))
                    defaultResponse.getEntityTypes().addAll(returnedElement.getTypes());
                else
                    defaultResponse.getEntityTypes().add(returnType);

                possibleObjects.stream().filter(o -> o instanceof JsonValue).map(o -> (JsonValue) o).forEach(defaultResponse.getInlineEntities()::add);

                defaultResponse.getContentTypes().addAll(methodResult.getResponseMediaTypes());

                methodResult.getResponses().add(defaultResponse);
            }

            // add Response results as well
            returnedElement.getPossibleValues().stream().filter(o -> o instanceof HttpResponse).map(o -> (HttpResponse) o).forEach(methodResult.getResponses()::add);
        } finally {
            lock.unlock();
        }
    }
387083
protected static void addFeatureThenClear(StringBuilder rawFeature, List<Integer> featureVector, FeatureMap featureMap)
    {
        int id = featureMap.idOf(rawFeature.toString());
        if (id != -1)
        {
            featureVector.add(id);
        }
        rawFeature.setLength(0);
    }
995174
public void buildReturnCode(MethodSpec.Builder methodBuilder, boolean updateMode, SQLiteModelMethod method, TypeName returnType) {
		if (returnType == TypeName.VOID) {

		} else if (isTypeIncludedIn(returnType, Boolean.TYPE, Boolean.class)) {
			methodBuilder.addJavadoc("\n");
			if (updateMode)
				methodBuilder.addJavadoc("@return <code>true</code> if record is updated, <code>false</code> otherwise");
			else
				methodBuilder.addJavadoc("@return <code>true</code> if record is deleted, <code>false</code> otherwise");
			methodBuilder.addJavadoc("\n");

			methodBuilder.addCode("return result!=0;\n");
		} else if (isTypeIncludedIn(returnType, Long.TYPE, Long.class, Integer.TYPE, Integer.class, Short.TYPE, Short.class)) {
			methodBuilder.addJavadoc("\n");
			if (updateMode) {
				methodBuilder.addJavadoc("@return number of updated records");
			} else {
				methodBuilder.addJavadoc("@return number of deleted records");
			}
			methodBuilder.addJavadoc("\n");

			methodBuilder.addCode("return result;\n");
		} else {
			// more than one listener found
			throw (new InvalidMethodSignException(method, "invalid return type"));
		}
	}
1142092
private void invokeFactoryMethod(MethodDefinition read, Map<Short, LocalVariableDefinition> structData, LocalVariableDefinition instance)
    {
        if (metadata.getBuilderMethod().isPresent()) {
            ThriftMethodInjection builderMethod = metadata.getBuilderMethod().get();
            read.loadVariable(instance);

            // push parameters on stack
            for (ThriftParameterInjection parameter : builderMethod.getParameters()) {
                read.loadVariable(structData.get(parameter.getId()));
            }

            // invoke the method
            read.invokeVirtual(builderMethod.getMethod())
                    .storeVariable(instance);
        }
    }
1288088
private void addReturnTypeNarrowingDeclarations(AbstractTypeDeclaration node) {
    TypeElement type = node.getTypeElement();

    // No need to run this if the entire class is dead.
    if (deadCodeMap != null && deadCodeMap.containsClass(type, elementUtil)) {
      return;
    }

    Map<String, ExecutablePair> newDeclarations = new HashMap<>();
    Map<String, TypeMirror> resolvedReturnTypes = new HashMap<>();
    for (DeclaredType inheritedType : typeUtil.getObjcOrderedInheritedTypes(type.asType())) {
      TypeElement inheritedElem = (TypeElement) inheritedType.asElement();
      for (ExecutableElement methodElem : ElementUtil.getMethods(inheritedElem)) {
        if (ElementUtil.isPrivate(methodElem)) {
          continue;
        }
        TypeMirror declaredReturnType = typeUtil.erasure(methodElem.getReturnType());
        if (!TypeUtil.isReferenceType(declaredReturnType)) {
          continue;  // Short circuit
        }
        String selector = nameTable.getMethodSelector(methodElem);
        ExecutableType methodType = typeUtil.asMemberOf(inheritedType, methodElem);
        TypeMirror returnType = typeUtil.erasure(methodType.getReturnType());
        TypeMirror resolvedReturnType = resolvedReturnTypes.get(selector);
        if (resolvedReturnType == null) {
          resolvedReturnType = declaredReturnType;
          resolvedReturnTypes.put(selector, resolvedReturnType);
        } else if (!typeUtil.isSubtype(returnType, resolvedReturnType)) {
          continue;
        }
        if (resolvedReturnType != returnType
            && !nameTable.getObjCType(resolvedReturnType).equals(
                nameTable.getObjCType(returnType))) {
          newDeclarations.put(selector, new ExecutablePair(methodElem, methodType));
          resolvedReturnTypes.put(selector, returnType);
        }
      }
    }

    for (Map.Entry<String, ExecutablePair> newDecl : newDeclarations.entrySet()) {
      if (deadCodeMap != null
          && deadCodeMap.containsMethod(newDecl.getValue().element(), typeUtil)) {
        continue;
      }
      node.addBodyDeclaration(newReturnTypeNarrowingDeclaration(
          newDecl.getKey(), newDecl.getValue(), type));
    }
  }
1016091
public static Class<?> resolveReturnType(Method method, Class clazz) {
		Preconditions.checkNotNull(method, "Method must not be null");
		Type genericType = method.getGenericReturnType();
		Preconditions.checkNotNull(clazz, "Class must not be null");
		Map<TypeVariable, Type> typeVariableMap = getTypeVariableMap(clazz);
		Type rawType = getRawType(genericType, typeVariableMap);
		return (rawType instanceof Class ? (Class) rawType : method.getReturnType());
	}
430585
void initResolve() {
        featureNamesToResolve = new HashSet<>();
        samplesToInstall = new ArrayList<>();
        resolvedFeatures = new HashMap<>();
        requestedFeatureNames = new HashSet<>();
        featuresMissing = new ArrayList<>();
        resourcesWrongProduct = new ArrayList<>();
        requirementsFoundForOtherProducts = new HashSet<>();
        missingTopLevelRequirements = new ArrayList<>();
        missingRequirements = new ArrayList<>();
        resolverRepository.clearPreferredVersions();
    }