private VariableDeclarationStatement createDeclaration( IVariableBinding binding, Expression intilizer) { VariableDeclaration original = ASTNodes.findVariableDeclaration(binding, fAnalyzer.getEnclosingBodyDeclaration()); VariableDeclarationFragment fragment = fAST.newVariableDeclarationFragment(); fragment.setName((SimpleName) ASTNode.copySubtree(fAST, original.getName())); fragment.setInitializer(intilizer); VariableDeclarationStatement result = fAST.newVariableDeclarationStatement(fragment); result.modifiers().addAll(ASTNode.copySubtrees(fAST, ASTNodes.getModifiers(original))); result.setType( ASTNodeFactory.newType( fAST, original, fImportRewriter, new ContextSensitiveImportRewriteContext(original, fImportRewriter))); return result; }
@SuppressWarnings("unchecked") @Override public void createUnobservedInitStmt(CaptureLog log, int logRecNo) { PostProcessor.notifyRecentlyProcessedLogRecNo(logRecNo); // NOTE: PLAIN INIT: has always one non-null param // TODO: use primitives final int oid = log.objectIds.get(logRecNo); // final String type = log.oidClassNames.get(log.oidRecMapping.get(oid)); final Object value = log.params.get(logRecNo)[0]; this.isXStreamNeeded = true; final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); // handling because there must always be a new instantiation statement for pseudo inits this.oidToVarMapping.remove(oid); vd.setName(ast.newSimpleName(this.createNewVarName(oid, log.oidClassNames.get(log.oidRecMapping.get(oid)), true))); final MethodInvocation methodInvocation = ast.newMethodInvocation(); final Name name = ast.newSimpleName("XSTREAM"); methodInvocation.setExpression(name); methodInvocation.setName(ast.newSimpleName("fromXML")); final StringLiteral xmlParam = ast.newStringLiteral(); xmlParam.setLiteralValue((String) value); methodInvocation.arguments().add(xmlParam); // final CastExpression castExpr = ast.newCastExpression(); // castExpr.setType(this.createAstType(type, ast)); // castExpr.setExpression(methodInvocation); // vd.setInitializer(castExpr); vd.setInitializer(methodInvocation); final VariableDeclarationStatement vs = ast.newVariableDeclarationStatement(vd); vs.setType(this.createAstType("Object", ast)); methodBlock.statements().add(vs); }
@SuppressWarnings("unchecked") private void createUnobservedInitStmt(final int logRecNo, final Block methodBlock, final AST ast) { // NOTE: PLAIN INIT: has always one non-null param // TODO: use primitives final int oid = this.log.objectIds.get(logRecNo); final String type = this.log.oidClassNames.get(this.log.oidRecMapping.get(oid)); final Object value = this.log.params.get(logRecNo)[0]; this.isXStreamNeeded = true; final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); // handling because there must always be a new instantiation statement for pseudo inits this.oidToVarMapping.remove(oid); vd.setName(ast.newSimpleName(this.createNewVarName(oid, type))); final MethodInvocation methodInvocation = ast.newMethodInvocation(); final Name name = ast.newSimpleName("XSTREAM"); methodInvocation.setExpression(name); methodInvocation.setName(ast.newSimpleName("fromXML")); final StringLiteral xmlParam = ast.newStringLiteral(); xmlParam.setLiteralValue((String) value); methodInvocation.arguments().add(xmlParam); final CastExpression castExpr = ast.newCastExpression(); castExpr.setType(this.createAstType(type, ast)); castExpr.setExpression(methodInvocation); vd.setInitializer(castExpr); final VariableDeclarationStatement vs = ast.newVariableDeclarationStatement(vd); vs.setType(this.createAstType(type, ast)); methodBlock.statements().add(vs); }
public VariableDeclarationStatement variableDeclarationStatement(String name, Type type, Expression initializer) { VariableDeclarationFragment variableDeclarationFragment = variableDeclarationFragment(name); variableDeclarationFragment.setInitializer(initializer); VariableDeclarationStatement statement = ast.get().newVariableDeclarationStatement(variableDeclarationFragment); statement.setType(type); return statement; }
public boolean visit(VariableDeclarationStatement vds) { if (mtbStack.isEmpty()) // not part of a method return true; // make local variable declaration for (Object ovdf : vds.fragments()) { VariableDeclarationFragment vdf = (VariableDeclarationFragment) ovdf; try { facts.add(Fact.makeLocalVarFact(getQualifiedName(mtbStack .peek()), getQualifiedName(vds.getType() .resolveBinding()), vdf.getName().getIdentifier(), vdf .getInitializer().toString())); } catch (Exception e) { System.err.println("Cannot resolve variable declaration \"" + vdf.getName().toString() + "\""); } } return true; }
private VariableDeclarationStatement createDeclaration(IVariableBinding binding, Expression intilizer) { VariableDeclaration original = ASTNodes.findVariableDeclaration(binding, fAnalyzer.getEnclosingBodyDeclaration()); VariableDeclarationFragment fragment = fAST.newVariableDeclarationFragment(); fragment.setName((SimpleName) ASTNode.copySubtree(fAST, original.getName())); fragment.setInitializer(intilizer); VariableDeclarationStatement result = fAST.newVariableDeclarationStatement(fragment); result.modifiers().addAll(ASTNode.copySubtrees(fAST, ASTNodes.getModifiers(original))); result.setType(ASTNodeFactory.newType(fAST, original, fImportRewriter, new ContextSensitiveImportRewriteContext(original, fImportRewriter))); return result; }
@Override public boolean visit(VariableDeclarationFragment param) { ASTNode parent = param.getParent(); if (parent instanceof VariableDeclarationStatement) { VariableDeclarationStatement statement = (VariableDeclarationStatement) parent; ASTNode annotation = getAnnotation(statement.modifiers(), "Domain"); if (annotation != null) { ListRewrite paramRewrite = rewrite.getListRewrite(statement, VariableDeclarationStatement.MODIFIERS2_PROPERTY); paramRewrite.remove(annotation, null); } } return super.visit(param); }
public boolean visit(VariableDeclarationStatement vds) { if (this.mtbStack.isEmpty()) { return true; } for (Object ovdf : vds.fragments()) { VariableDeclarationFragment vdf = (VariableDeclarationFragment)ovdf; try { this.facts.add(Fact.makeLocalVarFact(getQualifiedName( (IMethodBinding)this.mtbStack.peek()), getQualifiedName(vds.getType() .resolveBinding()), vdf.getName().getIdentifier(), vdf .getInitializer().toString())); } catch (Exception e) { System.err.println("Cannot resolve variable declaration \"" + vdf.getName().toString() + "\""); } } return true; }
public boolean visit(VariableDeclarationStatement vds) { if (this.mtbStack.isEmpty()) { return true; } for (Object ovdf : vds.fragments()) { VariableDeclarationFragment vdf = (VariableDeclarationFragment)ovdf; try { this.facts.add(Fact.makeLocalVarFact(getQualifiedName( (IMethodBinding)this.mtbStack.peek()), getQualifiedName(vds.getType() .resolveBinding()), vdf.getName().getIdentifier(), vdf .getInitializer().toString())); } catch (Exception localException) { System.err.println("Cannot resolve variable declaration \"" + vdf.getName().toString() + "\""); } } return true; }
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; }
private VariableDeclarationStatement createTempDeclaration(Expression initializer) throws CoreException { AST ast = fCURewrite.getAST(); VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment(); vdf.setName(ast.newSimpleName(fTempName)); vdf.setInitializer(initializer); VariableDeclarationStatement vds = ast.newVariableDeclarationStatement(vdf); if (fDeclareFinal) { vds.modifiers().add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD)); } vds.setType(createTempType()); if (fLinkedProposalModel != null) { ASTRewrite rewrite = fCURewrite.getASTRewrite(); LinkedProposalPositionGroup nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true); nameGroup.addPosition(rewrite.track(vdf.getName()), true); String[] nameSuggestions = guessTempNames(); if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fTempName)) { nameGroup.addProposal(fTempName, null, nameSuggestions.length + 1); } for (int i = 0; i < nameSuggestions.length; i++) { nameGroup.addProposal(nameSuggestions[i], null, nameSuggestions.length - i); } } return vds; }
@SuppressWarnings("unchecked") @Override public void createCollectionInitStmt(final CaptureLog log, final int logRecNo) { final int oid = log.objectIds.get(logRecNo); final Object[] params = log.params.get(logRecNo); String collTypeName = log.oidClassNames.get(log.oidRecMapping.get(oid)); final Class<?> collType = getClassForName(collTypeName); final String varName; // -- determine if an alternative collection must be used for code generation final boolean isPrivate = java.lang.reflect.Modifier.isPrivate(collType.getModifiers()); if(isPrivate || ! hasDefaultConstructor(collType)) { if(Set.class.isAssignableFrom(collType)) { collTypeName = HashSet.class.getName(); } else if (List.class.isAssignableFrom(collType)) { collTypeName = ArrayList.class.getName(); } else if(Queue.class.isAssignableFrom(collType)) { collTypeName = ArrayDeque.class.getName(); } else { throw new RuntimeException("Collection " + collType + " is not supported"); } } // -- create code for instantiating collection varName = this.createNewVarName(oid, collTypeName); final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); final SimpleName varNameExpr = ast.newSimpleName(varName); vd.setName(varNameExpr); final ClassInstanceCreation ci = ast.newClassInstanceCreation(); ci.setType(this.createAstType(collTypeName, ast)); vd.setInitializer(ci); final VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd); stmt.setType(this.createAstType(collTypeName, ast)); methodBlock.statements().add(stmt); // --- create code for filling the collection Integer paramOID; MethodInvocation mi; for(int i = 0; i < params.length; i++) { mi = ast.newMethodInvocation(); mi.setName(ast.newSimpleName("add")); paramOID = (Integer) params[i]; if(paramOID == null) { mi.arguments().add(ast.newNullLiteral()); } else { mi.arguments().add(ast.newSimpleName(this.oidToVarMapping.get(paramOID))); } methodBlock.statements().add(mi); } }
@Override public void createMapInitStmt(final CaptureLog log, final int logRecNo) { final int oid = log.objectIds.get(logRecNo); final Object[] params = log.params.get(logRecNo); String collTypeName = log.oidClassNames.get(log.oidRecMapping.get(oid)); final Class<?> collType = getClassForName(collTypeName); final String varName; // -- determine if an alternative collection must be used for code generation final boolean isPrivate = java.lang.reflect.Modifier.isPrivate(collType.getModifiers()); if(isPrivate || ! hasDefaultConstructor(collType)) { collTypeName = HashMap.class.getName(); } // -- create code for instantiating collection varName = this.createNewVarName(oid, collTypeName); final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); final SimpleName varNameExpr = ast.newSimpleName(varName); vd.setName(varNameExpr); final ClassInstanceCreation ci = ast.newClassInstanceCreation(); ci.setType(this.createAstType(collTypeName, ast)); vd.setInitializer(ci); final VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd); stmt.setType(this.createAstType(collTypeName, ast)); methodBlock.statements().add(stmt); // --- create code for filling the collection Integer valueOID; Integer keyOID; MethodInvocation mi; for(int i = 0; i + 1< params.length; i+=2) { mi = ast.newMethodInvocation(); mi.setName(ast.newSimpleName("put")); keyOID = (Integer) params[i]; mi.arguments().add(ast.newSimpleName(this.oidToVarMapping.get(keyOID))); valueOID = (Integer) params[i + 1]; if(valueOID == null) { mi.arguments().add(ast.newNullLiteral()); } else { mi.arguments().add(ast.newSimpleName(this.oidToVarMapping.get(valueOID))); } methodBlock.statements().add(mi); } }
private void findUnnecessaryStore(ReturnStatement node) { Block block = TraversalUtil.findClosestAncestor(node, Block.class); @SuppressWarnings("unchecked") List<Statement> blockStatements = block.statements(); for (int i = 1; i < blockStatements.size(); i++) { Statement statement = blockStatements.get(i); if (statement == this.originalReturn) { for (int j = i - 1; j >= 0; j--) { Statement storeStatement = blockStatements.get(j); if (storeStatement instanceof VariableDeclarationStatement) { splitStatementAndInitializer((VariableDeclarationStatement) storeStatement); return; } else if (storeStatement instanceof ExpressionStatement) { if (splitStatementAndInitializer((ExpressionStatement) storeStatement)) { // we found our extra storage statement return; } } } } } }
@Override public boolean visit(VariableDeclarationStatement node) { List fragments = node.fragments(); for(Object o : fragments) { VariableDeclarationFragment frag = (VariableDeclarationFragment) o; String varName = frag.getName().getIdentifier(); int line = cunit.getLineNumber(frag.getStartPosition()); Scope scope = new Scope(line, getEndLine(node.getParent(), cunit)); VariableTags tags = new VariableTags(varName, null, line, scope, false); variables.add(tags); } return super.visit(node); }
@Override public boolean visit(VariableDeclarationStatement node) { List fragments = node.fragments(); VariableDeclarationFragment varDec = (VariableDeclarationFragment) fragments.get(0); System.out.println(varDec.getName().getIdentifier() + " " + node.getParent()); return super.visit(node); }
/** * 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 splitUpDeclarations(ASTRewrite rewrite, TextEditGroup group, VariableDeclarationFragment frag, VariableDeclarationStatement originalStatement, List<Expression> sideEffects) { if (sideEffects.size() > 0) { ListRewrite statementRewrite= rewrite.getListRewrite(originalStatement.getParent(), (ChildListPropertyDescriptor) originalStatement.getLocationInParent()); Statement previousStatement= originalStatement; for (int i= 0; i < sideEffects.size(); i++) { Expression sideEffect= sideEffects.get(i); Expression movedInit= (Expression) rewrite.createMoveTarget(sideEffect); ExpressionStatement wrapped= rewrite.getAST().newExpressionStatement(movedInit); statementRewrite.insertAfter(wrapped, previousStatement, group); previousStatement= wrapped; } VariableDeclarationStatement newDeclaration= null; List<VariableDeclarationFragment> fragments= originalStatement.fragments(); int fragIndex= fragments.indexOf(frag); ListIterator<VariableDeclarationFragment> fragmentIterator= fragments.listIterator(fragIndex+1); while (fragmentIterator.hasNext()) { VariableDeclarationFragment currentFragment= fragmentIterator.next(); VariableDeclarationFragment movedFragment= (VariableDeclarationFragment) rewrite.createMoveTarget(currentFragment); if (newDeclaration == null) { newDeclaration= rewrite.getAST().newVariableDeclarationStatement(movedFragment); Type copiedType= (Type) rewrite.createCopyTarget(originalStatement.getType()); newDeclaration.setType(copiedType); } else { newDeclaration.fragments().add(movedFragment); } } if (newDeclaration != null){ statementRewrite.insertAfter(newDeclaration, previousStatement, group); if (originalStatement.fragments().size() == newDeclaration.fragments().size() + 1){ rewrite.remove(originalStatement, group); } } } }
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()); } } } }
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; }
@Override public OOGContext transfer(SourceVariableDeclaration instr, OOGContext value) { // Get the source variable that is being declared SourceVariable declaredVariable = instr.getDeclaredVariable(); // Get the set of qualifiers of the variable that is being declared Set<OType> declVarSet = this.tm.getAnalysisResult(declaredVariable); // Check if the declared variable is the left-hand side of a new expression, call T-New for its ser // And remove the qualfiers that contain 'n.PD' VariableDeclaration node = instr.getNode(); ASTNode parent = node.getParent(); if(parent instanceof VariableDeclarationStatement){ if(node.getInitializer()!=null && node.getInitializer() instanceof ClassInstanceCreation){ TypeConstraints.tNewNoOthersPublicDomain(declVarSet); } } return value; }
/** * @return <code>null</code> if the selection is invalid or does not cover a temp declaration or * reference. */ public static VariableDeclaration findTempDeclaration( CompilationUnit cu, int selectionOffset, int selectionLength) { TempSelectionAnalyzer analyzer = new TempSelectionAnalyzer(selectionOffset, selectionLength); cu.accept(analyzer); ASTNode[] selected = analyzer.getSelectedNodes(); if (selected == null || selected.length != 1) return null; ASTNode selectedNode = selected[0]; if (selectedNode instanceof VariableDeclaration) return (VariableDeclaration) selectedNode; if (selectedNode instanceof Name) { Name reference = (Name) selectedNode; IBinding binding = reference.resolveBinding(); if (binding == null) return null; ASTNode declaringNode = cu.findDeclaringNode(binding); if (declaringNode instanceof VariableDeclaration) return (VariableDeclaration) declaringNode; else return null; } else if (selectedNode instanceof VariableDeclarationStatement) { VariableDeclarationStatement vds = (VariableDeclarationStatement) selectedNode; if (vds.fragments().size() != 1) return null; return (VariableDeclaration) vds.fragments().get(0); } return null; }
private void removeTemp(CompilationUnitRewrite cuRewrite) { VariableDeclaration variableDeclaration = getVariableDeclaration(); TextEditGroup groupDesc = cuRewrite.createGroupDescription( RefactoringCoreMessages.InlineTempRefactoring_remove_edit_name); ASTNode parent = variableDeclaration.getParent(); ASTRewrite rewrite = cuRewrite.getASTRewrite(); TightSourceRangeComputer sourceRangeComputer = new TightSourceRangeComputer(); rewrite.setTargetSourceRangeComputer(sourceRangeComputer); if (parent instanceof VariableDeclarationStatement && ((VariableDeclarationStatement) parent).fragments().size() == 1) { sourceRangeComputer.addTightSourceNode(parent); rewrite.remove(parent, groupDesc); } else { sourceRangeComputer.addTightSourceNode(variableDeclaration); rewrite.remove(variableDeclaration, groupDesc); } }
private RefactoringStatus checkTempTypeForLocalTypeUsage() { VariableDeclarationStatement vds = getTempDeclarationStatement(); if (vds == null) return RefactoringStatus.createFatalErrorStatus( RefactoringCoreMessages.PromoteTempToFieldRefactoring_cannot_promote); Type type = vds.getType(); ITypeBinding binding = type.resolveBinding(); if (binding == null) return RefactoringStatus.createFatalErrorStatus( RefactoringCoreMessages.PromoteTempToFieldRefactoring_cannot_promote); IMethodBinding declaringMethodBinding = getMethodDeclaration().resolveBinding(); ITypeBinding[] methodTypeParameters = declaringMethodBinding == null ? new ITypeBinding[0] : declaringMethodBinding.getTypeParameters(); LocalTypeAndVariableUsageAnalyzer analyzer = new LocalTypeAndVariableUsageAnalyzer(methodTypeParameters); type.accept(analyzer); boolean usesLocalTypes = !analyzer.getUsageOfEnclosingNodes().isEmpty(); fTempTypeUsesClassTypeVariables = analyzer.getClassTypeVariablesUsed(); if (usesLocalTypes) return RefactoringStatus.createFatalErrorStatus( RefactoringCoreMessages.PromoteTempToFieldRefactoring_uses_type_declared_locally); return null; }
private void addLocalDeclarationRemoval(ASTRewrite rewrite) { VariableDeclarationStatement tempDeclarationStatement = getTempDeclarationStatement(); List<VariableDeclarationFragment> fragments = tempDeclarationStatement.fragments(); int fragmentIndex = fragments.indexOf(fTempDeclarationNode); Assert.isTrue(fragmentIndex != -1); VariableDeclarationFragment fragment = fragments.get(fragmentIndex); rewrite.remove(fragment, null); if (fragments.size() == 1) rewrite.remove(tempDeclarationStatement, 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()); } } } }
private void createAndInsertTempDeclaration() throws CoreException { Expression initializer = getSelectedExpression().createCopyTarget(fCURewrite.getASTRewrite(), true); VariableDeclarationStatement vds = createTempDeclaration(initializer); if ((!fReplaceAllOccurrences) || (retainOnlyReplacableMatches(getMatchingFragments()).length <= 1)) { insertAt(getSelectedExpression().getAssociatedNode(), vds); return; } ASTNode[] firstReplaceNodeParents = getParents(getFirstReplacedExpression().getAssociatedNode()); ASTNode[] commonPath = findDeepestCommonSuperNodePathForReplacedNodes(); Assert.isTrue(commonPath.length <= firstReplaceNodeParents.length); ASTNode deepestCommonParent = firstReplaceNodeParents[commonPath.length - 1]; if (deepestCommonParent instanceof Block) insertAt(firstReplaceNodeParents[commonPath.length], vds); else insertAt(deepestCommonParent, vds); }
public RefactoringStatus initialize(ASTNode invocation, int severity) { RefactoringStatus result = new RefactoringStatus(); fInvocation = invocation; fLocals = new ArrayList<VariableDeclarationStatement>(3); checkMethodDeclaration(result, severity); if (result.getSeverity() >= severity) return result; initializeRewriteState(); initializeTargetNode(); flowAnalysis(); fContext = new CallContext(fInvocation, fInvocationScope, fTargetNode.getNodeType(), fImportRewrite); try { computeRealArguments(); computeReceiver(); } catch (BadLocationException exception) { JavaPlugin.log(exception); } checkInvocationContext(result, severity); return result; }
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; }
@Override public void createArrayInitStmt(final CaptureLog log, final int logRecNo) { final int oid = log.objectIds.get(logRecNo); final Object[] params = log.params.get(logRecNo); final String arrTypeName = log.oidClassNames.get(log.oidRecMapping.get(oid)); final Class<?> arrType = getClassForName(arrTypeName); // --- create array instance creation e.g. int[] var = new int[10]; final ArrayType arrAstType = (ArrayType) createAstArrayType(arrTypeName, ast); final ArrayCreation arrCreationExpr = ast.newArrayCreation(); arrCreationExpr.setType(arrAstType); arrCreationExpr.dimensions().add(ast.newNumberLiteral(String.valueOf(params.length))); final String arrVarName = this.createNewVarName(oid, arrTypeName); final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); final SimpleName arrVarNameExpr = ast.newSimpleName(arrVarName); vd.setName(arrVarNameExpr); vd.setInitializer(arrCreationExpr); final VariableDeclarationStatement varDeclStmt = ast.newVariableDeclarationStatement(vd); varDeclStmt.setType(this.createAstType(arrTypeName, ast)); methodBlock.statements().add(varDeclStmt); // create array access statements var[0] = var1; Integer paramOID; Assignment assign; ArrayAccess arrAccessExpr; for(int i = 0; i < params.length; i++) { assign = ast.newAssignment(); arrAccessExpr = ast.newArrayAccess(); arrAccessExpr.setIndex(ast.newNumberLiteral(String.valueOf(i))); arrAccessExpr.setArray(arrVarNameExpr); assign.setLeftHandSide(arrAccessExpr); paramOID = (Integer) params[i]; if(paramOID == null) { assign.setRightHandSide(ast.newNullLiteral()); } else { assign.setRightHandSide(ast.newSimpleName(this.oidToVarMapping.get(paramOID))); } methodBlock.statements().add(assign); } }
@Override public boolean visit(final VariableDeclarationStatement node) { for (final Object fragment : node.fragments()) { final VariableDeclarationFragment vdf = (VariableDeclarationFragment) fragment; final IdentifierInformation vd = new IdentifierInformation(SHA, file, vdf.getName().getIdentifier(), node.getType() .toString(), getLineNumber(vdf), getAstParentString(vdf)); identifiers.add(vd); } return super.visit(node); }
@Override public boolean visit(final VariableDeclarationStatement node) { final ASTNode parent = node.getParent(); for (final Object fragment : node.fragments()) { final VariableDeclarationFragment frag = (VariableDeclarationFragment) fragment; variableScopes.put(parent, new Variable(frag.getName() .getIdentifier(), node.getType().toString(), ScopeType.SCOPE_LOCAL)); } return false; }
/** * Looks for local variable declarations. For every declaration of a * variable, the parent {@link Block} denoting the variable's scope is * stored in {@link #variableScope} map. * * @param node * the node to visit */ @Override public boolean visit(final VariableDeclarationStatement node) { for (final Object fragment : node.fragments()) { final VariableDeclarationFragment frag = (VariableDeclarationFragment) fragment; addBinding(node, frag.getName().getIdentifier()); } return true; }
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; } }
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$ } }
@Override protected void initialize() { super.initialize(); fBuilderVariableName= createNameSuggestion(getContext().is50orHigher() ? "builder" : "buffer", NamingConventions.VK_LOCAL); //$NON-NLS-1$ //$NON-NLS-2$ fBuffer= new StringBuffer(); VariableDeclarationFragment fragment= fAst.newVariableDeclarationFragment(); fragment.setName(fAst.newSimpleName(fBuilderVariableName)); ClassInstanceCreation classInstance= fAst.newClassInstanceCreation(); Name typeName= addImport(getContext().is50orHigher() ? "java.lang.StringBuilder" : "java.lang.StringBuffer"); //$NON-NLS-1$ //$NON-NLS-2$ classInstance.setType(fAst.newSimpleType(typeName)); fragment.setInitializer(classInstance); VariableDeclarationStatement vStatement= fAst.newVariableDeclarationStatement(fragment); vStatement.setType(fAst.newSimpleType((Name)ASTNode.copySubtree(fAst, typeName))); toStringMethod.getBody().statements().add(vStatement); }
private static boolean getInlineLocalProposal(IInvocationContext context, final ASTNode node, Collection<ICommandAccess> proposals) throws CoreException { if (!(node instanceof SimpleName)) return false; SimpleName name= (SimpleName) node; IBinding binding= name.resolveBinding(); if (!(binding instanceof IVariableBinding)) return false; IVariableBinding varBinding= (IVariableBinding) binding; if (varBinding.isField() || varBinding.isParameter()) return false; ASTNode decl= context.getASTRoot().findDeclaringNode(varBinding); if (!(decl instanceof VariableDeclarationFragment) || decl.getLocationInParent() != VariableDeclarationStatement.FRAGMENTS_PROPERTY) return false; if (proposals == null) { return true; } InlineTempRefactoring refactoring= new InlineTempRefactoring((VariableDeclaration) decl); if (refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) { String label= CorrectionMessages.QuickAssistProcessor_inline_local_description; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); RefactoringCorrectionProposal proposal= new RefactoringCorrectionProposal(label, context.getCompilationUnit(), refactoring, 5, image); proposal.setCommandId(INLINE_LOCAL_ID); proposals.add(proposal); } return true; }