Search in sources :

Example 96 with TypeMirror

use of javax.lang.model.type.TypeMirror in project checker-framework by typetools.

the class Resolver method findMethod.

/**
 * Finds the method element for a given name and list of expected parameter types.
 *
 * <p>The method adheres to all the rules of Java's scoping (while also considering the imports)
 * for name resolution.
 *
 * @param methodName name of the method to find
 * @param receiverType type of the receiver of the method
 * @param path tree path
 * @return the method element (if found)
 */
public Element findMethod(String methodName, TypeMirror receiverType, TreePath path, java.util.List<TypeMirror> argumentTypes) {
    Log.DiagnosticHandler discardDiagnosticHandler = new Log.DiscardDiagnosticHandler(log);
    try {
        Env<AttrContext> env = getEnvForPath(path);
        Type site = (Type) receiverType;
        Name name = names.fromString(methodName);
        List<Type> argtypes = List.nil();
        for (TypeMirror a : argumentTypes) {
            argtypes = argtypes.append((Type) a);
        }
        List<Type> typeargtypes = List.nil();
        boolean allowBoxing = true;
        boolean useVarargs = false;
        boolean operator = true;
        try {
            // For some reason we have to set our own method context, which is rather ugly.
            // TODO: find a nicer way to do this.
            Object methodContext = buildMethodContext();
            Object oldContext = getField(resolve, "currentResolutionContext");
            setField(resolve, "currentResolutionContext", methodContext);
            Element result = wrapInvocationOnResolveInstance(FIND_METHOD, env, site, name, argtypes, typeargtypes, allowBoxing, useVarargs, operator);
            setField(resolve, "currentResolutionContext", oldContext);
            return result;
        } catch (Throwable t) {
            Error err = new AssertionError("Unexpected Reflection error");
            err.initCause(t);
            throw err;
        }
    } finally {
        log.popDiagnosticHandler(discardDiagnosticHandler);
    }
}
Also used : Log(com.sun.tools.javac.util.Log) VariableElement(javax.lang.model.element.VariableElement) Element(javax.lang.model.element.Element) AttrContext(com.sun.tools.javac.comp.AttrContext) Name(com.sun.tools.javac.util.Name) Type(com.sun.tools.javac.code.Type) TypeMirror(javax.lang.model.type.TypeMirror)

Example 97 with TypeMirror

use of javax.lang.model.type.TypeMirror in project checker-framework by typetools.

the class TreeBuilder method buildIteratorMethodAccess.

/**
 * Builds an AST Tree to access the iterator() method of some iterable expression.
 *
 * @param iterableExpr an expression whose type is a subtype of Iterable
 * @return a MemberSelectTree that accesses the iterator() method of the expression
 */
public MemberSelectTree buildIteratorMethodAccess(ExpressionTree iterableExpr) {
    DeclaredType exprType = (DeclaredType) TypesUtils.upperBound(TreeUtils.typeOf(iterableExpr));
    assert exprType != null : "expression must be of declared type Iterable<>";
    TypeElement exprElement = (TypeElement) exprType.asElement();
    // Find the iterator() method of the iterable type
    Symbol.MethodSymbol iteratorMethod = null;
    for (ExecutableElement method : ElementFilter.methodsIn(elements.getAllMembers(exprElement))) {
        Name methodName = method.getSimpleName();
        if (method.getParameters().size() == 0) {
            if (methodName.contentEquals("iterator")) {
                iteratorMethod = (Symbol.MethodSymbol) method;
            }
        }
    }
    assert iteratorMethod != null : "no iterator method declared for expression type";
    Type.MethodType methodType = (Type.MethodType) iteratorMethod.asType();
    Symbol.TypeSymbol methodClass = methodType.asElement();
    DeclaredType iteratorType = (DeclaredType) methodType.getReturnType();
    iteratorType = (DeclaredType) javacTypes.asSuper((Type) iteratorType, symtab.iteratorType.asElement());
    assert iteratorType.getTypeArguments().size() == 1 : "expected exactly one type argument for Iterator";
    TypeMirror elementType = iteratorType.getTypeArguments().get(0);
    // Remove captured type from a wildcard.
    if (elementType instanceof Type.CapturedType) {
        elementType = ((Type.CapturedType) elementType).wildcard;
        iteratorType = modelTypes.getDeclaredType((TypeElement) modelTypes.asElement(iteratorType), elementType);
    }
    // Replace the iterator method's generic return type with
    // the actual element type of the expression.
    Type.MethodType updatedMethodType = new Type.MethodType(com.sun.tools.javac.util.List.nil(), (Type) iteratorType, com.sun.tools.javac.util.List.nil(), methodClass);
    JCTree.JCFieldAccess iteratorAccess = (JCTree.JCFieldAccess) maker.Select((JCTree.JCExpression) iterableExpr, iteratorMethod);
    iteratorAccess.setType(updatedMethodType);
    return iteratorAccess;
}
Also used : TypeElement(javax.lang.model.element.TypeElement) Symbol(com.sun.tools.javac.code.Symbol) ExecutableElement(javax.lang.model.element.ExecutableElement) JCTree(com.sun.tools.javac.tree.JCTree) Name(javax.lang.model.element.Name) DeclaredType(javax.lang.model.type.DeclaredType) ArrayType(javax.lang.model.type.ArrayType) Type(com.sun.tools.javac.code.Type) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) TypeMirror(javax.lang.model.type.TypeMirror) DeclaredType(javax.lang.model.type.DeclaredType)

Example 98 with TypeMirror

use of javax.lang.model.type.TypeMirror in project checker-framework by typetools.

the class TreeBuilder method getValueOfMethod.

/**
 * Returns the valueOf method of a boxed type such as Short or Float.
 */
public static Symbol.MethodSymbol getValueOfMethod(ProcessingEnvironment env, TypeMirror boxedType) {
    Symbol.MethodSymbol valueOfMethod = null;
    TypeMirror unboxedType = env.getTypeUtils().unboxedType(boxedType);
    TypeElement boxedElement = (TypeElement) ((DeclaredType) boxedType).asElement();
    for (ExecutableElement method : ElementFilter.methodsIn(env.getElementUtils().getAllMembers(boxedElement))) {
        Name methodName = method.getSimpleName();
        if (methodName.contentEquals("valueOf")) {
            List<? extends VariableElement> params = method.getParameters();
            if (params.size() == 1 && env.getTypeUtils().isSameType(params.get(0).asType(), unboxedType)) {
                valueOfMethod = (Symbol.MethodSymbol) method;
            }
        }
    }
    assert valueOfMethod != null : "no valueOf method declared for boxed type";
    return valueOfMethod;
}
Also used : TypeMirror(javax.lang.model.type.TypeMirror) Symbol(com.sun.tools.javac.code.Symbol) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Name(javax.lang.model.element.Name)

Example 99 with TypeMirror

use of javax.lang.model.type.TypeMirror in project checker-framework by typetools.

the class AnnotationBuilderTest method testClassPositive.

@Test
public void testClassPositive() {
    AnnotationBuilder builder = new AnnotationBuilder(env, ClassElt.class);
    builder.setValue("value", String.class);
    builder.setValue("value", int.class);
    builder.setValue("value", int[].class);
    builder.setValue("value", void.class);
    Object storedValue = builder.build().getElementValues().values().iterator().next().getValue();
    assertTrue("storedValue is " + storedValue.getClass(), storedValue instanceof TypeMirror);
}
Also used : AnnotationBuilder(org.checkerframework.javacutil.AnnotationBuilder) TypeMirror(javax.lang.model.type.TypeMirror) Test(org.junit.Test)

Example 100 with TypeMirror

use of javax.lang.model.type.TypeMirror in project kie-wb-common by kiegroup.

the class GeneratorUtils method getAnnotatedMethods.

public static List<ExecutableElement> getAnnotatedMethods(final TypeElement originalClassElement, final ProcessingEnvironment processingEnvironment, final String annotationName, final TypeMirror requiredReturnType, final String[] requiredParameterTypes) {
    final Types typeUtils = processingEnvironment.getTypeUtils();
    final Elements elementUtils = processingEnvironment.getElementUtils();
    TypeElement classElement = originalClassElement;
    while (true) {
        final List<ExecutableElement> methods = ElementFilter.methodsIn(classElement.getEnclosedElements());
        List<ExecutableElement> matches = new ArrayList<ExecutableElement>();
        for (ExecutableElement e : methods) {
            final TypeMirror actualReturnType = e.getReturnType();
            if (getAnnotation(elementUtils, e, annotationName) == null) {
                continue;
            }
            List<String> problems = new ArrayList<String>();
            if (!typeUtils.isAssignable(actualReturnType, requiredReturnType)) {
                problems.add("return " + requiredReturnType);
            }
            if (!doParametersMatch(typeUtils, elementUtils, e, requiredParameterTypes)) {
                if (requiredParameterTypes.length == 0) {
                    problems.add("take no parameters");
                } else {
                    StringBuilder sb = new StringBuilder();
                    sb.append("take ").append(requiredParameterTypes.length).append(" parameters of type (");
                    boolean first = true;
                    for (String p : requiredParameterTypes) {
                        if (!first) {
                            sb.append(", ");
                        }
                        sb.append(p);
                        first = false;
                    }
                    sb.append(")");
                    problems.add(sb.toString());
                }
            }
            if (e.getModifiers().contains(Modifier.STATIC)) {
                problems.add("be non-static");
            }
            if (e.getModifiers().contains(Modifier.PRIVATE)) {
                problems.add("be non-private");
            }
            if (problems.isEmpty()) {
                matches.add(e);
            } else {
                processingEnvironment.getMessager().printMessage(Diagnostic.Kind.ERROR, formatProblemsList(annotationName, problems), e);
            }
        }
        if (!matches.isEmpty()) {
            return matches;
        }
        TypeMirror superclass = classElement.getSuperclass();
        if (superclass instanceof DeclaredType) {
            classElement = (TypeElement) ((DeclaredType) superclass).asElement();
        } else {
            break;
        }
    }
    return Collections.emptyList();
}
Also used : Types(javax.lang.model.util.Types) TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ArrayList(java.util.ArrayList) Elements(javax.lang.model.util.Elements) DeclaredType(javax.lang.model.type.DeclaredType)

Aggregations

TypeMirror (javax.lang.model.type.TypeMirror)1086 TypeElement (javax.lang.model.element.TypeElement)419 ExecutableElement (javax.lang.model.element.ExecutableElement)259 VariableElement (javax.lang.model.element.VariableElement)237 Element (javax.lang.model.element.Element)196 DeclaredType (javax.lang.model.type.DeclaredType)177 ArrayList (java.util.ArrayList)154 Test (org.junit.Test)152 AnnotationMirror (javax.lang.model.element.AnnotationMirror)75 Types (javax.lang.model.util.Types)70 List (java.util.List)66 Elements (javax.lang.model.util.Elements)60 HashSet (java.util.HashSet)53 ArrayCodeTypeMirror (com.oracle.truffle.dsl.processor.java.model.CodeTypeMirror.ArrayCodeTypeMirror)50 Map (java.util.Map)49 ExecutableType (javax.lang.model.type.ExecutableType)45 MethodSpec (com.squareup.javapoet.MethodSpec)44 PackageElement (javax.lang.model.element.PackageElement)41 ArrayType (javax.lang.model.type.ArrayType)41 Expression (com.google.devtools.j2objc.ast.Expression)39