v8  3.14.5(node0.10.28)
V8 is Google's open source JavaScript engine
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
parser.h
Go to the documentation of this file.
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 
28 #ifndef V8_PARSER_H_
29 #define V8_PARSER_H_
30 
31 #include "allocation.h"
32 #include "ast.h"
33 #include "preparse-data-format.h"
34 #include "preparse-data.h"
35 #include "scopes.h"
36 #include "preparser.h"
37 
38 namespace v8 {
39 namespace internal {
40 
41 class CompilationInfo;
42 class FuncNameInferrer;
43 class ParserLog;
44 class PositionStack;
45 class Target;
46 
47 template <typename T> class ZoneListWrapper;
48 
49 
50 class ParserMessage : public Malloced {
51  public:
54  : loc_(loc),
55  message_(message),
56  args_(args) { }
58  Scanner::Location location() { return loc_; }
59  const char* message() { return message_; }
60  Vector<const char*> args() { return args_; }
61  private:
62  Scanner::Location loc_;
63  const char* message_;
64  Vector<const char*> args_;
65 };
66 
67 
68 class FunctionEntry BASE_EMBEDDED {
69  public:
70  enum {
76  kSize
77  };
78 
79  explicit FunctionEntry(Vector<unsigned> backing)
80  : backing_(backing) { }
81 
82  FunctionEntry() : backing_() { }
83 
84  int start_pos() { return backing_[kStartPositionIndex]; }
85  int end_pos() { return backing_[kEndPositionIndex]; }
86  int literal_count() { return backing_[kLiteralCountIndex]; }
87  int property_count() { return backing_[kPropertyCountIndex]; }
89  ASSERT(backing_[kLanguageModeIndex] == CLASSIC_MODE ||
90  backing_[kLanguageModeIndex] == STRICT_MODE ||
91  backing_[kLanguageModeIndex] == EXTENDED_MODE);
92  return static_cast<LanguageMode>(backing_[kLanguageModeIndex]);
93  }
94 
95  bool is_valid() { return !backing_.is_empty(); }
96 
97  private:
98  Vector<unsigned> backing_;
99  bool owns_data_;
100 };
101 
102 
103 class ScriptDataImpl : public ScriptData {
104  public:
106  : store_(store),
107  owns_store_(true) { }
108 
109  // Create an empty ScriptDataImpl that is guaranteed to not satisfy
110  // a SanityCheck.
111  ScriptDataImpl() : owns_store_(false) { }
112 
113  virtual ~ScriptDataImpl();
114  virtual int Length();
115  virtual const char* Data();
116  virtual bool HasError();
117 
118  void Initialize();
119  void ReadNextSymbolPosition();
120 
121  FunctionEntry GetFunctionEntry(int start);
122  int GetSymbolIdentifier();
123  bool SanityCheck();
124 
126  const char* BuildMessage();
128 
129  int symbol_count() {
130  return (store_.length() > PreparseDataConstants::kHeaderSize)
132  : 0;
133  }
134  // The following functions should only be called if SanityCheck has
135  // returned true.
137  unsigned magic() { return store_[PreparseDataConstants::kMagicOffset]; }
138  unsigned version() { return store_[PreparseDataConstants::kVersionOffset]; }
139 
140  private:
141  Vector<unsigned> store_;
142  unsigned char* symbol_data_;
143  unsigned char* symbol_data_end_;
144  int function_index_;
145  bool owns_store_;
146 
147  unsigned Read(int position);
148  unsigned* ReadAddress(int position);
149  // Reads a number from the current symbols
150  int ReadNumber(byte** source);
151 
152  ScriptDataImpl(const char* backing_store, int length)
153  : store_(reinterpret_cast<unsigned*>(const_cast<char*>(backing_store)),
154  length / static_cast<int>(sizeof(unsigned))),
155  owns_store_(false) {
156  ASSERT_EQ(0, static_cast<int>(
157  reinterpret_cast<intptr_t>(backing_store) % sizeof(unsigned)));
158  }
159 
160  // Read strings written by ParserRecorder::WriteString.
161  static const char* ReadString(unsigned* start, int* chars);
162 
163  friend class ScriptData;
164 };
165 
166 
167 class ParserApi {
168  public:
169  // Parses the source code represented by the compilation info and sets its
170  // function literal. Returns false (and deallocates any allocated AST
171  // nodes) if parsing failed.
172  static bool Parse(CompilationInfo* info, int flags);
173 
174  // Generic preparser generating full preparse data.
176  v8::Extension* extension,
177  int flags);
178 };
179 
180 // ----------------------------------------------------------------------------
181 // REGEXP PARSING
182 
183 // A BufferedZoneList is an automatically growing list, just like (and backed
184 // by) a ZoneList, that is optimized for the case of adding and removing
185 // a single element. The last element added is stored outside the backing list,
186 // and if no more than one element is ever added, the ZoneList isn't even
187 // allocated.
188 // Elements must not be NULL pointers.
189 template <typename T, int initial_size>
191  public:
192  BufferedZoneList() : list_(NULL), last_(NULL) {}
193 
194  // Adds element at end of list. This element is buffered and can
195  // be read using last() or removed using RemoveLast until a new Add or until
196  // RemoveLast or GetList has been called.
197  void Add(T* value, Zone* zone) {
198  if (last_ != NULL) {
199  if (list_ == NULL) {
200  list_ = new(zone) ZoneList<T*>(initial_size, zone);
201  }
202  list_->Add(last_, zone);
203  }
204  last_ = value;
205  }
206 
207  T* last() {
208  ASSERT(last_ != NULL);
209  return last_;
210  }
211 
213  ASSERT(last_ != NULL);
214  T* result = last_;
215  if ((list_ != NULL) && (list_->length() > 0))
216  last_ = list_->RemoveLast();
217  else
218  last_ = NULL;
219  return result;
220  }
221 
222  T* Get(int i) {
223  ASSERT((0 <= i) && (i < length()));
224  if (list_ == NULL) {
225  ASSERT_EQ(0, i);
226  return last_;
227  } else {
228  if (i == list_->length()) {
229  ASSERT(last_ != NULL);
230  return last_;
231  } else {
232  return list_->at(i);
233  }
234  }
235  }
236 
237  void Clear() {
238  list_ = NULL;
239  last_ = NULL;
240  }
241 
242  int length() {
243  int length = (list_ == NULL) ? 0 : list_->length();
244  return length + ((last_ == NULL) ? 0 : 1);
245  }
246 
248  if (list_ == NULL) {
249  list_ = new(zone) ZoneList<T*>(initial_size, zone);
250  }
251  if (last_ != NULL) {
252  list_->Add(last_, zone);
253  last_ = NULL;
254  }
255  return list_;
256  }
257 
258  private:
259  ZoneList<T*>* list_;
260  T* last_;
261 };
262 
263 
264 // Accumulates RegExp atoms and assertions into lists of terms and alternatives.
265 class RegExpBuilder: public ZoneObject {
266  public:
267  explicit RegExpBuilder(Zone* zone);
268  void AddCharacter(uc16 character);
269  // "Adds" an empty expression. Does nothing except consume a
270  // following quantifier
271  void AddEmpty();
272  void AddAtom(RegExpTree* tree);
273  void AddAssertion(RegExpTree* tree);
274  void NewAlternative(); // '|'
275  void AddQuantifierToAtom(int min, int max, RegExpQuantifier::Type type);
276  RegExpTree* ToRegExp();
277 
278  private:
279  void FlushCharacters();
280  void FlushText();
281  void FlushTerms();
282  Zone* zone() const { return zone_; }
283 
284  Zone* zone_;
285  bool pending_empty_;
286  ZoneList<uc16>* characters_;
289  BufferedZoneList<RegExpTree, 2> alternatives_;
290 #ifdef DEBUG
291  enum {ADD_NONE, ADD_CHAR, ADD_TERM, ADD_ASSERT, ADD_ATOM} last_added_;
292 #define LAST(x) last_added_ = x;
293 #else
294 #define LAST(x)
295 #endif
296 };
297 
298 
300  public:
302  Handle<String>* error,
303  bool multiline_mode,
304  Zone* zone);
305 
306  static bool ParseRegExp(FlatStringReader* input,
307  bool multiline,
308  RegExpCompileData* result,
309  Zone* zone);
310 
315 
316  // Parses a {...,...} quantifier and stores the range in the given
317  // out parameters.
318  bool ParseIntervalQuantifier(int* min_out, int* max_out);
319 
320  // Parses and returns a single escaped character. The character
321  // must not be 'b' or 'B' since they are usually handle specially.
323 
324  // Checks whether the following is a length-digit hexadecimal number,
325  // and sets the value if it is.
326  bool ParseHexEscape(int length, uc32* value);
327 
329 
330  // Tries to parse the input as a back reference. If successful it
331  // stores the result in the output parameter and returns true. If
332  // it fails it will push back the characters read so the same characters
333  // can be reparsed.
334  bool ParseBackReferenceIndex(int* index_out);
335 
336  CharacterRange ParseClassAtom(uc16* char_class);
338  void Advance();
339  void Advance(int dist);
340  void Reset(int pos);
341 
342  // Reports whether the pattern might be used as a literal search string.
343  // Only use if the result of the parse is a single atom node.
344  bool simple();
345  bool contains_anchor() { return contains_anchor_; }
346  void set_contains_anchor() { contains_anchor_ = true; }
347  int captures_started() { return captures_ == NULL ? 0 : captures_->length(); }
348  int position() { return next_pos_ - 1; }
349  bool failed() { return failed_; }
350 
351  static const int kMaxCaptures = 1 << 16;
352  static const uc32 kEndMarker = (1 << 21);
353 
354  private:
355  enum SubexpressionType {
356  INITIAL,
357  CAPTURE, // All positive values represent captures.
358  POSITIVE_LOOKAHEAD,
359  NEGATIVE_LOOKAHEAD,
360  GROUPING
361  };
362 
363  class RegExpParserState : public ZoneObject {
364  public:
365  RegExpParserState(RegExpParserState* previous_state,
366  SubexpressionType group_type,
367  int disjunction_capture_index,
368  Zone* zone)
369  : previous_state_(previous_state),
370  builder_(new(zone) RegExpBuilder(zone)),
371  group_type_(group_type),
372  disjunction_capture_index_(disjunction_capture_index) {}
373  // Parser state of containing expression, if any.
374  RegExpParserState* previous_state() { return previous_state_; }
375  bool IsSubexpression() { return previous_state_ != NULL; }
376  // RegExpBuilder building this regexp's AST.
377  RegExpBuilder* builder() { return builder_; }
378  // Type of regexp being parsed (parenthesized group or entire regexp).
379  SubexpressionType group_type() { return group_type_; }
380  // Index in captures array of first capture in this sub-expression, if any.
381  // Also the capture index of this sub-expression itself, if group_type
382  // is CAPTURE.
383  int capture_index() { return disjunction_capture_index_; }
384 
385  private:
386  // Linked list implementation of stack of states.
387  RegExpParserState* previous_state_;
388  // Builder for the stored disjunction.
389  RegExpBuilder* builder_;
390  // Stored disjunction type (capture, look-ahead or grouping), if any.
391  SubexpressionType group_type_;
392  // Stored disjunction's capture index (if any).
393  int disjunction_capture_index_;
394  };
395 
396  Isolate* isolate() { return isolate_; }
397  Zone* zone() const { return zone_; }
398 
399  uc32 current() { return current_; }
400  bool has_more() { return has_more_; }
401  bool has_next() { return next_pos_ < in()->length(); }
402  uc32 Next();
403  FlatStringReader* in() { return in_; }
404  void ScanForCaptures();
405 
406  Isolate* isolate_;
407  Zone* zone_;
408  Handle<String>* error_;
409  ZoneList<RegExpCapture*>* captures_;
410  FlatStringReader* in_;
411  uc32 current_;
412  int next_pos_;
413  // The capture count is only valid after we have scanned for captures.
414  int capture_count_;
415  bool has_more_;
416  bool multiline_;
417  bool simple_;
418  bool contains_anchor_;
419  bool is_scanned_for_captures_;
420  bool failed_;
421 };
422 
423 // ----------------------------------------------------------------------------
424 // JAVASCRIPT PARSING
425 
426 // Forward declaration.
427 class SingletonLogger;
428 
429 class Parser {
430  public:
431  Parser(CompilationInfo* info,
432  int parsing_flags, // Combination of ParsingFlags
433  v8::Extension* extension,
434  ScriptDataImpl* pre_data);
435  virtual ~Parser() {
436  delete reusable_preparser_;
437  reusable_preparser_ = NULL;
438  }
439 
440  // Returns NULL if parsing failed.
443 
445  const char* message,
446  Vector<const char*> args);
448  const char* message,
449  Vector<Handle<String> > args);
450 
451  private:
452  // Limit on number of function parameters is chosen arbitrarily.
453  // Code::Flags uses only the low 17 bits of num-parameters to
454  // construct a hashable id, so if more than 2^17 are allowed, this
455  // should be checked.
456  static const int kMaxNumFunctionParameters = 32766;
457  static const int kMaxNumFunctionLocals = 131071; // 2^17-1
458 
459  enum Mode {
460  PARSE_LAZILY,
461  PARSE_EAGERLY
462  };
463 
464  enum VariableDeclarationContext {
465  kModuleElement,
466  kBlockElement,
467  kStatement,
468  kForStatement
469  };
470 
471  // If a list of variable declarations includes any initializers.
472  enum VariableDeclarationProperties {
473  kHasInitializers,
474  kHasNoInitializers
475  };
476 
477  class BlockState;
478 
480  public:
481  FunctionState(Parser* parser,
482  Scope* scope,
483  Isolate* isolate);
484  ~FunctionState();
485 
486  int NextMaterializedLiteralIndex() {
487  return next_materialized_literal_index_++;
488  }
489  int materialized_literal_count() {
490  return next_materialized_literal_index_ - JSFunction::kLiteralsPrefixSize;
491  }
492 
493  int NextHandlerIndex() { return next_handler_index_++; }
494  int handler_count() { return next_handler_index_; }
495 
496  void SetThisPropertyAssignmentInfo(
497  bool only_simple_this_property_assignments,
498  Handle<FixedArray> this_property_assignments) {
499  only_simple_this_property_assignments_ =
500  only_simple_this_property_assignments;
501  this_property_assignments_ = this_property_assignments;
502  }
503  bool only_simple_this_property_assignments() {
504  return only_simple_this_property_assignments_;
505  }
506  Handle<FixedArray> this_property_assignments() {
507  return this_property_assignments_;
508  }
509 
510  void AddProperty() { expected_property_count_++; }
511  int expected_property_count() { return expected_property_count_; }
512 
513  AstNodeFactory<AstConstructionVisitor>* factory() { return &factory_; }
514 
515  private:
516  // Used to assign an index to each literal that needs materialization in
517  // the function. Includes regexp literals, and boilerplate for object and
518  // array literals.
519  int next_materialized_literal_index_;
520 
521  // Used to assign a per-function index to try and catch handlers.
522  int next_handler_index_;
523 
524  // Properties count estimation.
525  int expected_property_count_;
526 
527  // Keeps track of assignments to properties of this. Used for
528  // optimizing constructors.
529  bool only_simple_this_property_assignments_;
530  Handle<FixedArray> this_property_assignments_;
531 
532  Parser* parser_;
533  FunctionState* outer_function_state_;
534  Scope* outer_scope_;
535  int saved_ast_node_id_;
536  AstNodeFactory<AstConstructionVisitor> factory_;
537  };
538 
539  class ParsingModeScope BASE_EMBEDDED {
540  public:
541  ParsingModeScope(Parser* parser, Mode mode)
542  : parser_(parser),
543  old_mode_(parser->mode()) {
544  parser_->mode_ = mode;
545  }
546  ~ParsingModeScope() {
547  parser_->mode_ = old_mode_;
548  }
549 
550  private:
551  Parser* parser_;
552  Mode old_mode_;
553  };
554 
555  FunctionLiteral* ParseLazy(Utf16CharacterStream* source,
556  ZoneScope* zone_scope);
557 
558  Isolate* isolate() { return isolate_; }
559  Zone* zone() const { return zone_; }
560  CompilationInfo* info() const { return info_; }
561 
562  // Called by ParseProgram after setting up the scanner.
563  FunctionLiteral* DoParseProgram(CompilationInfo* info,
564  Handle<String> source,
565  ZoneScope* zone_scope);
566 
567  // Report syntax error
568  void ReportUnexpectedToken(Token::Value token);
569  void ReportInvalidPreparseData(Handle<String> name, bool* ok);
570  void ReportMessage(const char* message, Vector<const char*> args);
571  void ReportMessage(const char* message, Vector<Handle<String> > args);
572 
573  bool inside_with() const { return top_scope_->inside_with(); }
574  Scanner& scanner() { return scanner_; }
575  Mode mode() const { return mode_; }
576  ScriptDataImpl* pre_data() const { return pre_data_; }
577  bool is_extended_mode() {
578  ASSERT(top_scope_ != NULL);
579  return top_scope_->is_extended_mode();
580  }
581  Scope* DeclarationScope(VariableMode mode) {
582  return IsLexicalVariableMode(mode)
583  ? top_scope_ : top_scope_->DeclarationScope();
584  }
585 
586  // Check if the given string is 'eval' or 'arguments'.
587  bool IsEvalOrArguments(Handle<String> string);
588 
589  // All ParseXXX functions take as the last argument an *ok parameter
590  // which is set to false if parsing failed; it is unchanged otherwise.
591  // By making the 'exception handling' explicit, we are forced to check
592  // for failure at the call sites.
593  void* ParseSourceElements(ZoneList<Statement*>* processor, int end_token,
594  bool is_eval, bool is_global, bool* ok);
595  Statement* ParseModuleElement(ZoneStringList* labels, bool* ok);
596  Statement* ParseModuleDeclaration(ZoneStringList* names, bool* ok);
597  Module* ParseModule(bool* ok);
598  Module* ParseModuleLiteral(bool* ok);
599  Module* ParseModulePath(bool* ok);
600  Module* ParseModuleVariable(bool* ok);
601  Module* ParseModuleUrl(bool* ok);
602  Module* ParseModuleSpecifier(bool* ok);
603  Block* ParseImportDeclaration(bool* ok);
604  Statement* ParseExportDeclaration(bool* ok);
605  Statement* ParseBlockElement(ZoneStringList* labels, bool* ok);
606  Statement* ParseStatement(ZoneStringList* labels, bool* ok);
607  Statement* ParseFunctionDeclaration(ZoneStringList* names, bool* ok);
608  Statement* ParseNativeDeclaration(bool* ok);
609  Block* ParseBlock(ZoneStringList* labels, bool* ok);
610  Block* ParseVariableStatement(VariableDeclarationContext var_context,
611  ZoneStringList* names,
612  bool* ok);
613  Block* ParseVariableDeclarations(VariableDeclarationContext var_context,
614  VariableDeclarationProperties* decl_props,
615  ZoneStringList* names,
616  Handle<String>* out,
617  bool* ok);
618  Statement* ParseExpressionOrLabelledStatement(ZoneStringList* labels,
619  bool* ok);
620  IfStatement* ParseIfStatement(ZoneStringList* labels, bool* ok);
621  Statement* ParseContinueStatement(bool* ok);
622  Statement* ParseBreakStatement(ZoneStringList* labels, bool* ok);
623  Statement* ParseReturnStatement(bool* ok);
624  Statement* ParseWithStatement(ZoneStringList* labels, bool* ok);
625  CaseClause* ParseCaseClause(bool* default_seen_ptr, bool* ok);
626  SwitchStatement* ParseSwitchStatement(ZoneStringList* labels, bool* ok);
627  DoWhileStatement* ParseDoWhileStatement(ZoneStringList* labels, bool* ok);
628  WhileStatement* ParseWhileStatement(ZoneStringList* labels, bool* ok);
629  Statement* ParseForStatement(ZoneStringList* labels, bool* ok);
630  Statement* ParseThrowStatement(bool* ok);
631  Expression* MakeCatchContext(Handle<String> id, VariableProxy* value);
632  TryStatement* ParseTryStatement(bool* ok);
633  DebuggerStatement* ParseDebuggerStatement(bool* ok);
634 
635  // Support for hamony block scoped bindings.
636  Block* ParseScopedBlock(ZoneStringList* labels, bool* ok);
637 
638  Expression* ParseExpression(bool accept_IN, bool* ok);
639  Expression* ParseAssignmentExpression(bool accept_IN, bool* ok);
640  Expression* ParseConditionalExpression(bool accept_IN, bool* ok);
641  Expression* ParseBinaryExpression(int prec, bool accept_IN, bool* ok);
642  Expression* ParseUnaryExpression(bool* ok);
643  Expression* ParsePostfixExpression(bool* ok);
644  Expression* ParseLeftHandSideExpression(bool* ok);
645  Expression* ParseNewExpression(bool* ok);
646  Expression* ParseMemberExpression(bool* ok);
647  Expression* ParseNewPrefix(PositionStack* stack, bool* ok);
648  Expression* ParseMemberWithNewPrefixesExpression(PositionStack* stack,
649  bool* ok);
650  Expression* ParsePrimaryExpression(bool* ok);
651  Expression* ParseArrayLiteral(bool* ok);
652  Expression* ParseObjectLiteral(bool* ok);
653  ObjectLiteral::Property* ParseObjectLiteralGetSet(bool is_getter, bool* ok);
654  Expression* ParseRegExpLiteral(bool seen_equal, bool* ok);
655 
656  // Populate the constant properties fixed array for a materialized object
657  // literal.
658  void BuildObjectLiteralConstantProperties(
659  ZoneList<ObjectLiteral::Property*>* properties,
660  Handle<FixedArray> constants,
661  bool* is_simple,
662  bool* fast_elements,
663  int* depth);
664 
665  // Populate the literals fixed array for a materialized array literal.
666  void BuildArrayLiteralBoilerplateLiterals(ZoneList<Expression*>* properties,
667  Handle<FixedArray> constants,
668  bool* is_simple,
669  int* depth);
670 
671  // Decide if a property should be in the object boilerplate.
672  bool IsBoilerplateProperty(ObjectLiteral::Property* property);
673  // If the expression is a literal, return the literal value;
674  // if the expression is a materialized literal and is simple return a
675  // compile time value as encoded by CompileTimeValue::GetValue().
676  // Otherwise, return undefined literal as the placeholder
677  // in the object literal boilerplate.
678  Handle<Object> GetBoilerplateValue(Expression* expression);
679 
680  ZoneList<Expression*>* ParseArguments(bool* ok);
681  FunctionLiteral* ParseFunctionLiteral(Handle<String> var_name,
682  bool name_is_reserved,
683  int function_token_position,
685  bool* ok);
686 
687 
688  // Magical syntax support.
689  Expression* ParseV8Intrinsic(bool* ok);
690 
691  INLINE(Token::Value peek()) {
692  if (stack_overflow_) return Token::ILLEGAL;
693  return scanner().peek();
694  }
695 
696  INLINE(Token::Value Next()) {
697  // BUG 1215673: Find a thread safe way to set a stack limit in
698  // pre-parse mode. Otherwise, we cannot safely pre-parse from other
699  // threads.
700  if (stack_overflow_) {
701  return Token::ILLEGAL;
702  }
703  if (StackLimitCheck(isolate()).HasOverflowed()) {
704  // Any further calls to Next or peek will return the illegal token.
705  // The current call must return the next token, which might already
706  // have been peek'ed.
707  stack_overflow_ = true;
708  }
709  return scanner().Next();
710  }
711 
712  bool peek_any_identifier();
713 
714  INLINE(void Consume(Token::Value token));
715  void Expect(Token::Value token, bool* ok);
716  bool Check(Token::Value token);
717  void ExpectSemicolon(bool* ok);
718  void ExpectContextualKeyword(const char* keyword, bool* ok);
719 
720  Handle<String> LiteralString(PretenureFlag tenured) {
721  if (scanner().is_literal_ascii()) {
722  return isolate_->factory()->NewStringFromAscii(
723  scanner().literal_ascii_string(), tenured);
724  } else {
725  return isolate_->factory()->NewStringFromTwoByte(
726  scanner().literal_utf16_string(), tenured);
727  }
728  }
729 
730  Handle<String> NextLiteralString(PretenureFlag tenured) {
731  if (scanner().is_next_literal_ascii()) {
732  return isolate_->factory()->NewStringFromAscii(
733  scanner().next_literal_ascii_string(), tenured);
734  } else {
735  return isolate_->factory()->NewStringFromTwoByte(
736  scanner().next_literal_utf16_string(), tenured);
737  }
738  }
739 
740  Handle<String> GetSymbol(bool* ok);
741 
742  // Get odd-ball literals.
743  Literal* GetLiteralUndefined();
744  Literal* GetLiteralTheHole();
745 
746  Handle<String> ParseIdentifier(bool* ok);
747  Handle<String> ParseIdentifierOrStrictReservedWord(
748  bool* is_strict_reserved, bool* ok);
749  Handle<String> ParseIdentifierName(bool* ok);
750  Handle<String> ParseIdentifierNameOrGetOrSet(bool* is_get,
751  bool* is_set,
752  bool* ok);
753 
754  // Determine if the expression is a variable proxy and mark it as being used
755  // in an assignment or with a increment/decrement operator. This is currently
756  // used on for the statically checking assignments to harmony const bindings.
757  void MarkAsLValue(Expression* expression);
758 
759  // Strict mode validation of LValue expressions
760  void CheckStrictModeLValue(Expression* expression,
761  const char* error,
762  bool* ok);
763 
764  // Strict mode octal literal validation.
765  void CheckOctalLiteral(int beg_pos, int end_pos, bool* ok);
766 
767  // For harmony block scoping mode: Check if the scope has conflicting var/let
768  // declarations from different scopes. It covers for example
769  //
770  // function f() { { { var x; } let x; } }
771  // function g() { { var x; let x; } }
772  //
773  // The var declarations are hoisted to the function scope, but originate from
774  // a scope where the name has also been let bound or the var declaration is
775  // hoisted over such a scope.
776  void CheckConflictingVarDeclarations(Scope* scope, bool* ok);
777 
778  // Parser support
779  VariableProxy* NewUnresolved(Handle<String> name,
780  VariableMode mode,
781  Interface* interface);
782  void Declare(Declaration* declaration, bool resolve, bool* ok);
783 
784  bool TargetStackContainsLabel(Handle<String> label);
785  BreakableStatement* LookupBreakTarget(Handle<String> label, bool* ok);
786  IterationStatement* LookupContinueTarget(Handle<String> label, bool* ok);
787 
788  void RegisterTargetUse(Label* target, Target* stop);
789 
790  // Factory methods.
791 
792  Scope* NewScope(Scope* parent, ScopeType type);
793 
794  Handle<String> LookupSymbol(int symbol_id);
795 
796  Handle<String> LookupCachedSymbol(int symbol_id);
797 
798  // Generate AST node that throw a ReferenceError with the given type.
799  Expression* NewThrowReferenceError(Handle<String> type);
800 
801  // Generate AST node that throw a SyntaxError with the given
802  // type. The first argument may be null (in the handle sense) in
803  // which case no arguments are passed to the constructor.
804  Expression* NewThrowSyntaxError(Handle<String> type, Handle<Object> first);
805 
806  // Generate AST node that throw a TypeError with the given
807  // type. Both arguments must be non-null (in the handle sense).
808  Expression* NewThrowTypeError(Handle<String> type,
809  Handle<Object> first,
810  Handle<Object> second);
811 
812  // Generic AST generator for throwing errors from compiled code.
813  Expression* NewThrowError(Handle<String> constructor,
814  Handle<String> type,
815  Vector< Handle<Object> > arguments);
816 
817  preparser::PreParser::PreParseResult LazyParseFunctionLiteral(
818  SingletonLogger* logger);
819 
820  AstNodeFactory<AstConstructionVisitor>* factory() {
821  return current_function_state_->factory();
822  }
823 
824  Isolate* isolate_;
825  ZoneList<Handle<String> > symbol_cache_;
826 
827  Handle<Script> script_;
828  Scanner scanner_;
829  preparser::PreParser* reusable_preparser_;
830  Scope* top_scope_;
831  FunctionState* current_function_state_;
832  Target* target_stack_; // for break, continue statements
833  v8::Extension* extension_;
834  ScriptDataImpl* pre_data_;
835  FuncNameInferrer* fni_;
836 
837  Mode mode_;
838  bool allow_natives_syntax_;
839  bool allow_lazy_;
840  bool allow_modules_;
841  bool stack_overflow_;
842  // If true, the next (and immediately following) function literal is
843  // preceded by a parenthesis.
844  // Heuristically that means that the function will be called immediately,
845  // so never lazily compile it.
846  bool parenthesized_function_;
847 
848  Zone* zone_;
849  CompilationInfo* info_;
850  friend class BlockState;
851  friend class FunctionState;
852 };
853 
854 
855 // Support for handling complex values (array and object literals) that
856 // can be fully handled at compile time.
858  public:
859  enum Type {
863  };
864 
865  static bool IsCompileTimeValue(Expression* expression);
866 
868 
869  // Get the value as a compile time value.
870  static Handle<FixedArray> GetValue(Expression* expression);
871 
872  // Get the type of a compile time value returned by GetValue().
873  static Type GetType(Handle<FixedArray> value);
874 
875  // Get the elements array of a compile time value returned by GetValue().
877 
878  private:
879  static const int kTypeSlot = 0;
880  static const int kElementsSlot = 1;
881 
882  DISALLOW_IMPLICIT_CONSTRUCTORS(CompileTimeValue);
883 };
884 
885 } } // namespace v8::internal
886 
887 #endif // V8_PARSER_H_
activate correct semantics for inheriting readonliness enable harmony semantics for typeof enable harmony enable harmony proxies enable all harmony harmony_scoping harmony_proxies harmony_scoping tracks arrays with only smi values automatically unbox arrays of doubles use crankshaft use hydrogen range analysis use hydrogen global value numbering use function inlining maximum number of AST nodes considered for a single inlining loop invariant code motion print statistics for hydrogen trace generated IR for specified phases trace register allocator trace range analysis trace representation types environment for every instruction put a break point before deoptimizing polymorphic inlining perform array bounds checks elimination use dead code elimination trace on stack replacement optimize closures cache optimized code for closures functions with arguments object loop weight for representation inference allow uint32 values on optimize frames if they are used only in safe operations track parallel recompilation enable all profiler experiments number of stack frames inspected by the profiler call recompile stub directly when self optimizing trigger profiler ticks based on counting instead of timing weight back edges by jump distance for interrupt triggering percentage of ICs that must have type info to allow optimization watch_ic_patching retry_self_opt interrupt_at_exit extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of SAHF instruction if enable use of VFP3 instructions if available this implies enabling ARMv7 and VFP2 enable use of VFP2 instructions if available enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of MIPS FPU instructions if expose natives in global object expose gc extension number of stack frames to capture disable builtin natives files print a stack trace if an assertion failure occurs use random jit cookie to mask large constants trace lazy optimization use adaptive optimizations prepare for turning on always opt minimum length for automatic enable preparsing maximum number of optimization attempts before giving up cache prototype transitions automatically set the debug break flag when debugger commands are in the queue always cause a debug break before aborting maximum length of function source code printed in a stack trace max size of the new max size of the old max size of executable always perform global GCs print one trace line following each garbage collection do not print trace line after scavenger collection print more details following each garbage collection print amount of external allocated memory after each time it is adjusted flush code that we expect not to use again before full gc do incremental marking steps track object counts and memory usage use caching Perform compaction on every full GC Never perform compaction on full GC testing only Compact code space on full incremental collections Default seed for initializing random allows verbose printing trace parsing and preparsing Check icache flushes in ARM and MIPS simulator Stack alingment in bytes in print stack trace when throwing exceptions randomize hashes to avoid predictable hash Fixed seed to use to hash property activate a timer that switches between V8 threads testing_bool_flag float flag Seed used for threading test randomness A filename with extra code to be included in the Print usage including on console Map counters to a file Enable debugger compile events enable GDBJIT interface(disables compacting GC)") DEFINE_bool(gdbjit_full
const char * message()
Definition: parser.h:59
RegExpTree * ToRegExp()
Definition: parser.cc:189
Scope * DeclarationScope()
Definition: scopes.cc:745
static bool ParseRegExp(FlatStringReader *input, bool multiline, RegExpCompileData *result, Zone *zone)
Definition: parser.cc:5921
static ScriptDataImpl * PreParse(Utf16CharacterStream *source, v8::Extension *extension, int flags)
Definition: parser.cc:5909
Vector< const char * > BuildArgs()
Definition: parser.cc:384
Parser(CompilationInfo *info, int parsing_flags, v8::Extension *extension, ScriptDataImpl *pre_data)
Definition: parser.cc:535
friend class BlockState
Definition: parser.h:850
static const uc32 kEndMarker
Definition: parser.h:352
RegExpTree * ReportError(Vector< const char > message)
Definition: parser.cc:5075
bool ParseHexEscape(int length, uc32 *value)
Definition: parser.cc:5609
Scanner::Location location()
Definition: parser.h:58
static Handle< FixedArray > GetElements(Handle< FixedArray > value)
Definition: parser.cc:3877
int32_t uc32
Definition: globals.h:260
T & at(int i) const
Definition: list.h:90
RegExpTree * ParseCharacterClass()
Definition: parser.cc:5752
RegExpParser(FlatStringReader *in, Handle< String > *error, bool multiline_mode, Zone *zone)
Definition: parser.cc:5010
void AddAtom(RegExpTree *tree)
Definition: parser.cc:144
#define ASSERT(condition)
Definition: checks.h:270
static bool IsCompileTimeValue(Expression *expression)
Definition: parser.cc:3830
static Type GetType(Handle< FixedArray > value)
Definition: parser.cc:3871
Vector< const char * > args()
Definition: parser.h:60
Factory * factory()
Definition: isolate.h:992
FunctionLiteral * ParseProgram()
Definition: parser.cc:568
bool ParseBackReferenceIndex(int *index_out)
Definition: parser.cc:5487
virtual ~Parser()
Definition: parser.h:435
RegExpTree * ParsePattern()
Definition: parser.cc:5087
static bool Parse(CompilationInfo *info, int flags)
Definition: parser.cc:5944
FunctionEntry GetFunctionEntry(int start)
Definition: parser.cc:292
uint8_t byte
Definition: globals.h:156
void AddQuantifierToAtom(int min, int max, RegExpQuantifier::Type type)
Definition: parser.cc:202
RegExpTree * ParseDisjunction()
Definition: parser.cc:5109
void AddAssertion(RegExpTree *tree)
Definition: parser.cc:160
friend class FunctionState
Definition: parser.h:851
void Add(T *value, Zone *zone)
Definition: parser.h:197
FunctionLiteral * ParseLazy()
Definition: parser.cc:685
ZoneList< T * > * GetList(Zone *zone)
Definition: parser.h:247
CharacterRange ParseClassAtom(uc16 *char_class)
Definition: parser.cc:5712
Handle< String > NewStringFromTwoByte(Vector< const uc16 > str, PretenureFlag pretenure=NOT_TENURED)
Definition: factory.cc:216
bool IsLexicalVariableMode(VariableMode mode)
Definition: v8globals.h:521
int length() const
Definition: utils.h:384
#define BASE_EMBEDDED
Definition: allocation.h:68
activate correct semantics for inheriting readonliness false
Definition: flags.cc:141
#define T(name, string, precedence)
Definition: token.cc:48
static Handle< FixedArray > GetValue(Expression *expression)
Definition: parser.cc:3849
const char * BuildMessage()
Definition: parser.cc:378
ParserMessage(Scanner::Location loc, const char *message, Vector< const char * > args)
Definition: parser.h:52
Handle< String > NewStringFromAscii(Vector< const char > str, PretenureFlag pretenure=NOT_TENURED)
Definition: factory.cc:199
void ReportMessageAt(Scanner::Location loc, const char *message, Vector< const char * > args)
Definition: parser.cc:800
LanguageMode language_mode()
Definition: parser.h:88
virtual const char * Data()
Definition: parser.cc:5828
void AddCharacter(uc16 character)
Definition: parser.cc:129
uint16_t uc16
Definition: globals.h:259
Scanner::Location MessageLocation()
Definition: parser.cc:371
#define ASSERT_EQ(v1, v2)
Definition: checks.h:271
bool inside_with() const
Definition: scopes.h:306
activate correct semantics for inheriting readonliness enable harmony semantics for typeof enable harmony enable harmony proxies enable all harmony harmony_scoping harmony_proxies harmony_scoping tracks arrays with only smi values automatically unbox arrays of doubles use crankshaft use hydrogen range analysis use hydrogen global value numbering use function inlining maximum number of AST nodes considered for a single inlining loop invariant code motion print statistics for hydrogen trace generated IR for specified phases trace register allocator trace range analysis trace representation types environment for every instruction put a break point before deoptimizing polymorphic inlining perform array bounds checks elimination use dead code elimination trace on stack replacement optimize closures cache optimized code for closures functions with arguments object loop weight for representation inference allow uint32 values on optimize frames if they are used only in safe operations track parallel recompilation enable all profiler experiments number of stack frames inspected by the profiler call recompile stub directly when self optimizing trigger profiler ticks based on counting instead of timing weight back edges by jump distance for interrupt triggering percentage of ICs that must have type info to allow optimization watch_ic_patching retry_self_opt interrupt_at_exit extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of SAHF instruction if enable use of VFP3 instructions if available this implies enabling ARMv7 and VFP2 enable use of VFP2 instructions if available enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of MIPS FPU instructions if expose natives in global object expose gc extension number of stack frames to capture disable builtin natives files print a stack trace if an assertion failure occurs use random jit cookie to mask large constants trace lazy optimization use adaptive optimizations prepare for turning on always opt minimum length for automatic enable preparsing maximum number of optimization attempts before giving up cache prototype transitions automatically set the debug break flag when debugger commands are in the queue always cause a debug break before aborting maximum length of function source code printed in a stack trace max size of the new max size of the old max size of executable always perform global GCs print one trace line following each garbage collection do not print trace line after scavenger collection print more details following each garbage collection print amount of external allocated memory after each time it is adjusted flush code that we expect not to use again before full gc do incremental marking steps track object counts and memory usage use caching Perform compaction on every full GC Never perform compaction on full GC testing only Compact code space on full incremental collections Default seed for initializing random allows verbose printing trace parsing and preparsing Check icache flushes in ARM and MIPS simulator Stack alingment in bytes in print stack trace when throwing exceptions randomize hashes to avoid predictable hash Fixed seed to use to hash property activate a timer that switches between V8 threads testing_bool_flag float flag Seed used for threading test randomness A filename with extra code to be included in the Print usage message
Definition: flags.cc:495
Token::Value peek() const
Definition: scanner.h:367
void Add(const T &element, AllocationPolicy allocator=AllocationPolicy())
Definition: list-inl.h:38
activate correct semantics for inheriting readonliness enable harmony semantics for typeof enable harmony enable harmony proxies enable all harmony harmony_scoping harmony_proxies harmony_scoping tracks arrays with only smi values automatically unbox arrays of doubles use crankshaft use hydrogen range analysis use hydrogen global value numbering use function inlining maximum number of AST nodes considered for a single inlining loop invariant code motion print statistics for hydrogen trace generated IR for specified phases trace register allocator trace range analysis trace representation types environment for every instruction put a break point before deoptimizing polymorphic inlining perform array bounds checks elimination use dead code elimination trace on stack replacement optimize closures cache optimized code for closures functions with arguments object loop weight for representation inference allow uint32 values on optimize frames if they are used only in safe operations track parallel recompilation enable all profiler experiments number of stack frames inspected by the profiler call recompile stub directly when self optimizing trigger profiler ticks based on counting instead of timing weight back edges by jump distance for interrupt triggering percentage of ICs that must have type info to allow optimization watch_ic_patching retry_self_opt interrupt_at_exit extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of SAHF instruction if enable use of VFP3 instructions if available this implies enabling ARMv7 and VFP2 enable use of VFP2 instructions if available enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of MIPS FPU instructions if NULL
Definition: flags.cc:301
static const int kMaxCaptures
Definition: parser.h:351
ZoneList< Handle< String > > ZoneStringList
Definition: ast.h:155
Token::Value Next()
Definition: scanner.cc:224
bool ParseIntervalQuantifier(int *min_out, int *max_out)
Definition: parser.cc:5531
FunctionEntry(Vector< unsigned > backing)
Definition: parser.h:79
ScriptDataImpl(Vector< unsigned > store)
Definition: parser.h:105
activate correct semantics for inheriting readonliness enable harmony semantics for typeof enable harmony enable harmony proxies enable all harmony harmony_scoping harmony_proxies harmony_scoping tracks arrays with only smi values automatically unbox arrays of doubles use crankshaft use hydrogen range analysis use hydrogen global value numbering use function inlining maximum number of AST nodes considered for a single inlining loop invariant code motion print statistics for hydrogen trace generated IR for specified phases trace register allocator trace range analysis trace representation types environment for every instruction put a break point before deoptimizing polymorphic inlining perform array bounds checks elimination use dead code elimination trace on stack replacement optimize closures cache optimized code for closures functions with arguments object loop weight for representation inference allow uint32 values on optimize frames if they are used only in safe operations track parallel recompilation enable all profiler experiments number of stack frames inspected by the profiler call recompile stub directly when self optimizing trigger profiler ticks based on counting instead of timing weight back edges by jump distance for interrupt triggering percentage of ICs that must have type info to allow optimization watch_ic_patching retry_self_opt interrupt_at_exit extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of SAHF instruction if enable use of VFP3 instructions if available this implies enabling ARMv7 and VFP2 enable use of VFP2 instructions if available enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of MIPS FPU instructions if expose natives in global object expose gc extension number of stack frames to capture disable builtin natives files print a stack trace if an assertion failure occurs use random jit cookie to mask large constants trace lazy optimization use adaptive optimizations prepare for turning on always opt minimum length for automatic enable preparsing maximum number of optimization attempts before giving up cache prototype transitions automatically set the debug break flag when debugger commands are in the queue always cause a debug break before aborting maximum length of function source code printed in a stack trace max size of the new max size of the old max size of executable always perform global GCs print one trace line following each garbage collection do not print trace line after scavenger collection print more details following each garbage collection print amount of external allocated memory after each time it is adjusted flush code that we expect not to use again before full gc do incremental marking steps track object counts and memory usage use caching Perform compaction on every full GC Never perform compaction on full GC testing only Compact code space on full incremental collections Default seed for initializing random allows verbose printing trace parsing and preparsing Check icache flushes in ARM and MIPS simulator Stack alingment in bytes in print stack trace when throwing exceptions randomize hashes to avoid predictable hash Fixed seed to use to hash property activate a timer that switches between V8 threads testing_bool_flag float flag Seed used for threading test randomness A filename with extra code to be included in the Print usage including flags
Definition: flags.cc:495
RegExpBuilder(Zone *zone)
Definition: parser.cc:89
bool is_extended_mode() const
Definition: scopes.h:289
virtual bool HasError()
Definition: parser.cc:5833
static bool ArrayLiteralElementNeedsInitialization(Expression *value)
Definition: parser.cc:3837
static const int kLiteralsPrefixSize
Definition: objects.h:6194