Ejemplo n.º 1
0
 /*
  * @see ASTVisitor#visit(ConditionalExpression)
  */
 public boolean visit(ConditionalExpression node) {
   node.getExpression().accept(this);
   this.fBuffer.append("?"); // $NON-NLS-1$
   node.getThenExpression().accept(this);
   this.fBuffer.append(":"); // $NON-NLS-1$
   node.getElseExpression().accept(this);
   return false;
 }
  /** @deprecated using deprecated code */
  public void testConditionalExpression() throws Exception {
    IPackageFragment pack1 = this.sourceFolder.createPackageFragment("test1", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("    function foo() {\n");
    buf.append("        i= (k == 0) ? 1 : 2;\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);
    //		TypeDeclaration type= findTypeDeclaration(astRoot, "E");
    FunctionDeclaration methodDecl = findMethodDeclaration(astRoot, "foo");
    Block block = methodDecl.getBody();
    List statements = block.statements();
    assertTrue("Number of statements not 1", statements.size() == 1);
    { // change compare expression, then expression & else expression
      ExpressionStatement stmt = (ExpressionStatement) statements.get(0);
      Assignment assignment = (Assignment) stmt.getExpression();
      ConditionalExpression condExpression = (ConditionalExpression) assignment.getRightHandSide();

      BooleanLiteral literal = ast.newBooleanLiteral(true);
      rewrite.replace(condExpression.getExpression(), literal, null);

      SimpleName newThenExpre = ast.newSimpleName("x");
      rewrite.replace(condExpression.getThenExpression(), newThenExpre, null);

      InfixExpression infixExpression = ast.newInfixExpression();
      infixExpression.setLeftOperand(ast.newNumberLiteral("1"));
      infixExpression.setRightOperand(ast.newNumberLiteral("2"));
      infixExpression.setOperator(InfixExpression.Operator.PLUS);

      rewrite.replace(condExpression.getElseExpression(), infixExpression, null);
    }

    String preview = evaluateRewrite(cu, rewrite);

    buf = new StringBuffer();
    buf.append("    function foo() {\n");
    buf.append("        i= true ? x : 1 + 2;\n");
    buf.append("    }\n");
    assertEqualString(preview, buf.toString());
  }