org.eclipse.jdt.core.dom.NodeFinder Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.NodeFinder. 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: NLSStringHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
	if (!(getEditor() instanceof JavaEditor))
		return null;

	ITypeRoot je= getEditorInputJavaElement();
	if (je == null)
		return null;

	// Never wait for an AST in UI thread.
	CompilationUnit ast= SharedASTProvider.getAST(je, SharedASTProvider.WAIT_NO, null);
	if (ast == null)
		return null;

	ASTNode node= NodeFinder.perform(ast, offset, 1);
	if (node instanceof StringLiteral) {
		StringLiteral stringLiteral= (StringLiteral)node;
		return new Region(stringLiteral.getStartPosition(), stringLiteral.getLength());
	} else if (node instanceof SimpleName) {
		SimpleName simpleName= (SimpleName)node;
		return new Region(simpleName.getStartPosition(), simpleName.getLength());
	}

	return null;
}
 
Example #2
Source File: RenameNodeCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
	super.addEdits(doc, root);

	// build a full AST
	CompilationUnit unit= SharedASTProvider.getAST(getCompilationUnit(), SharedASTProvider.WAIT_YES, null);

	ASTNode name= NodeFinder.perform(unit, fOffset, fLength);
	if (name instanceof SimpleName) {

		SimpleName[] names= LinkedNodeFinder.findByProblems(unit, (SimpleName) name);
		if (names != null) {
			for (int i= 0; i < names.length; i++) {
				SimpleName curr= names[i];
				root.addChild(new ReplaceEdit(curr.getStartPosition(), curr.getLength(), fNewName));
			}
			return;
		}
	}
	root.addChild(new ReplaceEdit(fOffset, fLength, fNewName));
}
 
Example #3
Source File: MoveStaticMembersProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
	try {
		pm.beginTask(RefactoringCoreMessages.MoveMembersRefactoring_checking, 1);
		RefactoringStatus result= new RefactoringStatus();
		result.merge(checkDeclaringType());
		pm.worked(1);
		if (result.hasFatalError())
			return result;

		fSource= new CompilationUnitRewrite(fMembersToMove[0].getCompilationUnit());
		fSourceBinding= (ITypeBinding)((SimpleName)NodeFinder.perform(fSource.getRoot(), fMembersToMove[0].getDeclaringType().getNameRange())).resolveBinding();
		fMemberBindings= getMemberBindings();
		if (fSourceBinding == null || hasUnresolvedMemberBinding()) {
			result.addFatalError(Messages.format(
				RefactoringCoreMessages.MoveMembersRefactoring_compile_errors,
				BasicElementLabels.getFileName(fSource.getCu())));
		}
		fMemberDeclarations= getASTMembers(result);
		return result;
	} finally {
		pm.done();
	}
}
 
Example #4
Source File: ImplementationsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private boolean shouldIncludeDefinition(ITypeRoot typeRoot, IRegion region, IJavaElement elementToSearch, List<Location> implementations) {
	boolean isUnimplemented = false;
	try {
		isUnimplemented = isUnimplementedMember(elementToSearch);
	} catch (JavaModelException e) {
		// do nothing.
	}

	if (isUnimplemented && implementations != null && !implementations.isEmpty()) {
		return false;
	}

	CompilationUnit ast = CoreASTProvider.getInstance().getAST(typeRoot, CoreASTProvider.WAIT_YES, new NullProgressMonitor());
	if (ast == null) {
		return false;
	}

	ASTNode node = NodeFinder.perform(ast, region.getOffset(), region.getLength());
	if (node instanceof SimpleName && !(node.getParent() instanceof MethodDeclaration || node.getParent() instanceof SuperMethodInvocation || node.getParent() instanceof AbstractTypeDeclaration)) {
		return true;
	}

	return false;
}
 
Example #5
Source File: RenameNodeCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
	super.addEdits(doc, root);

	// build a full AST
	CompilationUnit unit = CoreASTProvider.getInstance().getAST(getCompilationUnit(), CoreASTProvider.WAIT_YES, null);

	ASTNode name= NodeFinder.perform(unit, fOffset, fLength);
	if (name instanceof SimpleName) {

		SimpleName[] names= LinkedNodeFinder.findByProblems(unit, (SimpleName) name);
		if (names != null) {
			for (int i= 0; i < names.length; i++) {
				SimpleName curr= names[i];
				root.addChild(new ReplaceEdit(curr.getStartPosition(), curr.getLength(), fNewName));
			}
			return;
		}
	}
	root.addChild(new ReplaceEdit(fOffset, fLength, fNewName));
}
 
Example #6
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void initAST(IProgressMonitor pm) {
   	if (fCompilationUnitNode == null) {
   		fCompilationUnitNode= RefactoringASTParser.parseWithASTProvider(fCu, true, pm);
   	}
   	if (fAnonymousInnerClassNode == null) {
   		fAnonymousInnerClassNode= getAnonymousInnerClass(NodeFinder.perform(fCompilationUnitNode, fSelectionStart, fSelectionLength));
   	}
	if (fAnonymousInnerClassNode != null) {
		final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(fAnonymousInnerClassNode, AbstractTypeDeclaration.class);
		if (declaration instanceof TypeDeclaration) {
			final AbstractTypeDeclaration[] nested= ((TypeDeclaration) declaration).getTypes();
			fClassNamesUsed= new HashSet<String>(nested.length);
			for (int index= 0; index < nested.length; index++)
				fClassNamesUsed.add(nested[index].getName().getIdentifier());
		} else
			fClassNamesUsed= Collections.emptySet();
	}
}
 
Example #7
Source File: InlineConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Name findConstantNameNode() {
	ASTNode node= NodeFinder.perform(fSelectionCuRewrite.getRoot(), fSelectionStart, fSelectionLength);
	if (node == null)
		return null;
	if (node instanceof FieldAccess)
		node= ((FieldAccess) node).getName();
	if (!(node instanceof Name))
		return null;
	Name name= (Name) node;
	IBinding binding= name.resolveBinding();
	if (!(binding instanceof IVariableBinding))
		return null;
	IVariableBinding variableBinding= (IVariableBinding) binding;
	if (!variableBinding.isField() || variableBinding.isEnumConstant())
		return null;
	int modifiers= binding.getModifiers();
	if (! (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)))
		return null;

	return name;
}
 
Example #8
Source File: AddGetterSetterOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generates a new setter method for the specified field
 * 
 * @param field the field
 * @param astRewrite the AST rewrite to use
 * @param rewrite the list rewrite to use
 * @throws CoreException if an error occurs
 * @throws OperationCanceledException if the operation has been cancelled
 */
private void generateSetterMethod(final IField field, ASTRewrite astRewrite, final ListRewrite rewrite) throws CoreException, OperationCanceledException {
	final IType type= field.getDeclaringType();
	final String name= GetterSetterUtil.getSetterName(field, null);
	final IMethod existing= JavaModelUtil.findMethod(name, new String[] { field.getTypeSignature()}, false, type);
	if (existing == null || !querySkipExistingMethods(existing)) {
		IJavaElement sibling= null;
		if (existing != null) {
			sibling= StubUtility.findNextSibling(existing);
			removeExistingAccessor(existing, rewrite);
		} else
			sibling= fInsert;
		ASTNode insertion= StubUtility2.getNodeToInsertBefore(rewrite, sibling);
		addNewAccessor(type, field, GetterSetterUtil.getSetterStub(field, name, fSettings.createComments, fVisibility | (field.getFlags() & Flags.AccStatic)), rewrite, insertion);
		if (Flags.isFinal(field.getFlags())) {
			ASTNode fieldDecl= ASTNodes.getParent(NodeFinder.perform(fASTRoot, field.getNameRange()), FieldDeclaration.class);
			if (fieldDecl != null) {
				ModifierRewrite.create(astRewrite, fieldDecl).setModifiers(0, Modifier.FINAL, null);
			}
		}

	}
}
 
Example #9
Source File: MoveStaticMembersProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private BodyDeclaration[] getASTMembers(RefactoringStatus status) throws JavaModelException {
	BodyDeclaration[] result= new BodyDeclaration[fMembersToMove.length];
	for (int i= 0; i < fMembersToMove.length; i++) {
		IMember member= fMembersToMove[i];
		ASTNode node= NodeFinder.perform(fSource.getRoot(), member.getNameRange());
		result[i]= (BodyDeclaration)ASTNodes.getParent(node, BodyDeclaration.class);

		//Fix for bug 42383: exclude multiple VariableDeclarationFragments ("int a=1, b=2")
		//ReferenceAnalyzer#visit(FieldDeclaration node) depends on fragments().size() != 1 !
		if (result[i] instanceof FieldDeclaration
				&& ((FieldDeclaration) result[i]).fragments().size() != 1) {
			status.addFatalError(RefactoringCoreMessages.MoveMembersRefactoring_multi_var_fields);
			return result;
		}

	}

	//Sorting members is important for field declarations referring to previous fields.
	Arrays.sort(result, new Comparator<BodyDeclaration>() {
		public int compare(BodyDeclaration o1, BodyDeclaration o2) {
			return o1.getStartPosition() - o2.getStartPosition();
		}
	});
	return result;
}
 
Example #10
Source File: JavaStatementPostfixContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void initDomAST() {
		if (isReadOnly())
			return;
		
		ASTParser parser= ASTParser.newParser(AST.JLS8);
		parser.setSource(getCompilationUnit());
		parser.setResolveBindings(true);
		org.eclipse.jdt.core.dom.ASTNode domAst = parser.createAST(new NullProgressMonitor());
		
//		org.eclipse.jdt.core.dom.AST ast = domAst.getAST();
		
		NodeFinder nf = new NodeFinder(domAst, getCompletionOffset(), 1);
		org.eclipse.jdt.core.dom.ASTNode cv = nf.getCoveringNode();
		
		bodyDeclaration = ASTResolving.findParentBodyDeclaration(cv);
		parentDeclaration = ASTResolving.findParentType(cv);
		domInitialized = true;
	}
 
Example #11
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Finds and returns the <code>ASTNode</code> for the given source text
 * selection, if it is an entire constructor call or the class name portion
 * of a constructor call or constructor declaration, or null otherwise.
 * @param unit The compilation unit in which the selection was made
 * @param offset The textual offset of the start of the selection
 * @param length The length of the selection in characters
 * @return ClassInstanceCreation or MethodDeclaration
 */
private ASTNode getTargetNode(ICompilationUnit unit, int offset, int length) {
	ASTNode node= ASTNodes.getNormalizedNode(NodeFinder.perform(fCU, offset, length));
	if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION)
		return node;
	if (node.getNodeType() == ASTNode.METHOD_DECLARATION && ((MethodDeclaration)node).isConstructor())
		return node;
	// we have some sub node. Make sure its the right child of the parent
	StructuralPropertyDescriptor location= node.getLocationInParent();
	ASTNode parent= node.getParent();
	if (location == ClassInstanceCreation.TYPE_PROPERTY) {
		return parent;
	} else if (location == MethodDeclaration.NAME_PROPERTY && ((MethodDeclaration)parent).isConstructor()) {
		return parent;
	}
	return null;
}
 
Example #12
Source File: OverrideIndicatorLabelDecorator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private int findInHierarchyWithAST(CompilationUnit astRoot, IMethod method) throws JavaModelException {
	ASTNode node= NodeFinder.perform(astRoot, method.getNameRange());
	if (node instanceof SimpleName && node.getParent() instanceof MethodDeclaration) {
		IMethodBinding binding= ((MethodDeclaration) node.getParent()).resolveBinding();
		if (binding != null) {
			IMethodBinding defining= Bindings.findOverriddenMethod(binding, true);
			if (defining != null) {
				if (JdtFlags.isAbstract(defining)) {
					return JavaElementImageDescriptor.IMPLEMENTS;
				} else {
					return JavaElementImageDescriptor.OVERRIDES;
				}
			}
			return 0;
		}
	}
	return -1;
}
 
Example #13
Source File: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus createExceptionInfoList() {
	if (fExceptionInfos == null || fExceptionInfos.isEmpty()) {
		fExceptionInfos= new ArrayList<ExceptionInfo>(0);
		try {
			ASTNode nameNode= NodeFinder.perform(fBaseCuRewrite.getRoot(), fMethod.getNameRange());
			if (nameNode == null || !(nameNode instanceof Name) || !(nameNode.getParent() instanceof MethodDeclaration))
				return null;
			MethodDeclaration methodDeclaration= (MethodDeclaration) nameNode.getParent();
			List<Type> exceptions= methodDeclaration.thrownExceptionTypes();
			List<ExceptionInfo> result= new ArrayList<ExceptionInfo>(exceptions.size());
			for (int i= 0; i < exceptions.size(); i++) {
				Type type= exceptions.get(i);
				ITypeBinding typeBinding= type.resolveBinding();
				if (typeBinding == null)
					return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeSignatureRefactoring_no_exception_binding);
				IJavaElement element= typeBinding.getJavaElement();
				result.add(ExceptionInfo.createInfoForOldException(element, typeBinding));
			}
			fExceptionInfos= result;
		} catch (JavaModelException e) {
			JavaPlugin.log(e);
		}
	}
	return null;
}
 
Example #14
Source File: ASTNodeSearchUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ASTNode findNode(SearchMatch searchResult, CompilationUnit cuNode) {
	ASTNode selectedNode= NodeFinder.perform(cuNode, searchResult.getOffset(), searchResult.getLength());
	if (selectedNode == null)
		return null;
	if (selectedNode.getParent() == null)
		return null;
	return selectedNode;
}
 
Example #15
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ASTNode getInlineableMethodNode(ITypeRoot typeRoot, CompilationUnit root, int offset, int length) {
	ASTNode node= null;
	try {
		node= getInlineableMethodNode(NodeFinder.perform(root, offset, length, typeRoot), typeRoot);
	} catch(JavaModelException e) {
		// Do nothing
	}
	if (node != null)
		return node;
	return getInlineableMethodNode(NodeFinder.perform(root, offset, length), typeRoot);
}
 
Example #16
Source File: AddUnimplementedConstructorsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public AddUnimplementedConstructorsContentProvider(IType type) throws JavaModelException {
	RefactoringASTParser parser= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL);
	fUnit= parser.parse(type.getCompilationUnit(), true);
	AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(NodeFinder.perform(fUnit, type.getNameRange()), AbstractTypeDeclaration.class);
	if (declaration != null) {
		ITypeBinding binding= declaration.resolveBinding();
		if (binding != null)
			fMethodsList= StubUtility2.getVisibleConstructors(binding, true, false);
	}
}
 
Example #17
Source File: ASTNodeSearchUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static ASTNode findNode(ISourceRange range, CompilationUnit cuNode){
	NodeFinder nodeFinder= new NodeFinder(cuNode, range.getOffset(), range.getLength());
	ASTNode coveredNode= nodeFinder.getCoveredNode();
	if (coveredNode != null)
		return coveredNode;
	else
		return nodeFinder.getCoveringNode();
}
 
Example #18
Source File: RenameLocalVariableProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void initAST() {
	if (!fIsComposite)
		fCompilationUnitNode= RefactoringASTParser.parseWithASTProvider(fCu, true, null);
	ISourceRange sourceRange= fLocalVariable.getNameRange();
	ASTNode name= NodeFinder.perform(fCompilationUnitNode, sourceRange);
	if (name == null)
		return;
	if (name.getParent() instanceof VariableDeclaration)
		fTempDeclarationNode= (VariableDeclaration) name.getParent();
}
 
Example #19
Source File: JavadocHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static ASTNode getHoveredASTNode(ITypeRoot editorInputElement, IRegion hoverRegion) {
	if (editorInputElement == null)
		return null;

	CompilationUnit unit= SharedASTProvider.getAST(editorInputElement, SharedASTProvider.WAIT_ACTIVE_ONLY, null);
	if (unit == null)
		return null;
	
	return NodeFinder.perform(unit, hoverRegion.getOffset(),	hoverRegion.getLength());
}
 
Example #20
Source File: GenerateMethodAbstractAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
void initialize(IType type) throws JavaModelException {
	RefactoringASTParser parser= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL);
	fUnit= parser.parse(type.getCompilationUnit(), true);
	fTypeBinding= null;
	// type cannot be anonymous
	final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(NodeFinder.perform(fUnit, type.getNameRange()),
			AbstractTypeDeclaration.class);
	if (declaration != null)
		fTypeBinding= declaration.resolveBinding();
}
 
Example #21
Source File: RenameAnalyzeUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This method analyzes a set of local variable renames inside one cu. It checks whether
 * any new compile errors have been introduced by the rename(s) and whether the correct
 * node(s) has/have been renamed.
 *
 * @param analyzePackages the LocalAnalyzePackages containing the information about the local renames
 * @param cuChange the TextChange containing all local variable changes to be applied.
 * @param oldCUNode the fully (incl. bindings) resolved AST node of the original compilation unit
 * @param recovery whether statements and bindings recovery should be performed when parsing the changed CU
 * @return a RefactoringStatus containing errors if compile errors or wrongly renamed nodes are found
 * @throws CoreException thrown if there was an error greating the preview content of the change
 */
public static RefactoringStatus analyzeLocalRenames(LocalAnalyzePackage[] analyzePackages, TextChange cuChange, CompilationUnit oldCUNode, boolean recovery) throws CoreException {

	RefactoringStatus result= new RefactoringStatus();
	ICompilationUnit compilationUnit= (ICompilationUnit) oldCUNode.getJavaElement();

	String newCuSource= cuChange.getPreviewContent(new NullProgressMonitor());
	CompilationUnit newCUNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(newCuSource, compilationUnit, true, recovery, null);

	result.merge(analyzeCompileErrors(newCuSource, newCUNode, oldCUNode));
	if (result.hasError())
		return result;

	for (int i= 0; i < analyzePackages.length; i++) {
		ASTNode enclosing= getEnclosingBlockOrMethodOrLambda(analyzePackages[i].fDeclarationEdit, cuChange, newCUNode);

		// get new declaration
		IRegion newRegion= RefactoringAnalyzeUtil.getNewTextRange(analyzePackages[i].fDeclarationEdit, cuChange);
		ASTNode newDeclaration= NodeFinder.perform(newCUNode, newRegion.getOffset(), newRegion.getLength());
		Assert.isTrue(newDeclaration instanceof Name);

		VariableDeclaration declaration= getVariableDeclaration((Name) newDeclaration);
		Assert.isNotNull(declaration);

		SimpleName[] problemNodes= ProblemNodeFinder.getProblemNodes(enclosing, declaration, analyzePackages[i].fOccurenceEdits, cuChange);
		result.merge(RefactoringAnalyzeUtil.reportProblemNodes(newCuSource, problemNodes));
	}
	return result;
}
 
Example #22
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean isSideEffectFree(SimpleName simpleName, CompilationUnit completeRoot) {
	SimpleName nameNode= (SimpleName) NodeFinder.perform(completeRoot, simpleName.getStartPosition(), simpleName.getLength());
	SimpleName[] references= LinkedNodeFinder.findByBinding(completeRoot, nameNode.resolveBinding());
	for (int i= 0; i < references.length; i++) {
		if (hasSideEffect(references[i]))
			return false;
	}
	return true;
}
 
Example #23
Source File: TypeContextChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ITypeBinding resolveSuperClass(String superclass, IType typeHandle, StubTypeContext superClassContext) {
	StringBuffer cuString= new StringBuffer();
	cuString.append(superClassContext.getBeforeString());
	cuString.append(superclass);
	cuString.append(superClassContext.getAfterString());

	try {
		ICompilationUnit wc= typeHandle.getCompilationUnit().getWorkingCopy(new WorkingCopyOwner() {/*subclass*/}, new NullProgressMonitor());
		try {
			wc.getBuffer().setContents(cuString.toString());
			CompilationUnit compilationUnit= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(wc, true);
			ASTNode type= NodeFinder.perform(compilationUnit, superClassContext.getBeforeString().length(), superclass.length());
			if (type instanceof Type) {
				return handleBug84585(((Type) type).resolveBinding());
			} else if (type instanceof Name) {
				ASTNode parent= type.getParent();
				if (parent instanceof Type)
					return handleBug84585(((Type) parent).resolveBinding());
			}
			throw new IllegalStateException();
		} finally {
			wc.discardWorkingCopy();
		}
	} catch (JavaModelException e) {
		return null;
	}
}
 
Example #24
Source File: IntroduceParameterRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void replaceSelectedExpression(CompilationUnitRewrite cuRewrite) {
	if (! fSourceCU.equals(cuRewrite.getCu()))
		return;
	// TODO: do for all methodDeclarations and replace matching fragments?

	// cannot use fSelectedExpression here, since it could be from another AST (if method was replaced by overridden):
	Expression expression= (Expression) NodeFinder.perform(cuRewrite.getRoot(), fSelectedExpression.getStartPosition(), fSelectedExpression.getLength());

	ASTNode newExpression= cuRewrite.getRoot().getAST().newSimpleName(fParameter.getNewName());
	String description= RefactoringCoreMessages.IntroduceParameterRefactoring_replace;
	cuRewrite.getASTRewrite().replace(expression.getParent() instanceof ParenthesizedExpression
			? expression.getParent() : expression, newExpression, cuRewrite.createGroupDescription(description));
}
 
Example #25
Source File: ReplaceInvocationsRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static ASTNode getTargetNode(ICompilationUnit unit, CompilationUnit root, int offset, int length) {
	ASTNode node= null;
	try {
		node= checkNode(NodeFinder.perform(root, offset, length, unit));
	} catch(JavaModelException e) {
		// Do nothing
	}
	if (node != null)
		return node;
	return checkNode(NodeFinder.perform(root, offset, length));
}
 
Example #26
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ASTNode typeToDeclaration(IType type, CompilationUnit root) throws JavaModelException {
	Name intermediateName= (Name) NodeFinder.perform(root, type.getNameRange());
	if (type.isAnonymous()) {
		return ASTNodes.getParent(intermediateName, AnonymousClassDeclaration.class);
	} else {
		return ASTNodes.getParent(intermediateName, AbstractTypeDeclaration.class);
	}
}
 
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: ASTNodeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ASTNode newStatement(AST ast, String content) {
	StringBuffer buffer= new StringBuffer(STATEMENT_HEADER);
	buffer.append(content);
	buffer.append(STATEMENT_FOOTER);
	ASTParser p= ASTParser.newParser(ast.apiLevel());
	p.setSource(buffer.toString().toCharArray());
	CompilationUnit root= (CompilationUnit) p.createAST(null);
	ASTNode result= ASTNode.copySubtree(ast, NodeFinder.perform(root, STATEMENT_HEADER.length(), content.length()));
	result.accept(new PositionClearer());
	return result;
}
 
Example #29
Source File: CompilationUnitRange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ASTNode getNode(CompilationUnit rootNode) {
	NodeFinder finder= new NodeFinder(rootNode, fSourceRange.getOffset(), fSourceRange.getLength());
	ASTNode result= finder.getCoveringNode();
	if (result != null)
		return result;
	return finder.getCoveredNode();
}
 
Example #30
Source File: TypeContextChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Type parseSuperType(String superType, boolean isInterface) {
	if (! superType.trim().equals(superType)) {
		return null;
	}

	StringBuffer cuBuff= new StringBuffer();
	if (isInterface)
		cuBuff.append("class __X__ implements "); //$NON-NLS-1$
	else
		cuBuff.append("class __X__ extends "); //$NON-NLS-1$
	int offset= cuBuff.length();
	cuBuff.append(superType).append(" {}"); //$NON-NLS-1$

	ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	p.setSource(cuBuff.toString().toCharArray());
	Map<String, String> options= new HashMap<String, String>();
	JavaModelUtil.setComplianceOptions(options, JavaModelUtil.VERSION_LATEST);
	p.setCompilerOptions(options);
	CompilationUnit cu= (CompilationUnit) p.createAST(null);
	ASTNode selected= NodeFinder.perform(cu, offset, superType.length());
	if (selected instanceof Name)
		selected= selected.getParent();
	if (selected.getStartPosition() != offset
			|| selected.getLength() != superType.length()
			|| ! (selected instanceof Type)
			|| selected instanceof PrimitiveType) {
		return null;
	}
	Type type= (Type) selected;

	String typeNodeRange= cuBuff.substring(type.getStartPosition(), ASTNodes.getExclusiveEnd(type));
	if (! superType.equals(typeNodeRange)){
		return null;
	}
	return type;
}