Search in sources :

Example 86 with BugInCF

use of org.checkerframework.javacutil.BugInCF in project checker-framework by typetools.

the class DependentTypesHelper method atVariableDeclaration.

/**
 * Standardize the Java expressions in annotations in a variable declaration. Converts the
 * parameter syntax, e.g "#1", to the parameter name.
 *
 * @param type the type of the variable declaration; is side-effected by this method
 * @param declarationTree the variable declaration
 * @param variableElt the element of the variable declaration
 */
public void atVariableDeclaration(AnnotatedTypeMirror type, Tree declarationTree, VariableElement variableElt) {
    if (!hasDependentType(type)) {
        return;
    }
    TreePath pathToVariableDecl = factory.getPath(declarationTree);
    if (pathToVariableDecl == null) {
        // If this is a synthetic created by dataflow, the path will be null.
        return;
    }
    ElementKind variableKind = variableElt.getKind();
    if (ElementUtils.isBindingVariable(variableElt)) {
        // Treat binding variables the same as local variables.
        variableKind = ElementKind.LOCAL_VARIABLE;
    }
    switch(variableKind) {
        case PARAMETER:
            TreePath pathTillEnclTree = TreePathUtil.pathTillOfKind(pathToVariableDecl, METHOD_OR_LAMBDA);
            if (pathTillEnclTree == null) {
                throw new BugInCF("no enclosing method or lambda found for " + variableElt);
            }
            Tree enclTree = pathTillEnclTree.getLeaf();
            if (enclTree.getKind() == Tree.Kind.METHOD) {
                MethodTree methodDeclTree = (MethodTree) enclTree;
                StringToJavaExpression stringToJavaExpr = stringExpr -> StringToJavaExpression.atMethodBody(stringExpr, methodDeclTree, factory.getChecker());
                if (debugStringToJavaExpression) {
                    System.out.printf("atVariableDeclaration(%s, %s, %s) 1 created %s%n", type, TreeUtils.toStringTruncated(declarationTree, 65), variableElt, stringToJavaExpr);
                }
                convertAnnotatedTypeMirror(stringToJavaExpr, type);
            } else {
                // Lambdas can use local variables defined in the enclosing method, so allow
                // identifiers to be locals in scope at the location of the lambda.
                StringToJavaExpression stringToJavaExpr = stringExpr -> StringToJavaExpression.atLambdaParameter(stringExpr, (LambdaExpressionTree) enclTree, pathToVariableDecl.getParentPath(), factory.getChecker());
                if (debugStringToJavaExpression) {
                    System.out.printf("atVariableDeclaration(%s, %s, %s) 2 created %s%n", type, TreeUtils.toStringTruncated(declarationTree, 65), variableElt, stringToJavaExpr);
                }
                convertAnnotatedTypeMirror(stringToJavaExpr, type);
            }
            break;
        case LOCAL_VARIABLE:
        case RESOURCE_VARIABLE:
        case EXCEPTION_PARAMETER:
            StringToJavaExpression stringToJavaExprVar = stringExpr -> StringToJavaExpression.atPath(stringExpr, pathToVariableDecl, factory.getChecker());
            if (debugStringToJavaExpression) {
                System.out.printf("atVariableDeclaration(%s, %s, %s) 3 created %s%n", type, TreeUtils.toStringTruncated(declarationTree, 65), variableElt, stringToJavaExprVar);
            }
            convertAnnotatedTypeMirror(stringToJavaExprVar, type);
            break;
        case FIELD:
        case ENUM_CONSTANT:
            StringToJavaExpression stringToJavaExprField = stringExpr -> StringToJavaExpression.atFieldDecl(stringExpr, variableElt, factory.getChecker());
            if (debugStringToJavaExpression) {
                System.out.printf("atVariableDeclaration(%s, %s, %s) 4 created %s%n", type, TreeUtils.toStringTruncated(declarationTree, 65), variableElt, stringToJavaExprField);
            }
            convertAnnotatedTypeMirror(stringToJavaExprField, type);
            break;
        default:
            throw new BugInCF("unexpected element kind " + variableElt.getKind() + " for " + variableElt);
    }
}
Also used : ElementKind(javax.lang.model.element.ElementKind) BugInCF(org.checkerframework.javacutil.BugInCF) TypeElement(javax.lang.model.element.TypeElement) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) LambdaExpressionTree(com.sun.source.tree.LambdaExpressionTree) Map(java.util.Map) Method(java.lang.reflect.Method) EnumSet(java.util.EnumSet) AnnotatedExecutableType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType) TreePath(com.sun.source.util.TreePath) Set(java.util.Set) Element(javax.lang.model.element.Element) MemberSelectTree(com.sun.source.tree.MemberSelectTree) TreeUtils(org.checkerframework.javacutil.TreeUtils) AnnotatedTypeParameterBounds(org.checkerframework.framework.type.AnnotatedTypeParameterBounds) Unknown(org.checkerframework.dataflow.expression.Unknown) TypeKind(javax.lang.model.type.TypeKind) TreeAnnotator(org.checkerframework.framework.type.treeannotator.TreeAnnotator) List(java.util.List) LocalVariable(org.checkerframework.dataflow.expression.LocalVariable) AnnotatedDeclaredType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType) Annotation(java.lang.annotation.Annotation) ModifiersTree(com.sun.source.tree.ModifiersTree) TypesUtils(org.checkerframework.javacutil.TypesUtils) DoubleAnnotatedTypeScanner(org.checkerframework.framework.type.visitor.DoubleAnnotatedTypeScanner) AnnotatedTypeScanner(org.checkerframework.framework.type.visitor.AnnotatedTypeScanner) AnnotationTree(com.sun.source.tree.AnnotationTree) MethodTree(com.sun.source.tree.MethodTree) SourceChecker(org.checkerframework.framework.source.SourceChecker) VariableElement(javax.lang.model.element.VariableElement) VariableTree(com.sun.source.tree.VariableTree) HashMap(java.util.HashMap) Function(java.util.function.Function) ArrayList(java.util.ArrayList) NewClassTree(com.sun.source.tree.NewClassTree) TreePathUtil(org.checkerframework.javacutil.TreePathUtil) AnnotationBuilder(org.checkerframework.javacutil.AnnotationBuilder) Tree(com.sun.source.tree.Tree) AnnotationUtils(org.checkerframework.javacutil.AnnotationUtils) ClassTree(com.sun.source.tree.ClassTree) Nullable(org.checkerframework.checker.nullness.qual.Nullable) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) JavaExpressionParseException(org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException) ElementKind(javax.lang.model.element.ElementKind) ExpressionTree(com.sun.source.tree.ExpressionTree) ExecutableElement(javax.lang.model.element.ExecutableElement) JavaExpression(org.checkerframework.dataflow.expression.JavaExpression) JavaExpressionConverter(org.checkerframework.dataflow.expression.JavaExpressionConverter) JCTree(com.sun.tools.javac.tree.JCTree) AnnotationMirror(javax.lang.model.element.AnnotationMirror) SimpleAnnotatedTypeScanner(org.checkerframework.framework.type.visitor.SimpleAnnotatedTypeScanner) StringToJavaExpression(org.checkerframework.framework.util.StringToJavaExpression) AnnotatedTypeFactory(org.checkerframework.framework.type.AnnotatedTypeFactory) TypeMirror(javax.lang.model.type.TypeMirror) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) FormalParameter(org.checkerframework.dataflow.expression.FormalParameter) Collections(java.util.Collections) ElementUtils(org.checkerframework.javacutil.ElementUtils) CollectionsPlume(org.plumelib.util.CollectionsPlume) TreePath(com.sun.source.util.TreePath) MethodTree(com.sun.source.tree.MethodTree) StringToJavaExpression(org.checkerframework.framework.util.StringToJavaExpression) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) LambdaExpressionTree(com.sun.source.tree.LambdaExpressionTree) MemberSelectTree(com.sun.source.tree.MemberSelectTree) ModifiersTree(com.sun.source.tree.ModifiersTree) AnnotationTree(com.sun.source.tree.AnnotationTree) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) NewClassTree(com.sun.source.tree.NewClassTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) ExpressionTree(com.sun.source.tree.ExpressionTree) JCTree(com.sun.tools.javac.tree.JCTree) BugInCF(org.checkerframework.javacutil.BugInCF)

Example 87 with BugInCF

use of org.checkerframework.javacutil.BugInCF in project checker-framework by typetools.

the class TargetedElementAnnotationApplier method handleInvalid.

/**
 * This implementation reports all invalid annotations as errors.
 *
 * @param invalid the list of annotations that were returned by getRawTypeAttributes and were not
 *     handled by handleTargeted or handleValid
 */
protected void handleInvalid(List<Attribute.TypeCompound> invalid) {
    List<Attribute.TypeCompound> remaining = new ArrayList<>(invalid.size());
    for (Attribute.TypeCompound tc : invalid) {
        if (tc.getAnnotationType().getKind() != TypeKind.ERROR) {
            // Filter out annotations that have an error type. javac will
            // already have raised an error for them.
            remaining.add(tc);
        }
    }
    if (!remaining.isEmpty()) {
        StringJoiner msg = new StringJoiner(System.lineSeparator());
        msg.add("handleInvalid(this=" + this.getClass().getName() + "):");
        msg.add("Invalid variable and element passed to extractAndApply; type: " + type);
        String elementInfoPrefix = "  element: " + element + " (kind: " + element.getKind() + "), invalid annotations: ";
        StringJoiner remainingInfo = new StringJoiner(", ", elementInfoPrefix, "");
        for (Attribute.TypeCompound r : remaining) {
            remainingInfo.add(r.toString() + " (" + r.position + ")");
        }
        msg.add(remainingInfo.toString());
        msg.add("Targeted annotations: " + StringsPlume.join(", ", annotatedTargets()));
        msg.add("Valid annotations: " + StringsPlume.join(", ", validTargets()));
        throw new BugInCF(msg.toString());
    }
}
Also used : TypeCompound(com.sun.tools.javac.code.Attribute.TypeCompound) Attribute(com.sun.tools.javac.code.Attribute) ArrayList(java.util.ArrayList) TypeCompound(com.sun.tools.javac.code.Attribute.TypeCompound) BugInCF(org.checkerframework.javacutil.BugInCF) StringJoiner(java.util.StringJoiner)

Example 88 with BugInCF

use of org.checkerframework.javacutil.BugInCF in project checker-framework by typetools.

the class TypeParamElementAnnotationApplier method applyComponentAnnotation.

private void applyComponentAnnotation(final TypeCompound anno) throws UnexpectedAnnotationLocationException {
    final AnnotatedTypeMirror upperBoundType = typeParam.getUpperBound();
    Map<AnnotatedTypeMirror, List<TypeCompound>> typeToAnnotations = new HashMap<>();
    if (anno.position.type == upperBoundTarget()) {
        if (upperBoundType.getKind() == TypeKind.INTERSECTION) {
            final List<AnnotatedTypeMirror> bounds = ((AnnotatedIntersectionType) upperBoundType).getBounds();
            final int boundIndex = anno.position.bound_index + ElementAnnotationUtil.getBoundIndexOffset(bounds);
            if (boundIndex < 0 || boundIndex > bounds.size()) {
                throw new BugInCF("Invalid bound index on element annotation ( " + anno + " ) " + "for type ( " + typeParam + " ) with upper bound ( " + typeParam.getUpperBound() + " )");
            }
            addAnnotationToMap(bounds.get(boundIndex), anno, typeToAnnotations);
        } else {
            addAnnotationToMap(upperBoundType, anno, typeToAnnotations);
        }
    } else {
        addAnnotationToMap(typeParam.getLowerBound(), anno, typeToAnnotations);
    }
    for (Map.Entry<AnnotatedTypeMirror, List<TypeCompound>> typeToAnno : typeToAnnotations.entrySet()) {
        ElementAnnotationUtil.annotateViaTypeAnnoPosition(typeToAnno.getKey(), typeToAnno.getValue());
    }
}
Also used : AnnotatedIntersectionType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedIntersectionType) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) List(java.util.List) BugInCF(org.checkerframework.javacutil.BugInCF) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) HashMap(java.util.HashMap) Map(java.util.Map)

Example 89 with BugInCF

use of org.checkerframework.javacutil.BugInCF in project checker-framework by typetools.

the class EqualitiesSolver method updateTargetsWithPartiallyInferredType.

// If we determined that this target T1 is equal to a type ATM in hierarchies @A,@B,@C
// for each of those hierarchies, if a target is equal to T1 in that hierarchy it is also equal
// to ATM.
// e.g.
// if : T1 == @A @B @C ATM in only the A,B hierarchies
// and T1 == T2 only in @A hierarchy
// 
// then T2 == @A @B @C only in the @A hierarchy
// 
public boolean updateTargetsWithPartiallyInferredType(final Equalities equalities, ConstraintMap constraintMap, AnnotatedTypeFactory typeFactory) {
    boolean updated = false;
    if (!equalities.types.isEmpty()) {
        if (equalities.types.size() != 1) {
            throw new BugInCF("Equalities should have at most 1 constraint.");
        }
        Map.Entry<AnnotatedTypeMirror, AnnotationMirrorSet> remainingTypeEquality;
        remainingTypeEquality = equalities.types.entrySet().iterator().next();
        final AnnotatedTypeMirror remainingType = remainingTypeEquality.getKey();
        final AnnotationMirrorSet remainingHierarchies = remainingTypeEquality.getValue();
        // update targets
        for (Map.Entry<TypeVariable, AnnotationMirrorSet> targetToHierarchies : equalities.targets.entrySet()) {
            final TypeVariable equalTarget = targetToHierarchies.getKey();
            final AnnotationMirrorSet hierarchies = targetToHierarchies.getValue();
            final AnnotationMirrorSet equalTypeHierarchies = new AnnotationMirrorSet(remainingHierarchies);
            equalTypeHierarchies.retainAll(hierarchies);
            final Map<AnnotatedTypeMirror, AnnotationMirrorSet> otherTargetsEqualTypes = constraintMap.getConstraints(equalTarget).equalities.types;
            AnnotationMirrorSet equalHierarchies = otherTargetsEqualTypes.get(remainingType);
            if (equalHierarchies == null) {
                equalHierarchies = new AnnotationMirrorSet(equalTypeHierarchies);
                otherTargetsEqualTypes.put(remainingType, equalHierarchies);
                updated = true;
            } else {
                final int size = equalHierarchies.size();
                equalHierarchies.addAll(equalTypeHierarchies);
                updated = size == equalHierarchies.size();
            }
        }
    }
    return updated;
}
Also used : AnnotatedTypeVariable(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable) TypeVariable(javax.lang.model.type.TypeVariable) BugInCF(org.checkerframework.javacutil.BugInCF) AnnotationMirrorSet(org.checkerframework.framework.util.AnnotationMirrorSet) AnnotationMirrorMap(org.checkerframework.framework.util.AnnotationMirrorMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror)

Example 90 with BugInCF

use of org.checkerframework.javacutil.BugInCF in project checker-framework by typetools.

the class SupertypesSolver method leastUpperBound.

/**
 * Successively calls least upper bound on the elements of types. Unlike
 * AnnotatedTypes.leastUpperBound, this method will box primitives if necessary
 */
public static AnnotatedTypeMirror leastUpperBound(final TypeVariable target, final AnnotatedTypeFactory typeFactory, final Map<AnnotatedTypeMirror, AnnotationMirrorSet> types) {
    QualifierHierarchy qualifierHierarchy = typeFactory.getQualifierHierarchy();
    AnnotatedTypeVariable targetsDeclaredType = (AnnotatedTypeVariable) typeFactory.getAnnotatedType(target.asElement());
    final AnnotationMirrorMap<AnnotationMirror> lowerBoundAnnos = TypeArgInferenceUtil.createHierarchyMap(new AnnotationMirrorSet(targetsDeclaredType.getLowerBound().getEffectiveAnnotations()), qualifierHierarchy);
    final Iterator<Map.Entry<AnnotatedTypeMirror, AnnotationMirrorSet>> typesIter = types.entrySet().iterator();
    if (!typesIter.hasNext()) {
        throw new BugInCF("Calling LUB on empty list.");
    }
    /**
     * If a constraint implies that a type parameter Ti is a supertype of an annotated type mirror
     * Ai but only in a subset of all qualifier hierarchies then for all other qualifier hierarchies
     * replace the primary annotation on Ai with the lowest possible annotation (ensuring that it
     * won't be the LUB unless there are no other constraints, or all other constraints imply the
     * bottom annotation is the LUB). Note: Even if we choose bottom as the lub here, the assignment
     * context may raise this annotation.
     */
    final Map.Entry<AnnotatedTypeMirror, AnnotationMirrorSet> head = typesIter.next();
    AnnotatedTypeMirror lubType = groundMissingHierarchies(head, lowerBoundAnnos);
    AnnotatedTypeMirror nextType = null;
    while (typesIter.hasNext()) {
        nextType = groundMissingHierarchies(typesIter.next(), lowerBoundAnnos);
        if (lubType.getKind().isPrimitive()) {
            if (!nextType.getKind().isPrimitive()) {
                lubType = typeFactory.getBoxedType((AnnotatedPrimitiveType) lubType);
            }
        } else if (nextType.getKind().isPrimitive()) {
            if (!lubType.getKind().isPrimitive()) {
                nextType = typeFactory.getBoxedType((AnnotatedPrimitiveType) nextType);
            }
        }
        lubType = AnnotatedTypes.leastUpperBound(typeFactory, lubType, nextType);
    }
    return lubType;
}
Also used : AnnotationMirror(javax.lang.model.element.AnnotationMirror) QualifierHierarchy(org.checkerframework.framework.type.QualifierHierarchy) AnnotationMirrorSet(org.checkerframework.framework.util.AnnotationMirrorSet) BugInCF(org.checkerframework.javacutil.BugInCF) AnnotatedTypeVariable(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) AnnotationMirrorMap(org.checkerframework.framework.util.AnnotationMirrorMap) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) AnnotatedPrimitiveType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedPrimitiveType)

Aggregations

BugInCF (org.checkerframework.javacutil.BugInCF)127 AnnotatedTypeMirror (org.checkerframework.framework.type.AnnotatedTypeMirror)29 ArrayList (java.util.ArrayList)28 AnnotationMirror (javax.lang.model.element.AnnotationMirror)26 TypeElement (javax.lang.model.element.TypeElement)26 TypeMirror (javax.lang.model.type.TypeMirror)25 ExecutableElement (javax.lang.model.element.ExecutableElement)24 MethodTree (com.sun.source.tree.MethodTree)20 ExpressionTree (com.sun.source.tree.ExpressionTree)18 VariableTree (com.sun.source.tree.VariableTree)18 Element (javax.lang.model.element.Element)18 ClassTree (com.sun.source.tree.ClassTree)17 MethodInvocationTree (com.sun.source.tree.MethodInvocationTree)17 NewClassTree (com.sun.source.tree.NewClassTree)17 LambdaExpressionTree (com.sun.source.tree.LambdaExpressionTree)16 IOException (java.io.IOException)16 Tree (com.sun.source.tree.Tree)15 Map (java.util.Map)15 List (java.util.List)14 VariableElement (javax.lang.model.element.VariableElement)14