Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(2)

Side by Side Diff: src/parser.h

Issue 4343003: Version 2.5.4 (Closed)
Patch Set: Created 10 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « src/ia32/stub-cache-ia32.cc ('k') | src/parser.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2010 the V8 project authors. All rights reserved. 1 // Copyright 2010 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without 2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are 3 // modification, are permitted provided that the following conditions are
4 // met: 4 // met:
5 // 5 //
6 // * Redistributions of source code must retain the above copyright 6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer. 7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above 8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following 9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided 10 // disclaimer in the documentation and/or other materials provided
(...skipping 13 matching lines...) Expand all
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 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. 26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 27
28 #ifndef V8_PARSER_H_ 28 #ifndef V8_PARSER_H_
29 #define V8_PARSER_H_ 29 #define V8_PARSER_H_
30 30
31 #include "allocation.h" 31 #include "allocation.h"
32 #include "ast.h" 32 #include "ast.h"
33 #include "scanner.h" 33 #include "scanner.h"
34 #include "scopes.h"
34 35
35 namespace v8 { 36 namespace v8 {
36 namespace internal { 37 namespace internal {
37 38
38 class CompilationInfo; 39 class CompilationInfo;
39 class FuncNameInferrer; 40 class FuncNameInferrer;
40 class ParserFactory;
41 class ParserLog; 41 class ParserLog;
42 class PositionStack; 42 class PositionStack;
43 class Target; 43 class Target;
44 class TemporaryScope; 44 class TemporaryScope;
45 45
46 template <typename T> class ZoneListWrapper; 46 template <typename T> class ZoneListWrapper;
47 47
48 48
49 class ParserMessage : public Malloced { 49 class ParserMessage : public Malloced {
50 public: 50 public:
(...skipping 119 matching lines...) Expand 10 before | Expand all | Expand 10 after
170 reinterpret_cast<intptr_t>(backing_store) % sizeof(unsigned))); 170 reinterpret_cast<intptr_t>(backing_store) % sizeof(unsigned)));
171 } 171 }
172 172
173 // Read strings written by ParserRecorder::WriteString. 173 // Read strings written by ParserRecorder::WriteString.
174 static const char* ReadString(unsigned* start, int* chars); 174 static const char* ReadString(unsigned* start, int* chars);
175 175
176 friend class ScriptData; 176 friend class ScriptData;
177 }; 177 };
178 178
179 179
180 // Record only functions.
181 class PartialParserRecorder {
182 public:
183 PartialParserRecorder();
184
185 void LogFunction(int start, int end, int literals, int properties) {
186 function_store_.Add(start);
187 function_store_.Add(end);
188 function_store_.Add(literals);
189 function_store_.Add(properties);
190 }
191
192 void LogSymbol(int start, const char* symbol, int length) { }
193
194 // Logs an error message and marks the log as containing an error.
195 // Further logging will be ignored, and ExtractData will return a vector
196 // representing the error only.
197 void LogMessage(int start,
198 int end,
199 const char* message,
200 const char* argument_opt) {
201 Scanner::Location location(start, end);
202 Vector<const char*> arguments;
203 if (argument_opt != NULL) {
204 arguments = Vector<const char*>(&argument_opt, 1);
205 }
206 this->LogMessage(location, message, arguments);
207 }
208
209 int function_position() { return function_store_.size(); }
210
211 void LogMessage(Scanner::Location loc,
212 const char* message,
213 Vector<const char*> args);
214
215 Vector<unsigned> ExtractData();
216
217 void PauseRecording() {
218 pause_count_++;
219 is_recording_ = false;
220 }
221
222 void ResumeRecording() {
223 ASSERT(pause_count_ > 0);
224 if (--pause_count_ == 0) is_recording_ = !has_error();
225 }
226
227 int symbol_position() { return 0; }
228 int symbol_ids() { return 0; }
229
230 protected:
231 bool has_error() {
232 return static_cast<bool>(preamble_[ScriptDataImpl::kHasErrorOffset]);
233 }
234
235 bool is_recording() {
236 return is_recording_;
237 }
238
239 void WriteString(Vector<const char> str);
240
241 Collector<unsigned> function_store_;
242 unsigned preamble_[ScriptDataImpl::kHeaderSize];
243 bool is_recording_;
244 int pause_count_;
245
246 #ifdef DEBUG
247 int prev_start_;
248 #endif
249 };
250
251
252 // Record both functions and symbols.
253 class CompleteParserRecorder: public PartialParserRecorder {
254 public:
255 CompleteParserRecorder();
256
257 void LogSymbol(int start, Vector<const char> literal);
258
259 void LogSymbol(int start, const char* symbol, int length) {
260 LogSymbol(start, Vector<const char>(symbol, length));
261 }
262
263 Vector<unsigned> ExtractData();
264
265 int symbol_position() { return symbol_store_.size(); }
266 int symbol_ids() { return symbol_id_; }
267
268 private:
269 static int vector_hash(Vector<const char> string) {
270 int hash = 0;
271 for (int i = 0; i < string.length(); i++) {
272 int c = string[i];
273 hash += c;
274 hash += (hash << 10);
275 hash ^= (hash >> 6);
276 }
277 return hash;
278 }
279
280 static bool vector_compare(void* a, void* b) {
281 Vector<const char>* string1 = reinterpret_cast<Vector<const char>* >(a);
282 Vector<const char>* string2 = reinterpret_cast<Vector<const char>* >(b);
283 int length = string1->length();
284 if (string2->length() != length) return false;
285 return memcmp(string1->start(), string2->start(), length) == 0;
286 }
287
288 // Write a non-negative number to the symbol store.
289 void WriteNumber(int number);
290
291 Collector<byte> symbol_store_;
292 Collector<Vector<const char> > symbol_entries_;
293 HashMap symbol_table_;
294 int symbol_id_;
295 };
296
297
298
180 class ParserApi { 299 class ParserApi {
181 public: 300 public:
182 // Parses the source code represented by the compilation info and sets its 301 // Parses the source code represented by the compilation info and sets its
183 // function literal. Returns false (and deallocates any allocated AST 302 // function literal. Returns false (and deallocates any allocated AST
184 // nodes) if parsing failed. 303 // nodes) if parsing failed.
185 static bool Parse(CompilationInfo* info); 304 static bool Parse(CompilationInfo* info);
186 305
187 // Generic preparser generating full preparse data. 306 // Generic preparser generating full preparse data.
188 static ScriptDataImpl* PreParse(Handle<String> source, 307 static ScriptDataImpl* PreParse(Handle<String> source,
189 unibrow::CharacterStream* stream, 308 unibrow::CharacterStream* stream,
190 v8::Extension* extension); 309 v8::Extension* extension);
191 310
192 // Preparser that only does preprocessing that makes sense if only used 311 // Preparser that only does preprocessing that makes sense if only used
193 // immediately after. 312 // immediately after.
194 static ScriptDataImpl* PartialPreParse(Handle<String> source, 313 static ScriptDataImpl* PartialPreParse(Handle<String> source,
195 unibrow::CharacterStream* stream, 314 unibrow::CharacterStream* stream,
196 v8::Extension* extension); 315 v8::Extension* extension);
197 }; 316 };
198 317
318 // ----------------------------------------------------------------------------
319 // REGEXP PARSING
199 320
200 // A BuffferedZoneList is an automatically growing list, just like (and backed 321 // A BuffferedZoneList is an automatically growing list, just like (and backed
201 // by) a ZoneList, that is optimized for the case of adding and removing 322 // by) a ZoneList, that is optimized for the case of adding and removing
202 // a single element. The last element added is stored outside the backing list, 323 // a single element. The last element added is stored outside the backing list,
203 // and if no more than one element is ever added, the ZoneList isn't even 324 // and if no more than one element is ever added, the ZoneList isn't even
204 // allocated. 325 // allocated.
205 // Elements must not be NULL pointers. 326 // Elements must not be NULL pointers.
206 template <typename T, int initial_size> 327 template <typename T, int initial_size>
207 class BufferedZoneList { 328 class BufferedZoneList {
208 public: 329 public:
(...skipping 195 matching lines...) Expand 10 before | Expand all | Expand 10 after
404 // Stored disjunction's capture index (if any). 525 // Stored disjunction's capture index (if any).
405 int disjunction_capture_index_; 526 int disjunction_capture_index_;
406 }; 527 };
407 528
408 uc32 current() { return current_; } 529 uc32 current() { return current_; }
409 bool has_more() { return has_more_; } 530 bool has_more() { return has_more_; }
410 bool has_next() { return next_pos_ < in()->length(); } 531 bool has_next() { return next_pos_ < in()->length(); }
411 uc32 Next(); 532 uc32 Next();
412 FlatStringReader* in() { return in_; } 533 FlatStringReader* in() { return in_; }
413 void ScanForCaptures(); 534 void ScanForCaptures();
535
536 Handle<String>* error_;
537 ZoneList<RegExpCapture*>* captures_;
538 FlatStringReader* in_;
414 uc32 current_; 539 uc32 current_;
540 int next_pos_;
541 // The capture count is only valid after we have scanned for captures.
542 int capture_count_;
415 bool has_more_; 543 bool has_more_;
416 bool multiline_; 544 bool multiline_;
417 int next_pos_;
418 FlatStringReader* in_;
419 Handle<String>* error_;
420 bool simple_; 545 bool simple_;
421 bool contains_anchor_; 546 bool contains_anchor_;
422 ZoneList<RegExpCapture*>* captures_;
423 bool is_scanned_for_captures_; 547 bool is_scanned_for_captures_;
424 // The capture count is only valid after we have scanned for captures.
425 int capture_count_;
426 bool failed_; 548 bool failed_;
427 }; 549 };
428 550
551 // ----------------------------------------------------------------------------
552 // JAVASCRIPT PARSING
429 553
430 class Parser { 554 class Parser {
431 public: 555 public:
432 Parser(Handle<Script> script, bool allow_natives_syntax, 556 Parser(Handle<Script> script,
433 v8::Extension* extension, ParserMode is_pre_parsing, 557 bool allow_natives_syntax,
434 ParserFactory* factory, ParserLog* log, ScriptDataImpl* pre_data); 558 v8::Extension* extension,
559 ScriptDataImpl* pre_data);
435 virtual ~Parser() { } 560 virtual ~Parser() { }
436 561
437 // Pre-parse the program from the character stream; returns true on
438 // success, false if a stack-overflow happened during parsing.
439 bool PreParseProgram(Handle<String> source, unibrow::CharacterStream* stream);
440
441 void ReportMessage(const char* message, Vector<const char*> args);
442 virtual void ReportMessageAt(Scanner::Location loc,
443 const char* message,
444 Vector<const char*> args) = 0;
445
446
447 // Returns NULL if parsing failed. 562 // Returns NULL if parsing failed.
448 FunctionLiteral* ParseProgram(Handle<String> source, 563 FunctionLiteral* ParseProgram(Handle<String> source,
449 bool in_global_context); 564 bool in_global_context);
565
450 FunctionLiteral* ParseLazy(Handle<SharedFunctionInfo> info); 566 FunctionLiteral* ParseLazy(Handle<SharedFunctionInfo> info);
451 567
452 // The minimum number of contiguous assignment that will 568 void ReportMessageAt(Scanner::Location loc,
453 // be treated as an initialization block. Benchmarks show that 569 const char* message,
454 // the overhead exceeds the savings below this limit. 570 Vector<const char*> args);
455 static const int kMinInitializationBlock = 3;
456 571
457 protected: 572 protected:
458
459 enum Mode { 573 enum Mode {
460 PARSE_LAZILY, 574 PARSE_LAZILY,
461 PARSE_EAGERLY 575 PARSE_EAGERLY
462 }; 576 };
463 577
464 // Report syntax error 578 // Report syntax error
465 void ReportUnexpectedToken(Token::Value token); 579 void ReportUnexpectedToken(Token::Value token);
466 void ReportInvalidPreparseData(Handle<String> name, bool* ok); 580 void ReportInvalidPreparseData(Handle<String> name, bool* ok);
467 581 void ReportMessage(const char* message, Vector<const char*> args);
468 Handle<Script> script_;
469 Scanner scanner_;
470
471 Scope* top_scope_;
472 int with_nesting_level_;
473
474 TemporaryScope* temp_scope_;
475 Mode mode_;
476
477 Target* target_stack_; // for break, continue statements
478 bool allow_natives_syntax_;
479 v8::Extension* extension_;
480 ParserFactory* factory_;
481 ParserLog* log_;
482 bool is_pre_parsing_;
483 ScriptDataImpl* pre_data_;
484 FuncNameInferrer* fni_;
485 582
486 bool inside_with() const { return with_nesting_level_ > 0; } 583 bool inside_with() const { return with_nesting_level_ > 0; }
487 ParserFactory* factory() const { return factory_; }
488 ParserLog* log() const { return log_; }
489 Scanner& scanner() { return scanner_; } 584 Scanner& scanner() { return scanner_; }
490 Mode mode() const { return mode_; } 585 Mode mode() const { return mode_; }
491 ScriptDataImpl* pre_data() const { return pre_data_; } 586 ScriptDataImpl* pre_data() const { return pre_data_; }
492 587
493 // All ParseXXX functions take as the last argument an *ok parameter 588 // All ParseXXX functions take as the last argument an *ok parameter
494 // which is set to false if parsing failed; it is unchanged otherwise. 589 // which is set to false if parsing failed; it is unchanged otherwise.
495 // By making the 'exception handling' explicit, we are forced to check 590 // By making the 'exception handling' explicit, we are forced to check
496 // for failure at the call sites. 591 // for failure at the call sites.
497 void* ParseSourceElements(ZoneListWrapper<Statement>* processor, 592 void* ParseSourceElements(ZoneList<Statement*>* processor,
498 int end_token, bool* ok); 593 int end_token, bool* ok);
499 Statement* ParseStatement(ZoneStringList* labels, bool* ok); 594 Statement* ParseStatement(ZoneStringList* labels, bool* ok);
500 Statement* ParseFunctionDeclaration(bool* ok); 595 Statement* ParseFunctionDeclaration(bool* ok);
501 Statement* ParseNativeDeclaration(bool* ok); 596 Statement* ParseNativeDeclaration(bool* ok);
502 Block* ParseBlock(ZoneStringList* labels, bool* ok); 597 Block* ParseBlock(ZoneStringList* labels, bool* ok);
503 Block* ParseVariableStatement(bool* ok); 598 Block* ParseVariableStatement(bool* ok);
504 Block* ParseVariableDeclarations(bool accept_IN, Expression** var, bool* ok); 599 Block* ParseVariableDeclarations(bool accept_IN, Expression** var, bool* ok);
505 Statement* ParseExpressionOrLabelledStatement(ZoneStringList* labels, 600 Statement* ParseExpressionOrLabelledStatement(ZoneStringList* labels,
506 bool* ok); 601 bool* ok);
507 IfStatement* ParseIfStatement(ZoneStringList* labels, bool* ok); 602 IfStatement* ParseIfStatement(ZoneStringList* labels, bool* ok);
(...skipping 92 matching lines...) Expand 10 before | Expand all | Expand 10 after
600 Literal* GetLiteralTheHole(); 695 Literal* GetLiteralTheHole();
601 Literal* GetLiteralNumber(double value); 696 Literal* GetLiteralNumber(double value);
602 697
603 Handle<String> ParseIdentifier(bool* ok); 698 Handle<String> ParseIdentifier(bool* ok);
604 Handle<String> ParseIdentifierName(bool* ok); 699 Handle<String> ParseIdentifierName(bool* ok);
605 Handle<String> ParseIdentifierOrGetOrSet(bool* is_get, 700 Handle<String> ParseIdentifierOrGetOrSet(bool* is_get,
606 bool* is_set, 701 bool* is_set,
607 bool* ok); 702 bool* ok);
608 703
609 // Parser support 704 // Parser support
610 virtual VariableProxy* Declare(Handle<String> name, Variable::Mode mode, 705 VariableProxy* Declare(Handle<String> name, Variable::Mode mode,
611 FunctionLiteral* fun, 706 FunctionLiteral* fun,
612 bool resolve, 707 bool resolve,
613 bool* ok) = 0; 708 bool* ok);
614 709
615 bool TargetStackContainsLabel(Handle<String> label); 710 bool TargetStackContainsLabel(Handle<String> label);
616 BreakableStatement* LookupBreakTarget(Handle<String> label, bool* ok); 711 BreakableStatement* LookupBreakTarget(Handle<String> label, bool* ok);
617 IterationStatement* LookupContinueTarget(Handle<String> label, bool* ok); 712 IterationStatement* LookupContinueTarget(Handle<String> label, bool* ok);
618 713
619 void RegisterTargetUse(BreakTarget* target, Target* stop); 714 void RegisterTargetUse(BreakTarget* target, Target* stop);
620 715
716 // Factory methods.
717
718 Statement* EmptyStatement() {
719 static v8::internal::EmptyStatement empty;
720 return &empty;
721 }
722
723 Scope* NewScope(Scope* parent, Scope::Type type, bool inside_with);
724
725 Handle<String> LookupSymbol(int symbol_id,
726 Vector<const char> string);
727
728 Handle<String> LookupCachedSymbol(int symbol_id,
729 Vector<const char> string);
730
731 Expression* NewCall(Expression* expression,
732 ZoneList<Expression*>* arguments,
733 int pos) {
734 return new Call(expression, arguments, pos);
735 }
736
737
621 // Create a number literal. 738 // Create a number literal.
622 Literal* NewNumberLiteral(double value); 739 Literal* NewNumberLiteral(double value);
623 740
624 // Generate AST node that throw a ReferenceError with the given type. 741 // Generate AST node that throw a ReferenceError with the given type.
625 Expression* NewThrowReferenceError(Handle<String> type); 742 Expression* NewThrowReferenceError(Handle<String> type);
626 743
627 // Generate AST node that throw a SyntaxError with the given 744 // Generate AST node that throw a SyntaxError with the given
628 // type. The first argument may be null (in the handle sense) in 745 // type. The first argument may be null (in the handle sense) in
629 // which case no arguments are passed to the constructor. 746 // which case no arguments are passed to the constructor.
630 Expression* NewThrowSyntaxError(Handle<String> type, Handle<Object> first); 747 Expression* NewThrowSyntaxError(Handle<String> type, Handle<Object> first);
631 748
632 // Generate AST node that throw a TypeError with the given 749 // Generate AST node that throw a TypeError with the given
633 // type. Both arguments must be non-null (in the handle sense). 750 // type. Both arguments must be non-null (in the handle sense).
634 Expression* NewThrowTypeError(Handle<String> type, 751 Expression* NewThrowTypeError(Handle<String> type,
635 Handle<Object> first, 752 Handle<Object> first,
636 Handle<Object> second); 753 Handle<Object> second);
637 754
638 // Generic AST generator for throwing errors from compiled code. 755 // Generic AST generator for throwing errors from compiled code.
639 Expression* NewThrowError(Handle<String> constructor, 756 Expression* NewThrowError(Handle<String> constructor,
640 Handle<String> type, 757 Handle<String> type,
641 Vector< Handle<Object> > arguments); 758 Vector< Handle<Object> > arguments);
759
760 ZoneList<Handle<String> > symbol_cache_;
761
762 Handle<Script> script_;
763 Scanner scanner_;
764
765 Scope* top_scope_;
766 int with_nesting_level_;
767
768 TemporaryScope* temp_scope_;
769 Mode mode_;
770
771 Target* target_stack_; // for break, continue statements
772 bool allow_natives_syntax_;
773 v8::Extension* extension_;
774 bool is_pre_parsing_;
775 ScriptDataImpl* pre_data_;
776 FuncNameInferrer* fni_;
642 }; 777 };
643 778
644 779
645 // Support for handling complex values (array and object literals) that 780 // Support for handling complex values (array and object literals) that
646 // can be fully handled at compile time. 781 // can be fully handled at compile time.
647 class CompileTimeValue: public AllStatic { 782 class CompileTimeValue: public AllStatic {
648 public: 783 public:
649 enum Type { 784 enum Type {
650 OBJECT_LITERAL_FAST_ELEMENTS, 785 OBJECT_LITERAL_FAST_ELEMENTS,
651 OBJECT_LITERAL_SLOW_ELEMENTS, 786 OBJECT_LITERAL_SLOW_ELEMENTS,
(...skipping 14 matching lines...) Expand all
666 static Handle<FixedArray> GetElements(Handle<FixedArray> value); 801 static Handle<FixedArray> GetElements(Handle<FixedArray> value);
667 802
668 private: 803 private:
669 static const int kTypeSlot = 0; 804 static const int kTypeSlot = 0;
670 static const int kElementsSlot = 1; 805 static const int kElementsSlot = 1;
671 806
672 DISALLOW_IMPLICIT_CONSTRUCTORS(CompileTimeValue); 807 DISALLOW_IMPLICIT_CONSTRUCTORS(CompileTimeValue);
673 }; 808 };
674 809
675 810
811 // ----------------------------------------------------------------------------
812 // JSON PARSING
813
676 // JSON is a subset of JavaScript, as specified in, e.g., the ECMAScript 5 814 // JSON is a subset of JavaScript, as specified in, e.g., the ECMAScript 5
677 // specification section 15.12.1 (and appendix A.8). 815 // specification section 15.12.1 (and appendix A.8).
678 // The grammar is given section 15.12.1.2 (and appendix A.8.2). 816 // The grammar is given section 15.12.1.2 (and appendix A.8.2).
679 class JsonParser BASE_EMBEDDED { 817 class JsonParser BASE_EMBEDDED {
680 public: 818 public:
681 // Parse JSON input as a single JSON value. 819 // Parse JSON input as a single JSON value.
682 // Returns null handle and sets exception if parsing failed. 820 // Returns null handle and sets exception if parsing failed.
683 static Handle<Object> Parse(Handle<String> source) { 821 static Handle<Object> Parse(Handle<String> source) {
684 return JsonParser().ParseJson(source); 822 return JsonParser().ParseJson(source);
685 } 823 }
(...skipping 26 matching lines...) Expand all
712 // return a null handle. Primarily for readability. 850 // return a null handle. Primarily for readability.
713 Handle<Object> ReportUnexpectedToken() { return Handle<Object>::null(); } 851 Handle<Object> ReportUnexpectedToken() { return Handle<Object>::null(); }
714 // Converts the currently parsed literal to a JavaScript String. 852 // Converts the currently parsed literal to a JavaScript String.
715 Handle<String> GetString(); 853 Handle<String> GetString();
716 854
717 Scanner scanner_; 855 Scanner scanner_;
718 }; 856 };
719 } } // namespace v8::internal 857 } } // namespace v8::internal
720 858
721 #endif // V8_PARSER_H_ 859 #endif // V8_PARSER_H_
OLDNEW
« no previous file with comments | « src/ia32/stub-cache-ia32.cc ('k') | src/parser.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698