Search in sources :

Example 6 with JavaExpressionParseException

use of org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException in project checker-framework by typetools.

the class LessThanAnnotatedTypeFactory method getMinValueFromString.

/**
 * Returns the minimum value of {@code expression} at {@code tree}.
 *
 * @param expression the expression whose minimum value to retrieve
 * @param tree where to determine the value
 * @param path the path to {@code tree}
 * @return the minimum value of {@code expression} at {@code tree}
 */
private long getMinValueFromString(String expression, Tree tree, TreePath path) {
    ValueAnnotatedTypeFactory valueAtypeFactory = getValueAnnotatedTypeFactory();
    JavaExpression expressionJe;
    try {
        expressionJe = valueAtypeFactory.parseJavaExpressionString(expression, path);
    } catch (JavaExpressionParseException e) {
        return Long.MIN_VALUE;
    }
    AnnotationMirror intRange = valueAtypeFactory.getAnnotationFromJavaExpression(expressionJe, tree, IntRange.class);
    if (intRange != null) {
        return valueAtypeFactory.getRange(intRange).from;
    }
    AnnotationMirror intValue = valueAtypeFactory.getAnnotationFromJavaExpression(expressionJe, tree, IntVal.class);
    if (intValue != null) {
        List<Long> possibleValues = valueAtypeFactory.getIntValues(intValue);
        return Collections.min(possibleValues);
    }
    if (expressionJe instanceof FieldAccess) {
        FieldAccess fieldAccess = ((FieldAccess) expressionJe);
        if (fieldAccess.getReceiver().getType().getKind() == TypeKind.ARRAY) {
            // array.length might not be in the store, so check for the length of the array.
            AnnotationMirror arrayRange = valueAtypeFactory.getAnnotationFromJavaExpression(fieldAccess.getReceiver(), tree, ArrayLenRange.class);
            if (arrayRange != null) {
                return valueAtypeFactory.getRange(arrayRange).from;
            }
            AnnotationMirror arrayLen = valueAtypeFactory.getAnnotationFromJavaExpression(expressionJe, tree, ArrayLen.class);
            if (arrayLen != null) {
                List<Integer> possibleValues = valueAtypeFactory.getArrayLength(arrayLen);
                return Collections.min(possibleValues);
            }
            // Even arrays that we know nothing about must have at least zero length.
            return 0;
        }
    }
    return Long.MIN_VALUE;
}
Also used : AnnotationMirror(javax.lang.model.element.AnnotationMirror) JavaExpression(org.checkerframework.dataflow.expression.JavaExpression) JavaExpressionParseException(org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException) FieldAccess(org.checkerframework.dataflow.expression.FieldAccess) ValueAnnotatedTypeFactory(org.checkerframework.common.value.ValueAnnotatedTypeFactory)

Example 7 with JavaExpressionParseException

use of org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException in project checker-framework by typetools.

the class CFAbstractTransfer method addInformationFromPreconditions.

/**
 * Add the information from all the preconditions of a method to the initial store in the method
 * body.
 *
 * @param initialStore the initial store for the method body
 * @param factory the type factory
 * @param methodAst the AST for a method declaration
 * @param methodDeclTree the declaration of the method; is a field of {@code methodAst}
 * @param methodElement the element for the method
 */
protected void addInformationFromPreconditions(S initialStore, AnnotatedTypeFactory factory, CFGMethod methodAst, MethodTree methodDeclTree, ExecutableElement methodElement) {
    ContractsFromMethod contractsUtils = analysis.atypeFactory.getContractsFromMethod();
    Set<Precondition> preconditions = contractsUtils.getPreconditions(methodElement);
    StringToJavaExpression stringToJavaExpr = stringExpr -> StringToJavaExpression.atMethodBody(stringExpr, methodDeclTree, analysis.checker);
    for (Precondition p : preconditions) {
        String stringExpr = p.expressionString;
        AnnotationMirror annotation = p.viewpointAdaptDependentTypeAnnotation(analysis.atypeFactory, stringToJavaExpr, /*errorTree=*/
        null);
        JavaExpression exprJe;
        try {
            // TODO: currently, these expressions are parsed at the declaration (i.e. here) and for
            // every use. this could be optimized to store the result the first time.
            // (same for other annotations)
            exprJe = StringToJavaExpression.atMethodBody(stringExpr, methodDeclTree, analysis.checker);
        } catch (JavaExpressionParseException e) {
            // Errors are reported by BaseTypeVisitor.checkContractsAtMethodDeclaration().
            continue;
        }
        initialStore.insertValuePermitNondeterministic(exprJe, annotation);
    }
}
Also used : NodeUtils(org.checkerframework.dataflow.util.NodeUtils) Arrays(java.util.Arrays) TransferResult(org.checkerframework.dataflow.analysis.TransferResult) Modifier(javax.lang.model.element.Modifier) ForwardTransferFunction(org.checkerframework.dataflow.analysis.ForwardTransferFunction) TypeElement(javax.lang.model.element.TypeElement) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) StringConversionNode(org.checkerframework.dataflow.cfg.node.StringConversionNode) GenericAnnotatedTypeFactory(org.checkerframework.framework.type.GenericAnnotatedTypeFactory) Map(java.util.Map) WideningConversionNode(org.checkerframework.dataflow.cfg.node.WideningConversionNode) InternedDistinct(org.checkerframework.checker.interning.qual.InternedDistinct) AnnotatedExecutableType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType) ClassNameNode(org.checkerframework.dataflow.cfg.node.ClassNameNode) TreePath(com.sun.source.util.TreePath) ObjectCreationNode(org.checkerframework.dataflow.cfg.node.ObjectCreationNode) UnderlyingAST(org.checkerframework.dataflow.cfg.UnderlyingAST) AbstractNodeVisitor(org.checkerframework.dataflow.cfg.node.AbstractNodeVisitor) Set(java.util.Set) Element(javax.lang.model.element.Element) Contract(org.checkerframework.framework.util.Contract) TreeUtils(org.checkerframework.javacutil.TreeUtils) CFGMethod(org.checkerframework.dataflow.cfg.UnderlyingAST.CFGMethod) LocalVariableNode(org.checkerframework.dataflow.cfg.node.LocalVariableNode) NarrowingConversionNode(org.checkerframework.dataflow.cfg.node.NarrowingConversionNode) List(java.util.List) LocalVariable(org.checkerframework.dataflow.expression.LocalVariable) AnnotatedDeclaredType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType) EqualToNode(org.checkerframework.dataflow.cfg.node.EqualToNode) AnnotatedTypes(org.checkerframework.framework.util.AnnotatedTypes) CFGLambda(org.checkerframework.dataflow.cfg.UnderlyingAST.CFGLambda) VariableDeclarationNode(org.checkerframework.dataflow.cfg.node.VariableDeclarationNode) RegularTransferResult(org.checkerframework.dataflow.analysis.RegularTransferResult) TernaryExpressionNode(org.checkerframework.dataflow.cfg.node.TernaryExpressionNode) Postcondition(org.checkerframework.framework.util.Contract.Postcondition) MethodTree(com.sun.source.tree.MethodTree) ConditionalPostcondition(org.checkerframework.framework.util.Contract.ConditionalPostcondition) VariableElement(javax.lang.model.element.VariableElement) InstanceOfNode(org.checkerframework.dataflow.cfg.node.InstanceOfNode) HashMap(java.util.HashMap) ThisNode(org.checkerframework.dataflow.cfg.node.ThisNode) ArrayList(java.util.ArrayList) ConditionalTransferResult(org.checkerframework.dataflow.analysis.ConditionalTransferResult) AssignmentNode(org.checkerframework.dataflow.cfg.node.AssignmentNode) CaseNode(org.checkerframework.dataflow.cfg.node.CaseNode) HashSet(java.util.HashSet) LambdaResultExpressionNode(org.checkerframework.dataflow.cfg.node.LambdaResultExpressionNode) Precondition(org.checkerframework.framework.util.Contract.Precondition) FieldAccessNode(org.checkerframework.dataflow.cfg.node.FieldAccessNode) TreePathUtil(org.checkerframework.javacutil.TreePathUtil) SwitchExpressionNode(org.checkerframework.dataflow.cfg.node.SwitchExpressionNode) NotEqualNode(org.checkerframework.dataflow.cfg.node.NotEqualNode) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) Nullable(org.checkerframework.checker.nullness.qual.Nullable) FieldAccess(org.checkerframework.dataflow.expression.FieldAccess) TransferInput(org.checkerframework.dataflow.analysis.TransferInput) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) ArrayAccessNode(org.checkerframework.dataflow.cfg.node.ArrayAccessNode) ConditionalNotNode(org.checkerframework.dataflow.cfg.node.ConditionalNotNode) 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) ReturnNode(org.checkerframework.dataflow.cfg.node.ReturnNode) JavaExpression(org.checkerframework.dataflow.expression.JavaExpression) FieldInitialValue(org.checkerframework.framework.flow.CFAbstractAnalysis.FieldInitialValue) MethodInvocationNode(org.checkerframework.dataflow.cfg.node.MethodInvocationNode) AnnotationMirror(javax.lang.model.element.AnnotationMirror) StringToJavaExpression(org.checkerframework.framework.util.StringToJavaExpression) AnnotatedTypeFactory(org.checkerframework.framework.type.AnnotatedTypeFactory) StringConcatenateAssignmentNode(org.checkerframework.dataflow.cfg.node.StringConcatenateAssignmentNode) TypeMirror(javax.lang.model.type.TypeMirror) Collections(java.util.Collections) ElementUtils(org.checkerframework.javacutil.ElementUtils) Node(org.checkerframework.dataflow.cfg.node.Node) ContractsFromMethod(org.checkerframework.framework.util.ContractsFromMethod) AnnotationMirror(javax.lang.model.element.AnnotationMirror) JavaExpression(org.checkerframework.dataflow.expression.JavaExpression) StringToJavaExpression(org.checkerframework.framework.util.StringToJavaExpression) Precondition(org.checkerframework.framework.util.Contract.Precondition) StringToJavaExpression(org.checkerframework.framework.util.StringToJavaExpression) JavaExpressionParseException(org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException) ContractsFromMethod(org.checkerframework.framework.util.ContractsFromMethod)

Example 8 with JavaExpressionParseException

use of org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException in project checker-framework by typetools.

the class CFAbstractTransfer method processPostconditionsAndConditionalPostconditions.

/**
 * Add information from the postconditions and conditional postconditions of a method to the
 * stores after an invocation.
 *
 * @param invocationNode a method call
 * @param invocationTree the tree for the method call
 * @param thenStore the "then" store; is side-effected by this method
 * @param elseStore the "else" store; is side-effected by this method
 * @param postconditions the postconditions
 */
private void processPostconditionsAndConditionalPostconditions(MethodInvocationNode invocationNode, Tree invocationTree, S thenStore, S elseStore, Set<? extends Contract> postconditions) {
    StringToJavaExpression stringToJavaExpr = stringExpr -> StringToJavaExpression.atMethodInvocation(stringExpr, invocationNode, analysis.checker);
    for (Contract p : postconditions) {
        // Viewpoint-adapt to the method use (the call site).
        AnnotationMirror anno = p.viewpointAdaptDependentTypeAnnotation(analysis.atypeFactory, stringToJavaExpr, /*errorTree=*/
        null);
        String expressionString = p.expressionString;
        try {
            JavaExpression je = stringToJavaExpr.toJavaExpression(expressionString);
            // are removed from the store before this method is called.
            if (p.kind == Contract.Kind.CONDITIONALPOSTCONDITION) {
                if (((ConditionalPostcondition) p).resultValue) {
                    thenStore.insertOrRefinePermitNondeterministic(je, anno);
                } else {
                    elseStore.insertOrRefinePermitNondeterministic(je, anno);
                }
            } else {
                thenStore.insertOrRefinePermitNondeterministic(je, anno);
            }
        } catch (JavaExpressionParseException e) {
            // report errors here
            if (e.isFlowParseError()) {
                Object[] args = new Object[e.args.length + 1];
                args[0] = ElementUtils.getSimpleSignature(TreeUtils.elementFromUse(invocationNode.getTree()));
                System.arraycopy(e.args, 0, args, 1, e.args.length);
                analysis.checker.reportError(invocationTree, "flowexpr.parse.error.postcondition", args);
            } else {
                analysis.checker.report(invocationTree, e.getDiagMessage());
            }
        }
    }
}
Also used : NodeUtils(org.checkerframework.dataflow.util.NodeUtils) Arrays(java.util.Arrays) TransferResult(org.checkerframework.dataflow.analysis.TransferResult) Modifier(javax.lang.model.element.Modifier) ForwardTransferFunction(org.checkerframework.dataflow.analysis.ForwardTransferFunction) TypeElement(javax.lang.model.element.TypeElement) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) StringConversionNode(org.checkerframework.dataflow.cfg.node.StringConversionNode) GenericAnnotatedTypeFactory(org.checkerframework.framework.type.GenericAnnotatedTypeFactory) Map(java.util.Map) WideningConversionNode(org.checkerframework.dataflow.cfg.node.WideningConversionNode) InternedDistinct(org.checkerframework.checker.interning.qual.InternedDistinct) AnnotatedExecutableType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType) ClassNameNode(org.checkerframework.dataflow.cfg.node.ClassNameNode) TreePath(com.sun.source.util.TreePath) ObjectCreationNode(org.checkerframework.dataflow.cfg.node.ObjectCreationNode) UnderlyingAST(org.checkerframework.dataflow.cfg.UnderlyingAST) AbstractNodeVisitor(org.checkerframework.dataflow.cfg.node.AbstractNodeVisitor) Set(java.util.Set) Element(javax.lang.model.element.Element) Contract(org.checkerframework.framework.util.Contract) TreeUtils(org.checkerframework.javacutil.TreeUtils) CFGMethod(org.checkerframework.dataflow.cfg.UnderlyingAST.CFGMethod) LocalVariableNode(org.checkerframework.dataflow.cfg.node.LocalVariableNode) NarrowingConversionNode(org.checkerframework.dataflow.cfg.node.NarrowingConversionNode) List(java.util.List) LocalVariable(org.checkerframework.dataflow.expression.LocalVariable) AnnotatedDeclaredType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType) EqualToNode(org.checkerframework.dataflow.cfg.node.EqualToNode) AnnotatedTypes(org.checkerframework.framework.util.AnnotatedTypes) CFGLambda(org.checkerframework.dataflow.cfg.UnderlyingAST.CFGLambda) VariableDeclarationNode(org.checkerframework.dataflow.cfg.node.VariableDeclarationNode) RegularTransferResult(org.checkerframework.dataflow.analysis.RegularTransferResult) TernaryExpressionNode(org.checkerframework.dataflow.cfg.node.TernaryExpressionNode) Postcondition(org.checkerframework.framework.util.Contract.Postcondition) MethodTree(com.sun.source.tree.MethodTree) ConditionalPostcondition(org.checkerframework.framework.util.Contract.ConditionalPostcondition) VariableElement(javax.lang.model.element.VariableElement) InstanceOfNode(org.checkerframework.dataflow.cfg.node.InstanceOfNode) HashMap(java.util.HashMap) ThisNode(org.checkerframework.dataflow.cfg.node.ThisNode) ArrayList(java.util.ArrayList) ConditionalTransferResult(org.checkerframework.dataflow.analysis.ConditionalTransferResult) AssignmentNode(org.checkerframework.dataflow.cfg.node.AssignmentNode) CaseNode(org.checkerframework.dataflow.cfg.node.CaseNode) HashSet(java.util.HashSet) LambdaResultExpressionNode(org.checkerframework.dataflow.cfg.node.LambdaResultExpressionNode) Precondition(org.checkerframework.framework.util.Contract.Precondition) FieldAccessNode(org.checkerframework.dataflow.cfg.node.FieldAccessNode) TreePathUtil(org.checkerframework.javacutil.TreePathUtil) SwitchExpressionNode(org.checkerframework.dataflow.cfg.node.SwitchExpressionNode) NotEqualNode(org.checkerframework.dataflow.cfg.node.NotEqualNode) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) Nullable(org.checkerframework.checker.nullness.qual.Nullable) FieldAccess(org.checkerframework.dataflow.expression.FieldAccess) TransferInput(org.checkerframework.dataflow.analysis.TransferInput) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) ArrayAccessNode(org.checkerframework.dataflow.cfg.node.ArrayAccessNode) ConditionalNotNode(org.checkerframework.dataflow.cfg.node.ConditionalNotNode) 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) ReturnNode(org.checkerframework.dataflow.cfg.node.ReturnNode) JavaExpression(org.checkerframework.dataflow.expression.JavaExpression) FieldInitialValue(org.checkerframework.framework.flow.CFAbstractAnalysis.FieldInitialValue) MethodInvocationNode(org.checkerframework.dataflow.cfg.node.MethodInvocationNode) AnnotationMirror(javax.lang.model.element.AnnotationMirror) StringToJavaExpression(org.checkerframework.framework.util.StringToJavaExpression) AnnotatedTypeFactory(org.checkerframework.framework.type.AnnotatedTypeFactory) StringConcatenateAssignmentNode(org.checkerframework.dataflow.cfg.node.StringConcatenateAssignmentNode) TypeMirror(javax.lang.model.type.TypeMirror) Collections(java.util.Collections) ElementUtils(org.checkerframework.javacutil.ElementUtils) Node(org.checkerframework.dataflow.cfg.node.Node) ContractsFromMethod(org.checkerframework.framework.util.ContractsFromMethod) AnnotationMirror(javax.lang.model.element.AnnotationMirror) JavaExpression(org.checkerframework.dataflow.expression.JavaExpression) StringToJavaExpression(org.checkerframework.framework.util.StringToJavaExpression) StringToJavaExpression(org.checkerframework.framework.util.StringToJavaExpression) JavaExpressionParseException(org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException) ConditionalPostcondition(org.checkerframework.framework.util.Contract.ConditionalPostcondition) Contract(org.checkerframework.framework.util.Contract)

Example 9 with JavaExpressionParseException

use of org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException in project checker-framework by typetools.

the class BaseTypeVisitor method checkPreconditions.

/**
 * Checks that all the given {@code preconditions} hold true immediately prior to the method
 * invocation or variable access at {@code tree}.
 *
 * @param tree the method invocation; immediately prior to it, the preconditions must hold true
 * @param preconditions the preconditions to be checked
 */
protected void checkPreconditions(MethodInvocationTree tree, Set<Precondition> preconditions) {
    // TODO: Remove this check and investigate the root cause.
    if (preconditions.isEmpty()) {
        return;
    }
    StringToJavaExpression stringToJavaExpr = stringExpr -> StringToJavaExpression.atMethodInvocation(stringExpr, tree, checker);
    for (Contract c : preconditions) {
        Precondition p = (Precondition) c;
        String expressionString = p.expressionString;
        AnnotationMirror anno = c.viewpointAdaptDependentTypeAnnotation(atypeFactory, stringToJavaExpr, tree);
        JavaExpression exprJe;
        try {
            exprJe = StringToJavaExpression.atMethodInvocation(expressionString, tree, checker);
        } catch (JavaExpressionParseException e) {
            // report errors here
            checker.report(tree, e.getDiagMessage());
            return;
        }
        CFAbstractStore<?, ?> store = atypeFactory.getStoreBefore(tree);
        CFAbstractValue<?> value = null;
        if (CFAbstractStore.canInsertJavaExpression(exprJe)) {
            value = store.getValue(exprJe);
        }
        AnnotationMirror inferredAnno = null;
        if (value != null) {
            QualifierHierarchy hierarchy = atypeFactory.getQualifierHierarchy();
            Set<AnnotationMirror> annos = value.getAnnotations();
            inferredAnno = hierarchy.findAnnotationInSameHierarchy(annos, anno);
        }
        if (!checkContract(exprJe, anno, inferredAnno, store)) {
            if (exprJe != null) {
                expressionString = exprJe.toString();
            }
            checker.reportError(tree, "contracts.precondition", tree.getMethodSelect().toString(), contractExpressionAndType(expressionString, inferredAnno), contractExpressionAndType(expressionString, anno));
        }
    }
}
Also used : AnnotationEqualityVisitor(org.checkerframework.framework.ajava.AnnotationEqualityVisitor) CompoundAssignmentTree(com.sun.source.tree.CompoundAssignmentTree) Arrays(java.util.Arrays) TransferResult(org.checkerframework.dataflow.analysis.TransferResult) AnnotatedArrayType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedArrayType) Modifier(javax.lang.model.element.Modifier) QualifierHierarchy(org.checkerframework.framework.type.QualifierHierarchy) TypeElement(javax.lang.model.element.TypeElement) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) DefaultPrettyPrinter(com.github.javaparser.printer.DefaultPrettyPrinter) GenericAnnotatedTypeFactory(org.checkerframework.framework.type.GenericAnnotatedTypeFactory) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) AssignmentTree(com.sun.source.tree.AssignmentTree) TypeCastTree(com.sun.source.tree.TypeCastTree) Vector(java.util.Vector) LambdaExpressionTree(com.sun.source.tree.LambdaExpressionTree) Map(java.util.Map) InstanceOfTree(com.sun.source.tree.InstanceOfTree) EnumSet(java.util.EnumSet) SideEffectFree(org.checkerframework.dataflow.qual.SideEffectFree) AnnotatedExecutableType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType) ConditionalExpressionTree(com.sun.source.tree.ConditionalExpressionTree) TreePath(com.sun.source.util.TreePath) Pure(org.checkerframework.dataflow.qual.Pure) Set(java.util.Set) AnnotatedWildcardType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedWildcardType) Element(javax.lang.model.element.Element) MemberSelectTree(com.sun.source.tree.MemberSelectTree) TreeUtils(org.checkerframework.javacutil.TreeUtils) TreeScanner(com.sun.source.util.TreeScanner) ParameterizedExecutableType(org.checkerframework.framework.type.AnnotatedTypeFactory.ParameterizedExecutableType) Unused(org.checkerframework.framework.qual.Unused) ThrowTree(com.sun.source.tree.ThrowTree) JCIdent(com.sun.tools.javac.tree.JCTree.JCIdent) AnnotationValue(javax.lang.model.element.AnnotationValue) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) TypesUtils(org.checkerframework.javacutil.TypesUtils) AnnotatedPrimitiveType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedPrimitiveType) ReturnTree(com.sun.source.tree.ReturnTree) PurityResult(org.checkerframework.dataflow.util.PurityChecker.PurityResult) ArrayTypeTree(com.sun.source.tree.ArrayTypeTree) ConditionalPostcondition(org.checkerframework.framework.util.Contract.ConditionalPostcondition) UnaryTree(com.sun.source.tree.UnaryTree) CFAbstractValue(org.checkerframework.framework.flow.CFAbstractValue) VariableElement(javax.lang.model.element.VariableElement) VariableTree(com.sun.source.tree.VariableTree) BooleanLiteralNode(org.checkerframework.dataflow.cfg.node.BooleanLiteralNode) ReferenceKind(com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind) TypeParameterTree(com.sun.source.tree.TypeParameterTree) ArrayList(java.util.ArrayList) CompilerMessageKey(org.checkerframework.checker.compilermsgs.qual.CompilerMessageKey) NewClassTree(com.sun.source.tree.NewClassTree) ParameterizedTypeTree(com.sun.source.tree.ParameterizedTypeTree) Precondition(org.checkerframework.framework.util.Contract.Precondition) FindDistinct(org.checkerframework.checker.interning.qual.FindDistinct) SwitchExpressionScanner(org.checkerframework.javacutil.SwitchExpressionScanner) TreeInfo(com.sun.tools.javac.tree.TreeInfo) DeclaredType(javax.lang.model.type.DeclaredType) TreePathUtil(org.checkerframework.javacutil.TreePathUtil) ElementFilter(javax.lang.model.util.ElementFilter) Tree(com.sun.source.tree.Tree) LinkedHashSet(java.util.LinkedHashSet) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) SourceVisitor(org.checkerframework.framework.source.SourceVisitor) QualifierPolymorphism(org.checkerframework.framework.type.poly.QualifierPolymorphism) FieldInvariants(org.checkerframework.framework.util.FieldInvariants) ExpressionTree(com.sun.source.tree.ExpressionTree) IOException(java.io.IOException) Target(java.lang.annotation.Target) AnnotationMirror(javax.lang.model.element.AnnotationMirror) StringToJavaExpression(org.checkerframework.framework.util.StringToJavaExpression) ParseProblemException(com.github.javaparser.ParseProblemException) DiagMessage(org.checkerframework.framework.source.DiagMessage) SourcePositions(com.sun.source.util.SourcePositions) IntersectionTypeTree(com.sun.source.tree.IntersectionTypeTree) FunctionalSwitchExpressionScanner(org.checkerframework.javacutil.SwitchExpressionScanner.FunctionalSwitchExpressionScanner) ElementUtils(org.checkerframework.javacutil.ElementUtils) ContractsFromMethod(org.checkerframework.framework.util.ContractsFromMethod) CollectionsPlume(org.plumelib.util.CollectionsPlume) PurityUtils(org.checkerframework.dataflow.util.PurityUtils) JointVisitorWithDefaultAction(org.checkerframework.framework.ajava.JointVisitorWithDefaultAction) AnnotatedIntersectionType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedIntersectionType) BugInCF(org.checkerframework.javacutil.BugInCF) PurityChecker(org.checkerframework.dataflow.util.PurityChecker) JCFieldAccess(com.sun.tools.javac.tree.JCTree.JCFieldAccess) AnnotatedTypeTree(com.sun.source.tree.AnnotatedTypeTree) InsertAjavaAnnotations(org.checkerframework.framework.ajava.InsertAjavaAnnotations) JCMemberReference(com.sun.tools.javac.tree.JCTree.JCMemberReference) IdentifierTree(com.sun.source.tree.IdentifierTree) CatchTree(com.sun.source.tree.CatchTree) NewArrayTree(com.sun.source.tree.NewArrayTree) CompilationUnit(com.github.javaparser.ast.CompilationUnit) Pair(org.checkerframework.javacutil.Pair) ArraysPlume(org.plumelib.util.ArraysPlume) ReferenceMode(com.sun.source.tree.MemberReferenceTree.ReferenceMode) Analysis(org.checkerframework.dataflow.analysis.Analysis) WholeProgramInference(org.checkerframework.common.wholeprograminference.WholeProgramInference) ExpectedTreesVisitor(org.checkerframework.framework.ajava.ExpectedTreesVisitor) CFAbstractStore(org.checkerframework.framework.flow.CFAbstractStore) Contract(org.checkerframework.framework.util.Contract) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) AnnotatedTypeParameterBounds(org.checkerframework.framework.type.AnnotatedTypeParameterBounds) TypeKind(javax.lang.model.type.TypeKind) List(java.util.List) LocalVariable(org.checkerframework.dataflow.expression.LocalVariable) AnnotatedDeclaredType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType) TypeHierarchy(org.checkerframework.framework.type.TypeHierarchy) Annotation(java.lang.annotation.Annotation) ModifiersTree(com.sun.source.tree.ModifiersTree) AnnotatedTypes(org.checkerframework.framework.util.AnnotatedTypes) Postcondition(org.checkerframework.framework.util.Contract.Postcondition) AnnotatedTypeVariable(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable) AnnotationTree(com.sun.source.tree.AnnotationTree) MethodTree(com.sun.source.tree.MethodTree) HashMap(java.util.HashMap) HashSet(java.util.HashSet) Kind(javax.tools.Diagnostic.Kind) AnnotationBuilder(org.checkerframework.javacutil.AnnotationBuilder) AnnotationUtils(org.checkerframework.javacutil.AnnotationUtils) ClassTree(com.sun.source.tree.ClassTree) Nullable(org.checkerframework.checker.nullness.qual.Nullable) Name(javax.lang.model.element.Name) JavaExpressionParseException(org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException) ElementKind(javax.lang.model.element.ElementKind) MemberReferenceTree(com.sun.source.tree.MemberReferenceTree) ExecutableElement(javax.lang.model.element.ExecutableElement) ReturnNode(org.checkerframework.dataflow.cfg.node.ReturnNode) JavaExpression(org.checkerframework.dataflow.expression.JavaExpression) JCTree(com.sun.tools.javac.tree.JCTree) ElementType(java.lang.annotation.ElementType) SimpleAnnotatedTypeScanner(org.checkerframework.framework.type.visitor.SimpleAnnotatedTypeScanner) JavaExpressionScanner(org.checkerframework.dataflow.expression.JavaExpressionScanner) AnnotatedTypeFactory(org.checkerframework.framework.type.AnnotatedTypeFactory) AnnotatedUnionType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedUnionType) TypeMirror(javax.lang.model.type.TypeMirror) StringJoiner(java.util.StringJoiner) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) Deterministic(org.checkerframework.dataflow.qual.Deterministic) JavaParserUtil(org.checkerframework.framework.util.JavaParserUtil) Collections(java.util.Collections) Node(org.checkerframework.dataflow.cfg.node.Node) DefaultQualifier(org.checkerframework.framework.qual.DefaultQualifier) InputStream(java.io.InputStream) AnnotationMirror(javax.lang.model.element.AnnotationMirror) StringToJavaExpression(org.checkerframework.framework.util.StringToJavaExpression) JavaExpression(org.checkerframework.dataflow.expression.JavaExpression) Precondition(org.checkerframework.framework.util.Contract.Precondition) QualifierHierarchy(org.checkerframework.framework.type.QualifierHierarchy) StringToJavaExpression(org.checkerframework.framework.util.StringToJavaExpression) JavaExpressionParseException(org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException) Contract(org.checkerframework.framework.util.Contract)

Example 10 with JavaExpressionParseException

use of org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException in project checker-framework by typetools.

the class DependentTypesHelper method delocalize.

/**
 * Viewpoint-adapt all dependent type annotations to the method declaration, {@code
 * methodDeclTree}. This method changes occurrences of formal parameter names to the "#2" syntax,
 * and it removes expressions that contain other local variables.
 *
 * <p>If a Java expression in {@code atm} references local variables (other than formal
 * parameters), the expression is removed from the annotation. This could result in dependent type
 * annotations with empty lists of expressions. If this is a problem, a subclass can override
 * {@link #buildAnnotation(AnnotationMirror, Map)} to do something besides creating an annotation
 * with a empty list.
 *
 * @param atm type to viewpoint-adapt; is side-effected by this method
 * @param methodDeclTree the method declaration to which the annotations are viewpoint-adapted
 */
public void delocalize(AnnotatedTypeMirror atm, MethodTree methodDeclTree) {
    if (!hasDependentType(atm)) {
        return;
    }
    TreePath pathToMethodDecl = factory.getPath(methodDeclTree);
    ExecutableElement methodElement = TreeUtils.elementFromDeclaration(methodDeclTree);
    List<FormalParameter> parameters = JavaExpression.getFormalParameters(methodElement);
    List<JavaExpression> paramsAsLocals = JavaExpression.getParametersAsLocalVariables(methodElement);
    StringToJavaExpression stringToJavaExpr = expression -> {
        JavaExpression javaExpr;
        try {
            javaExpr = StringToJavaExpression.atPath(expression, pathToMethodDecl, factory.getChecker());
        } catch (JavaExpressionParseException ex) {
            return null;
        }
        JavaExpressionConverter jec = new JavaExpressionConverter() {

            @Override
            protected JavaExpression visitLocalVariable(LocalVariable localVarExpr, Void unused) {
                int index = paramsAsLocals.indexOf(localVarExpr);
                if (index == -1) {
                    throw new FoundLocalException();
                }
                return parameters.get(index);
            }
        };
        try {
            return jec.convert(javaExpr);
        } catch (FoundLocalException ex) {
            return null;
        }
    };
    if (debugStringToJavaExpression) {
        System.out.printf("delocalize(%s, %s) created %s%n", atm, TreeUtils.toStringTruncated(methodDeclTree, 65), stringToJavaExpr);
    }
    convertAnnotatedTypeMirror(stringToJavaExpr, atm);
}
Also used : FormalParameter(org.checkerframework.dataflow.expression.FormalParameter) 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) JavaExpressionConverter(org.checkerframework.dataflow.expression.JavaExpressionConverter) JavaExpression(org.checkerframework.dataflow.expression.JavaExpression) StringToJavaExpression(org.checkerframework.framework.util.StringToJavaExpression) ExecutableElement(javax.lang.model.element.ExecutableElement) LocalVariable(org.checkerframework.dataflow.expression.LocalVariable) TreePath(com.sun.source.util.TreePath) StringToJavaExpression(org.checkerframework.framework.util.StringToJavaExpression) JavaExpressionParseException(org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException)

Aggregations

JavaExpressionParseException (org.checkerframework.framework.util.JavaExpressionParseUtil.JavaExpressionParseException)16 JavaExpression (org.checkerframework.dataflow.expression.JavaExpression)13 StringToJavaExpression (org.checkerframework.framework.util.StringToJavaExpression)10 AnnotationMirror (javax.lang.model.element.AnnotationMirror)9 ExecutableElement (javax.lang.model.element.ExecutableElement)9 ArrayList (java.util.ArrayList)8 Element (javax.lang.model.element.Element)8 Nullable (org.checkerframework.checker.nullness.qual.Nullable)8 LocalVariable (org.checkerframework.dataflow.expression.LocalVariable)8 MethodTree (com.sun.source.tree.MethodTree)7 HashMap (java.util.HashMap)7 List (java.util.List)7 TypeElement (javax.lang.model.element.TypeElement)7 VariableElement (javax.lang.model.element.VariableElement)7 ClassTree (com.sun.source.tree.ClassTree)6 ExpressionTree (com.sun.source.tree.ExpressionTree)6 Tree (com.sun.source.tree.Tree)6 TreePath (com.sun.source.util.TreePath)6 Collections (java.util.Collections)6 Map (java.util.Map)6