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 File: Java50CleanUp.java    From Eclipse-Postfix-Code-Completion with 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 #2
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with 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 File: JdtBasedTypeFactory.java    From xtext-eclipse with 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
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 #5
Source File: PotentialProgrammingProblemsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #6
Source File: UnusedCodeCleanUp.java    From Eclipse-Postfix-Code-Completion with 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 File: BaseDiagnosticsHandler.java    From eclipse.jdt.ls with 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 File: CodeActionHandlerTest.java    From eclipse.jdt.ls with 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 File: CodeActionHandlerTest.java    From eclipse.jdt.ls with 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
Source File: NullAnnotationsCorrectionProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 File: CompilationUnit.java    From Eclipse-Postfix-Code-Completion with 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 File: UnimplementedCodeCleanUp.java    From Eclipse-Postfix-Code-Completion with 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 File: JDTJavaCompiler.java    From packagedrone with 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 File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with 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 File: CompilationResult.java    From Eclipse-Postfix-Code-Completion with 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
Source File: SelfEncapsulateFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void checkCompileErrors(RefactoringStatus result, CompilationUnit root, ICompilationUnit element) {
	IProblem[] messages= root.getProblems();
	for (int i= 0; i < messages.length; i++) {
		IProblem problem= messages[i];
		if (!isIgnorableProblem(problem)) {
			result.addWarning(Messages.format(
					RefactoringCoreMessages.SelfEncapsulateField_compiler_errors_update,
					BasicElementLabels.getFileName(element)), JavaStatusContext.create(element));
			return;
		}
	}
}
 
Example #17
Source File: ProblemHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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 File: PotentialProgrammingProblemsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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 #19
Source File: CompilationUnit.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Sets the array of problems reported by the compiler during the parsing or
 * name resolution of this compilation unit.
 *
 * @param problems the list of problems
 */
void setProblems(IProblem[] problems) {
	if (problems == null) {
		throw new IllegalArgumentException();
	}
	this.problems = problems;
}
 
Example #20
Source File: CodeStyleFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit,
		boolean addThisQualifier,
		boolean changeNonStaticAccessToStatic,
		boolean qualifyStaticFieldAccess,
		boolean changeIndirectStaticAccessToDirect,
		boolean qualifyMethodAccess,
		boolean qualifyStaticMethodAccess,
		boolean removeFieldQualifier,
		boolean removeMethodQualifier) {

	if (!addThisQualifier && !changeNonStaticAccessToStatic && !qualifyStaticFieldAccess && !changeIndirectStaticAccessToDirect && !qualifyMethodAccess && !qualifyStaticMethodAccess && !removeFieldQualifier && !removeMethodQualifier)
		return null;

	List<CompilationUnitRewriteOperation> operations= new ArrayList<CompilationUnitRewriteOperation>();
	if (addThisQualifier || qualifyStaticFieldAccess || qualifyMethodAccess || qualifyStaticMethodAccess) {
		CodeStyleVisitor codeStyleVisitor= new CodeStyleVisitor(compilationUnit, addThisQualifier, qualifyStaticFieldAccess, qualifyMethodAccess, qualifyStaticMethodAccess, operations);
		compilationUnit.accept(codeStyleVisitor);
	}

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

	if (removeFieldQualifier || removeMethodQualifier) {
		ThisQualifierVisitor visitor= new ThisQualifierVisitor(removeFieldQualifier, removeMethodQualifier, compilationUnit, operations);
		compilationUnit.accept(visitor);
	}

	if (operations.isEmpty())
		return null;

	CompilationUnitRewriteOperation[] operationsArray= operations.toArray(new CompilationUnitRewriteOperation[operations.size()]);
	return new CodeStyleFix(FixMessages.CodeStyleFix_change_name, compilationUnit, operationsArray);
}
 
Example #21
Source File: NullAnnotationsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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);
		}
	}
}
 
Example #22
Source File: TypeParametersFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static TypeParametersFix createRemoveRedundantTypeArgumentsFix(CompilationUnit compilationUnit, IProblemLocation problem) {
	int id= problem.getProblemId();
	if (id == IProblem.RedundantSpecificationOfTypeArguments) {
		ParameterizedType parameterizedType= getParameterizedType(compilationUnit, problem);
		if (parameterizedType == null)
			return null;
		RemoveTypeArgumentsOperation operation= new RemoveTypeArgumentsOperation(parameterizedType);
		return new TypeParametersFix(FixMessages.TypeParametersFix_remove_redundant_type_arguments_name, compilationUnit, new CompilationUnitRewriteOperation[] { operation });
	}
	return null;
}
 
Example #23
Source File: UnimplementedCodeCleanUp.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@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);
}
 
Example #24
Source File: RefactorProposalUtility.java    From eclipse.jdt.ls with 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 #25
Source File: ClasspathAccessRule.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static int toProblemId(int kind) {
	boolean ignoreIfBetter = (kind & IAccessRule.IGNORE_IF_BETTER) != 0;
	switch (kind & ~IAccessRule.IGNORE_IF_BETTER) {
		case K_NON_ACCESSIBLE:
			return ignoreIfBetter ? IProblem.ForbiddenReference | AccessRule.IgnoreIfBetter : IProblem.ForbiddenReference;
		case K_DISCOURAGED:
			return ignoreIfBetter ? IProblem.DiscouragedReference | AccessRule.IgnoreIfBetter : IProblem.DiscouragedReference;
		default:
			return ignoreIfBetter ? AccessRule.IgnoreIfBetter : 0;
	}
}
 
Example #26
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testCodeAction_superfluousSemicolon() throws Exception{
	ICompilationUnit unit = getWorkingCopy(
			"src/java/Foo.java",
			"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, ";");
	params.setRange(range);
	params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.SuperfluousSemicolon), range))));
	List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
	Assert.assertNotNull(codeActions);
	Assert.assertEquals(1, codeActions.size());
	Assert.assertEquals(codeActions.get(0), CodeActionKind.QuickFix);
	Command c = getCommand(codeActions.get(0));
	Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand());
	Assert.assertNotNull(c.getArguments());
	Assert.assertTrue(c.getArguments().get(0) instanceof WorkspaceEdit);
	WorkspaceEdit we = (WorkspaceEdit) c.getArguments().get(0);
	List<org.eclipse.lsp4j.TextEdit> edits = we.getChanges().get(JDTUtils.toURI(unit));
	Assert.assertEquals(1, edits.size());
	Assert.assertEquals("", edits.get(0).getNewText());
	Assert.assertEquals(range, edits.get(0).getRange());
}
 
Example #27
Source File: LinkedNodeFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static SimpleName[] findByProblems(ASTNode parent, SimpleName nameNode) {
	ArrayList<SimpleName> res= new ArrayList<SimpleName>();

	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()]);
}
 
Example #28
Source File: CorrectionMarkerResolutionGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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 #29
Source File: CompilationUnitDocumentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Sets up the infrastructure necessary for problem reporting.
 *
 * @param insideReportingSequence <code>true</code> if this method
 *            call is issued from inside a reporting sequence
 */
private void internalBeginReporting(boolean insideReportingSequence) {
	if (fCompilationUnit != null && fCompilationUnit.getJavaProject().isOnClasspath(fCompilationUnit)) {
		ProblemRequestorState state= new ProblemRequestorState();
		state.fInsideReportingSequence= insideReportingSequence;
		state.fReportedProblems= new ArrayList<IProblem>();
		synchronized (getLockObject()) {
			fProblemRequestorState.set(state);
			++fStateCount;
		}
	}
}
 
Example #30
Source File: StaticReferenceQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testInstanceFieldDuringConstructorInvocation() throws Exception {
	// Problem we are testing
	int problem = IProblem.NonStaticFieldFromStaticInvocation;

	IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class A {\n");
	buf.append("	int i;");
	buf.append("	A () {\n");
	buf.append("		this(i);\n"); // referencing in static context
	buf.append("	}\n");
	buf.append("}\n");
	ICompilationUnit cu = pack.createCompilationUnit("A.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class A {\n");
	buf.append("	static int i;");
	buf.append("	A () {\n");
	buf.append("		this(i);\n"); // referencing in static context
	buf.append("	}\n");
	buf.append("}\n");

	Expected e1 = new Expected("Change 'i' to 'static'", buf.toString());

	Range selection = CodeActionUtil.getRange(cu, "FOOBAR");
	assertCodeActions(cu, selection, e1);
}