Java Code Examples for javax.tools.Diagnostic

The following are top voted examples for showing how to use javax.tools.Diagnostic. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: javaide   File: SpanUtil.java   View source code 6 votes vote down vote up
public static Spannable createSrcSpan(Resources resources, @NonNull Diagnostic diagnostic) {
    if (diagnostic.getSource() == null) {
        return new SpannableString("Unknown");
    }
    if (!(diagnostic.getSource() instanceof JavaFileObject)) {
        return new SpannableString(diagnostic.getSource().toString());
    }
    try {
        JavaFileObject source = (JavaFileObject) diagnostic.getSource();
        File file = new File(source.getName());
        String name = file.getName();
        String line = diagnostic.getLineNumber() + ":" + diagnostic.getColumnNumber();
        SpannableString span = new SpannableString(name + ":" + line);
        span.setSpan(new ForegroundColorSpan(resources.getColor(R.color.dark_color_diagnostic_file)),
                0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return span;
    } catch (Exception e) {

    }
    return new SpannableString(diagnostic.getSource().toString());
}
 
Example 2
Project: openapi-annotation-processor   File: OpenAPIProcessor.java   View source code 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    boolean lastRound = roundEnv.processingOver();
    if (lastRound) {
        LOG.debug("Processing last round");
    } else {
        LOG.debug("Processing");
    }
    AtomicReference<Element> currentAnnotatedElement = new AtomicReference<>();
    try {
        doProcess(roundEnv, currentAnnotatedElement, new RoundDescriptor(roundNumber.incrementAndGet(), lastRound));
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage(), currentAnnotatedElement.get());
    }
    return true;
}
 
Example 3
Project: auto-nav   File: NavProcessor.java   View source code 6 votes vote down vote up
private ActivityIntentModel getActivityModel(TypeElement typeElement) {
    ActivityIntentModel activityModel = new ActivityIntentModel(
            elementsUtil.getPackageOf(typeElement).getQualifiedName().toString(),
            typeElement.getSimpleName().toString());

    messager.printMessage(Diagnostic.Kind.NOTE, "\ntype:" + typeElement.getQualifiedName());

    activityModel.addParamModels(getParamModels(typeElement));

    TypeMirror superType = typeElement.getSuperclass();

    while (superType != null && !Object.class.getName().equals(superType.toString())) {
        messager.printMessage(Diagnostic.Kind.NOTE, "\n   superType:" + superType.toString());
        Element element = typesUtil.asElement(superType);
        if (element != null && element instanceof TypeElement) {
            TypeElement superE = (TypeElement) element;
            activityModel.addParamModels(getParamModels(superE));

            superType = superE.getSuperclass();
        } else {
            superType = null;
        }
    }

    return activityModel;
}
 
Example 4
Project: openjdk-jdk10   File: JavacParserTest.java   View source code 6 votes vote down vote up
@Test
void testVariableInIfThen1() throws IOException {

    String code = "package t; class Test { " +
            "private static void t(String name) { " +
            "if (name != null) String nn = name.trim(); } }";

    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen1",
            Arrays.<String>asList("compiler.err.variable.not.allowed"),
            codes);
}
 
Example 5
Project: prefpin   File: PrefPinProcessor.java   View source code 6 votes vote down vote up
private void parsePreferenceBinding(RoundEnvironment roundEnv,
    Map<TypeElement, Set<Element>> bindingMap, Class<? extends Annotation> annotation) {
  for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) {
    if (element.getModifiers().contains(Modifier.PRIVATE)) {
      processingEnv.getMessager()
          .printMessage(Diagnostic.Kind.ERROR,
              "Binding annotation can not applied to private fields or methods.", element);
    }

    if (annotation == BindPref.class) {
      checkPreferenceAnnotation(element);
    }

    TypeElement targetPrefFragment = (TypeElement) element.getEnclosingElement();
    if (bindingMap.containsKey(targetPrefFragment)) {
      bindingMap.get(targetPrefFragment).add(element);
    } else {
      Set<Element> fields = new LinkedHashSet<>();
      fields.add(element);
      bindingMap.put(targetPrefFragment, fields);
    }
  }
}
 
Example 6
Project: immu   File: ImmuCompilerTest.java   View source code 6 votes vote down vote up
@Test
public void write_withIOException() throws Exception {
  final ProcessingEnvironment env = mock(ProcessingEnvironment.class);
  final Messager messager = mock(Messager.class);
  final Filer filer = mock(Filer.class);

  when(env.getMessager()).thenReturn(messager);
  when(env.getFiler()).thenReturn(filer);

  compiler.init(env);

  final JavaFile javaFile = mock(JavaFile.class);
  doThrow(IOException.class).when(javaFile).writeTo(any(Filer.class));

  compiler.writeSource(javaFile);

  verify(messager, times(1)).printMessage(eq(Diagnostic.Kind.ERROR), any());
}
 
Example 7
Project: incubator-netbeans   File: UtilitiesTest.java   View source code 6 votes vote down vote up
public void testLambdaPattern() throws Exception {
    prepareTest("test/Test.java", "package test; public class Test{}");

    Scope s = Utilities.constructScope(info, Collections.<String, TypeMirror>emptyMap());
    Tree result = Utilities.parseAndAttribute(info, "new $type() {\n $mods$ $resultType $methodName($args$) {\n $statements$;\n }\n }\n", s);

    assertTrue(result.getKind().name(), result.getKind() == Kind.NEW_CLASS);

    String golden = "new $type(){ $mods$ $resultType $methodName($args$) { $statements$; } }";
    assertEquals(golden.replaceAll("[ \n\r]+", " "), result.toString().replaceAll("[ \n\r]+", " "));

    Collection<Diagnostic<? extends JavaFileObject>> errors = new LinkedList<Diagnostic<? extends JavaFileObject>>();

    result = Utilities.parseAndAttribute(info, "new $type() {\n $mods$ $resultType $methodName($args$) {\n $statements$;\n }\n }\n", null, errors);
    assertTrue(result.getKind().name(), result.getKind() == Kind.NEW_CLASS);

    golden = "new $type(){ $mods$ $resultType $methodName($args$) { $statements$; } }";
    assertEquals(golden.replaceAll("[ \n\r]+", " "), result.toString().replaceAll("[ \n\r]+", " "));
    assertTrue(errors.toString(), errors.isEmpty());
}
 
Example 8
Project: GitHub   File: EventBusAnnotationProcessor.java   View source code 6 votes vote down vote up
private boolean checkHasNoErrors(ExecutableElement element, Messager messager) {
    if (element.getModifiers().contains(Modifier.STATIC)) {
        messager.printMessage(Diagnostic.Kind.ERROR, "Subscriber method must not be static", element);
        return false;
    }

    if (!element.getModifiers().contains(Modifier.PUBLIC)) {
        messager.printMessage(Diagnostic.Kind.ERROR, "Subscriber method must be public", element);
        return false;
    }

    List<? extends VariableElement> parameters = ((ExecutableElement) element).getParameters();
    if (parameters.size() != 1) {
        messager.printMessage(Diagnostic.Kind.ERROR, "Subscriber method must have exactly 1 parameter", element);
        return false;
    }
    return true;
}
 
Example 9
Project: GitHub   File: MvpCompiler.java   View source code 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
	if (annotations.isEmpty()) {
		return false;
	}

	try {
		return throwableProcess(roundEnv);
	} catch (RuntimeException e) {
		getMessager().printMessage(Diagnostic.Kind.OTHER, "Moxy compilation failed. Could you copy stack trace above and write us (or make issue on Githhub)?");
		e.printStackTrace();
		getMessager().printMessage(Diagnostic.Kind.ERROR, "Moxy compilation failed; see the compiler error output for details (" + e + ")");
	}

	return true;
}
 
Example 10
Project: AptSpring   File: VerifiedSpringConfiguration.java   View source code 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
  try  {
    if (env.processingOver()) {
      definitionAggregator.outputErrors(messager);
    } else {
      AptElementVisitor visitor = new AptElementVisitor(te -> new SpringAnnotationParser().extractDefinition(te, messager));
      for (Element annotatedElement : env.getElementsAnnotatedWith(Verified.class)) {
        visitor.visit(annotatedElement, definitionAggregator);        
      }
    }
    return true;
  } catch (Exception exception) {
    // Catch and print for debugging reasons. This code path is unexpected.
    StringWriter writer = new StringWriter();
    exception.printStackTrace(new PrintWriter(writer));
    messager.printMessage(Diagnostic.Kind.ERROR, writer.toString());
    return true;
  }
}
 
Example 11
Project: manifold   File: ExtCodeGen.java   View source code 6 votes vote down vote up
private boolean warnIfDuplicate( AbstractSrcMethod method, SrcClass extendedType, DiagnosticListener<JavaFileObject> errorHandler, JavacTaskImpl javacTask )
{
  AbstractSrcMethod duplicate = findMethod( method, extendedType, new JavacTaskImpl[]{javacTask} );

  if( duplicate == null )
  {
    return false;
  }

  JavacElements elems = JavacElements.instance( javacTask.getContext() );
  Symbol.ClassSymbol sym = elems.getTypeElement( ((SrcClass)method.getOwner()).getName() );
  JavaFileObject file = sym.sourcefile;
  SrcAnnotationExpression anno = duplicate.getAnnotation( ExtensionMethod.class );
  if( anno != null )
  {
    errorHandler.report( new JavacDiagnostic( file.toUri().getScheme() == null ? null : new SourceJavaFileObject( file.toUri() ),
                                              Diagnostic.Kind.WARNING, 0, 0, 0, ExtIssueMsg.MSG_EXTENSION_DUPLICATION.get( method.signature(), ((SrcClass)method.getOwner()).getName(), anno.getArgument( ExtensionMethod.extensionClass ).getValue()) ) );
  }
  else
  {
    errorHandler.report( new JavacDiagnostic( file.toUri().getScheme() == null ? null : new SourceJavaFileObject( file.toUri() ),
                                              Diagnostic.Kind.WARNING, 0, 0, 0, ExtIssueMsg.MSG_EXTENSION_SHADOWS.get( method.signature(), ((SrcClass)method.getOwner()).getName(), extendedType.getName()) ) );
  }
  return true;
}
 
Example 12
Project: annotation-processor-toolkit   File: AnnotationProcessorWrapper.java   View source code 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

    // now set note message before calling the processor
    messager.printMessage(Diagnostic.Kind.NOTE, AbstractAnnotationProcessorTest.TEST_EXECUTION_MESSAGE);

    return wrappedProcessor.process(annotations, roundEnv);
}
 
Example 13
Project: OpenJSharp   File: Messages.java   View source code 5 votes vote down vote up
protected void report(Group group, Diagnostic.Kind dkind, DocTree tree, String code, Object... args) {
    if (options.isEnabled(group, env.currAccess)) {
        String msg = (code == null) ? (String) args[0] : localize(code, args);
        env.trees.printMessage(dkind, msg, tree,
                env.currDocComment, env.currPath.getCompilationUnit());

        stats.record(group, dkind, code);
    }
}
 
Example 14
Project: javaide   File: AbstractProcessor.java   View source code 5 votes vote down vote up
/**
 * If the processor class is annotated with {@link
 * SupportedAnnotationTypes}, return an unmodifiable set with the
 * same set of strings as the annotation.  If the class is not so
 * annotated, an empty set is returned.
 *
 * @return the names of the annotation types supported by this
 * processor, or an empty set if none
 */
public Set<String> getSupportedAnnotationTypes() {
        SupportedAnnotationTypes sat = this.getClass().getAnnotation(SupportedAnnotationTypes.class);
        if  (sat == null) {
            if (isInitialized())
                processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING,
                                                         "No SupportedAnnotationTypes annotation " +
                                                         "found on " + this.getClass().getName() +
                                                         ", returning an empty set.");
            return Collections.emptySet();
        }
        else
            return arrayToSet(sat.value());
    }
 
Example 15
Project: openjdk-jdk10   File: UnusedResourcesTest.java   View source code 5 votes vote down vote up
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
    if (diagnostic.getKind() == Diagnostic.Kind.WARNING &&
            diagnostic.getCode().contains("try.resource.not.referenced")) {
        String varName = unwrap(diagnostic).getArgs()[0].toString();
        if (varName.equals(TwrStmt.TWR1.resourceName)) {
            unused_r1 = true;
        } else if (varName.equals(TwrStmt.TWR2.resourceName)) {
            unused_r2 = true;
        } else if (varName.equals(TwrStmt.TWR3.resourceName)) {
            unused_r3 = true;
        }
    }
}
 
Example 16
Project: guava-beta-checker   File: TestCompiler.java   View source code 5 votes vote down vote up
/**
 * Compiles the given {@code sources} and returns a list of diagnostics produced by the compiler.
 */
public List<Diagnostic<? extends JavaFileObject>> compile(
    Iterable<? extends JavaFileObject> sources) {
  ScannerSupplier scannerSupplier = ScannerSupplier.fromBugCheckerClasses(checker);
  DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<>();
  JavaCompiler compiler = new BaseErrorProneJavaCompiler(scannerSupplier);
  File tmpDir = Files.createTempDir();
  CompilationTask task =
      compiler.getTask(
          new PrintWriter(System.err, true),
          null /*filemanager*/,
          collector,
          ImmutableList.of("-d", tmpDir.getAbsolutePath()),
          null /*classes*/,
          sources);
  try {
    task.call();
    return collector.getDiagnostics();
  } finally {
    File[] files = tmpDir.listFiles();
    if (files != null) {
      for (File file : files) {
        file.delete();
      }
    }
    tmpDir.delete();
  }
}
 
Example 17
Project: domino   File: ServerModuleAnnotationProcessor.java   View source code 5 votes vote down vote up
private void generateServerModule(ProcessorElement processorElement, List<ProcessorElement> handlers,
                                  List<ProcessorElement> interceptors, List<ProcessorElement> globalInterceptors) {
    try (Writer sourceWriter = obtainSourceWriter(processorElement.elementPackage(), processorElement.getAnnotation(ServerModule.class).name() + "ServerModule")) {
        sourceWriter.write(new ServerModuleSourceWriter(processorElement, handlers, interceptors, globalInterceptors).write());
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Could not generate classes : ", e);
        messager.printMessage(Diagnostic.Kind.ERROR, "could not generate class");
    }
}
 
Example 18
Project: remoter   File: RemoterProcessor.java   View source code 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
    for (Element element : env.getElementsAnnotatedWith(Remoter.class)) {
        if (element.getKind() == ElementKind.INTERFACE) {
            bindingManager.generateProxy(element);
            bindingManager.generateStub(element);
        } else {
            messager.printMessage(Diagnostic.Kind.WARNING, "@Remoter is expected only for interface. Ignoring " + element.getSimpleName());
        }
    }
    return false;
}
 
Example 19
Project: manifold   File: JavascriptCodeGen.java   View source code 5 votes vote down vote up
private void reportErrors( DiagnosticListener<JavaFileObject> errorHandler, ProgramNode programNode )
{
  if( programNode.errorCount() > 0 )
  {
    JavaFileObject file = new SourceJavaFileObject( _file.toURI() );
    for( ParseError error : programNode.getErrorList() )
    {
      Token token = error.getToken();
      errorHandler.report( new JavacDiagnostic( file, Diagnostic.Kind.ERROR, token.getOffset(), token.getLineNumber(), token.getCol(), error.getMessage() ) );
    }
  }
}
 
Example 20
Project: incubator-netbeans   File: CompilationInfoImpl.java   View source code 5 votes vote down vote up
@Override
public void report(Diagnostic<? extends JavaFileObject> message) {
    if (partialReparseErrors != null) {
        if (this.jfo != null && this.jfo == message.getSource()) {
            partialReparseErrors.add(message);
            if (message.getKind() == Kind.ERROR) {
                partialReparseRealErrors = true;
            }
        }
    } else {
        Diagnostics errors = getErrors(message.getSource());
        errors.add((int) message.getPosition(), message);
    }
}
 
Example 21
Project: openjdk-jdk10   File: Example.java   View source code 5 votes vote down vote up
private JCDiagnostic unwrap(Diagnostic<? extends JavaFileObject> diagnostic) {
    if (diagnostic instanceof JCDiagnostic)
        return (JCDiagnostic) diagnostic;
    if (diagnostic instanceof ClientCodeWrapper.DiagnosticSourceUnwrapper)
        return ((ClientCodeWrapper.DiagnosticSourceUnwrapper)diagnostic).d;
    throw new IllegalArgumentException();
}
 
Example 22
Project: java-code-templates   File: AstSubstitutionProcessor.java   View source code 5 votes vote down vote up
void clearSubstitutions() {
	if (!substitutionStack.isEmpty()) {
		messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING,
				String.format("Substitution stack cleared while %d elements remained", substitutionStack.size()),
				substitutionInventory.typeElement());
	}
	substitutionStack.clear();
}
 
Example 23
Project: incubator-netbeans   File: DiagnosticListenerImpl.java   View source code 5 votes vote down vote up
public void report(Diagnostic<? extends JavaFileObject> d) {
    assert logDiagnostic(d);

    JavaFileObject source = d.getSource();

    if (source != null) {
        List<Diagnostic<? extends JavaFileObject>> current = diagnostics.get(source.toUri());

        if (current == null) {
            diagnostics.put(source.toUri(), current = new LinkedList<Diagnostic<? extends JavaFileObject>>());
        }

        current.add(d);
    }
}
 
Example 24
Project: javaide   File: FormattingJavaFileObject.java   View source code 5 votes vote down vote up
@Override
public Writer openWriter() throws IOException {
  final StringBuilder stringBuilder = new StringBuilder(DEFAULT_FILE_SIZE);
  return new Writer() {
    @Override
    public void write(char[] chars, int start, int end) throws IOException {
      stringBuilder.append(chars, start, end - start);
    }

    @Override
    public void flush() throws IOException {}

    @Override
    public void close() throws IOException {
      try {
        formatter.formatSource(
            CharSource.wrap(stringBuilder),
            new CharSink() {
              @Override
              public Writer openStream() throws IOException {
                return fileObject.openWriter();
              }
            });
      } catch (FormatterException e) {
        // An exception will happen when the code being formatted has an error. It's better to
        // log the exception and emit unformatted code so the developer can view the code which
        // caused a problem.
        try (Writer writer = fileObject.openWriter()) {
          writer.append(stringBuilder.toString());
        }
        if (messager != null) {
          messager.printMessage(Diagnostic.Kind.NOTE, "Error formatting " + getName());
        }
      }
    }
  };
}
 
Example 25
Project: openjdk-jdk10   File: TaskFactory.java   View source code 5 votes vote down vote up
DiagList getDiagnostics() {
    if (diags == null) {
        LinkedHashMap<String, Diag> diagMap = new LinkedHashMap<>();
        for (Diagnostic<? extends JavaFileObject> in : diagnostics.getDiagnostics()) {
            Diag d = diag(in);
            String uniqueKey = d.getCode() + ":" + d.getPosition() + ":" + d.getMessage(PARSED_LOCALE);
            diagMap.put(uniqueKey, d);
        }
        diags = new DiagList(diagMap.values());
    }
    return diags;
}
 
Example 26
Project: jdoocsoup   File: JDoocsSoupAnnotationProcessor.java   View source code 5 votes vote down vote up
private void createJavaFile(String packageName, TypeSpec typeSpec) {
    try {
        JavaFile javaFile = JavaFile.builder(packageName, typeSpec)
                .build();
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException ex) {
        processingEnv.getMessager()
                .printMessage(Diagnostic.Kind.ERROR, "It was not possible to generate java files due to an error: \n" + ex.getMessage());
    }
}
 
Example 27
Project: domino   File: ContributionsCollector.java   View source code 5 votes vote down vote up
private boolean addContribution(ProcessorElement c) {
    if(!c.isImplementsGenericInterface(Contribution.class)) {
        messager.printMessage(Diagnostic.Kind.ERROR, "Not implementing contribution interface", c.getElement());
        throw new NotImplementingContributionInterfaceException();
    }
    return contributions
            .add(c.fullQualifiedNoneGenericName() + ":" +
                    getContributionExtensionPoint(c));
}
 
Example 28
Project: Coconut-IDE   File: HighlightCell.java   View source code 5 votes vote down vote up
private static TreeItem<Path> isCurrTreeItem(Diagnostic diagnostic) {
    JavaFileObject javaFileObject = (JavaFileObject) diagnostic.getSource();
    Optional<TreeItem<Path>> item = treeItems.parallelStream()
            .filter(c -> javaFileObject.getName().equals(c.getValue().toString()))
            .findFirst();

    if (item.isPresent()) {
        TreeItem<Path> treeItem = item.get();
        treeItems.remove(treeItem);
        return treeItem;
    }

    return null;
}
 
Example 29
Project: incubator-netbeans   File: Utilities.java   View source code 5 votes vote down vote up
private static Token<JavaTokenId> createHighlightImpl(CompilationInfo info, Document doc, TreePath tree) {
    Tree leaf = tree.getLeaf();
    SourcePositions positions = info.getTrees().getSourcePositions();
    CompilationUnitTree cu = info.getCompilationUnit();
    
    //XXX: do not use instanceof:
    if (leaf instanceof MethodTree || leaf instanceof VariableTree || leaf instanceof ClassTree
            || leaf instanceof MemberSelectTree || leaf instanceof AnnotatedTypeTree || leaf instanceof MemberReferenceTree) {
        return findIdentifierSpan(info, doc, tree);
    }
    
    int start = (int) positions.getStartPosition(cu, leaf);
    int end = (int) positions.getEndPosition(cu, leaf);
    
    if (start == Diagnostic.NOPOS || end == Diagnostic.NOPOS) {
        return null;
    }
    
    TokenHierarchy<?> th = info.getTokenHierarchy();
    TokenSequence<JavaTokenId> ts = th.tokenSequence(JavaTokenId.language());
    
    if (ts.move(start) == Integer.MAX_VALUE) {
        return null;
    }
    
    if (ts.moveNext()) {
        Token<JavaTokenId> token = ts.token();
        if (ts.offset() == start && token != null) {
            final JavaTokenId id = token.id();
            if (id == JavaTokenId.IDENTIFIER) {
                return token;
            }
            if (id == JavaTokenId.THIS || id == JavaTokenId.SUPER) {
                return ts.offsetToken();
            }
        }
    }
    
    return null;
}
 
Example 30
Project: incubator-netbeans   File: JavaCompletionTask.java   View source code 5 votes vote down vote up
private void insideAssignment(Env env) throws IOException {
    int offset = env.getOffset();
    TreePath path = env.getPath();
    AssignmentTree as = (AssignmentTree) path.getLeaf();
    SourcePositions sourcePositions = env.getSourcePositions();
    CompilationUnitTree root = env.getRoot();
    int asTextStart = (int) sourcePositions.getEndPosition(root, as.getVariable());
    if (asTextStart != Diagnostic.NOPOS) {
        Tree expr = unwrapErrTree(as.getExpression());
        if (expr == null || offset <= (int) sourcePositions.getStartPosition(root, expr)) {
            CompilationController controller = env.getController();
            String asText = controller.getText().substring(asTextStart, offset);
            int eqPos = asText.indexOf('='); //NOI18N
            if (eqPos > -1) {
                TreePath parentPath = path.getParentPath();
                if (parentPath.getLeaf().getKind() != Tree.Kind.ANNOTATION) {
                    localResult(env);
                    addValueKeywords(env);
                } else if (as.getVariable().getKind() == Tree.Kind.IDENTIFIER) {
                    insideAnnotationAttribute(env, parentPath, ((IdentifierTree) as.getVariable()).getName());
                    addLocalConstantsAndTypes(env);
                }
            }
        } else {
            insideExpression(env, new TreePath(path, expr));
        }
    }
}
 
Example 31
Project: openjdk-jdk10   File: ClassesTest.java   View source code 5 votes vote down vote up
public void classesIgnoredModifiersAnnotation() {
    assertEval("public @interface X { }");
    assertEval("@X public interface A { }");
    assertDeclareWarn1("@X static class B implements A { }",
            new ExpectedDiagnostic("jdk.eval.warn.illegal.modifiers", 0, 9, 0, -1, -1, Diagnostic.Kind.WARNING));
    assertDeclareWarn1("@X final interface C extends A { }",
            new ExpectedDiagnostic("jdk.eval.warn.illegal.modifiers", 0, 8, 0, -1, -1, Diagnostic.Kind.WARNING));
    assertActiveKeys();
}
 
Example 32
Project: mcc   File: CompilerErrorTest.java   View source code 5 votes vote down vote up
@Test
public void testTaskListError() {

    SourceTask sourceTask = new SourceTask();
    sourceTask.createSourceClass("teste", "Teste0", "package teste; public class Teste0 {}");
    sourceTask.createSourceClass("teste", "Teste1", "public class Teste0 {}");
    sourceTask.createSourceClass("teste", "Teste2", "package teste; public class Teste2 {}");

    MemoryClassCompiler compiler = new MemoryClassCompiler();

    boolean throwError = false;

    try {
        compiler.compile(sourceTask);
    } catch (MemoryCompilerException ex) {
        Assert.assertEquals(sourceTask.getSourcesClass().size(), 3);
        SourceClass sourceClass1 = sourceTask.findSourceClass("teste.Teste0");
        Assert.assertNull(sourceClass1.getBytecode());
        SourceClass sourceClass2 = sourceTask.findSourceClass("teste.Teste1");
        Assert.assertNull(sourceClass2.getBytecode());
        SourceClass sourceClass3 = sourceTask.findSourceClass("teste.Teste2");
        Assert.assertNull(sourceClass3.getBytecode());

        Assert.assertEquals(ex.getMessageCompiler().getMessage(), "Error in compilation of class");
        Assert.assertEquals(ex.getMessageCompiler().getStatus(), MessageStatus.FAILED);
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getCode(), "compiler.err.class.public.should.be.in.file");
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getColumnNumber(), 8);
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getEndPosition(), 22);
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getLineNumber(), 1);
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getMessage(null), "class Teste0 is public, should be declared in a file named Teste0.java");
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getPosition(), 7);
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getStartPosition(), 0);
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getKind(), Diagnostic.Kind.ERROR);
        throwError = true;
    }
    Assert.assertTrue(throwError);
}
 
Example 33
Project: OpenJSharp   File: WebServiceAp.java   View source code 5 votes vote down vote up
@Override
public void processWarning(String message) {
    if (isCommandLineInvocation) {
        processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, message);
    } else {
        report(message);
    }
}
 
Example 34
Project: jtsgen   File: TsGenProcessor.java   View source code 5 votes vote down vote up
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    try {
        LOG.log(INFO, () -> String.format("P: Processing Annotations %s (isOver=%b)", annotations, roundEnv.processingOver()));
        if (roundEnv.processingOver() && !roundEnv.errorRaised()) {
            LOG.info(() -> "P: processing over. Start rendering.");
            new TSRenderer(processingEnv, typeScriptModel).writeFiles();
        } else if (roundEnv.processingOver() && roundEnv.errorRaised()) {
            LOG.info(() -> "P: processing over. error raised. nothing to do");
        } else {
            PROCESSING_ORDER.forEach(
                    (x) -> {
                        final Optional<? extends TypeElement> annotation = annotations
                                .stream()
                                .filter((y) -> y.getSimpleName().contentEquals(x.getSimpleName()))
                                .findFirst();
                        LOG.finest(() -> String.format("P: Annotation %s member %s", x, annotation.isPresent()));
                        annotation.ifPresent(typeElement -> processElements(typeElement, roundEnv));
                    }
            );
        }
    } catch (Exception e) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "internal error in jtsgen " + e);
        System.err.println("FATAL error in jtsgen. Please file an issue with the following stack trace @ https://github.com/dzuvic/jtsgen/issues");
        e.printStackTrace();
    }

    return true;
}
 
Example 35
Project: incubator-netbeans   File: UtilitiesTest.java   View source code 5 votes vote down vote up
public void testErrorsForPatterns1() throws Exception {
    prepareTest("test/Test.java", "package test; public class Test{}");

    SourcePositions[] positions = new SourcePositions[1];
    Collection<Diagnostic<? extends JavaFileObject>> errors = new LinkedList<Diagnostic<? extends JavaFileObject>>();
    String code = "foo bar";
    Tree result = Utilities.parseAndAttribute(info, code, null, positions, errors);

    assertDiagnostics(errors, "7-7:compiler.err.expected");
    assertPositions(result, positions[0], code, "foo", "foo bar");
}
 
Example 36
Project: openjdk-jdk10   File: UnusedResourcesTest.java   View source code 5 votes vote down vote up
private JCDiagnostic unwrap(Diagnostic<? extends JavaFileObject> diagnostic) {
    if (diagnostic instanceof JCDiagnostic)
        return (JCDiagnostic) diagnostic;
    if (diagnostic instanceof ClientCodeWrapper.DiagnosticSourceUnwrapper)
        return ((ClientCodeWrapper.DiagnosticSourceUnwrapper)diagnostic).d;
    throw new IllegalArgumentException();
}
 
Example 37
Project: shortbread   File: ShortcutProcessor.java   View source code 5 votes vote down vote up
private void error(Element element, String message, Object... args) {
    if (args.length > 0) {
        message = String.format(message, args);
    }

    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message, element);
}
 
Example 38
Project: incubator-netbeans   File: BaseTask.java   View source code 5 votes vote down vote up
List<Tree> getArgumentsUpToPos(Env env, Iterable<? extends ExpressionTree> args, int startPos, int position, boolean strict) {
    List<Tree> ret = new ArrayList<>();
    CompilationUnitTree root = env.getRoot();
    SourcePositions sourcePositions = env.getSourcePositions();
    if (args == null) {
        return null; //TODO: member reference???
    }
    for (ExpressionTree e : args) {
        int pos = (int) sourcePositions.getEndPosition(root, e);
        if (pos != Diagnostic.NOPOS && (position > pos || !strict && position == pos)) {
            startPos = pos;
            ret.add(e);
        } else {
            break;
        }
    }
    if (startPos < 0) {
        return ret;
    }
    if (position >= startPos) {
        TokenSequence<JavaTokenId> last = findLastNonWhitespaceToken(env, startPos, position);
        if (last == null) {
            if (!strict && !ret.isEmpty()) {
                ret.remove(ret.size() - 1);
                return ret;
            }
        } else if (last.token().id() == JavaTokenId.LPAREN || last.token().id() == JavaTokenId.COMMA) {
            return ret;
        }
    }
    return null;
}
 
Example 39
Project: javaide   File: CompileJavaTask.java   View source code 5 votes vote down vote up
@Override
protected Integer doInBackground(JavaProjectFolder... params) {
    if (params[0] == null) return null;
    this.projectFile = params[0];
    DiagnosticListener listener = new DiagnosticListener() {
        @Override
        public void report(Diagnostic diagnostic) {
            mDiagnostics.add(diagnostic);
        }
    };
    //clean task
    projectFile.clean();
    projectFile.createBuildDir();

    int status = CompileHelper.compileJava(context, projectFile, listener);
    if (status == Main.EXIT_OK) {
        try {
            CompileHelper.convertToDexFormat(context, projectFile);
        } catch (Throwable e) {
            this.error = e;
            Log.e(TAG, "doInBackground: ", e);
            publishProgress(e.getMessage().toCharArray(), 0, e.getMessage().length());
            status = Main.EXIT_ERROR;
        }
    }
    return status;
}
 
Example 40
Project: GitHub   File: CompilerWarningIT.java   View source code 5 votes vote down vote up
@Test
public void checkWarnings() {
  schemaRule.generate(schema, "com.example", config);
  schemaRule.compile(compiler, new NullWriter(), new ArrayList<File>(), config);
  
  List<Diagnostic<? extends JavaFileObject>> warnings = warnings(schemaRule.getDiagnostics());
  
  assertThat(warnings, matcher);
}