Search in sources :

Example 1 with Types

use of com.sun.tools.javac.code.Types in project bazel by bazelbuild.

the class InternalUtils method leastUpperBound.

/**
     * Returns the least upper bound of two {@link TypeMirror}s.
     *
     * @param processingEnv The {@link ProcessingEnvironment} to use.
     * @param tm1 A {@link TypeMirror}.
     * @param tm2 A {@link TypeMirror}.
     * @return The least upper bound of {@code tm1} and {@code tm2}.
     */
public static TypeMirror leastUpperBound(ProcessingEnvironment processingEnv, TypeMirror tm1, TypeMirror tm2) {
    Type t1 = (Type) tm1;
    Type t2 = (Type) tm2;
    JavacProcessingEnvironment javacEnv = (JavacProcessingEnvironment) processingEnv;
    Types types = Types.instance(javacEnv.getContext());
    if (types.isSameType(t1, t2)) {
        // Special case if the two types are equal.
        return t1;
    }
    // Handle the 'null' type manually (not done by types.lub).
    if (t1.getKind() == TypeKind.NULL) {
        return t2;
    }
    if (t2.getKind() == TypeKind.NULL) {
        return t1;
    }
    // Special case for primitives.
    if (TypesUtils.isPrimitive(t1) || TypesUtils.isPrimitive(t2)) {
        if (types.isAssignable(t1, t2)) {
            return t2;
        } else if (types.isAssignable(t2, t1)) {
            return t1;
        } else {
            return processingEnv.getTypeUtils().getNoType(TypeKind.NONE);
        }
    }
    if (t1.getKind() == TypeKind.WILDCARD) {
        WildcardType wc1 = (WildcardType) t1;
        Type bound = (Type) wc1.getExtendsBound();
        if (bound == null) {
            // Implicit upper bound of java.lang.Object
            Elements elements = processingEnv.getElementUtils();
            return elements.getTypeElement("java.lang.Object").asType();
        }
        t1 = bound;
    }
    if (t2.getKind() == TypeKind.WILDCARD) {
        WildcardType wc2 = (WildcardType) t2;
        Type bound = (Type) wc2.getExtendsBound();
        if (bound == null) {
            // Implicit upper bound of java.lang.Object
            Elements elements = processingEnv.getElementUtils();
            return elements.getTypeElement("java.lang.Object").asType();
        }
        t2 = bound;
    }
    return types.lub(t1, t2);
}
Also used : Types(com.sun.tools.javac.code.Types) JCAnnotatedType(com.sun.tools.javac.tree.JCTree.JCAnnotatedType) WildcardType(javax.lang.model.type.WildcardType) Type(com.sun.tools.javac.code.Type) WildcardType(javax.lang.model.type.WildcardType) JavacProcessingEnvironment(com.sun.tools.javac.processing.JavacProcessingEnvironment) Elements(javax.lang.model.util.Elements)

Example 2 with Types

use of com.sun.tools.javac.code.Types in project lombok by rzwitserloot.

the class HandleDelegate method createDelegateMethod.

public JCMethodDecl createDelegateMethod(MethodSig sig, JavacNode annotation, Name delegateName, DelegateReceiver delegateReceiver) throws TypeNotConvertibleException, CantMakeDelegates {
    /* public <T, U, ...> ReturnType methodName(ParamType1 name1, ParamType2 name2, ...) throws T1, T2, ... {
		 *      (return) delegate.<T, U>methodName(name1, name2);
		 *  }
		 */
    checkConflictOfTypeVarNames(sig, annotation);
    JavacTreeMaker maker = annotation.getTreeMaker();
    com.sun.tools.javac.util.List<JCAnnotation> annotations;
    if (sig.isDeprecated) {
        annotations = com.sun.tools.javac.util.List.of(maker.Annotation(genJavaLangTypeRef(annotation, "Deprecated"), com.sun.tools.javac.util.List.<JCExpression>nil()));
    } else {
        annotations = com.sun.tools.javac.util.List.nil();
    }
    JCModifiers mods = maker.Modifiers(PUBLIC, annotations);
    JCExpression returnType = JavacResolution.typeToJCTree((Type) sig.type.getReturnType(), annotation.getAst(), true);
    boolean useReturn = sig.type.getReturnType().getKind() != TypeKind.VOID;
    ListBuffer<JCVariableDecl> params = sig.type.getParameterTypes().isEmpty() ? null : new ListBuffer<JCVariableDecl>();
    ListBuffer<JCExpression> args = sig.type.getParameterTypes().isEmpty() ? null : new ListBuffer<JCExpression>();
    ListBuffer<JCExpression> thrown = sig.type.getThrownTypes().isEmpty() ? null : new ListBuffer<JCExpression>();
    ListBuffer<JCTypeParameter> typeParams = sig.type.getTypeVariables().isEmpty() ? null : new ListBuffer<JCTypeParameter>();
    ListBuffer<JCExpression> typeArgs = sig.type.getTypeVariables().isEmpty() ? null : new ListBuffer<JCExpression>();
    Types types = Types.instance(annotation.getContext());
    for (TypeMirror param : sig.type.getTypeVariables()) {
        Name name = ((TypeVar) param).tsym.name;
        ListBuffer<JCExpression> bounds = new ListBuffer<JCExpression>();
        for (Type type : types.getBounds((TypeVar) param)) {
            bounds.append(JavacResolution.typeToJCTree(type, annotation.getAst(), true));
        }
        typeParams.append(maker.TypeParameter(name, bounds.toList()));
        typeArgs.append(maker.Ident(name));
    }
    for (TypeMirror ex : sig.type.getThrownTypes()) {
        thrown.append(JavacResolution.typeToJCTree((Type) ex, annotation.getAst(), true));
    }
    int idx = 0;
    String[] paramNames = sig.getParameterNames();
    boolean varargs = sig.elem.isVarArgs();
    for (TypeMirror param : sig.type.getParameterTypes()) {
        long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, annotation.getContext());
        JCModifiers paramMods = maker.Modifiers(flags);
        Name name = annotation.toName(paramNames[idx++]);
        if (varargs && idx == paramNames.length) {
            paramMods.flags |= VARARGS;
        }
        params.append(maker.VarDef(paramMods, name, JavacResolution.typeToJCTree((Type) param, annotation.getAst(), true), null));
        args.append(maker.Ident(name));
    }
    JCExpression delegateCall = maker.Apply(toList(typeArgs), maker.Select(delegateReceiver.get(annotation, delegateName), sig.name), toList(args));
    JCStatement body = useReturn ? maker.Return(delegateCall) : maker.Exec(delegateCall);
    JCBlock bodyBlock = maker.Block(0, com.sun.tools.javac.util.List.of(body));
    return recursiveSetGeneratedBy(maker.MethodDef(mods, sig.name, returnType, toList(typeParams), toList(params), toList(thrown), bodyBlock, null), annotation.get(), annotation.getContext());
}
Also used : JavacTypes(com.sun.tools.javac.model.JavacTypes) Types(com.sun.tools.javac.code.Types) ListBuffer(com.sun.tools.javac.util.ListBuffer) JCStatement(com.sun.tools.javac.tree.JCTree.JCStatement) Name(com.sun.tools.javac.util.Name) TypeMirror(javax.lang.model.type.TypeMirror) JCAnnotation(com.sun.tools.javac.tree.JCTree.JCAnnotation) JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) JavacTreeMaker(lombok.javac.JavacTreeMaker) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) JCTypeParameter(com.sun.tools.javac.tree.JCTree.JCTypeParameter) ClassType(com.sun.tools.javac.code.Type.ClassType) Type(com.sun.tools.javac.code.Type) ExecutableType(javax.lang.model.type.ExecutableType) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) JCModifiers(com.sun.tools.javac.tree.JCTree.JCModifiers)

Example 3 with Types

use of com.sun.tools.javac.code.Types in project error-prone by google.

the class TryFailThrowable method hasInitialStringParameter.

private static boolean hasInitialStringParameter(MethodSymbol sym, VisitorState state) {
    Types types = state.getTypes();
    List<VarSymbol> parameters = sym.getParameters();
    return !parameters.isEmpty() && types.isSameType(parameters.get(0).type, state.getSymtab().stringType);
}
Also used : Types(com.sun.tools.javac.code.Types) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol)

Example 4 with Types

use of com.sun.tools.javac.code.Types in project error-prone by google.

the class IndexOfChar method matchMethodInvocation.

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
    if (!MATCHER.matches(tree, state)) {
        return NO_MATCH;
    }
    List<? extends ExpressionTree> arguments = tree.getArguments();
    Symtab syms = state.getSymtab();
    Types types = state.getTypes();
    if (types.isSameType(types.unboxedTypeOrType(getType(arguments.get(0))), syms.intType) && types.isSameType(types.unboxedTypeOrType(getType(arguments.get(1))), syms.charType)) {
        return describeMatch(tree, SuggestedFix.builder().replace(arguments.get(0), state.getSourceForNode(arguments.get(1))).replace(arguments.get(1), state.getSourceForNode(arguments.get(0))).build());
    }
    return NO_MATCH;
}
Also used : Symtab(com.sun.tools.javac.code.Symtab) Types(com.sun.tools.javac.code.Types)

Example 5 with Types

use of com.sun.tools.javac.code.Types in project error-prone by google.

the class AmbiguousMethodReference method matchClass.

@Override
public Description matchClass(ClassTree tree, VisitorState state) {
    ClassSymbol origin = getSymbol(tree);
    Types types = state.getTypes();
    Iterable<Symbol> members = types.membersClosure(getType(tree), /*skipInterface=*/
    false).getSymbols();
    // collect declared and inherited methods, grouped by reference descriptor
    Map<String, List<MethodSymbol>> methods = stream(members.spliterator(), false).filter(MethodSymbol.class::isInstance).map(MethodSymbol.class::cast).filter(m -> m.isConstructor() || m.owner.equals(origin)).collect(groupingBy(m -> methodReferenceDescriptor(types, m), toCollection(ArrayList::new)));
    // look for groups of ambiguous method references
    for (Tree member : tree.getMembers()) {
        if (!(member instanceof MethodTree)) {
            continue;
        }
        MethodSymbol msym = getSymbol((MethodTree) member);
        if (isSuppressed(msym)) {
            continue;
        }
        List<MethodSymbol> clash = methods.remove(methodReferenceDescriptor(types, msym));
        if (clash == null) {
            continue;
        }
        clash.remove(msym);
        // ignore overridden inherited methods and hidden interface methods
        clash.removeIf(m -> types.isSubSignature(msym.type, m.type));
        if (clash.isEmpty()) {
            continue;
        }
        String message = String.format("This method's reference is ambiguous, its name and functional interface type" + " are the same as: %s", clash.stream().map(m -> Signatures.prettyMethodSignature(origin, m)).collect(joining(", ")));
        state.reportMatch(buildDescription(member).setMessage(message).build());
    }
    return NO_MATCH;
}
Also used : MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) ClassTreeMatcher(com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher) MethodTree(com.sun.source.tree.MethodTree) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) ASTHelpers.getSymbol(com.google.errorprone.util.ASTHelpers.getSymbol) Symbol(com.sun.tools.javac.code.Symbol) NO_MATCH(com.google.errorprone.matchers.Description.NO_MATCH) ASTHelpers.getType(com.google.errorprone.util.ASTHelpers.getType) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) Collectors.joining(java.util.stream.Collectors.joining) ArrayList(java.util.ArrayList) Collectors.toCollection(java.util.stream.Collectors.toCollection) VisitorState(com.google.errorprone.VisitorState) List(java.util.List) Types(com.sun.tools.javac.code.Types) StreamSupport.stream(java.util.stream.StreamSupport.stream) Signatures(com.google.errorprone.util.Signatures) Description(com.google.errorprone.matchers.Description) Map(java.util.Map) BugPattern(com.google.errorprone.BugPattern) WARNING(com.google.errorprone.BugPattern.SeverityLevel.WARNING) JDK(com.google.errorprone.BugPattern.Category.JDK) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) Types(com.sun.tools.javac.code.Types) MethodTree(com.sun.source.tree.MethodTree) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) ASTHelpers.getSymbol(com.google.errorprone.util.ASTHelpers.getSymbol) Symbol(com.sun.tools.javac.code.Symbol) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) ArrayList(java.util.ArrayList) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) MethodTree(com.sun.source.tree.MethodTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

Types (com.sun.tools.javac.code.Types)39 Type (com.sun.tools.javac.code.Type)29 MethodSymbol (com.sun.tools.javac.code.Symbol.MethodSymbol)10 Tree (com.sun.source.tree.Tree)9 Symbol (com.sun.tools.javac.code.Symbol)9 VisitorState (com.google.errorprone.VisitorState)8 ASTHelpers.getType (com.google.errorprone.util.ASTHelpers.getType)7 ExpressionTree (com.sun.source.tree.ExpressionTree)6 Symtab (com.sun.tools.javac.code.Symtab)6 SuggestedFix (com.google.errorprone.fixes.SuggestedFix)5 Description (com.google.errorprone.matchers.Description)5 ClassTree (com.sun.source.tree.ClassTree)5 MethodTree (com.sun.source.tree.MethodTree)5 ClassSymbol (com.sun.tools.javac.code.Symbol.ClassSymbol)5 VarSymbol (com.sun.tools.javac.code.Symbol.VarSymbol)5 JavacProcessingEnvironment (com.sun.tools.javac.processing.JavacProcessingEnvironment)5 ArrayList (java.util.ArrayList)5 ConditionalExpressionTree (com.sun.source.tree.ConditionalExpressionTree)4 List (java.util.List)4 BugPattern (com.google.errorprone.BugPattern)3