rewriter.cc 13.6 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
#include "src/ast/ast.h"
#include "src/ast/scopes.h"
9
#include "src/objects-inl.h"
10
#include "src/parsing/parse-info.h"
11
#include "src/parsing/parser.h"
12

13 14
namespace v8 {
namespace internal {
15

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

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

46
  void Process(ZonePtrList<Statement>* statements);
47
  bool result_assigned() const { return result_assigned_; }
48

49
  Zone* zone() { return zone_; }
50
  DeclarationScope* closure_scope() { return closure_scope_; }
51
  AstNodeFactory* factory() { return &factory_; }
52

53 54 55 56 57
  // 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
58
                                    kNoSourcePosition);
59 60 61 62 63
  }

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

64
 private:
65
  Variable* result_;
66

67 68 69 70 71 72
  // 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_;

73 74 75 76
  // 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_;

77 78 79
  // 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
80
  // was hoping for.
81 82
  bool is_set_;

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
  bool breakable_;

  class BreakableScope final {
   public:
    explicit BreakableScope(Processor* processor, bool breakable = true)
        : processor_(processor), previous_(processor->breakable_) {
      processor->breakable_ = processor->breakable_ || breakable;
    }

    ~BreakableScope() { processor_->breakable_ = previous_; }

   private:
    Processor* processor_;
    bool previous_;
  };

99
  Zone* zone_;
100
  DeclarationScope* closure_scope_;
101
  AstNodeFactory factory_;
102

103
  // Node visitors.
104
#define DEF_VISIT(type) void Visit##type(type* node);
105
  AST_NODE_LIST(DEF_VISIT)
106
#undef DEF_VISIT
107 108

  void VisitIterationStatement(IterationStatement* stmt);
109 110

  DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
111 112 113
};


114
Statement* Processor::AssignUndefinedBefore(Statement* s) {
yangguo's avatar
yangguo committed
115
  Expression* undef = factory()->NewUndefinedLiteral(kNoSourcePosition);
116
  Expression* assignment = SetResult(undef);
117
  Block* b = factory()->NewBlock(2, false);
118
  b->statements()->Add(
yangguo's avatar
yangguo committed
119
      factory()->NewExpressionStatement(assignment, kNoSourcePosition), zone());
120 121 122 123
  b->statements()->Add(s, zone());
  return b;
}

124
void Processor::Process(ZonePtrList<Statement>* statements) {
125 126 127 128 129 130 131
  // If we're in a breakable scope (named block, iteration, or switch), we walk
  // all statements. The last value producing statement before the break needs
  // to assign to .result. If we're not in a breakable scope, only the last
  // value producing statement in the block assigns to .result, so we can stop
  // early.
  for (int i = statements->length() - 1; i >= 0 && (breakable_ || !is_set_);
       --i) {
132
    Visit(statements->at(i));
133
    statements->Set(i, replacement_);
134 135 136 137 138 139 140 141 142 143 144 145 146
  }
}


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.
147 148 149 150
  if (!node->ignore_completion_value()) {
    BreakableScope scope(this, node->labels() != nullptr);
    Process(node->statements());
  }
151
  replacement_ = node;
152 153 154 155 156
}


void Processor::VisitExpressionStatement(ExpressionStatement* node) {
  // Rewrite : <x>; -> .result = <x>;
157
  if (!is_set_) {
158
    node->set_expression(SetResult(node->expression()));
159
    is_set_ = true;
160
  }
161
  replacement_ = node;
162 163 164 165
}


void Processor::VisitIfStatement(IfStatement* node) {
166 167
  // Rewrite both branches.
  bool set_after = is_set_;
168

169
  Visit(node->then_statement());
170
  node->set_then_statement(replacement_);
171
  bool set_in_then = is_set_;
172

173 174
  is_set_ = set_after;
  Visit(node->else_statement());
175
  node->set_else_statement(replacement_);
176

177 178
  replacement_ = set_in_then && is_set_ ? node : AssignUndefinedBefore(node);
  is_set_ = true;
179 180 181
}


182
void Processor::VisitIterationStatement(IterationStatement* node) {
183 184 185 186 187
  // The statement may have to produce a value, so always assign undefined
  // before.
  // TODO(verwaest): Omit it if we know that there's no break/continue leaving
  // it early.
  DCHECK(breakable_ || !is_set_);
188
  BreakableScope scope(this);
189

190
  Visit(node->body());
191
  node->set_body(replacement_);
192

193 194
  replacement_ = AssignUndefinedBefore(node);
  is_set_ = true;
195 196 197
}


198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
void Processor::VisitDoWhileStatement(DoWhileStatement* node) {
  VisitIterationStatement(node);
}


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


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


213
void Processor::VisitForInStatement(ForInStatement* node) {
214
  VisitIterationStatement(node);
215 216 217
}


218 219 220 221 222
void Processor::VisitForOfStatement(ForOfStatement* node) {
  VisitIterationStatement(node);
}


223
void Processor::VisitTryCatchStatement(TryCatchStatement* node) {
224 225
  // Rewrite both try and catch block.
  bool set_after = is_set_;
226

227
  Visit(node->try_block());
228
  node->set_try_block(static_cast<Block*>(replacement_));
229
  bool set_in_try = is_set_;
230

231 232
  is_set_ = set_after;
  Visit(node->catch_block());
233
  node->set_catch_block(static_cast<Block*>(replacement_));
234

235 236
  replacement_ = is_set_ && set_in_try ? node : AssignUndefinedBefore(node);
  is_set_ = true;
237 238 239
}


240
void Processor::VisitTryFinallyStatement(TryFinallyStatement* node) {
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
  // Only rewrite finally if it could contain 'break' or 'continue'. Always
  // rewrite try.
  if (breakable_) {
    // Only set result before a 'break' or 'continue'.
    is_set_ = true;
    Visit(node->finally_block());
    node->set_finally_block(replacement_->AsBlock());
    // 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.
    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());
265 266 267
    // We can't tell whether the finally-block is guaranteed to set .result, so
    // reset is_set_ before visiting the try-block.
    is_set_ = false;
neis's avatar
neis committed
268 269
  }
  Visit(node->try_block());
270
  node->set_try_block(replacement_->AsBlock());
271

272 273
  replacement_ = is_set_ ? node : AssignUndefinedBefore(node);
  is_set_ = true;
274 275 276 277
}


void Processor::VisitSwitchStatement(SwitchStatement* node) {
278 279 280 281 282
  // The statement may have to produce a value, so always assign undefined
  // before.
  // TODO(verwaest): Omit it if we know that there's no break/continue leaving
  // it early.
  DCHECK(breakable_ || !is_set_);
283
  BreakableScope scope(this);
284
  // Rewrite statements in all case clauses.
285
  ZonePtrList<CaseClause>* clauses = node->cases();
286 287 288 289
  for (int i = clauses->length() - 1; i >= 0; --i) {
    CaseClause* clause = clauses->at(i);
    Process(clause->statements());
  }
290

291 292
  replacement_ = AssignUndefinedBefore(node);
  is_set_ = true;
293 294 295 296 297
}


void Processor::VisitContinueStatement(ContinueStatement* node) {
  is_set_ = false;
298
  replacement_ = node;
299 300 301 302 303
}


void Processor::VisitBreakStatement(BreakStatement* node) {
  is_set_ = false;
304
  replacement_ = node;
305 306 307
}


308 309
void Processor::VisitWithStatement(WithStatement* node) {
  Visit(node->statement());
310
  node->set_statement(replacement_);
311

312 313
  replacement_ = is_set_ ? node : AssignUndefinedBefore(node);
  is_set_ = true;
314 315 316
}


317 318 319
void Processor::VisitSloppyBlockFunctionStatement(
    SloppyBlockFunctionStatement* node) {
  Visit(node->statement());
320 321
  node->set_statement(replacement_);
  replacement_ = node;
322 323 324
}


325 326 327
void Processor::VisitEmptyStatement(EmptyStatement* node) {
  replacement_ = node;
}
328 329


330 331 332 333 334 335 336 337 338
void Processor::VisitReturnStatement(ReturnStatement* node) {
  is_set_ = true;
  replacement_ = node;
}


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

340 341 342 343
void Processor::VisitInitializeClassFieldsStatement(
    InitializeClassFieldsStatement* node) {
  replacement_ = node;
}
344

345
// Expressions are never visited.
346 347 348 349
#define DEF_VISIT(type)                                         \
  void Processor::Visit##type(type* expr) { UNREACHABLE(); }
EXPRESSION_NODE_LIST(DEF_VISIT)
#undef DEF_VISIT
350 351


352 353 354 355 356 357 358
// Declarations are never visited.
#define DEF_VISIT(type) \
  void Processor::Visit##type(type* expr) { UNREACHABLE(); }
DECLARATION_NODE_LIST(DEF_VISIT)
#undef DEF_VISIT


359 360
// Assumes code has been parsed.  Mutates the AST, so the AST should not
// continue to be used in the case of failure.
361
bool Rewriter::Rewrite(ParseInfo* info) {
362 363 364
  DisallowHeapAllocation no_allocation;
  DisallowHandleAllocation no_handles;
  DisallowHandleDereference no_deref;
365

366
  RuntimeCallTimerScope runtimeTimer(
367
      info->runtime_call_stats(),
368
      info->on_background_thread()
369 370
          ? RuntimeCallCounterId::kCompileBackgroundRewriteReturnResult
          : RuntimeCallCounterId::kCompileRewriteReturnResult);
371

372
  FunctionLiteral* function = info->literal();
373
  DCHECK_NOT_NULL(function);
374
  Scope* scope = function->scope();
375
  DCHECK_NOT_NULL(scope);
376
  DCHECK_EQ(scope, scope->GetClosureScope());
377

378 379 380 381
  if (!(scope->is_script_scope() || scope->is_eval_scope() ||
        scope->is_module_scope())) {
    return true;
  }
382

383
  ZonePtrList<Statement>* body = function->body();
384
  DCHECK_IMPLIES(scope->is_module_scope(), !body->is_empty());
385
  if (!body->is_empty()) {
386
    Variable* result = scope->AsDeclarationScope()->NewTemporary(
387
        info->ast_value_factory()->dot_result_string());
388 389
    Processor processor(info->stack_limit(), scope->AsDeclarationScope(),
                        result, info->ast_value_factory());
390
    processor.Process(body);
391

392 393 394 395 396 397 398 399 400 401
    DCHECK_IMPLIES(scope->is_module_scope(), processor.result_assigned());
    if (processor.result_assigned()) {
      int pos = kNoSourcePosition;
      Expression* result_value =
          processor.factory()->NewVariableProxy(result, pos);
      Statement* result_statement =
          processor.factory()->NewReturnStatement(result_value, pos);
      body->Add(result_statement, info->zone());
    }

402 403
    if (processor.HasStackOverflow()) return false;
  }
404 405 406 407

  return true;
}

408 409
bool Rewriter::Rewrite(Parser* parser, DeclarationScope* closure_scope,
                       DoExpression* expr, AstValueFactory* factory) {
410 411 412 413
  DisallowHeapAllocation no_allocation;
  DisallowHandleAllocation no_handles;
  DisallowHandleDereference no_deref;

414
  Block* block = expr->block();
415
  DCHECK_EQ(closure_scope, closure_scope->GetClosureScope());
416
  DCHECK(block->scope() == nullptr ||
417
         block->scope()->GetClosureScope() == closure_scope);
418
  ZonePtrList<Statement>* body = block->statements();
419 420 421 422
  VariableProxy* result = expr->result();
  Variable* result_var = result->var();

  if (!body->is_empty()) {
423
    Processor processor(parser, closure_scope, result_var, factory);
424 425 426 427 428
    processor.Process(body);
    if (processor.HasStackOverflow()) return false;

    if (!processor.result_assigned()) {
      AstNodeFactory* node_factory = processor.factory();
yangguo's avatar
yangguo committed
429
      Expression* undef = node_factory->NewUndefinedLiteral(kNoSourcePosition);
430 431 432 433 434 435 436 437 438
      Statement* completion = node_factory->NewExpressionStatement(
          processor.SetResult(undef), expr->position());
      body->Add(completion, factory->zone());
    }
  }
  return true;
}


439 440
}  // namespace internal
}  // namespace v8