public void parse() throws ParseException { ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(source.toCharArray()); Map<String, String> options = JavaCore.getOptions(); options.put("org.eclipse.jdt.core.compiler.source", "1.8"); parser.setCompilerOptions(options); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setUnitName("Program.java"); parser.setEnvironment(new String[] { classpath != null? classpath : "" }, new String[] { "" }, new String[] { "UTF-8" }, true); parser.setResolveBindings(true); cu = (CompilationUnit) parser.createAST(null); List<IProblem> problems = Arrays.stream(cu.getProblems()).filter(p -> p.isError() && p.getID() != IProblem.PublicClassMustMatchFileName && // we use "Program.java" p.getID() != IProblem.ParameterMismatch // Evidence varargs ).collect(Collectors.toList()); if (problems.size() > 0) throw new ParseException(problems); }
@Override public IJavaCompletionProposal[] getCorrections(IInvocationContext context, IProblemLocation[] locations) throws CoreException { for (final IProblemLocation problem : locations) { if ((problem.getProblemId() == IProblem.UnresolvedVariable || problem.getProblemId() == IProblem.UndefinedType) && Utils.isAPGAS(problem.getProblemArguments()[0])) { if (!apgasInBuildPath(context.getCompilationUnit().getJavaProject())) { return getAddAPGASToBuildPathProposals(context); } } else if (problem.getProblemId() == IProblem.UndefinedMethod && Utils.isAPGAS(problem.getProblemArguments()[1])) { if (!apgasInBuildPath(context.getCompilationUnit().getJavaProject())) { return getAddAPGASToBuildPathProposals(context); } else { return getImportStaticConstructsProposal(context); } } } return null; }
private static int getProblemKind(IProblem problem) { switch (problem.getID()) { case IProblem.UndefinedField: return FIELD; case IProblem.UndefinedMethod: return METHOD; case IProblem.UndefinedLabel: return LABEL; case IProblem.UndefinedName: case IProblem.UnresolvedVariable: return NAME; case IProblem.UndefinedType: return TYPE; } return 0; }
public static UnusedCodeFix createRemoveUnusedCastFix(CompilationUnit compilationUnit, IProblemLocation problem) { if (problem.getProblemId() != IProblem.UnnecessaryCast) { return null; } ASTNode selectedNode= problem.getCoveringNode(compilationUnit); ASTNode curr= selectedNode; while (curr instanceof ParenthesizedExpression) { curr= ((ParenthesizedExpression) curr).getExpression(); } if (!(curr instanceof CastExpression)) { return null; } return new UnusedCodeFix(FixMessages.UnusedCodeFix_RemoveCast_description, compilationUnit, new CompilationUnitRewriteOperation[] {new RemoveCastOperation((CastExpression)curr)}); }
@SuppressWarnings("restriction") private static Range convertRange(IProblem problem) { Position start = new Position(); Position end = new Position(); start.setLine(problem.getSourceLineNumber()-1);// VSCode is 0-based end.setLine(problem.getSourceLineNumber()-1); if(problem instanceof DefaultProblem){ DefaultProblem dProblem = (DefaultProblem)problem; start.setCharacter(dProblem.getSourceColumnNumber() - 1); int offset = 0; if (dProblem.getSourceStart() != -1 && dProblem.getSourceEnd() != -1) { offset = dProblem.getSourceEnd() - dProblem.getSourceStart() + 1; } end.setCharacter(dProblem.getSourceColumnNumber() - 1 + offset); } return new Range(start, end); }
@Test public void testCodeAction_removeUnusedImport() throws Exception{ ICompilationUnit unit = getWorkingCopy( "src/java/Foo.java", "import java.sql.*; \n" + "public class Foo {\n"+ " void foo() {\n"+ " }\n"+ "}\n"); CodeActionParams params = new CodeActionParams(); params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit))); final Range range = getRange(unit, "java.sql"); params.setRange(range); params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.UnusedImport), range)))); List<? extends Command> commands = server.codeAction(params).join(); Assert.assertNotNull(commands); Assert.assertEquals(2, commands.size()); Command c = commands.get(0); Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand()); }
@Test public void testCodeAction_removeUnterminatedString() throws Exception{ ICompilationUnit unit = getWorkingCopy( "src/java/Foo.java", "public class Foo {\n"+ " void foo() {\n"+ "String s = \"some str\n" + " }\n"+ "}\n"); CodeActionParams params = new CodeActionParams(); params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit))); final Range range = getRange(unit, "some str"); params.setRange(range); params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.UnterminatedString), range)))); List<? extends Command> commands = server.codeAction(params).join(); Assert.assertNotNull(commands); Assert.assertEquals(1, commands.size()); Command c = commands.get(0); Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand()); }
protected List<Command> evaluateCodeActions(ICompilationUnit cu) throws JavaModelException { CompilationUnit astRoot = SharedASTProvider.getInstance().getAST(cu, null); IProblem[] problems = astRoot.getProblems(); Range range = getRange(cu, problems); CodeActionParams parms = new CodeActionParams(); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(); textDocument.setUri(JDTUtils.toURI(cu)); parms.setTextDocument(textDocument); parms.setRange(range); CodeActionContext context = new CodeActionContext(); context.setDiagnostics(DiagnosticsHandler.toDiagnosticsArray(Arrays.asList(problems))); parms.setContext(context); return new CodeActionHandler().getCodeActionCommands(parms, new NullProgressMonitor()); }
/** * Invoke CompilationResult#getProblems safely so that it works with * 3.1.1 and more recent versions of the eclipse java compiler. * See https://jsp.dev.java.net/issues/show_bug.cgi?id=13 * * @param result The compilation result. * @return The same object than CompilationResult#getProblems */ private static final IProblem[] safeGetProblems(CompilationResult result) { if (!USE_INTROSPECTION_TO_INVOKE_GET_PROBLEM) { try { return result.getProblems(); } catch (NoSuchMethodError re) { USE_INTROSPECTION_TO_INVOKE_GET_PROBLEM = true; } } try { if (GET_PROBLEM_METH == null) { GET_PROBLEM_METH = result.getClass() .getDeclaredMethod("getProblems", new Class[] {}); } //an array of a particular type can be casted into an array of a super type. return (IProblem[]) GET_PROBLEM_METH.invoke(result, null); } catch (Throwable e) { if (e instanceof RuntimeException) { throw (RuntimeException)e; } else { throw new RuntimeException(e); } } }
@Override public void acceptResult(CompilationResult result) { if (result.hasErrors()) { IProblem[] problems = result.getProblems(); if (problemList == null) problemList = new ArrayList<>(problems.length); Collections.addAll(problemList, problems); } else { ClassFile[] classFiles = result.getClassFiles(); for (ClassFile classFile : classFiles) targetClassLoader.addClass(className, classFile.getBytes()); } }
protected static void assertNumberOfProblems(int nProblems, IProblem[] problems) { if (problems.length != nProblems) { StringBuffer buf = new StringBuffer("Wrong number of problems, is: "); buf.append(problems.length).append(", expected: ").append(nProblems).append('\n'); for (int i = 0; i < problems.length; i++) { buf.append(problems[i]); buf.append('[') .append(problems[i].getSourceStart()) .append(" ,") .append(problems[i].getSourceEnd()) .append(']'); buf.append('\n'); } assertTrue(buf.toString(), false); } }
public static ICleanUpFix createCleanUp( CompilationUnit compilationUnit, IProblemLocation[] locations, int problemID) { ICompilationUnit cu = (ICompilationUnit) compilationUnit.getJavaElement(); if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) return null; List<CompilationUnitRewriteOperation> operations = new ArrayList<CompilationUnitRewriteOperation>(); if (locations == null) { org.eclipse.jdt.core.compiler.IProblem[] problems = compilationUnit.getProblems(); locations = new IProblemLocation[problems.length]; for (int i = 0; i < problems.length; i++) { if (problems[i].getID() == problemID) locations[i] = new ProblemLocation(problems[i]); } } createAddNullAnnotationOperations(compilationUnit, locations, operations); createRemoveRedundantNullAnnotationsOperations(compilationUnit, locations, operations); if (operations.size() == 0) return null; CompilationUnitRewriteOperation[] operationsArray = operations.toArray(new CompilationUnitRewriteOperation[operations.size()]); return new NullAnnotationsFix( FixMessages.NullAnnotationsFix_add_annotation_change_name, compilationUnit, operationsArray); }
private static void createRemoveRedundantNullAnnotationsOperations( CompilationUnit compilationUnit, IProblemLocation[] locations, List<CompilationUnitRewriteOperation> result) { for (int i = 0; i < locations.length; i++) { IProblemLocation problem = locations[i]; if (problem == null) continue; // problem was filtered out by createCleanUp() int problemId = problem.getProblemId(); if (problemId == IProblem.RedundantNullAnnotation || problemId == IProblem.RedundantNullDefaultAnnotationPackage || problemId == IProblem.RedundantNullDefaultAnnotationType || problemId == IProblem.RedundantNullDefaultAnnotationMethod) { RemoveRedundantAnnotationRewriteOperation operation = new RemoveRedundantAnnotationRewriteOperation(compilationUnit, problem); result.add(operation); } } }
/** * */ protected IProblem[] getJavaCompilationErrors(CompilationResult result) { return result.getErrors(); // // try { // Method getErrorsMethod = result.getClass().getMethod("getErrors", // (Class[]) null); // return (IProblem[]) getErrorsMethod.invoke(result, (Object[]) null); // } catch (SecurityException e) { // throw new JRRuntimeException("Error resolving JDT methods", e); // } catch (NoSuchMethodException e) { // throw new JRRuntimeException("Error resolving JDT methods", e); // } catch (IllegalArgumentException e) { // throw new JRRuntimeException("Error invoking JDT methods", e); // } catch (IllegalAccessException e) { // throw new JRRuntimeException("Error invoking JDT methods", e); // } catch (InvocationTargetException e) { // throw new JRRuntimeException("Error invoking JDT methods", e); // } }
public static UnusedCodeFix createRemoveUnusedCastFix( CompilationUnit compilationUnit, IProblemLocation problem) { if (problem.getProblemId() != IProblem.UnnecessaryCast) return null; ASTNode selectedNode = problem.getCoveringNode(compilationUnit); ASTNode curr = selectedNode; while (curr instanceof ParenthesizedExpression) { curr = ((ParenthesizedExpression) curr).getExpression(); } if (!(curr instanceof CastExpression)) return null; return new UnusedCodeFix( FixMessages.UnusedCodeFix_RemoveCast_description, compilationUnit, new CompilationUnitRewriteOperation[] {new RemoveCastOperation((CastExpression) curr)}); }
private RefactoringStatus checkCompilationofDeclaringCu() throws CoreException { ICompilationUnit cu = getCu(); TextChange change = fChangeManager.get(cu); String newCuSource = change.getPreviewContent(new NullProgressMonitor()); CompilationUnit newCUNode = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL) .parse(newCuSource, cu, true, false, null); IProblem[] problems = RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fBaseCuRewrite.getRoot()); RefactoringStatus result = new RefactoringStatus(); for (int i = 0; i < problems.length; i++) { IProblem problem = problems[i]; if (shouldReport(problem, newCUNode)) result.addEntry( new RefactoringStatusEntry( (problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem)))); } return result; }
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; }
/** * 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; }
public static void addUnusedMemberProposal( IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) { int problemId = problem.getProblemId(); UnusedCodeFix fix = UnusedCodeFix.createUnusedMemberFix(context.getASTRoot(), problem, false); if (fix != null) { addProposal(context, proposals, fix); } if (problemId == IProblem.LocalVariableIsNeverUsed) { fix = UnusedCodeFix.createUnusedMemberFix(context.getASTRoot(), problem, true); addProposal(context, proposals, fix); } if (problemId == IProblem.ArgumentIsNeverUsed) { JavadocTagsSubProcessor.getUnusedAndUndocumentedParameterOrExceptionProposals( context, problem, proposals); } if (problemId == IProblem.UnusedPrivateField) { GetterSetterCorrectionSubProcessor.addGetterSetterProposal( context, problem, proposals, IProposalRelevance.GETTER_SETTER_UNUSED_PRIVATE_FIELD); } }
private static SimpleName findProblemFieldName(ASTNode selectedNode, int problemID) { // if a field access occurs in an compatibility situation (assignment/return/argument) // with expected type declared @NonNull we first need to find the SimpleName inside: if (selectedNode instanceof FieldAccess) selectedNode = ((FieldAccess) selectedNode).getName(); else if (selectedNode instanceof QualifiedName) selectedNode = ((QualifiedName) selectedNode).getName(); if (selectedNode instanceof SimpleName) { SimpleName name = (SimpleName) selectedNode; if (problemID == IProblem.NullableFieldReference) return name; // not field dereference, but compatibility issue - is value a field reference? IBinding binding = name.resolveBinding(); if ((binding instanceof IVariableBinding) && ((IVariableBinding) binding).isField()) return name; } return null; }
/** * Used by quick assist * * @param context the invocation context * @param coveringNode the covering node * @param locations the problems at the corrent location * @param resultingCollections the resulting proposals * @return <code>true</code> if the quick assist is applicable at this offset */ public static boolean addGetterSetterProposal( IInvocationContext context, ASTNode coveringNode, IProblemLocation[] locations, ArrayList<ICommandAccess> resultingCollections) { if (locations != null) { for (int i = 0; i < locations.length; i++) { int problemId = locations[i].getProblemId(); if (problemId == IProblem.UnusedPrivateField) return false; if (problemId == IProblem.UnqualifiedFieldAccess) return false; } } return addGetterSetterProposal( context, coveringNode, resultingCollections, IProposalRelevance.GETTER_SETTER_QUICK_ASSIST); }
private static boolean containsQuickFixableRenameLocal(IProblemLocation[] locations) { if (locations != null) { for (int i = 0; i < locations.length; i++) { IProblemLocation location = locations[i]; if (IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER.equals(location.getMarkerType())) { switch (location.getProblemId()) { case IProblem.LocalVariableHidingLocalVariable: case IProblem.LocalVariableHidingField: case IProblem.FieldHidingLocalVariable: case IProblem.FieldHidingField: case IProblem.ArgumentHidingLocalVariable: case IProblem.ArgumentHidingField: return true; } } } } return false; }
/** {@inheritDoc} */ public boolean canFix(ICompilationUnit compilationUnit, IProblemLocation problem) { if (IProblem.UnqualifiedFieldAccess == problem.getProblemId()) return isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS) && isEnabled(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS); if (CodeStyleFix.isIndirectStaticAccess(problem)) return isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled( CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS); if (CodeStyleFix.isNonStaticAccess(problem)) return isEnabled(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS) && isEnabled( CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS); return false; }
/** {@inheritDoc} */ @Override public int computeNumberOfFixes(CompilationUnit compilationUnit) { int result = 0; IProblem[] problems = compilationUnit.getProblems(); for (int i = 0; i < problems.length; i++) { int id = problems[i].getID(); if (id == this.handledProblemID) { // FIXME search specifically: return param (which??) // if (!QuickFixes.hasExplicitNullnessAnnotation(compilationUnit, // problems[i].getSourceStart())) result++; } } return result; }
/** {@inheritDoc} */ @Override public int computeNumberOfFixes(CompilationUnit compilationUnit) { try { ICompilationUnit cu = (ICompilationUnit) compilationUnit.getJavaElement(); if (!cu.isStructureKnown()) return 0; // [clean up] 'Remove unnecessary $NLS-TAGS$' removes necessary ones in case of // syntax errors: https://bugs.eclipse.org/bugs/show_bug.cgi?id=285814 : } catch (JavaModelException e) { return 0; } int result = 0; IProblem[] problems = compilationUnit.getProblems(); if (isEnabled(CleanUpConstants.ADD_MISSING_NLS_TAGS)) result += getNumberOfProblems(problems, IProblem.NonExternalizedStringLiteral); if (isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS)) result += getNumberOfProblems(problems, IProblem.UnnecessaryNLSTag); return result; }
/** {@inheritDoc} */ @Override protected ICleanUpFix createFix(CompilationUnit unit) throws CoreException { IProblemLocation[] problemLocations = convertProblems(unit.getProblems()); problemLocations = filter( problemLocations, new int[] { IProblem.AbstractMethodMustBeImplemented, IProblem.EnumConstantMustImplementAbstractMethod }); return UnimplementedCodeFix.createCleanUp( unit, isEnabled(CleanUpConstants.ADD_MISSING_METHODES), isEnabled(MAKE_TYPE_ABSTRACT), problemLocations); }
/** {@inheritDoc} */ @Override protected ICleanUpFix createFix(CompilationUnit unit, IProblemLocation[] problems) throws CoreException { IProblemLocation[] problemLocations = filter( problems, new int[] { IProblem.AbstractMethodMustBeImplemented, IProblem.EnumConstantMustImplementAbstractMethod }); return UnimplementedCodeFix.createCleanUp( unit, isEnabled(CleanUpConstants.ADD_MISSING_METHODES), isEnabled(MAKE_TYPE_ABSTRACT), problemLocations); }
/** {@inheritDoc} */ @Override public int computeNumberOfFixes(CompilationUnit compilationUnit) { if (!isEnabled(CleanUpConstants.ADD_MISSING_METHODES) && !isEnabled(MAKE_TYPE_ABSTRACT)) return 0; IProblemLocation[] locations = filter( convertProblems(compilationUnit.getProblems()), new int[] { IProblem.AbstractMethodMustBeImplemented, IProblem.EnumConstantMustImplementAbstractMethod }); HashSet<ASTNode> types = new HashSet<ASTNode>(); for (int i = 0; i < locations.length; i++) { ASTNode type = UnimplementedCodeFix.getSelectedTypeNode(compilationUnit, locations[i]); if (type != null) { types.add(type); } } return types.size(); }
@Override public void processProblems() { for (int i = 0; i < units.length; i++) { JRCompilationSourceCode sourceCode = units[i].getCompilationSource(); IProblem[] problems = unitResults[i].getProblems(); if (problems != null) { for (int j = 0; j < problems.length; j++) { IProblem problem = problems[j]; int line = problem.getSourceLineNumber(); JRExpression expression = sourceCode.getExpressionAtLine(line); if (expression == null) errorHandler.addMarker(problem, null); else if (!addExpressionError(expression)) errorHandler.addMarker(problem, digester.getLocation(expression), expression); } } } }
private void encodeAccessRule( AccessRule accessRule, XMLWriter writer, boolean indent, boolean newLine) { HashMap parameters = new HashMap(); parameters.put(TAG_PATTERN, new String(accessRule.pattern)); switch (accessRule.getProblemId()) { case IProblem.ForbiddenReference: parameters.put(TAG_KIND, TAG_NON_ACCESSIBLE); break; case IProblem.DiscouragedReference: parameters.put(TAG_KIND, TAG_DISCOURAGED); break; default: parameters.put(TAG_KIND, TAG_ACCESSIBLE); break; } if (accessRule.ignoreIfBetter()) parameters.put(TAG_IGNORE_IF_BETTER, "true"); // $NON-NLS-1$ writer.printTag(TAG_ACCESS_RULE, parameters, indent, newLine, true); }
public List<Problem> ProcessFileParseMessagesRequest(Integer fileId) { List<FileParseMessagesResponse.Problem> ret = new ArrayList<FileParseMessagesResponse.Problem>(); if (ActiveUnits.containsKey(fileId)) { CompilationUnit cu = ActiveUnits.get(fileId); IProblem[] problems = cu.getProblems(); for(IProblem problem: problems) { System.out.println(problem.toString()); FileParseMessagesResponse.Problem.Builder retProblem = FileParseMessagesResponse.Problem.newBuilder() .setId(problem.getID()) .setMessage(problem.getMessage()) .setFileName(new String(problem.getOriginatingFileName())) .setScopeStart(problem.getSourceStart()) .setScopeEnd(problem.getSourceEnd() + 1) .setLineNumber(problem.getSourceLineNumber()) .setProblemType(GetProblemType(problem)); for(String arg: problem.getArguments()) retProblem.addArguments(arg); ret.add(retProblem.build()); } } return ret; }
@Test public void testParse() throws Exception { IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true,true); IFile impl = (IFile) ResourceManager .getResource(project.getProject().getFullPath().append("src/test/java/SimpleImpl.java").toString()); ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(impl); CompilationUnit cu = JDTManager.parse(compilationUnit); IProblem[] pbs = cu.getProblems(); assertEquals(0, pbs.length); }
@Test public void testRenameClass() throws Exception { IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true,true); IFile impl = (IFile) ResourceManager .getResource(project.getProject().getFullPath().append("src/test/java/SimpleImpl.java").toString()); // The rename method only renames the class name within the file. It does not rename the file and it is expected. // See the comment of the JDTManager.renameClass (...) api // And this is why we expect 1 pb "assertEquals(1, pbs.length);" below IFile f = JDTManager.renameClass(impl, "SimpleImpl", "SimpleImpl1", new NullProgressMonitor()); Waiter.waitUntil(new ICondition () { @Override public boolean checkCondition() throws Exception { IFolder folder = (IFolder) ResourceManager.getResource(project.getProject().getFullPath().append("src/test/java").toString()); IFile frenamed = folder.getFile("SimpleImpl1.java"); return frenamed.getName().equals("SimpleImpl1.java"); } @Override public String getFailureMessage() { return "file not renamed"; } }); ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(f); CompilationUnit cu = JDTManager.parse(compilationUnit); IProblem[] pbs = cu.getProblems(); assertEquals(1, pbs.length); }
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<>(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(); } else if ((severity & INFO) != 0) { consider= problem.isInfo(); } 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()]); }
private static int getNameNodeProblemKind(IProblem[] problems, SimpleName nameNode) { int nameOffset= nameNode.getStartPosition(); int nameInclEnd= nameOffset + nameNode.getLength() - 1; for (int i= 0; i < problems.length; i++) { IProblem curr= problems[i]; if (curr.getSourceStart() == nameOffset && curr.getSourceEnd() == nameInclEnd) { int kind= getProblemKind(curr); if (kind != 0) { return kind; } } } return 0; }
public static SimpleName[] findByProblems(ASTNode parent, SimpleName nameNode) { ArrayList<SimpleName> res= new ArrayList<>(); ASTNode astRoot = parent.getRoot(); if (!(astRoot instanceof CompilationUnit)) { return null; } IProblem[] problems= ((CompilationUnit) astRoot).getProblems(); int nameNodeKind= getNameNodeProblemKind(problems, nameNode); if (nameNodeKind == 0) { // no problem on node return null; } int bodyStart= parent.getStartPosition(); int bodyEnd= bodyStart + parent.getLength(); String name= nameNode.getIdentifier(); for (int i= 0; i < problems.length; i++) { IProblem curr= problems[i]; int probStart= curr.getSourceStart(); int probEnd= curr.getSourceEnd() + 1; if (probStart > bodyStart && probEnd < bodyEnd) { int currKind= getProblemKind(curr); if ((nameNodeKind & currKind) != 0) { ASTNode node= NodeFinder.perform(parent, probStart, (probEnd - probStart)); if (node instanceof SimpleName && name.equals(((SimpleName) node).getIdentifier())) { res.add((SimpleName) node); } } } } return res.toArray(new SimpleName[res.size()]); }
private static Collection<ImportDeclaration> determineUnresolvableImports(CompilationUnit cu) { Collection<ImportDeclaration> unresolvableImports= new ArrayList<>(cu.imports().size()); for (IProblem problem : cu.getProblems()) { if (problem.getID() == IProblem.ImportNotFound) { ImportDeclaration problematicImport= getProblematicImport(problem, cu); if (problematicImport != null) { unresolvableImports.add(problematicImport); } } } return unresolvableImports; }
private static ImportDeclaration getProblematicImport(IProblem problem, CompilationUnit astRoot) { ASTNode coveringNode = new NodeFinder(astRoot, problem.getSourceStart(), problem.getSourceEnd() - problem.getSourceStart()).getCoveringNode(); if (coveringNode != null) { ASTNode importNode= ASTNodes.getParent(coveringNode, ASTNode.IMPORT_DECLARATION); if (importNode instanceof ImportDeclaration) { return (ImportDeclaration) importNode; } } return null; }
public static IProposableFix[] createMissingSerialVersionFixes(CompilationUnit compilationUnit, IProblemLocation problem) { if (problem.getProblemId() != IProblem.MissingSerialVersion) { return null; } final ICompilationUnit unit = (ICompilationUnit) compilationUnit.getJavaElement(); if (unit == null) { return null; } final SimpleName simpleName = getSelectedName(compilationUnit, problem); if (simpleName == null) { return null; } ASTNode declaringNode = getDeclarationNode(simpleName); if (declaringNode == null) { return null; } SerialVersionDefaultOperation defop = new SerialVersionDefaultOperation(unit, new ASTNode[] { declaringNode }); IProposableFix fix1 = new PotentialProgrammingProblemsFix(FixMessages.Java50Fix_SerialVersion_default_description, compilationUnit, new CompilationUnitRewriteOperation[] { defop }); SerialVersionHashOperation hashop = new SerialVersionHashOperation(unit, new ASTNode[] { declaringNode }); IProposableFix fix2 = new PotentialProgrammingProblemsFix(FixMessages.Java50Fix_SerialVersion_hash_description, compilationUnit, new CompilationUnitRewriteOperation[] { hashop }); return new IProposableFix[] { fix1, fix2 }; }