Ejemplo n.º 1
0
 /*
  * @see ASTVisitor#visit(ArrayAccess)
  */
 public boolean visit(ArrayAccess node) {
   node.getArray().accept(this);
   this.fBuffer.append("["); // $NON-NLS-1$
   node.getIndex().accept(this);
   this.fBuffer.append("]"); // $NON-NLS-1$
   return false;
 }
  public void testArrayAccess() throws Exception {
    IPackageFragment pack1 = this.sourceFolder.createPackageFragment("", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("function foo(o) {\n");
    buf.append("	o[3 /* comment*/ - 1]= this.o[3 - 1];\n");
    buf.append("}\n");
    buf.append("");
    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 1", statements.size() == 1);
    { // replace left hand side index, replace right hand side index by left side index
      ExpressionStatement stmt = (ExpressionStatement) statements.get(0);
      Assignment assignment = (Assignment) stmt.getExpression();

      ArrayAccess left = (ArrayAccess) assignment.getLeftHandSide();
      ArrayAccess right = (ArrayAccess) assignment.getRightHandSide();

      NumberLiteral name = ast.newNumberLiteral("1");
      rewrite.replace(left.getIndex(), name, null);

      ASTNode placeHolder = rewrite.createCopyTarget(left.getIndex());
      rewrite.replace(right.getIndex(), placeHolder, null);

      SimpleName newName = ast.newSimpleName("o");
      rewrite.replace(right.getArray(), newName, null);
    }

    String preview = evaluateRewrite(cu, rewrite);

    buf = new StringBuffer();
    buf.append("function foo(o) {\n");
    buf.append("	o[1]= o[3 /* comment*/ - 1];\n");
    buf.append("}\n");

    assertEqualString(preview, buf.toString());
  }