Java Code Examples for org.eclipse.jdt.core.dom.AST#newVariableDeclarationFragment()
The following examples show how to use
org.eclipse.jdt.core.dom.AST#newVariableDeclarationFragment() .
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: PromoteTempToFieldRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private FieldDeclaration createNewFieldDeclaration(ASTRewrite rewrite) { AST ast= getAST(); VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment(); SimpleName variableName= ast.newSimpleName(fFieldName); fragment.setName(variableName); addLinkedName(rewrite, variableName, false); List<Dimension> extraDimensions= DimensionRewrite.copyDimensions(fTempDeclarationNode.extraDimensions(), rewrite); fragment.extraDimensions().addAll(extraDimensions); if (fInitializeIn == INITIALIZE_IN_FIELD && tempHasInitializer()){ Expression initializer= (Expression)rewrite.createCopyTarget(getTempInitializer()); fragment.setInitializer(initializer); } FieldDeclaration fieldDeclaration= ast.newFieldDeclaration(fragment); VariableDeclarationStatement vds= getTempDeclarationStatement(); Type type= (Type)rewrite.createCopyTarget(vds.getType()); fieldDeclaration.setType(type); fieldDeclaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getModifiers())); return fieldDeclaration; }
Example 2
Source File: ConvertAnonymousToNestedRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private void createFieldsForAccessedLocals(CompilationUnitRewrite rewrite, IVariableBinding[] varBindings, String[] fieldNames, List<BodyDeclaration> newBodyDeclarations) throws CoreException { final ImportRewrite importRewrite= rewrite.getImportRewrite(); final ASTRewrite astRewrite= rewrite.getASTRewrite(); final AST ast= astRewrite.getAST(); for (int i= 0; i < varBindings.length; i++) { VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment(); fragment.setInitializer(null); fragment.setName(ast.newSimpleName(fieldNames[i])); FieldDeclaration field= ast.newFieldDeclaration(fragment); ITypeBinding varType= varBindings[i].getType(); field.setType(importRewrite.addImport(varType, ast)); field.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.FINAL)); if (doAddComments()) { String string= CodeGeneration.getFieldComment(rewrite.getCu(), varType.getName(), fieldNames[i], StubUtility.getLineDelimiterUsed(fCu)); if (string != null) { Javadoc javadoc= (Javadoc) astRewrite.createStringPlaceholder(string, ASTNode.JAVADOC); field.setJavadoc(javadoc); } } newBodyDeclarations.add(field); addLinkedPosition(KEY_FIELD_NAME_EXT + i, fragment.getName(), astRewrite, false); } }
Example 3
Source File: GenerateForLoopAssistProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * Generates the Assignment in an iterator based for, used in the first statement of an iterator * based <code>for</code> loop body, to retrieve the next element of the {@link Iterable} * instance. * * @param rewrite the current instance of {@link ASTRewrite} * @param loopOverType the {@link ITypeBinding} of the loop variable * @param loopVariableName the name of the loop variable * @return an {@link Assignment}, which retrieves the next element of the {@link Iterable} using * the active {@link Iterator} */ private Assignment getIteratorBasedForBodyAssignment(ASTRewrite rewrite, ITypeBinding loopOverType, SimpleName loopVariableName) { AST ast= rewrite.getAST(); Assignment assignResolvedVariable= ast.newAssignment(); // left hand side SimpleName resolvedVariableName= resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), loopVariableName.getIdentifier(), false); VariableDeclarationFragment resolvedVariableDeclarationFragment= ast.newVariableDeclarationFragment(); resolvedVariableDeclarationFragment.setName(resolvedVariableName); VariableDeclarationExpression resolvedVariableDeclaration= ast.newVariableDeclarationExpression(resolvedVariableDeclarationFragment); resolvedVariableDeclaration.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite()))); assignResolvedVariable.setLeftHandSide(resolvedVariableDeclaration); // right hand side MethodInvocation invokeIteratorNextExpression= ast.newMethodInvocation(); invokeIteratorNextExpression.setName(ast.newSimpleName("next")); //$NON-NLS-1$ SimpleName currentElementName= ast.newSimpleName(loopVariableName.getIdentifier()); addLinkedPosition(rewrite.track(currentElementName), LinkedPositionGroup.NO_STOP, currentElementName.getIdentifier()); invokeIteratorNextExpression.setExpression(currentElementName); assignResolvedVariable.setRightHandSide(invokeIteratorNextExpression); assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN); return assignResolvedVariable; }
Example 4
Source File: ParameterObjectFactory.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private FieldDeclaration createField(ParameterInfo pi, CompilationUnitRewrite cuRewrite) throws CoreException { AST ast= cuRewrite.getAST(); ICompilationUnit unit= cuRewrite.getCu(); VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment(); String lineDelim= StubUtility.getLineDelimiterUsed(unit); SimpleName fieldName= ast.newSimpleName(pi.getNewName()); fragment.setName(fieldName); FieldDeclaration declaration= ast.newFieldDeclaration(fragment); if (createComments(unit.getJavaProject())) { String comment= StubUtility.getFieldComment(unit, pi.getNewTypeName(), pi.getNewName(), lineDelim); if (comment != null) { Javadoc doc= (Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC); declaration.setJavadoc(doc); } } List<Modifier> modifiers= new ArrayList<Modifier>(); if (fCreateGetter) { modifiers.add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD)); } else { modifiers.add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD)); } declaration.modifiers().addAll(modifiers); declaration.setType(importBinding(pi.getNewTypeBinding(), cuRewrite)); return declaration; }
Example 5
Source File: MoveInnerToTopRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private void addEnclosingInstanceDeclaration(final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) throws CoreException { Assert.isNotNull(declaration); Assert.isNotNull(rewrite); final AST ast= declaration.getAST(); final VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(fEnclosingInstanceFieldName)); final FieldDeclaration newField= ast.newFieldDeclaration(fragment); newField.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getEnclosingInstanceAccessModifiers())); newField.setType(createEnclosingType(ast)); final String comment= CodeGeneration.getFieldComment(fType.getCompilationUnit(), declaration.getName().getIdentifier(), fEnclosingInstanceFieldName, StubUtility.getLineDelimiterUsed(fType.getJavaProject())); if (comment != null && comment.length() > 0) { final Javadoc doc= (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); newField.setJavadoc(doc); } rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertFirst(newField, null); }
Example 6
Source File: GenerateForLoopAssistProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * Generates the initializer for an iterator based <code>for</code> loop, which declares and * initializes the variable to loop over. * * @param rewrite the instance of {@link ASTRewrite} * @param loopVariableName the proposed name of the loop variable * @return a {@link VariableDeclarationExpression} to use as initializer */ private VariableDeclarationExpression getIteratorBasedForInitializer(ASTRewrite rewrite, SimpleName loopVariableName) { AST ast= rewrite.getAST(); IMethodBinding iteratorMethodBinding= Bindings.findMethodInHierarchy(fExpressionType, "iterator", new ITypeBinding[] {}); //$NON-NLS-1$ // initializing fragment VariableDeclarationFragment varDeclarationFragment= ast.newVariableDeclarationFragment(); varDeclarationFragment.setName(loopVariableName); MethodInvocation iteratorExpression= ast.newMethodInvocation(); iteratorExpression.setName(ast.newSimpleName(iteratorMethodBinding.getName())); iteratorExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression)); varDeclarationFragment.setInitializer(iteratorExpression); // declaration VariableDeclarationExpression varDeclarationExpression= ast.newVariableDeclarationExpression(varDeclarationFragment); varDeclarationExpression.setType(getImportRewrite().addImport(iteratorMethodBinding.getReturnType(), ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite()))); return varDeclarationExpression; }
Example 7
Source File: GenerateForLoopAssistProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Creates an {@link Assignment} as first expression appearing in a <code>for</code> loop's * body. This Assignment declares a local variable and initializes it using the array's current * element identified by the loop index. * * @param rewrite the current {@link ASTRewrite} instance * @param loopVariableName the name of the index variable in String representation * @return a completed {@link Assignment} containing the mentioned declaration and * initialization */ private Assignment getForBodyAssignment(ASTRewrite rewrite, SimpleName loopVariableName) { AST ast= rewrite.getAST(); ITypeBinding loopOverType= extractElementType(ast); Assignment assignResolvedVariable= ast.newAssignment(); // left hand side SimpleName resolvedVariableName= resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), loopVariableName.getIdentifier(), false); VariableDeclarationFragment resolvedVariableDeclarationFragment= ast.newVariableDeclarationFragment(); resolvedVariableDeclarationFragment.setName(resolvedVariableName); VariableDeclarationExpression resolvedVariableDeclaration= ast.newVariableDeclarationExpression(resolvedVariableDeclarationFragment); resolvedVariableDeclaration.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite()))); assignResolvedVariable.setLeftHandSide(resolvedVariableDeclaration); // right hand side ArrayAccess access= ast.newArrayAccess(); access.setArray((Expression) rewrite.createCopyTarget(fCurrentExpression)); SimpleName indexName= ast.newSimpleName(loopVariableName.getIdentifier()); addLinkedPosition(rewrite.track(indexName), LinkedPositionGroup.NO_STOP, indexName.getIdentifier()); access.setIndex(indexName); assignResolvedVariable.setRightHandSide(access); assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN); return assignResolvedVariable; }
Example 8
Source File: GenerateForLoopAssistProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Creates an {@link Assignment} as first expression appearing in an index based * <code>for</code> loop's body. This Assignment declares a local variable and initializes it * using the {@link List}'s current element identified by the loop index. * * @param rewrite the current {@link ASTRewrite} instance * @param loopVariableName the name of the index variable in String representation * @return a completed {@link Assignment} containing the mentioned declaration and * initialization */ private Expression getIndexBasedForBodyAssignment(ASTRewrite rewrite, SimpleName loopVariableName) { AST ast= rewrite.getAST(); ITypeBinding loopOverType= extractElementType(ast); Assignment assignResolvedVariable= ast.newAssignment(); // left hand side SimpleName resolvedVariableName= resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), loopVariableName.getIdentifier(), false); VariableDeclarationFragment resolvedVariableDeclarationFragment= ast.newVariableDeclarationFragment(); resolvedVariableDeclarationFragment.setName(resolvedVariableName); VariableDeclarationExpression resolvedVariableDeclaration= ast.newVariableDeclarationExpression(resolvedVariableDeclarationFragment); resolvedVariableDeclaration.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite()))); assignResolvedVariable.setLeftHandSide(resolvedVariableDeclaration); // right hand side MethodInvocation invokeGetExpression= ast.newMethodInvocation(); invokeGetExpression.setName(ast.newSimpleName("get")); //$NON-NLS-1$ SimpleName indexVariableName= ast.newSimpleName(loopVariableName.getIdentifier()); addLinkedPosition(rewrite.track(indexVariableName), LinkedPositionGroup.NO_STOP, indexVariableName.getIdentifier()); invokeGetExpression.arguments().add(indexVariableName); invokeGetExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression)); assignResolvedVariable.setRightHandSide(invokeGetExpression); assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN); return assignResolvedVariable; }
Example 9
Source File: JavaStatementPostfixContext.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private VariableDeclarationFragment addFieldDeclaration(ASTRewrite rewrite, org.eclipse.jdt.core.dom.ASTNode newTypeDecl, int modifiers, String varName, String qualifiedName, String value) { ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl); List<BodyDeclaration> decls = ASTNodes.getBodyDeclarations(newTypeDecl); AST ast = newTypeDecl.getAST(); VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment(); newDeclFrag.setName(ast.newSimpleName(varName)); Type type = createType(Signature.createTypeSignature(qualifiedName, true), ast); if (value != null && value.trim().length() > 0) { Expression e = createExpression(value); Expression ne = (Expression) org.eclipse.jdt.core.dom.ASTNode.copySubtree(ast, e); newDeclFrag.setInitializer(ne); } else { if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0)); } } FieldDeclaration newDecl = ast.newFieldDeclaration(newDeclFrag); newDecl.setType(type); newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers)); int insertIndex = findFieldInsertIndex(decls, getCompletionOffset(), modifiers); rewrite.getListRewrite(newTypeDecl, property).insertAt(newDecl, insertIndex, null); return newDeclFrag; }
Example 10
Source File: AssignToVariableAssistProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private VariableDeclarationFragment addFieldDeclaration(ASTRewrite rewrite, ASTNode newTypeDecl, int modifiers, Expression expression, ASTNode nodeToAssign, ITypeBinding typeBinding, int index) { if (fExistingFragment != null) { return fExistingFragment; } ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl); List<BodyDeclaration> decls= ASTNodes.getBodyDeclarations(newTypeDecl); AST ast= newTypeDecl.getAST(); String[] varNames= suggestFieldNames(typeBinding, expression, modifiers, nodeToAssign); for (int i= 0; i < varNames.length; i++) { addLinkedPositionProposal(KEY_NAME + index, varNames[i]); } String varName= varNames[0]; VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment(); newDeclFrag.setName(ast.newSimpleName(varName)); FieldDeclaration newDecl= ast.newFieldDeclaration(newDeclFrag); Type type= evaluateType(ast, nodeToAssign, typeBinding, KEY_TYPE + index, TypeLocation.FIELD); newDecl.setType(type); newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers)); ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(getLinkedProposalModel(), rewrite, newDecl.modifiers(), false, ModifierCorrectionSubProcessor.KEY_MODIFIER + index); int insertIndex= findFieldInsertIndex(decls, nodeToAssign.getStartPosition()) + index; rewrite.getListRewrite(newTypeDecl, property).insertAt(newDecl, insertIndex, null); return newDeclFrag; }
Example 11
Source File: AssignToVariableAssistProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private VariableDeclarationFragment addFieldDeclaration(ASTRewrite rewrite, ASTNode newTypeDecl, int modifiers, Expression expression) { if (fExistingFragment != null) { return fExistingFragment; } ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl); List<BodyDeclaration> decls= ASTNodes.getBodyDeclarations(newTypeDecl); AST ast= newTypeDecl.getAST(); String[] varNames= suggestFieldNames(fTypeBinding, expression, modifiers); for (int i= 0; i < varNames.length; i++) { addLinkedPositionProposal(KEY_NAME, varNames[i], null); } String varName= varNames[0]; VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment(); newDeclFrag.setName(ast.newSimpleName(varName)); FieldDeclaration newDecl= ast.newFieldDeclaration(newDeclFrag); Type type= evaluateType(ast); newDecl.setType(type); newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers)); ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(getLinkedProposalModel(), rewrite, newDecl.modifiers(), false); int insertIndex= findFieldInsertIndex(decls, fNodeToAssign.getStartPosition()); rewrite.getListRewrite(newTypeDecl, property).insertAt(newDecl, insertIndex, null); return newDeclFrag; }
Example 12
Source File: JavaASTFlattener.java From xtext-xtend with Eclipse Public License 2.0 | 4 votes |
@Override public boolean visit(final PostfixExpression node) { final AST dummyAST = AST.newAST(node.getAST().apiLevel()); final PostfixExpression.Operator pfOperator = node.getOperator(); Expression _operand = node.getOperand(); if ((_operand instanceof ArrayAccess)) { Expression _operand_1 = node.getOperand(); final ArrayAccess pfOperand = ((ArrayAccess) _operand_1); if ((Objects.equal(pfOperator, PostfixExpression.Operator.INCREMENT) || Objects.equal(pfOperator, PostfixExpression.Operator.DECREMENT))) { final String arrayName = this.computeArrayName(pfOperand); StringConcatenation _builder = new StringConcatenation(); _builder.append("_postIndx_"); _builder.append(arrayName); final String idxName = _builder.toString(); StringConcatenation _builder_1 = new StringConcatenation(); _builder_1.append("_postVal_"); _builder_1.append(arrayName); final String tempVarName = _builder_1.toString(); StringConcatenation _builder_2 = new StringConcatenation(); _builder_2.append("{ var "); _builder_2.append(idxName); _builder_2.append("="); this.appendToBuffer(_builder_2.toString()); pfOperand.getIndex().accept(this); StringConcatenation _builder_3 = new StringConcatenation(); _builder_3.append(" "); _builder_3.append("var "); this.appendToBuffer(_builder_3.toString()); final VariableDeclarationFragment varDeclaration = dummyAST.newVariableDeclarationFragment(); varDeclaration.setName(dummyAST.newSimpleName(tempVarName)); ASTNode _copySubtree = ASTNode.copySubtree(dummyAST, pfOperand); final ArrayAccess arrayAccess = ((ArrayAccess) _copySubtree); arrayAccess.setIndex(dummyAST.newSimpleName(idxName)); varDeclaration.setInitializer(arrayAccess); varDeclaration.accept(this); final InfixExpression infixOp = dummyAST.newInfixExpression(); infixOp.setLeftOperand(dummyAST.newSimpleName(tempVarName)); PostfixExpression.Operator _operator = node.getOperator(); boolean _equals = Objects.equal(_operator, PostfixExpression.Operator.DECREMENT); if (_equals) { infixOp.setOperator(InfixExpression.Operator.MINUS); } else { infixOp.setOperator(InfixExpression.Operator.PLUS); } infixOp.setRightOperand(dummyAST.newNumberLiteral("1")); final Assignment assigment = dummyAST.newAssignment(); ASTNode _copySubtree_1 = ASTNode.copySubtree(dummyAST, pfOperand); final ArrayAccess writeArray = ((ArrayAccess) _copySubtree_1); writeArray.setIndex(dummyAST.newSimpleName(idxName)); assigment.setLeftHandSide(writeArray); ASTNode _copySubtree_2 = ASTNode.copySubtree(dummyAST, infixOp); assigment.setRightHandSide(((Expression) _copySubtree_2)); assigment.accept(this); StringConcatenation _builder_4 = new StringConcatenation(); String _xifexpression = null; boolean _needsReturnValue = this._aSTFlattenerUtils.needsReturnValue(node); if (_needsReturnValue) { _xifexpression = tempVarName; } _builder_4.append(_xifexpression); _builder_4.append(" }"); this.appendToBuffer(_builder_4.toString()); return false; } } node.getOperand().accept(this); this.appendToBuffer(pfOperator.toString()); return false; }
Example 13
Source File: ExtractClassRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private FieldDeclaration createParameterObjectField(ParameterObjectFactory pof, TypeDeclaration typeNode, int modifier) { AST ast= fBaseCURewrite.getAST(); ClassInstanceCreation creation= ast.newClassInstanceCreation(); creation.setType(pof.createType(fDescriptor.isCreateTopLevel(), fBaseCURewrite, typeNode.getStartPosition())); ListRewrite listRewrite= fBaseCURewrite.getASTRewrite().getListRewrite(creation, ClassInstanceCreation.ARGUMENTS_PROPERTY); for (Iterator<FieldInfo> iter= fVariables.values().iterator(); iter.hasNext();) { FieldInfo fi= iter.next(); if (isCreateField(fi)) { Expression expression= fi.initializer; if (expression != null && !fi.hasFieldReference()) { importNodeTypes(expression, fBaseCURewrite); ASTNode createMoveTarget= fBaseCURewrite.getASTRewrite().createMoveTarget(expression); if (expression instanceof ArrayInitializer) { ArrayInitializer ai= (ArrayInitializer) expression; ITypeBinding type= ai.resolveTypeBinding(); Type addImport= fBaseCURewrite.getImportRewrite().addImport(type, ast); fBaseCURewrite.getImportRemover().registerAddedImports(addImport); ArrayCreation arrayCreation= ast.newArrayCreation(); arrayCreation.setType((ArrayType) addImport); arrayCreation.setInitializer((ArrayInitializer) createMoveTarget); listRewrite.insertLast(arrayCreation, null); } else { listRewrite.insertLast(createMoveTarget, null); } } } } VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(fDescriptor.getFieldName())); fragment.setInitializer(creation); ModifierKeyword acc= null; if (Modifier.isPublic(modifier)) { acc= ModifierKeyword.PUBLIC_KEYWORD; } else if (Modifier.isProtected(modifier)) { acc= ModifierKeyword.PROTECTED_KEYWORD; } else if (Modifier.isPrivate(modifier)) { acc= ModifierKeyword.PRIVATE_KEYWORD; } FieldDeclaration fieldDeclaration= ast.newFieldDeclaration(fragment); fieldDeclaration.setType(pof.createType(fDescriptor.isCreateTopLevel(), fBaseCURewrite, typeNode.getStartPosition())); if (acc != null) fieldDeclaration.modifiers().add(ast.newModifier(acc)); return fieldDeclaration; }
Example 14
Source File: AssignToVariableAssistProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
private ASTRewrite doAddLocal() { ASTNode nodeToAssign= fNodesToAssign.get(0); Expression expression= ((ExpressionStatement) nodeToAssign).getExpression(); AST ast= nodeToAssign.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); createImportRewrite((CompilationUnit) nodeToAssign.getRoot()); String[] varNames= suggestLocalVariableNames(fTypeBinding, expression); for (int i= 0; i < varNames.length; i++) { addLinkedPositionProposal(KEY_NAME, varNames[i]); } VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment(); newDeclFrag.setName(ast.newSimpleName(varNames[0])); newDeclFrag.setInitializer((Expression) rewrite.createCopyTarget(expression)); Type type= evaluateType(ast, nodeToAssign, fTypeBinding, KEY_TYPE, TypeLocation.LOCAL_VARIABLE); if (ASTNodes.isControlStatementBody(nodeToAssign.getLocationInParent())) { Block block= ast.newBlock(); block.statements().add(rewrite.createMoveTarget(nodeToAssign)); rewrite.replace(nodeToAssign, block, null); } if (needsSemicolon(expression)) { VariableDeclarationStatement varStatement= ast.newVariableDeclarationStatement(newDeclFrag); varStatement.setType(type); rewrite.replace(expression, varStatement, null); } else { // trick for bug 43248: use an VariableDeclarationExpression and keep the ExpressionStatement VariableDeclarationExpression varExpression= ast.newVariableDeclarationExpression(newDeclFrag); varExpression.setType(type); rewrite.replace(expression, varExpression, null); } addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME); addLinkedPosition(rewrite.track(type), false, KEY_TYPE); setEndPosition(rewrite.track(nodeToAssign)); // set cursor after expression statement return rewrite; }
Example 15
Source File: NewVariableCorrectionProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
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, TypeLocation.FIELD); 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); return rewrite; } return null; }
Example 16
Source File: NewVariableCorrectionProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
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 17
Source File: AssignToVariableAssistProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private ASTRewrite doAddLocal() { Expression expression= ((ExpressionStatement) fNodeToAssign).getExpression(); AST ast= fNodeToAssign.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); createImportRewrite((CompilationUnit) fNodeToAssign.getRoot()); String[] varNames= suggestLocalVariableNames(fTypeBinding, expression); for (int i= 0; i < varNames.length; i++) { addLinkedPositionProposal(KEY_NAME, varNames[i], null); } VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment(); newDeclFrag.setName(ast.newSimpleName(varNames[0])); newDeclFrag.setInitializer((Expression) rewrite.createCopyTarget(expression)); Type type= evaluateType(ast); if (ASTNodes.isControlStatementBody(fNodeToAssign.getLocationInParent())) { Block block= ast.newBlock(); block.statements().add(rewrite.createMoveTarget(fNodeToAssign)); rewrite.replace(fNodeToAssign, block, null); } if (needsSemicolon(expression)) { VariableDeclarationStatement varStatement= ast.newVariableDeclarationStatement(newDeclFrag); varStatement.setType(type); rewrite.replace(expression, varStatement, null); } else { // trick for bug 43248: use an VariableDeclarationExpression and keep the ExpressionStatement VariableDeclarationExpression varExpression= ast.newVariableDeclarationExpression(newDeclFrag); varExpression.setType(type); rewrite.replace(expression, varExpression, null); } addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME); addLinkedPosition(rewrite.track(type), false, KEY_TYPE); setEndPosition(rewrite.track(fNodeToAssign)); // set cursor after expression statement return rewrite; }
Example 18
Source File: ExtractConstantRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private void createConstantDeclaration() throws CoreException { Type type= getConstantType(); IExpressionFragment fragment= getSelectedExpression(); Expression initializer= getSelectedExpression().createCopyTarget(fCuRewrite.getASTRewrite(), true); AST ast= fCuRewrite.getAST(); VariableDeclarationFragment variableDeclarationFragment= ast.newVariableDeclarationFragment(); variableDeclarationFragment.setName(ast.newSimpleName(fConstantName)); variableDeclarationFragment.setInitializer(initializer); FieldDeclaration fieldDeclaration= ast.newFieldDeclaration(variableDeclarationFragment); fieldDeclaration.setType(type); Modifier.ModifierKeyword accessModifier= Modifier.ModifierKeyword.toKeyword(fVisibility); if (accessModifier != null) fieldDeclaration.modifiers().add(ast.newModifier(accessModifier)); fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD)); fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD)); boolean createComments= JavaPreferencesSettings.getCodeGenerationSettings(fCu.getJavaProject()).createComments; if (createComments) { String comment= CodeGeneration.getFieldComment(fCu, getConstantTypeName(), fConstantName, StubUtility.getLineDelimiterUsed(fCu)); if (comment != null && comment.length() > 0) { Javadoc doc= (Javadoc) fCuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC); fieldDeclaration.setJavadoc(doc); } } AbstractTypeDeclaration parent= getContainingTypeDeclarationNode(); ListRewrite listRewrite= fCuRewrite.getASTRewrite().getListRewrite(parent, parent.getBodyDeclarationsProperty()); TextEditGroup msg= fCuRewrite.createGroupDescription(RefactoringCoreMessages.ExtractConstantRefactoring_declare_constant); if (insertFirst()) { listRewrite.insertFirst(fieldDeclaration, msg); } else { listRewrite.insertAfter(fieldDeclaration, getNodeToInsertConstantDeclarationAfter(), msg); } if (fLinkedProposalModel != null) { ASTRewrite rewrite= fCuRewrite.getASTRewrite(); LinkedProposalPositionGroup nameGroup= fLinkedProposalModel.getPositionGroup(KEY_NAME, true); nameGroup.addPosition(rewrite.track(variableDeclarationFragment.getName()), true); String[] nameSuggestions= guessConstantNames(); if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fConstantName)) { nameGroup.addProposal(fConstantName, null, nameSuggestions.length + 1); } for (int i= 0; i < nameSuggestions.length; i++) { nameGroup.addProposal(nameSuggestions[i], null, nameSuggestions.length - i); } LinkedProposalPositionGroup typeGroup= fLinkedProposalModel.getPositionGroup(KEY_TYPE, true); typeGroup.addPosition(rewrite.track(type), true); ITypeBinding typeBinding= guessBindingForReference(fragment.getAssociatedExpression()); if (typeBinding != null) { ITypeBinding[] relaxingTypes= ASTResolving.getNarrowingTypes(ast, typeBinding); for (int i= 0; i < relaxingTypes.length; i++) { typeGroup.addProposal(relaxingTypes[i], fCuRewrite.getCu(), relaxingTypes.length - i); } } boolean isInterface= parent.resolveBinding() != null && parent.resolveBinding().isInterface(); ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(fLinkedProposalModel, rewrite, fieldDeclaration.modifiers(), isInterface); } }
Example 19
Source File: LambdaExpressionsFix.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
/** * {@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); } }
Example 20
Source File: AbstractSerialVersionOperation.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
/** * {@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)); }