Java Code Examples for org.eclipse.jdt.core.compiler.IProblem#isError()

The following examples show how to use org.eclipse.jdt.core.compiler.IProblem#isError() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JdtParser.java    From j2cl with Apache License 2.0 6 votes vote down vote up
private boolean compilationHasErrors(String filename, CompilationUnit unit) {
  boolean hasErrors = false;
  // Here we check for instances of @GwtIncompatible in the ast. If that is the case, we throw an
  // error since these should have been stripped by the build system already.
  GwtIncompatibleNodeCollector collector = new GwtIncompatibleNodeCollector();
  unit.accept(collector);
  if (!collector.getNodes().isEmpty()) {
    problems.fatal(FatalError.GWT_INCOMPATIBLE_FOUND_IN_COMPILE, filename);
  }
  for (IProblem problem : unit.getProblems()) {
    if (problem.isError()) {
      problems.error(problem.getSourceLineNumber(), filename, "%s", problem.getMessage());
      hasErrors = true;
    }
  }
  return hasErrors;
}
 
Example 2
Source File: JavaASTUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns <code>true</code> if any of the problems fall within the
 * {@link ASTNode}'s source range.
 */
public static boolean hasErrors(ASTNode node, IProblem[] problems) {
  int startPosition = node.getStartPosition();
  int endPosition = startPosition + node.getLength() - 1;

  for (IProblem problem : problems) {
    if (!problem.isError()) {
      // Skip any problem that is not an error
      continue;
    }
    if (problem.getSourceStart() >= startPosition
        && problem.getSourceEnd() <= endPosition) {
      return true;
    }
  }

  return false;
}
 
Example 3
Source File: SourceCompiler.java    From junion with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void printProblem(IProblem p) {
	if(p.isError()) {
		System.err.print("ERROR: ");
	}
	else if(p.isWarning()) {
		System.err.print("WARNING: ");
	}
	else if(p.isInfo()) {
		System.err.print("INFO: ");
	}
	else System.err.print("UNKNOWN: ");
	System.err.println(p.getMessage());
	String f = String.valueOf(p.getOriginatingFileName());
	if(f != null) {
		f = new File(f).getName();
	}
	
	System.err.println("\t at " + "("+f+":"+p.getSourceLineNumber()+")");
}
 
Example 4
Source File: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Evaluates if a problem needs to be reported.
 * @param problem the problem
 * @param cu the AST containing the new source
 * @return return <code>true</code> if the problem needs to be reported
 */
protected boolean shouldReport(IProblem problem, CompilationUnit cu) {
	if (! problem.isError())
		return false;
	if (problem.getID() == IProblem.UndefinedType) //reported when trying to import
		return false;
	return true;
}
 
Example 5
Source File: Preprocessor.java    From APDE with GNU General Public License v2.0 5 votes vote down vote up
public CompilerProblem buildCompilerProblem(IProblem problem) throws TextTransform.LockException {
	// ECJ gives us the full path to the file, we just want the filename
	String filename = new File(new String(problem.getOriginatingFileName())).getName();
	
	// Check to see if main file or not
	if (context.getSketchMainFilename().equals(filename)) {
		return buildCompilerProblem(
				new TextTransform.Range(problem.getSourceStart(), problem.getSourceEnd() - problem.getSourceStart() + 1),
				problem.isError(), problem.getMessage(), false);
	} else {
		// Check all java files
		for (SketchCode sketchFile : context.getSketchFiles()) {
			if (sketchFile.isJava() && sketchFile.getFilename().equals(filename)) {
				int absStart = problem.getSourceStart() - sketchFile.javaImportHeaderOffset;
				int line = sketchFile.lineForOffset(absStart);
				int start = absStart - sketchFile.offsetForLine(line);
				
				return new CompilerProblem(sketchFile, line, start,
						problem.getSourceEnd() - problem.getSourceStart() + 1,
						problem.isError(), problem.getMessage());
			}
		}
		
		// If we can't find it
		System.err.println("Unable to find java file: " + filename);
		return new CompilerProblem(context.getSketchFiles().get(0), 0, 0, 1,
				problem.isError(), problem.getMessage());
	}
}
 
Example 6
Source File: TranslateNodeTest.java    From juniversal with MIT License 5 votes vote down vote up
public CompilationUnit parseCompilationUnit(String java) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    parser.setSource(java.toCharArray()); // set source
    parser.setResolveBindings(true); // we need bindings later on
    parser.setEnvironment(new String[0], new String[0], null, true);
    parser.setUnitName("TestClass.java");

    // In order to parse 1.8 code, some compiler options need to be set to 1.8
    Map options = JavaCore.getOptions();
    JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
    parser.setCompilerOptions(options);

    CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null /* IProgressMonitor */);

    IProblem[] problems = compilationUnit.getProblems();
    if (problems.length > 0) {
        StringBuilder problemsText = new StringBuilder();

        for (IProblem problem : problems) {
            if (problem.isError()) {
                problemsText.append(problem.getMessage() + "\n");
            }
        }

        if (problemsText.length() > 0)
            throw new RuntimeException(problemsText.toString());
    }

    return compilationUnit;
}
 
Example 7
Source File: ProblemLocation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ProblemLocation(IProblem problem) {
	fId= problem.getID();
	fArguments= problem.getArguments();
	fOffset= problem.getSourceStart();
	fLength= problem.getSourceEnd() - fOffset + 1;
	fIsError= problem.isError();
	fMarkerType= problem instanceof CategorizedProblem ? ((CategorizedProblem) problem).getMarkerType() : IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER;
}
 
Example 8
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IProblem[] getProblems(ASTNode node, int scope, int severity) {
	ASTNode root= node.getRoot();
	if (!(root instanceof CompilationUnit))
		return EMPTY_PROBLEMS;
	IProblem[] problems= ((CompilationUnit)root).getProblems();
	if (root == node)
		return problems;
	final int iterations= computeIterations(scope);
	List<IProblem> result= new ArrayList<IProblem>(5);
	for (int i= 0; i < problems.length; i++) {
		IProblem problem= problems[i];
		boolean consider= false;
		if ((severity & PROBLEMS) == PROBLEMS)
			consider= true;
		else if ((severity & WARNING) != 0)
			consider= problem.isWarning();
		else if ((severity & ERROR) != 0)
			consider= problem.isError();
		if (consider) {
			ASTNode temp= node;
			int count= iterations;
			do {
				int nodeOffset= temp.getStartPosition();
				int problemOffset= problem.getSourceStart();
				if (nodeOffset <= problemOffset && problemOffset < nodeOffset + temp.getLength()) {
					result.add(problem);
					count= 0;
				} else {
					count--;
				}
			} while ((temp= temp.getParent()) != null && count > 0);
		}
	}
	return result.toArray(new IProblem[result.size()]);
}
 
Example 9
Source File: ExtractConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void checkSource(SubProgressMonitor monitor, RefactoringStatus result) throws CoreException {
	String newCuSource= fChange.getPreviewContent(new NullProgressMonitor());
	CompilationUnit newCUNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(newCuSource, fCu, true, true, monitor);

	IProblem[] newProblems= RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCuRewrite.getRoot());
	for (int i= 0; i < newProblems.length; i++) {
		IProblem problem= newProblems[i];
		if (problem.isError())
			result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem))));
	}
}
 
Example 10
Source File: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void checkNewSource(SubProgressMonitor monitor, RefactoringStatus result) throws CoreException {
	String newCuSource= fChange.getPreviewContent(new NullProgressMonitor());
	CompilationUnit newCUNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(newCuSource, fCu, true, true, monitor);
	IProblem[] newProblems= RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCompilationUnitNode);
	for (int i= 0; i < newProblems.length; i++) {
		IProblem problem= newProblems[i];
		if (problem.isError())
			result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem))));
	}
}
 
Example 11
Source File: RenameAnalyzeUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static RefactoringStatus analyzeCompileErrors(String newCuSource, CompilationUnit newCUNode, CompilationUnit oldCUNode) {
	RefactoringStatus result= new RefactoringStatus();
	IProblem[] newProblems= RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, oldCUNode);
	for (int i= 0; i < newProblems.length; i++) {
		IProblem problem= newProblems[i];
		if (problem.isError())
			result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource,
					SourceRangeFactory.create(problem))));
	}
	return result;
}
 
Example 12
Source File: BaseDiagnosticsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static DiagnosticSeverity convertSeverity(IProblem problem) {
	if (problem.isError()) {
		return DiagnosticSeverity.Error;
	}
	if (problem.isWarning() && (problem.getID() != IProblem.Task)) {
		return DiagnosticSeverity.Warning;
	}
	return DiagnosticSeverity.Information;
}
 
Example 13
Source File: ExtractConstantRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void checkSource(SubProgressMonitor monitor, RefactoringStatus result) throws CoreException {
	String newCuSource = fChange.getPreviewContent(new NullProgressMonitor());
	CompilationUnit newCUNode = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(newCuSource, fCu, true, true, monitor);

	IProblem[] newProblems = RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCuRewrite.getRoot());
	for (int i = 0; i < newProblems.length; i++) {
		IProblem problem = newProblems[i];
		if (problem.isError()) {
			result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem))));
		}
	}
}
 
Example 14
Source File: ExtractTempRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void checkNewSource(SubProgressMonitor monitor, RefactoringStatus result) throws CoreException {
	String newCuSource = fChange.getPreviewContent(new NullProgressMonitor());
	CompilationUnit newCUNode = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(newCuSource, fCu, true, true, monitor);
	IProblem[] newProblems = RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCompilationUnitNode);
	for (int i = 0; i < newProblems.length; i++) {
		IProblem problem = newProblems[i];
		if (problem.isError()) {
			result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem))));
		}
	}
}
 
Example 15
Source File: RenameAnalyzeUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static RefactoringStatus analyzeCompileErrors(String newCuSource, CompilationUnit newCUNode, CompilationUnit oldCUNode) {
	RefactoringStatus result= new RefactoringStatus();
	IProblem[] newProblems= RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, oldCUNode);
	for (int i= 0; i < newProblems.length; i++) {
		IProblem problem= newProblems[i];
		if (problem.isError()) {
			result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource,
					SourceRangeFactory.create(problem))));
		}
	}
	return result;
}
 
Example 16
Source File: Translator.java    From juniversal with MIT License 4 votes vote down vote up
/**
   * Translate all source files configured for the translator.   If a user errors occurs during translation for a file
   * (e.g. a SourceNotSupported exception is thrown), an error message is output for that file, the translation
   * continues on with remaining files, and false is eventually returned from this method as the translate failed.  If
   * an internal occurs during translation (e.g. the translator has a bug), an exception is thrown.
   *
   * @return true if all files were translated without error, false if some failed
   */
  public boolean translate() {
      ASTParser parser = ASTParser.newParser(AST.JLS8);
      parser.setKind(ASTParser.K_COMPILATION_UNIT);
      //parser.setEnvironment(new String[0], new String[0], null, false);
      //TODO: Set classpath & sourcepath differently probably; this just uses the current VM (I think), but I can
      //see that it doesn't resolve everything for some reason
      parser.setEnvironment(classpath, sourcepath, null, true);
      parser.setResolveBindings(true);

      Map options = JavaCore.getOptions();
      JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
      parser.setCompilerOptions(options);

      Var<Boolean> failed = new Var<>(false);

      FileASTRequestor astRequestor = new FileASTRequestor() {
          public void acceptAST(String sourceFilePath, CompilationUnit compilationUnit) {
              SourceFile sourceFile = new SourceFile(compilationUnit, new File(sourceFilePath), sourceTabStop);

              //boolean outputErrorForFile = false;
              for (IProblem problem : compilationUnit.getProblems()) {
                  if (problem.isError()) {
                      System.err.println("Error: " + problem.getMessage());
                      System.err.println(sourceFile.getPositionDescription(problem.getSourceStart()));
                  }
              }

              // Translate each file as it's returned; if a user error occurs while translating (e.g. a
              // SourceNotSupported exception is thrown), print the message for that, note the failure, and continue
              // on
              System.out.println("Translating " + sourceFilePath);
              try {
                  translateFile(sourceFile);
              } catch (UserViewableException e) {
                  System.err.println("Error: " + e.getMessage());
                  failed.set(true);
              }
          }
      };

      parser.createASTs(getJavaFiles(), null, new String[0], astRequestor, null);

      return !failed.value();

/*
       * String source = readFile(jUniversal.getJavaProjectDirectories().get(0).getPath());
 * parser.setSource(source.toCharArray());
 *
 * CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
 *
 *
 * TypeDeclaration typeDeclaration = ASTUtil.getFirstTypeDeclaration(compilationUnit);
 *
 * FileWriter writer; try { writer = new FileWriter(jUniversal.getOutputDirectory()); }
 * catch (IOException e) { throw new RuntimeException(e);   }
 *
 * CPPProfile profile = new CPPProfile(); // profile.setTabStop(4);
 *
 * CPPWriter cppWriter = new CPPWriter(writer, profile);
 *
 * Context context = new Context((CompilationUnit) compilationUnit.getRoot(), source, 8,
 * profile, cppWriter, OutputType.SOURCE);
 *
 * context.setPosition(typeDeclaration.getStartPosition());
 *
 * ASTWriters astWriters = new ASTWriters();
 *
 * try { context.setPosition(typeDeclaration.getStartPosition());
 * skipSpaceAndComments();
 *
 * astWriters.writeNode(typeDeclaration, context); } catch (UserViewableException e) {
 * System.err.println(e.getMessage()); System.exit(1); } catch (RuntimeException e) { if (e
 * instanceof ContextPositionMismatchException) throw e; else throw new
 * JUniversalException(e.getMessage() + "\nError occurred with context at position\n" +
 * context.getPositionDescription(context.getPosition()), e); }
 *
 * try { writer.close(); } catch (IOException e) { throw new RuntimeException(e); }
 */
  }
 
Example 17
Source File: ExtractAnnotations.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
@TaskAction
protected void compile() {
    if (!hasAndroidAnnotations()) {
        return;

    }


    if (encoding == null) {
        encoding = "UTF_8";
    }


    Pair<Collection<CompilationUnitDeclaration>, INameEnvironment> result = parseSources();
    Collection<CompilationUnitDeclaration> parsedUnits = result.getFirst();
    INameEnvironment environment = result.getSecond();

    try {
        if (!allowErrors) {
            for (CompilationUnitDeclaration unit : parsedUnits) {
                // so maybe I don't need my map!!
                CategorizedProblem[] problems = unit.compilationResult().getAllProblems();
                for (IProblem problem : problems) {
                    if (problem.isError()) {
                        System.out.println("Not extracting annotations (compilation problems encountered)");
                        System.out.println("Error: " + problem.getOriginatingFileName() + ":" + problem.getSourceLineNumber() + ": " + problem.getMessage());
                        // TODO: Consider whether we abort the build at this point!
                        return;

                    }

                }

            }

        }


        // API definition file
        ApiDatabase database = null;
        if (apiFilter != null && apiFilter.exists()) {
            try {
                database = new ApiDatabase(apiFilter);
            } catch (IOException e) {
                throw new BuildException("Could not open API database " + apiFilter, e);
            }

        }


        boolean displayInfo = getProject().getLogger().isEnabled(LogLevel.INFO);
        Boolean includeClassRetentionAnnotations = false;
        Boolean sortAnnotations = false;

        Extractor extractor = new Extractor(database, classDir, displayInfo, includeClassRetentionAnnotations, sortAnnotations);
        extractor.extractFromProjectSource(parsedUnits);
        if (mergeJars != null) {
            for (File jar : mergeJars) {
                extractor.mergeExisting(jar);
            }

        }

        extractor.export(output, proguard);
        extractor.removeTypedefClasses();
    } finally {
        if (environment != null) {
            environment.cleanup();
        }

    }

}