/** * Adds a problem to the provided CompilationResult object so that it will show up * in the Problems/Warnings view. */ public static void addProblemToCompilationResult(char[] fileNameArray, CompilationResult result, boolean isWarning, String message, int sourceStart, int sourceEnd) { if (result == null) return; if (fileNameArray == null) fileNameArray = "(unknown).java".toCharArray(); int lineNumber = 0; int columnNumber = 1; int[] lineEnds = null; lineNumber = sourceStart >= 0 ? Util.getLineNumber(sourceStart, lineEnds = result.getLineSeparatorPositions(), 0, lineEnds.length-1) : 0; columnNumber = sourceStart >= 0 ? Util.searchColumnNumber(result.getLineSeparatorPositions(), lineNumber,sourceStart) : 0; CategorizedProblem ecProblem = new LombokProblem( fileNameArray, message, 0, new String[0], isWarning ? ProblemSeverities.Warning : ProblemSeverities.Error, sourceStart, sourceEnd, lineNumber, columnNumber); result.record(ecProblem, null); }
/** * Report working copy problems to a given requestor. * * @param workingCopy * @param problemRequestor */ private void reportProblems(CompilationUnit workingCopy, IProblemRequestor problemRequestor) { try { problemRequestor.beginReporting(); for (Iterator iteraror = this.problems.values().iterator(); iteraror.hasNext(); ) { CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror.next(); if (categorizedProblems == null) continue; for (int i = 0, length = categorizedProblems.length; i < length; i++) { CategorizedProblem problem = categorizedProblems[i]; if (JavaModelManager.VERBOSE) { System.out.println( "PROBLEM FOUND while reconciling : " + problem.getMessage()); // $NON-NLS-1$ } if (this.progressMonitor != null && this.progressMonitor.isCanceled()) break; problemRequestor.acceptProblem(problem); } } } finally { problemRequestor.endReporting(); } }
public void testDependentTypeIsNotSyncInterface() throws JavaModelException { JavaProjectUtilities.createCompilationUnit(javaProject, "com.google.TestService", "package com.google;\npublic interface TestService { void foo(); }\n"); ICompilationUnit asyncInterface = JavaProjectUtilities.createCompilationUnit( javaProject, "com.google.TestServiceAsync", "package com.google;\nimport com.google.gwt.user.client.rpc.AsyncCallback;\npublic interface TestServiceAsync { void foo(AsyncCallback foo); }\n"); RemoteServiceValidator rsv = new RemoteServiceValidator(); ValidationResult validationResults; ASTNode asyncAst = newAST(asyncInterface); // Test that no errors are reported on the "Async" interface since the sync // interface does not extend RemoteService validationResults = rsv.validate(asyncAst); assertProblemsEqual(Collections.<CategorizedProblem> emptyList(), validationResults.getProblems()); assertEquals(Arrays.asList("com.google.TestService"), validationResults.getTypeDependencies()); }
@Override protected List<CategorizedProblem> doValidateMethodOnDependentInterface( IMethodBinding dependentMethodBinding, TypeDeclaration changedInterface, ITypeBinding dependentTypeBinding) { String[] parameters = RemoteServiceUtilities.computeSyncParameterTypes(dependentMethodBinding); if (Bindings.findMethodInHierarchy(changedInterface.resolveBinding(), dependentMethodBinding.getName(), parameters) == null) { CategorizedProblem problem1 = RemoteServiceProblemFactory.newMissingSyncMethodOnSync( changedInterface, dependentMethodBinding); if (problem1 != null) { return Collections.singletonList(problem1); } } return Collections.emptyList(); }
@Override protected List<CategorizedProblem> doValidateMethodOnDependentInterface( IMethodBinding methodBinding, TypeDeclaration changedInterface, ITypeBinding dependentInterfaceBinding) { String[] parameters = RemoteServiceUtilities.computeAsyncParameterTypes(methodBinding); String methodName = methodBinding.getName(); if (Bindings.findMethodInHierarchy(changedInterface.resolveBinding(), methodName, parameters) == null) { CategorizedProblem problem = RemoteServiceProblemFactory.newMissingAsyncMethodOnAsync( methodBinding, changedInterface); if (problem != null) { return Collections.singletonList(problem); } } return Collections.emptyList(); }
/** * Report working copy problems to a given requestor. * * @param workingCopy * @param problemRequestor */ private void reportProblems(CompilationUnit workingCopy, IProblemRequestor problemRequestor) { try { problemRequestor.beginReporting(); for (Iterator iteraror = this.problems.values().iterator(); iteraror.hasNext();) { CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror.next(); if (categorizedProblems == null) continue; for (int i = 0, length = categorizedProblems.length; i < length; i++) { CategorizedProblem problem = categorizedProblems[i]; if (JavaModelManager.VERBOSE){ System.out.println("PROBLEM FOUND while reconciling : " + problem.getMessage());//$NON-NLS-1$ } if (this.progressMonitor != null && this.progressMonitor.isCanceled()) break; problemRequestor.acceptProblem(problem); } } } finally { problemRequestor.endReporting(); } }
/** * INTERNAL USE-ONLY * Generate the byte for problem method infos that correspond to missing abstract methods. * http://dev.eclipse.org/bugs/show_bug.cgi?id=3179 * * @param methodDeclarations Array of all missing abstract methods */ public void generateMissingAbstractMethods(MethodDeclaration[] methodDeclarations, CompilationResult compilationResult) { if (methodDeclarations != null) { TypeDeclaration currentDeclaration = this.referenceBinding.scope.referenceContext; int typeDeclarationSourceStart = currentDeclaration.sourceStart(); int typeDeclarationSourceEnd = currentDeclaration.sourceEnd(); for (int i = 0, max = methodDeclarations.length; i < max; i++) { MethodDeclaration methodDeclaration = methodDeclarations[i]; MethodBinding methodBinding = methodDeclaration.binding; String readableName = new String(methodBinding.readableName()); CategorizedProblem[] problems = compilationResult.problems; int problemsCount = compilationResult.problemCount; for (int j = 0; j < problemsCount; j++) { CategorizedProblem problem = problems[j]; if (problem != null && problem.getID() == IProblem.AbstractMethodMustBeImplemented && problem.getMessage().indexOf(readableName) != -1 && problem.getSourceStart() >= typeDeclarationSourceStart && problem.getSourceEnd() <= typeDeclarationSourceEnd) { // we found a match addMissingAbstractProblemMethod(methodDeclaration, methodBinding, problem, compilationResult); } } } } }
public void record(CategorizedProblem newProblem, ReferenceContext referenceContext, boolean mandatoryError) { //new Exception("VERBOSE PROBLEM REPORTING").printStackTrace(); if(newProblem.getID() == IProblem.Task) { recordTask(newProblem); return; } if (this.problemCount == 0) { this.problems = new CategorizedProblem[5]; } else if (this.problemCount == this.problems.length) { System.arraycopy(this.problems, 0, (this.problems = new CategorizedProblem[this.problemCount * 2]), 0, this.problemCount); } this.problems[this.problemCount++] = newProblem; if (referenceContext != null){ if (this.problemsMap == null) this.problemsMap = new HashMap(5); if (this.firstErrors == null) this.firstErrors = new HashSet(5); if (newProblem.isError() && !referenceContext.hasErrors()) this.firstErrors.add(newProblem); this.problemsMap.put(newProblem, referenceContext); } if (newProblem.isError()) { this.numberOfErrors++; if (mandatoryError) this.hasMandatoryErrors = true; if ((newProblem.getID() & IProblem.Syntax) != 0) { this.hasSyntaxError = true; } } }
public boolean isSuppressed(CategorizedProblem problem) { if (this.suppressWarningsCount == 0) return false; int irritant = ProblemReporter.getIrritant(problem.getID()); if (irritant == 0) return false; int start = problem.getSourceStart(); int end = problem.getSourceEnd(); nextSuppress: for (int iSuppress = 0, suppressCount = this.suppressWarningsCount; iSuppress < suppressCount; iSuppress++) { long position = this.suppressWarningScopePositions[iSuppress]; int startSuppress = (int) (position >>> 32); int endSuppress = (int) position; if (start < startSuppress) continue nextSuppress; if (end > endSuppress) continue nextSuppress; if (this.suppressWarningIrritants[iSuppress].isSet(irritant)) return true; } return false; }
/** * Answer the problems (errors and warnings) encountered during compilation. * * This is not a compiler internal API - it has side-effects ! * It is intended to be used only once all problems have been detected, * and makes sure the problems slot as the exact size of the number of * problems. */ public CategorizedProblem[] getProblems() { // Re-adjust the size of the problems if necessary. if (this.problems != null) { if (this.problemCount != this.problems.length) { System.arraycopy(this.problems, 0, (this.problems = new CategorizedProblem[this.problemCount]), 0, this.problemCount); } if (this.maxProblemPerUnit > 0 && this.problemCount > this.maxProblemPerUnit){ quickPrioritize(this.problems, 0, this.problemCount - 1); this.problemCount = this.maxProblemPerUnit; System.arraycopy(this.problems, 0, (this.problems = new CategorizedProblem[this.problemCount]), 0, this.problemCount); } // Stable sort problems per source positions. Arrays.sort(this.problems, 0, this.problems.length, CompilationResult.PROBLEM_COMPARATOR); //quickSort(problems, 0, problems.length-1); } return this.problems; }
private void quickPrioritize(CategorizedProblem[] problemList, int left, int right) { if (left >= right) return; // sort the problems by their priority... starting with the highest priority int original_left = left; int original_right = right; int mid = computePriority(problemList[left + (right - left) / 2]); do { while (computePriority(problemList[right]) < mid) right--; while (mid < computePriority(problemList[left])) left++; if (left <= right) { CategorizedProblem tmp = problemList[left]; problemList[left] = problemList[right]; problemList[right] = tmp; left++; right--; } } while (left <= right); if (original_left < right) quickPrioritize(problemList, original_left, right); if (left < original_right) quickPrioritize(problemList, left, original_right); }
public CategorizedProblem createProblem( char[] fileName, int problemId, String[] problemArguments, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, int lineNumber, int columnNumber) { return this.problemFactory.createProblem( fileName, problemId, problemArguments, messageArguments, severity, problemStartPosition, problemEndPosition, lineNumber, columnNumber); }
public CategorizedProblem createProblem( char[] fileName, int problemId, String[] problemArguments, int elaborationId, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, int lineNumber, int columnNumber) { return this.problemFactory.createProblem( fileName, problemId, problemArguments, elaborationId, messageArguments, severity, problemStartPosition, problemEndPosition, lineNumber, columnNumber); }
protected void report(Environment environment, CategorizedProblem problem) { if (problem == null) { throw new IllegalArgumentException("problem cannot be null"); } File file = new File(new String(problem.getOriginatingFileName())); String filename = file.getAbsolutePath(); String message = problem.getMessage() + " at " + filename + ":" + problem.getSourceLineNumber(); if (problem.isError()) { if (!environment.getNoClasspath()) { // by default, compilation errors are notified as exception throw new ModelBuildingException(message); } } }
/** * Returns the ECJ AST for the given class element. This allows to specify * compiler options. * * <I>Note</I>: We do not cache the AST as it is not immutable. * * @return the AST or null if nothing compilable was found (such as * interfaces). */ public static EcjCompilationResult getEcjAST(IJavaElement element, EcjCompilerOptions options) throws ConQATException { String content = element.getTextContent(); UnmodifiableList<String> scopeClasspath = element.getJavaContext() .getClassPath(); String[] classpath = EcjUtils.obtainClasspath(CollectionUtils.toArray( scopeClasspath, String.class)); ErrorAwareCompilerRequestor requestor = new ErrorAwareCompilerRequestor( element.getUniformPath()); CompilationUnitDeclaration result = EcjASTAccess.compileAST(element .getUniformPath(), content, classpath, element.getEncoding() .name(), options, requestor); return new EcjCompilationResult(result, CollectionUtils.toArray( requestor.getErrors(), CategorizedProblem.class)); }
/** * When only the boot class path is provided the compiler should be able to * find all system classes but not our referenced classes. */ public void testWithBootClasspath() throws IOException { CollectingCompilerRequestor requestor = compile(EcjUtils .obtainClasspath()); assertEquals(1, requestor.getClassFiles().size()); assertEquals("MainClass", EcjUtils.getFQName(CollectionUtils.getAny( requestor.getClassFiles()).getCompoundName())); // the compiler should be able to find all system classes but not our // referenced classes assertEquals(3, requestor.getErrors().size()); for (CategorizedProblem problem : requestor.getErrors()) { assertEquals(50, problem.getCategoryID()); } }
public CategorizedProblem createProblem( char[] originatingFileName, int problemId, String[] problemArguments, int elaborationId, String[] messageArguments, int severity, int start, int end, int lineNumber, int columnNumber) { return checkProblem( super.createProblem( originatingFileName, problemId, problemArguments, elaborationId, messageArguments, severity, start, end, lineNumber, columnNumber), originatingFileName, severity, start); }
public CategorizedProblem createProblem( char[] originatingFileName, int problemId, String[] problemArguments, String[] messageArguments, int severity, int start, int end, int lineNumber, int columnNumber) { return checkProblem( super.createProblem( originatingFileName, problemId, problemArguments, messageArguments, severity, start, end, lineNumber, columnNumber), originatingFileName, severity, start); }
/** * @see ICodeSnippetRequestor */ public void acceptProblem(CategorizedProblem problem, char[] fragmentSource, int fragmentKind) { try { IMarker marker = ResourcesPlugin.getWorkspace().getRoot().createMarker(IJavaModelMarker.TRANSIENT_PROBLEM); marker.setAttribute(IJavaModelMarker.ID, problem.getID()); marker.setAttribute(IMarker.CHAR_START, problem.getSourceStart()); marker.setAttribute(IMarker.CHAR_END, problem.getSourceEnd() + 1); marker.setAttribute(IMarker.LINE_NUMBER, problem.getSourceLineNumber()); //marker.setAttribute(IMarker.LOCATION, "#" + problem.getSourceLineNumber()); marker.setAttribute(IMarker.MESSAGE, problem.getMessage()); marker.setAttribute(IMarker.SEVERITY, (problem.isWarning() ? IMarker.SEVERITY_WARNING : IMarker.SEVERITY_ERROR)); marker.setAttribute(IMarker.SOURCE_ID, JavaBuilder.SOURCE_ID); this.requestor.acceptProblem(marker, new String(fragmentSource), fragmentKind); } catch (CoreException e) { e.printStackTrace(); } }
private static boolean hasFatalError(CompilationUnit compilationUnit) { try { if (!((ICompilationUnit) compilationUnit.getJavaElement()).isStructureKnown()) return true; } catch (JavaModelException e) { JavaPlugin.log(e); return true; } IProblem[] problems = compilationUnit.getProblems(); for (int i = 0; i < problems.length; i++) { if (problems[i].isError()) { if (!(problems[i] instanceof CategorizedProblem)) return true; CategorizedProblem categorizedProblem = (CategorizedProblem) problems[i]; int categoryID = categorizedProblem.getCategoryID(); if (categoryID == CategorizedProblem.CAT_BUILDPATH) return true; if (categoryID == CategorizedProblem.CAT_SYNTAX) return true; if (categoryID == CategorizedProblem.CAT_IMPORT) return true; if (categoryID == CategorizedProblem.CAT_TYPE) return true; if (categoryID == CategorizedProblem.CAT_MEMBER) return true; if (categoryID == CategorizedProblem.CAT_INTERNAL) return true; } } return false; }
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; }
private void propagateErrors( ASTNode astNode, CategorizedProblem[] problems, RecoveryScannerData data) { astNode.accept(new ASTSyntaxErrorPropagator(problems)); if (data != null) { astNode.accept(new ASTRecoveryPropagator(problems, data)); } }
private void assertProblemsEqual(List<? extends CategorizedProblem> expected, List<? extends CategorizedProblem> actual) { if (expected.size() == actual.size()) { for (int i = 0, n = expected.size(); i < n; ++i) { if (!equals(expected.get(i), actual.get(i))) { failNotEquals(null, expected, actual); } } } }
public void addProblem(CategorizedProblem problem) { if (problem == null) { // This occurs when the problem creation method returns null because the // problem's severity is Ignore. return; } problems.add(problem); }
@Override protected List<CategorizedProblem> doMissingDependentInterface( TypeDeclaration changedInterface) { ValidationSuppressionVisitor warningSuppressionVisitor = new ValidationSuppressionVisitor(); /* * BodyDeclaration.modifiers returns a raw type, which can only be an * instance of IExtendedModifier. IExtendedModifier is only implemented by * the Annotation and Modifier ASTNode subtypes. */ @SuppressWarnings("unchecked") List<ASTNode> modifiers = changedInterface.modifiers(); for (ASTNode modifier : modifiers) { modifier.accept(warningSuppressionVisitor); } if (warningSuppressionVisitor.shouldSuppressValidation()) { return Collections.emptyList(); } CategorizedProblem problem = RemoteServiceProblemFactory.newMissingAsyncType(changedInterface); if (problem != null) { return Collections.singletonList(problem); } return Collections.emptyList(); }
public List<CategorizedProblem> validate(TypeDeclaration changedInterface, ITypeBinding dependentTypeBinding) { CompilationUnit compilationUnit = getCompilationUnit(changedInterface); if (JavaASTUtils.hasErrors(changedInterface, compilationUnit.getProblems())) { /* * Don't validate any type that already has errors (we are assuming that * it has JDT errors. */ return Collections.emptyList(); } if (dependentTypeBinding == null) { return doMissingDependentInterface(changedInterface); } // Check that for every method on the changed interface, there is a // corresponding method on the dependent interface List<CategorizedProblem> problems = new ArrayList<CategorizedProblem>(); for (MethodDeclaration methodDeclaration : changedInterface.getMethods()) { List<CategorizedProblem> methodProblems = doValidateMethodOnChangedType( methodDeclaration, dependentTypeBinding); problems.addAll(methodProblems); } List<ITypeBinding> superTypeBindings = new ArrayList<ITypeBinding>(); RemoteServiceUtilities.expandSuperInterfaces(dependentTypeBinding, superTypeBindings); for (ITypeBinding typeBinding : superTypeBindings) { for (IMethodBinding methodBinding : typeBinding.getDeclaredMethods()) { List<CategorizedProblem> dependentMethodProblems = doValidateMethodOnDependentInterface( methodBinding, changedInterface, typeBinding); problems.addAll(dependentMethodProblems); } } return problems; }
@Override public List<CategorizedProblem> validate(TypeDeclaration changedInterface, ITypeBinding dependentTypeBinding) { if (dependentTypeBinding != null && !RemoteServiceUtilities.isSynchronousInterface(dependentTypeBinding)) { // Not really an async interface return Collections.emptyList(); } return super.validate(changedInterface, dependentTypeBinding); }
@Override protected List<CategorizedProblem> doMissingDependentInterface( TypeDeclaration changedInterface) { // If the sync interface is missing assume that this is not an async // interface return Collections.emptyList(); }
/** * Validate that the AsyncCallback's parameterization and the sync method's * return type are assignment compatible. */ @SuppressWarnings("unchecked") private List<CategorizedProblem> doValidateReturnTypes( MethodDeclaration node, SingleVariableDeclaration lastParameter, ITypeBinding[] parameterTypes, IMethodBinding dependentMethod) { ITypeBinding asyncCallbackParam = parameterTypes[parameterTypes.length - 1]; if (asyncCallbackParam.isParameterizedType()) { ITypeBinding[] typeArguments = asyncCallbackParam.getTypeArguments(); ITypeBinding syncReturnTypeBinding = dependentMethod.getReturnType(); ITypeBinding typeBinding = syncReturnTypeBinding; if (syncReturnTypeBinding.isPrimitive()) { String qualifiedWrapperTypeName = JavaASTUtils.getWrapperTypeName(syncReturnTypeBinding.getQualifiedName()); typeBinding = node.getAST().resolveWellKnownType( qualifiedWrapperTypeName); } boolean compatible = false; if (typeBinding != null) { compatible = canAssign(typeArguments[0], typeBinding); } if (!compatible) { ParameterizedType parameterizedType = (ParameterizedType) lastParameter.getType(); List<Type> types = parameterizedType.typeArguments(); CategorizedProblem problem = RemoteServiceProblemFactory.newAsyncCallbackTypeArgumentMismatchOnAsync( types.get(0), typeArguments[0], syncReturnTypeBinding); if (problem != null) { return Collections.singletonList(problem); } } } return Collections.emptyList(); }
/** * Adds the given problem to the list of problems of this evaluation result. */ void addProblem(CategorizedProblem problem) { CategorizedProblem[] existingProblems = this.problems; int existingLength = existingProblems.length; this.problems = new CategorizedProblem[existingLength + 1]; System.arraycopy(existingProblems, 0, this.problems, 0, existingLength); this.problems[existingLength] = problem; }
private static boolean hasFatalError(CompilationUnit compilationUnit) { try { if (!((ICompilationUnit) compilationUnit.getJavaElement()).isStructureKnown()) return true; } catch (JavaModelException e) { JavaPlugin.log(e); return true; } IProblem[] problems= compilationUnit.getProblems(); for (int i= 0; i < problems.length; i++) { if (problems[i].isError()) { if (!(problems[i] instanceof CategorizedProblem)) return true; CategorizedProblem categorizedProblem= (CategorizedProblem) problems[i]; int categoryID= categorizedProblem.getCategoryID(); if (categoryID == CategorizedProblem.CAT_BUILDPATH) return true; if (categoryID == CategorizedProblem.CAT_SYNTAX) return true; if (categoryID == CategorizedProblem.CAT_IMPORT) return true; if (categoryID == CategorizedProblem.CAT_TYPE) return true; if (categoryID == CategorizedProblem.CAT_MEMBER) return true; if (categoryID == CategorizedProblem.CAT_INTERNAL) return true; } } return false; }
public void removeProblem(CategorizedProblem problem) { if (this.problemsMap != null) this.problemsMap.remove(problem); if (this.firstErrors != null) this.firstErrors.remove(problem); if (problem.isError()) { this.numberOfErrors--; } this.problemCount--; }
/** * Answer the errors encountered during compilation. */ public CategorizedProblem[] getErrors() { CategorizedProblem[] reportedProblems = getProblems(); int errorCount = 0; for (int i = 0; i < this.problemCount; i++) { if (reportedProblems[i].isError()) errorCount++; } if (errorCount == this.problemCount) return reportedProblems; CategorizedProblem[] errors = new CategorizedProblem[errorCount]; int index = 0; for (int i = 0; i < this.problemCount; i++) { if (reportedProblems[i].isError()) errors[index++] = reportedProblems[i]; } return errors; }
/** * Answer the tasks (TO-DO, ...) encountered during compilation. * * This is not a compiler internal API - it has side-effects ! * It is intended to be used only once all problems have been detected, * and makes sure the problems slot as the exact size of the number of * problems. */ public CategorizedProblem[] getTasks() { // Re-adjust the size of the tasks if necessary. if (this.tasks != null) { if (this.taskCount != this.tasks.length) { System.arraycopy(this.tasks, 0, (this.tasks = new CategorizedProblem[this.taskCount]), 0, this.taskCount); } // Stable sort problems per source positions. Arrays.sort(this.tasks, 0, this.tasks.length, CompilationResult.PROBLEM_COMPARATOR); //quickSort(tasks, 0, tasks.length-1); } return this.tasks; }
protected void printDebug(CategorizedProblem error) { if(CompletionEngine.DEBUG) { System.out.print("COMPLETION - completionFailure("); //$NON-NLS-1$ System.out.print(error); System.out.println(")"); //$NON-NLS-1$ } }