Search in sources :

Example 1 with UserError

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

the class DOTCFGVisualizer method visualize.

@Override
@Nullable
public Map<String, Object> visualize(ControlFlowGraph cfg, Block entry, @Nullable Analysis<V, S, T> analysis) {
    String dotGraph = visualizeGraph(cfg, entry, analysis);
    String dotFileName = dotOutputFileName(cfg.underlyingAST);
    try {
        FileWriter fStream = new FileWriter(dotFileName);
        BufferedWriter out = new BufferedWriter(fStream);
        out.write(dotGraph);
        out.close();
    } catch (IOException e) {
        throw new UserError("Error creating dot file (is the path valid?): " + dotFileName, e);
    }
    return Collections.singletonMap("dotFileName", dotFileName);
}
Also used : UserError(org.checkerframework.javacutil.UserError) FileWriter(java.io.FileWriter) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Example 2 with UserError

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

the class UnitsAnnotatedTypeFactory method addUnitsRelations.

/**
 * Look for an @UnitsRelations annotation on the qualifier and add it to the list of
 * UnitsRelations.
 *
 * @param qual the qualifier to investigate
 */
private void addUnitsRelations(Class<? extends Annotation> qual) {
    AnnotationMirror am = AnnotationBuilder.fromClass(elements, qual);
    for (AnnotationMirror ama : am.getAnnotationType().asElement().getAnnotationMirrors()) {
        if (areSameByClass(ama, unitsRelationsAnnoClass)) {
            String theclassname = AnnotationUtils.getElementValueClassName(ama, unitsRelationsValueElement).toString();
            if (!Signatures.isClassGetName(theclassname)) {
                throw new UserError("Malformed class name \"%s\" should be in ClassGetName format in annotation %s", theclassname, ama);
            }
            Class<?> valueElement;
            try {
                ClassLoader classLoader = InternalUtils.getClassLoaderForClass(AnnotationUtils.class);
                valueElement = Class.forName(theclassname, true, classLoader);
            } catch (ClassNotFoundException e) {
                String msg = String.format("Could not load class '%s' for field 'value' in annotation %s", theclassname, ama);
                throw new UserError(msg, e);
            }
            Class<? extends UnitsRelations> unitsRelationsClass;
            try {
                unitsRelationsClass = valueElement.asSubclass(UnitsRelations.class);
            } catch (ClassCastException ex) {
                throw new UserError("Invalid @UnitsRelations meta-annotation found in %s. " + "@UnitsRelations value %s is not a subclass of " + "org.checkerframework.checker.units.UnitsRelations.", qual, ama);
            }
            String classname = unitsRelationsClass.getCanonicalName();
            if (!getUnitsRel().containsKey(classname)) {
                try {
                    unitsRel.put(classname, unitsRelationsClass.getDeclaredConstructor().newInstance().init(processingEnv));
                } catch (Throwable e) {
                    throw new TypeSystemError("Throwable when instantiating UnitsRelations", e);
                }
            }
        }
    }
}
Also used : AnnotationMirror(javax.lang.model.element.AnnotationMirror) UserError(org.checkerframework.javacutil.UserError) AnnotationClassLoader(org.checkerframework.framework.type.AnnotationClassLoader) TypeSystemError(org.checkerframework.javacutil.TypeSystemError)

Example 3 with UserError

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

the class ASceneWrapper method writeToFile.

/**
 * Write the scene wrapped by this object to a file at the given path.
 *
 * @param jaifPath the path of the file to be written, but ending in ".jaif". If {@code
 *     outputformat} is not {@code JAIF}, the path will be modified to match.
 * @param annosToIgnore which annotations should be ignored in which contexts
 * @param outputFormat the output format to use
 * @param checker the checker from which this method is called, for naming stub files
 */
public void writeToFile(String jaifPath, AnnotationsInContexts annosToIgnore, OutputFormat outputFormat, BaseTypeChecker checker) {
    assert jaifPath.endsWith(".jaif");
    AScene scene = theScene.clone();
    removeAnnosFromScene(scene, annosToIgnore);
    scene.prune();
    String filepath;
    switch(outputFormat) {
        case JAIF:
            filepath = jaifPath;
            break;
        case STUB:
            String astubWithChecker = "-" + checker.getClass().getCanonicalName() + ".astub";
            filepath = jaifPath.replace(".jaif", astubWithChecker);
            break;
        default:
            throw new BugInCF("Unhandled outputFormat " + outputFormat);
    }
    new File(filepath).delete();
    // Only write non-empty scenes into files.
    if (!scene.isEmpty()) {
        try {
            switch(outputFormat) {
                case STUB:
                    // For stub files, pass in the checker to compute contracts on the fly; precomputing
                    // yields incorrect annotations, most likely due to nested classes.
                    SceneToStubWriter.write(this, filepath, checker);
                    break;
                case JAIF:
                    // nothing about (and cannot depend on) the Checker Framework.
                    for (Map.Entry<String, AClass> classEntry : scene.classes.entrySet()) {
                        AClass aClass = classEntry.getValue();
                        for (Map.Entry<String, AMethod> methodEntry : aClass.getMethods().entrySet()) {
                            AMethod aMethod = methodEntry.getValue();
                            List<AnnotationMirror> contractAnnotationMirrors = checker.getTypeFactory().getContractAnnotations(aMethod);
                            List<Annotation> contractAnnotations = CollectionsPlume.mapList(AnnotationConverter::annotationMirrorToAnnotation, contractAnnotationMirrors);
                            aMethod.contracts = contractAnnotations;
                        }
                    }
                    IndexFileWriter.write(scene, new FileWriter(filepath));
                    break;
                default:
                    throw new BugInCF("Unhandled outputFormat " + outputFormat);
            }
        } catch (IOException e) {
            throw new UserError("Problem while writing %s: %s", filepath, e.getMessage());
        } catch (DefException e) {
            throw new BugInCF(e);
        }
    }
}
Also used : AScene(scenelib.annotations.el.AScene) AnnotationConverter(org.checkerframework.common.wholeprograminference.AnnotationConverter) UserError(org.checkerframework.javacutil.UserError) DefException(scenelib.annotations.el.DefException) IndexFileWriter(scenelib.annotations.io.IndexFileWriter) FileWriter(java.io.FileWriter) IOException(java.io.IOException) BugInCF(org.checkerframework.javacutil.BugInCF) Annotation(scenelib.annotations.Annotation) AnnotationMirror(javax.lang.model.element.AnnotationMirror) AClass(scenelib.annotations.el.AClass) File(java.io.File) Map(java.util.Map) AMethod(scenelib.annotations.el.AMethod)

Example 4 with UserError

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

the class GenericAnnotatedTypeFactory method createCFGVisualizer.

/**
 * Create a new CFGVisualizer.
 *
 * @return a new CFGVisualizer, or null if none will be used on this run
 */
@Nullable
protected CFGVisualizer<Value, Store, TransferFunction> createCFGVisualizer() {
    if (checker.hasOption("flowdotdir")) {
        String flowdotdir = checker.getOption("flowdotdir");
        if (flowdotdir.equals("")) {
            throw new UserError("Emtpy string provided for -Aflowdotdir command-line argument");
        }
        boolean verbose = checker.hasOption("verbosecfg");
        Map<String, Object> args = new HashMap<>(2);
        args.put("outdir", flowdotdir);
        args.put("verbose", verbose);
        args.put("checkerName", getCheckerName());
        CFGVisualizer<Value, Store, TransferFunction> res = new DOTCFGVisualizer<>();
        res.init(args);
        return res;
    } else if (checker.hasOption("cfgviz")) {
        String cfgviz = checker.getOption("cfgviz");
        if (cfgviz == null) {
            throw new UserError("-Acfgviz specified without arguments, should be -Acfgviz=VizClassName[,opts,...]");
        }
        String[] opts = cfgviz.split(",");
        String vizClassName = opts[0];
        if (!Signatures.isBinaryName(vizClassName)) {
            throw new UserError("Bad -Acfgviz class name \"%s\", should be a binary name.", vizClassName);
        }
        Map<String, Object> args = processCFGVisualizerOption(opts);
        if (!args.containsKey("verbose")) {
            boolean verbose = checker.hasOption("verbosecfg");
            args.put("verbose", verbose);
        }
        args.put("checkerName", getCheckerName());
        CFGVisualizer<Value, Store, TransferFunction> res = BaseTypeChecker.invokeConstructorFor(vizClassName, null, null);
        res.init(args);
        return res;
    }
    // Nobody expected to use cfgVisualizer if neither option given.
    return null;
}
Also used : UserError(org.checkerframework.javacutil.UserError) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) CFStore(org.checkerframework.framework.flow.CFStore) CFAbstractStore(org.checkerframework.framework.flow.CFAbstractStore) DOTCFGVisualizer(org.checkerframework.dataflow.cfg.visualize.DOTCFGVisualizer) CFGVisualizer(org.checkerframework.dataflow.cfg.visualize.CFGVisualizer) DOTCFGVisualizer(org.checkerframework.dataflow.cfg.visualize.DOTCFGVisualizer) CFAbstractValue(org.checkerframework.framework.flow.CFAbstractValue) CFValue(org.checkerframework.framework.flow.CFValue) FieldInitialValue(org.checkerframework.framework.flow.CFAbstractAnalysis.FieldInitialValue) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Example 5 with UserError

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

the class CFCFGBuilder method build.

/**
 * Build the control flow graph of some code.
 */
public static ControlFlowGraph build(CompilationUnitTree root, UnderlyingAST underlyingAST, BaseTypeChecker checker, AnnotatedTypeFactory factory, ProcessingEnvironment env) {
    boolean assumeAssertionsEnabled = checker.hasOption("assumeAssertionsAreEnabled");
    boolean assumeAssertionsDisabled = checker.hasOption("assumeAssertionsAreDisabled");
    if (assumeAssertionsEnabled && assumeAssertionsDisabled) {
        throw new UserError("Assertions cannot be assumed to be enabled and disabled at the same time.");
    }
    // allow a super-checker to query the stores of a subchecker.
    if (factory instanceof GenericAnnotatedTypeFactory) {
        GenericAnnotatedTypeFactory<?, ?, ?, ?> asGATF = (GenericAnnotatedTypeFactory<?, ?, ?, ?>) factory;
        if (asGATF.hasOrIsSubchecker) {
            ControlFlowGraph sharedCFG = asGATF.getSharedCFGForTree(underlyingAST.getCode());
            if (sharedCFG != null) {
                return sharedCFG;
            }
        }
    }
    CFTreeBuilder builder = new CFTreeBuilder(env);
    PhaseOneResult phase1result = new CFCFGTranslationPhaseOne(builder, checker, factory, assumeAssertionsEnabled, assumeAssertionsDisabled, env).process(root, underlyingAST);
    ControlFlowGraph phase2result = CFGTranslationPhaseTwo.process(phase1result);
    ControlFlowGraph phase3result = CFGTranslationPhaseThree.process(phase2result);
    if (factory instanceof GenericAnnotatedTypeFactory) {
        GenericAnnotatedTypeFactory<?, ?, ?, ?> asGATF = (GenericAnnotatedTypeFactory<?, ?, ?, ?>) factory;
        if (asGATF.hasOrIsSubchecker) {
            asGATF.addSharedCFGForTree(underlyingAST.getCode(), phase3result);
        }
    }
    return phase3result;
}
Also used : GenericAnnotatedTypeFactory(org.checkerframework.framework.type.GenericAnnotatedTypeFactory) UserError(org.checkerframework.javacutil.UserError) ControlFlowGraph(org.checkerframework.dataflow.cfg.ControlFlowGraph) PhaseOneResult(org.checkerframework.dataflow.cfg.builder.PhaseOneResult)

Aggregations

UserError (org.checkerframework.javacutil.UserError)16 IOException (java.io.IOException)4 JavacProcessingEnvironment (com.sun.tools.javac.processing.JavacProcessingEnvironment)3 FileWriter (java.io.FileWriter)3 Map (java.util.Map)3 Nullable (org.checkerframework.checker.nullness.qual.Nullable)3 Context (com.sun.tools.javac.util.Context)2 BufferedWriter (java.io.BufferedWriter)2 File (java.io.File)2 HashMap (java.util.HashMap)2 IdentityHashMap (java.util.IdentityHashMap)2 AnnotationMirror (javax.lang.model.element.AnnotationMirror)2 BugInCF (org.checkerframework.javacutil.BugInCF)2 TypeSystemError (org.checkerframework.javacutil.TypeSystemError)2 AScene (scenelib.annotations.el.AScene)2 ExpressionTree (com.sun.source.tree.ExpressionTree)1 VariableTree (com.sun.source.tree.VariableTree)1 Source (com.sun.tools.javac.code.Source)1 DiagnosticSource (com.sun.tools.javac.util.DiagnosticSource)1 Log (com.sun.tools.javac.util.Log)1