Upstream version 7.35.139.0
[platform/framework/web/crosswalk.git] / src / v8 / src / preparser.cc
1 // Copyright 2011 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 #include <cmath>
29
30 #include "../include/v8stdint.h"
31
32 #include "allocation.h"
33 #include "checks.h"
34 #include "conversions.h"
35 #include "conversions-inl.h"
36 #include "globals.h"
37 #include "hashmap.h"
38 #include "list.h"
39 #include "preparse-data-format.h"
40 #include "preparse-data.h"
41 #include "preparser.h"
42 #include "unicode.h"
43 #include "utils.h"
44
45 #if V8_LIBC_MSVCRT && (_MSC_VER < 1800)
46 namespace std {
47
48 // Usually defined in math.h, but not in MSVC until VS2013+.
49 // Abstracted to work
50 int isfinite(double value);
51
52 }  // namespace std
53 #endif
54
55 namespace v8 {
56 namespace internal {
57
58
59 void PreParserTraits::ReportMessageAt(Scanner::Location location,
60                                       const char* message,
61                                       Vector<const char*> args,
62                                       bool is_reference_error) {
63   ReportMessageAt(location.beg_pos,
64                   location.end_pos,
65                   message,
66                   args.length() > 0 ? args[0] : NULL,
67                   is_reference_error);
68 }
69
70
71 void PreParserTraits::ReportMessageAt(Scanner::Location location,
72                                       const char* type,
73                                       const char* name_opt,
74                                       bool is_reference_error) {
75   pre_parser_->log_
76       ->LogMessage(location.beg_pos, location.end_pos, type, name_opt);
77 }
78
79
80 void PreParserTraits::ReportMessageAt(int start_pos,
81                                       int end_pos,
82                                       const char* type,
83                                       const char* name_opt,
84                                       bool is_reference_error) {
85   pre_parser_->log_->LogMessage(start_pos, end_pos, type, name_opt);
86 }
87
88
89 PreParserIdentifier PreParserTraits::GetSymbol(Scanner* scanner) {
90   pre_parser_->LogSymbol();
91   if (scanner->current_token() == Token::FUTURE_RESERVED_WORD) {
92     return PreParserIdentifier::FutureReserved();
93   } else if (scanner->current_token() ==
94              Token::FUTURE_STRICT_RESERVED_WORD) {
95     return PreParserIdentifier::FutureStrictReserved();
96   } else if (scanner->current_token() == Token::YIELD) {
97     return PreParserIdentifier::Yield();
98   }
99   if (scanner->UnescapedLiteralMatches("eval", 4)) {
100     return PreParserIdentifier::Eval();
101   }
102   if (scanner->UnescapedLiteralMatches("arguments", 9)) {
103     return PreParserIdentifier::Arguments();
104   }
105   return PreParserIdentifier::Default();
106 }
107
108
109 PreParserExpression PreParserTraits::ExpressionFromString(
110     int pos, Scanner* scanner, PreParserFactory* factory) {
111   pre_parser_->LogSymbol();
112   if (scanner->UnescapedLiteralMatches("use strict", 10)) {
113     return PreParserExpression::UseStrictStringLiteral();
114   }
115   return PreParserExpression::StringLiteral();
116 }
117
118
119 PreParserExpression PreParserTraits::ParseV8Intrinsic(bool* ok) {
120   return pre_parser_->ParseV8Intrinsic(ok);
121 }
122
123
124 PreParserExpression PreParserTraits::ParseFunctionLiteral(
125     PreParserIdentifier name,
126     Scanner::Location function_name_location,
127     bool name_is_strict_reserved,
128     bool is_generator,
129     int function_token_position,
130     FunctionLiteral::FunctionType type,
131     bool* ok) {
132   return pre_parser_->ParseFunctionLiteral(
133       name, function_name_location, name_is_strict_reserved, is_generator,
134       function_token_position, type, ok);
135 }
136
137
138 PreParser::PreParseResult PreParser::PreParseLazyFunction(
139     StrictMode strict_mode, bool is_generator, ParserRecorder* log) {
140   log_ = log;
141   // Lazy functions always have trivial outer scopes (no with/catch scopes).
142   PreParserScope top_scope(scope_, GLOBAL_SCOPE);
143   FunctionState top_state(&function_state_, &scope_, &top_scope);
144   scope_->SetStrictMode(strict_mode);
145   PreParserScope function_scope(scope_, FUNCTION_SCOPE);
146   FunctionState function_state(&function_state_, &scope_, &function_scope);
147   function_state.set_is_generator(is_generator);
148   ASSERT_EQ(Token::LBRACE, scanner()->current_token());
149   bool ok = true;
150   int start_position = peek_position();
151   ParseLazyFunctionLiteralBody(&ok);
152   if (stack_overflow()) return kPreParseStackOverflow;
153   if (!ok) {
154     ReportUnexpectedToken(scanner()->current_token());
155   } else {
156     ASSERT_EQ(Token::RBRACE, scanner()->peek());
157     if (scope_->strict_mode() == STRICT) {
158       int end_pos = scanner()->location().end_pos;
159       CheckOctalLiteral(start_position, end_pos, &ok);
160     }
161   }
162   return kPreParseSuccess;
163 }
164
165
166 // Preparsing checks a JavaScript program and emits preparse-data that helps
167 // a later parsing to be faster.
168 // See preparser-data.h for the data.
169
170 // The PreParser checks that the syntax follows the grammar for JavaScript,
171 // and collects some information about the program along the way.
172 // The grammar check is only performed in order to understand the program
173 // sufficiently to deduce some information about it, that can be used
174 // to speed up later parsing. Finding errors is not the goal of pre-parsing,
175 // rather it is to speed up properly written and correct programs.
176 // That means that contextual checks (like a label being declared where
177 // it is used) are generally omitted.
178
179
180 #define CHECK_OK  ok);                      \
181   if (!*ok) return kUnknownSourceElements;  \
182   ((void)0
183 #define DUMMY )  // to make indentation work
184 #undef DUMMY
185
186
187 PreParser::Statement PreParser::ParseSourceElement(bool* ok) {
188   // (Ecma 262 5th Edition, clause 14):
189   // SourceElement:
190   //    Statement
191   //    FunctionDeclaration
192   //
193   // In harmony mode we allow additionally the following productions
194   // SourceElement:
195   //    LetDeclaration
196   //    ConstDeclaration
197   //    GeneratorDeclaration
198
199   switch (peek()) {
200     case Token::FUNCTION:
201       return ParseFunctionDeclaration(ok);
202     case Token::LET:
203     case Token::CONST:
204       return ParseVariableStatement(kSourceElement, ok);
205     default:
206       return ParseStatement(ok);
207   }
208 }
209
210
211 PreParser::SourceElements PreParser::ParseSourceElements(int end_token,
212                                                          bool* ok) {
213   // SourceElements ::
214   //   (Statement)* <end_token>
215
216   bool directive_prologue = true;
217   while (peek() != end_token) {
218     if (directive_prologue && peek() != Token::STRING) {
219       directive_prologue = false;
220     }
221     Statement statement = ParseSourceElement(CHECK_OK);
222     if (directive_prologue) {
223       if (statement.IsUseStrictLiteral()) {
224         scope_->SetStrictMode(STRICT);
225       } else if (!statement.IsStringLiteral()) {
226         directive_prologue = false;
227       }
228     }
229   }
230   return kUnknownSourceElements;
231 }
232
233
234 #undef CHECK_OK
235 #define CHECK_OK  ok);                   \
236   if (!*ok) return Statement::Default();  \
237   ((void)0
238 #define DUMMY )  // to make indentation work
239 #undef DUMMY
240
241
242 PreParser::Statement PreParser::ParseStatement(bool* ok) {
243   // Statement ::
244   //   Block
245   //   VariableStatement
246   //   EmptyStatement
247   //   ExpressionStatement
248   //   IfStatement
249   //   IterationStatement
250   //   ContinueStatement
251   //   BreakStatement
252   //   ReturnStatement
253   //   WithStatement
254   //   LabelledStatement
255   //   SwitchStatement
256   //   ThrowStatement
257   //   TryStatement
258   //   DebuggerStatement
259
260   // Note: Since labels can only be used by 'break' and 'continue'
261   // statements, which themselves are only valid within blocks,
262   // iterations or 'switch' statements (i.e., BreakableStatements),
263   // labels can be simply ignored in all other cases; except for
264   // trivial labeled break statements 'label: break label' which is
265   // parsed into an empty statement.
266
267   // Keep the source position of the statement
268   switch (peek()) {
269     case Token::LBRACE:
270       return ParseBlock(ok);
271
272     case Token::CONST:
273     case Token::LET:
274     case Token::VAR:
275       return ParseVariableStatement(kStatement, ok);
276
277     case Token::SEMICOLON:
278       Next();
279       return Statement::Default();
280
281     case Token::IF:
282       return ParseIfStatement(ok);
283
284     case Token::DO:
285       return ParseDoWhileStatement(ok);
286
287     case Token::WHILE:
288       return ParseWhileStatement(ok);
289
290     case Token::FOR:
291       return ParseForStatement(ok);
292
293     case Token::CONTINUE:
294       return ParseContinueStatement(ok);
295
296     case Token::BREAK:
297       return ParseBreakStatement(ok);
298
299     case Token::RETURN:
300       return ParseReturnStatement(ok);
301
302     case Token::WITH:
303       return ParseWithStatement(ok);
304
305     case Token::SWITCH:
306       return ParseSwitchStatement(ok);
307
308     case Token::THROW:
309       return ParseThrowStatement(ok);
310
311     case Token::TRY:
312       return ParseTryStatement(ok);
313
314     case Token::FUNCTION: {
315       Scanner::Location start_location = scanner()->peek_location();
316       Statement statement = ParseFunctionDeclaration(CHECK_OK);
317       Scanner::Location end_location = scanner()->location();
318       if (strict_mode() == STRICT) {
319         PreParserTraits::ReportMessageAt(start_location.beg_pos,
320                                          end_location.end_pos,
321                                          "strict_function",
322                                          NULL);
323         *ok = false;
324         return Statement::Default();
325       } else {
326         return statement;
327       }
328     }
329
330     case Token::DEBUGGER:
331       return ParseDebuggerStatement(ok);
332
333     default:
334       return ParseExpressionOrLabelledStatement(ok);
335   }
336 }
337
338
339 PreParser::Statement PreParser::ParseFunctionDeclaration(bool* ok) {
340   // FunctionDeclaration ::
341   //   'function' Identifier '(' FormalParameterListopt ')' '{' FunctionBody '}'
342   // GeneratorDeclaration ::
343   //   'function' '*' Identifier '(' FormalParameterListopt ')'
344   //      '{' FunctionBody '}'
345   Expect(Token::FUNCTION, CHECK_OK);
346   int pos = position();
347   bool is_generator = allow_generators() && Check(Token::MUL);
348   bool is_strict_reserved = false;
349   Identifier name = ParseIdentifierOrStrictReservedWord(
350       &is_strict_reserved, CHECK_OK);
351   ParseFunctionLiteral(name,
352                        scanner()->location(),
353                        is_strict_reserved,
354                        is_generator,
355                        pos,
356                        FunctionLiteral::DECLARATION,
357                        CHECK_OK);
358   return Statement::FunctionDeclaration();
359 }
360
361
362 PreParser::Statement PreParser::ParseBlock(bool* ok) {
363   // Block ::
364   //   '{' Statement* '}'
365
366   // Note that a Block does not introduce a new execution scope!
367   // (ECMA-262, 3rd, 12.2)
368   //
369   Expect(Token::LBRACE, CHECK_OK);
370   while (peek() != Token::RBRACE) {
371     if (allow_harmony_scoping() && strict_mode() == STRICT) {
372       ParseSourceElement(CHECK_OK);
373     } else {
374       ParseStatement(CHECK_OK);
375     }
376   }
377   Expect(Token::RBRACE, ok);
378   return Statement::Default();
379 }
380
381
382 PreParser::Statement PreParser::ParseVariableStatement(
383     VariableDeclarationContext var_context,
384     bool* ok) {
385   // VariableStatement ::
386   //   VariableDeclarations ';'
387
388   Statement result = ParseVariableDeclarations(var_context,
389                                                NULL,
390                                                NULL,
391                                                CHECK_OK);
392   ExpectSemicolon(CHECK_OK);
393   return result;
394 }
395
396
397 // If the variable declaration declares exactly one non-const
398 // variable, then *var is set to that variable. In all other cases,
399 // *var is untouched; in particular, it is the caller's responsibility
400 // to initialize it properly. This mechanism is also used for the parsing
401 // of 'for-in' loops.
402 PreParser::Statement PreParser::ParseVariableDeclarations(
403     VariableDeclarationContext var_context,
404     VariableDeclarationProperties* decl_props,
405     int* num_decl,
406     bool* ok) {
407   // VariableDeclarations ::
408   //   ('var' | 'const') (Identifier ('=' AssignmentExpression)?)+[',']
409   //
410   // The ES6 Draft Rev3 specifies the following grammar for const declarations
411   //
412   // ConstDeclaration ::
413   //   const ConstBinding (',' ConstBinding)* ';'
414   // ConstBinding ::
415   //   Identifier '=' AssignmentExpression
416   //
417   // TODO(ES6):
418   // ConstBinding ::
419   //   BindingPattern '=' AssignmentExpression
420   bool require_initializer = false;
421   if (peek() == Token::VAR) {
422     Consume(Token::VAR);
423   } else if (peek() == Token::CONST) {
424     // TODO(ES6): The ES6 Draft Rev4 section 12.2.2 reads:
425     //
426     // ConstDeclaration : const ConstBinding (',' ConstBinding)* ';'
427     //
428     // * It is a Syntax Error if the code that matches this production is not
429     //   contained in extended code.
430     //
431     // However disallowing const in sloppy mode will break compatibility with
432     // existing pages. Therefore we keep allowing const with the old
433     // non-harmony semantics in sloppy mode.
434     Consume(Token::CONST);
435     if (strict_mode() == STRICT) {
436       if (allow_harmony_scoping()) {
437         if (var_context != kSourceElement && var_context != kForStatement) {
438           ReportMessageAt(scanner()->peek_location(), "unprotected_const");
439           *ok = false;
440           return Statement::Default();
441         }
442         require_initializer = true;
443       } else {
444         Scanner::Location location = scanner()->peek_location();
445         ReportMessageAt(location, "strict_const");
446         *ok = false;
447         return Statement::Default();
448       }
449     }
450   } else if (peek() == Token::LET) {
451     // ES6 Draft Rev4 section 12.2.1:
452     //
453     // LetDeclaration : let LetBindingList ;
454     //
455     // * It is a Syntax Error if the code that matches this production is not
456     //   contained in extended code.
457     //
458     // TODO(rossberg): make 'let' a legal identifier in sloppy mode.
459     if (!allow_harmony_scoping() || strict_mode() == SLOPPY) {
460       ReportMessageAt(scanner()->peek_location(), "illegal_let");
461       *ok = false;
462       return Statement::Default();
463     }
464     Consume(Token::LET);
465     if (var_context != kSourceElement &&
466         var_context != kForStatement) {
467       ReportMessageAt(scanner()->peek_location(), "unprotected_let");
468       *ok = false;
469       return Statement::Default();
470     }
471   } else {
472     *ok = false;
473     return Statement::Default();
474   }
475
476   // The scope of a var/const declared variable anywhere inside a function
477   // is the entire function (ECMA-262, 3rd, 10.1.3, and 12.2). The scope
478   // of a let declared variable is the scope of the immediately enclosing
479   // block.
480   int nvars = 0;  // the number of variables declared
481   do {
482     // Parse variable name.
483     if (nvars > 0) Consume(Token::COMMA);
484     ParseIdentifier(kDontAllowEvalOrArguments, CHECK_OK);
485     nvars++;
486     if (peek() == Token::ASSIGN || require_initializer) {
487       Expect(Token::ASSIGN, CHECK_OK);
488       ParseAssignmentExpression(var_context != kForStatement, CHECK_OK);
489       if (decl_props != NULL) *decl_props = kHasInitializers;
490     }
491   } while (peek() == Token::COMMA);
492
493   if (num_decl != NULL) *num_decl = nvars;
494   return Statement::Default();
495 }
496
497
498 PreParser::Statement PreParser::ParseExpressionOrLabelledStatement(bool* ok) {
499   // ExpressionStatement | LabelledStatement ::
500   //   Expression ';'
501   //   Identifier ':' Statement
502
503   bool starts_with_identifier = peek_any_identifier();
504   Expression expr = ParseExpression(true, CHECK_OK);
505   // Even if the expression starts with an identifier, it is not necessarily an
506   // identifier. For example, "foo + bar" starts with an identifier but is not
507   // an identifier.
508   if (starts_with_identifier && expr.IsIdentifier() && peek() == Token::COLON) {
509     // Expression is a single identifier, and not, e.g., a parenthesized
510     // identifier.
511     ASSERT(!expr.AsIdentifier().IsFutureReserved());
512     ASSERT(strict_mode() == SLOPPY ||
513            (!expr.AsIdentifier().IsFutureStrictReserved() &&
514             !expr.AsIdentifier().IsYield()));
515     Consume(Token::COLON);
516     return ParseStatement(ok);
517     // Preparsing is disabled for extensions (because the extension details
518     // aren't passed to lazily compiled functions), so we don't
519     // accept "native function" in the preparser.
520   }
521   // Parsed expression statement.
522   ExpectSemicolon(CHECK_OK);
523   return Statement::ExpressionStatement(expr);
524 }
525
526
527 PreParser::Statement PreParser::ParseIfStatement(bool* ok) {
528   // IfStatement ::
529   //   'if' '(' Expression ')' Statement ('else' Statement)?
530
531   Expect(Token::IF, CHECK_OK);
532   Expect(Token::LPAREN, CHECK_OK);
533   ParseExpression(true, CHECK_OK);
534   Expect(Token::RPAREN, CHECK_OK);
535   ParseStatement(CHECK_OK);
536   if (peek() == Token::ELSE) {
537     Next();
538     ParseStatement(CHECK_OK);
539   }
540   return Statement::Default();
541 }
542
543
544 PreParser::Statement PreParser::ParseContinueStatement(bool* ok) {
545   // ContinueStatement ::
546   //   'continue' [no line terminator] Identifier? ';'
547
548   Expect(Token::CONTINUE, CHECK_OK);
549   Token::Value tok = peek();
550   if (!scanner()->HasAnyLineTerminatorBeforeNext() &&
551       tok != Token::SEMICOLON &&
552       tok != Token::RBRACE &&
553       tok != Token::EOS) {
554     // ECMA allows "eval" or "arguments" as labels even in strict mode.
555     ParseIdentifier(kAllowEvalOrArguments, CHECK_OK);
556   }
557   ExpectSemicolon(CHECK_OK);
558   return Statement::Default();
559 }
560
561
562 PreParser::Statement PreParser::ParseBreakStatement(bool* ok) {
563   // BreakStatement ::
564   //   'break' [no line terminator] Identifier? ';'
565
566   Expect(Token::BREAK, CHECK_OK);
567   Token::Value tok = peek();
568   if (!scanner()->HasAnyLineTerminatorBeforeNext() &&
569       tok != Token::SEMICOLON &&
570       tok != Token::RBRACE &&
571       tok != Token::EOS) {
572     // ECMA allows "eval" or "arguments" as labels even in strict mode.
573     ParseIdentifier(kAllowEvalOrArguments, CHECK_OK);
574   }
575   ExpectSemicolon(CHECK_OK);
576   return Statement::Default();
577 }
578
579
580 PreParser::Statement PreParser::ParseReturnStatement(bool* ok) {
581   // ReturnStatement ::
582   //   'return' [no line terminator] Expression? ';'
583
584   // Consume the return token. It is necessary to do the before
585   // reporting any errors on it, because of the way errors are
586   // reported (underlining).
587   Expect(Token::RETURN, CHECK_OK);
588
589   // An ECMAScript program is considered syntactically incorrect if it
590   // contains a return statement that is not within the body of a
591   // function. See ECMA-262, section 12.9, page 67.
592   // This is not handled during preparsing.
593
594   Token::Value tok = peek();
595   if (!scanner()->HasAnyLineTerminatorBeforeNext() &&
596       tok != Token::SEMICOLON &&
597       tok != Token::RBRACE &&
598       tok != Token::EOS) {
599     ParseExpression(true, CHECK_OK);
600   }
601   ExpectSemicolon(CHECK_OK);
602   return Statement::Default();
603 }
604
605
606 PreParser::Statement PreParser::ParseWithStatement(bool* ok) {
607   // WithStatement ::
608   //   'with' '(' Expression ')' Statement
609   Expect(Token::WITH, CHECK_OK);
610   if (strict_mode() == STRICT) {
611     ReportMessageAt(scanner()->location(), "strict_mode_with");
612     *ok = false;
613     return Statement::Default();
614   }
615   Expect(Token::LPAREN, CHECK_OK);
616   ParseExpression(true, CHECK_OK);
617   Expect(Token::RPAREN, CHECK_OK);
618
619   PreParserScope with_scope(scope_, WITH_SCOPE);
620   BlockState block_state(&scope_, &with_scope);
621   ParseStatement(CHECK_OK);
622   return Statement::Default();
623 }
624
625
626 PreParser::Statement PreParser::ParseSwitchStatement(bool* ok) {
627   // SwitchStatement ::
628   //   'switch' '(' Expression ')' '{' CaseClause* '}'
629
630   Expect(Token::SWITCH, CHECK_OK);
631   Expect(Token::LPAREN, CHECK_OK);
632   ParseExpression(true, CHECK_OK);
633   Expect(Token::RPAREN, CHECK_OK);
634
635   Expect(Token::LBRACE, CHECK_OK);
636   Token::Value token = peek();
637   while (token != Token::RBRACE) {
638     if (token == Token::CASE) {
639       Expect(Token::CASE, CHECK_OK);
640       ParseExpression(true, CHECK_OK);
641     } else {
642       Expect(Token::DEFAULT, CHECK_OK);
643     }
644     Expect(Token::COLON, CHECK_OK);
645     token = peek();
646     while (token != Token::CASE &&
647            token != Token::DEFAULT &&
648            token != Token::RBRACE) {
649       ParseStatement(CHECK_OK);
650       token = peek();
651     }
652   }
653   Expect(Token::RBRACE, ok);
654   return Statement::Default();
655 }
656
657
658 PreParser::Statement PreParser::ParseDoWhileStatement(bool* ok) {
659   // DoStatement ::
660   //   'do' Statement 'while' '(' Expression ')' ';'
661
662   Expect(Token::DO, CHECK_OK);
663   ParseStatement(CHECK_OK);
664   Expect(Token::WHILE, CHECK_OK);
665   Expect(Token::LPAREN, CHECK_OK);
666   ParseExpression(true, CHECK_OK);
667   Expect(Token::RPAREN, ok);
668   if (peek() == Token::SEMICOLON) Consume(Token::SEMICOLON);
669   return Statement::Default();
670 }
671
672
673 PreParser::Statement PreParser::ParseWhileStatement(bool* ok) {
674   // WhileStatement ::
675   //   'while' '(' Expression ')' Statement
676
677   Expect(Token::WHILE, CHECK_OK);
678   Expect(Token::LPAREN, CHECK_OK);
679   ParseExpression(true, CHECK_OK);
680   Expect(Token::RPAREN, CHECK_OK);
681   ParseStatement(ok);
682   return Statement::Default();
683 }
684
685
686 bool PreParser::CheckInOrOf(bool accept_OF) {
687   if (Check(Token::IN) ||
688       (allow_for_of() && accept_OF &&
689        CheckContextualKeyword(CStrVector("of")))) {
690     return true;
691   }
692   return false;
693 }
694
695
696 PreParser::Statement PreParser::ParseForStatement(bool* ok) {
697   // ForStatement ::
698   //   'for' '(' Expression? ';' Expression? ';' Expression? ')' Statement
699
700   Expect(Token::FOR, CHECK_OK);
701   Expect(Token::LPAREN, CHECK_OK);
702   if (peek() != Token::SEMICOLON) {
703     if (peek() == Token::VAR || peek() == Token::CONST ||
704         peek() == Token::LET) {
705       bool is_let = peek() == Token::LET;
706       int decl_count;
707       VariableDeclarationProperties decl_props = kHasNoInitializers;
708       ParseVariableDeclarations(
709           kForStatement, &decl_props, &decl_count, CHECK_OK);
710       bool has_initializers = decl_props == kHasInitializers;
711       bool accept_IN = decl_count == 1 && !(is_let && has_initializers);
712       bool accept_OF = !has_initializers;
713       if (accept_IN && CheckInOrOf(accept_OF)) {
714         ParseExpression(true, CHECK_OK);
715         Expect(Token::RPAREN, CHECK_OK);
716
717         ParseStatement(CHECK_OK);
718         return Statement::Default();
719       }
720     } else {
721       Expression lhs = ParseExpression(false, CHECK_OK);
722       if (CheckInOrOf(lhs.IsIdentifier())) {
723         ParseExpression(true, CHECK_OK);
724         Expect(Token::RPAREN, CHECK_OK);
725
726         ParseStatement(CHECK_OK);
727         return Statement::Default();
728       }
729     }
730   }
731
732   // Parsed initializer at this point.
733   Expect(Token::SEMICOLON, CHECK_OK);
734
735   if (peek() != Token::SEMICOLON) {
736     ParseExpression(true, CHECK_OK);
737   }
738   Expect(Token::SEMICOLON, CHECK_OK);
739
740   if (peek() != Token::RPAREN) {
741     ParseExpression(true, CHECK_OK);
742   }
743   Expect(Token::RPAREN, CHECK_OK);
744
745   ParseStatement(ok);
746   return Statement::Default();
747 }
748
749
750 PreParser::Statement PreParser::ParseThrowStatement(bool* ok) {
751   // ThrowStatement ::
752   //   'throw' [no line terminator] Expression ';'
753
754   Expect(Token::THROW, CHECK_OK);
755   if (scanner()->HasAnyLineTerminatorBeforeNext()) {
756     ReportMessageAt(scanner()->location(), "newline_after_throw");
757     *ok = false;
758     return Statement::Default();
759   }
760   ParseExpression(true, CHECK_OK);
761   ExpectSemicolon(ok);
762   return Statement::Default();
763 }
764
765
766 PreParser::Statement PreParser::ParseTryStatement(bool* ok) {
767   // TryStatement ::
768   //   'try' Block Catch
769   //   'try' Block Finally
770   //   'try' Block Catch Finally
771   //
772   // Catch ::
773   //   'catch' '(' Identifier ')' Block
774   //
775   // Finally ::
776   //   'finally' Block
777
778   Expect(Token::TRY, CHECK_OK);
779
780   ParseBlock(CHECK_OK);
781
782   Token::Value tok = peek();
783   if (tok != Token::CATCH && tok != Token::FINALLY) {
784     ReportMessageAt(scanner()->location(), "no_catch_or_finally");
785     *ok = false;
786     return Statement::Default();
787   }
788   if (tok == Token::CATCH) {
789     Consume(Token::CATCH);
790     Expect(Token::LPAREN, CHECK_OK);
791     ParseIdentifier(kDontAllowEvalOrArguments, CHECK_OK);
792     Expect(Token::RPAREN, CHECK_OK);
793     {
794       PreParserScope with_scope(scope_, WITH_SCOPE);
795       BlockState block_state(&scope_, &with_scope);
796       ParseBlock(CHECK_OK);
797     }
798     tok = peek();
799   }
800   if (tok == Token::FINALLY) {
801     Consume(Token::FINALLY);
802     ParseBlock(CHECK_OK);
803   }
804   return Statement::Default();
805 }
806
807
808 PreParser::Statement PreParser::ParseDebuggerStatement(bool* ok) {
809   // In ECMA-262 'debugger' is defined as a reserved keyword. In some browser
810   // contexts this is used as a statement which invokes the debugger as if a
811   // break point is present.
812   // DebuggerStatement ::
813   //   'debugger' ';'
814
815   Expect(Token::DEBUGGER, CHECK_OK);
816   ExpectSemicolon(ok);
817   return Statement::Default();
818 }
819
820
821 #undef CHECK_OK
822 #define CHECK_OK  ok);                     \
823   if (!*ok) return Expression::Default();  \
824   ((void)0
825 #define DUMMY )  // to make indentation work
826 #undef DUMMY
827
828
829 PreParser::Expression PreParser::ParseFunctionLiteral(
830     Identifier function_name,
831     Scanner::Location function_name_location,
832     bool name_is_strict_reserved,
833     bool is_generator,
834     int function_token_pos,
835     FunctionLiteral::FunctionType function_type,
836     bool* ok) {
837   // Function ::
838   //   '(' FormalParameterList? ')' '{' FunctionBody '}'
839
840   // Parse function body.
841   ScopeType outer_scope_type = scope_->type();
842   PreParserScope function_scope(scope_, FUNCTION_SCOPE);
843   FunctionState function_state(&function_state_, &scope_, &function_scope);
844   function_state.set_is_generator(is_generator);
845   //  FormalParameterList ::
846   //    '(' (Identifier)*[','] ')'
847   Expect(Token::LPAREN, CHECK_OK);
848   int start_position = position();
849   bool done = (peek() == Token::RPAREN);
850   DuplicateFinder duplicate_finder(scanner()->unicode_cache());
851   // We don't yet know if the function will be strict, so we cannot yet produce
852   // errors for parameter names or duplicates. However, we remember the
853   // locations of these errors if they occur and produce the errors later.
854   Scanner::Location eval_args_error_loc = Scanner::Location::invalid();
855   Scanner::Location dupe_error_loc = Scanner::Location::invalid();
856   Scanner::Location reserved_error_loc = Scanner::Location::invalid();
857   while (!done) {
858     bool is_strict_reserved = false;
859     Identifier param_name =
860         ParseIdentifierOrStrictReservedWord(&is_strict_reserved, CHECK_OK);
861     if (!eval_args_error_loc.IsValid() && param_name.IsEvalOrArguments()) {
862       eval_args_error_loc = scanner()->location();
863     }
864     if (!reserved_error_loc.IsValid() && is_strict_reserved) {
865       reserved_error_loc = scanner()->location();
866     }
867
868     int prev_value = scanner()->FindSymbol(&duplicate_finder, 1);
869
870     if (!dupe_error_loc.IsValid() && prev_value != 0) {
871       dupe_error_loc = scanner()->location();
872     }
873
874     done = (peek() == Token::RPAREN);
875     if (!done) {
876       Expect(Token::COMMA, CHECK_OK);
877     }
878   }
879   Expect(Token::RPAREN, CHECK_OK);
880
881   // See Parser::ParseFunctionLiteral for more information about lazy parsing
882   // and lazy compilation.
883   bool is_lazily_parsed = (outer_scope_type == GLOBAL_SCOPE && allow_lazy() &&
884                            !parenthesized_function_);
885   parenthesized_function_ = false;
886
887   Expect(Token::LBRACE, CHECK_OK);
888   if (is_lazily_parsed) {
889     ParseLazyFunctionLiteralBody(CHECK_OK);
890   } else {
891     ParseSourceElements(Token::RBRACE, ok);
892   }
893   Expect(Token::RBRACE, CHECK_OK);
894
895   // Validate strict mode. We can do this only after parsing the function,
896   // since the function can declare itself strict.
897   if (strict_mode() == STRICT) {
898     if (function_name.IsEvalOrArguments()) {
899       ReportMessageAt(function_name_location, "strict_eval_arguments");
900       *ok = false;
901       return Expression::Default();
902     }
903     if (name_is_strict_reserved) {
904       ReportMessageAt(function_name_location, "unexpected_strict_reserved");
905       *ok = false;
906       return Expression::Default();
907     }
908     if (eval_args_error_loc.IsValid()) {
909       ReportMessageAt(eval_args_error_loc, "strict_eval_arguments");
910       *ok = false;
911       return Expression::Default();
912     }
913     if (dupe_error_loc.IsValid()) {
914       ReportMessageAt(dupe_error_loc, "strict_param_dupe");
915       *ok = false;
916       return Expression::Default();
917     }
918     if (reserved_error_loc.IsValid()) {
919       ReportMessageAt(reserved_error_loc, "unexpected_strict_reserved");
920       *ok = false;
921       return Expression::Default();
922     }
923
924     int end_position = scanner()->location().end_pos;
925     CheckOctalLiteral(start_position, end_position, CHECK_OK);
926   }
927
928   return Expression::Default();
929 }
930
931
932 void PreParser::ParseLazyFunctionLiteralBody(bool* ok) {
933   int body_start = position();
934   bool is_logging = log_->ShouldLogSymbols();
935   if (is_logging) log_->PauseRecording();
936   ParseSourceElements(Token::RBRACE, ok);
937   if (is_logging) log_->ResumeRecording();
938   if (!*ok) return;
939
940   // Position right after terminal '}'.
941   ASSERT_EQ(Token::RBRACE, scanner()->peek());
942   int body_end = scanner()->peek_location().end_pos;
943   log_->LogFunction(body_start, body_end,
944                     function_state_->materialized_literal_count(),
945                     function_state_->expected_property_count(),
946                     strict_mode());
947 }
948
949
950 PreParser::Expression PreParser::ParseV8Intrinsic(bool* ok) {
951   // CallRuntime ::
952   //   '%' Identifier Arguments
953   Expect(Token::MOD, CHECK_OK);
954   if (!allow_natives_syntax()) {
955     *ok = false;
956     return Expression::Default();
957   }
958   // Allow "eval" or "arguments" for backward compatibility.
959   ParseIdentifier(kAllowEvalOrArguments, CHECK_OK);
960   ParseArguments(ok);
961
962   return Expression::Default();
963 }
964
965 #undef CHECK_OK
966
967
968 void PreParser::LogSymbol() {
969   if (log_->ShouldLogSymbols()) {
970     scanner()->LogSymbol(log_, position());
971   }
972 }
973
974
975 } }  // v8::internal