blob: a067bd7c7dbbde265d76b691b1475d02e55c3b6f [file] [log] [blame]
Ben Murdochf87a2032010-10-22 12:50:53 +01001// Copyright 2010 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// 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
Steve Blocka7e24c12009-10-30 11:49:00 +000031#include "allocation.h"
Ben Murdochf87a2032010-10-22 12:50:53 +010032#include "ast.h"
33#include "scanner.h"
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -080034#include "scopes.h"
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -080035#include "preparse-data.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000036
37namespace v8 {
38namespace internal {
39
Ben Murdochf87a2032010-10-22 12:50:53 +010040class CompilationInfo;
41class FuncNameInferrer;
Ben Murdochf87a2032010-10-22 12:50:53 +010042class ParserLog;
43class PositionStack;
44class Target;
45class TemporaryScope;
46
47template <typename T> class ZoneListWrapper;
48
Steve Blocka7e24c12009-10-30 11:49:00 +000049
50class ParserMessage : public Malloced {
51 public:
52 ParserMessage(Scanner::Location loc, const char* message,
53 Vector<const char*> args)
54 : loc_(loc),
55 message_(message),
56 args_(args) { }
57 ~ParserMessage();
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
68class FunctionEntry BASE_EMBEDDED {
69 public:
70 explicit FunctionEntry(Vector<unsigned> backing) : backing_(backing) { }
71 FunctionEntry() : backing_(Vector<unsigned>::empty()) { }
72
73 int start_pos() { return backing_[kStartPosOffset]; }
74 void set_start_pos(int value) { backing_[kStartPosOffset] = value; }
75
76 int end_pos() { return backing_[kEndPosOffset]; }
77 void set_end_pos(int value) { backing_[kEndPosOffset] = value; }
78
79 int literal_count() { return backing_[kLiteralCountOffset]; }
80 void set_literal_count(int value) { backing_[kLiteralCountOffset] = value; }
81
82 int property_count() { return backing_[kPropertyCountOffset]; }
Kristian Monsen80d68ea2010-09-08 11:05:35 +010083 void set_property_count(int value) {
84 backing_[kPropertyCountOffset] = value;
85 }
86
Steve Blocka7e24c12009-10-30 11:49:00 +000087 bool is_valid() { return backing_.length() > 0; }
88
Ben Murdochf87a2032010-10-22 12:50:53 +010089 static const int kSize = 4;
Steve Blocka7e24c12009-10-30 11:49:00 +000090
91 private:
92 Vector<unsigned> backing_;
93 static const int kStartPosOffset = 0;
94 static const int kEndPosOffset = 1;
95 static const int kLiteralCountOffset = 2;
96 static const int kPropertyCountOffset = 3;
Steve Blocka7e24c12009-10-30 11:49:00 +000097};
98
99
100class ScriptDataImpl : public ScriptData {
101 public:
102 explicit ScriptDataImpl(Vector<unsigned> store)
103 : store_(store),
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100104 owns_store_(true) { }
Iain Merrick9ac36c92010-09-13 15:29:50 +0100105
106 // Create an empty ScriptDataImpl that is guaranteed to not satisfy
107 // a SanityCheck.
108 ScriptDataImpl() : store_(Vector<unsigned>()), owns_store_(false) { }
109
Steve Blocka7e24c12009-10-30 11:49:00 +0000110 virtual ~ScriptDataImpl();
111 virtual int Length();
Leon Clarkef7060e22010-06-03 12:02:55 +0100112 virtual const char* Data();
Leon Clarkee46be812010-01-19 14:06:41 +0000113 virtual bool HasError();
Iain Merrick9ac36c92010-09-13 15:29:50 +0100114
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100115 void Initialize();
116 void ReadNextSymbolPosition();
117
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100118 FunctionEntry GetFunctionEntry(int start);
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100119 int GetSymbolIdentifier();
Steve Blocka7e24c12009-10-30 11:49:00 +0000120 bool SanityCheck();
121
122 Scanner::Location MessageLocation();
123 const char* BuildMessage();
124 Vector<const char*> BuildArgs();
125
Iain Merrick9ac36c92010-09-13 15:29:50 +0100126 int symbol_count() {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800127 return (store_.length() > PreparseDataConstants::kHeaderSize)
128 ? store_[PreparseDataConstants::kSymbolCountOffset]
129 : 0;
Iain Merrick9ac36c92010-09-13 15:29:50 +0100130 }
131 // The following functions should only be called if SanityCheck has
132 // returned true.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800133 bool has_error() { return store_[PreparseDataConstants::kHasErrorOffset]; }
134 unsigned magic() { return store_[PreparseDataConstants::kMagicOffset]; }
135 unsigned version() { return store_[PreparseDataConstants::kVersionOffset]; }
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100136
Steve Blocka7e24c12009-10-30 11:49:00 +0000137 private:
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100138 Vector<unsigned> store_;
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100139 unsigned char* symbol_data_;
140 unsigned char* symbol_data_end_;
Iain Merrick9ac36c92010-09-13 15:29:50 +0100141 int function_index_;
Iain Merrick9ac36c92010-09-13 15:29:50 +0100142 bool owns_store_;
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100143
Steve Blocka7e24c12009-10-30 11:49:00 +0000144 unsigned Read(int position);
145 unsigned* ReadAddress(int position);
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100146 // Reads a number from the current symbols
147 int ReadNumber(byte** source);
Steve Blocka7e24c12009-10-30 11:49:00 +0000148
Iain Merrick9ac36c92010-09-13 15:29:50 +0100149 ScriptDataImpl(const char* backing_store, int length)
150 : store_(reinterpret_cast<unsigned*>(const_cast<char*>(backing_store)),
Ben Murdochf87a2032010-10-22 12:50:53 +0100151 length / static_cast<int>(sizeof(unsigned))),
Iain Merrick9ac36c92010-09-13 15:29:50 +0100152 owns_store_(false) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100153 ASSERT_EQ(0, static_cast<int>(
154 reinterpret_cast<intptr_t>(backing_store) % sizeof(unsigned)));
Iain Merrick9ac36c92010-09-13 15:29:50 +0100155 }
156
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100157 // Read strings written by ParserRecorder::WriteString.
158 static const char* ReadString(unsigned* start, int* chars);
Iain Merrick9ac36c92010-09-13 15:29:50 +0100159
160 friend class ScriptData;
Steve Blocka7e24c12009-10-30 11:49:00 +0000161};
162
163
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800164class ParserApi {
165 public:
Ben Murdochf87a2032010-10-22 12:50:53 +0100166 // Parses the source code represented by the compilation info and sets its
167 // function literal. Returns false (and deallocates any allocated AST
168 // nodes) if parsing failed.
169 static bool Parse(CompilationInfo* info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000170
Ben Murdochf87a2032010-10-22 12:50:53 +0100171 // Generic preparser generating full preparse data.
172 static ScriptDataImpl* PreParse(Handle<String> source,
173 unibrow::CharacterStream* stream,
174 v8::Extension* extension);
175
176 // Preparser that only does preprocessing that makes sense if only used
177 // immediately after.
178 static ScriptDataImpl* PartialPreParse(Handle<String> source,
179 unibrow::CharacterStream* stream,
180 v8::Extension* extension);
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800181};
182
183// ----------------------------------------------------------------------------
184// REGEXP PARSING
185
186// A BuffferedZoneList is an automatically growing list, just like (and backed
187// by) a ZoneList, that is optimized for the case of adding and removing
188// a single element. The last element added is stored outside the backing list,
189// and if no more than one element is ever added, the ZoneList isn't even
190// allocated.
191// Elements must not be NULL pointers.
192template <typename T, int initial_size>
193class BufferedZoneList {
194 public:
195 BufferedZoneList() : list_(NULL), last_(NULL) {}
196
197 // Adds element at end of list. This element is buffered and can
198 // be read using last() or removed using RemoveLast until a new Add or until
199 // RemoveLast or GetList has been called.
200 void Add(T* value) {
201 if (last_ != NULL) {
202 if (list_ == NULL) {
203 list_ = new ZoneList<T*>(initial_size);
204 }
205 list_->Add(last_);
206 }
207 last_ = value;
208 }
209
210 T* last() {
211 ASSERT(last_ != NULL);
212 return last_;
213 }
214
215 T* RemoveLast() {
216 ASSERT(last_ != NULL);
217 T* result = last_;
218 if ((list_ != NULL) && (list_->length() > 0))
219 last_ = list_->RemoveLast();
220 else
221 last_ = NULL;
222 return result;
223 }
224
225 T* Get(int i) {
226 ASSERT((0 <= i) && (i < length()));
227 if (list_ == NULL) {
228 ASSERT_EQ(0, i);
229 return last_;
230 } else {
231 if (i == list_->length()) {
232 ASSERT(last_ != NULL);
233 return last_;
234 } else {
235 return list_->at(i);
236 }
237 }
238 }
239
240 void Clear() {
241 list_ = NULL;
242 last_ = NULL;
243 }
244
245 int length() {
246 int length = (list_ == NULL) ? 0 : list_->length();
247 return length + ((last_ == NULL) ? 0 : 1);
248 }
249
250 ZoneList<T*>* GetList() {
251 if (list_ == NULL) {
252 list_ = new ZoneList<T*>(initial_size);
253 }
254 if (last_ != NULL) {
255 list_->Add(last_);
256 last_ = NULL;
257 }
258 return list_;
259 }
260
261 private:
262 ZoneList<T*>* list_;
263 T* last_;
264};
265
266
267// Accumulates RegExp atoms and assertions into lists of terms and alternatives.
268class RegExpBuilder: public ZoneObject {
269 public:
270 RegExpBuilder();
271 void AddCharacter(uc16 character);
272 // "Adds" an empty expression. Does nothing except consume a
273 // following quantifier
274 void AddEmpty();
275 void AddAtom(RegExpTree* tree);
276 void AddAssertion(RegExpTree* tree);
277 void NewAlternative(); // '|'
278 void AddQuantifierToAtom(int min, int max, RegExpQuantifier::Type type);
279 RegExpTree* ToRegExp();
280
281 private:
282 void FlushCharacters();
283 void FlushText();
284 void FlushTerms();
285 bool pending_empty_;
286 ZoneList<uc16>* characters_;
287 BufferedZoneList<RegExpTree, 2> terms_;
288 BufferedZoneList<RegExpTree, 2> text_;
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
299class RegExpParser {
300 public:
301 RegExpParser(FlatStringReader* in,
302 Handle<String>* error,
303 bool multiline_mode);
Ben Murdochf87a2032010-10-22 12:50:53 +0100304
305 static bool ParseRegExp(FlatStringReader* input,
306 bool multiline,
307 RegExpCompileData* result);
308
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800309 RegExpTree* ParsePattern();
310 RegExpTree* ParseDisjunction();
311 RegExpTree* ParseGroup();
312 RegExpTree* ParseCharacterClass();
Ben Murdochf87a2032010-10-22 12:50:53 +0100313
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800314 // Parses a {...,...} quantifier and stores the range in the given
315 // out parameters.
316 bool ParseIntervalQuantifier(int* min_out, int* max_out);
Steve Block59151502010-09-22 15:07:15 +0100317
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800318 // Parses and returns a single escaped character. The character
319 // must not be 'b' or 'B' since they are usually handle specially.
320 uc32 ParseClassCharacterEscape();
321
322 // Checks whether the following is a length-digit hexadecimal number,
323 // and sets the value if it is.
324 bool ParseHexEscape(int length, uc32* value);
325
326 uc32 ParseControlLetterEscape();
327 uc32 ParseOctalLiteral();
328
329 // Tries to parse the input as a back reference. If successful it
330 // stores the result in the output parameter and returns true. If
331 // it fails it will push back the characters read so the same characters
332 // can be reparsed.
333 bool ParseBackReferenceIndex(int* index_out);
334
335 CharacterRange ParseClassAtom(uc16* char_class);
336 RegExpTree* ReportError(Vector<const char> message);
337 void Advance();
338 void Advance(int dist);
339 void Reset(int pos);
340
341 // Reports whether the pattern might be used as a literal search string.
342 // Only use if the result of the parse is a single atom node.
343 bool simple();
344 bool contains_anchor() { return contains_anchor_; }
345 void set_contains_anchor() { contains_anchor_ = true; }
346 int captures_started() { return captures_ == NULL ? 0 : captures_->length(); }
347 int position() { return next_pos_ - 1; }
348 bool failed() { return failed_; }
349
350 static const int kMaxCaptures = 1 << 16;
351 static const uc32 kEndMarker = (1 << 21);
352
353 private:
354 enum SubexpressionType {
355 INITIAL,
356 CAPTURE, // All positive values represent captures.
357 POSITIVE_LOOKAHEAD,
358 NEGATIVE_LOOKAHEAD,
359 GROUPING
360 };
361
362 class RegExpParserState : public ZoneObject {
363 public:
364 RegExpParserState(RegExpParserState* previous_state,
365 SubexpressionType group_type,
366 int disjunction_capture_index)
367 : previous_state_(previous_state),
368 builder_(new RegExpBuilder()),
369 group_type_(group_type),
370 disjunction_capture_index_(disjunction_capture_index) {}
371 // Parser state of containing expression, if any.
372 RegExpParserState* previous_state() { return previous_state_; }
373 bool IsSubexpression() { return previous_state_ != NULL; }
374 // RegExpBuilder building this regexp's AST.
375 RegExpBuilder* builder() { return builder_; }
376 // Type of regexp being parsed (parenthesized group or entire regexp).
377 SubexpressionType group_type() { return group_type_; }
378 // Index in captures array of first capture in this sub-expression, if any.
379 // Also the capture index of this sub-expression itself, if group_type
380 // is CAPTURE.
381 int capture_index() { return disjunction_capture_index_; }
382
383 private:
384 // Linked list implementation of stack of states.
385 RegExpParserState* previous_state_;
386 // Builder for the stored disjunction.
387 RegExpBuilder* builder_;
388 // Stored disjunction type (capture, look-ahead or grouping), if any.
389 SubexpressionType group_type_;
390 // Stored disjunction's capture index (if any).
391 int disjunction_capture_index_;
392 };
393
394 uc32 current() { return current_; }
395 bool has_more() { return has_more_; }
396 bool has_next() { return next_pos_ < in()->length(); }
397 uc32 Next();
398 FlatStringReader* in() { return in_; }
399 void ScanForCaptures();
400
401 Handle<String>* error_;
402 ZoneList<RegExpCapture*>* captures_;
403 FlatStringReader* in_;
404 uc32 current_;
405 int next_pos_;
406 // The capture count is only valid after we have scanned for captures.
407 int capture_count_;
408 bool has_more_;
409 bool multiline_;
410 bool simple_;
411 bool contains_anchor_;
412 bool is_scanned_for_captures_;
413 bool failed_;
414};
415
416// ----------------------------------------------------------------------------
417// JAVASCRIPT PARSING
418
419class Parser {
420 public:
421 Parser(Handle<Script> script,
422 bool allow_natives_syntax,
423 v8::Extension* extension,
424 ScriptDataImpl* pre_data);
425 virtual ~Parser() { }
Steve Blocka7e24c12009-10-30 11:49:00 +0000426
Ben Murdochf87a2032010-10-22 12:50:53 +0100427 // Returns NULL if parsing failed.
428 FunctionLiteral* ParseProgram(Handle<String> source,
429 bool in_global_context);
Ben Murdochf87a2032010-10-22 12:50:53 +0100430
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800431 FunctionLiteral* ParseLazy(Handle<SharedFunctionInfo> info);
432
433 void ReportMessageAt(Scanner::Location loc,
434 const char* message,
435 Vector<const char*> args);
Ben Murdochf87a2032010-10-22 12:50:53 +0100436
437 protected:
Ben Murdochf87a2032010-10-22 12:50:53 +0100438 enum Mode {
439 PARSE_LAZILY,
440 PARSE_EAGERLY
441 };
442
443 // Report syntax error
444 void ReportUnexpectedToken(Token::Value token);
445 void ReportInvalidPreparseData(Handle<String> name, bool* ok);
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800446 void ReportMessage(const char* message, Vector<const char*> args);
Ben Murdochf87a2032010-10-22 12:50:53 +0100447
448 bool inside_with() const { return with_nesting_level_ > 0; }
Ben Murdochf87a2032010-10-22 12:50:53 +0100449 Scanner& scanner() { return scanner_; }
450 Mode mode() const { return mode_; }
451 ScriptDataImpl* pre_data() const { return pre_data_; }
452
453 // All ParseXXX functions take as the last argument an *ok parameter
454 // which is set to false if parsing failed; it is unchanged otherwise.
455 // By making the 'exception handling' explicit, we are forced to check
456 // for failure at the call sites.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800457 void* ParseSourceElements(ZoneList<Statement*>* processor,
Ben Murdochf87a2032010-10-22 12:50:53 +0100458 int end_token, bool* ok);
459 Statement* ParseStatement(ZoneStringList* labels, bool* ok);
460 Statement* ParseFunctionDeclaration(bool* ok);
461 Statement* ParseNativeDeclaration(bool* ok);
462 Block* ParseBlock(ZoneStringList* labels, bool* ok);
463 Block* ParseVariableStatement(bool* ok);
464 Block* ParseVariableDeclarations(bool accept_IN, Expression** var, bool* ok);
465 Statement* ParseExpressionOrLabelledStatement(ZoneStringList* labels,
466 bool* ok);
467 IfStatement* ParseIfStatement(ZoneStringList* labels, bool* ok);
468 Statement* ParseContinueStatement(bool* ok);
469 Statement* ParseBreakStatement(ZoneStringList* labels, bool* ok);
470 Statement* ParseReturnStatement(bool* ok);
471 Block* WithHelper(Expression* obj,
472 ZoneStringList* labels,
473 bool is_catch_block,
474 bool* ok);
475 Statement* ParseWithStatement(ZoneStringList* labels, bool* ok);
476 CaseClause* ParseCaseClause(bool* default_seen_ptr, bool* ok);
477 SwitchStatement* ParseSwitchStatement(ZoneStringList* labels, bool* ok);
478 DoWhileStatement* ParseDoWhileStatement(ZoneStringList* labels, bool* ok);
479 WhileStatement* ParseWhileStatement(ZoneStringList* labels, bool* ok);
480 Statement* ParseForStatement(ZoneStringList* labels, bool* ok);
481 Statement* ParseThrowStatement(bool* ok);
482 Expression* MakeCatchContext(Handle<String> id, VariableProxy* value);
483 TryStatement* ParseTryStatement(bool* ok);
484 DebuggerStatement* ParseDebuggerStatement(bool* ok);
485
486 Expression* ParseExpression(bool accept_IN, bool* ok);
487 Expression* ParseAssignmentExpression(bool accept_IN, bool* ok);
488 Expression* ParseConditionalExpression(bool accept_IN, bool* ok);
489 Expression* ParseBinaryExpression(int prec, bool accept_IN, bool* ok);
490 Expression* ParseUnaryExpression(bool* ok);
491 Expression* ParsePostfixExpression(bool* ok);
492 Expression* ParseLeftHandSideExpression(bool* ok);
493 Expression* ParseNewExpression(bool* ok);
494 Expression* ParseMemberExpression(bool* ok);
495 Expression* ParseNewPrefix(PositionStack* stack, bool* ok);
496 Expression* ParseMemberWithNewPrefixesExpression(PositionStack* stack,
497 bool* ok);
498 Expression* ParsePrimaryExpression(bool* ok);
499 Expression* ParseArrayLiteral(bool* ok);
500 Expression* ParseObjectLiteral(bool* ok);
501 ObjectLiteral::Property* ParseObjectLiteralGetSet(bool is_getter, bool* ok);
502 Expression* ParseRegExpLiteral(bool seen_equal, bool* ok);
503
504 Expression* NewCompareNode(Token::Value op,
505 Expression* x,
506 Expression* y,
507 int position);
508
509 // Populate the constant properties fixed array for a materialized object
510 // literal.
511 void BuildObjectLiteralConstantProperties(
512 ZoneList<ObjectLiteral::Property*>* properties,
513 Handle<FixedArray> constants,
514 bool* is_simple,
515 bool* fast_elements,
516 int* depth);
517
518 // Populate the literals fixed array for a materialized array literal.
519 void BuildArrayLiteralBoilerplateLiterals(ZoneList<Expression*>* properties,
520 Handle<FixedArray> constants,
521 bool* is_simple,
522 int* depth);
523
524 // Decide if a property should be in the object boilerplate.
525 bool IsBoilerplateProperty(ObjectLiteral::Property* property);
526 // If the expression is a literal, return the literal value;
527 // if the expression is a materialized literal and is simple return a
528 // compile time value as encoded by CompileTimeValue::GetValue().
529 // Otherwise, return undefined literal as the placeholder
530 // in the object literal boilerplate.
531 Handle<Object> GetBoilerplateValue(Expression* expression);
532
533 enum FunctionLiteralType {
534 EXPRESSION,
535 DECLARATION,
536 NESTED
537 };
538
539 ZoneList<Expression*>* ParseArguments(bool* ok);
540 FunctionLiteral* ParseFunctionLiteral(Handle<String> var_name,
541 int function_token_position,
542 FunctionLiteralType type,
543 bool* ok);
Steve Blocka7e24c12009-10-30 11:49:00 +0000544
545
Ben Murdochf87a2032010-10-22 12:50:53 +0100546 // Magical syntax support.
547 Expression* ParseV8Intrinsic(bool* ok);
548
549 INLINE(Token::Value peek()) { return scanner_.peek(); }
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800550 INLINE(Token::Value Next()) { return scanner_.NextCheckStack(); }
Ben Murdochf87a2032010-10-22 12:50:53 +0100551 INLINE(void Consume(Token::Value token));
552 void Expect(Token::Value token, bool* ok);
553 bool Check(Token::Value token);
554 void ExpectSemicolon(bool* ok);
555
556 Handle<String> GetSymbol(bool* ok);
557
558 // Get odd-ball literals.
559 Literal* GetLiteralUndefined();
560 Literal* GetLiteralTheHole();
561 Literal* GetLiteralNumber(double value);
562
563 Handle<String> ParseIdentifier(bool* ok);
564 Handle<String> ParseIdentifierName(bool* ok);
565 Handle<String> ParseIdentifierOrGetOrSet(bool* is_get,
566 bool* is_set,
567 bool* ok);
568
569 // Parser support
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800570 VariableProxy* Declare(Handle<String> name, Variable::Mode mode,
571 FunctionLiteral* fun,
572 bool resolve,
573 bool* ok);
Ben Murdochf87a2032010-10-22 12:50:53 +0100574
575 bool TargetStackContainsLabel(Handle<String> label);
576 BreakableStatement* LookupBreakTarget(Handle<String> label, bool* ok);
577 IterationStatement* LookupContinueTarget(Handle<String> label, bool* ok);
578
579 void RegisterTargetUse(BreakTarget* target, Target* stop);
580
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800581 // Factory methods.
582
583 Statement* EmptyStatement() {
584 static v8::internal::EmptyStatement empty;
585 return &empty;
586 }
587
588 Scope* NewScope(Scope* parent, Scope::Type type, bool inside_with);
589
590 Handle<String> LookupSymbol(int symbol_id,
591 Vector<const char> string);
592
593 Handle<String> LookupCachedSymbol(int symbol_id,
594 Vector<const char> string);
595
596 Expression* NewCall(Expression* expression,
597 ZoneList<Expression*>* arguments,
598 int pos) {
599 return new Call(expression, arguments, pos);
600 }
601
602
Ben Murdochf87a2032010-10-22 12:50:53 +0100603 // Create a number literal.
604 Literal* NewNumberLiteral(double value);
605
606 // Generate AST node that throw a ReferenceError with the given type.
607 Expression* NewThrowReferenceError(Handle<String> type);
608
609 // Generate AST node that throw a SyntaxError with the given
610 // type. The first argument may be null (in the handle sense) in
611 // which case no arguments are passed to the constructor.
612 Expression* NewThrowSyntaxError(Handle<String> type, Handle<Object> first);
613
614 // Generate AST node that throw a TypeError with the given
615 // type. Both arguments must be non-null (in the handle sense).
616 Expression* NewThrowTypeError(Handle<String> type,
617 Handle<Object> first,
618 Handle<Object> second);
619
620 // Generic AST generator for throwing errors from compiled code.
621 Expression* NewThrowError(Handle<String> constructor,
622 Handle<String> type,
623 Vector< Handle<Object> > arguments);
624
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800625 ZoneList<Handle<String> > symbol_cache_;
Ben Murdochf87a2032010-10-22 12:50:53 +0100626
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800627 Handle<Script> script_;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800628 V8JavaScriptScanner scanner_;
Ben Murdochf87a2032010-10-22 12:50:53 +0100629
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800630 Scope* top_scope_;
631 int with_nesting_level_;
Ben Murdochf87a2032010-10-22 12:50:53 +0100632
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800633 TemporaryScope* temp_scope_;
634 Mode mode_;
635
636 Target* target_stack_; // for break, continue statements
637 bool allow_natives_syntax_;
638 v8::Extension* extension_;
639 bool is_pre_parsing_;
640 ScriptDataImpl* pre_data_;
641 FuncNameInferrer* fni_;
Ben Murdochf87a2032010-10-22 12:50:53 +0100642};
Steve Blocka7e24c12009-10-30 11:49:00 +0000643
644
645// Support for handling complex values (array and object literals) that
646// can be fully handled at compile time.
647class CompileTimeValue: public AllStatic {
648 public:
649 enum Type {
Steve Block6ded16b2010-05-10 14:33:55 +0100650 OBJECT_LITERAL_FAST_ELEMENTS,
651 OBJECT_LITERAL_SLOW_ELEMENTS,
Steve Blocka7e24c12009-10-30 11:49:00 +0000652 ARRAY_LITERAL
653 };
654
655 static bool IsCompileTimeValue(Expression* expression);
656
Iain Merrick75681382010-08-19 15:07:18 +0100657 static bool ArrayLiteralElementNeedsInitialization(Expression* value);
658
Steve Blocka7e24c12009-10-30 11:49:00 +0000659 // Get the value as a compile time value.
660 static Handle<FixedArray> GetValue(Expression* expression);
661
662 // Get the type of a compile time value returned by GetValue().
663 static Type GetType(Handle<FixedArray> value);
664
665 // Get the elements array of a compile time value returned by GetValue().
666 static Handle<FixedArray> GetElements(Handle<FixedArray> value);
667
668 private:
669 static const int kTypeSlot = 0;
670 static const int kElementsSlot = 1;
671
672 DISALLOW_IMPLICIT_CONSTRUCTORS(CompileTimeValue);
673};
674
675
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800676// ----------------------------------------------------------------------------
677// JSON PARSING
678
679// JSON is a subset of JavaScript, as specified in, e.g., the ECMAScript 5
680// specification section 15.12.1 (and appendix A.8).
681// The grammar is given section 15.12.1.2 (and appendix A.8.2).
682class JsonParser BASE_EMBEDDED {
683 public:
684 // Parse JSON input as a single JSON value.
685 // Returns null handle and sets exception if parsing failed.
686 static Handle<Object> Parse(Handle<String> source) {
687 return JsonParser().ParseJson(source);
688 }
689
690 private:
691 JsonParser() { }
692 ~JsonParser() { }
693
694 // Parse a string containing a single JSON value.
695 Handle<Object> ParseJson(Handle<String>);
696 // Parse a single JSON value from input (grammar production JSONValue).
697 // A JSON value is either a (double-quoted) string literal, a number literal,
698 // one of "true", "false", or "null", or an object or array literal.
699 Handle<Object> ParseJsonValue();
700 // Parse a JSON object literal (grammar production JSONObject).
701 // An object literal is a squiggly-braced and comma separated sequence
702 // (possibly empty) of key/value pairs, where the key is a JSON string
703 // literal, the value is a JSON value, and the two are separated by a colon.
704 // A JSON array dosn't allow numbers and identifiers as keys, like a
705 // JavaScript array.
706 Handle<Object> ParseJsonObject();
707 // Parses a JSON array literal (grammar production JSONArray). An array
708 // literal is a square-bracketed and comma separated sequence (possibly empty)
709 // of JSON values.
710 // A JSON array doesn't allow leaving out values from the sequence, nor does
711 // it allow a terminal comma, like a JavaScript array does.
712 Handle<Object> ParseJsonArray();
713
714 // Mark that a parsing error has happened at the current token, and
715 // return a null handle. Primarily for readability.
716 Handle<Object> ReportUnexpectedToken() { return Handle<Object>::null(); }
717 // Converts the currently parsed literal to a JavaScript String.
718 Handle<String> GetString();
719
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800720 JsonScanner scanner_;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800721};
Steve Blocka7e24c12009-10-30 11:49:00 +0000722} } // namespace v8::internal
723
724#endif // V8_PARSER_H_