@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 RastNode createMethod(String methodSignature, HasChildrenNodes parent, String sourceFilePath, boolean constructor, MethodDeclaration ast) { String methodName = ast.isConstructor() ? "" : ast.getName().getIdentifier(); RastNode rastNode = new RastNode(++nodeCounter); rastNode.setType(ast.getClass().getSimpleName()); Block body = ast.getBody(); int bodyStart; int bodyLength; if (body == null) { rastNode.addStereotypes(Stereotype.ABSTRACT); bodyStart = ast.getStartPosition() + ast.getLength(); bodyLength = 0; } else { bodyStart = body.getStartPosition(); bodyLength = body.getLength(); } rastNode.setLocation(new Location(sourceFilePath, ast.getStartPosition(), ast.getStartPosition() + ast.getLength(), bodyStart, bodyStart + bodyLength)); rastNode.setLocalName(methodSignature); rastNode.setSimpleName(methodName); parent.addNode(rastNode); keyMap.put(JavaParser.getKey(rastNode), rastNode); return rastNode; }
/** * Method that check the method's body to detect some * connection between them * @author Mariana Azevedo * @since 20/01/2016 * @param firstMethod * @param secondMethod */ private void checkMethodsBody(MethodDeclaration firstMethod, MethodDeclaration secondMethod) { if (firstMethod != null && secondMethod != null){ Block firstMethodBody = firstMethod.getBody(); Block secondMethodBody = secondMethod.getBody(); if (firstMethodBody != null && secondMethodBody != null){ for (String attribute : listOfAttributes){ if (firstMethodBody.toString().contains(attribute) && secondMethodBody.toString().contains(attribute)){ numDirectConnections++; } } } } }
/** * 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++; } } } } } }
/** * Method to get the number of methods with indirect connections. * @author Mariana Azevedo * @since 13/07/2014 * @param methodsWithDirectConn * @param itMethods */ private void getNumberOfIndirectConnections(List<MethodDeclaration> methodsWithDirectConn, Iterator<MethodDeclaration> itMethods){ int i=0; while (itMethods.hasNext()){ MethodDeclaration firstMethod = itMethods.next(); if (firstMethod != null){ Block firstMethodBody = firstMethod.getBody(); if (firstMethodBody != null){ SimpleName methodDeclaration = methodsWithDirectConn.get(i).getName(); if (firstMethodBody.toString().contains(methodDeclaration.toString())){ numIndirectConnections++; } } } } }
private Block createWithMethodBody(AST ast, BuilderField builderField) { String originalFieldName = builderField.getOriginalFieldName(); String builderFieldName = builderField.getBuilderFieldName(); Block newBlock = ast.newBlock(); ReturnStatement builderReturnStatement = ast.newReturnStatement(); builderReturnStatement.setExpression(ast.newThisExpression()); Assignment newAssignment = ast.newAssignment(); FieldAccess fieldAccess = ast.newFieldAccess(); fieldAccess.setExpression(ast.newThisExpression()); fieldAccess.setName(ast.newSimpleName(originalFieldName)); newAssignment.setLeftHandSide(fieldAccess); newAssignment.setRightHandSide(ast.newSimpleName(builderFieldName)); newBlock.statements().add(ast.newExpressionStatement(newAssignment)); newBlock.statements().add(builderReturnStatement); return newBlock; }
private Block createWithMethodBody(AST ast, String originalFieldName, String builderFieldName) { Block newBlock = ast.newBlock(); ReturnStatement builderReturnStatement = ast.newReturnStatement(); builderReturnStatement.setExpression(ast.newThisExpression()); Assignment newAssignment = ast.newAssignment(); FieldAccess fieldAccess = ast.newFieldAccess(); fieldAccess.setExpression(ast.newThisExpression()); fieldAccess.setName(ast.newSimpleName(originalFieldName)); newAssignment.setLeftHandSide(fieldAccess); newAssignment.setRightHandSide(ast.newSimpleName(builderFieldName)); newBlock.statements().add(ast.newExpressionStatement(newAssignment)); newBlock.statements().add(builderReturnStatement); return newBlock; }
private MethodDeclaration createNewWithMethod(AST ast, String fieldName, Block newBlock, SingleVariableDeclaration methodParameterDeclaration, TypeDeclaration builderType, BuilderField builderField) { MethodDeclaration builderMethod = ast.newMethodDeclaration(); builderMethod.setName(ast.newSimpleName(builderClassMethodNameGeneratorService.build(fieldName))); builderMethod.setReturnType2(ast.newSimpleType( ast.newName(builderType.getName().getIdentifier()))); builderMethod.setBody(newBlock); builderMethod.parameters().add(methodParameterDeclaration); javadocAdder.addJavadocForWithMethod(ast, fieldName, builderMethod); if (preferencesManager.getPreferenceValue(ADD_NONNULL_ON_RETURN)) { markerAnnotationAttacher.attachNonNull(ast, builderMethod); } builderMethod.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD)); return builderMethod; }
public Block createReturnBlock(AST ast, TypeDeclaration builderType, String withName, String parameterName) { Block builderMethodBlock = ast.newBlock(); ReturnStatement returnStatement = ast.newReturnStatement(); ClassInstanceCreation newClassInstanceCreation = ast.newClassInstanceCreation(); newClassInstanceCreation.setType(ast.newSimpleType(ast.newName(builderType.getName().toString()))); MethodInvocation withMethodInvocation = ast.newMethodInvocation(); withMethodInvocation.setExpression(newClassInstanceCreation); withMethodInvocation.setName(ast.newSimpleName(withName)); withMethodInvocation.arguments().add(ast.newSimpleName(parameterName)); returnStatement.setExpression(withMethodInvocation); builderMethodBlock.statements().add(returnStatement); return builderMethodBlock; }
public void addBuilderMethodToCompilationUnit(CompilationUnitModificationDomain modificationDomain, TypeDeclaration builderType, StagedBuilderProperties currentStage) { AST ast = modificationDomain.getAst(); ListRewrite listRewrite = modificationDomain.getListRewrite(); BuilderField firstField = currentStage.getNamedVariableDeclarationField().get(0); StagedBuilderProperties nextStage = currentStage.getNextStage().orElse(currentStage); MethodDeclaration staticWithMethod = stagedBuilderWithMethodDefiniationCreatorFragment.createNewWithMethod(ast, firstField, nextStage); staticWithMethod.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD)); String parameterName = firstField.getBuilderFieldName(); String withMethodName = staticWithMethod.getName().toString(); Block block = newBuilderAndWithMethodCallCreationFragment.createReturnBlock(ast, builderType, withMethodName, parameterName); javadocAdder.addJavadocForWithBuilderMethod(ast, builderType.getName().toString(), parameterName, staticWithMethod); staticWithMethod.setBody(block); listRewrite.insertLast(staticWithMethod, null); }
@Override protected void handleOneMany(ASTNode[] replacements, TextEditGroup description) { AST ast= fToReplace[0].getAST(); // to replace == 1, but more than one replacement. Have to check if we // need to insert a block to not change structure if (ASTNodes.isControlStatementBody(fDescriptor)) { Block block= ast.newBlock(); ListRewrite statements= fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); for (int i= 0; i < replacements.length; i++) { statements.insertLast(replacements[i], description); } fRewrite.replace(fToReplace[0], block, description); } else { ListRewrite container= fRewrite.getListRewrite(fToReplace[0].getParent(), (ChildListPropertyDescriptor)fDescriptor); container.replace(fToReplace[0], replacements[0], description); for (int i= 1; i < replacements.length; i++) { container.insertAfter(replacements[i], replacements[i - 1], description); } } }
@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; }
/** * @param rewrite * @param declaration */ private void annotateMethods(ASTRewrite rewrite, TypeDeclaration declaration) { MethodDeclaration[] methods = declaration.getMethods(); for (int i = 0; i < methods.length; i++) { MethodDeclaration methodDeclaration = methods[i]; annotateMethodReturnType(rewrite, methodDeclaration); annotateMethodParameters(rewrite, methodDeclaration); DefaultingVisitor visitor = new DefaultingVisitor(); visitor.rewrite = rewrite; Block body = methodDeclaration.getBody(); if (body != null) { body.accept(visitor); } } }
private boolean isEquivalent(IMethod method, IMethod otherMethod, Optional<IProgressMonitor> monitor) throws JavaModelException { monitor.ifPresent(m -> m.beginTask("Checking method equivalence ...", 2)); MethodDeclaration methodDeclaration = this.getMethodDeclaration(method, monitor.map(m -> new SubProgressMonitor(m, 1))); MethodDeclaration otherMethodDeclaration = this.getMethodDeclaration(otherMethod, monitor.map(m -> new SubProgressMonitor(m, 1))); monitor.ifPresent(IProgressMonitor::done); Block methodDeclarationBody = methodDeclaration.getBody(); Block otherMethodDeclarationBody = otherMethodDeclaration.getBody(); boolean match = methodDeclarationBody.subtreeMatch(new ASTMatcher(), otherMethodDeclarationBody); return match; }
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; }
@SuppressWarnings("unchecked") //node.parameters() liefert Liste von SingleVariableDeclarations, siehe API doc //node.modifiers() liefert List von Modifier zurueck @Override public boolean visit(final MethodDeclaration node) { if( node.getName().getIdentifier().equals(fMethodName) && hasParameters(node.parameters()) && hasModifiers(node.modifiers()) && hasReturnType(node)) { for(IEvaluable<Block> expr : fExpressions) { if( !expr.eval(node.getBody()) ) { setMatch(false); return true; } } //gesuchte Methode gefunden, und (evtl.) Subexpression ok, nur dann ok setMatch(true); return true; } return true; }
/** * Teste zuerst CommonSyntax. */ public boolean eval(final Block block) { boolean evalOk = false; ResultVisitor visitor = createResultVisitor(); block.accept(visitor); evalOk = visitor.hasMatch(); if( evalOk ) { // // TODO hier CommonSyntax testen, wenn implementiert wird // evalOk = true; } return evalOk; }
@Override protected void handleOneMany(ASTNode[] replacements, TextEditGroup description) { AST ast = fToReplace[0].getAST(); // to replace == 1, but more than one replacement. Have to check if we // need to insert a block to not change structure if (ASTNodes.isControlStatementBody(fDescriptor)) { Block block = ast.newBlock(); ListRewrite statements = fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); for (int i = 0; i < replacements.length; i++) { statements.insertLast(replacements[i], description); } fRewrite.replace(fToReplace[0], block, description); } else { ListRewrite container = fRewrite.getListRewrite( fToReplace[0].getParent(), (ChildListPropertyDescriptor) fDescriptor); container.replace(fToReplace[0], replacements[0], description); for (int i = 1; i < replacements.length; i++) { container.insertAfter(replacements[i], replacements[i - 1], description); } } }
public static CompilationUnitRewriteOperationsFix createIndirectAccessToStaticFix( CompilationUnit compilationUnit, IProblemLocation problem) { if (!isIndirectStaticAccess(problem)) return null; ToStaticAccessOperation operations[] = createToStaticAccessOperations( compilationUnit, new HashMap<ASTNode, Block>(), problem, false); if (operations == null) return null; String label = Messages.format( FixMessages.CodeStyleFix_ChangeStaticAccess_description, operations[0].getAccessorName()); return new CodeStyleFix( label, compilationUnit, new CompilationUnitRewriteOperation[] {operations[0]}); }
/** {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { ASTRewrite rewrite = cuRewrite.getASTRewrite(); String label; if (fBodyProperty == IfStatement.THEN_STATEMENT_PROPERTY) { label = FixMessages.CodeStyleFix_ChangeIfToBlock_desription; } else if (fBodyProperty == IfStatement.ELSE_STATEMENT_PROPERTY) { label = FixMessages.CodeStyleFix_ChangeElseToBlock_description; } else { label = FixMessages.CodeStyleFix_ChangeControlToBlock_description; } TextEditGroup group = createTextEditGroup(label, cuRewrite); ASTNode moveTarget = rewrite.createMoveTarget(fBody); Block replacingBody = cuRewrite.getRoot().getAST().newBlock(); replacingBody.statements().add(moveTarget); rewrite.set(fControlStatement, fBodyProperty, replacingBody, group); }
private void addNewConstructorToSubclass( AbstractTypeDeclaration subclass, CompilationUnitRewrite cuRewrite) { AST ast = subclass.getAST(); MethodDeclaration newConstructor = ast.newMethodDeclaration(); newConstructor.setName(ast.newSimpleName(subclass.getName().getIdentifier())); newConstructor.setConstructor(true); newConstructor.setJavadoc(null); newConstructor .modifiers() .addAll(ASTNodeFactory.newModifiers(ast, getAccessModifier(subclass))); newConstructor.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); Block body = ast.newBlock(); newConstructor.setBody(body); SuperConstructorInvocation superCall = ast.newSuperConstructorInvocation(); addArgumentsToNewSuperConstructorCall(superCall, cuRewrite); body.statements().add(superCall); String msg = RefactoringCoreMessages.ChangeSignatureRefactoring_add_constructor; TextEditGroup description = cuRewrite.createGroupDescription(msg); cuRewrite .getASTRewrite() .getListRewrite(subclass, subclass.getBodyDeclarationsProperty()) .insertFirst(newConstructor, description); // TODO use AbstractTypeDeclaration }
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 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); }
private void replaceSelectedExpressionWithTempDeclaration() throws CoreException { ASTRewrite rewrite = fCURewrite.getASTRewrite(); Expression selectedExpression = getSelectedExpression().getAssociatedExpression(); // whole expression selected Expression initializer = (Expression) rewrite.createMoveTarget(selectedExpression); ASTNode replacement = createTempDeclaration(initializer); // creates a VariableDeclarationStatement ExpressionStatement parent = (ExpressionStatement) selectedExpression.getParent(); if (ASTNodes.isControlStatementBody(parent.getLocationInParent())) { Block block = rewrite.getAST().newBlock(); block.statements().add(replacement); replacement = block; } rewrite.replace( parent, replacement, fCURewrite.createGroupDescription( RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable)); }
public static RefactoringStatus checkMethodSyntaxErrors( int selectionStart, int selectionLength, CompilationUnit cuNode, String invalidSelectionMessage) { SelectionAnalyzer analyzer = new SelectionAnalyzer( Selection.createFromStartLength(selectionStart, selectionLength), true); cuNode.accept(analyzer); ASTNode coveringNode = analyzer.getLastCoveringNode(); if (!(coveringNode instanceof Block) || !(coveringNode.getParent() instanceof MethodDeclaration)) return RefactoringStatus.createFatalErrorStatus(invalidSelectionMessage); if (ASTNodes.getMessages(coveringNode, ASTNodes.NODE_ONLY).length == 0) return RefactoringStatus.createFatalErrorStatus(invalidSelectionMessage); MethodDeclaration methodDecl = (MethodDeclaration) coveringNode.getParent(); String message = Messages.format( RefactoringCoreMessages.CodeRefactoringUtil_error_message, BasicElementLabels.getJavaElementName(methodDecl.getName().getIdentifier())); return RefactoringStatus.createFatalErrorStatus(message); }
/** * Helper to generate an iterator based <code>for</code> loop to iterate over an {@link Iterable}. * * @param ast the {@link AST} instance to rewrite the loop to * @return the complete {@link ASTRewrite} object */ private ASTRewrite generateIteratorBasedForRewrite(AST ast) { ASTRewrite rewrite = ASTRewrite.create(ast); ForStatement loopStatement = ast.newForStatement(); ITypeBinding loopOverType = extractElementType(ast); SimpleName loopVariableName = resolveLinkedVariableNameWithProposals(rewrite, "iterator", null, true); // $NON-NLS-1$ loopStatement.initializers().add(getIteratorBasedForInitializer(rewrite, loopVariableName)); MethodInvocation loopExpression = ast.newMethodInvocation(); loopExpression.setName(ast.newSimpleName("hasNext")); // $NON-NLS-1$ SimpleName expressionName = ast.newSimpleName(loopVariableName.getIdentifier()); addLinkedPosition( rewrite.track(expressionName), LinkedPositionGroup.NO_STOP, expressionName.getIdentifier()); loopExpression.setExpression(expressionName); loopStatement.setExpression(loopExpression); Block forLoopBody = ast.newBlock(); Assignment assignResolvedVariable = getIteratorBasedForBodyAssignment(rewrite, loopOverType, loopVariableName); forLoopBody.statements().add(ast.newExpressionStatement(assignResolvedVariable)); forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite)); loopStatement.setBody(forLoopBody); rewrite.replace(fCurrentNode, loopStatement, null); return rewrite; }
/** * Helper to generate an index based <code>for</code> loop to iterate over a {@link List} * implementation. * * @param ast the current {@link AST} instance to generate the {@link ASTRewrite} for * @return an applicable {@link ASTRewrite} instance */ private ASTRewrite generateIndexBasedForRewrite(AST ast) { ASTRewrite rewrite = ASTRewrite.create(ast); ForStatement loopStatement = ast.newForStatement(); SimpleName loopVariableName = resolveLinkedVariableNameWithProposals(rewrite, "int", null, true); // $NON-NLS-1$ loopStatement.initializers().add(getForInitializer(ast, loopVariableName)); MethodInvocation listSizeExpression = ast.newMethodInvocation(); listSizeExpression.setName(ast.newSimpleName("size")); // $NON-NLS-1$ Expression listExpression = (Expression) rewrite.createCopyTarget(fCurrentExpression); listSizeExpression.setExpression(listExpression); loopStatement.setExpression( getLinkedInfixExpression( rewrite, loopVariableName.getIdentifier(), listSizeExpression, InfixExpression.Operator.LESS)); loopStatement .updaters() .add(getLinkedIncrementExpression(rewrite, loopVariableName.getIdentifier())); Block forLoopBody = ast.newBlock(); forLoopBody .statements() .add(ast.newExpressionStatement(getIndexBasedForBodyAssignment(rewrite, loopVariableName))); forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite)); loopStatement.setBody(forLoopBody); rewrite.replace(fCurrentNode, loopStatement, null); return rewrite; }
/** * Retrieves name proposals for a fresh local variable. * * @param basename the basename of the proposals * @param excludedName a name that cannot be used for the variable; <code>null</code> if none * @return an array of proposal strings */ private String[] getVariableNameProposals(String basename, String excludedName) { ASTNode surroundingBlock = fCurrentNode; while ((surroundingBlock = surroundingBlock.getParent()) != null) { if (surroundingBlock instanceof Block) { break; } } Collection<String> localUsedNames = new ScopeAnalyzer((CompilationUnit) fCurrentExpression.getRoot()) .getUsedVariableNames( surroundingBlock.getStartPosition(), surroundingBlock.getLength()); if (excludedName != null) { localUsedNames.add(excludedName); } String[] names = StubUtility.getLocalNameSuggestions( getCompilationUnit().getJavaProject(), basename, 0, localUsedNames.toArray(new String[localUsedNames.size()])); return names; }
@Override public void insertIfStatement(IfStatement ifStmt, Block thenBlock) { // when stmt declares a local variable (see RearrangeStrategy.create(..)) we need to move // all // subsequent statements into the then-block to ensure that the existing declared local is // visible: List<ASTNode> blockStmts = this.block.statements(); int stmtIdx = blockStmts.indexOf(this.origStmt); int lastIdx = blockStmts.size() - 1; if (stmtIdx != -1 && stmtIdx < lastIdx) { thenBlock .statements() .add( this.blockRewrite.createMoveTarget( blockStmts.get(stmtIdx + 1), blockStmts.get(lastIdx), null, this.group)); } super.insertIfStatement(ifStmt, thenBlock); }
private SimpleName[] getAllReferences(Block body) { SimpleName[] names = LinkedNodeFinder.findByProblems(body, fOriginalNode); if (names == null) { return new SimpleName[] {fOriginalNode}; } if (names.length > 1) { Arrays.sort( names, new Comparator<SimpleName>() { public int compare(SimpleName s1, SimpleName s2) { return s1.getStartPosition() - s2.getStartPosition(); } }); } return names; }
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 VariableReference retrieveVariableReference( ClassInstanceCreation instanceCreation, Class<?> varType) { if ((instanceCreation.getParent() instanceof MethodInvocation) || (instanceCreation.getParent() instanceof ClassInstanceCreation)) { VariableReference result = new ValidVariableReference( testCase.getReference(), retrieveTypeClass(instanceCreation.getType())); nestedCallResults.push(result); return result; } if ((instanceCreation.getParent() instanceof ExpressionStatement) && (instanceCreation.getParent().getParent() instanceof Block)) { if (varType == null) { varType = retrieveTypeClass(instanceCreation); } VariableReference varRef = new ValidVariableReference( testCase.getReference(), varType); return varRef; } return retrieveVariableReference(instanceCreation.getParent(), varType); }
@Override public boolean visit(final Block node) { assert this.childToSearch.getParent() == node; final StructuralPropertyDescriptor propertyToInsertIn = this.childToSearch.getLocationInParent(); assert propertyToInsertIn.isChildListProperty(); @SuppressWarnings("unchecked") final List<Statement> listToInsertIn = (List<Statement>) node.getStructuralProperty(propertyToInsertIn); final int index = listToInsertIn.indexOf(this.childToSearch); // It’s a child of {@code node}, so it must be a Statement AstStatementInserter.this.markedStatement = (Statement) this.childToSearch; AstStatementInserter.this.insertionList = Optional.of(listToInsertIn); AstStatementInserter.this.markerIndex = index; this.success = true; return false; }
private static void addToStaticAccessOperations(CompilationUnit compilationUnit, IProblemLocation[] problems, boolean changeNonStaticAccessToStatic, boolean changeIndirectStaticAccessToDirect, List<CompilationUnitRewriteOperation> result) { if (!changeNonStaticAccessToStatic && !changeIndirectStaticAccessToDirect) return; HashMap<ASTNode, Block> createdBlocks= new HashMap<ASTNode, Block>(); for (int i= 0; i < problems.length; i++) { IProblemLocation problem= problems[i]; boolean isNonStaticAccess= changeNonStaticAccessToStatic && isNonStaticAccess(problem); boolean isIndirectStaticAccess= changeIndirectStaticAccessToDirect && isIndirectStaticAccess(problem); if (isNonStaticAccess || isIndirectStaticAccess) { ToStaticAccessOperation[] nonStaticAccessInformation= createToStaticAccessOperations(compilationUnit, createdBlocks, problem, true); if (nonStaticAccessInformation != null) { ToStaticAccessOperation op= nonStaticAccessInformation[0]; Expression qualifier= op.fQualifier; if (!(qualifier instanceof MethodInvocation) || !isMethodArgument(qualifier)) { result.add(op); } } } } }
/** * Returns the reserved identifiers in the method to move. * * @return the reserved identifiers * @throws JavaModelException * if the method declaration could not be found */ protected String[] computeReservedIdentifiers() throws JavaModelException { final List<String> names= new ArrayList<String>(); final MethodDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(fMethod, fSourceRewrite.getRoot()); if (declaration != null) { final List<SingleVariableDeclaration> parameters= declaration.parameters(); VariableDeclaration variable= null; for (int index= 0; index < parameters.size(); index++) { variable= parameters.get(index); names.add(variable.getName().getIdentifier()); } final Block body= declaration.getBody(); if (body != null) { final IBinding[] bindings= new ScopeAnalyzer(fSourceRewrite.getRoot()).getDeclarationsAfter(body.getStartPosition(), ScopeAnalyzer.VARIABLES); for (int index= 0; index < bindings.length; index++) names.add(bindings[index].getName()); } } final String[] result= new String[names.size()]; names.toArray(result); return result; }
private void addNewConstructorToSubclass(AbstractTypeDeclaration subclass, CompilationUnitRewrite cuRewrite) { AST ast= subclass.getAST(); MethodDeclaration newConstructor= ast.newMethodDeclaration(); newConstructor.setName(ast.newSimpleName(subclass.getName().getIdentifier())); newConstructor.setConstructor(true); newConstructor.setJavadoc(null); newConstructor.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getAccessModifier(subclass))); newConstructor.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); Block body= ast.newBlock(); newConstructor.setBody(body); SuperConstructorInvocation superCall= ast.newSuperConstructorInvocation(); addArgumentsToNewSuperConstructorCall(superCall, cuRewrite); body.statements().add(superCall); String msg= RefactoringCoreMessages.ChangeSignatureRefactoring_add_constructor; TextEditGroup description= cuRewrite.createGroupDescription(msg); cuRewrite.getASTRewrite().getListRewrite(subclass, subclass.getBodyDeclarationsProperty()).insertFirst(newConstructor, description); // TODO use AbstractTypeDeclaration }
@SuppressWarnings("unchecked") private static TryStatement findLastTryStatementUsingVariable(SimpleName variable) { // looks for the last try statement that has a reference to the variable referred to // by the included simpleName. // If we can't find such a try block, we give up trying to fix Block parentBlock = TraversalUtil.findClosestAncestor(variable, Block.class); List<Statement> statements = parentBlock.statements(); for (int i = statements.size() - 1; i >= 0; i--) { Statement s = statements.get(i); if (s instanceof TryStatement) { TryStatement tryStatement = (TryStatement) s; if (tryRefersToVariable(tryStatement, variable)) { return tryStatement; } } } return null; }
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; }