Search in sources :

Example 36 with BugInCF

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

the class SourceChecker method report.

/**
 * Reports a diagnostic message. By default, it prints it to the screen via the compiler's
 * internal messager; however, it might also store it for later output.
 *
 * @param source the source position information; may be an Element, a Tree, or null
 * @param kind the type of message
 * @param messageKey the message key
 * @param args arguments for interpolation in the string corresponding to the given message key
 */
// Not a format method.  However, messageKey should be either a format string for `args`, or  a
// property key that maps to a format string for `args`.
// @FormatMethod
// arg is a format string or a property key
@SuppressWarnings("formatter:format.string")
private void report(Object source, javax.tools.Diagnostic.Kind kind, @CompilerMessageKey String messageKey, Object... args) {
    assert messagesProperties != null : "null messagesProperties";
    if (shouldSuppressWarnings(source, messageKey)) {
        return;
    }
    if (args != null) {
        for (int i = 0; i < args.length; ++i) {
            args[i] = processArg(args[i]);
        }
    }
    if (kind == Kind.NOTE) {
        System.err.println("(NOTE) " + String.format(messageKey, args));
        return;
    }
    final String defaultFormat = "(" + messageKey + ")";
    String fmtString;
    if (this.processingEnv.getOptions() != null && /*nnbug*/
    this.processingEnv.getOptions().containsKey("nomsgtext")) {
        fmtString = defaultFormat;
    } else if (this.processingEnv.getOptions() != null && /*nnbug*/
    this.processingEnv.getOptions().containsKey("detailedmsgtext")) {
        // The -Adetailedmsgtext command-line option was given, so output
        // a stylized error message for easy parsing by a tool.
        fmtString = detailedMsgTextPrefix(source, defaultFormat, args) + fullMessageOf(messageKey, defaultFormat);
    } else {
        fmtString = "[" + suppressWarningsString(messageKey) + "] " + fullMessageOf(messageKey, defaultFormat);
    }
    String messageText;
    try {
        messageText = String.format(fmtString, args);
    } catch (Exception e) {
        throw new BugInCF("Invalid format string: \"" + fmtString + "\" args: " + Arrays.toString(args), e);
    }
    if (kind == Kind.ERROR && hasOption("warns")) {
        kind = Kind.MANDATORY_WARNING;
    }
    if (source instanceof Element) {
        messager.printMessage(kind, messageText, (Element) source);
    } else if (source instanceof Tree) {
        printOrStoreMessage(kind, messageText, (Tree) source, currentRoot);
    } else {
        throw new BugInCF("invalid position source, class=" + source.getClass());
    }
}
Also used : TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) AnnotationTree(com.sun.source.tree.AnnotationTree) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) BugInCF(org.checkerframework.javacutil.BugInCF) PatternSyntaxException(java.util.regex.PatternSyntaxException) IOException(java.io.IOException)

Example 37 with BugInCF

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

the class AnnotationFileElementTypes method getFakeOverride.

/**
 * Returns the method type of the most specific fake override for the given element, when used as
 * a member of the given type.
 *
 * @param elt element for which annotations are returned
 * @param receiverType the type of the class that contains member (or a subtype of it)
 * @return the most specific AnnotatedTypeMirror for {@code elt} that is a fake override, or null
 *     if there are no fake overrides
 */
@Nullable
public AnnotatedExecutableType getFakeOverride(Element elt, AnnotatedTypeMirror receiverType) {
    if (parsing) {
        throw new BugInCF("parsing while calling getFakeOverride");
    }
    if (elt.getKind() != ElementKind.METHOD) {
        return null;
    }
    ExecutableElement method = (ExecutableElement) elt;
    // This is a list of pairs of (where defined, method type) for fake overrides.  The second
    // element of each pair is currently always an AnnotatedExecutableType.
    List<Pair<TypeMirror, AnnotatedTypeMirror>> candidates = annotationFileAnnos.fakeOverrides.get(method);
    if (candidates == null || candidates.isEmpty()) {
        return null;
    }
    TypeMirror receiverTypeMirror = receiverType.getUnderlyingType();
    // A list of fake receiver types.
    List<TypeMirror> applicableClasses = new ArrayList<>();
    List<TypeMirror> applicableInterfaces = new ArrayList<>();
    for (Pair<TypeMirror, AnnotatedTypeMirror> candidatePair : candidates) {
        TypeMirror fakeLocation = candidatePair.first;
        AnnotatedExecutableType candidate = (AnnotatedExecutableType) candidatePair.second;
        if (factory.types.isSameType(receiverTypeMirror, fakeLocation)) {
            return candidate;
        } else if (factory.types.isSubtype(receiverTypeMirror, fakeLocation)) {
            TypeElement fakeElement = TypesUtils.getTypeElement(fakeLocation);
            switch(fakeElement.getKind()) {
                case CLASS:
                case ENUM:
                    applicableClasses.add(fakeLocation);
                    break;
                case INTERFACE:
                case ANNOTATION_TYPE:
                    applicableInterfaces.add(fakeLocation);
                    break;
                default:
                    throw new BugInCF("What type? %s %s %s", fakeElement.getKind(), fakeElement.getClass(), fakeElement);
            }
        }
    }
    if (applicableClasses.isEmpty() && applicableInterfaces.isEmpty()) {
        return null;
    }
    TypeMirror fakeReceiverType = TypesUtils.mostSpecific(!applicableClasses.isEmpty() ? applicableClasses : applicableInterfaces, factory.getProcessingEnv());
    if (fakeReceiverType == null) {
        StringJoiner message = new StringJoiner(System.lineSeparator());
        message.add(String.format("No most specific fake override found for %s with receiver %s." + " These fake overrides are applicable:", elt, receiverTypeMirror));
        for (TypeMirror candidate : applicableClasses) {
            message.add("  class candidate: " + candidate);
        }
        for (TypeMirror candidate : applicableInterfaces) {
            message.add("  interface candidate: " + candidate);
        }
        throw new BugInCF(message.toString());
    }
    for (Pair<TypeMirror, AnnotatedTypeMirror> candidatePair : candidates) {
        TypeMirror candidateReceiverType = candidatePair.first;
        if (factory.types.isSameType(fakeReceiverType, candidateReceiverType)) {
            return (AnnotatedExecutableType) candidatePair.second;
        }
    }
    throw new BugInCF("No match for %s in %s %s %s", fakeReceiverType, candidates, applicableClasses, applicableInterfaces);
}
Also used : AnnotatedExecutableType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ArrayList(java.util.ArrayList) BugInCF(org.checkerframework.javacutil.BugInCF) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) StringJoiner(java.util.StringJoiner) Pair(org.checkerframework.javacutil.Pair) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Example 38 with BugInCF

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

the class AnnotationFileElementTypes method prepJdkFromJar.

/**
 * Walk through the JDK directory and create a mapping, {@link #jdkStubFilesJar}, from file name
 * to the class contained with in it. Also, parses all package-info.java files.
 *
 * @param resourceURL the URL pointing to the JDK directory
 */
private void prepJdkFromJar(URL resourceURL) {
    JarURLConnection connection = getJarURLConnectionToJdk();
    try (JarFile jarFile = connection.getJarFile()) {
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements(); ) {
            JarEntry jarEntry = e.nextElement();
            // filter out directories and non-class files
            if (!jarEntry.isDirectory() && jarEntry.getName().endsWith(".java") && jarEntry.getName().startsWith("annotated-jdk") && // JavaParser can't parse module-info files, so skip them.
            !jarEntry.getName().contains("module-info")) {
                String jarEntryName = jarEntry.getName();
                if (parseAllJdkFiles) {
                    parseJdkJarEntry(jarEntryName);
                    continue;
                }
                int index = jarEntry.getName().indexOf("/share/classes/");
                String shortName = jarEntryName.substring(index + "/share/classes/".length()).replace(".java", "").replace('/', '.');
                jdkStubFilesJar.put(shortName, jarEntryName);
                if (jarEntryName.endsWith("package-info.java")) {
                    parseJdkJarEntry(jarEntryName);
                }
            }
        }
    } catch (IOException e) {
        throw new BugInCF("cannot open the Jar file " + resourceURL.getFile(), e);
    }
}
Also used : JarURLConnection(java.net.JarURLConnection) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) BugInCF(org.checkerframework.javacutil.BugInCF)

Example 39 with BugInCF

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

the class AnnotationFileElementTypes method prepJdkFromFile.

/**
 * Walk through the JDK directory and create a mapping, {@link #jdkStubFiles}, from file name to
 * the class contained with in it. Also, parses all package-info.java files.
 *
 * @param resourceURL the URL pointing to the JDK directory
 */
private void prepJdkFromFile(URL resourceURL) {
    Path root;
    try {
        root = Paths.get(resourceURL.toURI());
    } catch (URISyntaxException e) {
        throw new BugInCF("Can parse URL: " + resourceURL.toString(), e);
    }
    try (Stream<Path> walk = Files.walk(root)) {
        List<Path> paths = walk.filter(p -> Files.isRegularFile(p) && p.toString().endsWith(".java")).collect(Collectors.toList());
        for (Path path : paths) {
            if (path.getFileName().toString().equals("package-info.java")) {
                parseJdkStubFile(path);
                continue;
            }
            if (path.getFileName().toString().equals("module-info.java")) {
                // JavaParser can't parse module-info files, so skip them.
                continue;
            }
            if (parseAllJdkFiles) {
                parseJdkStubFile(path);
                continue;
            }
            Path relativePath = root.relativize(path);
            // 4: /src/<module>/share/classes
            Path savepath = relativePath.subpath(4, relativePath.getNameCount());
            String s = savepath.toString().replace(".java", "").replace(File.separatorChar, '.');
            jdkStubFiles.put(s, path);
        }
    } catch (IOException e) {
        throw new BugInCF("prepJdkFromFile(" + resourceURL + ")", e);
    }
}
Also used : Path(java.nio.file.Path) ClassGraph(io.github.classgraph.ClassGraph) Arrays(java.util.Arrays) BugInCF(org.checkerframework.javacutil.BugInCF) Enumeration(java.util.Enumeration) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) JarFile(java.util.jar.JarFile) TypeElement(javax.lang.model.element.TypeElement) Map(java.util.Map) URI(java.net.URI) JarURLConnection(java.net.JarURLConnection) Pair(org.checkerframework.javacutil.Pair) Path(java.nio.file.Path) AnnotatedExecutableType(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType) AnnotationFileAnnotations(org.checkerframework.framework.stub.AnnotationFileParser.AnnotationFileAnnotations) Set(java.util.Set) Element(javax.lang.model.element.Element) Types(javax.lang.model.util.Types) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) Collectors(java.util.stream.Collectors) AnnotationFileType(org.checkerframework.framework.stub.AnnotationFileUtil.AnnotationFileType) List(java.util.List) Stream(java.util.stream.Stream) StubFiles(org.checkerframework.framework.qual.StubFiles) TypesUtils(org.checkerframework.javacutil.TypesUtils) SourceChecker(org.checkerframework.framework.source.SourceChecker) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CanonicalNameOrEmpty(org.checkerframework.checker.signature.qual.CanonicalNameOrEmpty) JarEntry(java.util.jar.JarEntry) RecordComponentStub(org.checkerframework.framework.stub.AnnotationFileParser.RecordComponentStub) Kind(javax.tools.Diagnostic.Kind) Nullable(org.checkerframework.checker.nullness.qual.Nullable) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) ElementKind(javax.lang.model.element.ElementKind) Files(java.nio.file.Files) ExecutableElement(javax.lang.model.element.ExecutableElement) IOException(java.io.IOException) BaseTypeChecker(org.checkerframework.common.basetype.BaseTypeChecker) FileInputStream(java.io.FileInputStream) AnnotationMirror(javax.lang.model.element.AnnotationMirror) SystemUtil(org.checkerframework.javacutil.SystemUtil) File(java.io.File) AnnotatedTypeFactory(org.checkerframework.framework.type.AnnotatedTypeFactory) TypeMirror(javax.lang.model.type.TypeMirror) Paths(java.nio.file.Paths) StringJoiner(java.util.StringJoiner) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) Collections(java.util.Collections) ElementUtils(org.checkerframework.javacutil.ElementUtils) InputStream(java.io.InputStream) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) BugInCF(org.checkerframework.javacutil.BugInCF)

Example 40 with BugInCF

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

the class GenericAnnotatedTypeFactory method getPreconditionAnnotations.

/**
 * Return the precondition annotations for the given AMethod. Does not modify the AMethod. This
 * method must only be called when using WholeProgramInferenceScenes.
 *
 * @param m AFU representation of a method
 * @return precondition annotations for the method
 */
public List<AnnotationMirror> getPreconditionAnnotations(AMethod m) {
    List<AnnotationMirror> result = new ArrayList<>(m.getPreconditions().size());
    for (Map.Entry<String, AField> entry : m.getPreconditions().entrySet()) {
        WholeProgramInferenceImplementation<?> wholeProgramInference = (WholeProgramInferenceImplementation<?>) getWholeProgramInference();
        WholeProgramInferenceScenesStorage storage = (WholeProgramInferenceScenesStorage) wholeProgramInference.getStorage();
        TypeMirror typeMirror = entry.getValue().getTypeMirror();
        if (typeMirror == null) {
            throw new BugInCF("null TypeMirror in AField inferred by WPI precondition inference. AField: " + entry.getValue().toString());
        }
        AnnotatedTypeMirror declaredType = storage.getPreconditionDeclaredType(m, entry.getKey());
        AnnotatedTypeMirror inferredType = storage.atmFromStorageLocation(typeMirror, entry.getValue().type);
        result.addAll(getPreconditionAnnotations(entry.getKey(), inferredType, declaredType));
    }
    Collections.sort(result, Ordering.usingToString());
    return result;
}
Also used : WholeProgramInferenceImplementation(org.checkerframework.common.wholeprograminference.WholeProgramInferenceImplementation) ArrayList(java.util.ArrayList) WholeProgramInferenceScenesStorage(org.checkerframework.common.wholeprograminference.WholeProgramInferenceScenesStorage) BugInCF(org.checkerframework.javacutil.BugInCF) AField(scenelib.annotations.el.AField) AnnotationMirror(javax.lang.model.element.AnnotationMirror) TypeMirror(javax.lang.model.type.TypeMirror) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap)

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