rewriter.cc 12.2 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/parsing/parse-info.h"
10
#include "src/parsing/parser.h"
11

12 13
namespace v8 {
namespace internal {
14

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

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

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

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

50 51 52 53 54
  // 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
55
                                    kNoSourcePosition);
56 57 58 59 60
  }

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

61
 private:
62
  Variable* result_;
63

64 65 66 67 68 69
  // 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_;

70 71 72 73
  // 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_;

74 75 76
  // 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
77
  // was hoping for.
78 79
  bool is_set_;

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

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

  void VisitIterationStatement(IterationStatement* stmt);
90 91

  DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
92 93 94
};


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


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


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.
125
  if (!node->ignore_completion_value()) Process(node->statements());
126
  replacement_ = node;
127 128 129 130 131
}


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


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

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


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

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


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


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


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


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


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


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

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


219
void Processor::VisitTryFinallyStatement(TryFinallyStatement* node) {
220
  // Rewrite both try and finally block (in reverse order).
neis's avatar
neis committed
221 222
  bool set_after = is_set_;
  is_set_ = true;  // Don't normally need to assign in finally block.
223
  Visit(node->finally_block());
224
  node->set_finally_block(replacement_->AsBlock());
neis's avatar
neis committed
225 226 227 228
  {  // 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.
229 230 231 232 233 234 235 236 237 238 239 240 241
     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
242 243 244
  }
  is_set_ = set_after;
  Visit(node->try_block());
245 246
  node->set_try_block(replacement_->AsBlock());
  replacement_ = node;
247

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


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

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


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


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


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

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


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


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


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


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


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


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


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

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

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

  return true;
}

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

  if (!body->is_empty()) {
383
    Processor processor(parser, closure_scope, result_var, factory);
384 385 386 387 388
    processor.Process(body);
    if (processor.HasStackOverflow()) return false;

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


399 400
}  // namespace internal
}  // namespace v8