Java Code Examples for org.eclipse.jdt.core.dom.ASTNode#getParent()

The following examples show how to use org.eclipse.jdt.core.dom.ASTNode#getParent() . 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: 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 2
Source File: ExtractTempRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private ASTNode getEnclosingBodyNode() throws JavaModelException {
	ASTNode node = getSelectedExpression().getAssociatedNode();

	// expression must be in a method, lambda or initializer body
	// make sure it is not in method or parameter annotation
	StructuralPropertyDescriptor location = null;
	while (node != null && !(node instanceof BodyDeclaration)) {
		location = node.getLocationInParent();
		node = node.getParent();
		if (node instanceof LambdaExpression) {
			break;
		}
	}
	if (location == MethodDeclaration.BODY_PROPERTY || location == Initializer.BODY_PROPERTY || (location == LambdaExpression.BODY_PROPERTY && ((LambdaExpression) node).resolveMethodBinding() != null)) {
		return (ASTNode) node.getStructuralProperty(location);
	}
	return null;
}
 
Example 3
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Finds the ancestor type of <code>node</code> (includes <code>node</code> in the search).
 *
 * @param node the node to start the search from, can be <code>null</code>
 * @param treatModifiersOutside if set, modifiers are not part of their type, but of the type's
 *            parent
 * @return returns the ancestor type of <code>node</code> (AbstractTypeDeclaration or
 *         AnonymousTypeDeclaration) if any (including <code>node</code>), <code>null</code>
 *         otherwise
 */
public static ASTNode findParentType(ASTNode node, boolean treatModifiersOutside) {
	StructuralPropertyDescriptor lastLocation= null;

	while (node != null) {
		if (node instanceof AbstractTypeDeclaration) {
			AbstractTypeDeclaration decl= (AbstractTypeDeclaration) node;
			if (!treatModifiersOutside || lastLocation != decl.getModifiersProperty()) {
				return decl;
			}
		} else if (node instanceof AnonymousClassDeclaration) {
			return node;
		}
		lastLocation= node.getLocationInParent();
		node= node.getParent();
	}
	return null;
}
 
Example 4
Source File: SharedUtils.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
public static String qualifiedName(TypeDeclaration decl) {
	String name = decl.getName().getIdentifier();
	ASTNode parent = decl.getParent();
	// resolve full name e.g.: A.B
	while (parent != null && parent.getClass() == TypeDeclaration.class) {
		name = ((TypeDeclaration) parent).getName().getIdentifier() + "." + name;
		parent = parent.getParent();
	}
	// resolve fully qualified name e.g.: some.package.A.B
	if (decl.getRoot().getClass() == CompilationUnit.class) {
		CompilationUnit root = (CompilationUnit) decl.getRoot();
		if (root.getPackage() != null) {
			PackageDeclaration pack = root.getPackage();
			name = pack.getName().getFullyQualifiedName() + "." + name;
		}
	}
	return name;
}
 
Example 5
Source File: RefactorProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static <T extends ASTNode> T getEnclosingHeader(ASTNode node, Class<T> headerType, StructuralPropertyDescriptor... headerProperties) {
	if (headerType.isInstance(node)) {
		return headerType.cast(node);
	}

	while (node != null) {
		ASTNode parent = node.getParent();
		if (headerType.isInstance(parent)) {
			StructuralPropertyDescriptor locationInParent = node.getLocationInParent();
			for (StructuralPropertyDescriptor property : headerProperties) {
				if (locationInParent == property) {
					return headerType.cast(parent);
				}
			}
			return null;
		}
		node = parent;
	}
	return null;
}
 
Example 6
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static BodyDeclaration findParentBodyDeclaration(ASTNode node, boolean treatModifiersOutside) {
	StructuralPropertyDescriptor lastLocation= null;

	while (node != null) {
		if (node instanceof BodyDeclaration) {
			BodyDeclaration decl= (BodyDeclaration) node;
			if (!treatModifiersOutside || lastLocation != decl.getModifiersProperty()) {
				return decl;
			}
			treatModifiersOutside= false;
		}
		lastLocation= node.getLocationInParent();
		node= node.getParent();
	}
	return (BodyDeclaration) node;
}
 
Example 7
Source File: VariableScopeExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void preVisit(final ASTNode node) {
	if (node.getParent() != null) {
		variables.putAll(node, variables.get(node.getParent()));
	}
	variables.putAll(node, variableDeclarations.get(node));
	super.preVisit(node);
}
 
Example 8
Source File: ExtractMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void initializeDuplicates() {
	ASTNode start= fAnalyzer.getEnclosingBodyDeclaration();
	while (!(start instanceof AbstractTypeDeclaration)) {
		start= start.getParent();
	}

	fDuplicates= SnippetFinder.perform(start, fAnalyzer.getSelectedNodes());
	fReplaceDuplicates= fDuplicates.length > 0 && ! fAnalyzer.isLiteralNodeSelected();
}
 
Example 9
Source File: TreedMapper.java    From compiler with Apache License 2.0 5 votes vote down vote up
private void getNotYetMappedAncestors(ASTNode node, ArrayList<ASTNode> ancestors) {
	ASTNode p = node.getParent();
	if (treeMap.get(p).isEmpty()) {
		ancestors.add(p);
		getNotYetMappedAncestors(p, ancestors);
	}
}
 
Example 10
Source File: ExtractMethodRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private boolean matchesLocationInEnclosingBodyDecl(BodyDeclaration originalEnclosingBodyDeclaration, BodyDeclaration duplicateEnclosingBodyDeclaration, VariableDeclaration originalReturnNode, VariableDeclaration duplicateReturnNode) {
	boolean matches = true;
	ASTNode original = originalReturnNode;
	ASTNode dupliacte = duplicateReturnNode;

	// walk up the parent chains to check if the location of the return nodes in their respective parent chains is same
	do {
		ASTNode originalParent = original.getParent();
		ASTNode duplicateParent = dupliacte.getParent();
		StructuralPropertyDescriptor originalLoc = original.getLocationInParent();
		StructuralPropertyDescriptor duplicateLoc = dupliacte.getLocationInParent();

		if (originalParent != null && duplicateParent != null && originalLoc.getNodeClass().equals(duplicateLoc.getNodeClass()) && originalLoc.getId().equals(duplicateLoc.getId())) {
			if (originalLoc.isChildListProperty() && duplicateLoc.isChildListProperty()) {
				int indexOfOriginal = ((List<?>) originalParent.getStructuralProperty(originalLoc)).indexOf(original);
				int indexOfDuplicate = ((List<?>) duplicateParent.getStructuralProperty(duplicateLoc)).indexOf(dupliacte);
				if (indexOfOriginal != indexOfDuplicate) {
					matches = false;
					break;
				}
			}
		} else {
			matches = false;
			break;
		}

		original = originalParent;
		dupliacte = duplicateParent;

		if ((originalEnclosingBodyDeclaration.equals(original) && !duplicateEnclosingBodyDeclaration.equals(dupliacte)) || (!originalEnclosingBodyDeclaration.equals(original) && duplicateEnclosingBodyDeclaration.equals(dupliacte))) {
			matches = false;
			break;
		}
	} while (!originalEnclosingBodyDeclaration.equals(original) && !duplicateEnclosingBodyDeclaration.equals(dupliacte));

	return matches;
}
 
Example 11
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean canReplace(IASTFragment fragment) {
	ASTNode node = fragment.getAssociatedNode();
	ASTNode parent = node.getParent();
	if (parent instanceof VariableDeclarationFragment) {
		VariableDeclarationFragment vdf = (VariableDeclarationFragment) parent;
		if (node.equals(vdf.getName())) {
			return false;
		}
	}
	if (isMethodParameter(node)) {
		return false;
	}
	if (isThrowableInCatchBlock(node)) {
		return false;
	}
	if (parent instanceof ExpressionStatement) {
		return false;
	}
	if (parent instanceof LambdaExpression) {
		return false;
	}
	if (isLeftValue(node)) {
		return false;
	}
	if (isReferringToLocalVariableFromFor((Expression) node)) {
		return false;
	}
	if (isUsedInForInitializerOrUpdater((Expression) node)) {
		return false;
	}
	if (parent instanceof SwitchCase) {
		return false;
	}
	return true;
}
 
Example 12
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isDeclaredInLambdaExpression() throws JavaModelException {
	ASTNode node = getSelectedExpression().getAssociatedNode();
	while (node != null && !(node instanceof BodyDeclaration)) {
		node = node.getParent();
		if (node instanceof LambdaExpression) {
			return true;
		}
	}

	return false;
}
 
Example 13
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Expression getBooleanExpression(ASTNode node) {
	if (!(node instanceof Expression)) {
		return null;
	}

	// check if the node is a location where it can be negated
	StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
	if (locationInParent == QualifiedName.NAME_PROPERTY) {
		node= node.getParent();
		locationInParent= node.getLocationInParent();
	}
	while (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) {
		node= node.getParent();
		locationInParent= node.getLocationInParent();
	}
	Expression expression= (Expression) node;
	if (!isBoolean(expression)) {
		return null;
	}
	if (expression.getParent() instanceof InfixExpression) {
		return expression;
	}
	if (locationInParent == Assignment.RIGHT_HAND_SIDE_PROPERTY || locationInParent == IfStatement.EXPRESSION_PROPERTY
			|| locationInParent == WhileStatement.EXPRESSION_PROPERTY || locationInParent == DoStatement.EXPRESSION_PROPERTY
			|| locationInParent == ReturnStatement.EXPRESSION_PROPERTY || locationInParent == ForStatement.EXPRESSION_PROPERTY
			|| locationInParent == AssertStatement.EXPRESSION_PROPERTY || locationInParent == MethodInvocation.ARGUMENTS_PROPERTY
			|| locationInParent == ConstructorInvocation.ARGUMENTS_PROPERTY || locationInParent == SuperMethodInvocation.ARGUMENTS_PROPERTY
			|| locationInParent == EnumConstantDeclaration.ARGUMENTS_PROPERTY || locationInParent == SuperConstructorInvocation.ARGUMENTS_PROPERTY
			|| locationInParent == ClassInstanceCreation.ARGUMENTS_PROPERTY || locationInParent == ConditionalExpression.EXPRESSION_PROPERTY
			|| locationInParent == PrefixExpression.OPERAND_PROPERTY) {
		return expression;
	}
	return null;
}
 
Example 14
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isWriteAccess(Name selectedNode) {
	ASTNode curr= selectedNode;
	ASTNode parent= curr.getParent();
	while (parent != null) {
		switch (parent.getNodeType()) {
			case ASTNode.QUALIFIED_NAME:
				if (((QualifiedName) parent).getQualifier() == curr) {
					return false;
				}
				break;
			case ASTNode.FIELD_ACCESS:
				if (((FieldAccess) parent).getExpression() == curr) {
					return false;
				}
				break;
			case ASTNode.SUPER_FIELD_ACCESS:
				break;
			case ASTNode.ASSIGNMENT:
				return ((Assignment) parent).getLeftHandSide() == curr;
			case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
			case ASTNode.SINGLE_VARIABLE_DECLARATION:
				return ((VariableDeclaration) parent).getName() == curr;
			case ASTNode.POSTFIX_EXPRESSION:
				return true;
			case ASTNode.PREFIX_EXPRESSION:
				PrefixExpression.Operator op= ((PrefixExpression) parent).getOperator();
				return op == PrefixExpression.Operator.DECREMENT || op == PrefixExpression.Operator.INCREMENT;
			default:
				return false;
		}

		curr= parent;
		parent= curr.getParent();
	}
	return false;
}
 
Example 15
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isInsideModifiers(ASTNode node) {
	while (node != null && !(node instanceof BodyDeclaration)) {
		if (node instanceof Annotation) {
			return true;
		}
		node= node.getParent();
	}
	return false;
}
 
Example 16
Source File: QuickAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static boolean getAssignParamToFieldProposals(IInvocationContext context, ASTNode node, Collection<ChangeCorrectionProposal> 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);
	resultingCollections.add(fieldProposal);
	return true;
}
 
Example 17
Source File: ASTFlattenerUtils.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
public boolean needsReturnValue(final ASTNode node) {
  return ((node.getParent() != null) && ((!(node.getParent() instanceof Statement)) || (node.getParent() instanceof ReturnStatement)));
}
 
Example 18
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Determines what kind of ASTNode has been selected.
 * @param node the node
 * @return  A non-null String containing an error message
 * is returned if the ChangeTypeRefactoring refactoring cannot be applied to the selected ASTNode.
 * A return value of null indicates a valid selection.
 */
private String determineSelection(ASTNode node) {
	if (node == null) {
		return RefactoringCoreMessages.ChangeTypeRefactoring_invalidSelection;
	} else {

		if (DEBUG) System.out.println("node nodeType= " + node.getClass().getName()); //$NON-NLS-1$
		if (DEBUG) System.out.println("parent nodeType= " + node.getParent().getClass().getName()); //$NON-NLS-1$
		if (DEBUG) System.out.println("GrandParent nodeType= " + node.getParent().getParent().getClass().getName()); //$NON-NLS-1$

		ASTNode parent= node.getParent();
		ASTNode grandParent= parent.getParent();
		if (grandParent == null)
			return nodeTypeNotSupported();

		// adjustment needed if part of a parameterized type is selected
		if (grandParent.getNodeType() == ASTNode.PARAMETERIZED_TYPE){
			node= grandParent;
		}

		// adjustment needed if part of a qualified name is selected
		ASTNode current= null;
		if (node.getNodeType() == ASTNode.QUALIFIED_NAME){
			current= node;
			while (current.getNodeType() == ASTNode.QUALIFIED_NAME){
				current= current.getParent();
			}
			if (current.getNodeType() != ASTNode.SIMPLE_TYPE){
				return nodeTypeNotSupported();
			}
			node= current.getParent();
		} else if (parent.getNodeType() == ASTNode.QUALIFIED_NAME){
			current= parent;
			while (current.getNodeType() == ASTNode.QUALIFIED_NAME){
				current= current.getParent();
			}
			if (current.getNodeType() != ASTNode.SIMPLE_TYPE){
				return nodeTypeNotSupported();
			}
			node= current.getParent();
		}

		fObject= node.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
		switch (node.getNodeType()) {
			case ASTNode.SIMPLE_NAME :
				return simpleNameSelected((SimpleName)node);
			case ASTNode.VARIABLE_DECLARATION_STATEMENT :
				return variableDeclarationStatementSelected((VariableDeclarationStatement) node);
			case ASTNode.FIELD_DECLARATION :
				return fieldDeclarationSelected((FieldDeclaration) node);
			case ASTNode.SINGLE_VARIABLE_DECLARATION :
				return singleVariableDeclarationSelected((SingleVariableDeclaration) node);
			case ASTNode.PARAMETERIZED_TYPE:
				return parameterizedTypeSelected((ParameterizedType) node);
			default :
				return nodeTypeNotSupported();
		}
	}
}
 
Example 19
Source File: RefactorProposalUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static String getEnclosingType(ASTNode declaration) {
	ASTNode node = declaration == null ? null : declaration.getParent();
	ITypeBinding type = ASTNodes.getEnclosingType(node);
	return type == null ? null : type.getQualifiedName();
}
 
Example 20
Source File: ASTResolving.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static Type guessTypeForReference(AST ast, ASTNode node) {
	ASTNode parent= node.getParent();
	while (parent != null) {
		switch (parent.getNodeType()) {
			case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
				if (((VariableDeclarationFragment) parent).getInitializer() == node) {
					return ASTNodeFactory.newType(ast, (VariableDeclaration) parent);
				}
				return null;
			case ASTNode.SINGLE_VARIABLE_DECLARATION:
				if (((VariableDeclarationFragment) parent).getInitializer() == node) {
					return ASTNodeFactory.newType(ast, (VariableDeclaration) parent);
				}
				return null;
			case ASTNode.ARRAY_ACCESS:
				if (!((ArrayAccess) parent).getIndex().equals(node)) {
					Type type = guessTypeForReference(ast, parent);
					if (type != null) {
						return ASTNodeFactory.newArrayType(type);
					}
				}
				return null;
			case ASTNode.FIELD_ACCESS:
				if (node.equals(((FieldAccess) parent).getName())) {
					node = parent;
					parent = parent.getParent();
				} else {
					return null;
				}
				break;
			case ASTNode.SUPER_FIELD_ACCESS:
			case ASTNode.PARENTHESIZED_EXPRESSION:
				node= parent;
				parent= parent.getParent();
				break;
			case ASTNode.QUALIFIED_NAME:
				if (node.equals(((QualifiedName) parent).getName())) {
					node = parent;
					parent = parent.getParent();
				} else {
					return null;
				}
				break;
			default:
				return null;
		}
	}
	return null;
}