public void testBug128818() throws Exception { IPackageFragment pack1 = this.sourceFolder.createPackageFragment("test1", false, null); StringBuffer buf = new StringBuffer(); buf.append("function foo() {\n"); buf.append(" if (true) {\n"); buf.append(" } // comment\n"); buf.append(" else\n"); buf.append(" return;\n"); buf.append("}\n"); IJavaScriptUnit cu = pack1.createCompilationUnit("E.js", buf.toString(), false, null); JavaScriptUnit astRoot = createAST3(cu); ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST()); AST ast = astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); FunctionDeclaration function = findMethodDeclaration(astRoot, "foo"); IfStatement statement = (IfStatement) function.getBody().statements().get(0); rewrite.set(statement, IfStatement.ELSE_STATEMENT_PROPERTY, ast.newBlock(), null); String preview = evaluateRewrite(cu, rewrite); buf = new StringBuffer(); buf.append("function foo() {\n"); buf.append(" if (true) {\n"); buf.append(" } // comment\n"); buf.append(" else {\n"); buf.append("}\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); }
public void testCatchClause() throws Exception { IPackageFragment pack1 = this.sourceFolder.createPackageFragment("test1", false, null); StringBuffer buf = new StringBuffer(); buf.append("function foo() {\n"); buf.append(" try {\n"); buf.append(" } catch (e) {\n"); buf.append(" }\n"); buf.append("}\n"); IJavaScriptUnit cu = pack1.createCompilationUnit("E.js", buf.toString(), false, null); JavaScriptUnit astRoot = createAST(cu); ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST()); AST ast = astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); FunctionDeclaration methodDecl = findMethodDeclaration(astRoot, "foo"); Block block = methodDecl.getBody(); List statements = block.statements(); assertTrue("Number of statements not 3", statements.size() == 1); List catchClauses = ((TryStatement) statements.get(0)).catchClauses(); assertTrue("Number of catchClauses not 1", catchClauses.size() == 1); { // change exception type CatchClause clause = (CatchClause) catchClauses.get(0); SingleVariableDeclaration exception = clause.getException(); SingleVariableDeclaration newException = ast.newSingleVariableDeclaration(); newException.setName(ast.newSimpleName("ex")); rewrite.replace(exception, newException, null); } { // change body CatchClause clause = (CatchClause) catchClauses.get(0); Block body = clause.getBody(); Block newBody = ast.newBlock(); ReturnStatement returnStatement = ast.newReturnStatement(); newBody.statements().add(returnStatement); rewrite.replace(body, newBody, null); } String preview = evaluateRewrite(cu, rewrite); buf = new StringBuffer(); buf.append("function foo() {\n"); buf.append(" try {\n"); buf.append(" } catch (ex) {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); }