rewriter.cc 12 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#include "src/parsing/rewriter.h"
6

7 8 9
#include "src/ast/ast.h"
#include "src/ast/scopes.h"
#include "src/parsing/parser.h"
10

11 12
namespace v8 {
namespace internal {
13

14
class Processor final : public AstVisitor<Processor> {
15
 public:
16
  Processor(Isolate* isolate, DeclarationScope* closure_scope, Variable* result,
17
            AstValueFactory* ast_value_factory)
18
      : result_(result),
19
        result_assigned_(false),
20
        replacement_(nullptr),
21
        is_set_(false),
22
        zone_(ast_value_factory->zone()),
23
        closure_scope_(closure_scope),
24
        factory_(ast_value_factory) {
25
    DCHECK_EQ(closure_scope, closure_scope->GetClosureScope());
26
    InitializeAstVisitor(isolate);
27
  }
28

29
  Processor(Parser* parser, DeclarationScope* closure_scope, Variable* result,
30 31 32 33 34
            AstValueFactory* ast_value_factory)
      : result_(result),
        result_assigned_(false),
        replacement_(nullptr),
        is_set_(false),
35
        zone_(ast_value_factory->zone()),
36
        closure_scope_(closure_scope),
37
        factory_(ast_value_factory) {
38
    DCHECK_EQ(closure_scope, closure_scope->GetClosureScope());
39 40 41
    InitializeAstVisitor(parser->stack_limit());
  }

42
  void Process(ZoneList<Statement*>* statements);
43
  bool result_assigned() const { return result_assigned_; }
44

45
  Zone* zone() { return zone_; }
46
  DeclarationScope* closure_scope() { return closure_scope_; }
47
  AstNodeFactory* factory() { return &factory_; }
48

49 50 51 52 53
  // Returns ".result = value"
  Expression* SetResult(Expression* value) {
    result_assigned_ = true;
    VariableProxy* result_proxy = factory()->NewVariableProxy(result_);
    return factory()->NewAssignment(Token::ASSIGN, result_proxy, value,
yangguo's avatar
yangguo committed
54
                                    kNoSourcePosition);
55 56 57 58 59
  }

  // Inserts '.result = undefined' in front of the given statement.
  Statement* AssignUndefinedBefore(Statement* s);

60
 private:
61
  Variable* result_;
62

63 64 65 66 67 68
  // We are not tracking result usage via the result_'s use
  // counts (we leave the accurate computation to the
  // usage analyzer). Instead we simple remember if
  // there was ever an assignment to result_.
  bool result_assigned_;

69 70 71 72
  // When visiting a node, we "return" a replacement for that node in
  // [replacement_].  In many cases this will just be the original node.
  Statement* replacement_;

73 74 75
  // To avoid storing to .result all the time, we eliminate some of
  // the stores by keeping track of whether or not we're sure .result
  // will be overwritten anyway. This is a bit more tricky than what I
76
  // was hoping for.
77 78
  bool is_set_;

79
  Zone* zone_;
80
  DeclarationScope* closure_scope_;
81
  AstNodeFactory factory_;
82

83
  // Node visitors.
84
#define DEF_VISIT(type) void Visit##type(type* node);
85
  AST_NODE_LIST(DEF_VISIT)
86
#undef DEF_VISIT
87 88

  void VisitIterationStatement(IterationStatement* stmt);
89 90

  DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
91 92 93
};


94 95
Statement* Processor::AssignUndefinedBefore(Statement* s) {
  Expression* result_proxy = factory()->NewVariableProxy(result_);
yangguo's avatar
yangguo committed
96 97 98 99
  Expression* undef = factory()->NewUndefinedLiteral(kNoSourcePosition);
  Expression* assignment = factory()->NewAssignment(Token::ASSIGN, result_proxy,
                                                    undef, kNoSourcePosition);
  Block* b = factory()->NewBlock(NULL, 2, false, kNoSourcePosition);
100
  b->statements()->Add(
yangguo's avatar
yangguo committed
101
      factory()->NewExpressionStatement(assignment, kNoSourcePosition), zone());
102 103 104 105 106
  b->statements()->Add(s, zone());
  return b;
}


107 108 109
void Processor::Process(ZoneList<Statement*>* statements) {
  for (int i = statements->length() - 1; i >= 0; --i) {
    Visit(statements->at(i));
110
    statements->Set(i, replacement_);
111 112 113 114 115 116 117 118 119 120 121 122 123
  }
}


void Processor::VisitBlock(Block* node) {
  // An initializer block is the rewritten form of a variable declaration
  // with initialization expressions. The initializer block contains the
  // list of assignments corresponding to the initialization expressions.
  // While unclear from the spec (ECMA-262, 3rd., 12.2), the value of
  // a variable declaration with initialization expression is 'undefined'
  // with some JS VMs: For instance, using smjs, print(eval('var x = 7'))
  // returns 'undefined'. To obtain the same behavior with v8, we need
  // to prevent rewriting in that case.
124
  if (!node->ignore_completion_value()) Process(node->statements());
125
  replacement_ = node;
126 127 128 129 130
}


void Processor::VisitExpressionStatement(ExpressionStatement* node) {
  // Rewrite : <x>; -> .result = <x>;
131
  if (!is_set_) {
132
    node->set_expression(SetResult(node->expression()));
133
    is_set_ = true;
134
  }
135
  replacement_ = node;
136 137 138 139
}


void Processor::VisitIfStatement(IfStatement* node) {
140 141
  // Rewrite both branches.
  bool set_after = is_set_;
142
  Visit(node->then_statement());
143
  node->set_then_statement(replacement_);
144 145 146
  bool set_in_then = is_set_;
  is_set_ = set_after;
  Visit(node->else_statement());
147
  node->set_else_statement(replacement_);
148
  is_set_ = is_set_ && set_in_then;
149
  replacement_ = node;
150

151
  if (!is_set_) {
152 153 154
    is_set_ = true;
    replacement_ = AssignUndefinedBefore(node);
  }
155 156 157
}


158 159
void Processor::VisitIterationStatement(IterationStatement* node) {
  // Rewrite the body.
160 161
  bool set_after = is_set_;
  is_set_ = false;  // We are in a loop, so we can't rely on [set_after].
162
  Visit(node->body());
163
  node->set_body(replacement_);
164
  is_set_ = is_set_ && set_after;
165
  replacement_ = node;
166

167
  if (!is_set_) {
168 169 170
    is_set_ = true;
    replacement_ = AssignUndefinedBefore(node);
  }
171 172 173
}


174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
void Processor::VisitDoWhileStatement(DoWhileStatement* node) {
  VisitIterationStatement(node);
}


void Processor::VisitWhileStatement(WhileStatement* node) {
  VisitIterationStatement(node);
}


void Processor::VisitForStatement(ForStatement* node) {
  VisitIterationStatement(node);
}


189
void Processor::VisitForInStatement(ForInStatement* node) {
190
  VisitIterationStatement(node);
191 192 193
}


194 195 196 197 198
void Processor::VisitForOfStatement(ForOfStatement* node) {
  VisitIterationStatement(node);
}


199
void Processor::VisitTryCatchStatement(TryCatchStatement* node) {
200 201
  // Rewrite both try and catch block.
  bool set_after = is_set_;
202
  Visit(node->try_block());
203
  node->set_try_block(static_cast<Block*>(replacement_));
204 205 206
  bool set_in_try = is_set_;
  is_set_ = set_after;
  Visit(node->catch_block());
207
  node->set_catch_block(static_cast<Block*>(replacement_));
208
  is_set_ = is_set_ && set_in_try;
209
  replacement_ = node;
210

211
  if (!is_set_) {
212 213 214
    is_set_ = true;
    replacement_ = AssignUndefinedBefore(node);
  }
215 216 217
}


218
void Processor::VisitTryFinallyStatement(TryFinallyStatement* node) {
219
  // Rewrite both try and finally block (in reverse order).
neis's avatar
neis committed
220 221
  bool set_after = is_set_;
  is_set_ = true;  // Don't normally need to assign in finally block.
222
  Visit(node->finally_block());
223
  node->set_finally_block(replacement_->AsBlock());
neis's avatar
neis committed
224 225 226 227
  {  // Save .result value at the beginning of the finally block and restore it
     // at the end again: ".backup = .result; ...; .result = .backup"
     // This is necessary because the finally block does not normally contribute
     // to the completion value.
228 229 230 231 232 233 234 235 236 237 238 239 240
     CHECK_NOT_NULL(closure_scope());
     Variable* backup = closure_scope()->NewTemporary(
         factory()->ast_value_factory()->dot_result_string());
     Expression* backup_proxy = factory()->NewVariableProxy(backup);
     Expression* result_proxy = factory()->NewVariableProxy(result_);
     Expression* save = factory()->NewAssignment(
         Token::ASSIGN, backup_proxy, result_proxy, kNoSourcePosition);
     Expression* restore = factory()->NewAssignment(
         Token::ASSIGN, result_proxy, backup_proxy, kNoSourcePosition);
     node->finally_block()->statements()->InsertAt(
         0, factory()->NewExpressionStatement(save, kNoSourcePosition), zone());
     node->finally_block()->statements()->Add(
         factory()->NewExpressionStatement(restore, kNoSourcePosition), zone());
neis's avatar
neis committed
241 242 243
  }
  is_set_ = set_after;
  Visit(node->try_block());
244 245
  node->set_try_block(replacement_->AsBlock());
  replacement_ = node;
246

247
  if (!is_set_) {
248 249 250
    is_set_ = true;
    replacement_ = AssignUndefinedBefore(node);
  }
251 252 253 254
}


void Processor::VisitSwitchStatement(SwitchStatement* node) {
255
  // Rewrite statements in all case clauses (in reverse order).
256
  ZoneList<CaseClause*>* clauses = node->cases();
257
  bool set_after = is_set_;
258 259 260 261
  for (int i = clauses->length() - 1; i >= 0; --i) {
    CaseClause* clause = clauses->at(i);
    Process(clause->statements());
  }
262
  is_set_ = is_set_ && set_after;
263
  replacement_ = node;
264

265
  if (!is_set_) {
266 267 268
    is_set_ = true;
    replacement_ = AssignUndefinedBefore(node);
  }
269 270 271 272 273
}


void Processor::VisitContinueStatement(ContinueStatement* node) {
  is_set_ = false;
274
  replacement_ = node;
275 276 277 278 279
}


void Processor::VisitBreakStatement(BreakStatement* node) {
  is_set_ = false;
280
  replacement_ = node;
281 282 283
}


284 285
void Processor::VisitWithStatement(WithStatement* node) {
  Visit(node->statement());
286 287
  node->set_statement(replacement_);
  replacement_ = node;
288

289
  if (!is_set_) {
290 291 292
    is_set_ = true;
    replacement_ = AssignUndefinedBefore(node);
  }
293 294 295
}


296 297 298
void Processor::VisitSloppyBlockFunctionStatement(
    SloppyBlockFunctionStatement* node) {
  Visit(node->statement());
299 300
  node->set_statement(replacement_);
  replacement_ = node;
301 302 303
}


304 305 306
void Processor::VisitEmptyStatement(EmptyStatement* node) {
  replacement_ = node;
}
307 308


309 310 311 312 313 314 315 316 317
void Processor::VisitReturnStatement(ReturnStatement* node) {
  is_set_ = true;
  replacement_ = node;
}


void Processor::VisitDebuggerStatement(DebuggerStatement* node) {
  replacement_ = node;
}
318 319


320
// Expressions are never visited.
321 322 323 324
#define DEF_VISIT(type)                                         \
  void Processor::Visit##type(type* expr) { UNREACHABLE(); }
EXPRESSION_NODE_LIST(DEF_VISIT)
#undef DEF_VISIT
325 326


327 328 329 330 331 332 333
// Declarations are never visited.
#define DEF_VISIT(type) \
  void Processor::Visit##type(type* expr) { UNREACHABLE(); }
DECLARATION_NODE_LIST(DEF_VISIT)
#undef DEF_VISIT


334 335
// Assumes code has been parsed.  Mutates the AST, so the AST should not
// continue to be used in the case of failure.
336
bool Rewriter::Rewrite(ParseInfo* info) {
337
  FunctionLiteral* function = info->literal();
338
  DCHECK_NOT_NULL(function);
339
  Scope* scope = function->scope();
340
  DCHECK_NOT_NULL(scope);
341
  if (!scope->is_script_scope() && !scope->is_eval_scope()) return true;
342
  DeclarationScope* closure_scope = scope->GetClosureScope();
343 344

  ZoneList<Statement*>* body = function->body();
345
  if (!body->is_empty()) {
346 347
    Variable* result = closure_scope->NewTemporary(
        info->ast_value_factory()->dot_result_string());
348
    // The name string must be internalized at this point.
349
    DCHECK(!result->name().is_null());
350
    Processor processor(info->isolate(), closure_scope, result,
neis's avatar
neis committed
351
                        info->ast_value_factory());
352 353
    processor.Process(body);
    if (processor.HasStackOverflow()) return false;
354

355
    if (processor.result_assigned()) {
yangguo's avatar
yangguo committed
356
      int pos = kNoSourcePosition;
357 358 359 360 361 362
      VariableProxy* result_proxy =
          processor.factory()->NewVariableProxy(result, pos);
      Statement* result_statement =
          processor.factory()->NewReturnStatement(result_proxy, pos);
      body->Add(result_statement, info->zone());
    }
363
  }
364 365 366 367

  return true;
}

368 369
bool Rewriter::Rewrite(Parser* parser, DeclarationScope* closure_scope,
                       DoExpression* expr, AstValueFactory* factory) {
370
  Block* block = expr->block();
371
  DCHECK_EQ(closure_scope, closure_scope->GetClosureScope());
372
  DCHECK(block->scope() == nullptr ||
373
         block->scope()->GetClosureScope() == closure_scope);
374 375 376 377 378
  ZoneList<Statement*>* body = block->statements();
  VariableProxy* result = expr->result();
  Variable* result_var = result->var();

  if (!body->is_empty()) {
379
    Processor processor(parser, closure_scope, result_var, factory);
380 381 382 383 384
    processor.Process(body);
    if (processor.HasStackOverflow()) return false;

    if (!processor.result_assigned()) {
      AstNodeFactory* node_factory = processor.factory();
yangguo's avatar
yangguo committed
385
      Expression* undef = node_factory->NewUndefinedLiteral(kNoSourcePosition);
386 387 388 389 390 391 392 393 394
      Statement* completion = node_factory->NewExpressionStatement(
          processor.SetResult(undef), expr->position());
      body->Add(completion, factory->zone());
    }
  }
  return true;
}


395 396
}  // namespace internal
}  // namespace v8