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

The following examples show how to use org.eclipse.jdt.core.dom.ASTNode#getAST() . 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: JavadocTagsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void getInvalidQualificationProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode node= problem.getCoveringNode(context.getASTRoot());
	if (!(node instanceof Name)) {
		return;
	}
	Name name= (Name) node;
	IBinding binding= name.resolveBinding();
	if (!(binding instanceof ITypeBinding)) {
		return;
	}
	ITypeBinding typeBinding= (ITypeBinding)binding;

	AST ast= node.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	rewrite.replace(name, ast.newName(typeBinding.getQualifiedName()), null);

	String label= CorrectionMessages.JavadocTagsSubProcessor_qualifylinktoinner_description;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.QUALIFY_INNER_TYPE_NAME, image);

	proposals.add(proposal);
}
 
Example 3
Source File: ImplementInterfaceProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected ASTRewrite getRewrite() throws CoreException {
	ASTNode boundNode= fAstRoot.findDeclaringNode(fBinding);
	ASTNode declNode= null;
	CompilationUnit newRoot= fAstRoot;
	if (boundNode != null) {
		declNode= boundNode; // is same CU
	} else {
		newRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		declNode= newRoot.findDeclaringNode(fBinding.getKey());
	}
	ImportRewrite imports= createImportRewrite(newRoot);

	if (declNode instanceof TypeDeclaration) {
		AST ast= declNode.getAST();
		ASTRewrite rewrite= ASTRewrite.create(ast);

		ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(declNode, imports);
		Type newInterface= imports.addImport(fNewInterface, ast, importRewriteContext, TypeLocation.OTHER);
		ListRewrite listRewrite= rewrite.getListRewrite(declNode, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY);
		listRewrite.insertLast(newInterface, null);

		return rewrite;
	}
	return null;
}
 
Example 4
Source File: NewMethodCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected SimpleName getNewName(ASTRewrite rewrite) {
	ASTNode invocationNode= getInvocationNode();
	String name;
	if (invocationNode instanceof MethodInvocation) {
		name= ((MethodInvocation)invocationNode).getName().getIdentifier();
	} else if (invocationNode instanceof SuperMethodInvocation) {
		name= ((SuperMethodInvocation)invocationNode).getName().getIdentifier();
	} else {
		name= getSenderBinding().getName(); // name of the class
	}
	AST ast= rewrite.getAST();
	SimpleName newNameNode= ast.newSimpleName(name);
	addLinkedPosition(rewrite.track(newNameNode), false, KEY_NAME);

	ASTNode invocationName= getInvocationNameNode();
	if (invocationName != null && invocationName.getAST() == ast) { // in the same CU
		addLinkedPosition(rewrite.track(invocationName), true, KEY_NAME);
	}
	return newNameNode;
}
 
Example 5
Source File: NewVariableCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private ASTRewrite doAddEnumConst(CompilationUnit astRoot) {
	SimpleName node= fOriginalNode;

	ASTNode newTypeDecl= astRoot.findDeclaringNode(fSenderBinding);
	if (newTypeDecl == null) {
		astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
	}

	if (newTypeDecl != null) {
		AST ast= newTypeDecl.getAST();

		ASTRewrite rewrite= ASTRewrite.create(ast);

		EnumConstantDeclaration constDecl= ast.newEnumConstantDeclaration();
		constDecl.setName(ast.newSimpleName(node.getIdentifier()));

		ListRewrite listRewriter= rewrite.getListRewrite(newTypeDecl, EnumDeclaration.ENUM_CONSTANTS_PROPERTY);
		listRewriter.insertLast(constDecl, null);

		addLinkedPosition(rewrite.track(constDecl.getName()), false, KEY_NAME);

		return rewrite;
	}
	return null;
}
 
Example 6
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean getAddElseProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
	if (!(node instanceof IfStatement)) {
		return false;
	}
	IfStatement ifStatement= (IfStatement) node;
	if (ifStatement.getElseStatement() != null) {
		return false;
	}

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

	AST ast= node.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	Block body= ast.newBlock();

	rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, body, null);

	String label= CorrectionMessages.QuickAssistProcessor_addelseblock_description;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_ELSE_BLOCK, image);
	resultingCollections.add(proposal);
	return true;
}
 
Example 7
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean getInverseConditionalExpressionProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
	// try to find conditional expression as parent
	while (covering instanceof Expression) {
		if (covering instanceof ConditionalExpression)
			break;
		covering= covering.getParent();
	}
	if (!(covering instanceof ConditionalExpression)) {
		return false;
	}
	ConditionalExpression expression= (ConditionalExpression) covering;
	//  we could produce quick assist
	if (resultingCollections == null) {
		return true;
	}
	//
	AST ast= covering.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	// prepare new conditional expression
	ConditionalExpression newExpression= ast.newConditionalExpression();
	newExpression.setExpression(getInversedExpression(rewrite, expression.getExpression()));
	newExpression.setThenExpression((Expression) rewrite.createCopyTarget(expression.getElseExpression()));
	newExpression.setElseExpression((Expression) rewrite.createCopyTarget(expression.getThenExpression()));
	// replace old expression with new
	rewrite.replace(expression, newExpression, null);
	// add correction proposal
	String label= CorrectionMessages.AdvancedQuickAssistProcessor_inverseConditionalExpression_description;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_CONDITIONAL_EXPRESSION, image);
	resultingCollections.add(proposal);
	return true;
}
 
Example 8
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean getInverseConditionProposals(IInvocationContext context, ASTNode covering, ArrayList<ASTNode> coveredNodes, Collection<ICommandAccess> resultingCollections) {
	if (coveredNodes.isEmpty()) {
		return false;
	}
	//
	final AST ast= covering.getAST();
	final ASTRewrite rewrite= ASTRewrite.create(ast);
	// check sub-expressions in fully covered nodes
	boolean hasChanges= false;
	for (Iterator<ASTNode> iter= coveredNodes.iterator(); iter.hasNext();) {
		ASTNode covered= iter.next();
		Expression coveredExpression= getBooleanExpression(covered);
		if (coveredExpression != null) {
			Expression inversedExpression= getInversedExpression(rewrite, coveredExpression);
			rewrite.replace(coveredExpression, inversedExpression, null);
			hasChanges= true;
		}
	}
	//
	if (!hasChanges) {
		return false;
	}
	if (resultingCollections == null) {
		return true;
	}
	// add correction proposal
	String label= CorrectionMessages.AdvancedQuickAssistProcessor_inverseConditions_description;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_CONDITIONS, image);
	resultingCollections.add(proposal);
	return true;
}
 
Example 9
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addUnnecessaryInstanceofProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());

	ASTNode curr= selectedNode;
	while (curr instanceof ParenthesizedExpression) {
		curr= ((ParenthesizedExpression) curr).getExpression();
	}

	if (curr instanceof InstanceofExpression) {
		AST ast= curr.getAST();

		ASTRewrite rewrite= ASTRewrite.create(ast);

		InstanceofExpression inst= (InstanceofExpression) curr;

		InfixExpression expression= ast.newInfixExpression();
		expression.setLeftOperand((Expression) rewrite.createCopyTarget(inst.getLeftOperand()));
		expression.setOperator(InfixExpression.Operator.NOT_EQUALS);
		expression.setRightOperand(ast.newNullLiteral());

		rewrite.replace(inst, expression, null);

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

}
 
Example 10
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the necessary change to updated a comment reference represented
 * by a search match.
 *
 * @param rewrite
 *            the current compilation unit rewrite
 * @param declaration
 *            the source method declaration
 * @param match
 *            the search match representing the method reference
 * @param status
 *            the refactoring status
 */
protected void createMethodJavadocReference(CompilationUnitRewrite rewrite, MethodDeclaration declaration, SearchMatch match, RefactoringStatus status) {
	Assert.isNotNull(rewrite);
	Assert.isNotNull(declaration);
	Assert.isNotNull(match);
	Assert.isNotNull(status);
	final ASTNode node= ASTNodeSearchUtil.findNode(match, rewrite.getRoot());
	if (node instanceof MethodRef) {
		final AST ast= node.getAST();
		final MethodRef successor= ast.newMethodRef();

		rewrite.getASTRewrite().replace(node, successor, null);
	}
}
 
Example 11
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected static ASTNode moveNode(CompilationUnitRewrite cuRewrite, ASTNode node) {
	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	if (rewrite.getAST() != node.getAST()) {
		String str= ASTNodes.getNodeSource(node, true, true);
		if (str != null) {
			return rewrite.createStringPlaceholder(str, node.getNodeType());
		}
		return ASTNode.copySubtree(rewrite.getAST(), node);
	}
	return rewrite.createMoveTarget(node);
}
 
Example 12
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean getConvertStringConcatenationProposals(IInvocationContext context, Collection<ICommandAccess> resultingCollections) {
	ASTNode node= context.getCoveringNode();
	BodyDeclaration parentDecl= ASTResolving.findParentBodyDeclaration(node);
	if (!(parentDecl instanceof MethodDeclaration || parentDecl instanceof Initializer))
		return false;

	AST ast= node.getAST();
	ITypeBinding stringBinding= ast.resolveWellKnownType("java.lang.String"); //$NON-NLS-1$

	if (node instanceof Expression && !(node instanceof InfixExpression)) {
		node= node.getParent();
	}
	if (node instanceof VariableDeclarationFragment) {
		node= ((VariableDeclarationFragment) node).getInitializer();
	} else if (node instanceof Assignment) {
		node= ((Assignment) node).getRightHandSide();
	}

	InfixExpression oldInfixExpression= null;
	while (node instanceof InfixExpression) {
		InfixExpression curr= (InfixExpression) node;
		if (curr.resolveTypeBinding() == stringBinding && curr.getOperator() == InfixExpression.Operator.PLUS) {
			oldInfixExpression= curr; // is a infix expression we can use
		} else {
			break;
		}
		node= node.getParent();
	}
	if (oldInfixExpression == null)
		return false;

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

	LinkedCorrectionProposal stringBufferProposal= getConvertToStringBufferProposal(context, ast, oldInfixExpression);
	resultingCollections.add(stringBufferProposal);

	ASTRewriteCorrectionProposal messageFormatProposal= getConvertToMessageFormatProposal(context, ast, oldInfixExpression);
	if (messageFormatProposal != null)
		resultingCollections.add(messageFormatProposal);

	return true;
}
 
Example 13
Source File: AbstractSerialVersionOperation.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 positionGroups) throws CoreException {
	final ASTRewrite rewrite= cuRewrite.getASTRewrite();
	VariableDeclarationFragment fragment= null;
	for (int i= 0; i < fNodes.length; i++) {
		final ASTNode node= fNodes[i];

		final AST ast= node.getAST();

		fragment= ast.newVariableDeclarationFragment();
		fragment.setName(ast.newSimpleName(NAME_FIELD));

		final FieldDeclaration declaration= ast.newFieldDeclaration(fragment);
		declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG));
		declaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL));

		if (!addInitializer(fragment, node))
			continue;

		if (fragment.getInitializer() != null) {

			final TextEditGroup editGroup= createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite);
			if (node instanceof AbstractTypeDeclaration)
				rewrite.getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()).insertAt(declaration, 0, editGroup);
			else if (node instanceof AnonymousClassDeclaration)
				rewrite.getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup);
			else if (node instanceof ParameterizedType) {
				final ParameterizedType type= (ParameterizedType) node;
				final ASTNode parent= type.getParent();
				if (parent instanceof ClassInstanceCreation) {
					final ClassInstanceCreation creation= (ClassInstanceCreation) parent;
					final AnonymousClassDeclaration anonymous= creation.getAnonymousClassDeclaration();
					if (anonymous != null)
						rewrite.getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup);
				}
			} else
				Assert.isTrue(false);

			addLinkedPositions(rewrite, fragment, positionGroups);
		}

		final String comment= CodeGeneration.getFieldComment(fUnit, declaration.getType().toString(), NAME_FIELD, StubUtility.getLineDelimiterUsed(fUnit));
		if (comment != null && comment.length() > 0) {
			final Javadoc doc= (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
			declaration.setJavadoc(doc);
		}
	}
	if (fragment == null)
		return;

	positionGroups.setEndPosition(rewrite.track(fragment));
}
 
Example 14
Source File: NewVariableCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private ASTRewrite doAddField(CompilationUnit astRoot) {
	SimpleName node= fOriginalNode;
	boolean isInDifferentCU= false;

	ASTNode newTypeDecl= astRoot.findDeclaringNode(fSenderBinding);
	if (newTypeDecl == null) {
		astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
		isInDifferentCU= true;
	}
	ImportRewrite imports= createImportRewrite(astRoot);
	ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(node), imports);

	if (newTypeDecl != null) {
		AST ast= newTypeDecl.getAST();

		ASTRewrite rewrite= ASTRewrite.create(ast);

		VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
		fragment.setName(ast.newSimpleName(node.getIdentifier()));

		Type type= evaluateVariableType(ast, imports, importRewriteContext, fSenderBinding);

		FieldDeclaration newDecl= ast.newFieldDeclaration(fragment);
		newDecl.setType(type);
		newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl)));

		if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) {
			fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
		}

		ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
		List<BodyDeclaration> decls= ASTNodes.<BodyDeclaration>getChildListProperty(newTypeDecl, property);

		int maxOffset= isInDifferentCU ? -1 : node.getStartPosition();

		int insertIndex= findFieldInsertIndex(decls, newDecl, maxOffset);

		ListRewrite listRewriter= rewrite.getListRewrite(newTypeDecl, property);
		listRewriter.insertAt(newDecl, insertIndex, null);

		ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(getLinkedProposalModel(), rewrite, newDecl.modifiers(), fSenderBinding.isInterface());

		addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
		if (!isInDifferentCU) {
			addLinkedPosition(rewrite.track(node), true, KEY_NAME);
		}
		addLinkedPosition(rewrite.track(fragment.getName()), false, KEY_NAME);

		if (fragment.getInitializer() != null) {
			addLinkedPosition(rewrite.track(fragment.getInitializer()), false, KEY_INITIALIZER);
		}
		return rewrite;
	}
	return null;
}
 
Example 15
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean getAddParenthesesForExpressionProposals(IInvocationContext context, ASTNode coveringNode, Collection<ICommandAccess> resultingCollections) {
	ASTNode node;

	if (context.getSelectionLength() == 0) {
		node= coveringNode;
		while (node != null && !(node instanceof CastExpression) && !(node instanceof InfixExpression) && !(node instanceof InstanceofExpression) && !(node instanceof ConditionalExpression)) {
			node= node.getParent();
		}
	} else {
		node= context.getCoveredNode();
	}

	String label= null;
	if (node instanceof CastExpression) {
		label= CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
	} else if (node instanceof InstanceofExpression) {
		label= CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_instanceof_description;
	} else if (node instanceof InfixExpression) {
		InfixExpression infixExpression= (InfixExpression)node;
		label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_description, infixExpression.getOperator().toString());
	} else if (node instanceof ConditionalExpression) {
		label= CorrectionMessages.AdvancedQuickAssistProcessor_putConditionalExpressionInParentheses;
	} else {
		return false;
	}

	if (node.getParent() instanceof ParenthesizedExpression)
		return false;

	if (resultingCollections == null)
		return true;

	AST ast= node.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);

	ParenthesizedExpression parenthesizedExpression= ast.newParenthesizedExpression();
	parenthesizedExpression.setExpression((Expression)rewrite.createCopyTarget(node));
	rewrite.replace(node, parenthesizedExpression, null);

	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_PARENTHESES_FOR_EXPRESSION, image);
	resultingCollections.add(proposal);
	return true;
}
 
Example 16
Source File: ModifierChangeCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected ASTRewrite getRewrite() throws CoreException {
	CompilationUnit astRoot = ASTResolving.findParentCompilationUnit(fNode);
	ASTNode boundNode = astRoot.findDeclaringNode(fBinding);
	ASTNode declNode = null;

	if (boundNode != null) {
		declNode = boundNode; // is same CU
	} else {
		//setSelectionDescription(selectionDescription);
		CompilationUnit newRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		declNode = newRoot.findDeclaringNode(fBinding.getKey());
	}
	if (declNode != null) {
		AST ast = declNode.getAST();
		ASTRewrite rewrite = ASTRewrite.create(ast);

		if (declNode.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
			VariableDeclarationFragment fragment = (VariableDeclarationFragment) declNode;
			ASTNode parent = declNode.getParent();
			if (parent instanceof FieldDeclaration) {
				FieldDeclaration fieldDecl = (FieldDeclaration) parent;
				if (fieldDecl.fragments().size() > 1 && (fieldDecl.getParent() instanceof AbstractTypeDeclaration)) { // split
					VariableDeclarationRewrite.rewriteModifiers(fieldDecl, new VariableDeclarationFragment[] { fragment }, fIncludedModifiers, fExcludedModifiers, rewrite, null);
					return rewrite;
				}
			} else if (parent instanceof VariableDeclarationStatement) {
				VariableDeclarationStatement varDecl = (VariableDeclarationStatement) parent;
				if (varDecl.fragments().size() > 1 && (varDecl.getParent() instanceof Block)) { // split
					VariableDeclarationRewrite.rewriteModifiers(varDecl, new VariableDeclarationFragment[] { fragment }, fIncludedModifiers, fExcludedModifiers, rewrite, null);
					return rewrite;
				}
			} else if (parent instanceof VariableDeclarationExpression) {
				// can't separate
			}
			declNode = parent;
		} else if (declNode.getNodeType() == ASTNode.METHOD_DECLARATION) {
			MethodDeclaration methodDecl = (MethodDeclaration) declNode;
			if (!methodDecl.isConstructor()) {
				IMethodBinding methodBinding = methodDecl.resolveBinding();
				if (methodDecl.getBody() == null && methodBinding != null && Modifier.isAbstract(methodBinding.getModifiers()) && Modifier.isStatic(fIncludedModifiers)) {
					// add body
					ICompilationUnit unit = getCompilationUnit();
					String delimiter = unit.findRecommendedLineSeparator();
					String bodyStatement = ""; //$NON-NLS-1$

					Block body = ast.newBlock();
					rewrite.set(methodDecl, MethodDeclaration.BODY_PROPERTY, body, null);
					Type returnType = methodDecl.getReturnType2();
					if (returnType != null) {
						Expression expression = ASTNodeFactory.newDefaultExpression(ast, returnType, methodDecl.getExtraDimensions());
						if (expression != null) {
							ReturnStatement returnStatement = ast.newReturnStatement();
							returnStatement.setExpression(expression);
							bodyStatement = ASTNodes.asFormattedString(returnStatement, 0, delimiter, unit.getJavaProject().getOptions(true));
						}
					}
					String placeHolder = CodeGeneration.getMethodBodyContent(unit, methodBinding.getDeclaringClass().getName(), methodBinding.getName(), false, bodyStatement, delimiter);
					if (placeHolder != null) {
						ReturnStatement todoNode = (ReturnStatement) rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
						body.statements().add(todoNode);
					}
				}
			}
		}
		ModifierRewrite listRewrite = ModifierRewrite.create(rewrite, declNode);
		PositionInformation trackedDeclNode = listRewrite.setModifiers(fIncludedModifiers, fExcludedModifiers, null);

		LinkedProposalPositionGroupCore positionGroup = new LinkedProposalPositionGroupCore("group"); //$NON-NLS-1$
		positionGroup.addPosition(trackedDeclNode);
		getLinkedProposalModel().addPositionGroup(positionGroup);

		if (boundNode != null) {
			// only set end position if in same CU
			setEndPosition(rewrite.track(fNode));
		}
		return rewrite;
	}
	return null;
}
 
Example 17
Source File: AbstractMethodCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private MethodDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) throws CoreException {
	ImportRewriteContext context=new ContextSensitiveImportRewriteContext(targetTypeDecl, getImportRewrite());

	AST ast= targetTypeDecl.getAST();
	MethodDeclaration decl= ast.newMethodDeclaration();

	SimpleName newNameNode= getNewName(rewrite);

	decl.setConstructor(isConstructor());

	addNewModifiers(rewrite, targetTypeDecl, decl.modifiers());

	ArrayList<String> takenNames= new ArrayList<>();
	addNewTypeParameters(rewrite, takenNames, decl.typeParameters(), context);

	decl.setName(newNameNode);

	IVariableBinding[] declaredFields= fSenderBinding.getDeclaredFields();
	for (int i= 0; i < declaredFields.length; i++) { // avoid to take parameter names that are equal to field names
		takenNames.add(declaredFields[i].getName());
	}

	String bodyStatement= ""; //$NON-NLS-1$
	boolean isAbstractMethod= Modifier.isAbstract(decl.getModifiers()) || (fSenderBinding.isInterface() && !Modifier.isStatic(decl.getModifiers()) && !Modifier.isDefault(decl.getModifiers()));
	if (!isConstructor()) {
		Type returnType= getNewMethodType(rewrite, context);
		decl.setReturnType2(returnType);

		boolean isVoid= returnType instanceof PrimitiveType && PrimitiveType.VOID.equals(((PrimitiveType)returnType).getPrimitiveTypeCode());
		if (!isAbstractMethod && !isVoid) {
			ReturnStatement returnStatement= ast.newReturnStatement();
			returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
			bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true));
		}
	}

	addNewParameters(rewrite, takenNames, decl.parameters(), context);
	addNewExceptions(rewrite, decl.thrownExceptionTypes(), context);

	Block body= null;
	if (!isAbstractMethod && !Flags.isAbstract(decl.getModifiers())) {
		body= ast.newBlock();
		if (bodyStatement.length() > 0) {
			ReturnStatement todoNode = (ReturnStatement) rewrite.createStringPlaceholder(bodyStatement,
					ASTNode.RETURN_STATEMENT);
			body.statements().add(todoNode);
		}
	}
	decl.setBody(body);

	CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(getCompilationUnit().getResource());
	if (settings.createComments && !fSenderBinding.isAnonymous()) {
		String string = CodeGeneration.getMethodComment(getCompilationUnit(), fSenderBinding.getName(), decl, null,
				String.valueOf('\n'));
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 18
Source File: ModifierRewrite.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private ModifierRewrite(ASTRewrite rewrite, ASTNode declNode) {
	fModifierRewrite = evaluateListRewrite(rewrite, declNode);
	fAst = declNode.getAST();
}
 
Example 19
Source File: ASTRewrite.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void validateIsCorrectAST(ASTNode node) {
	if (node.getAST() != getAST()) {
		throw new IllegalArgumentException("Node is not inside the AST"); //$NON-NLS-1$
	}
}
 
Example 20
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean getPickOutStringProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
	// we work with String's
	if (!(node instanceof StringLiteral)) {
		return false;
	}
	// user should select part of String
	int selectionPos= context.getSelectionOffset();
	int selectionLen= context.getSelectionLength();
	if (selectionLen == 0) {
		return false;
	}
	int valueStart= node.getStartPosition() + 1;
	int valueEnd= node.getStartPosition() + node.getLength() - 1;

	// selection must be inside node and the quotes and not contain the full value
	if (selectionPos < valueStart || selectionPos + selectionLen > valueEnd || valueEnd - valueStart == selectionLen) {
		return false;
	}

	// prepare string parts positions
	StringLiteral stringLiteral= (StringLiteral) node;
	String stringValue= stringLiteral.getEscapedValue();

	int firstPos= selectionPos - node.getStartPosition();
	int secondPos= firstPos + selectionLen;


	// prepare new string literals

	AST ast= node.getAST();
	StringLiteral leftLiteral= ast.newStringLiteral();
	StringLiteral centerLiteral= ast.newStringLiteral();
	StringLiteral rightLiteral= ast.newStringLiteral();
	try {
		leftLiteral.setEscapedValue('"' + stringValue.substring(1, firstPos) + '"');
		centerLiteral.setEscapedValue('"' + stringValue.substring(firstPos, secondPos) + '"');
		rightLiteral.setEscapedValue('"' + stringValue.substring(secondPos, stringValue.length() - 1) + '"');
	} catch (IllegalArgumentException e) {
		return false;
	}
	if (resultingCollections == null) {
		return true;
	}

	ASTRewrite rewrite= ASTRewrite.create(ast);

	// prepare new expression instead of StringLiteral
	InfixExpression expression= ast.newInfixExpression();
	expression.setOperator(InfixExpression.Operator.PLUS);
	if (firstPos != 1) {
		expression.setLeftOperand(leftLiteral);
	}


	if (firstPos == 1) {
		expression.setLeftOperand(centerLiteral);
	} else {
		expression.setRightOperand(centerLiteral);
	}

	if (secondPos < stringValue.length() - 1) {
		if (firstPos == 1) {
			expression.setRightOperand(rightLiteral);
		} else {
			expression.extendedOperands().add(rightLiteral);
		}
	}
	// use new expression instead of old StirngLiteral
	rewrite.replace(stringLiteral, expression, null);
	// add correction proposal
	String label= CorrectionMessages.AdvancedQuickAssistProcessor_pickSelectedString;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.PICK_SELECTED_STRING, image);
	proposal.addLinkedPosition(rewrite.track(centerLiteral), true, "CENTER_STRING"); //$NON-NLS-1$
	resultingCollections.add(proposal);
	return true;
}