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

The following examples show how to use org.eclipse.jdt.ui.text.java.IInvocationContext#getASTRoot() . 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: NullAnnotationsCorrectionProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Fix for {@link IProblem#NullableFieldReference}
 * @param context context
 * @param problem problem to be fixed
 * @param proposals accumulator for computed proposals
 */
public static void addExtractCheckedLocalProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	CompilationUnit compilationUnit = context.getASTRoot();
	ICompilationUnit cu= (ICompilationUnit) compilationUnit.getJavaElement();

	ASTNode selectedNode= problem.getCoveringNode(compilationUnit);

	SimpleName name= findProblemFieldName(selectedNode, problem.getProblemId());
	if (name == null)
		return;

	ASTNode method= ASTNodes.getParent(selectedNode, MethodDeclaration.class);
	if (method == null)
		method= ASTNodes.getParent(selectedNode, Initializer.class);
	if (method == null)
		return;
	
	proposals.add(new ExtractToNullCheckedLocalProposal(cu, compilationUnit, name, method));
}
 
Example 2
Source File: ReturnTypeSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void addMethodRetunsVoidProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws JavaModelException {
	CompilationUnit astRoot= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(astRoot);
	if (!(selectedNode instanceof ReturnStatement)) {
		return;
	}
	ReturnStatement returnStatement= (ReturnStatement) selectedNode;
	Expression expression= returnStatement.getExpression();
	if (expression == null) {
		return;
	}
	BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
	if (decl instanceof MethodDeclaration) {
		MethodDeclaration methDecl= (MethodDeclaration) decl;
		Type retType= methDecl.getReturnType2();
		if (retType == null || retType.resolveBinding() == null) {
			return;
		}
		TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, expression, retType.resolveBinding(), false, IProposalRelevance.METHOD_RETURNS_VOID, proposals);
	}
}
 
Example 3
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 4
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 5
Source File: NullAnnotationsCorrectionProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addReturnAndArgumentTypeProposal(IInvocationContext context, IProblemLocation problem, ChangeKind changeKind, 
		Collection<ICommandAccess> proposals) {
	CompilationUnit astRoot= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(astRoot);

	boolean isArgumentProblem= NullAnnotationsFix.isComplainingAboutArgument(selectedNode);
	if (isArgumentProblem || NullAnnotationsFix.isComplainingAboutReturn(selectedNode))
		addNullAnnotationInSignatureProposal(context, problem, proposals, changeKind, isArgumentProblem);
}
 
Example 6
Source File: ModifierCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void addMakeTypeAbstractProposal(IInvocationContext context, TypeDeclaration parentTypeDecl, Collection<ICommandAccess> proposals) {
	MakeTypeAbstractOperation operation= new UnimplementedCodeFix.MakeTypeAbstractOperation(parentTypeDecl);

	String label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_addabstract_description, BasicElementLabels.getJavaElementName(parentTypeDecl.getName().getIdentifier()));
	UnimplementedCodeFix fix= new UnimplementedCodeFix(label, context.getASTRoot(), new CompilationUnitRewriteOperation[] { operation });

	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	FixCorrectionProposal proposal= new FixCorrectionProposal(fix, null, IProposalRelevance.MAKE_TYPE_ABSTRACT_FIX, image, context);
	proposals.add(proposal);
}
 
Example 7
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 8
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);
}
 
Example 9
Source File: SurroundWithTemplateProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public SurroundWithTemplate(IInvocationContext context, Statement[] selectedNodes, Template template) {
	super(context.getASTRoot(), selectedNodes);
	fTemplate= template;
	fCurrentProject= context.getCompilationUnit().getJavaProject();
}
 
Example 10
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void addInvalidVariableNameProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	// hiding, redefined or future keyword

	CompilationUnit root= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(root);
	if (selectedNode instanceof MethodDeclaration) {
		selectedNode= ((MethodDeclaration) selectedNode).getName();
	}
	if (!(selectedNode instanceof SimpleName)) {
		return;
	}
	SimpleName nameNode= (SimpleName) selectedNode;
	String valueSuggestion= null;

	String name;
	switch (problem.getProblemId()) {
		case IProblem.LocalVariableHidingLocalVariable:
		case IProblem.LocalVariableHidingField:
			name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_hiding_local_label, BasicElementLabels.getJavaElementName(nameNode.getIdentifier()));
			break;
		case IProblem.FieldHidingLocalVariable:
		case IProblem.FieldHidingField:
		case IProblem.DuplicateField:
			name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_hiding_field_label, BasicElementLabels.getJavaElementName(nameNode.getIdentifier()));
			break;
		case IProblem.ArgumentHidingLocalVariable:
		case IProblem.ArgumentHidingField:
			name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_hiding_argument_label, BasicElementLabels.getJavaElementName(nameNode.getIdentifier()));
			break;
		case IProblem.DuplicateMethod:
			name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_renaming_duplicate_method, BasicElementLabels.getJavaElementName(nameNode.getIdentifier()));
			break;

		default:
			name= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_rename_var_label, BasicElementLabels.getJavaElementName(nameNode.getIdentifier()));
	}

	if (problem.getProblemId() == IProblem.UseEnumAsAnIdentifier) {
		valueSuggestion= "enumeration"; //$NON-NLS-1$
	} else {
		valueSuggestion= nameNode.getIdentifier() + '1';
	}

	LinkedNamesAssistProposal proposal= new LinkedNamesAssistProposal(name, context, nameNode, valueSuggestion);
	proposals.add(proposal);
}
 
Example 11
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 12
Source File: TypeMismatchSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void addIncompatibleReturnTypeProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws JavaModelException {
	CompilationUnit astRoot= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(astRoot);
	if (selectedNode == null) {
		return;
	}
	MethodDeclaration decl= ASTResolving.findParentMethodDeclaration(selectedNode);
	if (decl == null) {
		return;
	}
	IMethodBinding methodDeclBinding= decl.resolveBinding();
	if (methodDeclBinding == null) {
		return;
	}

	ITypeBinding returnType= methodDeclBinding.getReturnType();
	IMethodBinding overridden= Bindings.findOverriddenMethod(methodDeclBinding, false);
	if (overridden == null || overridden.getReturnType() == returnType) {
		return;
	}


	ICompilationUnit cu= context.getCompilationUnit();
	IMethodBinding methodDecl= methodDeclBinding.getMethodDeclaration();
	ITypeBinding overriddenReturnType= overridden.getReturnType();
	if (! JavaModelUtil.is50OrHigher(context.getCompilationUnit().getJavaProject())) {
		overriddenReturnType= overriddenReturnType.getErasure();
	}
	proposals.add(new TypeChangeCorrectionProposal(cu, methodDecl, astRoot, overriddenReturnType, false, IProposalRelevance.CHANGE_RETURN_TYPE));

	ICompilationUnit targetCu= cu;

	IMethodBinding overriddenDecl= overridden.getMethodDeclaration();
	ITypeBinding overridenDeclType= overriddenDecl.getDeclaringClass();

	if (overridenDeclType.isFromSource()) {
		targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, overridenDeclType);
		if (targetCu != null && ASTResolving.isUseableTypeInContext(returnType, overriddenDecl, false)) {
			TypeChangeCorrectionProposal proposal= new TypeChangeCorrectionProposal(targetCu, overriddenDecl, astRoot, returnType, false, IProposalRelevance.CHANGE_RETURN_TYPE_OF_OVERRIDDEN);
			if (overridenDeclType.isInterface()) {
				proposal.setDisplayName(Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturnofimplemented_description, BasicElementLabels.getJavaElementName(overriddenDecl.getName())));
			} else {
				proposal.setDisplayName(Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturnofoverridden_description, BasicElementLabels.getJavaElementName(overriddenDecl.getName())));
			}
			proposals.add(proposal);
		}
	}
}
 
Example 13
Source File: ReturnTypeSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void addMissingReturnTypeProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();

	CompilationUnit astRoot= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(astRoot);
	if (selectedNode == null) {
		return;
	}
	BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
	if (decl instanceof MethodDeclaration) {
		MethodDeclaration methodDeclaration= (MethodDeclaration) decl;

		ReturnStatementCollector eval= new ReturnStatementCollector();
		decl.accept(eval);

		AST ast= astRoot.getAST();

		ITypeBinding typeBinding= eval.getTypeBinding(decl.getAST());
		typeBinding= Bindings.normalizeTypeBinding(typeBinding);
		if (typeBinding == null) {
			typeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
		}
		if (typeBinding.isWildcardType()) {
			typeBinding= ASTResolving.normalizeWildcardType(typeBinding, true, ast);
		}

		ASTRewrite rewrite= ASTRewrite.create(ast);

		String label= Messages.format(CorrectionMessages.ReturnTypeSubProcessor_missingreturntype_description, BindingLabelProvider.getBindingLabel(typeBinding, BindingLabelProvider.DEFAULT_TEXTFLAGS));
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.MISSING_RETURN_TYPE, image);

		ImportRewrite imports= proposal.createImportRewrite(astRoot);
		ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports);
		Type type= imports.addImport(typeBinding, ast, importRewriteContext);

		rewrite.set(methodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, type, null);
		rewrite.set(methodDeclaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.FALSE, null);

		Javadoc javadoc= methodDeclaration.getJavadoc();
		if (javadoc != null && typeBinding != null) {
			TagElement newTag= ast.newTagElement();
			newTag.setTagName(TagElement.TAG_RETURN);
			TextElement commentStart= ast.newTextElement();
			newTag.fragments().add(commentStart);

			JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), newTag, null);
			proposal.addLinkedPosition(rewrite.track(commentStart), false, "comment_start"); //$NON-NLS-1$
		}

		String key= "return_type"; //$NON-NLS-1$
		proposal.addLinkedPosition(rewrite.track(type), true, key);
		if (typeBinding != null) {
			ITypeBinding[] bindings= ASTResolving.getRelaxingTypes(ast, typeBinding);
			for (int i= 0; i < bindings.length; i++) {
				proposal.addLinkedPositionProposal(key, bindings[i]);
			}
		}

		proposals.add(proposal);

		// change to constructor
		ASTNode parentType= ASTResolving.findParentType(decl);
		if (parentType instanceof AbstractTypeDeclaration) {
			boolean isInterface= parentType instanceof TypeDeclaration && ((TypeDeclaration) parentType).isInterface();
			if (!isInterface) {
				String constructorName= ((AbstractTypeDeclaration) parentType).getName().getIdentifier();
				ASTNode nameNode= methodDeclaration.getName();
				label= Messages.format(CorrectionMessages.ReturnTypeSubProcessor_wrongconstructorname_description, BasicElementLabels.getJavaElementName(constructorName));
				proposals.add(new ReplaceCorrectionProposal(label, cu, nameNode.getStartPosition(), nameNode.getLength(), constructorName, IProposalRelevance.CHANGE_TO_CONSTRUCTOR));
			}
		}
	}
}
 
Example 14
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean getAssignParamToFieldProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
	node= ASTNodes.getNormalizedNode(node);
	ASTNode parent= node.getParent();
	if (!(parent instanceof SingleVariableDeclaration) || !(parent.getParent() instanceof MethodDeclaration)) {
		return false;
	}
	SingleVariableDeclaration paramDecl= (SingleVariableDeclaration) parent;
	IVariableBinding binding= paramDecl.resolveBinding();

	MethodDeclaration methodDecl= (MethodDeclaration) parent.getParent();
	if (binding == null || methodDecl.getBody() == null) {
		return false;
	}
	ITypeBinding typeBinding= binding.getType();
	if (typeBinding == null) {
		return false;
	}

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

	ITypeBinding parentType= Bindings.getBindingOfParentType(node);
	if (parentType != null) {
		if (parentType.isInterface()) {
			return false;
		}
		// assign to existing fields
		CompilationUnit root= context.getASTRoot();
		IVariableBinding[] declaredFields= parentType.getDeclaredFields();
		boolean isStaticContext= ASTResolving.isInStaticContext(node);
		for (int i= 0; i < declaredFields.length; i++) {
			IVariableBinding curr= declaredFields[i];
			if (isStaticContext == Modifier.isStatic(curr.getModifiers()) && typeBinding.isAssignmentCompatible(curr.getType())) {
				ASTNode fieldDeclFrag= root.findDeclaringNode(curr);
				if (fieldDeclFrag instanceof VariableDeclarationFragment) {
					VariableDeclarationFragment fragment= (VariableDeclarationFragment) fieldDeclFrag;
					if (fragment.getInitializer() == null) {
						resultingCollections.add(new AssignToVariableAssistProposal(context.getCompilationUnit(), paramDecl, fragment, typeBinding, IProposalRelevance.ASSIGN_PARAM_TO_EXISTING_FIELD));
					}
				}
			}
		}
	}

	AssignToVariableAssistProposal fieldProposal= new AssignToVariableAssistProposal(context.getCompilationUnit(), paramDecl, null, typeBinding, IProposalRelevance.ASSIGN_PARAM_TO_NEW_FIELD);
	fieldProposal.setCommandId(ASSIGN_PARAM_TO_FIELD_ID);
	resultingCollections.add(fieldProposal);
	return true;
}
 
Example 15
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static void addStaticImportFavoriteProposals(IInvocationContext context, SimpleName node, boolean isMethod, Collection<ICommandAccess> proposals) throws JavaModelException {
	IJavaProject project= context.getCompilationUnit().getJavaProject();
	if (JavaModelUtil.is50OrHigher(project)) {
		String pref= PreferenceConstants.getPreference(PreferenceConstants.CODEASSIST_FAVORITE_STATIC_MEMBERS, project);
		String[] favourites= pref.split(";"); //$NON-NLS-1$
		if (favourites.length == 0) {
			return;
		}

		CompilationUnit root= context.getASTRoot();
		AST ast= root.getAST();
		
		String name= node.getIdentifier();
		String[] staticImports= SimilarElementsRequestor.getStaticImportFavorites(context.getCompilationUnit(), name, isMethod, favourites);
		for (int i= 0; i < staticImports.length; i++) {
			String curr= staticImports[i];
			
			ImportRewrite importRewrite= StubUtility.createImportRewrite(root, true);
			ASTRewrite astRewrite= ASTRewrite.create(ast);
			
			String label;
			String qualifiedTypeName= Signature.getQualifier(curr);
			String elementLabel= BasicElementLabels.getJavaElementName(JavaModelUtil.concatenateName(Signature.getSimpleName(qualifiedTypeName), name));
			
			String res= importRewrite.addStaticImport(qualifiedTypeName, name, isMethod, new ContextSensitiveImportRewriteContext(root, node.getStartPosition(), importRewrite));
			int dot= res.lastIndexOf('.');
			if (dot != -1) {
				String usedTypeName= importRewrite.addImport(qualifiedTypeName);
				Name newName= ast.newQualifiedName(ast.newName(usedTypeName), ast.newSimpleName(name));
				astRewrite.replace(node, newName, null);
				label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_change_to_static_import_description, elementLabel);
			} else {
				label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_add_static_import_description, elementLabel);
			}

			Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
			ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_STATIC_IMPORT, image);
			proposal.setImportRewrite(importRewrite);
			proposals.add(proposal);
		}
	}
}
 
Example 16
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();
}