use of org.eclipse.jdt.core.dom.ChildListPropertyDescriptor in project eclipse.jdt.ls by eclipse.
the class AddArgumentCorrectionProposal method getRewrite.
@Override
protected ASTRewrite getRewrite() {
AST ast = fCallerNode.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
ChildListPropertyDescriptor property = getProperty();
for (int i = 0; i < fInsertIndexes.length; i++) {
int idx = fInsertIndexes[i];
// $NON-NLS-1$
String key = "newarg_" + i;
Expression newArg = evaluateArgumentExpressions(ast, fParamTypes[idx], key);
ListRewrite listRewriter = rewrite.getListRewrite(fCallerNode, property);
listRewriter.insertAt(newArg, idx, null);
}
return rewrite;
}
use of org.eclipse.jdt.core.dom.ChildListPropertyDescriptor in project eclipse.jdt.ls by eclipse.
the class ExtractMethodRefactoring method createChange.
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
if (fMethodName == null) {
return null;
}
// $NON-NLS-1$
pm.beginTask("", 2);
try {
fAnalyzer.aboutToCreateChange();
BodyDeclaration declaration = fAnalyzer.getEnclosingBodyDeclaration();
fRewriter = ASTRewrite.create(declaration.getAST());
final CompilationUnitChange result = new CompilationUnitChange(RefactoringCoreMessages.ExtractMethodRefactoring_change_name, fCUnit);
result.setSaveMode(TextFileChange.KEEP_SAVE_STATE);
result.setDescriptor(new RefactoringChangeDescriptor(getRefactoringDescriptor()));
MultiTextEdit root = new MultiTextEdit();
result.setEdit(root);
ASTNode[] selectedNodes = fAnalyzer.getSelectedNodes();
fRewriter.setTargetSourceRangeComputer(new SelectionAwareSourceRangeComputer(selectedNodes, fCUnit.getBuffer(), fSelectionStart, fSelectionLength));
TextEditGroup substituteDesc = new TextEditGroup(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_substitute_with_call, BasicElementLabels.getJavaElementName(fMethodName)));
result.addTextEditGroup(substituteDesc);
MethodDeclaration mm = createNewMethod(selectedNodes, fCUnit.findRecommendedLineSeparator(), substituteDesc);
if (fLinkedProposalModel != null) {
LinkedProposalPositionGroup typeGroup = fLinkedProposalModel.getPositionGroup(KEY_TYPE, true);
typeGroup.addPosition(fRewriter.track(mm.getReturnType2()), false);
ITypeBinding typeBinding = fAnalyzer.getReturnTypeBinding();
if (typeBinding != null) {
ITypeBinding[] relaxingTypes = ASTResolving.getNarrowingTypes(fAST, typeBinding);
for (int i = 0; i < relaxingTypes.length; i++) {
typeGroup.addProposal(relaxingTypes[i], fCUnit, relaxingTypes.length - i);
}
}
LinkedProposalPositionGroup nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
nameGroup.addPosition(fRewriter.track(mm.getName()), false);
ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(fLinkedProposalModel, fRewriter, mm.modifiers(), false);
}
TextEditGroup insertDesc = new TextEditGroup(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_add_method, BasicElementLabels.getJavaElementName(fMethodName)));
result.addTextEditGroup(insertDesc);
if (fDestination == ASTResolving.findParentType(declaration.getParent())) {
ChildListPropertyDescriptor desc = (ChildListPropertyDescriptor) declaration.getLocationInParent();
ListRewrite container = fRewriter.getListRewrite(declaration.getParent(), desc);
container.insertAfter(mm, declaration, insertDesc);
} else {
BodyDeclarationRewrite container = BodyDeclarationRewrite.create(fRewriter, fDestination);
container.insert(mm, insertDesc);
}
replaceDuplicates(result, mm.getModifiers());
replaceBranches(result);
if (fImportRewriter.hasRecordedChanges()) {
TextEdit edit = fImportRewriter.rewriteImports(null);
root.addChild(edit);
result.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.ExtractMethodRefactoring_organize_imports, new TextEdit[] { edit }));
}
root.addChild(fRewriter.rewriteAST());
return result;
} finally {
pm.done();
}
}
use of org.eclipse.jdt.core.dom.ChildListPropertyDescriptor in project flux by eclipse.
the class QuickAssistProcessor method getConvertToStringBufferProposal.
private static LinkedCorrectionProposal getConvertToStringBufferProposal(IInvocationContext context, AST ast, InfixExpression oldInfixExpression) {
String bufferOrBuilderName;
ICompilationUnit cu = context.getCompilationUnit();
if (JavaModelUtil.is50OrHigher(cu.getJavaProject())) {
// $NON-NLS-1$
bufferOrBuilderName = "StringBuilder";
} else {
// $NON-NLS-1$
bufferOrBuilderName = "StringBuffer";
}
ASTRewrite rewrite = ASTRewrite.create(ast);
SimpleName existingBuffer = getEnclosingAppendBuffer(oldInfixExpression);
String mechanismName = BasicElementLabels.getJavaElementName(existingBuffer == null ? bufferOrBuilderName : existingBuffer.getIdentifier());
String label = Messages.format(CorrectionMessages.QuickAssistProcessor_convert_to_string_buffer_description, mechanismName);
// Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.CONVERT_TO_STRING_BUFFER);
proposal.setCommandId(CONVERT_TO_STRING_BUFFER_ID);
Statement insertAfter;
String bufferName;
// $NON-NLS-1$
String groupID = "nameId";
ListRewrite listRewrite;
Statement enclosingStatement = ASTResolving.findParentStatement(oldInfixExpression);
if (existingBuffer != null) {
if (ASTNodes.isControlStatementBody(enclosingStatement.getLocationInParent())) {
Block newBlock = ast.newBlock();
listRewrite = rewrite.getListRewrite(newBlock, Block.STATEMENTS_PROPERTY);
insertAfter = null;
rewrite.replace(enclosingStatement, newBlock, null);
} else {
listRewrite = rewrite.getListRewrite(enclosingStatement.getParent(), (ChildListPropertyDescriptor) enclosingStatement.getLocationInParent());
insertAfter = enclosingStatement;
}
bufferName = existingBuffer.getIdentifier();
} else {
// create buffer
VariableDeclarationFragment frag = ast.newVariableDeclarationFragment();
// check if name is already in use and provide alternative
List<String> fExcludedVariableNames = Arrays.asList(ASTResolving.getUsedVariableNames(oldInfixExpression));
SimpleType bufferType = ast.newSimpleType(ast.newName(bufferOrBuilderName));
ClassInstanceCreation newBufferExpression = ast.newClassInstanceCreation();
// StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, cu.getJavaProject(), bufferOrBuilderName, 0, fExcludedVariableNames, true);
String[] newBufferNames = new String[] {};
bufferName = newBufferNames[0];
SimpleName bufferNameDeclaration = ast.newSimpleName(bufferName);
frag.setName(bufferNameDeclaration);
proposal.addLinkedPosition(rewrite.track(bufferNameDeclaration), true, groupID);
for (int i = 0; i < newBufferNames.length; i++) {
proposal.addLinkedPositionProposal(groupID, newBufferNames[i], null);
}
newBufferExpression.setType(bufferType);
frag.setInitializer(newBufferExpression);
VariableDeclarationStatement bufferDeclaration = ast.newVariableDeclarationStatement(frag);
bufferDeclaration.setType(ast.newSimpleType(ast.newName(bufferOrBuilderName)));
insertAfter = bufferDeclaration;
Statement statement = ASTResolving.findParentStatement(oldInfixExpression);
if (ASTNodes.isControlStatementBody(statement.getLocationInParent())) {
Block newBlock = ast.newBlock();
listRewrite = rewrite.getListRewrite(newBlock, Block.STATEMENTS_PROPERTY);
listRewrite.insertFirst(bufferDeclaration, null);
listRewrite.insertLast(rewrite.createMoveTarget(statement), null);
rewrite.replace(statement, newBlock, null);
} else {
listRewrite = rewrite.getListRewrite(statement.getParent(), (ChildListPropertyDescriptor) statement.getLocationInParent());
listRewrite.insertBefore(bufferDeclaration, statement, null);
}
}
List<Expression> operands = new ArrayList<Expression>();
collectInfixPlusOperands(oldInfixExpression, operands);
Statement lastAppend = insertAfter;
for (Iterator<Expression> iter = operands.iterator(); iter.hasNext(); ) {
Expression operand = iter.next();
MethodInvocation appendIncovationExpression = ast.newMethodInvocation();
// $NON-NLS-1$
appendIncovationExpression.setName(ast.newSimpleName("append"));
SimpleName bufferNameReference = ast.newSimpleName(bufferName);
// If there was an existing name, don't offer to rename it
if (existingBuffer == null) {
proposal.addLinkedPosition(rewrite.track(bufferNameReference), true, groupID);
}
appendIncovationExpression.setExpression(bufferNameReference);
appendIncovationExpression.arguments().add(rewrite.createCopyTarget(operand));
ExpressionStatement appendExpressionStatement = ast.newExpressionStatement(appendIncovationExpression);
if (lastAppend == null) {
listRewrite.insertFirst(appendExpressionStatement, null);
} else {
listRewrite.insertAfter(appendExpressionStatement, lastAppend, null);
}
lastAppend = appendExpressionStatement;
}
if (existingBuffer != null) {
proposal.setEndPosition(rewrite.track(lastAppend));
if (insertAfter != null) {
rewrite.remove(enclosingStatement, null);
}
} else {
// replace old expression with toString
MethodInvocation bufferToString = ast.newMethodInvocation();
// $NON-NLS-1$
bufferToString.setName(ast.newSimpleName("toString"));
SimpleName bufferNameReference = ast.newSimpleName(bufferName);
bufferToString.setExpression(bufferNameReference);
proposal.addLinkedPosition(rewrite.track(bufferNameReference), true, groupID);
rewrite.replace(oldInfixExpression, bufferToString, null);
proposal.setEndPosition(rewrite.track(bufferToString));
}
return proposal;
}
use of org.eclipse.jdt.core.dom.ChildListPropertyDescriptor in project flux by eclipse.
the class AdvancedQuickAssistProcessor method getJoinOrIfStatementsProposals.
private static boolean getJoinOrIfStatementsProposals(IInvocationContext context, ASTNode covering, ArrayList<ASTNode> coveredNodes, Collection<ICommandAccess> resultingCollections) {
Operator orOperator = InfixExpression.Operator.CONDITIONAL_OR;
if (coveredNodes.size() < 2)
return false;
// check that all covered nodes are IfStatement's with same 'then' statement and without 'else'
String commonThenSource = null;
for (Iterator<ASTNode> iter = coveredNodes.iterator(); iter.hasNext(); ) {
ASTNode node = iter.next();
if (!(node instanceof IfStatement))
return false;
//
IfStatement ifStatement = (IfStatement) node;
if (ifStatement.getElseStatement() != null)
return false;
//
Statement thenStatement = ifStatement.getThenStatement();
try {
String thenSource = context.getCompilationUnit().getBuffer().getText(thenStatement.getStartPosition(), thenStatement.getLength());
if (commonThenSource == null) {
commonThenSource = thenSource;
} else {
if (!commonThenSource.equals(thenSource))
return false;
}
} catch (Throwable e) {
return false;
}
}
if (resultingCollections == null) {
return true;
}
//
final AST ast = covering.getAST();
final ASTRewrite rewrite = ASTRewrite.create(ast);
// prepare OR'ed condition
InfixExpression condition = null;
boolean hasRightOperand = false;
Statement thenStatement = null;
for (Iterator<ASTNode> iter = coveredNodes.iterator(); iter.hasNext(); ) {
IfStatement ifStatement = (IfStatement) iter.next();
if (thenStatement == null)
thenStatement = (Statement) rewrite.createCopyTarget(ifStatement.getThenStatement());
if (condition == null) {
condition = ast.newInfixExpression();
condition.setOperator(orOperator);
condition.setLeftOperand(getParenthesizedExpressionIfNeeded(ast, rewrite, ifStatement.getExpression(), condition, InfixExpression.LEFT_OPERAND_PROPERTY));
} else if (!hasRightOperand) {
condition.setRightOperand(getParenthesizedExpressionIfNeeded(ast, rewrite, ifStatement.getExpression(), condition, InfixExpression.RIGHT_OPERAND_PROPERTY));
hasRightOperand = true;
} else {
InfixExpression newCondition = ast.newInfixExpression();
newCondition.setOperator(orOperator);
newCondition.setLeftOperand(condition);
newCondition.setRightOperand(getParenthesizedExpressionIfNeeded(ast, rewrite, ifStatement.getExpression(), condition, InfixExpression.RIGHT_OPERAND_PROPERTY));
condition = newCondition;
}
}
// prepare new IfStatement with OR'ed condition
IfStatement newIf = ast.newIfStatement();
newIf.setExpression(condition);
newIf.setThenStatement(thenStatement);
//
ListRewrite listRewriter = null;
for (Iterator<ASTNode> iter = coveredNodes.iterator(); iter.hasNext(); ) {
IfStatement ifStatement = (IfStatement) iter.next();
if (listRewriter == null) {
Block sourceBlock = (Block) ifStatement.getParent();
// int insertIndex = sourceBlock.statements().indexOf(ifStatement);
listRewriter = rewrite.getListRewrite(sourceBlock, (ChildListPropertyDescriptor) ifStatement.getLocationInParent());
}
if (newIf != null) {
listRewriter.replace(ifStatement, newIf, null);
newIf = null;
} else {
listRewriter.remove(ifStatement, null);
}
}
// add correction proposal
String label = CorrectionMessages.AdvancedQuickAssistProcessor_joinWithOr_description;
// Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.JOIN_IF_STATEMENTS_WITH_OR);
resultingCollections.add(proposal);
return true;
}
use of org.eclipse.jdt.core.dom.ChildListPropertyDescriptor in project che by eclipse.
the class OverrideCompletionProposal method updateReplacementString.
/*
* @see JavaTypeCompletionProposal#updateReplacementString(IDocument,char,int,ImportRewrite)
*/
@Override
protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite importRewrite) throws CoreException, BadLocationException {
Document recoveredDocument = new Document();
CompilationUnit unit = getRecoveredAST(document, offset, recoveredDocument);
ImportRewriteContext context;
if (importRewrite != null) {
context = new ContextSensitiveImportRewriteContext(unit, offset, importRewrite);
} else {
// create a dummy import rewriter to have one
importRewrite = StubUtility.createImportRewrite(unit, true);
context = new // forces that all imports are fully qualified
ImportRewriteContext() {
@Override
public int findInContext(String qualifier, String name, int kind) {
return RES_NAME_CONFLICT;
}
};
}
ITypeBinding declaringType = null;
ChildListPropertyDescriptor descriptor = null;
ASTNode node = NodeFinder.perform(unit, offset, 1);
if (node instanceof AnonymousClassDeclaration) {
declaringType = ((AnonymousClassDeclaration) node).resolveBinding();
descriptor = AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
} else if (node instanceof AbstractTypeDeclaration) {
AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) node;
descriptor = declaration.getBodyDeclarationsProperty();
declaringType = declaration.resolveBinding();
}
if (declaringType != null) {
ASTRewrite rewrite = ASTRewrite.create(unit.getAST());
IMethodBinding methodToOverride = Bindings.findMethodInHierarchy(declaringType, fMethodName, fParamTypes);
if (methodToOverride == null && declaringType.isInterface()) {
//$NON-NLS-1$
methodToOverride = Bindings.findMethodInType(node.getAST().resolveWellKnownType("java.lang.Object"), fMethodName, fParamTypes);
}
if (methodToOverride != null) {
CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fJavaProject);
MethodDeclaration stub = StubUtility2.createImplementationStub(fCompilationUnit, rewrite, importRewrite, context, methodToOverride, declaringType.getName(), settings, declaringType.isInterface());
ListRewrite rewriter = rewrite.getListRewrite(node, descriptor);
rewriter.insertFirst(stub, null);
ITrackedNodePosition position = rewrite.track(stub);
try {
rewrite.rewriteAST(recoveredDocument, fJavaProject.getOptions(true)).apply(recoveredDocument);
String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());
int generatedIndent = IndentManipulation.measureIndentUnits(getIndentAt(recoveredDocument, position.getStartPosition(), settings), settings.tabWidth, settings.indentWidth);
String indent = getIndentAt(document, getReplacementOffset(), settings);
setReplacementString(IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth, settings.indentWidth, indent, TextUtilities.getDefaultLineDelimiter(document)));
} catch (MalformedTreeException exception) {
JavaPlugin.log(exception);
} catch (BadLocationException exception) {
JavaPlugin.log(exception);
}
}
}
return true;
}
Aggregations