private IStatus checkIteratorCondition() { List<Expression> initializers = getForStatement().initializers(); if (initializers.size() != 1) return SEMANTIC_CHANGE_WARNING_STATUS; Expression expression = initializers.get(0); if (!(expression instanceof VariableDeclarationExpression)) return SEMANTIC_CHANGE_WARNING_STATUS; VariableDeclarationExpression declaration = (VariableDeclarationExpression) expression; List<VariableDeclarationFragment> variableDeclarationFragments = declaration.fragments(); if (variableDeclarationFragments.size() != 1) return SEMANTIC_CHANGE_WARNING_STATUS; VariableDeclarationFragment declarationFragment = variableDeclarationFragments.get(0); Expression initializer = declarationFragment.getInitializer(); if (!(initializer instanceof MethodInvocation)) return SEMANTIC_CHANGE_WARNING_STATUS; MethodInvocation methodInvocation = (MethodInvocation) initializer; String methodName = methodInvocation.getName().getIdentifier(); if (!"iterator".equals(methodName) || methodInvocation.arguments().size() != 0) // $NON-NLS-1$ return SEMANTIC_CHANGE_WARNING_STATUS; return StatusInfo.OK_STATUS; }
/** * 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; }
/** * Generates a {@link VariableDeclarationExpression}, which initializes the loop variable to * iterate over an array. * * @param ast the current {@link AST} instance * @param loopVariableName the name of the variable which should be initialized * @return a filled {@link VariableDeclarationExpression}, declaring a int variable, which is * initializes with 0 */ private VariableDeclarationExpression getForInitializer(AST ast, SimpleName loopVariableName) { // initializing fragment VariableDeclarationFragment firstDeclarationFragment = ast.newVariableDeclarationFragment(); firstDeclarationFragment.setName(loopVariableName); NumberLiteral startIndex = ast.newNumberLiteral(); firstDeclarationFragment.setInitializer(startIndex); // declaration VariableDeclarationExpression variableDeclaration = ast.newVariableDeclarationExpression(firstDeclarationFragment); PrimitiveType variableType = ast.newPrimitiveType(PrimitiveType.INT); variableDeclaration.setType(variableType); return variableDeclaration; }
/** * Returns the type node for the given declaration. * * @param declaration the declaration * @return the type node or <code>null</code> if the given declaration represents a type * inferred parameter in lambda expression */ public static Type getType(VariableDeclaration declaration) { if (declaration instanceof SingleVariableDeclaration) { return ((SingleVariableDeclaration)declaration).getType(); } else if (declaration instanceof VariableDeclarationFragment) { ASTNode parent= ((VariableDeclarationFragment)declaration).getParent(); if (parent instanceof VariableDeclarationExpression) { return ((VariableDeclarationExpression)parent).getType(); } else if (parent instanceof VariableDeclarationStatement) { return ((VariableDeclarationStatement)parent).getType(); } else if (parent instanceof FieldDeclaration) { return ((FieldDeclaration)parent).getType(); } else if (parent instanceof LambdaExpression) { return null; } } Assert.isTrue(false, "Unknown VariableDeclaration"); //$NON-NLS-1$ return null; }
private void clearAccessMode(FlowInfo info, List<? extends ASTNode> nodes) { if (nodes == null || nodes.isEmpty() || info == null) { return; } for (Iterator<? extends ASTNode> iter = nodes.iterator(); iter.hasNext();) { Object node = iter.next(); Iterator<VariableDeclarationFragment> fragments = null; if (node instanceof VariableDeclarationStatement) { fragments = ((VariableDeclarationStatement) node).fragments().iterator(); } else if (node instanceof VariableDeclarationExpression) { fragments = ((VariableDeclarationExpression) node).fragments().iterator(); } if (fragments != null) { while (fragments.hasNext()) { clearAccessMode(info, fragments.next()); } } } }
@Override public boolean visit(TryStatement node) { if (traverseNode(node)) { fFlowContext.pushExcptions(node); for (Iterator<VariableDeclarationExpression> iterator = node.resources().iterator(); iterator.hasNext();) { iterator.next().accept(this); } node.getBody().accept(this); fFlowContext.popExceptions(); List<CatchClause> catchClauses = node.catchClauses(); for (Iterator<CatchClause> iter = catchClauses.iterator(); iter.hasNext();) { iter.next().accept(this); } Block finallyBlock = node.getFinally(); if (finallyBlock != null) { finallyBlock.accept(this); } } return false; }
@Override public void endVisit(TryStatement node) { if (skipNode(node)) { return; } TryFlowInfo info = createTry(); setFlowInfo(node, info); for (Iterator<VariableDeclarationExpression> iterator = node.resources().iterator(); iterator.hasNext();) { info.mergeResources(getFlowInfo(iterator.next()), fFlowContext); } info.mergeTry(getFlowInfo(node.getBody()), fFlowContext); for (Iterator<CatchClause> iter = node.catchClauses().iterator(); iter.hasNext();) { CatchClause element = iter.next(); info.mergeCatch(getFlowInfo(element), fFlowContext); } info.mergeFinally(getFlowInfo(node.getFinally()), fFlowContext); }
Type getDeclaredType(VariableDeclarationFragment frg) { ASTNode parent = frg.getParent(); if(parent instanceof VariableDeclarationStatement ) { VariableDeclarationStatement varDecl = (VariableDeclarationStatement)parent; return varDecl.getType(); } else if (parent instanceof VariableDeclarationExpression ) { VariableDeclarationExpression varExpr = (VariableDeclarationExpression)parent; return varExpr.getType(); } return null; }
/** {@inheritDoc} */ @Override public boolean visit(VariableDeclarationExpression node) { if (fAddFinalLocals && node.fragments().size() == 1) { SimpleName name = ((VariableDeclarationFragment) node.fragments().get(0)).getName(); IBinding binding = name.resolveBinding(); if (binding == null) return false; if (fWrittenVariables.containsKey(binding)) return false; ModifierChangeOperation op = createAddFinalOperation(name, node); if (op == null) return false; fResult.add(op); return false; } return false; }
private static boolean canAddFinal(IBinding binding, ASTNode declNode) { if (!(binding instanceof IVariableBinding)) return false; IVariableBinding varbinding = (IVariableBinding) binding; int modifiers = varbinding.getModifiers(); if (Modifier.isFinal(modifiers) || Modifier.isVolatile(modifiers) || Modifier.isTransient(modifiers)) return false; ASTNode parent = ASTNodes.getParent(declNode, VariableDeclarationExpression.class); if (parent != null && ((VariableDeclarationExpression) parent).fragments().size() > 1) return false; if (varbinding.isField() && !Modifier.isPrivate(modifiers)) return false; if (varbinding.isParameter()) { ASTNode varDecl = declNode.getParent(); if (varDecl instanceof MethodDeclaration) { MethodDeclaration declaration = (MethodDeclaration) varDecl; if (declaration.getBody() == null) return false; } } return true; }
@Override public void endVisit(VariableDeclarationExpression node) { // Constrain the types of the child VariableDeclarationFragments to be equal to one // another, since the initializers in a 'for' statement can only have one type. // Pairwise constraints between adjacent variables is enough. Type type = node.getType(); ConstraintVariable2 typeCv = getConstraintVariable(type); if (typeCv == null) return; setConstraintVariable(node, typeCv); List<VariableDeclarationFragment> fragments = node.fragments(); for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) { VariableDeclarationFragment fragment = iter.next(); ConstraintVariable2 fragmentCv = getConstraintVariable(fragment); fTCModel.createElementEqualsConstraints(typeCv, fragmentCv); } }
private void clearAccessMode(FlowInfo info, List<? extends ASTNode> nodes) { if (nodes == null || nodes.isEmpty() || info == null) return; for (Iterator<? extends ASTNode> iter = nodes.iterator(); iter.hasNext(); ) { Object node = iter.next(); Iterator<VariableDeclarationFragment> fragments = null; if (node instanceof VariableDeclarationStatement) { fragments = ((VariableDeclarationStatement) node).fragments().iterator(); } else if (node instanceof VariableDeclarationExpression) { fragments = ((VariableDeclarationExpression) node).fragments().iterator(); } if (fragments != null) { while (fragments.hasNext()) { clearAccessMode(info, fragments.next()); } } } }
private static List<IVariableBinding> getForInitializedVariables( VariableDeclarationExpression variableDeclarations) { List<IVariableBinding> forInitializerVariables = new ArrayList<IVariableBinding>(1); for (Iterator<VariableDeclarationFragment> iter = variableDeclarations.fragments().iterator(); iter.hasNext(); ) { VariableDeclarationFragment fragment = iter.next(); IVariableBinding binding = fragment.resolveBinding(); if (binding != null) forInitializerVariables.add(binding); } return forInitializerVariables; }
@Override public boolean visit(VariableDeclarationExpression node) { if (node.getLocationInParent() == TryStatement.RESOURCES_PROPERTY) { Type type = node.getType(); ITypeBinding resourceTypeBinding = type.resolveBinding(); if (resourceTypeBinding != null) { IMethodBinding methodBinding = Bindings.findMethodInHierarchy( resourceTypeBinding, "close", new ITypeBinding[0]); // $NON-NLS-1$ if (methodBinding != null) { addExceptions(methodBinding.getExceptionTypes(), node.getAST()); } } } return super.visit(node); }
/** * 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; }
/** * 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; }
/** * 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; }
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; }
private static Type getType(ASTNode node) { switch(node.getNodeType()){ case ASTNode.SINGLE_VARIABLE_DECLARATION: return ((SingleVariableDeclaration) node).getType(); case ASTNode.FIELD_DECLARATION: return ((FieldDeclaration) node).getType(); case ASTNode.VARIABLE_DECLARATION_STATEMENT: return ((VariableDeclarationStatement) node).getType(); case ASTNode.VARIABLE_DECLARATION_EXPRESSION: return ((VariableDeclarationExpression) node).getType(); case ASTNode.METHOD_DECLARATION: return ((MethodDeclaration)node).getReturnType2(); case ASTNode.PARAMETERIZED_TYPE: return ((ParameterizedType)node).getType(); default: Assert.isTrue(false); return null; } }
@Override public void endVisit(VariableDeclarationExpression node) { // Constrain the types of the child VariableDeclarationFragments to be equal to one // another, since the initializers in a 'for' statement can only have one type. // Pairwise constraints between adjacent variables is enough. Type type= node.getType(); ConstraintVariable2 typeCv= getConstraintVariable(type); if (typeCv == null) return; setConstraintVariable(node, typeCv); List<VariableDeclarationFragment> fragments= node.fragments(); for (Iterator<VariableDeclarationFragment> iter= fragments.iterator(); iter.hasNext();) { VariableDeclarationFragment fragment= iter.next(); ConstraintVariable2 fragmentCv= getConstraintVariable(fragment); fTCModel.createElementEqualsConstraints(typeCv, fragmentCv); } }
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); }
private void clearAccessMode(FlowInfo info, List<? extends ASTNode> nodes) { if (nodes== null || nodes.isEmpty() || info == null) return; for (Iterator<? extends ASTNode> iter= nodes.iterator(); iter.hasNext(); ) { Object node= iter.next(); Iterator<VariableDeclarationFragment> fragments= null; if (node instanceof VariableDeclarationStatement) { fragments= ((VariableDeclarationStatement)node).fragments().iterator(); } else if (node instanceof VariableDeclarationExpression) { fragments= ((VariableDeclarationExpression)node).fragments().iterator(); } if (fragments != null) { while (fragments.hasNext()) { clearAccessMode(info, fragments.next()); } } } }
private RefactoringStatus checkExpression() throws JavaModelException { Expression selectedExpression= getSelectedExpression().getAssociatedExpression(); if (selectedExpression != null) { final ASTNode parent= selectedExpression.getParent(); if (selectedExpression instanceof NullLiteral) { return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_null_literals); } else if (selectedExpression instanceof ArrayInitializer) { return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_array_initializer); } else if (selectedExpression instanceof Assignment) { if (parent instanceof Expression && !(parent instanceof ParenthesizedExpression)) return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_assignment); else return null; } else if (selectedExpression instanceof SimpleName) { if ((((SimpleName) selectedExpression)).isDeclaration()) return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_names_in_declarations); if (parent instanceof QualifiedName && selectedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY || parent instanceof FieldAccess && selectedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY) return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_select_expression); } else if (selectedExpression instanceof VariableDeclarationExpression && parent instanceof TryStatement) { return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_resource_in_try_with_resources); } } return null; }
/** * Returns the type node for the given declaration. * * @param declaration the declaration * @return the type node or <code>null</code> if the given declaration represents a type * inferred parameter in lambda expression */ public static Type getType(VariableDeclaration declaration) { if (declaration instanceof SingleVariableDeclaration) { return ((SingleVariableDeclaration)declaration).getType(); } else if (declaration instanceof VariableDeclarationFragment) { ASTNode parent= ((VariableDeclarationFragment)declaration).getParent(); if (parent instanceof VariableDeclarationExpression) return ((VariableDeclarationExpression)parent).getType(); else if (parent instanceof VariableDeclarationStatement) return ((VariableDeclarationStatement)parent).getType(); else if (parent instanceof FieldDeclaration) return ((FieldDeclaration)parent).getType(); else if (parent instanceof LambdaExpression) return null; } Assert.isTrue(false, "Unknown VariableDeclaration"); //$NON-NLS-1$ return null; }
private ListRewrite evaluateListRewrite(ASTRewrite rewrite, ASTNode declNode) { switch (declNode.getNodeType()) { case ASTNode.METHOD_DECLARATION: return rewrite.getListRewrite(declNode, MethodDeclaration.MODIFIERS2_PROPERTY); case ASTNode.FIELD_DECLARATION: return rewrite.getListRewrite(declNode, FieldDeclaration.MODIFIERS2_PROPERTY); case ASTNode.VARIABLE_DECLARATION_EXPRESSION: return rewrite.getListRewrite(declNode, VariableDeclarationExpression.MODIFIERS2_PROPERTY); case ASTNode.VARIABLE_DECLARATION_STATEMENT: return rewrite.getListRewrite(declNode, VariableDeclarationStatement.MODIFIERS2_PROPERTY); case ASTNode.SINGLE_VARIABLE_DECLARATION: return rewrite.getListRewrite(declNode, SingleVariableDeclaration.MODIFIERS2_PROPERTY); case ASTNode.TYPE_DECLARATION: return rewrite.getListRewrite(declNode, TypeDeclaration.MODIFIERS2_PROPERTY); case ASTNode.ENUM_DECLARATION: return rewrite.getListRewrite(declNode, EnumDeclaration.MODIFIERS2_PROPERTY); case ASTNode.ANNOTATION_TYPE_DECLARATION: return rewrite.getListRewrite(declNode, AnnotationTypeDeclaration.MODIFIERS2_PROPERTY); case ASTNode.ENUM_CONSTANT_DECLARATION: return rewrite.getListRewrite(declNode, EnumConstantDeclaration.MODIFIERS2_PROPERTY); case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: return rewrite.getListRewrite(declNode, AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY); default: throw new IllegalArgumentException("node has no modifiers: " + declNode.getClass().getName()); //$NON-NLS-1$ } }
/** * {@inheritDoc} */ @Override public boolean visit(VariableDeclarationExpression node) { if (fAddFinalLocals && node.fragments().size() == 1) { SimpleName name= ((VariableDeclarationFragment)node.fragments().get(0)).getName(); IBinding binding= name.resolveBinding(); if (binding == null) return false; if (fWrittenVariables.containsKey(binding)) return false; ModifierChangeOperation op= createAddFinalOperation(name, node); if (op == null) return false; fResult.add(op); return false; } return false; }
private static ModifierChangeOperation createAddFinalOperation(SimpleName name, ASTNode decl) { if (decl == null) return null; IBinding binding= name.resolveBinding(); if (!canAddFinal(binding, decl)) return null; if (decl instanceof SingleVariableDeclaration) { return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE); } else if (decl instanceof VariableDeclarationExpression) { return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE); } else if (decl instanceof VariableDeclarationFragment){ VariableDeclarationFragment frag= (VariableDeclarationFragment)decl; decl= decl.getParent(); if (decl instanceof FieldDeclaration || decl instanceof VariableDeclarationStatement) { List<VariableDeclarationFragment> list= new ArrayList<VariableDeclarationFragment>(); list.add(frag); return new ModifierChangeOperation(decl, list, Modifier.FINAL, Modifier.NONE); } else if (decl instanceof VariableDeclarationExpression) { return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE); } } return null; }
/** * 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; }
/** * 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; }
/** * Returns the type node for the given declaration. * @param declaration the declaration * @return the type node */ public static Type getType(VariableDeclaration declaration) { if (declaration instanceof SingleVariableDeclaration) { return ((SingleVariableDeclaration)declaration).getType(); } else if (declaration instanceof VariableDeclarationFragment) { ASTNode parent= ((VariableDeclarationFragment)declaration).getParent(); if (parent instanceof VariableDeclarationExpression) return ((VariableDeclarationExpression)parent).getType(); else if (parent instanceof VariableDeclarationStatement) return ((VariableDeclarationStatement)parent).getType(); else if (parent instanceof FieldDeclaration) return ((FieldDeclaration)parent).getType(); } Assert.isTrue(false, "Unknown VariableDeclaration"); //$NON-NLS-1$ return null; }
@Override public boolean visit(VariableDeclarationExpression node) { if (node.getAST().apiLevel() >= JLS3) { printModifiers(node.modifiers()); } node.getType().accept(this); this.fBuffer.append(" ");//$NON-NLS-1$ for (Iterator<VariableDeclarationFragment> it= node.fragments().iterator(); it.hasNext();) { VariableDeclarationFragment f= it.next(); f.accept(this); if (it.hasNext()) { this.fBuffer.append(", ");//$NON-NLS-1$ } } return false; }