Java Code Examples for org.eclipse.jdt.core.dom.SimpleName#getIdentifier()

The following examples show how to use org.eclipse.jdt.core.dom.SimpleName#getIdentifier() . 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: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode, Collection<ICommandAccess> proposals) {
	if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) {
		ASTNode type= selectedNode.getParent();
		if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) {
			SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent();
			if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) {
				if (svd.getName().getLength() == 0) {
					SimpleName simpleName= (SimpleName) selectedNode;
					String name= simpleName.getIdentifier();
					int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
					String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name));
					Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
					
					proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance, image));
				}
			}
		}
	}
}
 
Example 2
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode,
		Collection<ChangeCorrectionProposal> proposals) {
	if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) {
		ASTNode type= selectedNode.getParent();
		if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) {
			SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent();
			if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) {
				if (svd.getName().getLength() == 0) {
					SimpleName simpleName= (SimpleName) selectedNode;
					String name= simpleName.getIdentifier();
					int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
					String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name));

					proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL,
							simpleName, null, relevance));
				}
			}
		}
	}
}
 
Example 3
Source File: OrganizeImportsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static void addImports(CompilationUnit root, ICompilationUnit unit, String[] favourites, ImportRewrite importRewrite, AST ast, ASTRewrite astRewrite, SimpleName node, boolean isMethod) throws JavaModelException {
	String name = node.getIdentifier();
	String[] imports = SimilarElementsRequestor.getStaticImportFavorites(unit, name, isMethod, favourites);
	if (imports.length > 1) {
		// See https://github.com/redhat-developer/vscode-java/issues/1472
		return;
	}
	for (int i = 0; i < imports.length; i++) {
		String curr = imports[i];
		String qualifiedTypeName = Signature.getQualifier(curr);
		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);
		}
	}
}
 
Example 4
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ASTNode getFieldReference(SimpleName oldNameNode, ASTRewrite rewrite) {
	String name= oldNameNode.getIdentifier();
	AST ast= rewrite.getAST();
	if (isParameterName(name) || StubUtility.useThisForFieldAccess(fTargetRewrite.getCu().getJavaProject())) {
		FieldAccess fieldAccess= ast.newFieldAccess();
		fieldAccess.setExpression(ast.newThisExpression());
		fieldAccess.setName((SimpleName) rewrite.createMoveTarget(oldNameNode));
		return fieldAccess;
	}
	return rewrite.createMoveTarget(oldNameNode);
}
 
Example 5
Source File: ExtractToNullCheckedLocalProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
String proposeLocalName(SimpleName fieldName, CompilationUnit root, IJavaProject javaProject) {
	// don't propose names that are already in use:
	Collection<String> variableNames= new ScopeAnalyzer(root).getUsedVariableNames(this.enclosingMethod.getStartPosition(), this.enclosingMethod.getLength());
	String[] names = new String[variableNames.size()+1];
	variableNames.toArray(names);
	// don't propose the field name itself, either:
	String identifier= fieldName.getIdentifier();
	names[names.length-1] = identifier;
	return StubUtility.getLocalNameSuggestions(javaProject, identifier, 0, names)[0];
}
 
Example 6
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void addNewFieldForType(ICompilationUnit targetCU, ITypeBinding binding, ITypeBinding senderDeclBinding, SimpleName simpleName, boolean isWriteAccess, boolean mustBeConst, Collection<ICommandAccess> proposals) {
	String name= simpleName.getIdentifier();
	String nameLabel= BasicElementLabels.getJavaElementName(name);
	String label;
	Image image;
	if (senderDeclBinding.isEnum() && !isWriteAccess) {
		label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createenum_description, new Object[] { nameLabel, ASTResolving.getTypeSignature(senderDeclBinding) });
		image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
		proposals.add(new NewVariableCorrectionProposal(label, targetCU, NewVariableCorrectionProposal.ENUM_CONST, simpleName, senderDeclBinding, 10, image));
	} else {
		if (!mustBeConst) {
			if (binding == null) {
				label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createfield_description, nameLabel);
				image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
			} else {
				label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createfield_other_description, new Object[] { nameLabel, ASTResolving.getTypeSignature(senderDeclBinding) } );
				image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
			}
			int fieldRelevance= StubUtility.hasFieldName(targetCU.getJavaProject(), name) ? IProposalRelevance.CREATE_FIELD_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_FIELD;
			proposals.add(new NewVariableCorrectionProposal(label, targetCU, NewVariableCorrectionProposal.FIELD, simpleName, senderDeclBinding, fieldRelevance, image));
		}

		if (!isWriteAccess && !senderDeclBinding.isAnonymous()) {
			if (binding == null) {
				label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createconst_description, nameLabel);
				image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
			} else {
				label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createconst_other_description, new Object[] { nameLabel, ASTResolving.getTypeSignature(senderDeclBinding) } );
				image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
			}
			int constRelevance= StubUtility.hasConstantName(targetCU.getJavaProject(), name) ? IProposalRelevance.CREATE_CONSTANT_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_CONSTANT;
			proposals.add(new NewVariableCorrectionProposal(label, targetCU, NewVariableCorrectionProposal.CONST_FIELD, simpleName, senderDeclBinding, constRelevance, image));
		}
	}
}
 
Example 7
Source File: OrganizeImportsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Tries to find the given type name and add it to the import structure.
 * @param ref the name node
 */
public void add(SimpleName ref) {
	String typeName= ref.getIdentifier();

	if (fImportsAdded.contains(typeName)) {
		return;
	}

	IBinding binding= ref.resolveBinding();
	if (binding != null) {
		if (binding.getKind() != IBinding.TYPE) {
			return;
		}
		ITypeBinding typeBinding= (ITypeBinding) binding;
		if (typeBinding.isArray()) {
			typeBinding= typeBinding.getElementType();
		}
		typeBinding= typeBinding.getTypeDeclaration();
		if (!typeBinding.isRecovered()) {
			if (needsImport(typeBinding, ref)) {
				fImpStructure.addImport(typeBinding);
				fImportsAdded.add(typeName);
			}
			return;
		}
	} else {
		if (fDoIgnoreLowerCaseNames && typeName.length() > 0) {
			char ch= typeName.charAt(0);
			if (Strings.isLowerCase(ch) && Character.isLetter(ch)) {
				return;
			}
		}
	}
	fImportsAdded.add(typeName);
	fUnresolvedTypes.put(typeName, new UnresolvedTypeData(ref));
}
 
Example 8
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 9
Source File: VariableOrParameterUsageCount.java    From ck with Apache License 2.0 5 votes vote down vote up
public void visit(SimpleName node) {
	if(declaredVariables.contains(node.toString())) {
		String var = node.getIdentifier();
		if (!occurrences.containsKey(var))
			occurrences.put(var, -1);

		occurrences.put(var, occurrences.get(var) + 1);
	}
}
 
Example 10
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static void addNewFieldForType(ICompilationUnit targetCU, ITypeBinding binding,
		ITypeBinding senderDeclBinding, SimpleName simpleName, boolean isWriteAccess, boolean mustBeConst,
		Collection<ChangeCorrectionProposal> proposals) {
	String name= simpleName.getIdentifier();
	String nameLabel= BasicElementLabels.getJavaElementName(name);
	String label;
	if (senderDeclBinding.isEnum() && !isWriteAccess) {
		label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createenum_description,
				new Object[] { nameLabel, org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(senderDeclBinding) });
		proposals.add(new NewVariableCorrectionProposal(label, targetCU, NewVariableCorrectionProposal.ENUM_CONST,
				simpleName, senderDeclBinding, 10));
	} else {
		if (!mustBeConst) {
			if (binding == null) {
				label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createfield_description, nameLabel);
			} else {
				label = Messages.format(
						CorrectionMessages.UnresolvedElementsSubProcessor_createfield_other_description,
						new Object[] { nameLabel, org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(senderDeclBinding) });
			}
			int fieldRelevance= StubUtility.hasFieldName(targetCU.getJavaProject(), name) ? IProposalRelevance.CREATE_FIELD_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_FIELD;
			proposals.add(new NewVariableCorrectionProposal(label, targetCU, NewVariableCorrectionProposal.FIELD,
					simpleName, senderDeclBinding, fieldRelevance));
		}

		if (!isWriteAccess && !senderDeclBinding.isAnonymous()) {
			if (binding == null) {
				label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createconst_description, nameLabel);
			} else {
				label = Messages.format(
						CorrectionMessages.UnresolvedElementsSubProcessor_createconst_other_description,
						new Object[] { nameLabel, org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(senderDeclBinding) });
			}
			int constRelevance= StubUtility.hasConstantName(targetCU.getJavaProject(), name) ? IProposalRelevance.CREATE_CONSTANT_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_CONSTANT;
			proposals.add(new NewVariableCorrectionProposal(label, targetCU,
					NewVariableCorrectionProposal.CONST_FIELD, simpleName, senderDeclBinding, constRelevance));
		}
	}
}
 
Example 11
Source File: FlowInfo.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
protected static String makeString(SimpleName label) {
	if (label == null) {
		return UNLABELED;
	} else {
		return label.getIdentifier();
	}
}
 
Example 12
Source File: Purification.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
public boolean visit(SimpleName node){
	String name = node.getIdentifier();
	if(name.equals("this") || node.getParent().toString().contains(name + "(")){
		return true;
	}
	if(Character.isUpperCase(name.charAt(0))){
		return true;
	}
	variable.add(name);
	return true;
}
 
Example 13
Source File: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 5 votes vote down vote up
private String generateSubclassName(SimpleName variable) {
	String subclassName = "";
	StringTokenizer tokenizer = new StringTokenizer(variable.getIdentifier(),"_");
	while(tokenizer.hasMoreTokens()) {
		String tempName = tokenizer.nextToken().toLowerCase().toString();
		subclassName += tempName.subSequence(0, 1).toString().toUpperCase() + 
		tempName.subSequence(1, tempName.length()).toString();
	}
	return subclassName;
}
 
Example 14
Source File: TypeCheckElimination.java    From JDeodorant with MIT License 4 votes vote down vote up
public List<String> getSubclassNames() {
	List<String> subclassNames = new ArrayList<String>();
	for(Expression expression : typeCheckMap.keySet()) {
		List<SimpleName> simpleNameGroup = staticFieldMap.get(expression);
		if(simpleNameGroup != null) {
			for(SimpleName simpleName : simpleNameGroup) {
				String staticFieldName = simpleName.getIdentifier();
				Type castingType = getCastingType(typeCheckMap.get(expression));
				String subclassName = null;
				if(!staticFieldName.contains("_")) {
					subclassName = staticFieldName.substring(0, 1).toUpperCase() + 
					staticFieldName.substring(1, staticFieldName.length()).toLowerCase();
				}
				else {
					subclassName = "";
					StringTokenizer tokenizer = new StringTokenizer(staticFieldName,"_");
					while(tokenizer.hasMoreTokens()) {
						String tempName = tokenizer.nextToken().toLowerCase().toString();
						subclassName += tempName.subSequence(0, 1).toString().toUpperCase() + 
						tempName.subSequence(1, tempName.length()).toString();
					}
				}
				if(inheritanceTreeMatchingWithStaticTypes != null) {
					subclassNames.add(staticFieldSubclassTypeMap.get(simpleName));
				}
				else if(existingInheritanceTree != null) {
					DefaultMutableTreeNode root = existingInheritanceTree.getRootNode();
					DefaultMutableTreeNode leaf = root.getFirstLeaf();
					while(leaf != null) {
						String childClassName = (String)leaf.getUserObject();
						if(childClassName.endsWith(subclassName)) {
							subclassNames.add(childClassName);
							break;
						}
						else if(castingType != null && castingType.resolveBinding().getQualifiedName().equals(childClassName)) {
							subclassNames.add(childClassName);
							break;
						}
						leaf = leaf.getNextLeaf();
					}
				}
				else if(castingType != null) {
					subclassNames.add(castingType.resolveBinding().getQualifiedName());
				}
				else {
					subclassNames.add(subclassName);
				}
			}
		}
		List<Type> typeGroup = subclassTypeMap.get(expression);
		if(typeGroup != null) {
			for(Type type : typeGroup)
				subclassNames.add(type.resolveBinding().getQualifiedName());
		}
	}
	return subclassNames;
}
 
Example 15
Source File: JavaDebugElementCodeMining.java    From jdt-codemining with Eclipse Public License 1.0 4 votes vote down vote up
public JavaDebugElementCodeMining(SimpleName node, IJavaStackFrame frame, ITextViewer viewer,
		AbstractDebugVariableCodeMiningProvider provider) {
	super(getPosition(node, viewer.getDocument()), node.getIdentifier(), frame, provider);
}
 
Example 16
Source File: FlowInfo.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected static String makeString(SimpleName label) {
	if (label == null)
		return UNLABELED;
	else
		return label.getIdentifier();
}
 
Example 17
Source File: RenameLinkedMode.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void start() {
		if (getActiveLinkedMode() != null) {
			// for safety; should already be handled in RenameJavaElementAction
			fgActiveLinkedMode.startFullDialog();
			return;
		}

		ISourceViewer viewer= fEditor.getViewer();
		IDocument document= viewer.getDocument();
		fOriginalSelection= viewer.getSelectedRange();
		int offset= fOriginalSelection.x;

		try {
			CompilationUnit root= SharedASTProvider.getAST(getCompilationUnit(), SharedASTProvider.WAIT_YES, null);

			fLinkedPositionGroup= new LinkedPositionGroup();
			ASTNode selectedNode= NodeFinder.perform(root, fOriginalSelection.x, fOriginalSelection.y);
			if (! (selectedNode instanceof SimpleName)) {
				return; // TODO: show dialog
			}
			SimpleName nameNode= (SimpleName) selectedNode;

			if (viewer instanceof ITextViewerExtension6) {
				IUndoManager undoManager= ((ITextViewerExtension6)viewer).getUndoManager();
				if (undoManager instanceof IUndoManagerExtension) {
					IUndoManagerExtension undoManagerExtension= (IUndoManagerExtension)undoManager;
					IUndoContext undoContext= undoManagerExtension.getUndoContext();
					IOperationHistory operationHistory= OperationHistoryFactory.getOperationHistory();
					fStartingUndoOperation= operationHistory.getUndoOperation(undoContext);
				}
			}
			
			fOriginalName= nameNode.getIdentifier();
			final int pos= nameNode.getStartPosition();
			ASTNode[] sameNodes= LinkedNodeFinder.findByNode(root, nameNode);

			//TODO: copied from LinkedNamesAssistProposal#apply(..):
			// sort for iteration order, starting with the node @ offset
			Arrays.sort(sameNodes, new Comparator<ASTNode>() {
				public int compare(ASTNode o1, ASTNode o2) {
					return rank(o1) - rank(o2);
				}
				/**
				 * Returns the absolute rank of an <code>ASTNode</code>. Nodes
				 * preceding <code>pos</code> are ranked last.
				 *
				 * @param node the node to compute the rank for
				 * @return the rank of the node with respect to the invocation offset
				 */
				private int rank(ASTNode node) {
					int relativeRank= node.getStartPosition() + node.getLength() - pos;
					if (relativeRank < 0)
						return Integer.MAX_VALUE + relativeRank;
					else
						return relativeRank;
				}
			});
			for (int i= 0; i < sameNodes.length; i++) {
				ASTNode elem= sameNodes[i];
				LinkedPosition linkedPosition= new LinkedPosition(document, elem.getStartPosition(), elem.getLength(), i);
				if (i == 0)
					fNamePosition= linkedPosition;
				fLinkedPositionGroup.addPosition(linkedPosition);
			}

			fLinkedModeModel= new LinkedModeModel();
			fLinkedModeModel.addGroup(fLinkedPositionGroup);
			fLinkedModeModel.forceInstall();
			fLinkedModeModel.addLinkingListener(new EditorHighlightingSynchronizer(fEditor));
			fLinkedModeModel.addLinkingListener(new EditorSynchronizer());

			LinkedModeUI ui= new EditorLinkedModeUI(fLinkedModeModel, viewer);
			ui.setExitPosition(viewer, offset, 0, Integer.MAX_VALUE);
			ui.setExitPolicy(new ExitPolicy(document));
			ui.enter();

			viewer.setSelectedRange(fOriginalSelection.x, fOriginalSelection.y); // by default, full word is selected; restore original selection

			if (viewer instanceof IEditingSupportRegistry) {
				IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer;
				registry.register(fFocusEditingSupport);
			}

			openSecondaryPopup();
//			startAnimation();
			fgActiveLinkedMode= this;

		} catch (BadLocationException e) {
			JavaPlugin.log(e);
		}
	}
 
Example 18
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addStaticImportFavoriteProposals(IInvocationContext context, SimpleName node, boolean isMethod,
		Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
	IJavaProject project= context.getCompilationUnit().getJavaProject();
	if (JavaModelUtil.is50OrHigher(project)) {
		String[] favourites = PreferenceManager.getPrefs(context.getCompilationUnit().getResource())
				.getJavaCompletionFavoriteMembers();
		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 = CodeStyleConfiguration.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);
			}

			ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix,
					context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_STATIC_IMPORT);
			proposal.setImportRewrite(importRewrite);
			proposals.add(proposal);
		}
	}
}
 
Example 19
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 20
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);
		}
	}
}