Java Code Examples for org.eclipse.jdt.internal.corext.dom.ASTNodes#isParent()

The following examples show how to use org.eclipse.jdt.internal.corext.dom.ASTNodes#isParent() . 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: SnippetFinder.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
static boolean isLeftHandSideOfAssignment(ASTNode node) {
	Assignment assignment = (Assignment) ASTNodes.getParent(node, ASTNode.ASSIGNMENT);
	if (assignment != null) {
		Expression leftHandSide = assignment.getLeftHandSide();
		if (leftHandSide == node) {
			return true;
		}
		if (ASTNodes.isParent(node, leftHandSide)) {
			switch (leftHandSide.getNodeType()) {
				case ASTNode.SIMPLE_NAME:
					return true;
				case ASTNode.FIELD_ACCESS:
					return node == ((FieldAccess) leftHandSide).getName();
				case ASTNode.QUALIFIED_NAME:
					return node == ((QualifiedName) leftHandSide).getName();
				case ASTNode.SUPER_FIELD_ACCESS:
					return node == ((SuperFieldAccess) leftHandSide).getName();
				default:
					return false;
			}
		}
	}
	return false;
}
 
Example 2
Source File: SnippetFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean isLeftHandSideOfAssignment(ASTNode node) {
	Assignment assignment= (Assignment)ASTNodes.getParent(node, ASTNode.ASSIGNMENT);
	if (assignment != null) {
		Expression leftHandSide= assignment.getLeftHandSide();
		if (leftHandSide == node) {
			return true;
		}
		if (ASTNodes.isParent(node, leftHandSide)) {
			switch (leftHandSide.getNodeType()) {
				case ASTNode.SIMPLE_NAME:
					return true;
				case ASTNode.FIELD_ACCESS:
					return node == ((FieldAccess)leftHandSide).getName();
				case ASTNode.QUALIFIED_NAME:
					return node == ((QualifiedName)leftHandSide).getName();
				case ASTNode.SUPER_FIELD_ACCESS:
					return node == ((SuperFieldAccess)leftHandSide).getName();
				default:
					return false;
			}
		}
	}
	return false;
}
 
Example 3
Source File: NewVariableCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private ASTNode getCommonParent(ASTNode node1, ASTNode node2) {
	ASTNode parent= node1.getParent();
	while (parent != null && !ASTNodes.isParent(node2, parent)) {
		parent= parent.getParent();
	}
	return parent;
}
 
Example 4
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isInsideSubclassOfDeclaringType(ASTNode node) {
	Assert.isTrue((node instanceof ClassInstanceCreation) || (node instanceof SuperConstructorInvocation));
	final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(node, AbstractTypeDeclaration.class);
	Assert.isNotNull(declaration);

	final AnonymousClassDeclaration anonymous= (AnonymousClassDeclaration) ASTNodes.getParent(node, AnonymousClassDeclaration.class);
	boolean isAnonymous= anonymous != null && ASTNodes.isParent(anonymous, declaration);
	if (isAnonymous)
		return anonymous != null && isSubclassBindingOfEnclosingType(anonymous.resolveBinding());
	return isSubclassBindingOfEnclosingType(declaration.resolveBinding());
}
 
Example 5
Source File: Checks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isDeclaredIn(VariableDeclaration tempDeclaration, Class<? extends ASTNode> astNodeClass) {
	ASTNode initializer= ASTNodes.getParent(tempDeclaration, astNodeClass);
	if (initializer == null)
		return false;
	ASTNode anonymous= ASTNodes.getParent(tempDeclaration, AnonymousClassDeclaration.class);
	if (anonymous == null)
		return true;
	// stupid code. Is to find out if the variable declaration isn't a field.
	if (ASTNodes.isParent(anonymous, initializer))
		return false;
	return true;
}
 
Example 6
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isBindingToTemp(IVariableBinding variable) {
	if (variable.isField())
		return false;
	if (!Modifier.isFinal(variable.getModifiers()))
		return false;
	ASTNode declaringNode= fCompilationUnitNode.findDeclaringNode(variable);
	if (declaringNode == null)
		return false;
	if (ASTNodes.isParent(declaringNode, fAnonymousInnerClassNode))
		return false;
	return true;
}
 
Example 7
Source File: NewVariableCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ASTNode getCommonParent(ASTNode node1, ASTNode node2) {
	ASTNode parent= node1.getParent();
	while (parent != null && !ASTNodes.isParent(node2, parent)) {
		parent= parent.getParent();
	}
	return parent;
}
 
Example 8
Source File: NewMethodCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int evaluateModifiers(ASTNode targetTypeDecl) {
	if (getSenderBinding().isAnnotation()) {
		return 0;
	}
	if (getSenderBinding().isInterface()) {
		// for interface and annotation members copy the modifiers from an existing field
		MethodDeclaration[] methodDecls= ((TypeDeclaration) targetTypeDecl).getMethods();
		if (methodDecls.length > 0) {
			return methodDecls[0].getModifiers();
		}
		return 0;
	}
	ASTNode invocationNode= getInvocationNode();
	if (invocationNode instanceof MethodInvocation) {
		int modifiers= 0;
		Expression expression= ((MethodInvocation)invocationNode).getExpression();
		if (expression != null) {
			if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) {
				modifiers |= Modifier.STATIC;
			}
		} else if (ASTResolving.isInStaticContext(invocationNode)) {
			modifiers |= Modifier.STATIC;
		}
		ASTNode node= ASTResolving.findParentType(invocationNode);
		if (targetTypeDecl.equals(node)) {
			modifiers |= Modifier.PRIVATE;
		} else if (node instanceof AnonymousClassDeclaration && ASTNodes.isParent(node, targetTypeDecl)) {
			modifiers |= Modifier.PROTECTED;
			if (ASTResolving.isInStaticContext(node) && expression == null) {
				modifiers |= Modifier.STATIC;
			}
		} else {
			modifiers |= Modifier.PUBLIC;
		}
		return modifiers;
	}
	return Modifier.PUBLIC;
}
 
Example 9
Source File: NewMethodCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private int evaluateModifiers(ASTNode targetTypeDecl) {
	if (getSenderBinding().isAnnotation()) {
		return 0;
	}
	boolean isTargetInterface= getSenderBinding().isInterface();
	if (isTargetInterface && !JavaModelUtil.is18OrHigher(getCompilationUnit().getJavaProject())) {
		// only abstract methods are allowed for interface present in less than Java 1.8
		return getInterfaceMethodModifiers(targetTypeDecl, true);
	}
	ASTNode invocationNode= getInvocationNode();
	if (invocationNode instanceof MethodInvocation) {
		int modifiers= 0;
		Expression expression= ((MethodInvocation)invocationNode).getExpression();
		if (expression != null) {
			if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) {
				modifiers |= Modifier.STATIC;
			}
		} else if (ASTResolving.isInStaticContext(invocationNode)) {
			modifiers |= Modifier.STATIC;
		}
		ASTNode node= ASTResolving.findParentType(invocationNode);
		boolean isParentInterface= node instanceof TypeDeclaration && ((TypeDeclaration) node).isInterface();
		if (isTargetInterface || isParentInterface) {
			if (expression == null && !targetTypeDecl.equals(node)) {
				modifiers|= Modifier.STATIC;
				if (isTargetInterface) {
					modifiers|= getInterfaceMethodModifiers(targetTypeDecl, false);
				} else {
					modifiers|= Modifier.PROTECTED;
				}
			} else if (modifiers == Modifier.STATIC) {
				modifiers= getInterfaceMethodModifiers(targetTypeDecl, false) | Modifier.STATIC;
			} else {
				modifiers= getInterfaceMethodModifiers(targetTypeDecl, true);
			}
		} else if (targetTypeDecl.equals(node)) {
			modifiers |= Modifier.PRIVATE;
		} else if (node instanceof AnonymousClassDeclaration && ASTNodes.isParent(node, targetTypeDecl)) {
			modifiers |= Modifier.PROTECTED;
			if (ASTResolving.isInStaticContext(node) && expression == null) {
				modifiers |= Modifier.STATIC;
			}
		} else {
			modifiers |= Modifier.PUBLIC;
		}
		return modifiers;
	}
	return Modifier.PUBLIC;
}
 
Example 10
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private boolean isInAnonymousTypeInsideInputType(ASTNode node, AbstractTypeDeclaration declaration) {
	final AnonymousClassDeclaration anonymous= (AnonymousClassDeclaration) ASTNodes.getParent(node, AnonymousClassDeclaration.class);
	return anonymous != null && ASTNodes.isParent(anonymous, declaration);
}
 
Example 11
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private boolean isInLocalTypeInsideInputType(ASTNode node, AbstractTypeDeclaration declaration) {
	final TypeDeclarationStatement statement= (TypeDeclarationStatement) ASTNodes.getParent(node, TypeDeclarationStatement.class);
	return statement != null && ASTNodes.isParent(statement, declaration);
}
 
Example 12
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private boolean isInNonStaticMemberTypeInsideInputType(ASTNode node, AbstractTypeDeclaration declaration) {
	final AbstractTypeDeclaration nested= (AbstractTypeDeclaration) ASTNodes.getParent(node, AbstractTypeDeclaration.class);
	return nested != null && !declaration.equals(nested) && !Modifier.isStatic(nested.getFlags()) && ASTNodes.isParent(nested, declaration);
}
 
Example 13
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Attempts to qualify a "this" expression for a method invocation with an appropriate qualifier.
 * The invoked method is analyzed according to the following specs:
 *
 * 'this' must be qualified iff method is declared in an enclosing type or a supertype of an enclosing type
 *
 * 1) The method is declared somewhere outside of the cu of the invocation
 *      1a) inside a supertype of the current type
 *      1b) inside a supertype of an enclosing type
 * 2) The method is declared inside of the cu of the invocation
 * 		2a) inside the type of the invocation
 * 		2b) outside the type of the invocation
 *
 * In case of 1a) and 2b), qualify with the enclosing type.
 * @param expr a {@link ThisExpression}
 * @param originalInvocation the original method invocation
 * @param enclosing the enclosing member of the original method invocation
 * @param unitRewriter the rewrite
 * @return resulting status
 *
 */
private RefactoringStatus qualifyThisExpression(ThisExpression expr, MethodInvocation originalInvocation, IMember enclosing, CompilationUnitRewrite unitRewriter) {

	RefactoringStatus status= new RefactoringStatus();

	IMethodBinding methodBinding= originalInvocation.resolveMethodBinding();
	MethodDeclaration methodDeclaration= (MethodDeclaration) ASTNodes.findDeclaration(methodBinding, originalInvocation.getRoot());

	ITypeBinding currentTypeBinding= null;
	if (methodDeclaration != null) {
		// Case 1) : Declaring type is inside this cu => use its name if it's declared in an enclosing type
		if (ASTNodes.isParent(originalInvocation, methodDeclaration.getParent()))
			currentTypeBinding= methodBinding.getDeclaringClass();
		else
			currentTypeBinding= ASTNodes.getEnclosingType(originalInvocation);
	} else {
		// Case 2) : Declaring type is outside of this cu => find subclass in this cu
		ASTNode currentTypeDeclaration= getEnclosingTypeDeclaration(originalInvocation);
		currentTypeBinding= ASTNodes.getEnclosingType(currentTypeDeclaration);
		while (currentTypeDeclaration != null && (Bindings.findMethodInHierarchy(currentTypeBinding, methodBinding.getName(), methodBinding.getParameterTypes()) == null)) {
			currentTypeDeclaration= getEnclosingTypeDeclaration(currentTypeDeclaration.getParent());
			currentTypeBinding= ASTNodes.getEnclosingType(currentTypeDeclaration);
		}
	}

	if (currentTypeBinding == null) {
		status.merge(createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_declaring_type_not_found));
		return status;
	}

	currentTypeBinding= currentTypeBinding.getTypeDeclaration();

	ITypeBinding typeOfCall= ASTNodes.getEnclosingType(originalInvocation);
	if (!typeOfCall.equals(currentTypeBinding)) {
		if (currentTypeBinding.isAnonymous()) {
			// Cannot qualify, see bug 115277
			status.merge(createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_anonymous_cannot_qualify));
		} else {
			expr.setQualifier(unitRewriter.getAST().newSimpleName(currentTypeBinding.getName()));
		}
	} else {
		// do not qualify, only use "this.".
	}

	return status;
}
 
Example 14
Source File: LambdaExpressionsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
		 * {@inheritDoc}
		 */
		@Override
		public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {

			ASTRewrite rewrite= cuRewrite.getASTRewrite();
			ImportRemover importRemover= cuRewrite.getImportRemover();
			AST ast= rewrite.getAST();

			HashMap<ClassInstanceCreation, HashSet<String>> cicToNewNames= new HashMap<ClassInstanceCreation, HashSet<String>>();
			for (int i= 0; i < fExpressions.size(); i++) {
				ClassInstanceCreation classInstanceCreation= fExpressions.get(i);
				TextEditGroup group= createTextEditGroup(FixMessages.LambdaExpressionsFix_convert_to_lambda_expression, cuRewrite);

				AnonymousClassDeclaration anonymTypeDecl= classInstanceCreation.getAnonymousClassDeclaration();
				List<BodyDeclaration> bodyDeclarations= anonymTypeDecl.bodyDeclarations();

				Object object= bodyDeclarations.get(0);
				if (!(object instanceof MethodDeclaration))
					continue;
				MethodDeclaration methodDeclaration= (MethodDeclaration) object;
				HashSet<String> excludedNames= new HashSet<String>();
				if (i != 0) {
					for (ClassInstanceCreation convertedCic : fExpressions.subList(0, i)) {
						if (ASTNodes.isParent(classInstanceCreation, convertedCic)) {
							excludedNames.addAll(cicToNewNames.get(convertedCic));
						}
					}
				}
				HashSet<String> newNames= makeNamesUnique(excludedNames, methodDeclaration, rewrite, group);
				cicToNewNames.put(classInstanceCreation, new HashSet<String>(newNames));
				List<SingleVariableDeclaration> methodParameters= methodDeclaration.parameters();

				// use short form with inferred parameter types and without parentheses if possible
				LambdaExpression lambdaExpression= ast.newLambdaExpression();
				List<VariableDeclaration> lambdaParameters= lambdaExpression.parameters();
				lambdaExpression.setParentheses(methodParameters.size() != 1);
				for (SingleVariableDeclaration methodParameter : methodParameters) {
					VariableDeclarationFragment lambdaParameter= ast.newVariableDeclarationFragment();
					lambdaParameter.setName((SimpleName) rewrite.createCopyTarget(methodParameter.getName()));
					lambdaParameters.add(lambdaParameter);
				}
				
				Block body= methodDeclaration.getBody();
				List<Statement> statements= body.statements();
				ASTNode lambdaBody= body;
				if (statements.size() == 1) {
					// use short form with just an expression body if possible
					Statement statement= statements.get(0);
					if (statement instanceof ExpressionStatement) {
						lambdaBody= ((ExpressionStatement) statement).getExpression();
					} else if (statement instanceof ReturnStatement) {
						Expression returnExpression= ((ReturnStatement) statement).getExpression();
						if (returnExpression != null) {
							lambdaBody= returnExpression;
						}
					}
				}
				//TODO: Bug 421479: [1.8][clean up][quick assist] convert anonymous to lambda must consider lost scope of interface
//				lambdaBody.accept(new InterfaceAccessQualifier(rewrite, classInstanceCreation.getType().resolveBinding())); //TODO: maybe need a separate ASTRewrite and string placeholder
				
				lambdaExpression.setBody(rewrite.createCopyTarget(lambdaBody));
				Expression replacement= lambdaExpression;
				if (ASTNodes.isTargetAmbiguous(classInstanceCreation, lambdaParameters.isEmpty())) {
					CastExpression cast= ast.newCastExpression();
					cast.setExpression(lambdaExpression);
					ImportRewrite importRewrite= cuRewrite.getImportRewrite();
					ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(classInstanceCreation, importRewrite);
					Type castType= importRewrite.addImport(classInstanceCreation.getType().resolveBinding(), ast, importRewriteContext);
					cast.setType(castType);
					importRemover.registerAddedImports(castType);
					replacement= cast;
				}
				rewrite.replace(classInstanceCreation, replacement, group);

				importRemover.registerRemovedNode(classInstanceCreation);
				importRemover.registerRetainedNode(lambdaBody);
			}
		}