Java Code Examples for org.eclipse.jdt.ui.text.java.IInvocationContext#getCompilationUnit()

The following examples show how to use org.eclipse.jdt.ui.text.java.IInvocationContext#getCompilationUnit() . 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: ReturnTypeSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void addMethodWithConstrNameProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();

	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof MethodDeclaration) {
		MethodDeclaration declaration= (MethodDeclaration) selectedNode;

		ASTRewrite rewrite= ASTRewrite.create(declaration.getAST());
		rewrite.set(declaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.TRUE, null);

		String label= CorrectionMessages.ReturnTypeSubProcessor_constrnamemethod_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_TO_CONSTRUCTOR, image);
		proposals.add(proposal);
	}

}
 
Example 2
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean getAddElseProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
	if (!(node instanceof IfStatement)) {
		return false;
	}
	IfStatement ifStatement= (IfStatement) node;
	if (ifStatement.getElseStatement() != null) {
		return false;
	}

	if (resultingCollections == null) {
		return true;
	}

	AST ast= node.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	Block body= ast.newBlock();

	rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, body, null);

	String label= CorrectionMessages.QuickAssistProcessor_addelseblock_description;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_ELSE_BLOCK, image);
	resultingCollections.add(proposal);
	return true;
}
 
Example 3
Source File: ModifierCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void addNeedToEmulateProposal(IInvocationContext context, IProblemLocation problem, Collection<ModifierChangeCorrectionProposal> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();

	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (!(selectedNode instanceof SimpleName)) {
		return;
	}

	IBinding binding= ((SimpleName) selectedNode).resolveBinding();
	if (binding instanceof IVariableBinding) {
		binding= ((IVariableBinding) binding).getVariableDeclaration();
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		String label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changemodifiertofinal_description, BasicElementLabels.getJavaElementName(binding.getName()));
		proposals.add(new ModifierChangeCorrectionProposal(label, cu, binding, selectedNode, Modifier.FINAL, 0, IProposalRelevance.CHANGE_MODIFIER_OF_VARIABLE_TO_FINAL, image));
	}
}
 
Example 4
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void getAmbiguosTypeReferenceProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException {
	final ICompilationUnit cu= context.getCompilationUnit();
	int offset= problem.getOffset();
	int len= problem.getLength();

	IJavaElement[] elements= cu.codeSelect(offset, len);
	for (int i= 0; i < elements.length; i++) {
		IJavaElement curr= elements[i];
		if (curr instanceof IType && !TypeFilter.isFiltered((IType) curr)) {
			String qualifiedTypeName= ((IType) curr).getFullyQualifiedName('.');

			CompilationUnit root= context.getASTRoot();

			String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importexplicit_description, BasicElementLabels.getJavaElementName(qualifiedTypeName));
			Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
			ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, ASTRewrite.create(root.getAST()), IProposalRelevance.IMPORT_EXPLICIT, image);

			ImportRewrite imports= proposal.createImportRewrite(root);
			imports.addImport(qualifiedTypeName);

			proposals.add(proposal);
		}
	}
}
 
Example 5
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static ASTRewriteCorrectionProposal createNoSideEffectProposal(IInvocationContext context, SimpleName nodeToQualify, IVariableBinding fieldBinding, String label, int relevance) {
	AST ast= nodeToQualify.getAST();

	Expression qualifier;
	if (Modifier.isStatic(fieldBinding.getModifiers())) {
		ITypeBinding declaringClass= fieldBinding.getDeclaringClass();
		qualifier= ast.newSimpleName(declaringClass.getTypeDeclaration().getName());
	} else {
		qualifier= ast.newThisExpression();
	}

	ASTRewrite rewrite= ASTRewrite.create(ast);
	FieldAccess access= ast.newFieldAccess();
	access.setName((SimpleName) rewrite.createCopyTarget(nodeToQualify));
	access.setExpression(qualifier);
	rewrite.replace(nodeToQualify, access, null);


	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	return new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, relevance, image);
}
 
Example 6
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void addUnnecessaryThrownExceptionProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	selectedNode= ASTNodes.getNormalizedNode(selectedNode);
	if (selectedNode == null || selectedNode.getLocationInParent() != MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY) {
		return;
	}
	MethodDeclaration decl= (MethodDeclaration) selectedNode.getParent();
	IMethodBinding binding= decl.resolveBinding();
	if (binding != null) {
		List<Type> thrownExceptions= decl.thrownExceptionTypes();
		int index= thrownExceptions.indexOf(selectedNode);
		if (index == -1) {
			return;
		}
		ChangeDescription[] desc= new ChangeDescription[thrownExceptions.size()];
		desc[index]= new RemoveDescription();

		ICompilationUnit cu= context.getCompilationUnit();
		String label= CorrectionMessages.LocalCorrectionsSubProcessor_unnecessarythrow_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);

		proposals.add(new ChangeMethodSignatureProposal(label, cu, selectedNode, binding, null, desc, IProposalRelevance.UNNECESSARY_THROW, image));
	}

	JavadocTagsSubProcessor.getUnusedAndUndocumentedParameterOrExceptionProposals(context, problem, proposals);
}
 
Example 7
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void addRedundantSuperInterfaceProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (!(selectedNode instanceof Name)) {
		return;
	}
	ASTNode node= ASTNodes.getNormalizedNode(selectedNode);

	ASTRewrite rewrite= ASTRewrite.create(node.getAST());
	rewrite.remove(node, null);

	String label= CorrectionMessages.LocalCorrectionsSubProcessor_remove_redundant_superinterface;
	Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);

	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_REDUNDANT_SUPER_INTERFACE, image);
	proposals.add(proposal);

}
 
Example 8
Source File: ModifierCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void addAddMethodModifierProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals, int modifier, String label) {
	ICompilationUnit cu= context.getCompilationUnit();

	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (!(selectedNode instanceof MethodDeclaration)) {
		return;
	}

	IBinding binding= ((MethodDeclaration) selectedNode).resolveBinding();
	if (binding instanceof IMethodBinding) {
		binding= ((IMethodBinding) binding).getMethodDeclaration();
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		proposals.add(new ModifierChangeCorrectionProposal(label, cu, binding, selectedNode, modifier, 0, IProposalRelevance.ADD_METHOD_MODIFIER, image));
	}
}
 
Example 9
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean getInverseConditionalExpressionProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
	// try to find conditional expression as parent
	while (covering instanceof Expression) {
		if (covering instanceof ConditionalExpression)
			break;
		covering= covering.getParent();
	}
	if (!(covering instanceof ConditionalExpression)) {
		return false;
	}
	ConditionalExpression expression= (ConditionalExpression) covering;
	//  we could produce quick assist
	if (resultingCollections == null) {
		return true;
	}
	//
	AST ast= covering.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	// prepare new conditional expression
	ConditionalExpression newExpression= ast.newConditionalExpression();
	newExpression.setExpression(getInversedExpression(rewrite, expression.getExpression()));
	newExpression.setThenExpression((Expression) rewrite.createCopyTarget(expression.getElseExpression()));
	newExpression.setElseExpression((Expression) rewrite.createCopyTarget(expression.getThenExpression()));
	// replace old expression with new
	rewrite.replace(expression, newExpression, null);
	// add correction proposal
	String label= CorrectionMessages.AdvancedQuickAssistProcessor_inverseConditionalExpression_description;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_CONDITIONAL_EXPRESSION, image);
	resultingCollections.add(proposal);
	return true;
}
 
Example 10
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean getInlineLocalProposal(IInvocationContext context, final ASTNode node, Collection<ICommandAccess> proposals) throws CoreException {
	if (!(node instanceof SimpleName))
		return false;

	SimpleName name= (SimpleName) node;
	IBinding binding= name.resolveBinding();
	if (!(binding instanceof IVariableBinding))
		return false;
	IVariableBinding varBinding= (IVariableBinding) binding;
	if (varBinding.isField() || varBinding.isParameter())
		return false;
	ASTNode decl= context.getASTRoot().findDeclaringNode(varBinding);
	if (!(decl instanceof VariableDeclarationFragment) || decl.getLocationInParent() != VariableDeclarationStatement.FRAGMENTS_PROPERTY)
		return false;

	if (proposals == null) {
		return true;
	}

	InlineTempRefactoring refactoring= new InlineTempRefactoring((VariableDeclaration) decl);
	if (refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
		String label= CorrectionMessages.QuickAssistProcessor_inline_local_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		RefactoringCorrectionProposal proposal= new RefactoringCorrectionProposal(label, context.getCompilationUnit(), refactoring, IProposalRelevance.INLINE_LOCAL, image);
		proposal.setCommandId(INLINE_LOCAL_ID);
		proposals.add(proposal);

	}
	return true;
}
 
Example 11
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean getExtractMethodProposal(IInvocationContext context, ASTNode coveringNode, boolean problemsAtLocation, Collection<ICommandAccess> proposals) throws CoreException {
	if (!(coveringNode instanceof Expression) && !(coveringNode instanceof Statement) && !(coveringNode instanceof Block)) {
		return false;
	}
	if (coveringNode instanceof Block) {
		List<Statement> statements= ((Block) coveringNode).statements();
		int startIndex= getIndex(context.getSelectionOffset(), statements);
		if (startIndex == -1)
			return false;
		int endIndex= getIndex(context.getSelectionOffset() + context.getSelectionLength(), statements);
		if (endIndex == -1 || endIndex <= startIndex)
			return false;
	}

	if (proposals == null) {
		return true;
	}

	final ICompilationUnit cu= context.getCompilationUnit();
	final ExtractMethodRefactoring extractMethodRefactoring= new ExtractMethodRefactoring(context.getASTRoot(), context.getSelectionOffset(), context.getSelectionLength());
	extractMethodRefactoring.setMethodName("extracted"); //$NON-NLS-1$
	if (extractMethodRefactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
		String label= CorrectionMessages.QuickAssistProcessor_extractmethod_description;
		LinkedProposalModel linkedProposalModel= new LinkedProposalModel();
		extractMethodRefactoring.setLinkedProposalModel(linkedProposalModel);

		Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
		int relevance= problemsAtLocation ? IProposalRelevance.EXTRACT_METHOD_ERROR : IProposalRelevance.EXTRACT_METHOD;
		RefactoringCorrectionProposal proposal= new RefactoringCorrectionProposal(label, cu, extractMethodRefactoring, relevance, image);
		proposal.setCommandId(EXTRACT_METHOD_INPLACE_ID);
		proposal.setLinkedProposalModel(linkedProposalModel);
		proposals.add(proposal);
	}
	return true;
}
 
Example 12
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean getInverseIfProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
	if (!(covering instanceof IfStatement)) {
		return false;
	}
	IfStatement ifStatement= (IfStatement) covering;
	if (ifStatement.getElseStatement() == null) {
		return false;
	}
	//  we could produce quick assist
	if (resultingCollections == null) {
		return true;
	}
	//
	AST ast= covering.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	Statement thenStatement= ifStatement.getThenStatement();
	Statement elseStatement= ifStatement.getElseStatement();

	// prepare original nodes
	Expression inversedExpression= getInversedExpression(rewrite, ifStatement.getExpression());

	Statement newElseStatement= (Statement) rewrite.createMoveTarget(thenStatement);
	Statement newThenStatement= (Statement) rewrite.createMoveTarget(elseStatement);
	// set new nodes
	rewrite.set(ifStatement, IfStatement.EXPRESSION_PROPERTY, inversedExpression, null);

	if (elseStatement instanceof IfStatement) {// bug 79507 && bug 74580
		Block elseBlock= ast.newBlock();
		elseBlock.statements().add(newThenStatement);
		newThenStatement= elseBlock;
	}
	rewrite.set(ifStatement, IfStatement.THEN_STATEMENT_PROPERTY, newThenStatement, null);
	rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, newElseStatement, null);
	// add correction proposal
	String label= CorrectionMessages.AdvancedQuickAssistProcessor_inverseIf_description;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_IF_STATEMENT, image);
	resultingCollections.add(proposal);
	return true;
}
 
Example 13
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addUninitializedLocalVariableProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();

	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (!(selectedNode instanceof Name)) {
		return;
	}
	Name name= (Name) selectedNode;
	IBinding binding= name.resolveBinding();
	if (!(binding instanceof IVariableBinding)) {
		return;
	}
	IVariableBinding varBinding= (IVariableBinding) binding;

	CompilationUnit astRoot= context.getASTRoot();
	ASTNode node= astRoot.findDeclaringNode(binding);
	if (node instanceof VariableDeclarationFragment) {
		ASTRewrite rewrite= ASTRewrite.create(node.getAST());

		VariableDeclarationFragment fragment= (VariableDeclarationFragment) node;
		if (fragment.getInitializer() != null) {
			return;
		}
		Expression expression= ASTNodeFactory.newDefaultExpression(astRoot.getAST(), varBinding.getType());
		if (expression == null) {
			return;
		}
		rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, expression, null);

		String label= CorrectionMessages.LocalCorrectionsSubProcessor_uninitializedvariable_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);

		LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.INITIALIZE_VARIABLE, image);
		proposal.addLinkedPosition(rewrite.track(expression), false, "initializer"); //$NON-NLS-1$
		proposals.add(proposal);
	}
}
 
Example 14
Source File: CorrectionMarkerResolutionGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static IMarkerResolution[] internalGetResolutions(IMarker marker) {
	if (!internalHasResolutions(marker)) {
		return NO_RESOLUTIONS;
	}

	ICompilationUnit cu= getCompilationUnit(marker);
	if (cu != null) {
		IEditorInput input= EditorUtility.getEditorInput(cu);
		if (input != null) {
			IProblemLocation location= findProblemLocation(input, marker);
			if (location != null) {

				IInvocationContext context= new AssistContext(cu,  location.getOffset(), location.getLength());
				if (!hasProblem (context.getASTRoot().getProblems(), location))
					return NO_RESOLUTIONS;

				ArrayList<IJavaCompletionProposal> proposals= new ArrayList<IJavaCompletionProposal>();
				JavaCorrectionProcessor.collectCorrections(context, new IProblemLocation[] { location }, proposals);
				Collections.sort(proposals, new CompletionProposalComparator());

				int nProposals= proposals.size();
				IMarkerResolution[] resolutions= new IMarkerResolution[nProposals];
				for (int i= 0; i < nProposals; i++) {
					resolutions[i]= new CorrectionMarkerResolution(context.getCompilationUnit(), location.getOffset(), location.getLength(), proposals.get(i), marker);
				}
				return resolutions;
			}
		}
	}
	return NO_RESOLUTIONS;
}
 
Example 15
Source File: FixCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public FixCorrectionProposal(IProposableFix fix, ICleanUp cleanUp, int relevance, Image image, IInvocationContext context) {
	super(fix.getDisplayString(), context.getCompilationUnit(), null, relevance, image);
	fFix= fix;
	fCleanUp= cleanUp;
	fCompilationUnit= context.getASTRoot();
}
 
Example 16
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void addSuperfluousSemicolonProposal(IInvocationContext context, IProblemLocation problem,  Collection<ICommandAccess> proposals) {
	String label= CorrectionMessages.LocalCorrectionsSubProcessor_removesemicolon_description;
	ReplaceCorrectionProposal proposal= new ReplaceCorrectionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), "", IProposalRelevance.REMOVE_SEMICOLON); //$NON-NLS-1$
	proposals.add(proposal);
}
 
Example 17
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean getAddParenthesesForExpressionProposals(IInvocationContext context, ASTNode coveringNode, Collection<ICommandAccess> resultingCollections) {
	ASTNode node;

	if (context.getSelectionLength() == 0) {
		node= coveringNode;
		while (node != null && !(node instanceof CastExpression) && !(node instanceof InfixExpression) && !(node instanceof InstanceofExpression) && !(node instanceof ConditionalExpression)) {
			node= node.getParent();
		}
	} else {
		node= context.getCoveredNode();
	}

	String label= null;
	if (node instanceof CastExpression) {
		label= CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
	} else if (node instanceof InstanceofExpression) {
		label= CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_instanceof_description;
	} else if (node instanceof InfixExpression) {
		InfixExpression infixExpression= (InfixExpression)node;
		label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_description, infixExpression.getOperator().toString());
	} else if (node instanceof ConditionalExpression) {
		label= CorrectionMessages.AdvancedQuickAssistProcessor_putConditionalExpressionInParentheses;
	} else {
		return false;
	}

	if (node.getParent() instanceof ParenthesizedExpression)
		return false;

	if (resultingCollections == null)
		return true;

	AST ast= node.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);

	ParenthesizedExpression parenthesizedExpression= ast.newParenthesizedExpression();
	parenthesizedExpression.setExpression((Expression)rewrite.createCopyTarget(node));
	rewrite.replace(node, parenthesizedExpression, null);

	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_PARENTHESES_FOR_EXPRESSION, image);
	resultingCollections.add(proposal);
	return true;
}
 
Example 18
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void addDeprecatedFieldsToMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Name) {
		IBinding binding= ((Name) selectedNode).resolveBinding();
		if (binding instanceof IVariableBinding) {
			IVariableBinding variableBinding= (IVariableBinding) binding;
			if (variableBinding.isField()) {
				String qualifiedName= variableBinding.getDeclaringClass().getTypeDeclaration().getQualifiedName();
				String fieldName= variableBinding.getName();
				String[] methodName= getMethod(JavaModelUtil.concatenateName(qualifiedName, fieldName));
				if (methodName != null) {
					AST ast= selectedNode.getAST();
					ASTRewrite astRewrite= ASTRewrite.create(ast);
					ImportRewrite importRewrite= StubUtility.createImportRewrite(context.getASTRoot(), true);

					MethodInvocation method= ast.newMethodInvocation();
					String qfn= importRewrite.addImport(methodName[0]);
					method.setExpression(ast.newName(qfn));
					method.setName(ast.newSimpleName(methodName[1]));
					ASTNode parent= selectedNode.getParent();
					ICompilationUnit cu= context.getCompilationUnit();
					// add explicit type arguments if necessary (for 1.8 and later, we're optimistic that inference just works):
					if (Invocations.isInvocationWithArguments(parent) && !JavaModelUtil.is18OrHigher(cu.getJavaProject())) {
						IMethodBinding methodBinding= Invocations.resolveBinding(parent);
						if (methodBinding != null) {
							ITypeBinding[] parameterTypes= methodBinding.getParameterTypes();
							int i= Invocations.getArguments(parent).indexOf(selectedNode);
							if (parameterTypes.length >= i && parameterTypes[i].isParameterizedType()) {
								ITypeBinding[] typeArguments= parameterTypes[i].getTypeArguments();
								for (int j= 0; j < typeArguments.length; j++) {
									ITypeBinding typeArgument= typeArguments[j];
									typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast);
									if (! TypeRules.isJavaLangObject(typeArgument)) {
										// add all type arguments if at least one is found to be necessary:
										List<Type> typeArgumentsList= method.typeArguments();
										for (int k= 0; k < typeArguments.length; k++) {
											typeArgument= typeArguments[k];
											typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast);
											typeArgumentsList.add(importRewrite.addImport(typeArgument, ast));
										}
										break;
									}
								}
							}
						}
					}
					
					astRewrite.replace(selectedNode, method, null);

					String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description, BasicElementLabels.getJavaElementName(ASTNodes.asString(method)));
					Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
					ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, astRewrite, IProposalRelevance.REPLACE_FIELD_ACCESS_WITH_METHOD, image);
					proposal.setImportRewrite(importRewrite);
					proposals.add(proposal);
				}
			}
		}
	}
}
 
Example 19
Source File: ReorgCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void getWrongTypeNameProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();
	boolean isLinked= cu.getResource().isLinked();

	IJavaProject javaProject= cu.getJavaProject();
	String sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
	String compliance= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);

	CompilationUnit root= context.getASTRoot();

	ASTNode coveredNode= problem.getCoveredNode(root);
	if (!(coveredNode instanceof SimpleName))
		return;

	ASTNode parentType= coveredNode.getParent();
	if (!(parentType instanceof AbstractTypeDeclaration))
		return;

	String currTypeName= ((SimpleName) coveredNode).getIdentifier();
	String newTypeName= JavaCore.removeJavaLikeExtension(cu.getElementName());

	boolean hasOtherPublicTypeBefore= false;

	boolean found= false;
	List<AbstractTypeDeclaration> types= root.types();
	for (int i= 0; i < types.size(); i++) {
		AbstractTypeDeclaration curr= types.get(i);
		if (parentType != curr) {
			if (newTypeName.equals(curr.getName().getIdentifier())) {
				return;
			}
			if (!found && Modifier.isPublic(curr.getModifiers())) {
				hasOtherPublicTypeBefore= true;
			}
		} else {
			found= true;
		}
	}
	if (!JavaConventions.validateJavaTypeName(newTypeName, sourceLevel, compliance).matches(IStatus.ERROR)) {
		proposals.add(new CorrectMainTypeNameProposal(cu, context, currTypeName, newTypeName, IProposalRelevance.RENAME_TYPE));
	}

	if (!hasOtherPublicTypeBefore) {
		String newCUName= JavaModelUtil.getRenamedCUName(cu, currTypeName);
		ICompilationUnit newCU= ((IPackageFragment) (cu.getParent())).getCompilationUnit(newCUName);
		if (!newCU.exists() && !isLinked && !JavaConventions.validateCompilationUnitName(newCUName, sourceLevel, compliance).matches(IStatus.ERROR)) {
			RenameCompilationUnitChange change= new RenameCompilationUnitChange(cu, newCUName);

			// rename CU
			String label= Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_renamecu_description, BasicElementLabels.getResourceName(newCUName));
			proposals.add(new ChangeCorrectionProposal(label, change, IProposalRelevance.RENAME_CU, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_RENAME)));
		}
	}
}
 
Example 20
Source File: CreateAsyncInterfaceProposal.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
public static List<IJavaCompletionProposal> createProposals(IInvocationContext context, IProblemLocation problem)
    throws JavaModelException {
  String syncTypeName = problem.getProblemArguments()[0];
  IJavaProject javaProject = context.getCompilationUnit().getJavaProject();
  IType syncType = JavaModelSearch.findType(javaProject, syncTypeName);
  if (syncType == null || !syncType.isInterface()) {
    return Collections.emptyList();
  }

  CompilationUnit cu = context.getASTRoot();
  ASTNode coveredNode = problem.getCoveredNode(cu);
  TypeDeclaration syncTypeDecl = (TypeDeclaration) coveredNode.getParent();
  assert (cu.getAST().hasResolvedBindings());

  ITypeBinding syncTypeBinding = syncTypeDecl.resolveBinding();
  assert (syncTypeBinding != null);

  String asyncName = RemoteServiceUtilities.computeAsyncTypeName(problem.getProblemArguments()[0]);
  AST ast = context.getASTRoot().getAST();
  Name name = ast.newName(asyncName);

  /*
   * HACK: NewCUUsingWizardProposal wants a name that has a parent expression so we create an
   * assignment so that the name has a valid parent
   */
  ast.newAssignment().setLeftHandSide(name);

  IJavaElement typeContainer = syncType.getParent();
  if (typeContainer.getElementType() == IJavaElement.COMPILATION_UNIT) {
    typeContainer = syncType.getPackageFragment();
  }

  // Add a create async interface proposal
  CreateAsyncInterfaceProposal createAsyncInterfaceProposal = new CreateAsyncInterfaceProposal(
      context.getCompilationUnit(), name, K_INTERFACE, typeContainer, 2, syncTypeBinding);

  // Add the stock create interface proposal
  NewCompilationUnitUsingWizardProposal fallbackProposal = new NewCompilationUnitUsingWizardProposal(
      context.getCompilationUnit(), name, K_INTERFACE, context.getCompilationUnit().getParent(), 1);

  return Arrays.<IJavaCompletionProposal>asList(createAsyncInterfaceProposal, fallbackProposal);
}