ast.h 94.1 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#ifndef V8_AST_H_
#define V8_AST_H_

31 32 33
#include "v8.h"

#include "assembler.h"
34
#include "factory.h"
35
#include "isolate.h"
36
#include "jsregexp.h"
37
#include "list-inl.h"
38
#include "runtime.h"
39
#include "small-pointer-list.h"
40
#include "smart-pointers.h"
41
#include "token.h"
42 43
#include "type-info.h"  // TODO(rossberg): this should eventually be removed
#include "types.h"
44
#include "utils.h"
45
#include "variables.h"
46
#include "interface.h"
47
#include "zone-inl.h"
48

49 50
namespace v8 {
namespace internal {
51 52 53 54 55 56 57 58 59 60 61 62 63 64

// The abstract syntax tree is an intermediate, light-weight
// representation of the parsed JavaScript code suitable for
// compilation to native code.

// Nodes are allocated in a separate zone, which allows faster
// allocation and constant-time deallocation of the entire syntax
// tree.


// ----------------------------------------------------------------------------
// Nodes of the abstract syntax tree. Only concrete classes are
// enumerated here.

65 66
#define DECLARATION_NODE_LIST(V)                \
  V(VariableDeclaration)                        \
67
  V(FunctionDeclaration)                        \
68
  V(ModuleDeclaration)                          \
69 70
  V(ImportDeclaration)                          \
  V(ExportDeclaration)                          \
71 72 73 74 75 76

#define MODULE_NODE_LIST(V)                     \
  V(ModuleLiteral)                              \
  V(ModuleVariable)                             \
  V(ModulePath)                                 \
  V(ModuleUrl)
77

78
#define STATEMENT_NODE_LIST(V)                  \
79
  V(Block)                                      \
80
  V(ModuleStatement)                            \
81 82 83 84 85 86
  V(ExpressionStatement)                        \
  V(EmptyStatement)                             \
  V(IfStatement)                                \
  V(ContinueStatement)                          \
  V(BreakStatement)                             \
  V(ReturnStatement)                            \
87
  V(WithStatement)                              \
88
  V(SwitchStatement)                            \
89 90 91
  V(DoWhileStatement)                           \
  V(WhileStatement)                             \
  V(ForStatement)                               \
92
  V(ForInStatement)                             \
93
  V(ForOfStatement)                             \
94 95
  V(TryCatchStatement)                          \
  V(TryFinallyStatement)                        \
96 97 98
  V(DebuggerStatement)

#define EXPRESSION_NODE_LIST(V)                 \
99
  V(FunctionLiteral)                            \
100
  V(SharedFunctionInfoLiteral)                  \
101 102 103 104 105 106 107
  V(Conditional)                                \
  V(VariableProxy)                              \
  V(Literal)                                    \
  V(RegExpLiteral)                              \
  V(ObjectLiteral)                              \
  V(ArrayLiteral)                               \
  V(Assignment)                                 \
108
  V(Yield)                                      \
109 110 111 112 113 114 115 116 117 118 119
  V(Throw)                                      \
  V(Property)                                   \
  V(Call)                                       \
  V(CallNew)                                    \
  V(CallRuntime)                                \
  V(UnaryOperation)                             \
  V(CountOperation)                             \
  V(BinaryOperation)                            \
  V(CompareOperation)                           \
  V(ThisFunction)

120
#define AST_NODE_LIST(V)                        \
121
  DECLARATION_NODE_LIST(V)                      \
122
  MODULE_NODE_LIST(V)                           \
123 124
  STATEMENT_NODE_LIST(V)                        \
  EXPRESSION_NODE_LIST(V)
125

126 127 128 129
#ifdef WIN32
#undef Yield
#endif

130
// Forward declarations
131 132
class AstConstructionVisitor;
template<class> class AstNodeFactory;
133
class AstVisitor;
134
class Declaration;
135
class Module;
136 137 138
class BreakableStatement;
class Expression;
class IterationStatement;
139
class MaterializedLiteral;
140
class Statement;
141 142
class TargetCollector;
class TypeFeedbackOracle;
143

144 145 146 147 148 149 150 151 152 153 154 155 156
class RegExpAlternative;
class RegExpAssertion;
class RegExpAtom;
class RegExpBackReference;
class RegExpCapture;
class RegExpCharacterClass;
class RegExpCompiler;
class RegExpDisjunction;
class RegExpEmpty;
class RegExpLookahead;
class RegExpQuantifier;
class RegExpText;

157
#define DEF_FORWARD_DECLARATION(type) class type;
158
AST_NODE_LIST(DEF_FORWARD_DECLARATION)
159 160 161 162 163 164
#undef DEF_FORWARD_DECLARATION


// Typedef only introduced to avoid unreadable code.
// Please do appreciate the required space in "> >".
typedef ZoneList<Handle<String> > ZoneStringList;
165
typedef ZoneList<Handle<Object> > ZoneObjectList;
166 167


168 169 170
#define DECLARE_NODE_TYPE(type)                                             \
  virtual void Accept(AstVisitor* v);                                       \
  virtual AstNode::NodeType node_type() const { return AstNode::k##type; }  \
171
  template<class> friend class AstNodeFactory;
172 173 174 175 176 177


enum AstPropertiesFlag {
  kDontInline,
  kDontOptimize,
  kDontSelfOptimize,
178 179
  kDontSoftInline,
  kDontCache
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
};


class AstProperties BASE_EMBEDDED {
 public:
  class Flags : public EnumSet<AstPropertiesFlag, int> {};

  AstProperties() : node_count_(0) { }

  Flags* flags() { return &flags_; }
  int node_count() { return node_count_; }
  void add_node_count(int count) { node_count_ += count; }

 private:
  Flags flags_;
  int node_count_;
};


199
class AstNode: public ZoneObject {
200
 public:
201
#define DECLARE_TYPE_ENUM(type) k##type,
202
  enum NodeType {
203 204 205 206 207
    AST_NODE_LIST(DECLARE_TYPE_ENUM)
    kInvalid = -1
  };
#undef DECLARE_TYPE_ENUM

208
  void* operator new(size_t size, Zone* zone) {
vitalyr@chromium.org's avatar
vitalyr@chromium.org committed
209
    return zone->New(static_cast<int>(size));
210
  }
211

212
  AstNode() { }
213

214
  virtual ~AstNode() { }
215

216
  virtual void Accept(AstVisitor* v) = 0;
217
  virtual NodeType node_type() const = 0;
218 219 220

  // Type testing & conversion functions overridden by concrete subclasses.
#define DECLARE_NODE_FUNCTIONS(type)                  \
221 222
  bool Is##type() { return node_type() == AstNode::k##type; }          \
  type* As##type() { return Is##type() ? reinterpret_cast<type*>(this) : NULL; }
223 224
  AST_NODE_LIST(DECLARE_NODE_FUNCTIONS)
#undef DECLARE_NODE_FUNCTIONS
225

226
  virtual TargetCollector* AsTargetCollector() { return NULL; }
227 228
  virtual BreakableStatement* AsBreakableStatement() { return NULL; }
  virtual IterationStatement* AsIterationStatement() { return NULL; }
229
  virtual MaterializedLiteral* AsMaterializedLiteral() { return NULL; }
230 231

 protected:
232
  static int GetNextId(Isolate* isolate) {
233 234 235
    return ReserveIdRange(isolate, 1);
  }

236 237
  static int ReserveIdRange(Isolate* isolate, int n) {
    int tmp = isolate->ast_node_id();
238
    isolate->set_ast_node_id(tmp + n);
239 240 241
    return tmp;
  }

242 243 244 245 246 247
  // Some nodes re-use bailout IDs for type feedback.
  static TypeFeedbackId reuse(BailoutId id) {
    return TypeFeedbackId(id.ToInt());
  }


248 249 250 251 252
 private:
  // Hidden to prevent accidental usage. It would have to load the
  // current zone from the TLS.
  void* operator new(size_t size);

253
  friend class CaseClause;  // Generates AST IDs.
254 255 256
};


257
class Statement: public AstNode {
258
 public:
259 260
  Statement() : statement_pos_(RelocInfo::kNoPosition) {}

261
  bool IsEmpty() { return AsEmptyStatement() != NULL; }
262 263 264 265 266 267

  void set_statement_pos(int statement_pos) { statement_pos_ = statement_pos; }
  int statement_pos() const { return statement_pos_; }

 private:
  int statement_pos_;
268 269 270
};


271 272 273
class SmallMapList {
 public:
  SmallMapList() {}
274
  SmallMapList(int capacity, Zone* zone) : list_(capacity, zone) {}
275

276
  void Reserve(int capacity, Zone* zone) { list_.Reserve(capacity, zone); }
277
  void Clear() { list_.Clear(); }
278
  void Sort() { list_.Sort(); }
279 280 281 282

  bool is_empty() const { return list_.is_empty(); }
  int length() const { return list_.length(); }

283
  void AddMapIfMissing(Handle<Map> map, Zone* zone) {
284 285 286
    Map* updated = map->CurrentMapForDeprecated();
    if (updated == NULL) return;
    map = Handle<Map>(updated);
287 288 289 290 291 292
    for (int i = 0; i < length(); ++i) {
      if (at(i).is_identical_to(map)) return;
    }
    Add(map, zone);
  }

293
  void Add(Handle<Map> handle, Zone* zone) {
294
    ASSERT(!handle->is_deprecated());
295
    list_.Add(handle.location(), zone);
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
  }

  Handle<Map> at(int i) const {
    return Handle<Map>(list_.at(i));
  }

  Handle<Map> first() const { return at(0); }
  Handle<Map> last() const { return at(length() - 1); }

 private:
  // The list stores pointers to Map*, that is Map**, so it's GC safe.
  SmallPointerList<Map*> list_;

  DISALLOW_COPY_AND_ASSIGN(SmallMapList);
};


313
class Expression: public AstNode {
314
 public:
315 316 317 318 319 320 321 322 323 324 325 326
  enum Context {
    // Not assigned a context yet, or else will not be visited during
    // code generation.
    kUninitialized,
    // Evaluated for its side effects.
    kEffect,
    // Evaluated for its value (and side effects).
    kValue,
    // Evaluated for control flow (and side effects).
    kTest
  };

327 328 329 330 331
  virtual int position() const {
    UNREACHABLE();
    return 0;
  }

332 333
  virtual bool IsValidLeftHandSide() { return false; }

334 335 336 337
  // Helpers for ToBoolean conversion.
  virtual bool ToBooleanIsTrue() { return false; }
  virtual bool ToBooleanIsFalse() { return false; }

338 339 340 341 342
  // Symbols that cannot be parsed as array indices are considered property
  // names.  We do not treat symbols that can be array indexes as property
  // names because [] for string objects is handled only by keyed ICs.
  virtual bool IsPropertyName() { return false; }

343 344 345 346
  // True iff the result can be safely overwritten (to avoid allocation).
  // False for operations that can return one of their operands.
  virtual bool ResultOverwriteAllowed() { return false; }

347
  // True iff the expression is a literal represented as a smi.
348
  bool IsSmiLiteral();
349

350
  // True iff the expression is a string literal.
351
  bool IsStringLiteral();
352 353

  // True iff the expression is the null literal.
354
  bool IsNullLiteral();
355

356 357 358
  // True iff the expression is the undefined literal.
  bool IsUndefinedLiteral();

359 360 361 362 363
  // Expression type bounds
  Handle<Type> upper_type() { return upper_type_; }
  Handle<Type> lower_type() { return lower_type_; }
  void set_upper_type(Handle<Type> type) { upper_type_ = type; }
  void set_lower_type(Handle<Type> type) { lower_type_ = type; }
364

365 366 367 368 369
  // Type feedback information for assignments and properties.
  virtual bool IsMonomorphic() {
    UNREACHABLE();
    return false;
  }
370
  virtual SmallMapList* GetReceiverTypes() {
371 372 373
    UNREACHABLE();
    return NULL;
  }
374 375 376 377 378
  Handle<Map> GetMonomorphicReceiverType() {
    ASSERT(IsMonomorphic());
    SmallMapList* types = GetReceiverTypes();
    ASSERT(types != NULL && types->length() == 1);
    return types->at(0);
379
  }
380 381 382 383
  virtual KeyedAccessStoreMode GetStoreMode() {
    UNREACHABLE();
    return STANDARD_STORE;
  }
384

385 386 387 388
  // TODO(rossberg): this should move to its own AST node eventually.
  void RecordToBooleanTypeFeedback(TypeFeedbackOracle* oracle);
  byte to_boolean_types() const { return to_boolean_types_; }

389 390
  BailoutId id() const { return id_; }
  TypeFeedbackId test_id() const { return test_id_; }
391

392 393
 protected:
  explicit Expression(Isolate* isolate)
394 395
      : upper_type_(Type::Any(), isolate),
        lower_type_(Type::None(), isolate),
396
        id_(GetNextId(isolate)),
397 398
        test_id_(GetNextId(isolate)) {}

399
 private:
400 401
  Handle<Type> upper_type_;
  Handle<Type> lower_type_;
402 403
  byte to_boolean_types_;

404 405
  const BailoutId id_;
  const TypeFeedbackId test_id_;
406 407 408 409 410
};


class BreakableStatement: public Statement {
 public:
411
  enum BreakableType {
412 413 414 415 416 417 418 419 420 421 422 423
    TARGET_FOR_ANONYMOUS,
    TARGET_FOR_NAMED_ONLY
  };

  // The labels associated with this statement. May be NULL;
  // if it is != NULL, guaranteed to contain at least one entry.
  ZoneStringList* labels() const { return labels_; }

  // Type testing & conversion.
  virtual BreakableStatement* AsBreakableStatement() { return this; }

  // Code generation
424
  Label* break_target() { return &break_target_; }
425 426

  // Testers.
427 428 429
  bool is_target_for_anonymous() const {
    return breakable_type_ == TARGET_FOR_ANONYMOUS;
  }
430

431 432
  BailoutId EntryId() const { return entry_id_; }
  BailoutId ExitId() const { return exit_id_; }
433

434
 protected:
435 436
  BreakableStatement(
      Isolate* isolate, ZoneStringList* labels, BreakableType breakable_type)
437
      : labels_(labels),
438
        breakable_type_(breakable_type),
439 440 441 442 443
        entry_id_(GetNextId(isolate)),
        exit_id_(GetNextId(isolate)) {
    ASSERT(labels == NULL || labels->length() > 0);
  }

444 445 446

 private:
  ZoneStringList* labels_;
447
  BreakableType breakable_type_;
448
  Label break_target_;
449 450
  const BailoutId entry_id_;
  const BailoutId exit_id_;
451 452 453 454 455
};


class Block: public BreakableStatement {
 public:
456
  DECLARE_NODE_TYPE(Block)
457

458 459 460
  void AddStatement(Statement* statement, Zone* zone) {
    statements_.Add(statement, zone);
  }
461 462

  ZoneList<Statement*>* statements() { return &statements_; }
463
  bool is_initializer_block() const { return is_initializer_block_; }
464

465 466
  Scope* scope() const { return scope_; }
  void set_scope(Scope* scope) { scope_ = scope; }
467

468 469 470 471
 protected:
  Block(Isolate* isolate,
        ZoneStringList* labels,
        int capacity,
472 473
        bool is_initializer_block,
        Zone* zone)
474
      : BreakableStatement(isolate, labels, TARGET_FOR_NAMED_ONLY),
475
        statements_(capacity, zone),
476
        is_initializer_block_(is_initializer_block),
477
        scope_(NULL) {
478 479
  }

480 481 482
 private:
  ZoneList<Statement*> statements_;
  bool is_initializer_block_;
483
  Scope* scope_;
484 485 486
};


487
class Declaration: public AstNode {
488
 public:
489 490 491
  VariableProxy* proxy() const { return proxy_; }
  VariableMode mode() const { return mode_; }
  Scope* scope() const { return scope_; }
492
  virtual InitializationFlag initialization() const = 0;
493
  virtual bool IsInlineable() const;
494

495
 protected:
496
  Declaration(VariableProxy* proxy,
497
              VariableMode mode,
498
              Scope* scope)
499 500
      : proxy_(proxy),
        mode_(mode),
501
        scope_(scope) {
502
    ASSERT(IsDeclaredVariableMode(mode));
503 504 505 506
  }

 private:
  VariableProxy* proxy_;
507
  VariableMode mode_;
508 509 510

  // Nested scope from which the declaration originated.
  Scope* scope_;
511 512 513
};


514 515 516 517
class VariableDeclaration: public Declaration {
 public:
  DECLARE_NODE_TYPE(VariableDeclaration)

518 519 520 521 522 523 524 525 526 527 528 529
  virtual InitializationFlag initialization() const {
    return mode() == VAR ? kCreatedInitialized : kNeedsInitialization;
  }

 protected:
  VariableDeclaration(VariableProxy* proxy,
                      VariableMode mode,
                      Scope* scope)
      : Declaration(proxy, mode, scope) {
  }
};

530

531 532 533 534 535 536 537 538
class FunctionDeclaration: public Declaration {
 public:
  DECLARE_NODE_TYPE(FunctionDeclaration)

  FunctionLiteral* fun() const { return fun_; }
  virtual InitializationFlag initialization() const {
    return kCreatedInitialized;
  }
539 540 541
  virtual bool IsInlineable() const;

 protected:
542
  FunctionDeclaration(VariableProxy* proxy,
543 544 545 546 547
                      VariableMode mode,
                      FunctionLiteral* fun,
                      Scope* scope)
      : Declaration(proxy, mode, scope),
        fun_(fun) {
548 549 550
    // At the moment there are no "const functions" in JavaScript...
    ASSERT(mode == VAR || mode == LET);
    ASSERT(fun != NULL);
551 552 553 554 555 556 557
  }

 private:
  FunctionLiteral* fun_;
};


558 559 560 561 562
class ModuleDeclaration: public Declaration {
 public:
  DECLARE_NODE_TYPE(ModuleDeclaration)

  Module* module() const { return module_; }
563 564 565
  virtual InitializationFlag initialization() const {
    return kCreatedInitialized;
  }
566 567 568 569 570

 protected:
  ModuleDeclaration(VariableProxy* proxy,
                    Module* module,
                    Scope* scope)
571
      : Declaration(proxy, MODULE, scope),
572 573 574 575 576 577 578 579
        module_(module) {
  }

 private:
  Module* module_;
};


580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
class ImportDeclaration: public Declaration {
 public:
  DECLARE_NODE_TYPE(ImportDeclaration)

  Module* module() const { return module_; }
  virtual InitializationFlag initialization() const {
    return kCreatedInitialized;
  }

 protected:
  ImportDeclaration(VariableProxy* proxy,
                    Module* module,
                    Scope* scope)
      : Declaration(proxy, LET, scope),
        module_(module) {
  }

 private:
  Module* module_;
};


class ExportDeclaration: public Declaration {
 public:
  DECLARE_NODE_TYPE(ExportDeclaration)

  virtual InitializationFlag initialization() const {
    return kCreatedInitialized;
  }

 protected:
611 612
  ExportDeclaration(VariableProxy* proxy, Scope* scope)
      : Declaration(proxy, LET, scope) {}
613 614 615
};


616
class Module: public AstNode {
617 618
 public:
  Interface* interface() const { return interface_; }
619
  Block* body() const { return body_; }
620

621
 protected:
622 623 624 625 626 627
  explicit Module(Zone* zone)
      : interface_(Interface::NewModule(zone)),
        body_(NULL) {}
  explicit Module(Interface* interface, Block* body = NULL)
      : interface_(interface),
        body_(body) {}
628 629 630

 private:
  Interface* interface_;
631
  Block* body_;
632 633 634 635 636 637 638 639
};


class ModuleLiteral: public Module {
 public:
  DECLARE_NODE_TYPE(ModuleLiteral)

 protected:
640
  ModuleLiteral(Block* body, Interface* interface) : Module(interface, body) {}
641 642 643 644 645 646 647
};


class ModuleVariable: public Module {
 public:
  DECLARE_NODE_TYPE(ModuleVariable)

648
  VariableProxy* proxy() const { return proxy_; }
649 650

 protected:
651
  inline explicit ModuleVariable(VariableProxy* proxy);
652 653

 private:
654
  VariableProxy* proxy_;
655 656 657 658 659 660 661 662 663 664 665
};


class ModulePath: public Module {
 public:
  DECLARE_NODE_TYPE(ModulePath)

  Module* module() const { return module_; }
  Handle<String> name() const { return name_; }

 protected:
666 667 668
  ModulePath(Module* module, Handle<String> name, Zone* zone)
      : Module(zone),
        module_(module),
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
        name_(name) {
  }

 private:
  Module* module_;
  Handle<String> name_;
};


class ModuleUrl: public Module {
 public:
  DECLARE_NODE_TYPE(ModuleUrl)

  Handle<String> url() const { return url_; }

 protected:
685 686
  ModuleUrl(Handle<String> url, Zone* zone)
      : Module(zone), url_(url) {
687 688 689 690 691 692 693
  }

 private:
  Handle<String> url_;
};


694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
class ModuleStatement: public Statement {
 public:
  DECLARE_NODE_TYPE(ModuleStatement)

  VariableProxy* proxy() const { return proxy_; }
  Block* body() const { return body_; }

 protected:
  ModuleStatement(VariableProxy* proxy, Block* body)
      : proxy_(proxy),
        body_(body) {
  }

 private:
  VariableProxy* proxy_;
  Block* body_;
};


713 714 715 716 717 718 719
class IterationStatement: public BreakableStatement {
 public:
  // Type testing & conversion.
  virtual IterationStatement* AsIterationStatement() { return this; }

  Statement* body() const { return body_; }

720 721 722
  BailoutId OsrEntryId() const { return osr_entry_id_; }
  virtual BailoutId ContinueId() const = 0;
  virtual BailoutId StackCheckId() const = 0;
723

724
  // Code generation
725
  Label* continue_target()  { return &continue_target_; }
726 727

 protected:
728 729 730 731 732
  IterationStatement(Isolate* isolate, ZoneStringList* labels)
      : BreakableStatement(isolate, labels, TARGET_FOR_ANONYMOUS),
        body_(NULL),
        osr_entry_id_(GetNextId(isolate)) {
  }
733 734 735 736 737 738 739

  void Initialize(Statement* body) {
    body_ = body;
  }

 private:
  Statement* body_;
740
  Label continue_target_;
741

742
  const BailoutId osr_entry_id_;
743 744 745
};


746
class DoWhileStatement: public IterationStatement {
747
 public:
748 749
  DECLARE_NODE_TYPE(DoWhileStatement)

750 751 752 753
  void Initialize(Expression* cond, Statement* body) {
    IterationStatement::Initialize(body);
    cond_ = cond;
  }
754

755 756
  Expression* cond() const { return cond_; }

757 758 759 760 761
  // Position where condition expression starts. We need it to make
  // the loop's condition a breakable location.
  int condition_position() { return condition_position_; }
  void set_condition_position(int pos) { condition_position_ = pos; }

762 763 764
  virtual BailoutId ContinueId() const { return continue_id_; }
  virtual BailoutId StackCheckId() const { return back_edge_id_; }
  BailoutId BackEdgeId() const { return back_edge_id_; }
765

766 767 768 769 770 771 772 773
 protected:
  DoWhileStatement(Isolate* isolate, ZoneStringList* labels)
      : IterationStatement(isolate, labels),
        cond_(NULL),
        condition_position_(-1),
        continue_id_(GetNextId(isolate)),
        back_edge_id_(GetNextId(isolate)) {
  }
774

775 776
 private:
  Expression* cond_;
777

778
  int condition_position_;
779

780 781
  const BailoutId continue_id_;
  const BailoutId back_edge_id_;
782 783 784 785 786
};


class WhileStatement: public IterationStatement {
 public:
787 788
  DECLARE_NODE_TYPE(WhileStatement)

789 790 791 792 793 794 795 796 797
  void Initialize(Expression* cond, Statement* body) {
    IterationStatement::Initialize(body);
    cond_ = cond;
  }

  Expression* cond() const { return cond_; }
  bool may_have_function_literal() const {
    return may_have_function_literal_;
  }
798 799 800
  void set_may_have_function_literal(bool value) {
    may_have_function_literal_ = value;
  }
801

802 803 804
  virtual BailoutId ContinueId() const { return EntryId(); }
  virtual BailoutId StackCheckId() const { return body_id_; }
  BailoutId BodyId() const { return body_id_; }
805

806 807 808 809 810 811 812 813
 protected:
  WhileStatement(Isolate* isolate, ZoneStringList* labels)
      : IterationStatement(isolate, labels),
        cond_(NULL),
        may_have_function_literal_(true),
        body_id_(GetNextId(isolate)) {
  }

814 815
 private:
  Expression* cond_;
816

817 818
  // True if there is a function literal subexpression in the condition.
  bool may_have_function_literal_;
819

820
  const BailoutId body_id_;
821 822 823 824 825
};


class ForStatement: public IterationStatement {
 public:
826
  DECLARE_NODE_TYPE(ForStatement)
827 828 829 830 831 832 833 834 835 836 837

  void Initialize(Statement* init,
                  Expression* cond,
                  Statement* next,
                  Statement* body) {
    IterationStatement::Initialize(body);
    init_ = init;
    cond_ = cond;
    next_ = next;
  }

838 839 840
  Statement* init() const { return init_; }
  Expression* cond() const { return cond_; }
  Statement* next() const { return next_; }
841

842 843 844
  bool may_have_function_literal() const {
    return may_have_function_literal_;
  }
845 846 847
  void set_may_have_function_literal(bool value) {
    may_have_function_literal_ = value;
  }
848

849 850 851
  virtual BailoutId ContinueId() const { return continue_id_; }
  virtual BailoutId StackCheckId() const { return body_id_; }
  BailoutId BodyId() const { return body_id_; }
852

853 854 855
  bool is_fast_smi_loop() { return loop_variable_ != NULL; }
  Variable* loop_variable() { return loop_variable_; }
  void set_loop_variable(Variable* var) { loop_variable_ = var; }
856 857 858 859 860 861 862 863 864 865 866 867

 protected:
  ForStatement(Isolate* isolate, ZoneStringList* labels)
      : IterationStatement(isolate, labels),
        init_(NULL),
        cond_(NULL),
        next_(NULL),
        may_have_function_literal_(true),
        loop_variable_(NULL),
        continue_id_(GetNextId(isolate)),
        body_id_(GetNextId(isolate)) {
  }
868

869 870 871 872
 private:
  Statement* init_;
  Expression* cond_;
  Statement* next_;
873

874
  // True if there is a function literal subexpression in the condition.
875
  bool may_have_function_literal_;
876
  Variable* loop_variable_;
877

878 879
  const BailoutId continue_id_;
  const BailoutId body_id_;
880 881 882
};


883
class ForEachStatement: public IterationStatement {
884
 public:
885 886 887 888
  enum VisitMode {
    ENUMERATE,   // for (each in subject) body;
    ITERATE      // for (each of subject) body;
  };
889

890
  void Initialize(Expression* each, Expression* subject, Statement* body) {
891 892
    IterationStatement::Initialize(body);
    each_ = each;
893
    subject_ = subject;
894 895 896
  }

  Expression* each() const { return each_; }
897
  Expression* subject() const { return subject_; }
898

899
 protected:
900
  ForEachStatement(Isolate* isolate, ZoneStringList* labels)
901 902
      : IterationStatement(isolate, labels),
        each_(NULL),
903
        subject_(NULL) {
904 905
  }

906 907
 private:
  Expression* each_;
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
  Expression* subject_;
};


class ForInStatement: public ForEachStatement {
 public:
  DECLARE_NODE_TYPE(ForInStatement)

  Expression* enumerable() const {
    return subject();
  }

  TypeFeedbackId ForInFeedbackId() const { return reuse(PrepareId()); }
  void RecordTypeFeedback(TypeFeedbackOracle* oracle);
  enum ForInType { FAST_FOR_IN, SLOW_FOR_IN };
  ForInType for_in_type() const { return for_in_type_; }

925 926 927 928 929
  BailoutId BodyId() const { return body_id_; }
  BailoutId PrepareId() const { return prepare_id_; }
  virtual BailoutId ContinueId() const { return EntryId(); }
  virtual BailoutId StackCheckId() const { return body_id_; }

930 931 932
 protected:
  ForInStatement(Isolate* isolate, ZoneStringList* labels)
      : ForEachStatement(isolate, labels),
933 934 935
        for_in_type_(SLOW_FOR_IN),
        body_id_(GetNextId(isolate)),
        prepare_id_(GetNextId(isolate)) {
936
  }
937 938

  ForInType for_in_type_;
939 940
  const BailoutId body_id_;
  const BailoutId prepare_id_;
941
};
942

943 944 945 946 947

class ForOfStatement: public ForEachStatement {
 public:
  DECLARE_NODE_TYPE(ForOfStatement)

948 949 950 951 952 953 954 955 956 957 958 959 960 961
  void Initialize(Expression* each,
                  Expression* subject,
                  Statement* body,
                  Expression* assign_iterator,
                  Expression* next_result,
                  Expression* result_done,
                  Expression* assign_each) {
    ForEachStatement::Initialize(each, subject, body);
    assign_iterator_ = assign_iterator;
    next_result_ = next_result;
    result_done_ = result_done;
    assign_each_ = assign_each;
  }

962 963 964 965
  Expression* iterable() const {
    return subject();
  }

966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
  // var iterator = iterable;
  Expression* assign_iterator() const {
    return assign_iterator_;
  }

  // var result = iterator.next();
  Expression* next_result() const {
    return next_result_;
  }

  // result.done
  Expression* result_done() const {
    return result_done_;
  }

  // each = result.value
  Expression* assign_each() const {
    return assign_each_;
  }

  virtual BailoutId ContinueId() const { return EntryId(); }
  virtual BailoutId StackCheckId() const { return BackEdgeId(); }

  BailoutId BackEdgeId() const { return back_edge_id_; }

991 992
 protected:
  ForOfStatement(Isolate* isolate, ZoneStringList* labels)
993 994 995 996 997 998
      : ForEachStatement(isolate, labels),
        assign_iterator_(NULL),
        next_result_(NULL),
        result_done_(NULL),
        assign_each_(NULL),
        back_edge_id_(GetNextId(isolate)) {
999
  }
1000 1001 1002 1003 1004 1005

  Expression* assign_iterator_;
  Expression* next_result_;
  Expression* result_done_;
  Expression* assign_each_;
  const BailoutId back_edge_id_;
1006 1007 1008 1009 1010
};


class ExpressionStatement: public Statement {
 public:
1011
  DECLARE_NODE_TYPE(ExpressionStatement)
1012 1013

  void set_expression(Expression* e) { expression_ = e; }
1014
  Expression* expression() const { return expression_; }
1015

1016 1017 1018 1019
 protected:
  explicit ExpressionStatement(Expression* expression)
      : expression_(expression) { }

1020 1021 1022 1023 1024 1025 1026
 private:
  Expression* expression_;
};


class ContinueStatement: public Statement {
 public:
1027
  DECLARE_NODE_TYPE(ContinueStatement)
1028

1029
  IterationStatement* target() const { return target_; }
1030 1031 1032 1033

 protected:
  explicit ContinueStatement(IterationStatement* target)
      : target_(target) { }
1034 1035 1036 1037 1038 1039 1040 1041

 private:
  IterationStatement* target_;
};


class BreakStatement: public Statement {
 public:
1042
  DECLARE_NODE_TYPE(BreakStatement)
1043

1044
  BreakableStatement* target() const { return target_; }
1045 1046 1047 1048

 protected:
  explicit BreakStatement(BreakableStatement* target)
      : target_(target) { }
1049 1050 1051 1052 1053 1054 1055 1056

 private:
  BreakableStatement* target_;
};


class ReturnStatement: public Statement {
 public:
1057
  DECLARE_NODE_TYPE(ReturnStatement)
1058

1059
  Expression* expression() const { return expression_; }
1060 1061 1062 1063

 protected:
  explicit ReturnStatement(Expression* expression)
      : expression_(expression) { }
1064 1065 1066 1067 1068 1069

 private:
  Expression* expression_;
};


1070
class WithStatement: public Statement {
1071
 public:
1072
  DECLARE_NODE_TYPE(WithStatement)
1073

1074
  Scope* scope() { return scope_; }
1075
  Expression* expression() const { return expression_; }
1076
  Statement* statement() const { return statement_; }
1077

1078
 protected:
1079 1080 1081
  WithStatement(Scope* scope, Expression* expression, Statement* statement)
      : scope_(scope),
        expression_(expression),
1082
        statement_(statement) { }
1083

1084
 private:
1085
  Scope* scope_;
1086
  Expression* expression_;
1087
  Statement* statement_;
1088 1089 1090 1091 1092
};


class CaseClause: public ZoneObject {
 public:
1093 1094 1095 1096
  CaseClause(Isolate* isolate,
             Expression* label,
             ZoneList<Statement*>* statements,
             int pos);
1097

1098 1099
  bool is_default() const { return label_ == NULL; }
  Expression* label() const {
1100 1101 1102
    CHECK(!is_default());
    return label_;
  }
1103
  Label* body_target() { return &body_target_; }
1104
  ZoneList<Statement*>* statements() const { return statements_; }
1105

1106
  int position() const { return position_; }
1107 1108
  void set_position(int pos) { position_ = pos; }

1109
  BailoutId EntryId() const { return entry_id_; }
1110

1111
  // Type feedback information.
1112
  TypeFeedbackId CompareId() { return compare_id_; }
1113
  void RecordTypeFeedback(TypeFeedbackOracle* oracle);
1114
  Handle<Type> compare_type() { return compare_type_; }
1115

1116 1117
 private:
  Expression* label_;
1118
  Label body_target_;
1119
  ZoneList<Statement*>* statements_;
1120
  int position_;
1121 1122
  Handle<Type> compare_type_;

1123 1124
  const TypeFeedbackId compare_id_;
  const BailoutId entry_id_;
1125 1126 1127 1128 1129
};


class SwitchStatement: public BreakableStatement {
 public:
1130 1131
  DECLARE_NODE_TYPE(SwitchStatement)

1132 1133 1134
  void Initialize(Expression* tag, ZoneList<CaseClause*>* cases) {
    tag_ = tag;
    cases_ = cases;
1135
    switch_type_ = UNKNOWN_SWITCH;
1136 1137
  }

1138 1139
  Expression* tag() const { return tag_; }
  ZoneList<CaseClause*>* cases() const { return cases_; }
1140

1141 1142 1143 1144
  enum SwitchType { UNKNOWN_SWITCH, SMI_SWITCH, STRING_SWITCH, GENERIC_SWITCH };
  SwitchType switch_type() const { return switch_type_; }
  void set_switch_type(SwitchType switch_type) { switch_type_ = switch_type; }

1145 1146 1147 1148 1149
 protected:
  SwitchStatement(Isolate* isolate, ZoneStringList* labels)
      : BreakableStatement(isolate, labels, TARGET_FOR_ANONYMOUS),
        tag_(NULL),
        cases_(NULL) { }
1150 1151 1152 1153

 private:
  Expression* tag_;
  ZoneList<CaseClause*>* cases_;
1154
  SwitchType switch_type_;
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
};


// If-statements always have non-null references to their then- and
// else-parts. When parsing if-statements with no explicit else-part,
// the parser implicitly creates an empty statement. Use the
// HasThenStatement() and HasElseStatement() functions to check if a
// given if-statement has a then- or an else-part containing code.
class IfStatement: public Statement {
 public:
1165
  DECLARE_NODE_TYPE(IfStatement)
1166 1167 1168 1169 1170 1171 1172 1173

  bool HasThenStatement() const { return !then_statement()->IsEmpty(); }
  bool HasElseStatement() const { return !else_statement()->IsEmpty(); }

  Expression* condition() const { return condition_; }
  Statement* then_statement() const { return then_statement_; }
  Statement* else_statement() const { return else_statement_; }

1174 1175 1176
  BailoutId IfId() const { return if_id_; }
  BailoutId ThenId() const { return then_id_; }
  BailoutId ElseId() const { return else_id_; }
1177

1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
 protected:
  IfStatement(Isolate* isolate,
              Expression* condition,
              Statement* then_statement,
              Statement* else_statement)
      : condition_(condition),
        then_statement_(then_statement),
        else_statement_(else_statement),
        if_id_(GetNextId(isolate)),
        then_id_(GetNextId(isolate)),
        else_id_(GetNextId(isolate)) {
  }

1191 1192 1193 1194
 private:
  Expression* condition_;
  Statement* then_statement_;
  Statement* else_statement_;
1195 1196 1197
  const BailoutId if_id_;
  const BailoutId then_id_;
  const BailoutId else_id_;
1198 1199 1200
};


1201
// NOTE: TargetCollectors are represented as nodes to fit in the target
1202
// stack in the compiler; this should probably be reworked.
1203
class TargetCollector: public AstNode {
1204
 public:
1205
  explicit TargetCollector(Zone* zone) : targets_(0, zone) { }
1206

1207 1208 1209
  // Adds a jump target to the collector. The collector stores a pointer not
  // a copy of the target to make binding work, so make sure not to pass in
  // references to something on the stack.
1210
  void AddTarget(Label* target, Zone* zone);
1211

1212
  // Virtual behaviour. TargetCollectors are never part of the AST.
1213
  virtual void Accept(AstVisitor* v) { UNREACHABLE(); }
1214
  virtual NodeType node_type() const { return kInvalid; }
1215
  virtual TargetCollector* AsTargetCollector() { return this; }
1216

1217
  ZoneList<Label*>* targets() { return &targets_; }
1218 1219

 private:
1220
  ZoneList<Label*> targets_;
1221 1222 1223 1224 1225
};


class TryStatement: public Statement {
 public:
1226
  void set_escaping_targets(ZoneList<Label*>* targets) {
1227
    escaping_targets_ = targets;
1228 1229
  }

1230
  int index() const { return index_; }
1231
  Block* try_block() const { return try_block_; }
1232
  ZoneList<Label*>* escaping_targets() const { return escaping_targets_; }
1233 1234 1235 1236 1237 1238

 protected:
  TryStatement(int index, Block* try_block)
      : index_(index),
        try_block_(try_block),
        escaping_targets_(NULL) { }
1239 1240

 private:
1241 1242 1243
  // Unique (per-function) index of this handler.  This is not an AST ID.
  int index_;

1244
  Block* try_block_;
1245
  ZoneList<Label*>* escaping_targets_;
1246 1247 1248
};


1249
class TryCatchStatement: public TryStatement {
1250
 public:
1251 1252 1253 1254 1255 1256 1257
  DECLARE_NODE_TYPE(TryCatchStatement)

  Scope* scope() { return scope_; }
  Variable* variable() { return variable_; }
  Block* catch_block() const { return catch_block_; }

 protected:
1258 1259
  TryCatchStatement(int index,
                    Block* try_block,
1260 1261 1262
                    Scope* scope,
                    Variable* variable,
                    Block* catch_block)
1263
      : TryStatement(index, try_block),
1264 1265
        scope_(scope),
        variable_(variable),
1266 1267 1268 1269
        catch_block_(catch_block) {
  }

 private:
1270 1271
  Scope* scope_;
  Variable* variable_;
1272 1273 1274 1275
  Block* catch_block_;
};


1276
class TryFinallyStatement: public TryStatement {
1277
 public:
1278
  DECLARE_NODE_TYPE(TryFinallyStatement)
1279 1280

  Block* finally_block() const { return finally_block_; }
1281 1282 1283 1284 1285

 protected:
  TryFinallyStatement(int index, Block* try_block, Block* finally_block)
      : TryStatement(index, try_block),
        finally_block_(finally_block) { }
1286 1287 1288 1289 1290 1291 1292 1293

 private:
  Block* finally_block_;
};


class DebuggerStatement: public Statement {
 public:
1294
  DECLARE_NODE_TYPE(DebuggerStatement)
1295 1296 1297

 protected:
  DebuggerStatement() {}
1298 1299 1300 1301 1302
};


class EmptyStatement: public Statement {
 public:
1303
  DECLARE_NODE_TYPE(EmptyStatement)
1304

1305 1306
 protected:
  EmptyStatement() {}
1307 1308 1309 1310 1311
};


class Literal: public Expression {
 public:
1312 1313
  DECLARE_NODE_TYPE(Literal)

1314
  virtual bool IsPropertyName() {
1315
    if (value_->IsInternalizedString()) {
1316
      uint32_t ignored;
1317
      return !String::cast(*value_)->AsArrayIndex(&ignored);
1318 1319 1320 1321
    }
    return false;
  }

1322 1323
  Handle<String> AsPropertyName() {
    ASSERT(IsPropertyName());
1324
    return Handle<String>::cast(value_);
1325 1326
  }

1327 1328
  virtual bool ToBooleanIsTrue() { return value_->BooleanValue(); }
  virtual bool ToBooleanIsFalse() { return !value_->BooleanValue(); }
1329

1330
  // Identity testers.
1331
  bool IsNull() const {
1332 1333
    ASSERT(!value_.is_null());
    return value_->IsNull();
1334 1335
  }
  bool IsTrue() const {
1336 1337
    ASSERT(!value_.is_null());
    return value_->IsTrue();
1338
  }
1339
  bool IsFalse() const {
1340 1341
    ASSERT(!value_.is_null());
    return value_->IsFalse();
1342 1343
  }

1344
  Handle<Object> value() const { return value_; }
1345

1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
  // Support for using Literal as a HashMap key. NOTE: Currently, this works
  // only for string and number literals!
  uint32_t Hash() { return ToString()->Hash(); }

  static bool Match(void* literal1, void* literal2) {
    Handle<String> s1 = static_cast<Literal*>(literal1)->ToString();
    Handle<String> s2 = static_cast<Literal*>(literal2)->ToString();
    return s1->Equals(*s2);
  }

1356 1357
  TypeFeedbackId LiteralFeedbackId() const { return reuse(id()); }

1358
 protected:
1359
  Literal(Isolate* isolate, Handle<Object> value)
1360
      : Expression(isolate),
1361
        value_(value) { }
1362 1363

 private:
1364 1365
  Handle<String> ToString();

1366
  Handle<Object> value_;
1367 1368 1369 1370 1371 1372
};


// Base class for literals that needs space in the corresponding JSFunction.
class MaterializedLiteral: public Expression {
 public:
1373 1374
  virtual MaterializedLiteral* AsMaterializedLiteral() { return this; }

1375
  int literal_index() { return literal_index_; }
1376 1377 1378 1379 1380 1381

  // A materialized literal is simple if the values consist of only
  // constants and simple object and array literals.
  bool is_simple() const { return is_simple_; }

  int depth() const { return depth_; }
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391

 protected:
  MaterializedLiteral(Isolate* isolate,
                      int literal_index,
                      bool is_simple,
                      int depth)
      : Expression(isolate),
        literal_index_(literal_index),
        is_simple_(is_simple),
        depth_(depth) {}
1392

1393 1394
 private:
  int literal_index_;
1395 1396
  bool is_simple_;
  int depth_;
1397 1398 1399
};


1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
// Property is used for passing information
// about an object literal's properties from the parser
// to the code generator.
class ObjectLiteralProperty: public ZoneObject {
 public:
  enum Kind {
    CONSTANT,              // Property with constant value (compile time).
    COMPUTED,              // Property with computed value (execution time).
    MATERIALIZED_LITERAL,  // Property value is a materialized literal.
    GETTER, SETTER,        // Property is an accessor function.
    PROTOTYPE              // Property is __proto__.
  };

  ObjectLiteralProperty(Literal* key, Expression* value, Isolate* isolate);

  Literal* key() { return key_; }
  Expression* value() { return value_; }
  Kind kind() { return kind_; }

  // Type feedback information.
  void RecordTypeFeedback(TypeFeedbackOracle* oracle);
  bool IsMonomorphic() { return !receiver_type_.is_null(); }
  Handle<Map> GetReceiverType() { return receiver_type_; }

  bool IsCompileTimeValue();

  void set_emit_store(bool emit_store);
  bool emit_store();

 protected:
  template<class> friend class AstNodeFactory;

  ObjectLiteralProperty(bool is_getter, FunctionLiteral* value);
  void set_key(Literal* key) { key_ = key; }

 private:
  Literal* key_;
  Expression* value_;
  Kind kind_;
  bool emit_store_;
  Handle<Map> receiver_type_;
};


1444 1445 1446 1447
// An object literal has a boilerplate object that is used
// for minimizing the work when constructing it at runtime.
class ObjectLiteral: public MaterializedLiteral {
 public:
1448
  typedef ObjectLiteralProperty Property;
1449

1450
  DECLARE_NODE_TYPE(ObjectLiteral)
1451 1452 1453 1454 1455

  Handle<FixedArray> constant_properties() const {
    return constant_properties_;
  }
  ZoneList<Property*>* properties() const { return properties_; }
1456
  bool fast_elements() const { return fast_elements_; }
1457 1458
  bool may_store_doubles() const { return may_store_doubles_; }
  bool has_function() const { return has_function_; }
1459 1460 1461 1462

  // Mark all computed expressions that are bound to a key that
  // is shadowed by a later occurrence of the same key. For the
  // marked expressions, no store code is emitted.
1463
  void CalculateEmitStore(Zone* zone);
1464

1465 1466 1467 1468 1469 1470
  enum Flags {
    kNoFlags = 0,
    kFastElements = 1,
    kHasFunction = 1 << 1
  };

1471 1472 1473 1474 1475 1476
  struct Accessors: public ZoneObject {
    Accessors() : getter(NULL), setter(NULL) { }
    Expression* getter;
    Expression* setter;
  };

1477 1478 1479 1480 1481 1482 1483 1484
 protected:
  ObjectLiteral(Isolate* isolate,
                Handle<FixedArray> constant_properties,
                ZoneList<Property*>* properties,
                int literal_index,
                bool is_simple,
                bool fast_elements,
                int depth,
1485
                bool may_store_doubles,
1486 1487 1488 1489 1490
                bool has_function)
      : MaterializedLiteral(isolate, literal_index, is_simple, depth),
        constant_properties_(constant_properties),
        properties_(properties),
        fast_elements_(fast_elements),
1491
        may_store_doubles_(may_store_doubles),
1492 1493
        has_function_(has_function) {}

1494 1495 1496
 private:
  Handle<FixedArray> constant_properties_;
  ZoneList<Property*>* properties_;
1497
  bool fast_elements_;
1498
  bool may_store_doubles_;
1499
  bool has_function_;
1500 1501 1502 1503 1504 1505
};


// Node for capturing a regexp literal.
class RegExpLiteral: public MaterializedLiteral {
 public:
1506 1507 1508 1509 1510 1511
  DECLARE_NODE_TYPE(RegExpLiteral)

  Handle<String> pattern() const { return pattern_; }
  Handle<String> flags() const { return flags_; }

 protected:
1512 1513
  RegExpLiteral(Isolate* isolate,
                Handle<String> pattern,
1514 1515
                Handle<String> flags,
                int literal_index)
1516
      : MaterializedLiteral(isolate, literal_index, false, 1),
1517 1518 1519 1520 1521 1522 1523 1524 1525
        pattern_(pattern),
        flags_(flags) {}

 private:
  Handle<String> pattern_;
  Handle<String> flags_;
};

// An array literal has a literals object that is used
1526
// for minimizing the work when constructing it at runtime.
1527
class ArrayLiteral: public MaterializedLiteral {
1528
 public:
1529 1530 1531 1532 1533 1534
  DECLARE_NODE_TYPE(ArrayLiteral)

  Handle<FixedArray> constant_elements() const { return constant_elements_; }
  ZoneList<Expression*>* values() const { return values_; }

  // Return an AST id for an element that is used in simulate instructions.
1535 1536 1537
  BailoutId GetIdForElement(int i) {
    return BailoutId(first_element_id_.ToInt() + i);
  }
1538 1539

 protected:
1540 1541
  ArrayLiteral(Isolate* isolate,
               Handle<FixedArray> constant_elements,
1542 1543 1544 1545
               ZoneList<Expression*>* values,
               int literal_index,
               bool is_simple,
               int depth)
1546
      : MaterializedLiteral(isolate, literal_index, is_simple, depth),
1547
        constant_elements_(constant_elements),
1548
        values_(values),
1549
        first_element_id_(ReserveIdRange(isolate, values->length())) {}
1550 1551

 private:
1552
  Handle<FixedArray> constant_elements_;
1553
  ZoneList<Expression*>* values_;
1554
  const BailoutId first_element_id_;
1555 1556 1557 1558 1559
};


class VariableProxy: public Expression {
 public:
1560
  DECLARE_NODE_TYPE(VariableProxy)
1561 1562 1563 1564

  virtual bool IsValidLeftHandSide() {
    return var_ == NULL ? true : var_->IsValidLeftHandSide();
  }
1565

1566 1567 1568 1569
  bool IsVariable(Handle<String> n) {
    return !is_this() && name().is_identical_to(n);
  }

1570
  bool IsArguments() { return var_ != NULL && var_->is_arguments(); }
1571

1572 1573 1574 1575
  bool IsLValue() {
    return is_lvalue_;
  }

1576 1577 1578
  Handle<String> name() const { return name_; }
  Variable* var() const { return var_; }
  bool is_this() const { return is_this_; }
1579
  int position() const { return position_; }
1580 1581
  Interface* interface() const { return interface_; }

1582

1583
  void MarkAsTrivial() { is_trivial_ = true; }
1584
  void MarkAsLValue() { is_lvalue_ = true; }
1585

1586
  // Bind this proxy to the variable var. Interfaces must match.
1587 1588 1589
  void BindTo(Variable* var);

 protected:
1590 1591 1592 1593 1594
  VariableProxy(Isolate* isolate, Variable* var);

  VariableProxy(Isolate* isolate,
                Handle<String> name,
                bool is_this,
1595 1596
                Interface* interface,
                int position);
1597

1598 1599 1600
  Handle<String> name_;
  Variable* var_;  // resolved variable, or NULL
  bool is_this_;
1601
  bool is_trivial_;
1602 1603 1604
  // True if this variable proxy is being used in an assignment
  // or with a increment/decrement operator.
  bool is_lvalue_;
1605
  int position_;
1606
  Interface* interface_;
1607 1608 1609 1610 1611
};


class Property: public Expression {
 public:
1612
  DECLARE_NODE_TYPE(Property)
1613 1614 1615 1616 1617

  virtual bool IsValidLeftHandSide() { return true; }

  Expression* obj() const { return obj_; }
  Expression* key() const { return key_; }
1618
  virtual int position() const { return pos_; }
1619

1620
  BailoutId LoadId() const { return load_id_; }
1621

1622
  bool IsStringLength() const { return is_string_length_; }
1623
  bool IsStringAccess() const { return is_string_access_; }
1624 1625
  bool IsFunctionPrototype() const { return is_function_prototype_; }

1626
  // Type feedback information.
1627
  void RecordTypeFeedback(TypeFeedbackOracle* oracle, Zone* zone);
1628
  virtual bool IsMonomorphic() { return is_monomorphic_; }
1629
  virtual SmallMapList* GetReceiverTypes() { return &receiver_types_; }
1630 1631 1632
  virtual KeyedAccessStoreMode GetStoreMode() {
    return STANDARD_STORE;
  }
1633
  bool IsUninitialized() { return is_uninitialized_; }
1634
  TypeFeedbackId PropertyFeedbackId() { return reuse(id()); }
1635

1636 1637 1638 1639 1640 1641 1642 1643 1644
 protected:
  Property(Isolate* isolate,
           Expression* obj,
           Expression* key,
           int pos)
      : Expression(isolate),
        obj_(obj),
        key_(key),
        pos_(pos),
1645
        load_id_(GetNextId(isolate)),
1646
        is_monomorphic_(false),
1647
        is_uninitialized_(false),
1648 1649 1650 1651
        is_string_length_(false),
        is_string_access_(false),
        is_function_prototype_(false) { }

1652 1653 1654 1655
 private:
  Expression* obj_;
  Expression* key_;
  int pos_;
1656
  const BailoutId load_id_;
1657

1658
  SmallMapList receiver_types_;
1659
  bool is_monomorphic_ : 1;
1660
  bool is_uninitialized_ : 1;
1661
  bool is_string_length_ : 1;
1662
  bool is_string_access_ : 1;
1663
  bool is_function_prototype_ : 1;
1664 1665 1666 1667 1668
};


class Call: public Expression {
 public:
1669
  DECLARE_NODE_TYPE(Call)
1670 1671 1672

  Expression* expression() const { return expression_; }
  ZoneList<Expression*>* arguments() const { return arguments_; }
1673
  virtual int position() const { return pos_; }
1674

1675 1676 1677
  // Type feedback information.
  TypeFeedbackId CallFeedbackId() const { return reuse(id()); }
  void RecordTypeFeedback(TypeFeedbackOracle* oracle, CallKind call_kind);
1678
  virtual SmallMapList* GetReceiverTypes() { return &receiver_types_; }
1679
  virtual bool IsMonomorphic() { return is_monomorphic_; }
1680
  CheckType check_type() const { return check_type_; }
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696

  void set_string_check(Handle<JSObject> holder) {
    holder_ = holder;
    check_type_ = STRING_CHECK;
  }

  void set_number_check(Handle<JSObject> holder) {
    holder_ = holder;
    check_type_ = NUMBER_CHECK;
  }

  void set_map_check() {
    holder_ = Handle<JSObject>::null();
    check_type_ = RECEIVER_MAP_CHECK;
  }

1697
  Handle<JSFunction> target() { return target_; }
1698 1699 1700 1701

  // A cache for the holder, set as a side effect of computing the target of the
  // call. Note that it contains the null handle when the receiver is the same
  // as the holder!
1702
  Handle<JSObject> holder() { return holder_; }
1703

1704
  Handle<Cell> cell() { return cell_; }
1705 1706

  bool ComputeTarget(Handle<Map> type, Handle<String> name);
1707
  bool ComputeGlobalTarget(Handle<GlobalObject> global, LookupResult* lookup);
1708

1709
  BailoutId ReturnId() const { return return_id_; }
1710

1711 1712 1713 1714 1715
  // TODO(rossberg): this should really move somewhere else (and be merged with
  // various similar methods in objets.cc), but for now...
  static Handle<JSObject> GetPrototypeForPrimitiveCheck(
      CheckType check, Isolate* isolate);

1716 1717 1718 1719 1720
#ifdef DEBUG
  // Used to assert that the FullCodeGenerator records the return site.
  bool return_is_recorded_;
#endif

1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
 protected:
  Call(Isolate* isolate,
       Expression* expression,
       ZoneList<Expression*>* arguments,
       int pos)
      : Expression(isolate),
        expression_(expression),
        arguments_(arguments),
        pos_(pos),
        is_monomorphic_(false),
        check_type_(RECEIVER_MAP_CHECK),
        return_id_(GetNextId(isolate)) { }

1734 1735 1736 1737 1738
 private:
  Expression* expression_;
  ZoneList<Expression*>* arguments_;
  int pos_;

1739
  bool is_monomorphic_;
1740
  CheckType check_type_;
1741
  SmallMapList receiver_types_;
1742 1743
  Handle<JSFunction> target_;
  Handle<JSObject> holder_;
1744
  Handle<Cell> cell_;
1745

1746
  const BailoutId return_id_;
1747
};
1748

1749

1750
class CallNew: public Expression {
1751
 public:
1752 1753 1754 1755 1756 1757
  DECLARE_NODE_TYPE(CallNew)

  Expression* expression() const { return expression_; }
  ZoneList<Expression*>* arguments() const { return arguments_; }
  virtual int position() const { return pos_; }

1758 1759
  // Type feedback information.
  TypeFeedbackId CallNewFeedbackId() const { return reuse(id()); }
1760 1761
  void RecordTypeFeedback(TypeFeedbackOracle* oracle);
  virtual bool IsMonomorphic() { return is_monomorphic_; }
1762 1763
  Handle<JSFunction> target() const { return target_; }
  ElementsKind elements_kind() const { return elements_kind_; }
1764
  Handle<Cell> allocation_info_cell() const {
1765 1766
    return allocation_info_cell_;
  }
1767

1768
  BailoutId ReturnId() const { return return_id_; }
1769

1770
 protected:
1771 1772 1773 1774 1775 1776 1777
  CallNew(Isolate* isolate,
          Expression* expression,
          ZoneList<Expression*>* arguments,
          int pos)
      : Expression(isolate),
        expression_(expression),
        arguments_(arguments),
1778 1779
        pos_(pos),
        is_monomorphic_(false),
1780 1781
        elements_kind_(GetInitialFastElementsKind()),
        return_id_(GetNextId(isolate)) { }
1782

1783 1784 1785 1786
 private:
  Expression* expression_;
  ZoneList<Expression*>* arguments_;
  int pos_;
1787 1788 1789

  bool is_monomorphic_;
  Handle<JSFunction> target_;
1790
  ElementsKind elements_kind_;
1791
  Handle<Cell> allocation_info_cell_;
1792

1793
  const BailoutId return_id_;
1794 1795 1796
};


1797 1798 1799 1800 1801 1802
// The CallRuntime class does not represent any official JavaScript
// language construct. Instead it is used to call a C or JS function
// with a set of arguments. This is used from the builtins that are
// implemented in JavaScript (see "v8natives.js").
class CallRuntime: public Expression {
 public:
1803 1804 1805 1806 1807 1808 1809
  DECLARE_NODE_TYPE(CallRuntime)

  Handle<String> name() const { return name_; }
  const Runtime::Function* function() const { return function_; }
  ZoneList<Expression*>* arguments() const { return arguments_; }
  bool is_jsruntime() const { return function_ == NULL; }

1810 1811
  TypeFeedbackId CallRuntimeFeedbackId() const { return reuse(id()); }

1812
 protected:
1813 1814
  CallRuntime(Isolate* isolate,
              Handle<String> name,
1815
              const Runtime::Function* function,
1816
              ZoneList<Expression*>* arguments)
1817 1818 1819 1820
      : Expression(isolate),
        name_(name),
        function_(function),
        arguments_(arguments) { }
1821 1822 1823

 private:
  Handle<String> name_;
1824
  const Runtime::Function* function_;
1825 1826 1827 1828 1829 1830
  ZoneList<Expression*>* arguments_;
};


class UnaryOperation: public Expression {
 public:
1831 1832 1833 1834 1835 1836 1837 1838
  DECLARE_NODE_TYPE(UnaryOperation)

  virtual bool ResultOverwriteAllowed();

  Token::Value op() const { return op_; }
  Expression* expression() const { return expression_; }
  virtual int position() const { return pos_; }

1839 1840 1841 1842
  BailoutId MaterializeTrueId() { return materialize_true_id_; }
  BailoutId MaterializeFalseId() { return materialize_false_id_; }

  TypeFeedbackId UnaryOperationFeedbackId() const { return reuse(id()); }
1843 1844

 protected:
1845 1846 1847 1848
  UnaryOperation(Isolate* isolate,
                 Token::Value op,
                 Expression* expression,
                 int pos)
1849 1850 1851 1852
      : Expression(isolate),
        op_(op),
        expression_(expression),
        pos_(pos),
1853 1854
        materialize_true_id_(GetNextId(isolate)),
        materialize_false_id_(GetNextId(isolate)) {
1855 1856 1857 1858 1859 1860
    ASSERT(Token::IsUnaryOp(op));
  }

 private:
  Token::Value op_;
  Expression* expression_;
1861
  int pos_;
1862 1863 1864

  // For unary not (Token::NOT), the AST ids where true and false will
  // actually be materialized, respectively.
1865 1866
  const BailoutId materialize_true_id_;
  const BailoutId materialize_false_id_;
1867 1868 1869 1870 1871
};


class BinaryOperation: public Expression {
 public:
1872
  DECLARE_NODE_TYPE(BinaryOperation)
1873

1874
  virtual bool ResultOverwriteAllowed();
1875 1876 1877 1878

  Token::Value op() const { return op_; }
  Expression* left() const { return left_; }
  Expression* right() const { return right_; }
1879
  virtual int position() const { return pos_; }
1880

1881 1882 1883
  BailoutId RightId() const { return right_id_; }

  TypeFeedbackId BinaryOperationFeedbackId() const { return reuse(id()); }
1884 1885
  Maybe<int> fixed_right_arg() const { return fixed_right_arg_; }
  void set_fixed_right_arg(Maybe<int> arg) { fixed_right_arg_ = arg; }
1886

1887 1888 1889 1890 1891 1892
 protected:
  BinaryOperation(Isolate* isolate,
                  Token::Value op,
                  Expression* left,
                  Expression* right,
                  int pos)
1893 1894 1895 1896 1897 1898
      : Expression(isolate),
        op_(op),
        left_(left),
        right_(right),
        pos_(pos),
        right_id_(GetNextId(isolate)) {
1899 1900 1901
    ASSERT(Token::IsBinaryOp(op));
  }

1902 1903 1904 1905
 private:
  Token::Value op_;
  Expression* left_;
  Expression* right_;
1906
  int pos_;
1907

1908 1909 1910
  // TODO(rossberg): the fixed arg should probably be represented as a Constant
  // type for the RHS.
  Maybe<int> fixed_right_arg_;
1911

1912
  // The short-circuit logical operations need an AST ID for their
1913
  // right-hand subexpression.
1914
  const BailoutId right_id_;
1915 1916 1917
};


1918 1919
class CountOperation: public Expression {
 public:
1920
  DECLARE_NODE_TYPE(CountOperation)
1921

1922 1923
  bool is_prefix() const { return is_prefix_; }
  bool is_postfix() const { return !is_prefix_; }
1924

1925
  Token::Value op() const { return op_; }
1926
  Token::Value binary_op() {
1927
    return (op() == Token::INC) ? Token::ADD : Token::SUB;
1928
  }
1929

1930
  Expression* expression() const { return expression_; }
1931
  virtual int position() const { return pos_; }
1932 1933 1934

  virtual void MarkAsStatement() { is_prefix_ = true; }

1935
  void RecordTypeFeedback(TypeFeedbackOracle* oracle, Zone* znoe);
1936
  virtual bool IsMonomorphic() { return is_monomorphic_; }
1937
  virtual SmallMapList* GetReceiverTypes() { return &receiver_types_; }
1938 1939 1940
  virtual KeyedAccessStoreMode GetStoreMode() {
    return store_mode_;
  }
1941
  TypeInfo type() const { return type_; }
1942

1943 1944
  BailoutId AssignmentId() const { return assignment_id_; }

1945
  TypeFeedbackId CountBinOpFeedbackId() const { return count_id_; }
1946 1947
  TypeFeedbackId CountStoreFeedbackId() const { return reuse(id()); }

1948 1949 1950 1951 1952 1953 1954 1955 1956
 protected:
  CountOperation(Isolate* isolate,
                 Token::Value op,
                 bool is_prefix,
                 Expression* expr,
                 int pos)
      : Expression(isolate),
        op_(op),
        is_prefix_(is_prefix),
1957 1958
        is_monomorphic_(false),
        store_mode_(STANDARD_STORE),
1959 1960 1961 1962 1963
        expression_(expr),
        pos_(pos),
        assignment_id_(GetNextId(isolate)),
        count_id_(GetNextId(isolate)) {}

1964
 private:
1965
  Token::Value op_;
1966 1967
  bool is_prefix_ : 1;
  bool is_monomorphic_ : 1;
1968 1969
  KeyedAccessStoreMode store_mode_ : 5;  // Windows treats as signed,
                                         // must have extra bit.
1970 1971
  TypeInfo type_;

1972
  Expression* expression_;
1973
  int pos_;
1974
  const BailoutId assignment_id_;
1975
  const TypeFeedbackId count_id_;
1976
  SmallMapList receiver_types_;
1977 1978 1979 1980
};


class CompareOperation: public Expression {
1981
 public:
1982
  DECLARE_NODE_TYPE(CompareOperation)
1983 1984 1985 1986

  Token::Value op() const { return op_; }
  Expression* left() const { return left_; }
  Expression* right() const { return right_; }
1987
  virtual int position() const { return pos_; }
1988

1989
  // Type feedback information.
1990
  TypeFeedbackId CompareOperationFeedbackId() const { return reuse(id()); }
1991 1992
  Handle<Type> combined_type() const { return combined_type_; }
  void set_combined_type(Handle<Type> type) { combined_type_ = type; }
1993

1994 1995 1996
  // Match special cases.
  bool IsLiteralCompareTypeof(Expression** expr, Handle<String>* check);
  bool IsLiteralCompareUndefined(Expression** expr);
1997
  bool IsLiteralCompareNull(Expression** expr);
1998

1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
 protected:
  CompareOperation(Isolate* isolate,
                   Token::Value op,
                   Expression* left,
                   Expression* right,
                   int pos)
      : Expression(isolate),
        op_(op),
        left_(left),
        right_(right),
2009
        pos_(pos) {
2010 2011 2012
    ASSERT(Token::IsCompareOp(op));
  }

2013 2014 2015 2016
 private:
  Token::Value op_;
  Expression* left_;
  Expression* right_;
2017
  int pos_;
2018

2019
  Handle<Type> combined_type_;
2020 2021 2022 2023 2024
};


class Conditional: public Expression {
 public:
2025 2026 2027 2028 2029 2030 2031 2032 2033
  DECLARE_NODE_TYPE(Conditional)

  Expression* condition() const { return condition_; }
  Expression* then_expression() const { return then_expression_; }
  Expression* else_expression() const { return else_expression_; }

  int then_expression_position() const { return then_expression_position_; }
  int else_expression_position() const { return else_expression_position_; }

2034 2035
  BailoutId ThenId() const { return then_id_; }
  BailoutId ElseId() const { return else_id_; }
2036 2037

 protected:
2038 2039
  Conditional(Isolate* isolate,
              Expression* condition,
2040
              Expression* then_expression,
2041 2042 2043
              Expression* else_expression,
              int then_expression_position,
              int else_expression_position)
2044 2045
      : Expression(isolate),
        condition_(condition),
2046
        then_expression_(then_expression),
2047 2048
        else_expression_(else_expression),
        then_expression_position_(then_expression_position),
2049
        else_expression_position_(else_expression_position),
2050
        then_id_(GetNextId(isolate)),
2051
        else_id_(GetNextId(isolate)) { }
2052

2053 2054 2055 2056
 private:
  Expression* condition_;
  Expression* then_expression_;
  Expression* else_expression_;
2057 2058
  int then_expression_position_;
  int else_expression_position_;
2059 2060
  const BailoutId then_id_;
  const BailoutId else_id_;
2061 2062 2063 2064 2065
};


class Assignment: public Expression {
 public:
2066
  DECLARE_NODE_TYPE(Assignment)
2067

2068 2069
  Assignment* AsSimpleAssignment() { return !is_compound() ? this : NULL; }

2070 2071 2072 2073 2074
  Token::Value binary_op() const;

  Token::Value op() const { return op_; }
  Expression* target() const { return target_; }
  Expression* value() const { return value_; }
2075
  virtual int position() const { return pos_; }
2076 2077
  BinaryOperation* binary_operation() const { return binary_operation_; }

2078 2079
  // This check relies on the definition order of token in token.h.
  bool is_compound() const { return op() > Token::ASSIGN; }
2080

2081 2082
  BailoutId AssignmentId() const { return assignment_id_; }

2083
  // Type feedback information.
2084
  TypeFeedbackId AssignmentFeedbackId() { return reuse(id()); }
2085
  void RecordTypeFeedback(TypeFeedbackOracle* oracle, Zone* zone);
2086
  virtual bool IsMonomorphic() { return is_monomorphic_; }
2087
  bool IsUninitialized() { return is_uninitialized_; }
2088
  virtual SmallMapList* GetReceiverTypes() { return &receiver_types_; }
2089 2090 2091
  virtual KeyedAccessStoreMode GetStoreMode() {
    return store_mode_;
  }
2092

2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
 protected:
  Assignment(Isolate* isolate,
             Token::Value op,
             Expression* target,
             Expression* value,
             int pos);

  template<class Visitor>
  void Init(Isolate* isolate, AstNodeFactory<Visitor>* factory) {
    ASSERT(Token::IsAssignmentOp(op_));
    if (is_compound()) {
      binary_operation_ =
          factory->NewBinaryOperation(binary_op(), target_, value_, pos_ + 1);
    }
  }

2109 2110 2111 2112 2113
 private:
  Token::Value op_;
  Expression* target_;
  Expression* value_;
  int pos_;
2114
  BinaryOperation* binary_operation_;
2115
  const BailoutId assignment_id_;
2116

2117
  bool is_monomorphic_ : 1;
2118
  bool is_uninitialized_ : 1;
2119 2120
  KeyedAccessStoreMode store_mode_ : 5;  // Windows treats as signed,
                                         // must have extra bit.
2121
  SmallMapList receiver_types_;
2122 2123 2124
};


2125 2126 2127 2128
class Yield: public Expression {
 public:
  DECLARE_NODE_TYPE(Yield)

2129 2130 2131 2132 2133 2134 2135
  enum Kind {
    INITIAL,     // The initial yield that returns the unboxed generator object.
    SUSPEND,     // A normal yield: { value: EXPRESSION, done: false }
    DELEGATING,  // A yield*.
    FINAL        // A return: { value: EXPRESSION, done: true }
  };

2136
  Expression* generator_object() const { return generator_object_; }
2137
  Expression* expression() const { return expression_; }
2138
  Kind yield_kind() const { return yield_kind_; }
2139 2140
  virtual int position() const { return pos_; }

2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152
  // Delegating yield surrounds the "yield" in a "try/catch".  This index
  // locates the catch handler in the handler table, and is equivalent to
  // TryCatchStatement::index().
  int index() const {
    ASSERT(yield_kind() == DELEGATING);
    return index_;
  }
  void set_index(int index) {
    ASSERT(yield_kind() == DELEGATING);
    index_ = index;
  }

2153 2154
 protected:
  Yield(Isolate* isolate,
2155
        Expression* generator_object,
2156
        Expression* expression,
2157
        Kind yield_kind,
2158 2159
        int pos)
      : Expression(isolate),
2160
        generator_object_(generator_object),
2161
        expression_(expression),
2162
        yield_kind_(yield_kind),
2163
        index_(-1),
2164 2165 2166
        pos_(pos) { }

 private:
2167
  Expression* generator_object_;
2168
  Expression* expression_;
2169
  Kind yield_kind_;
2170
  int index_;
2171 2172 2173 2174
  int pos_;
};


2175 2176
class Throw: public Expression {
 public:
2177
  DECLARE_NODE_TYPE(Throw)
2178

2179
  Expression* exception() const { return exception_; }
2180
  virtual int position() const { return pos_; }
2181 2182 2183 2184

 protected:
  Throw(Isolate* isolate, Expression* exception, int pos)
      : Expression(isolate), exception_(exception), pos_(pos) {}
2185 2186 2187 2188 2189 2190 2191 2192 2193

 private:
  Expression* exception_;
  int pos_;
};


class FunctionLiteral: public Expression {
 public:
2194
  enum FunctionType {
2195 2196 2197 2198 2199
    ANONYMOUS_EXPRESSION,
    NAMED_EXPRESSION,
    DECLARATION
  };

2200 2201 2202 2203 2204 2205 2206 2207 2208 2209
  enum ParameterFlag {
    kNoDuplicateParameters = 0,
    kHasDuplicateParameters = 1
  };

  enum IsFunctionFlag {
    kGlobalOrEval,
    kIsFunction
  };

2210 2211 2212 2213 2214
  enum IsParenthesizedFlag {
    kIsParenthesized,
    kNotParenthesized
  };

2215 2216 2217 2218 2219
  enum IsGeneratorFlag {
    kIsGenerator,
    kNotGenerator
  };

2220
  DECLARE_NODE_TYPE(FunctionLiteral)
2221

2222 2223 2224
  Handle<String> name() const { return name_; }
  Scope* scope() const { return scope_; }
  ZoneList<Statement*>* body() const { return body_; }
2225 2226
  void set_function_token_position(int pos) { function_token_position_ = pos; }
  int function_token_position() const { return function_token_position_; }
2227 2228
  int start_position() const;
  int end_position() const;
2229
  int SourceSize() const { return end_position() - start_position(); }
2230 2231
  bool is_expression() const { return IsExpression::decode(bitfield_); }
  bool is_anonymous() const { return IsAnonymous::decode(bitfield_); }
2232 2233
  bool is_classic_mode() const { return language_mode() == CLASSIC_MODE; }
  LanguageMode language_mode() const;
2234 2235 2236

  int materialized_literal_count() { return materialized_literal_count_; }
  int expected_property_count() { return expected_property_count_; }
2237
  int handler_count() { return handler_count_; }
2238
  int parameter_count() { return parameter_count_; }
2239 2240

  bool AllowsLazyCompilation();
2241
  bool AllowsLazyCompilationWithoutContext();
2242

2243 2244 2245 2246 2247
  Handle<String> debug_name() const {
    if (name_->length() > 0) return name_;
    return inferred_name();
  }

2248
  Handle<String> inferred_name() const { return inferred_name_; }
2249 2250 2251 2252
  void set_inferred_name(Handle<String> inferred_name) {
    inferred_name_ = inferred_name;
  }

2253 2254
  bool pretenure() { return Pretenure::decode(bitfield_); }
  void set_pretenure() { bitfield_ |= Pretenure::encode(true); }
2255

2256 2257 2258
  bool has_duplicate_parameters() {
    return HasDuplicateParameters::decode(bitfield_);
  }
2259

2260 2261
  bool is_function() { return IsFunction::decode(bitfield_) == kIsFunction; }

2262 2263 2264 2265 2266
  // This is used as a heuristic on when to eagerly compile a function
  // literal. We consider the following constructs as hints that the
  // function will be called immediately:
  // - (function() { ... })();
  // - var x = function() { ... }();
2267 2268 2269
  bool is_parenthesized() {
    return IsParenthesized::decode(bitfield_) == kIsParenthesized;
  }
2270 2271 2272
  void set_parenthesized() {
    bitfield_ = IsParenthesized::update(bitfield_, kIsParenthesized);
  }
2273

2274 2275 2276 2277
  bool is_generator() {
    return IsGenerator::decode(bitfield_) == kIsGenerator;
  }

2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
  int ast_node_count() { return ast_properties_.node_count(); }
  AstProperties::Flags* flags() { return ast_properties_.flags(); }
  void set_ast_properties(AstProperties* ast_properties) {
    ast_properties_ = *ast_properties;
  }

 protected:
  FunctionLiteral(Isolate* isolate,
                  Handle<String> name,
                  Scope* scope,
                  ZoneList<Statement*>* body,
                  int materialized_literal_count,
                  int expected_property_count,
                  int handler_count,
                  int parameter_count,
2293
                  FunctionType function_type,
2294
                  ParameterFlag has_duplicate_parameters,
2295
                  IsFunctionFlag is_function,
2296 2297
                  IsParenthesizedFlag is_parenthesized,
                  IsGeneratorFlag is_generator)
2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
      : Expression(isolate),
        name_(name),
        scope_(scope),
        body_(body),
        inferred_name_(isolate->factory()->empty_string()),
        materialized_literal_count_(materialized_literal_count),
        expected_property_count_(expected_property_count),
        handler_count_(handler_count),
        parameter_count_(parameter_count),
        function_token_position_(RelocInfo::kNoPosition) {
    bitfield_ =
2309 2310
        IsExpression::encode(function_type != DECLARATION) |
        IsAnonymous::encode(function_type == ANONYMOUS_EXPRESSION) |
2311
        Pretenure::encode(false) |
2312
        HasDuplicateParameters::encode(has_duplicate_parameters) |
2313
        IsFunction::encode(is_function) |
2314 2315
        IsParenthesized::encode(is_parenthesized) |
        IsGenerator::encode(is_generator);
2316 2317
  }

2318 2319 2320 2321
 private:
  Handle<String> name_;
  Scope* scope_;
  ZoneList<Statement*>* body_;
2322
  Handle<String> inferred_name_;
2323
  AstProperties ast_properties_;
2324

2325 2326
  int materialized_literal_count_;
  int expected_property_count_;
2327
  int handler_count_;
2328
  int parameter_count_;
2329
  int function_token_position_;
2330 2331

  unsigned bitfield_;
2332 2333 2334 2335 2336 2337 2338
  class IsExpression: public BitField<bool, 0, 1> {};
  class IsAnonymous: public BitField<bool, 1, 1> {};
  class Pretenure: public BitField<bool, 2, 1> {};
  class HasDuplicateParameters: public BitField<ParameterFlag, 3, 1> {};
  class IsFunction: public BitField<IsFunctionFlag, 4, 1> {};
  class IsParenthesized: public BitField<IsParenthesizedFlag, 5, 1> {};
  class IsGenerator: public BitField<IsGeneratorFlag, 6, 1> {};
2339 2340 2341
};


2342
class SharedFunctionInfoLiteral: public Expression {
2343
 public:
2344 2345
  DECLARE_NODE_TYPE(SharedFunctionInfoLiteral)

2346 2347 2348
  Handle<SharedFunctionInfo> shared_function_info() const {
    return shared_function_info_;
  }
2349 2350 2351 2352 2353 2354 2355

 protected:
  SharedFunctionInfoLiteral(
      Isolate* isolate,
      Handle<SharedFunctionInfo> shared_function_info)
      : Expression(isolate),
        shared_function_info_(shared_function_info) { }
2356 2357

 private:
2358
  Handle<SharedFunctionInfo> shared_function_info_;
2359 2360 2361 2362 2363
};


class ThisFunction: public Expression {
 public:
2364
  DECLARE_NODE_TYPE(ThisFunction)
2365 2366 2367

 protected:
  explicit ThisFunction(Isolate* isolate): Expression(isolate) {}
2368 2369
};

2370 2371
#undef DECLARE_NODE_TYPE

2372

2373 2374 2375 2376
// ----------------------------------------------------------------------------
// Regular expressions


2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
class RegExpVisitor BASE_EMBEDDED {
 public:
  virtual ~RegExpVisitor() { }
#define MAKE_CASE(Name)                                              \
  virtual void* Visit##Name(RegExp##Name*, void* data) = 0;
  FOR_EACH_REG_EXP_TREE_TYPE(MAKE_CASE)
#undef MAKE_CASE
};


2387 2388
class RegExpTree: public ZoneObject {
 public:
2389
  static const int kInfinity = kMaxInt;
2390 2391 2392
  virtual ~RegExpTree() { }
  virtual void* Accept(RegExpVisitor* visitor, void* data) = 0;
  virtual RegExpNode* ToNode(RegExpCompiler* compiler,
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
2393
                             RegExpNode* on_success) = 0;
2394
  virtual bool IsTextElement() { return false; }
2395 2396
  virtual bool IsAnchoredAtStart() { return false; }
  virtual bool IsAnchoredAtEnd() { return false; }
2397 2398
  virtual int min_match() = 0;
  virtual int max_match() = 0;
2399 2400 2401
  // Returns the interval of registers used for captures within this
  // expression.
  virtual Interval CaptureRegisters() { return Interval::Empty(); }
2402 2403
  virtual void AppendToText(RegExpText* text, Zone* zone);
  SmartArrayPointer<const char> ToString(Zone* zone);
2404 2405 2406 2407 2408 2409 2410 2411 2412 2413
#define MAKE_ASTYPE(Name)                                                  \
  virtual RegExp##Name* As##Name();                                        \
  virtual bool Is##Name();
  FOR_EACH_REG_EXP_TREE_TYPE(MAKE_ASTYPE)
#undef MAKE_ASTYPE
};


class RegExpDisjunction: public RegExpTree {
 public:
2414
  explicit RegExpDisjunction(ZoneList<RegExpTree*>* alternatives);
2415 2416
  virtual void* Accept(RegExpVisitor* visitor, void* data);
  virtual RegExpNode* ToNode(RegExpCompiler* compiler,
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
2417
                             RegExpNode* on_success);
2418
  virtual RegExpDisjunction* AsDisjunction();
2419
  virtual Interval CaptureRegisters();
2420
  virtual bool IsDisjunction();
2421 2422
  virtual bool IsAnchoredAtStart();
  virtual bool IsAnchoredAtEnd();
2423 2424
  virtual int min_match() { return min_match_; }
  virtual int max_match() { return max_match_; }
2425 2426 2427
  ZoneList<RegExpTree*>* alternatives() { return alternatives_; }
 private:
  ZoneList<RegExpTree*>* alternatives_;
2428 2429
  int min_match_;
  int max_match_;
2430 2431 2432 2433 2434
};


class RegExpAlternative: public RegExpTree {
 public:
2435
  explicit RegExpAlternative(ZoneList<RegExpTree*>* nodes);
2436 2437
  virtual void* Accept(RegExpVisitor* visitor, void* data);
  virtual RegExpNode* ToNode(RegExpCompiler* compiler,
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
2438
                             RegExpNode* on_success);
2439
  virtual RegExpAlternative* AsAlternative();
2440
  virtual Interval CaptureRegisters();
2441
  virtual bool IsAlternative();
2442 2443
  virtual bool IsAnchoredAtStart();
  virtual bool IsAnchoredAtEnd();
2444 2445
  virtual int min_match() { return min_match_; }
  virtual int max_match() { return max_match_; }
2446 2447 2448
  ZoneList<RegExpTree*>* nodes() { return nodes_; }
 private:
  ZoneList<RegExpTree*>* nodes_;
2449 2450
  int min_match_;
  int max_match_;
2451 2452 2453 2454 2455
};


class RegExpAssertion: public RegExpTree {
 public:
2456
  enum AssertionType {
2457 2458 2459 2460 2461 2462
    START_OF_LINE,
    START_OF_INPUT,
    END_OF_LINE,
    END_OF_INPUT,
    BOUNDARY,
    NON_BOUNDARY
2463
  };
2464
  explicit RegExpAssertion(AssertionType type) : assertion_type_(type) { }
2465 2466
  virtual void* Accept(RegExpVisitor* visitor, void* data);
  virtual RegExpNode* ToNode(RegExpCompiler* compiler,
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
2467
                             RegExpNode* on_success);
2468 2469
  virtual RegExpAssertion* AsAssertion();
  virtual bool IsAssertion();
2470 2471
  virtual bool IsAnchoredAtStart();
  virtual bool IsAnchoredAtEnd();
2472 2473
  virtual int min_match() { return 0; }
  virtual int max_match() { return 0; }
2474
  AssertionType assertion_type() { return assertion_type_; }
2475
 private:
2476
  AssertionType assertion_type_;
2477 2478 2479
};


2480 2481 2482 2483 2484 2485 2486 2487
class CharacterSet BASE_EMBEDDED {
 public:
  explicit CharacterSet(uc16 standard_set_type)
      : ranges_(NULL),
        standard_set_type_(standard_set_type) {}
  explicit CharacterSet(ZoneList<CharacterRange>* ranges)
      : ranges_(ranges),
        standard_set_type_(0) {}
2488
  ZoneList<CharacterRange>* ranges(Zone* zone);
2489 2490 2491 2492 2493
  uc16 standard_set_type() { return standard_set_type_; }
  void set_standard_set_type(uc16 special_set_type) {
    standard_set_type_ = special_set_type;
  }
  bool is_standard() { return standard_set_type_ != 0; }
2494
  void Canonicalize();
2495 2496 2497 2498 2499 2500 2501 2502
 private:
  ZoneList<CharacterRange>* ranges_;
  // If non-zero, the value represents a standard set (e.g., all whitespace
  // characters) without having to expand the ranges.
  uc16 standard_set_type_;
};


2503 2504 2505
class RegExpCharacterClass: public RegExpTree {
 public:
  RegExpCharacterClass(ZoneList<CharacterRange>* ranges, bool is_negated)
2506
      : set_(ranges),
2507
        is_negated_(is_negated) { }
2508
  explicit RegExpCharacterClass(uc16 type)
2509 2510
      : set_(type),
        is_negated_(false) { }
2511 2512
  virtual void* Accept(RegExpVisitor* visitor, void* data);
  virtual RegExpNode* ToNode(RegExpCompiler* compiler,
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
2513
                             RegExpNode* on_success);
2514 2515 2516
  virtual RegExpCharacterClass* AsCharacterClass();
  virtual bool IsCharacterClass();
  virtual bool IsTextElement() { return true; }
2517 2518
  virtual int min_match() { return 1; }
  virtual int max_match() { return 1; }
2519
  virtual void AppendToText(RegExpText* text, Zone* zone);
2520 2521 2522
  CharacterSet character_set() { return set_; }
  // TODO(lrn): Remove need for complex version if is_standard that
  // recognizes a mangled standard set and just do { return set_.is_special(); }
2523
  bool is_standard(Zone* zone);
2524 2525 2526 2527 2528 2529 2530 2531 2532
  // Returns a value representing the standard character set if is_standard()
  // returns true.
  // Currently used values are:
  // s : unicode whitespace
  // S : unicode non-whitespace
  // w : ASCII word character (digit, letter, underscore)
  // W : non-ASCII word character
  // d : ASCII digit
  // D : non-ASCII digit
2533
  // . : non-unicode non-newline
2534 2535
  // * : All characters
  uc16 standard_type() { return set_.standard_set_type(); }
2536
  ZoneList<CharacterRange>* ranges(Zone* zone) { return set_.ranges(zone); }
2537
  bool is_negated() { return is_negated_; }
2538

2539
 private:
2540
  CharacterSet set_;
2541 2542 2543 2544 2545 2546 2547 2548 2549
  bool is_negated_;
};


class RegExpAtom: public RegExpTree {
 public:
  explicit RegExpAtom(Vector<const uc16> data) : data_(data) { }
  virtual void* Accept(RegExpVisitor* visitor, void* data);
  virtual RegExpNode* ToNode(RegExpCompiler* compiler,
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
2550
                             RegExpNode* on_success);
2551 2552 2553
  virtual RegExpAtom* AsAtom();
  virtual bool IsAtom();
  virtual bool IsTextElement() { return true; }
2554 2555
  virtual int min_match() { return data_.length(); }
  virtual int max_match() { return data_.length(); }
2556
  virtual void AppendToText(RegExpText* text, Zone* zone);
2557
  Vector<const uc16> data() { return data_; }
2558
  int length() { return data_.length(); }
2559 2560 2561 2562 2563
 private:
  Vector<const uc16> data_;
};


2564 2565
class RegExpText: public RegExpTree {
 public:
2566
  explicit RegExpText(Zone* zone) : elements_(2, zone), length_(0) {}
2567 2568 2569 2570 2571 2572 2573 2574
  virtual void* Accept(RegExpVisitor* visitor, void* data);
  virtual RegExpNode* ToNode(RegExpCompiler* compiler,
                             RegExpNode* on_success);
  virtual RegExpText* AsText();
  virtual bool IsText();
  virtual bool IsTextElement() { return true; }
  virtual int min_match() { return length_; }
  virtual int max_match() { return length_; }
2575 2576 2577
  virtual void AppendToText(RegExpText* text, Zone* zone);
  void AddElement(TextElement elm, Zone* zone)  {
    elements_.Add(elm, zone);
2578
    length_ += elm.length();
2579
  }
2580 2581 2582 2583 2584 2585 2586
  ZoneList<TextElement>* elements() { return &elements_; }
 private:
  ZoneList<TextElement> elements_;
  int length_;
};


2587 2588
class RegExpQuantifier: public RegExpTree {
 public:
2589 2590
  enum QuantifierType { GREEDY, NON_GREEDY, POSSESSIVE };
  RegExpQuantifier(int min, int max, QuantifierType type, RegExpTree* body)
2591 2592
      : body_(body),
        min_(min),
2593
        max_(max),
2594
        min_match_(min * body->min_match()),
2595
        quantifier_type_(type) {
2596 2597 2598 2599 2600 2601
    if (max > 0 && body->max_match() > kInfinity / max) {
      max_match_ = kInfinity;
    } else {
      max_match_ = max * body->max_match();
    }
  }
2602 2603
  virtual void* Accept(RegExpVisitor* visitor, void* data);
  virtual RegExpNode* ToNode(RegExpCompiler* compiler,
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
2604
                             RegExpNode* on_success);
2605 2606 2607 2608 2609
  static RegExpNode* ToNode(int min,
                            int max,
                            bool is_greedy,
                            RegExpTree* body,
                            RegExpCompiler* compiler,
2610 2611
                            RegExpNode* on_success,
                            bool not_at_start = false);
2612
  virtual RegExpQuantifier* AsQuantifier();
2613
  virtual Interval CaptureRegisters();
2614
  virtual bool IsQuantifier();
2615 2616
  virtual int min_match() { return min_match_; }
  virtual int max_match() { return max_match_; }
2617 2618
  int min() { return min_; }
  int max() { return max_; }
2619 2620 2621
  bool is_possessive() { return quantifier_type_ == POSSESSIVE; }
  bool is_non_greedy() { return quantifier_type_ == NON_GREEDY; }
  bool is_greedy() { return quantifier_type_ == GREEDY; }
2622
  RegExpTree* body() { return body_; }
2623

2624
 private:
2625
  RegExpTree* body_;
2626 2627
  int min_;
  int max_;
2628 2629
  int min_match_;
  int max_match_;
2630
  QuantifierType quantifier_type_;
2631 2632 2633 2634 2635 2636
};


class RegExpCapture: public RegExpTree {
 public:
  explicit RegExpCapture(RegExpTree* body, int index)
2637
      : body_(body), index_(index) { }
2638 2639
  virtual void* Accept(RegExpVisitor* visitor, void* data);
  virtual RegExpNode* ToNode(RegExpCompiler* compiler,
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
2640
                             RegExpNode* on_success);
2641 2642 2643
  static RegExpNode* ToNode(RegExpTree* body,
                            int index,
                            RegExpCompiler* compiler,
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
2644
                            RegExpNode* on_success);
2645
  virtual RegExpCapture* AsCapture();
2646 2647
  virtual bool IsAnchoredAtStart();
  virtual bool IsAnchoredAtEnd();
2648
  virtual Interval CaptureRegisters();
2649
  virtual bool IsCapture();
2650 2651
  virtual int min_match() { return body_->min_match(); }
  virtual int max_match() { return body_->max_match(); }
2652 2653 2654 2655
  RegExpTree* body() { return body_; }
  int index() { return index_; }
  static int StartRegister(int index) { return index * 2; }
  static int EndRegister(int index) { return index * 2 + 1; }
2656

2657 2658 2659 2660 2661 2662 2663 2664
 private:
  RegExpTree* body_;
  int index_;
};


class RegExpLookahead: public RegExpTree {
 public:
2665 2666 2667 2668
  RegExpLookahead(RegExpTree* body,
                  bool is_positive,
                  int capture_count,
                  int capture_from)
2669
      : body_(body),
2670 2671 2672 2673
        is_positive_(is_positive),
        capture_count_(capture_count),
        capture_from_(capture_from) { }

2674 2675
  virtual void* Accept(RegExpVisitor* visitor, void* data);
  virtual RegExpNode* ToNode(RegExpCompiler* compiler,
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
2676
                             RegExpNode* on_success);
2677
  virtual RegExpLookahead* AsLookahead();
2678
  virtual Interval CaptureRegisters();
2679
  virtual bool IsLookahead();
2680
  virtual bool IsAnchoredAtStart();
2681 2682
  virtual int min_match() { return 0; }
  virtual int max_match() { return 0; }
2683 2684
  RegExpTree* body() { return body_; }
  bool is_positive() { return is_positive_; }
2685 2686
  int capture_count() { return capture_count_; }
  int capture_from() { return capture_from_; }
2687

2688 2689 2690
 private:
  RegExpTree* body_;
  bool is_positive_;
2691 2692
  int capture_count_;
  int capture_from_;
2693 2694 2695 2696 2697 2698
};


class RegExpBackReference: public RegExpTree {
 public:
  explicit RegExpBackReference(RegExpCapture* capture)
2699
      : capture_(capture) { }
2700 2701
  virtual void* Accept(RegExpVisitor* visitor, void* data);
  virtual RegExpNode* ToNode(RegExpCompiler* compiler,
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
2702
                             RegExpNode* on_success);
2703 2704
  virtual RegExpBackReference* AsBackReference();
  virtual bool IsBackReference();
2705
  virtual int min_match() { return 0; }
2706
  virtual int max_match() { return capture_->max_match(); }
2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718
  int index() { return capture_->index(); }
  RegExpCapture* capture() { return capture_; }
 private:
  RegExpCapture* capture_;
};


class RegExpEmpty: public RegExpTree {
 public:
  RegExpEmpty() { }
  virtual void* Accept(RegExpVisitor* visitor, void* data);
  virtual RegExpNode* ToNode(RegExpCompiler* compiler,
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
2719
                             RegExpNode* on_success);
2720 2721
  virtual RegExpEmpty* AsEmpty();
  virtual bool IsEmpty();
2722 2723
  virtual int min_match() { return 0; }
  virtual int max_match() { return 0; }
2724 2725 2726 2727
  static RegExpEmpty* GetInstance() {
    static RegExpEmpty* instance = ::new RegExpEmpty();
    return instance;
  }
2728 2729 2730
};


2731 2732 2733 2734 2735 2736 2737 2738 2739
// ----------------------------------------------------------------------------
// Out-of-line inline constructors (to side-step cyclic dependencies).

inline ModuleVariable::ModuleVariable(VariableProxy* proxy)
    : Module(proxy->interface()),
      proxy_(proxy) {
}


2740 2741 2742 2743
// ----------------------------------------------------------------------------
// Basic visitor
// - leaf node visitors are abstract.

2744
class AstVisitor BASE_EMBEDDED {
2745
 public:
2746
  AstVisitor() {}
2747
  virtual ~AstVisitor() { }
2748

2749
  // Stack overflow check and dynamic dispatch.
2750
  virtual void Visit(AstNode* node) = 0;
2751

2752
  // Iteration left-to-right.
2753
  virtual void VisitDeclarations(ZoneList<Declaration*>* declarations);
2754 2755 2756
  virtual void VisitStatements(ZoneList<Statement*>* statements);
  virtual void VisitExpressions(ZoneList<Expression*>* expressions);

2757
  // Individual AST nodes.
2758 2759
#define DEF_VISIT(type)                         \
  virtual void Visit##type(type* node) = 0;
2760
  AST_NODE_LIST(DEF_VISIT)
2761
#undef DEF_VISIT
2762
};
2763

2764

2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790
#define DEFINE_AST_VISITOR_SUBCLASS_MEMBERS()                       \
public:                                                             \
  virtual void Visit(AstNode* node) {                               \
    if (!CheckStackOverflow()) node->Accept(this);                  \
  }                                                                 \
                                                                    \
  void SetStackOverflow() { stack_overflow_ = true; }               \
  void ClearStackOverflow() { stack_overflow_ = false; }            \
  bool HasStackOverflow() const { return stack_overflow_; }         \
                                                                    \
  bool CheckStackOverflow() {                                       \
    if (stack_overflow_) return true;                               \
    StackLimitCheck check(isolate_);                                \
    if (!check.HasOverflowed()) return false;                       \
    return (stack_overflow_ = true);                                \
  }                                                                 \
                                                                    \
private:                                                            \
  void InitializeAstVisitor() {                                     \
    isolate_ = Isolate::Current();                                  \
    stack_overflow_ = false;                                        \
  }                                                                 \
  Isolate* isolate() { return isolate_; }                           \
                                                                    \
  Isolate* isolate_;                                                \
  bool stack_overflow_
2791

2792

2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834
// ----------------------------------------------------------------------------
// Construction time visitor.

class AstConstructionVisitor BASE_EMBEDDED {
 public:
  AstConstructionVisitor() { }

  AstProperties* ast_properties() { return &properties_; }

 private:
  template<class> friend class AstNodeFactory;

  // Node visitors.
#define DEF_VISIT(type) \
  void Visit##type(type* node);
  AST_NODE_LIST(DEF_VISIT)
#undef DEF_VISIT

  void increase_node_count() { properties_.add_node_count(1); }
  void add_flag(AstPropertiesFlag flag) { properties_.flags()->Add(flag); }

  AstProperties properties_;
};


class AstNullVisitor BASE_EMBEDDED {
 public:
  // Node visitors.
#define DEF_VISIT(type) \
  void Visit##type(type* node) {}
  AST_NODE_LIST(DEF_VISIT)
#undef DEF_VISIT
};



// ----------------------------------------------------------------------------
// AstNode factory

template<class Visitor>
class AstNodeFactory BASE_EMBEDDED {
 public:
2835
  AstNodeFactory(Isolate* isolate, Zone* zone)
2836
      : isolate_(isolate),
2837
        zone_(zone) { }
2838 2839 2840 2841 2842 2843 2844

  Visitor* visitor() { return &visitor_; }

#define VISIT_AND_RETURN(NodeType, node) \
  visitor_.Visit##NodeType((node)); \
  return node;

2845 2846 2847 2848
  VariableDeclaration* NewVariableDeclaration(VariableProxy* proxy,
                                              VariableMode mode,
                                              Scope* scope) {
    VariableDeclaration* decl =
2849
        new(zone_) VariableDeclaration(proxy, mode, scope);
2850 2851 2852
    VISIT_AND_RETURN(VariableDeclaration, decl)
  }

2853 2854 2855 2856 2857 2858 2859 2860 2861
  FunctionDeclaration* NewFunctionDeclaration(VariableProxy* proxy,
                                              VariableMode mode,
                                              FunctionLiteral* fun,
                                              Scope* scope) {
    FunctionDeclaration* decl =
        new(zone_) FunctionDeclaration(proxy, mode, fun, scope);
    VISIT_AND_RETURN(FunctionDeclaration, decl)
  }

2862 2863 2864 2865 2866 2867 2868 2869
  ModuleDeclaration* NewModuleDeclaration(VariableProxy* proxy,
                                          Module* module,
                                          Scope* scope) {
    ModuleDeclaration* decl =
        new(zone_) ModuleDeclaration(proxy, module, scope);
    VISIT_AND_RETURN(ModuleDeclaration, decl)
  }

2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884
  ImportDeclaration* NewImportDeclaration(VariableProxy* proxy,
                                          Module* module,
                                          Scope* scope) {
    ImportDeclaration* decl =
        new(zone_) ImportDeclaration(proxy, module, scope);
    VISIT_AND_RETURN(ImportDeclaration, decl)
  }

  ExportDeclaration* NewExportDeclaration(VariableProxy* proxy,
                                          Scope* scope) {
    ExportDeclaration* decl =
        new(zone_) ExportDeclaration(proxy, scope);
    VISIT_AND_RETURN(ExportDeclaration, decl)
  }

2885 2886
  ModuleLiteral* NewModuleLiteral(Block* body, Interface* interface) {
    ModuleLiteral* module = new(zone_) ModuleLiteral(body, interface);
2887 2888 2889
    VISIT_AND_RETURN(ModuleLiteral, module)
  }

2890 2891 2892
  ModuleVariable* NewModuleVariable(VariableProxy* proxy) {
    ModuleVariable* module = new(zone_) ModuleVariable(proxy);
    VISIT_AND_RETURN(ModuleVariable, module)
2893 2894 2895
  }

  ModulePath* NewModulePath(Module* origin, Handle<String> name) {
2896
    ModulePath* module = new(zone_) ModulePath(origin, name, zone_);
2897
    VISIT_AND_RETURN(ModulePath, module)
2898 2899 2900
  }

  ModuleUrl* NewModuleUrl(Handle<String> url) {
2901
    ModuleUrl* module = new(zone_) ModuleUrl(url, zone_);
2902
    VISIT_AND_RETURN(ModuleUrl, module)
2903 2904
  }

2905 2906
  Block* NewBlock(ZoneStringList* labels,
                  int capacity,
2907
                  bool is_initializer_block) {
2908
    Block* block = new(zone_) Block(
2909
        isolate_, labels, capacity, is_initializer_block, zone_);
2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923
    VISIT_AND_RETURN(Block, block)
  }

#define STATEMENT_WITH_LABELS(NodeType) \
  NodeType* New##NodeType(ZoneStringList* labels) { \
    NodeType* stmt = new(zone_) NodeType(isolate_, labels); \
    VISIT_AND_RETURN(NodeType, stmt); \
  }
  STATEMENT_WITH_LABELS(DoWhileStatement)
  STATEMENT_WITH_LABELS(WhileStatement)
  STATEMENT_WITH_LABELS(ForStatement)
  STATEMENT_WITH_LABELS(SwitchStatement)
#undef STATEMENT_WITH_LABELS

2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939
  ForEachStatement* NewForEachStatement(ForEachStatement::VisitMode visit_mode,
                                        ZoneStringList* labels) {
    switch (visit_mode) {
      case ForEachStatement::ENUMERATE: {
        ForInStatement* stmt = new(zone_) ForInStatement(isolate_, labels);
        VISIT_AND_RETURN(ForInStatement, stmt);
      }
      case ForEachStatement::ITERATE: {
        ForOfStatement* stmt = new(zone_) ForOfStatement(isolate_, labels);
        VISIT_AND_RETURN(ForOfStatement, stmt);
      }
    }
    UNREACHABLE();
    return NULL;
  }

2940 2941 2942 2943 2944
  ModuleStatement* NewModuleStatement(VariableProxy* proxy, Block* body) {
    ModuleStatement* stmt = new(zone_) ModuleStatement(proxy, body);
    VISIT_AND_RETURN(ModuleStatement, stmt)
  }

2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964
  ExpressionStatement* NewExpressionStatement(Expression* expression) {
    ExpressionStatement* stmt = new(zone_) ExpressionStatement(expression);
    VISIT_AND_RETURN(ExpressionStatement, stmt)
  }

  ContinueStatement* NewContinueStatement(IterationStatement* target) {
    ContinueStatement* stmt = new(zone_) ContinueStatement(target);
    VISIT_AND_RETURN(ContinueStatement, stmt)
  }

  BreakStatement* NewBreakStatement(BreakableStatement* target) {
    BreakStatement* stmt = new(zone_) BreakStatement(target);
    VISIT_AND_RETURN(BreakStatement, stmt)
  }

  ReturnStatement* NewReturnStatement(Expression* expression) {
    ReturnStatement* stmt = new(zone_) ReturnStatement(expression);
    VISIT_AND_RETURN(ReturnStatement, stmt)
  }

2965 2966
  WithStatement* NewWithStatement(Scope* scope,
                                  Expression* expression,
2967
                                  Statement* statement) {
2968 2969
    WithStatement* stmt = new(zone_) WithStatement(
        scope, expression, statement);
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023
    VISIT_AND_RETURN(WithStatement, stmt)
  }

  IfStatement* NewIfStatement(Expression* condition,
                              Statement* then_statement,
                              Statement* else_statement) {
    IfStatement* stmt = new(zone_) IfStatement(
        isolate_, condition, then_statement, else_statement);
    VISIT_AND_RETURN(IfStatement, stmt)
  }

  TryCatchStatement* NewTryCatchStatement(int index,
                                          Block* try_block,
                                          Scope* scope,
                                          Variable* variable,
                                          Block* catch_block) {
    TryCatchStatement* stmt = new(zone_) TryCatchStatement(
        index, try_block, scope, variable, catch_block);
    VISIT_AND_RETURN(TryCatchStatement, stmt)
  }

  TryFinallyStatement* NewTryFinallyStatement(int index,
                                              Block* try_block,
                                              Block* finally_block) {
    TryFinallyStatement* stmt =
        new(zone_) TryFinallyStatement(index, try_block, finally_block);
    VISIT_AND_RETURN(TryFinallyStatement, stmt)
  }

  DebuggerStatement* NewDebuggerStatement() {
    DebuggerStatement* stmt = new(zone_) DebuggerStatement();
    VISIT_AND_RETURN(DebuggerStatement, stmt)
  }

  EmptyStatement* NewEmptyStatement() {
    return new(zone_) EmptyStatement();
  }

  Literal* NewLiteral(Handle<Object> handle) {
    Literal* lit = new(zone_) Literal(isolate_, handle);
    VISIT_AND_RETURN(Literal, lit)
  }

  Literal* NewNumberLiteral(double number) {
    return NewLiteral(isolate_->factory()->NewNumber(number, TENURED));
  }

  ObjectLiteral* NewObjectLiteral(
      Handle<FixedArray> constant_properties,
      ZoneList<ObjectLiteral::Property*>* properties,
      int literal_index,
      bool is_simple,
      bool fast_elements,
      int depth,
3024
      bool may_store_doubles,
3025 3026 3027
      bool has_function) {
    ObjectLiteral* lit = new(zone_) ObjectLiteral(
        isolate_, constant_properties, properties, literal_index,
3028
        is_simple, fast_elements, depth, may_store_doubles, has_function);
3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064
    VISIT_AND_RETURN(ObjectLiteral, lit)
  }

  ObjectLiteral::Property* NewObjectLiteralProperty(bool is_getter,
                                                    FunctionLiteral* value) {
    ObjectLiteral::Property* prop =
        new(zone_) ObjectLiteral::Property(is_getter, value);
    prop->set_key(NewLiteral(value->name()));
    return prop;  // Not an AST node, will not be visited.
  }

  RegExpLiteral* NewRegExpLiteral(Handle<String> pattern,
                                  Handle<String> flags,
                                  int literal_index) {
    RegExpLiteral* lit =
        new(zone_) RegExpLiteral(isolate_, pattern, flags, literal_index);
    VISIT_AND_RETURN(RegExpLiteral, lit);
  }

  ArrayLiteral* NewArrayLiteral(Handle<FixedArray> constant_elements,
                                ZoneList<Expression*>* values,
                                int literal_index,
                                bool is_simple,
                                int depth) {
    ArrayLiteral* lit = new(zone_) ArrayLiteral(
        isolate_, constant_elements, values, literal_index, is_simple, depth);
    VISIT_AND_RETURN(ArrayLiteral, lit)
  }

  VariableProxy* NewVariableProxy(Variable* var) {
    VariableProxy* proxy = new(zone_) VariableProxy(isolate_, var);
    VISIT_AND_RETURN(VariableProxy, proxy)
  }

  VariableProxy* NewVariableProxy(Handle<String> name,
                                  bool is_this,
3065 3066
                                  Interface* interface = Interface::NewValue(),
                                  int position = RelocInfo::kNoPosition) {
3067
    VariableProxy* proxy =
3068
        new(zone_) VariableProxy(isolate_, name, is_this, interface, position);
3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154
    VISIT_AND_RETURN(VariableProxy, proxy)
  }

  Property* NewProperty(Expression* obj, Expression* key, int pos) {
    Property* prop = new(zone_) Property(isolate_, obj, key, pos);
    VISIT_AND_RETURN(Property, prop)
  }

  Call* NewCall(Expression* expression,
                ZoneList<Expression*>* arguments,
                int pos) {
    Call* call = new(zone_) Call(isolate_, expression, arguments, pos);
    VISIT_AND_RETURN(Call, call)
  }

  CallNew* NewCallNew(Expression* expression,
                      ZoneList<Expression*>* arguments,
                      int pos) {
    CallNew* call = new(zone_) CallNew(isolate_, expression, arguments, pos);
    VISIT_AND_RETURN(CallNew, call)
  }

  CallRuntime* NewCallRuntime(Handle<String> name,
                              const Runtime::Function* function,
                              ZoneList<Expression*>* arguments) {
    CallRuntime* call =
        new(zone_) CallRuntime(isolate_, name, function, arguments);
    VISIT_AND_RETURN(CallRuntime, call)
  }

  UnaryOperation* NewUnaryOperation(Token::Value op,
                                    Expression* expression,
                                    int pos) {
    UnaryOperation* node =
        new(zone_) UnaryOperation(isolate_, op, expression, pos);
    VISIT_AND_RETURN(UnaryOperation, node)
  }

  BinaryOperation* NewBinaryOperation(Token::Value op,
                                      Expression* left,
                                      Expression* right,
                                      int pos) {
    BinaryOperation* node =
        new(zone_) BinaryOperation(isolate_, op, left, right, pos);
    VISIT_AND_RETURN(BinaryOperation, node)
  }

  CountOperation* NewCountOperation(Token::Value op,
                                    bool is_prefix,
                                    Expression* expr,
                                    int pos) {
    CountOperation* node =
        new(zone_) CountOperation(isolate_, op, is_prefix, expr, pos);
    VISIT_AND_RETURN(CountOperation, node)
  }

  CompareOperation* NewCompareOperation(Token::Value op,
                                        Expression* left,
                                        Expression* right,
                                        int pos) {
    CompareOperation* node =
        new(zone_) CompareOperation(isolate_, op, left, right, pos);
    VISIT_AND_RETURN(CompareOperation, node)
  }

  Conditional* NewConditional(Expression* condition,
                              Expression* then_expression,
                              Expression* else_expression,
                              int then_expression_position,
                              int else_expression_position) {
    Conditional* cond = new(zone_) Conditional(
        isolate_, condition, then_expression, else_expression,
        then_expression_position, else_expression_position);
    VISIT_AND_RETURN(Conditional, cond)
  }

  Assignment* NewAssignment(Token::Value op,
                            Expression* target,
                            Expression* value,
                            int pos) {
    Assignment* assign =
        new(zone_) Assignment(isolate_, op, target, value, pos);
    assign->Init(isolate_, this);
    VISIT_AND_RETURN(Assignment, assign)
  }

3155 3156
  Yield* NewYield(Expression *generator_object,
                  Expression* expression,
3157
                  Yield::Kind yield_kind,
3158 3159
                  int pos) {
    Yield* yield = new(zone_) Yield(
3160
        isolate_, generator_object, expression, yield_kind, pos);
3161 3162 3163
    VISIT_AND_RETURN(Yield, yield)
  }

3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176
  Throw* NewThrow(Expression* exception, int pos) {
    Throw* t = new(zone_) Throw(isolate_, exception, pos);
    VISIT_AND_RETURN(Throw, t)
  }

  FunctionLiteral* NewFunctionLiteral(
      Handle<String> name,
      Scope* scope,
      ZoneList<Statement*>* body,
      int materialized_literal_count,
      int expected_property_count,
      int handler_count,
      int parameter_count,
3177
      FunctionLiteral::ParameterFlag has_duplicate_parameters,
3178
      FunctionLiteral::FunctionType function_type,
3179
      FunctionLiteral::IsFunctionFlag is_function,
3180 3181
      FunctionLiteral::IsParenthesizedFlag is_parenthesized,
      FunctionLiteral::IsGeneratorFlag is_generator) {
3182 3183 3184
    FunctionLiteral* lit = new(zone_) FunctionLiteral(
        isolate_, name, scope, body,
        materialized_literal_count, expected_property_count, handler_count,
3185
        parameter_count, function_type, has_duplicate_parameters, is_function,
3186
        is_parenthesized, is_generator);
3187 3188
    // Top-level literal doesn't count for the AST's properties.
    if (is_function == FunctionLiteral::kIsFunction) {
3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214
      visitor_.VisitFunctionLiteral(lit);
    }
    return lit;
  }

  SharedFunctionInfoLiteral* NewSharedFunctionInfoLiteral(
      Handle<SharedFunctionInfo> shared_function_info) {
    SharedFunctionInfoLiteral* lit =
        new(zone_) SharedFunctionInfoLiteral(isolate_, shared_function_info);
    VISIT_AND_RETURN(SharedFunctionInfoLiteral, lit)
  }

  ThisFunction* NewThisFunction() {
    ThisFunction* fun = new(zone_) ThisFunction(isolate_);
    VISIT_AND_RETURN(ThisFunction, fun)
  }

#undef VISIT_AND_RETURN

 private:
  Isolate* isolate_;
  Zone* zone_;
  Visitor visitor_;
};


3215 3216 3217
} }  // namespace v8::internal

#endif  // V8_AST_H_