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

The following examples show how to use org.eclipse.jdt.core.dom.ASTNode#getLocationInParent() . 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: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) {
		AST ast= selectedNode.getAST();
		SwitchStatement parent= (SwitchStatement) selectedNode.getParent();
		
		for (Statement statement : (List<Statement>) parent.statements()) {
			if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) {
				
				// insert //$CASES-OMITTED$:
				ASTRewrite rewrite= ASTRewrite.create(ast);
				rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
				ListRewrite listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY);
				ASTNode casesOmittedComment= rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$
				listRewrite.insertBefore(casesOmittedComment, statement, null);
				
				String label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted;
				Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
				ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED, image);
				proposals.add(proposal);
				break;
			}
		}
	}
}
 
Example 2
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the type binding of the node's type context or null if the node is inside
 * an annotation, type parameter, super type declaration, or Javadoc of a top level type.
 * The result of this method is equal to the result of {@link #getBindingOfParentType(ASTNode)} for nodes in the type's body.
 * 
 * @param node an AST node
 * @return the type binding of the node's parent type context, or <code>null</code>
 */
public static ITypeBinding getBindingOfParentTypeContext(ASTNode node) {
	StructuralPropertyDescriptor lastLocation= null;

	while (node != null) {
		if (node instanceof AbstractTypeDeclaration) {
			AbstractTypeDeclaration decl= (AbstractTypeDeclaration) node;
			if (lastLocation == decl.getBodyDeclarationsProperty()
					|| lastLocation == decl.getJavadocProperty()) {
				return decl.resolveBinding();
			} else if (decl instanceof EnumDeclaration && lastLocation == EnumDeclaration.ENUM_CONSTANTS_PROPERTY) {
				return decl.resolveBinding();
			}
		} else if (node instanceof AnonymousClassDeclaration) {
			return ((AnonymousClassDeclaration) node).resolveBinding();
		}
		lastLocation= node.getLocationInParent();
		node= node.getParent();
	}
	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: SemanticHighlightings.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean consumes(SemanticToken token) {

	// 1: match types
	SimpleName name = token.getNode();
	ASTNode node = name.getParent();
	int nodeType = node.getNodeType();
	if (nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.QUALIFIED_TYPE) {
		return false;
	}

	// 2: match type arguments
	StructuralPropertyDescriptor locationInParent = node.getLocationInParent();
	if (locationInParent == ParameterizedType.TYPE_ARGUMENTS_PROPERTY) {
		return true;
	}

	return false;
}
 
Example 5
Source File: InlineTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkSelection(VariableDeclaration decl) {
	ASTNode parent= decl.getParent();
	if (parent instanceof MethodDeclaration) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineTempRefactoring_method_parameter);
	}

	if (parent instanceof CatchClause) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineTempRefactoring_exceptions_declared);
	}

	if (parent instanceof VariableDeclarationExpression && parent.getLocationInParent() == ForStatement.INITIALIZERS_PROPERTY) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineTempRefactoring_for_initializers);
	}

	if (parent instanceof VariableDeclarationExpression && parent.getLocationInParent() == TryStatement.RESOURCES_PROPERTY) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineTempRefactoring_resource_in_try_with_resources);
	}

	if (decl.getInitializer() == null) {
		String message= Messages.format(RefactoringCoreMessages.InlineTempRefactoring_not_initialized, BasicElementLabels.getJavaElementName(decl.getName().getIdentifier()));
		return RefactoringStatus.createFatalErrorStatus(message);
	}

	return checkAssignments(decl);
}
 
Example 6
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void addUnnecessaryThrownExceptionProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	selectedNode= ASTNodes.getNormalizedNode(selectedNode);
	if (selectedNode == null || selectedNode.getLocationInParent() != MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY) {
		return;
	}
	MethodDeclaration decl= (MethodDeclaration) selectedNode.getParent();
	IMethodBinding binding= decl.resolveBinding();
	if (binding != null) {
		List<Type> thrownExceptions= decl.thrownExceptionTypes();
		int index= thrownExceptions.indexOf(selectedNode);
		if (index == -1) {
			return;
		}
		ChangeDescription[] desc= new ChangeDescription[thrownExceptions.size()];
		desc[index]= new RemoveDescription();

		ICompilationUnit cu= context.getCompilationUnit();
		String label= CorrectionMessages.LocalCorrectionsSubProcessor_unnecessarythrow_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);

		proposals.add(new ChangeMethodSignatureProposal(label, cu, selectedNode, binding, null, desc, IProposalRelevance.UNNECESSARY_THROW, image));
	}

	JavadocTagsSubProcessor.getUnusedAndUndocumentedParameterOrExceptionProposals(context, problem, proposals);
}
 
Example 7
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addMissingDefaultCaseProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) {
		SwitchStatement switchStatement= (SwitchStatement) selectedNode.getParent();
		for (Statement statement : (List<Statement>) switchStatement.statements()) {
			if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) {
				return;
			}
		}
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		createMissingDefaultProposal(context, switchStatement, image, proposals);
	}
}
 
Example 8
Source File: LocalCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static void getMissingEnumConstantCaseProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) {
	for (ChangeCorrectionProposal proposal : proposals) {
		if (CorrectionMessages.LocalCorrectionsSubProcessor_add_missing_cases_description.equals(proposal.getName())) {
			return;
		}
	}

	ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Expression) {
		StructuralPropertyDescriptor locationInParent = selectedNode.getLocationInParent();
		ASTNode parent = selectedNode.getParent();
		ITypeBinding binding;
		List<Statement> statements;

		if (locationInParent == SwitchStatement.EXPRESSION_PROPERTY) {
			SwitchStatement statement = (SwitchStatement) parent;
			binding = statement.getExpression().resolveTypeBinding();
			statements = statement.statements();
		} else if (locationInParent == SwitchExpression.EXPRESSION_PROPERTY) {
			SwitchExpression switchExpression = (SwitchExpression) parent;
			binding = switchExpression.getExpression().resolveTypeBinding();
			statements = switchExpression.statements();
		} else {
			return;
		}

		if (binding == null || !binding.isEnum()) {
			return;
		}

		ArrayList<String> missingEnumCases = new ArrayList<>();
		boolean hasDefault = evaluateMissingSwitchCases(binding, statements, missingEnumCases);
		if (missingEnumCases.size() == 0 && hasDefault) {
			return;
		}

		createMissingCaseProposals(context, parent, missingEnumCases, proposals);
	}
}
 
Example 9
Source File: ASTRewrite.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Replaces the given node in this rewriter. The replacement node
 * must either be brand new (not part of the original AST) or a placeholder
 * node (for example, one created by {@link #createCopyTarget(ASTNode)}
 * or {@link #createStringPlaceholder(String, int)}). The AST itself
    * is not actually modified in any way; rather, the rewriter just records
    * a note that this node has been replaced.
 *
 * @param node the node being replaced. The node can either be an original node in the AST
 * or (since 3.4) a new node already inserted or used as replacement in this AST rewriter.
 * @param replacement the replacement node, or <code>null</code> if no
 * replacement
 * @param editGroup the edit group in which to collect the corresponding
 * text edits, or <code>null</code> if ungrouped
 * @throws IllegalArgumentException if the node is null, or if the node is not part
 * of this rewriter's AST, or if the replacement node is not a new node (or
    * placeholder), or if the described modification is otherwise invalid
 */
public final void replace(ASTNode node, ASTNode replacement, TextEditGroup editGroup) {
	if (node == null) {
		throw new IllegalArgumentException();
	}

	StructuralPropertyDescriptor property;
	ASTNode parent;
	if (RewriteEventStore.isNewNode(node)) { // replace a new node, bug 164862
		PropertyLocation location= this.eventStore.getPropertyLocation(node, RewriteEventStore.NEW);
		if (location != null) {
			property= location.getProperty();
			parent= location.getParent();
		} else {
			throw new IllegalArgumentException("Node is not part of the rewriter's AST"); //$NON-NLS-1$
		}
	} else {
		property= node.getLocationInParent();
		parent= node.getParent();
	}

	if (property.isChildListProperty()) {
		getListRewrite(parent, (ChildListPropertyDescriptor) property).replace(node, replacement, editGroup);
	} else {
		set(parent, property, replacement, editGroup);
	}
}
 
Example 10
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean getConvertLocalToFieldProposal(IInvocationContext context, final ASTNode node, Collection<ICommandAccess> proposals) throws CoreException {
	if (!(node instanceof SimpleName))
		return false;

	SimpleName name= (SimpleName) node;
	IBinding binding= name.resolveBinding();
	if (!(binding instanceof IVariableBinding))
		return false;
	IVariableBinding varBinding= (IVariableBinding) binding;
	if (varBinding.isField() || varBinding.isParameter())
		return false;
	ASTNode decl= context.getASTRoot().findDeclaringNode(varBinding);
	if (decl == null || decl.getLocationInParent() != VariableDeclarationStatement.FRAGMENTS_PROPERTY)
		return false;

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

	PromoteTempToFieldRefactoring refactoring= new PromoteTempToFieldRefactoring((VariableDeclaration) decl);
	if (refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
		String label= CorrectionMessages.QuickAssistProcessor_convert_local_to_field_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		LinkedProposalModel linkedProposalModel= new LinkedProposalModel();
		refactoring.setLinkedProposalModel(linkedProposalModel);

		RefactoringCorrectionProposal proposal= new RefactoringCorrectionProposal(label, context.getCompilationUnit(), refactoring, IProposalRelevance.CONVERT_LOCAL_TO_FIELD, image);
		proposal.setLinkedProposalModel(linkedProposalModel);
		proposal.setCommandId(CONVERT_LOCAL_TO_FIELD_ID);
		proposals.add(proposal);
	}
	return true;
}
 
Example 11
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 12
Source File: NullAnnotationsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isComplainingAboutReturn(ASTNode selectedNode) {
	if (selectedNode.getParent().getNodeType() == ASTNode.RETURN_STATEMENT)
		return true;
	while (!(selectedNode instanceof Type)) {
		if (selectedNode == null) return false;
		selectedNode = selectedNode.getParent();
	}
	return selectedNode.getLocationInParent() == MethodDeclaration.RETURN_TYPE2_PROPERTY;			
}
 
Example 13
Source File: CopyQualifiedNameAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks whether the given name belongs to a {@link ClassInstanceCreation} and if so, returns
 * its constructor binding.
 * 
 * @param nameNode the name node
 * @return the constructor binding or <code>null</code> if not found
 * @since 3.7
 */
private IBinding getConstructorBindingIfAvailable(Name nameNode) {
	ASTNode type= ASTNodes.getNormalizedNode(nameNode);
	StructuralPropertyDescriptor loc= type.getLocationInParent();
	if (loc == ClassInstanceCreation.TYPE_PROPERTY) {
		return ((ClassInstanceCreation) type.getParent()).resolveConstructorBinding();
	}
	return null;
}
 
Example 14
Source File: ExtractMethodAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void checkExpression(RefactoringStatus status) {
	ASTNode[] nodes = getSelectedNodes();
	if (nodes != null && nodes.length == 1) {
		ASTNode node = nodes[0];
		if (node instanceof Type) {
			status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference, JavaStatusContext.create(fCUnit, node));
		} else if (node.getLocationInParent() == SwitchCase.EXPRESSION_PROPERTY) {
			status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_switch_case, JavaStatusContext.create(fCUnit, node));
		} else if (node instanceof Annotation || ASTNodes.getParent(node, Annotation.class) != null) {
			status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_from_annotation, JavaStatusContext.create(fCUnit, node));
		}
	}
}
 
Example 15
Source File: NewCUUsingWizardProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ITypeBinding getPossibleSuperTypeBinding(ASTNode node) {
	if (fTypeKind == K_ANNOTATION) {
		return null;
	}

	AST ast= node.getAST();
	node= ASTNodes.getNormalizedNode(node);
	ASTNode parent= node.getParent();
	switch (parent.getNodeType()) {
		case ASTNode.METHOD_DECLARATION:
			if (node.getLocationInParent() == MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY) {
				return ast.resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$
			}
			break;
		case ASTNode.THROW_STATEMENT :
			return ast.resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$
		case ASTNode.SINGLE_VARIABLE_DECLARATION:
			if (parent.getLocationInParent() == CatchClause.EXCEPTION_PROPERTY) {
				return ast.resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$
			}
			break;
		case ASTNode.VARIABLE_DECLARATION_STATEMENT:
		case ASTNode.FIELD_DECLARATION:
			return null; // no guessing for LHS types, cannot be a supertype of a known type
		case ASTNode.PARAMETERIZED_TYPE:
			return null; // Inheritance doesn't help: A<X> z= new A<String>(); ->
	}
	ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node);
	if (binding != null && !binding.isRecovered()) {
		return binding;
	}
	return null;
}
 
Example 16
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addFallThroughProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof SwitchCase && selectedNode.getLocationInParent() == SwitchStatement.STATEMENTS_PROPERTY) {
		AST ast= selectedNode.getAST();
		ASTNode parent= selectedNode.getParent();

		// insert break:
		ASTRewrite rewrite= ASTRewrite.create(ast);
		ListRewrite listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY);
		listRewrite.insertBefore(ast.newBreakStatement(), selectedNode, null);

		String label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_break_statement;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_BREAK_STATEMENT, image);
		proposals.add(proposal);

		// insert //$FALL-THROUGH$:
		rewrite= ASTRewrite.create(ast);
		rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
		listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY);
		ASTNode fallThroughComment= rewrite.createStringPlaceholder("//$FALL-THROUGH$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$
		listRewrite.insertBefore(fallThroughComment, selectedNode, null);

		label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_fall_through;
		image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_FALL_THROUGH, image);
		proposals.add(proposal);
	}
}
 
Example 17
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static IBinding resolveBinding(ASTNode node) {
	if (node instanceof SimpleName) {
		SimpleName simpleName = (SimpleName) node;
		// workaround for https://bugs.eclipse.org/62605 (constructor name resolves to type, not method)
		ASTNode normalized = ASTNodes.getNormalizedNode(simpleName);
		if (normalized.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) {
			ClassInstanceCreation cic = (ClassInstanceCreation) normalized.getParent();
			IMethodBinding constructorBinding = cic.resolveConstructorBinding();
			if (constructorBinding == null) {
				return null;
			}
			ITypeBinding declaringClass = constructorBinding.getDeclaringClass();
			if (!declaringClass.isAnonymous()) {
				return constructorBinding;
			}
			ITypeBinding superTypeDeclaration = declaringClass.getSuperclass().getTypeDeclaration();
			return resolveSuperclassConstructor(superTypeDeclaration, constructorBinding);
		}
		return simpleName.resolveBinding();

	} else if (node instanceof SuperConstructorInvocation) {
		return ((SuperConstructorInvocation) node).resolveConstructorBinding();
	} else if (node instanceof ConstructorInvocation) {
		return ((ConstructorInvocation) node).resolveConstructorBinding();
	} else if (node instanceof LambdaExpression) {
		return ((LambdaExpression) node).resolveMethodBinding();
	} else {
		return null;
	}
}
 
Example 18
Source File: CodeStyleFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean isMethodArgument(Expression expression) {
	ASTNode parent= expression;
	while (parent instanceof Expression) {

		if (parent.getLocationInParent() == MethodInvocation.ARGUMENTS_PROPERTY)
			return true;

		if (parent.getLocationInParent() == ConstructorInvocation.ARGUMENTS_PROPERTY)
			return true;

		parent= ((Expression) parent).getParent();
	}

	return false;
}
 
Example 19
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 20
Source File: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private RefactoringStatus checkSelection(IProgressMonitor pm) throws JavaModelException {
	try {
		pm.beginTask("", 8); //$NON-NLS-1$

		IExpressionFragment selectedExpression= getSelectedExpression();

		if (selectedExpression == null) {
			String message= RefactoringCoreMessages.ExtractTempRefactoring_select_expression;
			return CodeRefactoringUtil.checkMethodSyntaxErrors(fSelectionStart, fSelectionLength, fCompilationUnitNode, message);
		}
		pm.worked(1);

		if (isUsedInExplicitConstructorCall())
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_explicit_constructor);
		pm.worked(1);

		ASTNode associatedNode= selectedExpression.getAssociatedNode();
		if (getEnclosingBodyNode() == null || ASTNodes.getParent(associatedNode, Annotation.class) != null)
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_expr_in_method_or_initializer);
		pm.worked(1);

		if (associatedNode instanceof Name && associatedNode.getParent() instanceof ClassInstanceCreation && associatedNode.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY)
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_name_in_new);
		pm.worked(1);

		RefactoringStatus result= new RefactoringStatus();
		result.merge(checkExpression());
		if (result.hasFatalError())
			return result;
		pm.worked(1);

		result.merge(checkExpressionFragmentIsRValue());
		if (result.hasFatalError())
			return result;
		pm.worked(1);

		if (isUsedInForInitializerOrUpdater(getSelectedExpression().getAssociatedExpression()))
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_for_initializer_updater);
		pm.worked(1);

		if (isReferringToLocalVariableFromFor(getSelectedExpression().getAssociatedExpression()))
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_refers_to_for_variable);
		pm.worked(1);

		return result;
	} finally {
		pm.done();
	}
}