public static Optional<GroovyClosure> asClosure(ASTNodeFactory nodeFactory, GroovyClosureBuilder groovyClosureBuilder, Expression expression, String methodName) { if (expression instanceof ClassInstanceCreation) { ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) expression; if (classInstanceCreation.getAnonymousClassDeclaration() != null) { AnonymousClassDeclaration classDeclaration = classInstanceCreation.getAnonymousClassDeclaration(); if (classDeclaration.bodyDeclarations().size() == 1 && classDeclaration.bodyDeclarations().get(0) instanceof MethodDeclaration && ((MethodDeclaration) classDeclaration.bodyDeclarations().get(0)) .getName().getIdentifier().equals(methodName)) { MethodDeclaration methodDeclaration = (MethodDeclaration) classDeclaration.bodyDeclarations().get(0); List<Statement> statements = nodeFactory.clone(methodDeclaration.getBody()).statements(); GroovyClosure closure = groovyClosureBuilder.aClosure() .withBodyStatements(statements) .withTypeLiteral(nodeFactory.typeLiteral(type(nodeFactory, classInstanceCreation))) .withArgument(nodeFactory.clone((SingleVariableDeclaration) methodDeclaration.parameters().get(0))) .build(); return Optional.of(closure); } } } return empty(); }
/** * Method to calculate method calls in the method's body. */ @SuppressWarnings("unchecked") private void calculateMethodCalls(){ Iterator<MethodDeclaration> itMethods = methodsList.iterator(); while (itMethods.hasNext()){ MethodDeclaration firstMethod = itMethods.next(); Block firstMethodBody = firstMethod.getBody(); if (firstMethodBody != null){ List<Statement> firstMethodStatements = firstMethodBody.statements(); if (!firstMethodStatements.isEmpty()){ for (IMethod mtd : listOfMethodsName){ if (firstMethodStatements.toString().contains(mtd.getElementName())){ numberMethodCalls++; } } } } } }
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 Statement getParentLoopBody(ASTNode node) { Statement stmt = null; ASTNode start = node; while (start != null && !(start instanceof ForStatement) && !(start instanceof DoStatement) && !(start instanceof WhileStatement) && !(start instanceof EnhancedForStatement) && !(start instanceof SwitchStatement)) { start = start.getParent(); } if (start instanceof ForStatement) { stmt = ((ForStatement) start).getBody(); } else if (start instanceof DoStatement) { stmt = ((DoStatement) start).getBody(); } else if (start instanceof WhileStatement) { stmt = ((WhileStatement) start).getBody(); } else if (start instanceof EnhancedForStatement) { stmt = ((EnhancedForStatement) start).getBody(); } if (start != null && start.getParent() instanceof LabeledStatement) { LabeledStatement labeledStatement = (LabeledStatement) start.getParent(); fEnclosingLoopLabel = labeledStatement.getLabel(); } return stmt; }
private void analyzeBaseMethod(IMethod method, Method tmlMethod) throws IllegalArgumentException, JavaModelException { CompilationUnit cu = JDTUtils .createASTRoot(method.getCompilationUnit()); MethodDeclaration md = JDTUtils.createMethodDeclaration(cu, method); Block body = md.getBody(); if (body != null) { for (Object statement : body.statements()) { if (statement instanceof Statement) { Statement st = (Statement) statement; processIfStatements(st, tmlMethod); } } } }
private List<IfStatement> collectIfStatements(MethodDeclaration md) { List<IfStatement> ifStatements = new ArrayList<IfStatement>(); Block body = md.getBody(); if (body == null) { return ifStatements; } for (Object statement : body.statements()) { if (statement instanceof Statement) { Statement st = (Statement) statement; ifStatements.addAll(collectIfStatements(st)); } } return ifStatements; }
/** * Creates the corresponding statement for the method invocation, based on the return type. * * @param declaration the method declaration where the invocation statement is inserted * @param invocation the method invocation being encapsulated by the resulting statement * @return the corresponding statement */ protected Statement createMethodInvocation( final MethodDeclaration declaration, final MethodInvocation invocation) { Assert.isNotNull(declaration); Assert.isNotNull(invocation); Statement statement = null; final Type type = declaration.getReturnType2(); if (type == null) statement = createExpressionStatement(invocation); else { if (type instanceof PrimitiveType) { final PrimitiveType primitive = (PrimitiveType) type; if (primitive.getPrimitiveTypeCode().equals(PrimitiveType.VOID)) statement = createExpressionStatement(invocation); else statement = createReturnStatement(invocation); } else statement = createReturnStatement(invocation); } return statement; }
private Statement newFieldAssignment( AST ast, SimpleName fieldNameNode, Expression initializer, boolean useThisAccess) { Assignment assignment = ast.newAssignment(); if (useThisAccess) { FieldAccess access = ast.newFieldAccess(); access.setExpression(ast.newThisExpression()); access.setName(fieldNameNode); assignment.setLeftHandSide(access); } else { assignment.setLeftHandSide(fieldNameNode); } assignment.setOperator(Assignment.Operator.ASSIGN); assignment.setRightHandSide(initializer); return ast.newExpressionStatement(assignment); }
private boolean isSingleControlStatementWithoutBlock() { List<Statement> statements = fDeclaration.getBody().statements(); int size = statements.size(); if (size != 1) return false; Statement statement = statements.get(size - 1); int nodeType = statement.getNodeType(); if (nodeType == ASTNode.IF_STATEMENT) { IfStatement ifStatement = (IfStatement) statement; return !(ifStatement.getThenStatement() instanceof Block) && !(ifStatement.getElseStatement() instanceof Block); } else if (nodeType == ASTNode.FOR_STATEMENT) { return !(((ForStatement) statement).getBody() instanceof Block); } else if (nodeType == ASTNode.WHILE_STATEMENT) { return !(((WhileStatement) statement).getBody() instanceof Block); } return false; }
/** * The first thing we do is add the variable to the node aliases if it is * present in a statement. */ public boolean visit(SimpleName node){ /* All we really need from this is the variable binding. */ IBinding binding = node.resolveBinding(); /* Make sure this is a variable. */ if(binding instanceof IVariableBinding){ LinkedList<String> variables; /* Get the statement. */ Statement statement = Slicer.getStatement(node); if(this.aliases.containsKey(statement)){ variables = this.aliases.get(statement); } else{ variables = new LinkedList<String>(); this.aliases.put(new Integer(statement.getStartPosition()), variables); } variables.add(binding.getKey()); } return true; }
@SuppressWarnings("unchecked") @Override public Statement instrumentStart(final CodeSection codeSection, final AST nodeFactory) { final EclipseStatementCreationHelper helper = new EclipseStatementCreationHelper(nodeFactory); final MethodInvocation startInvocation = nodeFactory.newMethodInvocation(); startInvocation.setExpression(helper.getName("de", "uka", "ipd", "sdq", "beagle", "measurement", "kieker", "remote", "MeasurementCentral")); startInvocation.setName(nodeFactory.newSimpleName("startResourceDemand")); startInvocation.arguments().add(nodeFactory.newNumberLiteral("" + this.identifier.getIdOf(codeSection))); return nodeFactory.newExpressionStatement(startInvocation); }
@Override public Statement instrumentEnd(final CodeSection codeSection, final AST nodeFactory) { final EclipseStatementCreationHelper helper = new EclipseStatementCreationHelper(nodeFactory); final MethodInvocation endInvocation = nodeFactory.newMethodInvocation(); endInvocation.setExpression(helper.getName("de", "uka", "ipd", "sdq", "beagle", "measurement", "kieker", "remote", "MeasurementCentral")); endInvocation.setName(nodeFactory.newSimpleName("stopResourceDemand")); return nodeFactory.newExpressionStatement(endInvocation); }
@Override public boolean preNext(IfStatement curElement) { Statement thenStatement = curElement.getThenStatement(); Statement elseStatement = curElement.getElseStatement(); Expression condition = curElement.getExpression(); if (elseStatement == null) { compiler.println("opt " + condition.toString()); return true; } else { compiler.println("alt " + condition.toString()); thenStatement.accept(compiler); if (elseStatement instanceof IfStatement) { processAltStatement((IfStatement) elseStatement); } else { compiler.println("else"); elseStatement.accept(compiler); } return false; } }
private void processAltStatement(IfStatement statement) { Statement thenStatement = statement.getThenStatement(); Statement elseStatement = statement.getElseStatement(); Expression condition = statement.getExpression(); compiler.println("else " + condition.toString()); thenStatement.accept(compiler); if (elseStatement != null) { if (elseStatement instanceof IfStatement) { processAltStatement((IfStatement) elseStatement); } else { compiler.println("else"); elseStatement.accept(compiler); } } }
@Override public boolean preNext(Statement curElement) { switch (curElement.getNodeType()) { case ASTNode.WHILE_STATEMENT: exportWhile((WhileStatement) curElement); break; case ASTNode.FOR_STATEMENT: exportFor((ForStatement) curElement); break; case ASTNode.ENHANCED_FOR_STATEMENT: exportForEach((EnhancedForStatement) curElement); break; case ASTNode.DO_STATEMENT: exportDoWhileStatement((DoStatement) curElement); break; } return true; }
/** * Creates the corresponding statement for the method invocation, based on * the return type. * * @param declaration the method declaration where the invocation statement * is inserted * @param invocation the method invocation being encapsulated by the * resulting statement * @return the corresponding statement */ protected Statement createMethodInvocation(final MethodDeclaration declaration, final MethodInvocation invocation) { Assert.isNotNull(declaration); Assert.isNotNull(invocation); Statement statement= null; final Type type= declaration.getReturnType2(); if (type == null) statement= createExpressionStatement(invocation); else { if (type instanceof PrimitiveType) { final PrimitiveType primitive= (PrimitiveType) type; if (primitive.getPrimitiveTypeCode().equals(PrimitiveType.VOID)) statement= createExpressionStatement(invocation); else statement= createReturnStatement(invocation); } else statement= createReturnStatement(invocation); } return statement; }
public boolean visit(SwitchStatement node) { this.buffer.append("switch (");//$NON-NLS-1$ node.getExpression().accept(this); this.buffer.append(") ");//$NON-NLS-1$ this.buffer.append("{\n");//$NON-NLS-1$ this.indent++; for (Iterator it = node.statements().iterator(); it.hasNext(); ) { Statement s = (Statement) it.next(); s.accept(this); this.indent--; // incremented in visit(SwitchCase) } this.indent--; printIndent(); this.buffer.append("}\n");//$NON-NLS-1$ return false; }
private boolean isSingleControlStatementWithoutBlock() { List<Statement> statements= fDeclaration.getBody().statements(); int size= statements.size(); if (size != 1) return false; Statement statement= statements.get(size - 1); int nodeType= statement.getNodeType(); if (nodeType == ASTNode.IF_STATEMENT) { IfStatement ifStatement= (IfStatement) statement; return !(ifStatement.getThenStatement() instanceof Block) && !(ifStatement.getElseStatement() instanceof Block); } else if (nodeType == ASTNode.FOR_STATEMENT) { return !(((ForStatement)statement).getBody() instanceof Block); } else if (nodeType == ASTNode.WHILE_STATEMENT) { return !(((WhileStatement)statement).getBody() instanceof Block); } return false; }
private Statement getParentLoopBody(ASTNode node) { Statement stmt= null; ASTNode start= node; while (start != null && !(start instanceof ForStatement) && !(start instanceof DoStatement) && !(start instanceof WhileStatement) && !(start instanceof EnhancedForStatement) && !(start instanceof SwitchStatement)) { start= start.getParent(); } if (start instanceof ForStatement) { stmt= ((ForStatement)start).getBody(); } else if (start instanceof DoStatement) { stmt= ((DoStatement)start).getBody(); } else if (start instanceof WhileStatement) { stmt= ((WhileStatement)start).getBody(); } else if (start instanceof EnhancedForStatement) { stmt= ((EnhancedForStatement)start).getBody(); } if (start != null && start.getParent() instanceof LabeledStatement) { LabeledStatement labeledStatement= (LabeledStatement)start.getParent(); fEnclosingLoopLabel= labeledStatement.getLabel(); } return stmt; }
private Statement createAddQualifiedHashCode(IVariableBinding binding) { MethodInvocation invoc= fAst.newMethodInvocation(); invoc.setExpression(getThisAccessForHashCode(binding.getName())); invoc.setName(fAst.newSimpleName(METHODNAME_HASH_CODE)); InfixExpression expr= fAst.newInfixExpression(); expr.setOperator(Operator.EQUALS); expr.setLeftOperand(getThisAccessForHashCode(binding.getName())); expr.setRightOperand(fAst.newNullLiteral()); ConditionalExpression cexpr= fAst.newConditionalExpression(); cexpr.setThenExpression(fAst.newNumberLiteral("0")); //$NON-NLS-1$ cexpr.setElseExpression(invoc); cexpr.setExpression(parenthesize(expr)); return prepareAssignment(parenthesize(cexpr)); }
@Override protected void addMemberCheckNull(Object member, boolean addSeparator) { IfStatement ifStatement= fAst.newIfStatement(); ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(member, true, true), Operator.NOT_EQUALS, fAst.newNullLiteral())); Block thenBlock= fAst.newBlock(); flushBuffer(null); String[] arrayString= getContext().getTemplateParser().getBody(); for (int i= 0; i < arrayString.length; i++) { addElement(processElement(arrayString[i], member), thenBlock); } if (addSeparator) addElement(getContext().getTemplateParser().getSeparator(), thenBlock); flushBuffer(thenBlock); if (thenBlock.statements().size() == 1 && !getContext().isForceBlocks()) { ifStatement.setThenStatement((Statement)ASTNode.copySubtree(fAst, (ASTNode)thenBlock.statements().get(0))); } else { ifStatement.setThenStatement(thenBlock); } toStringMethod.getBody().statements().add(ifStatement); }
private Statement createAddArrayHashCode(IVariableBinding binding) { MethodInvocation invoc= fAst.newMethodInvocation(); if (JavaModelUtil.is50OrHigher(fRewrite.getCu().getJavaProject())) { invoc.setName(fAst.newSimpleName(METHODNAME_HASH_CODE)); invoc.setExpression(getQualifiedName(JAVA_UTIL_ARRAYS)); invoc.arguments().add(getThisAccessForHashCode(binding.getName())); } else { invoc.setName(fAst.newSimpleName(METHODNAME_HASH_CODE)); final IJavaElement element= fType.getJavaElement(); if (element != null && !"".equals(element.getElementName())) //$NON-NLS-1$ invoc.setExpression(fAst.newSimpleName(element.getElementName())); invoc.arguments().add(getThisAccessForHashCode(binding.getName())); ITypeBinding type= binding.getType().getElementType(); if (!Bindings.isVoidType(type)) { if (!type.isPrimitive() || binding.getType().getDimensions() >= 2) type= fAst.resolveWellKnownType(JAVA_LANG_OBJECT); if (!fCustomHashCodeTypes.contains(type)) fCustomHashCodeTypes.add(type); } } return prepareAssignment(invoc); }
private Statement createOuterComparison() { MethodInvocation outer1= fAst.newMethodInvocation(); outer1.setName(fAst.newSimpleName(METHODNAME_OUTER_TYPE)); MethodInvocation outer2= fAst.newMethodInvocation(); outer2.setName(fAst.newSimpleName(METHODNAME_OUTER_TYPE)); outer2.setExpression(fAst.newSimpleName(VARIABLE_NAME_EQUALS_CASTED)); MethodInvocation outerEql= fAst.newMethodInvocation(); outerEql.setName(fAst.newSimpleName(METHODNAME_EQUALS)); outerEql.setExpression(outer1); outerEql.arguments().add(outer2); PrefixExpression not= fAst.newPrefixExpression(); not.setOperand(outerEql); not.setOperator(PrefixExpression.Operator.NOT); IfStatement notEqNull= fAst.newIfStatement(); notEqNull.setExpression(not); notEqNull.setThenStatement(getThenStatement(getReturnFalse())); return notEqNull; }
/** * List of VariableDeclaration of variables which are read in <code>selectedNodes</code>. * * @param maxVariableId Maximum number of variable declarations block * @param selectedNodes The selectedNodes * @return List of VariableDeclaration */ protected List<VariableDeclaration> getVariableDeclarationReadsInside(Statement[] selectedNodes, int maxVariableId) { ArrayList<VariableDeclaration> result= new ArrayList<VariableDeclaration>(); if (!fIsNewContext) return result; IVariableBinding[] reads= getReads(selectedNodes, maxVariableId); for (int i= 0; i < reads.length; i++) { IVariableBinding read= reads[i]; if (!read.isField()) { ASTNode readDecl= getRootNode().findDeclaringNode(read); if (readDecl instanceof VariableDeclaration) { result.add((VariableDeclaration) readDecl); } } } return result; }
private ASTNode prepareLambdaBody(Block body, List<Statement> 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; } } } return lambdaBody; }
private Statement createMultiArrayComparison(String name) { MethodInvocation invoc= fAst.newMethodInvocation(); invoc.setName(fAst.newSimpleName(METHODNAME_DEEP_EQUALS)); invoc.setExpression(getQualifiedName(JAVA_UTIL_ARRAYS)); invoc.arguments().add(getThisAccessForEquals(name)); invoc.arguments().add(getOtherAccess(name)); PrefixExpression pe= fAst.newPrefixExpression(); pe.setOperator(PrefixExpression.Operator.NOT); pe.setOperand(invoc); IfStatement ifSt= fAst.newIfStatement(); ifSt.setExpression(pe); ifSt.setThenStatement(getThenStatement(getReturnFalse())); return ifSt; }
@Override protected void addMemberCheckNull(Object member, boolean addSeparator) { IfStatement ifStatement= fAst.newIfStatement(); ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(member, true, true), Operator.NOT_EQUALS, fAst.newNullLiteral())); Block thenBlock= fAst.newBlock(); flushTemporaryExpression(); String[] arrayString= getContext().getTemplateParser().getBody(); for (int i= 0; i < arrayString.length; i++) { addElement(processElement(arrayString[i], member), thenBlock); } if (addSeparator) addElement(getContext().getTemplateParser().getSeparator(), thenBlock); flushTemporaryExpression(); if (thenBlock.statements().size() == 1 && !getContext().isForceBlocks()) { ifStatement.setThenStatement((Statement)ASTNode.copySubtree(fAst, (ASTNode)thenBlock.statements().get(0))); } else { ifStatement.setThenStatement(thenBlock); } toStringMethod.getBody().statements().add(ifStatement); }
private Statement makeSelfAssignment(ASTRewrite rewrite, ReturnValueResolutionVisitor rvrFinder) { AST rootNode = rewrite.getAST(); Assignment newAssignment = rootNode.newAssignment(); Expression leftExpression = rvrFinder.badMethodInvocation.getExpression(); while (leftExpression instanceof MethodInvocation) { leftExpression = ((MethodInvocation) leftExpression).getExpression(); } newAssignment.setLeftHandSide((Expression) rewrite.createCopyTarget(leftExpression)); newAssignment.setRightHandSide((Expression) rewrite.createCopyTarget( rvrFinder.badMethodInvocation)); return rootNode.newExpressionStatement(newAssignment); }
@SuppressWarnings("unchecked") @Override public boolean visit(SwitchStatement node) { if (badSwitchStatement != null) { return false; } List<Statement> switchStatements = node.statements(); for (Statement statement : switchStatements) { if (statement instanceof SwitchCase) { if (((SwitchCase) statement).getExpression() == null) { return true; // this one has a default case...skip it } } } badSwitchStatement = node; return false; }
@SuppressWarnings("unchecked") private Statement makeIfStatement(ASTRewrite rewrite, ReturnValueResolutionVisitor rvrFinder, boolean b) { AST rootNode = rewrite.getAST(); IfStatement ifStatement = rootNode.newIfStatement(); Expression expression = makeIfExpression(rewrite, rvrFinder, b); ifStatement.setExpression(expression); // the block surrounds the inner statement with {} Block thenBlock = rootNode.newBlock(); Statement thenStatement = makeExceptionalStatement(rootNode); thenBlock.statements().add(thenStatement); ifStatement.setThenStatement(thenBlock); return ifStatement; }
public static ASTNode getCopyOfInner(ASTRewrite rewrite, ASTNode statement, boolean toControlStatementBody) { if (statement.getNodeType() == ASTNode.BLOCK) { Block block= (Block) statement; List<Statement> innerStatements= block.statements(); int nStatements= innerStatements.size(); if (nStatements == 1) { return rewrite.createCopyTarget(innerStatements.get(0)); } else if (nStatements > 1) { if (toControlStatementBody) { return rewrite.createCopyTarget(block); } ListRewrite listRewrite= rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); ASTNode first= innerStatements.get(0); ASTNode last= innerStatements.get(nStatements - 1); return listRewrite.createCopyTarget(first, last); } return null; } else { return rewrite.createCopyTarget(statement); } }
public IBinding[] getDeclarationsAfter(int offset, int flags) { try { org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(fRoot, offset, 0); ASTNode node= finder.getCoveringNode(); if (node == null) { return null; } ASTNode declaration= ASTResolving.findParentStatement(node); while (declaration instanceof Statement && declaration.getNodeType() != ASTNode.BLOCK) { declaration= declaration.getParent(); } if (declaration instanceof Block) { DefaultBindingRequestor requestor= new DefaultBindingRequestor(); DeclarationsAfterVisitor visitor= new DeclarationsAfterVisitor(node.getStartPosition(), flags, requestor); declaration.accept(visitor); List<IBinding> result= requestor.getResult(); return result.toArray(new IBinding[result.size()]); } return NO_BINDING; } finally { clearLists(); } }
@SuppressWarnings("unchecked") private ClassInstanceCreation findMethodInitialization(SimpleName collectionName, MethodDeclaration methodDeclaration, boolean isField) throws EnumParsingException { // Look in this method for an initialization of the variable collectionName // This handles initialization of a field (i.e. something w/o a declaration) // and a local variable (i.e. something with a declaration) List<Statement> statements = methodDeclaration.getBody().statements(); for (Statement statement : statements) { if (!isField && statement instanceof VariableDeclarationStatement) { return findClassInstanceCreationInDeclaration(collectionName, (VariableDeclarationStatement) statement); } else if (isField && statement instanceof ExpressionStatement) { return findClassInstanceCreationInAssignment(collectionName, (ExpressionStatement) statement); } } throw new EnumParsingException(); }