org.eclipse.jdt.core.compiler.IProblem Java Examples

The following examples show how to use org.eclipse.jdt.core.compiler.IProblem. 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 Project: junion   Author: TehLeo   File: SourceCompiler.java    License: 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 #2
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: UnusedCodeFix.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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)});
}
 
Example #3
Source Project: xtext-eclipse   Author: eclipse   File: JdtBasedTypeFactory.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected void createAnnotationValues(IBinding annotated, JvmAnnotationTarget result) {
	try {
		resolveAnnotations.start();
		IAnnotationBinding[] annotationBindings = annotated.getAnnotations();
		if (annotationBindings.length != 0) {
			InternalEList<JvmAnnotationReference> annotations = (InternalEList<JvmAnnotationReference>)result.getAnnotations();
			for (IAnnotationBinding annotation : annotationBindings) {
				annotations.addUnique(createAnnotationReference(annotation));
			}
		}
	} catch(AbortCompilation aborted) {
		if (aborted.problem.getID() == IProblem.IsClassPathCorrect) {
			// ignore
		} else {
			log.info("Couldn't resolve annotations of "+annotated, aborted);
		}
	} finally {
		resolveAnnotations.stop();
	}
}
 
Example #4
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};
}
 
Example #5
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: Java50CleanUp.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public int computeNumberOfFixes(CompilationUnit compilationUnit) {
	int result= 0;
	
	boolean addAnnotations= isEnabled(CleanUpConstants.ADD_MISSING_ANNOTATIONS);
	boolean addMissingOverride= addAnnotations && isEnabled(CleanUpConstants.ADD_MISSING_ANNOTATIONS_OVERRIDE);
	boolean addMissingOverrideInterfaceMethods= addMissingOverride && isEnabled(CleanUpConstants.ADD_MISSING_ANNOTATIONS_OVERRIDE_FOR_INTERFACE_METHOD_IMPLEMENTATION);
	boolean addMissingDeprecated= addAnnotations && isEnabled(CleanUpConstants.ADD_MISSING_ANNOTATIONS_DEPRECATED);
	boolean useTypeArgs= isEnabled(CleanUpConstants.VARIABLE_DECLARATION_USE_TYPE_ARGUMENTS_FOR_RAW_TYPE_REFERENCES);
	
	IProblem[] problems= compilationUnit.getProblems();
	for (int i= 0; i < problems.length; i++) {
		int id= problems[i].getID();
		if (addMissingOverride && Java50Fix.isMissingOverrideAnnotationProblem(id))
			if (! Java50Fix.isMissingOverrideAnnotationInterfaceProblem(id) || addMissingOverrideInterfaceMethods)
				result++;
		if (addMissingDeprecated && Java50Fix.isMissingDeprecationProblem(id))
			result++;
		if (useTypeArgs && Java50Fix.isRawTypeReferenceProblem(id))
			result++;
	}
	return result;
}
 
Example #6
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: UnusedCodeCleanUp.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public int computeNumberOfFixes(CompilationUnit compilationUnit) {
	int result= 0;
	IProblem[] problems= compilationUnit.getProblems();
	if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS) && !isEnabled(CleanUpConstants.ORGANIZE_IMPORTS)) {
		for (int i=0;i<problems.length;i++) {
			int id= problems[i].getID();
			if (id == IProblem.UnusedImport || id == IProblem.DuplicateImport || id == IProblem.ConflictingImport ||
				    id == IProblem.CannotImportPackage || id == IProblem.ImportNotFound)
				result++;
		}
	}
	if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS))
		result+= getNumberOfProblems(problems, IProblem.UnusedPrivateMethod);
	if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS))
		result+= getNumberOfProblems(problems, IProblem.UnusedPrivateConstructor);
	if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES))
		result+= getNumberOfProblems(problems, IProblem.UnusedPrivateType);
	if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS))
		result+= getNumberOfProblems(problems, IProblem.UnusedPrivateField);
	if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES))
		result+= getNumberOfProblems(problems, IProblem.LocalVariableIsNeverUsed);
	return result;
}
 
Example #7
Source Project: eclipse.jdt.ls   Author: eclipse   File: BaseDiagnosticsHandler.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("restriction")
private static Range convertRange(IOpenable openable, IProblem problem) {
	try {
		return JDTUtils.toRange(openable, problem.getSourceStart(), problem.getSourceEnd() - problem.getSourceStart() + 1);
	} catch (CoreException e) {
		// In case failed to open the IOpenable's buffer, use the IProblem's information to calculate the range.
		Position start = new Position();
		Position end = new Position();

		start.setLine(problem.getSourceLineNumber() - 1);// The protocol 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);
	}
}
 
Example #8
Source Project: eclipse.jdt.ls   Author: eclipse   File: CodeActionHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@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 = CodeActionUtil.getRange(unit, "java.sql");
	params.setRange(range);
	params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.UnusedImport), range))));
	List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
	Assert.assertNotNull(codeActions);
	Assert.assertTrue(codeActions.size() >= 3);
	Assert.assertEquals(codeActions.get(0).getRight().getKind(), CodeActionKind.QuickFix);
	Assert.assertEquals(codeActions.get(1).getRight().getKind(), CodeActionKind.QuickFix);
	Assert.assertEquals(codeActions.get(2).getRight().getKind(), CodeActionKind.SourceOrganizeImports);
	Command c = codeActions.get(0).getRight().getCommand();
	Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand());
}
 
Example #9
Source Project: eclipse.jdt.ls   Author: eclipse   File: CodeActionHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCodeAction_quickfixActionsOnly() throws Exception {
	ICompilationUnit unit = getWorkingCopy(
			"src/java/Foo.java",
			"public class Foo {\n"+
			"	void foo() {\n"+
			"		String bar = \"astring\";"+
			"	}\n"+
			"}\n");
	CodeActionParams params = new CodeActionParams();
	params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
	final Range range = CodeActionUtil.getRange(unit, "bar");
	params.setRange(range);
	CodeActionContext context = new CodeActionContext(
		Arrays.asList(getDiagnostic(Integer.toString(IProblem.LocalVariableIsNeverUsed), range)),
		Collections.singletonList(CodeActionKind.QuickFix)
	);
	params.setContext(context);
	List<Either<Command, CodeAction>> quickfixActions = getCodeActions(params);

	Assert.assertNotNull(quickfixActions);
	Assert.assertFalse("No quickfix actions were found", quickfixActions.isEmpty());
	for (Either<Command, CodeAction> codeAction : quickfixActions) {
		Assert.assertTrue("Unexpected kind:" + codeAction.getRight().getKind(), codeAction.getRight().getKind().startsWith(CodeActionKind.QuickFix));
	}
}
 
Example #10
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;
}
 
Example #11
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: CompilationUnit.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the list of messages reported by the compiler during the parsing
 * or the type checking of this compilation unit. This list might be a subset of
 * errors detected and reported by a Java compiler.
 * <p>
 * This list of messages is suitable for simple clients that do little
 * more than log the messages or display them to the user. Clients that
 * need further details should call <code>getProblems</code> to get
 * compiler problem objects.
 * </p>
 *
 * @return the list of messages, possibly empty
 * @see #getProblems()
 * @see ASTParser
 */
public Message[] getMessages() {
	if (this.messages == null) {
		int problemLength = this.problems.length;
		if (problemLength == 0) {
			this.messages = EMPTY_MESSAGES;
		} else {
			this.messages = new Message[problemLength];
			for (int i = 0; i < problemLength; i++) {
				IProblem problem = this.problems[i];
				int start = problem.getSourceStart();
				int end = problem.getSourceEnd();
				this.messages[i] = new Message(problem.getMessage(), start, end - start + 1);
			}
		}
	}
	return this.messages;
}
 
Example #12
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: UnimplementedCodeCleanUp.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@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();
}
 
Example #13
Source Project: packagedrone   Author: eclipse   File: JDTJavaCompiler.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #14
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: UnusedCodeFix.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit,
		boolean removeUnusedPrivateMethods,
		boolean removeUnusedPrivateConstructors,
		boolean removeUnusedPrivateFields,
		boolean removeUnusedPrivateTypes,
		boolean removeUnusedLocalVariables,
		boolean removeUnusedImports,
		boolean removeUnusedCast) {

	IProblem[] problems= compilationUnit.getProblems();
	IProblemLocation[] locations= new IProblemLocation[problems.length];
	for (int i= 0; i < problems.length; i++) {
		locations[i]= new ProblemLocation(problems[i]);
	}

	return createCleanUp(compilationUnit, locations,
			removeUnusedPrivateMethods,
			removeUnusedPrivateConstructors,
			removeUnusedPrivateFields,
			removeUnusedPrivateTypes,
			removeUnusedLocalVariables,
			removeUnusedImports,
			removeUnusedCast);
}
 
Example #15
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: CompilationResult.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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;
		}
	}
}
 
Example #16
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, boolean addSerialVersionIds) {

		IProblem[] problems= compilationUnit.getProblems();
		IProblemLocation[] locations= new IProblemLocation[problems.length];
		for (int i= 0; i < problems.length; i++) {
			locations[i]= new ProblemLocation(problems[i]);
		}
		return createCleanUp(compilationUnit, locations, addSerialVersionIds);
	}
 
Example #17
private static boolean hasProblem(IProblem[] problems, IProblemLocation location) {
	for (int i= 0; i < problems.length; i++) {
		IProblem problem= problems[i];
		if (problem.getID() == location.getProblemId() && problem.getSourceStart() == location.getOffset())
			return true;
	}
	return false;
}
 
Example #18
Source Project: jetbrick-template-1x   Author: subchen   File: JdtCompiler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void generateJavaClass(JavaSource source) throws IOException {
    INameEnvironment env = new NameEnvironment(source);
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    CompilerOptions options = getCompilerOptions();
    CompilerRequestor requestor = new CompilerRequestor();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());

    Compiler compiler = new Compiler(env, policy, options, requestor, problemFactory);
    compiler.compile(new ICompilationUnit[] { new CompilationUnit(source) });

    if (requestor.hasErrors()) {
        String sourceCode = source.getSourceCode();
        String[] sourceCodeLines = sourceCode.split("(\r\n|\r|\n)", -1);
        StringBuilder sb = new StringBuilder();
        sb.append("Compilation failed.");
        sb.append('\n');
        for (IProblem p : requestor.getErrors()) {
            sb.append(p.getMessage()).append('\n');
            int start = p.getSourceStart();
            int column = start; // default
            for (int i = start; i >= 0; i--) {
                char c = sourceCode.charAt(i);
                if (c == '\n' || c == '\r') {
                    column = start - i;
                    break;
                }
            }
            sb.append(StringUtils.getPrettyError(sourceCodeLines, p.getSourceLineNumber(), column, p.getSourceStart(), p.getSourceEnd(), 3));
        }
        sb.append(requestor.getErrors().length);
        sb.append(" error(s)\n");
        throw new CompileErrorException(sb.toString());
    }

    requestor.save(source.getOutputdir());
}
 
Example #19
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: LinkedNodeFinder.java    License: Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example #20
Source Project: eclipse.jdt.ls   Author: eclipse   File: RefactorProposalUtility.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static CUCorrectionProposal getAssignFieldProposal(CodeActionParams params, IInvocationContext context, boolean problemsAtLocation, Map formatterOptions, boolean returnAsCommand,
		IProblemLocationCore[] locations) throws CoreException {
	ASTNode node = context.getCoveringNode();
	Statement statement = ASTResolving.findParentStatement(node);
	if (!(statement instanceof ExpressionStatement)) {
		return null;
	}
	ExpressionStatement expressionStatement = (ExpressionStatement) statement;
	Expression expression = expressionStatement.getExpression();
	if (expression.getNodeType() == ASTNode.ASSIGNMENT) {
		return null;
	}
	ITypeBinding typeBinding = expression.resolveTypeBinding();
	typeBinding = Bindings.normalizeTypeBinding(typeBinding);
	if (typeBinding == null) {
		return null;
	}
	if (containsMatchingProblem(locations, IProblem.UnusedObjectAllocation)) {
		return null;
	}
	final ICompilationUnit cu = context.getCompilationUnit();
	ASTNode type = ASTResolving.findParentType(expression);
	if (type != null) {
		int relevance;
		if (context.getSelectionLength() == 0) {
			relevance = IProposalRelevance.EXTRACT_LOCAL_ZERO_SELECTION;
		} else if (problemsAtLocation) {
			relevance = IProposalRelevance.EXTRACT_LOCAL_ERROR;
		} else {
			relevance = IProposalRelevance.EXTRACT_LOCAL;
		}
		if (returnAsCommand) {
			return new AssignToVariableAssistCommandProposal(cu, JavaCodeActionKind.REFACTOR_ASSIGN_FIELD, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, relevance, APPLY_REFACTORING_COMMAND_ID,
					Arrays.asList(ASSIGN_FIELD_COMMAND, params));
		} else {
			return new AssignToVariableAssistProposal(cu, JavaCodeActionKind.REFACTOR_ASSIGN_FIELD, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, relevance);
		}
	}
	return null;
}
 
Example #21
Source Project: juniversal   Author: juniversal   File: TranslateNodeTest.java    License: 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 #22
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ClasspathAccessRule.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public int getKind() {
	switch (getProblemId()) {
		case IProblem.ForbiddenReference:
			return K_NON_ACCESSIBLE;
		case IProblem.DiscouragedReference:
			return K_DISCOURAGED;
		default:
			return K_ACCESSIBLE;
	}
}
 
Example #23
Source Project: eclipse.jdt.ls   Author: eclipse   File: RefactoringAnalyzeUtil.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private static boolean isCorresponding(IProblem oldProblem, IProblem iProblem) {
	if (oldProblem.getID() != iProblem.getID()) {
		return false;
	}
	if (!oldProblem.getMessage().equals(iProblem.getMessage())) {
		return false;
	}
	return true;
}
 
Example #24
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ProblemLocation.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private String getErrorCode(int code) {
	StringBuffer buf= new StringBuffer();

	if ((code & IProblem.TypeRelated) != 0) {
		buf.append("TypeRelated + "); //$NON-NLS-1$
	}
	if ((code & IProblem.FieldRelated) != 0) {
		buf.append("FieldRelated + "); //$NON-NLS-1$
	}
	if ((code & IProblem.ConstructorRelated) != 0) {
		buf.append("ConstructorRelated + "); //$NON-NLS-1$
	}
	if ((code & IProblem.MethodRelated) != 0) {
		buf.append("MethodRelated + "); //$NON-NLS-1$
	}
	if ((code & IProblem.ImportRelated) != 0) {
		buf.append("ImportRelated + "); //$NON-NLS-1$
	}
	if ((code & IProblem.Internal) != 0) {
		buf.append("Internal + "); //$NON-NLS-1$
	}
	if ((code & IProblem.Syntax) != 0) {
		buf.append("Syntax + "); //$NON-NLS-1$
	}
	if ((code & IProblem.Javadoc) != 0) {
		buf.append("Javadoc + "); //$NON-NLS-1$
	}
	buf.append(code & IProblem.IgnoreCategoriesMask);

	return buf.toString();
}
 
Example #25
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: QuickAssistProcessor.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static boolean getAssignToVariableProposals(IInvocationContext context, ASTNode node, IProblemLocation[] locations, Collection<ICommandAccess> resultingCollections) {
	Statement statement= ASTResolving.findParentStatement(node);
	if (!(statement instanceof ExpressionStatement)) {
		return false;
	}
	ExpressionStatement expressionStatement= (ExpressionStatement) statement;

	Expression expression= expressionStatement.getExpression();
	if (expression.getNodeType() == ASTNode.ASSIGNMENT) {
		return false; // too confusing and not helpful
	}

	ITypeBinding typeBinding= expression.resolveTypeBinding();
	typeBinding= Bindings.normalizeTypeBinding(typeBinding);
	if (typeBinding == null) {
		return false;
	}
	if (resultingCollections == null) {
		return true;
	}

	// don't add if already added as quick fix
	if (containsMatchingProblem(locations, IProblem.UnusedObjectAllocation))
		return false;
	
	ICompilationUnit cu= context.getCompilationUnit();

	AssignToVariableAssistProposal localProposal= new AssignToVariableAssistProposal(cu, AssignToVariableAssistProposal.LOCAL, expressionStatement, typeBinding, IProposalRelevance.ASSIGN_TO_LOCAL);
	localProposal.setCommandId(ASSIGN_TO_LOCAL_ID);
	resultingCollections.add(localProposal);

	ASTNode type= ASTResolving.findParentType(expression);
	if (type != null) {
		AssignToVariableAssistProposal fieldProposal= new AssignToVariableAssistProposal(cu, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, IProposalRelevance.ASSIGN_TO_FIELD);
		fieldProposal.setCommandId(ASSIGN_TO_FIELD_ID);
		resultingCollections.add(fieldProposal);
	}
	return true;

}
 
Example #26
Source Project: eclipse.jdt.ls   Author: eclipse   File: ExtractConstantRefactoring.java    License: 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 #27
Source Project: eclipse.jdt.ls   Author: eclipse   File: GetterSetterCorrectionSubProcessor.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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, IProblemLocationCore[] locations, ArrayList<ChangeCorrectionProposal> 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);
}
 
Example #28
Source Project: eclipse.jdt.ls   Author: eclipse   File: JavadocTagsSubProcessor.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static void getUnusedAndUndocumentedParameterOrExceptionProposals(IInvocationContext context,
		IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();
	IJavaProject project= cu.getJavaProject();

	if (!JavaCore.ENABLED.equals(project.getOption(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, true))) {
		return;
	}

	int problemId= problem.getProblemId();
	boolean isUnusedTypeParam= problemId == IProblem.UnusedTypeParameter;
	boolean isUnusedParam= problemId == IProblem.ArgumentIsNeverUsed || isUnusedTypeParam;
	String key= isUnusedParam ? JavaCore.COMPILER_PB_UNUSED_PARAMETER_INCLUDE_DOC_COMMENT_REFERENCE : JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION_INCLUDE_DOC_COMMENT_REFERENCE;

	if (!JavaCore.ENABLED.equals(project.getOption(key, true))) {
		return;
	}

	ASTNode node= problem.getCoveringNode(context.getASTRoot());
	if (node == null) {
		return;
	}

	BodyDeclaration bodyDecl= ASTResolving.findParentBodyDeclaration(node);
	if (bodyDecl == null || ASTResolving.getParentMethodOrTypeBinding(bodyDecl) == null) {
		return;
	}

	String label;
	if (isUnusedTypeParam) {
		label= CorrectionMessages.JavadocTagsSubProcessor_document_type_parameter_description;
	} else if (isUnusedParam) {
		label= CorrectionMessages.JavadocTagsSubProcessor_document_parameter_description;
	} else {
		node= ASTNodes.getNormalizedNode(node);
		label= CorrectionMessages.JavadocTagsSubProcessor_document_exception_description;
	}
	ASTRewriteCorrectionProposal proposal= new AddMissingJavadocTagProposal(label, context.getCompilationUnit(), bodyDecl, node, IProposalRelevance.DOCUMENT_UNUSED_ITEM);
	proposals.add(proposal);
}
 
Example #29
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ASTNodes.java    License: 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 #30
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: TypeContextChecker.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private static Type parseType(String typeString, IJavaProject javaProject, List<String> problemsCollector) {
	if ("".equals(typeString.trim())) //speed up for a common case //$NON-NLS-1$
		return null;
	if (! typeString.trim().equals(typeString))
		return null;

	StringBuffer cuBuff= new StringBuffer();
	cuBuff.append("interface A{"); //$NON-NLS-1$
	int offset= cuBuff.length();
	cuBuff.append(typeString).append(" m();}"); //$NON-NLS-1$

	ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	p.setSource(cuBuff.toString().toCharArray());
	p.setProject(javaProject);
	CompilationUnit cu= (CompilationUnit) p.createAST(null);
	Selection selection= Selection.createFromStartLength(offset, typeString.length());
	SelectionAnalyzer analyzer= new SelectionAnalyzer(selection, false);
	cu.accept(analyzer);
	ASTNode selected= analyzer.getFirstSelectedNode();
	if (!(selected instanceof Type))
		return null;
	Type type= (Type)selected;
	if (MethodTypesSyntaxChecker.isVoidArrayType(type))
		return null;
	IProblem[] problems= ASTNodes.getProblems(type, ASTNodes.NODE_ONLY, ASTNodes.PROBLEMS);
	if (problems.length > 0) {
		for (int i= 0; i < problems.length; i++)
			problemsCollector.add(problems[i].getMessage());
	}

	String typeNodeRange= cuBuff.substring(type.getStartPosition(), ASTNodes.getExclusiveEnd(type));
	if (typeString.equals(typeNodeRange))
		return type;
	else
		return null;
}