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());
}
}
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);
}
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);
}
}
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);
}
}
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;
}
Aggregations