ParseTentative.cpp revision 198954
1//===--- ParseTentative.cpp - Ambiguity Resolution Parsing ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements the tentative parsing portions of the Parser
11//  interfaces, for ambiguity resolution.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Parse/Parser.h"
16#include "clang/Parse/ParseDiagnostic.h"
17using namespace clang;
18
19/// isCXXDeclarationStatement - C++-specialized function that disambiguates
20/// between a declaration or an expression statement, when parsing function
21/// bodies. Returns true for declaration, false for expression.
22///
23///         declaration-statement:
24///           block-declaration
25///
26///         block-declaration:
27///           simple-declaration
28///           asm-definition
29///           namespace-alias-definition
30///           using-declaration
31///           using-directive
32/// [C++0x]   static_assert-declaration
33///
34///         asm-definition:
35///           'asm' '(' string-literal ')' ';'
36///
37///         namespace-alias-definition:
38///           'namespace' identifier = qualified-namespace-specifier ';'
39///
40///         using-declaration:
41///           'using' typename[opt] '::'[opt] nested-name-specifier
42///                 unqualified-id ';'
43///           'using' '::' unqualified-id ;
44///
45///         using-directive:
46///           'using' 'namespace' '::'[opt] nested-name-specifier[opt]
47///                 namespace-name ';'
48///
49bool Parser::isCXXDeclarationStatement() {
50  switch (Tok.getKind()) {
51    // asm-definition
52  case tok::kw_asm:
53    // namespace-alias-definition
54  case tok::kw_namespace:
55    // using-declaration
56    // using-directive
57  case tok::kw_using:
58    return true;
59  case tok::kw_static_assert:
60    // static_assert-declaration
61    return true;
62  default:
63    // simple-declaration
64    return isCXXSimpleDeclaration();
65  }
66}
67
68/// isCXXSimpleDeclaration - C++-specialized function that disambiguates
69/// between a simple-declaration or an expression-statement.
70/// If during the disambiguation process a parsing error is encountered,
71/// the function returns true to let the declaration parsing code handle it.
72/// Returns false if the statement is disambiguated as expression.
73///
74/// simple-declaration:
75///   decl-specifier-seq init-declarator-list[opt] ';'
76///
77bool Parser::isCXXSimpleDeclaration() {
78  // C++ 6.8p1:
79  // There is an ambiguity in the grammar involving expression-statements and
80  // declarations: An expression-statement with a function-style explicit type
81  // conversion (5.2.3) as its leftmost subexpression can be indistinguishable
82  // from a declaration where the first declarator starts with a '('. In those
83  // cases the statement is a declaration. [Note: To disambiguate, the whole
84  // statement might have to be examined to determine if it is an
85  // expression-statement or a declaration].
86
87  // C++ 6.8p3:
88  // The disambiguation is purely syntactic; that is, the meaning of the names
89  // occurring in such a statement, beyond whether they are type-names or not,
90  // is not generally used in or changed by the disambiguation. Class
91  // templates are instantiated as necessary to determine if a qualified name
92  // is a type-name. Disambiguation precedes parsing, and a statement
93  // disambiguated as a declaration may be an ill-formed declaration.
94
95  // We don't have to parse all of the decl-specifier-seq part. There's only
96  // an ambiguity if the first decl-specifier is
97  // simple-type-specifier/typename-specifier followed by a '(', which may
98  // indicate a function-style cast expression.
99  // isCXXDeclarationSpecifier will return TPResult::Ambiguous() only in such
100  // a case.
101
102  TPResult TPR = isCXXDeclarationSpecifier();
103  if (TPR != TPResult::Ambiguous())
104    return TPR != TPResult::False(); // Returns true for TPResult::True() or
105                                     // TPResult::Error().
106
107  // FIXME: Add statistics about the number of ambiguous statements encountered
108  // and how they were resolved (number of declarations+number of expressions).
109
110  // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
111  // We need tentative parsing...
112
113  TentativeParsingAction PA(*this);
114
115  TPR = TryParseSimpleDeclaration();
116  SourceLocation TentativeParseLoc = Tok.getLocation();
117
118  PA.Revert();
119
120  // In case of an error, let the declaration parsing code handle it.
121  if (TPR == TPResult::Error())
122    return true;
123
124  // Declarations take precedence over expressions.
125  if (TPR == TPResult::Ambiguous())
126    TPR = TPResult::True();
127
128  assert(TPR == TPResult::True() || TPR == TPResult::False());
129  return TPR == TPResult::True();
130}
131
132/// simple-declaration:
133///   decl-specifier-seq init-declarator-list[opt] ';'
134///
135Parser::TPResult Parser::TryParseSimpleDeclaration() {
136  // We know that we have a simple-type-specifier/typename-specifier followed
137  // by a '('.
138  assert(isCXXDeclarationSpecifier() == TPResult::Ambiguous());
139
140  if (Tok.is(tok::kw_typeof))
141    TryParseTypeofSpecifier();
142  else
143    ConsumeToken();
144
145  assert(Tok.is(tok::l_paren) && "Expected '('");
146
147  TPResult TPR = TryParseInitDeclaratorList();
148  if (TPR != TPResult::Ambiguous())
149    return TPR;
150
151  if (Tok.isNot(tok::semi))
152    return TPResult::False();
153
154  return TPResult::Ambiguous();
155}
156
157///       init-declarator-list:
158///         init-declarator
159///         init-declarator-list ',' init-declarator
160///
161///       init-declarator:
162///         declarator initializer[opt]
163/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
164///
165/// initializer:
166///   '=' initializer-clause
167///   '(' expression-list ')'
168///
169/// initializer-clause:
170///   assignment-expression
171///   '{' initializer-list ','[opt] '}'
172///   '{' '}'
173///
174Parser::TPResult Parser::TryParseInitDeclaratorList() {
175  // GCC only examines the first declarator for disambiguation:
176  // i.e:
177  // int(x), ++x; // GCC regards it as ill-formed declaration.
178  //
179  // Comeau and MSVC will regard the above statement as correct expression.
180  // Clang examines all of the declarators and also regards the above statement
181  // as correct expression.
182
183  while (1) {
184    // declarator
185    TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
186    if (TPR != TPResult::Ambiguous())
187      return TPR;
188
189    // [GNU] simple-asm-expr[opt] attributes[opt]
190    if (Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
191      return TPResult::True();
192
193    // initializer[opt]
194    if (Tok.is(tok::l_paren)) {
195      // Parse through the parens.
196      ConsumeParen();
197      if (!SkipUntil(tok::r_paren))
198        return TPResult::Error();
199    } else if (Tok.is(tok::equal)) {
200      // MSVC won't examine the rest of declarators if '=' is encountered, it
201      // will conclude that it is a declaration.
202      // Comeau and Clang will examine the rest of declarators.
203      // Note that "int(x) = {0}, ++x;" will be interpreted as ill-formed
204      // expression.
205      //
206      // Parse through the initializer-clause.
207      SkipUntil(tok::comma, true/*StopAtSemi*/, true/*DontConsume*/);
208    }
209
210    if (Tok.isNot(tok::comma))
211      break;
212    ConsumeToken(); // the comma.
213  }
214
215  return TPResult::Ambiguous();
216}
217
218/// isCXXConditionDeclaration - Disambiguates between a declaration or an
219/// expression for a condition of a if/switch/while/for statement.
220/// If during the disambiguation process a parsing error is encountered,
221/// the function returns true to let the declaration parsing code handle it.
222///
223///       condition:
224///         expression
225///         type-specifier-seq declarator '=' assignment-expression
226/// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
227///             '=' assignment-expression
228///
229bool Parser::isCXXConditionDeclaration() {
230  TPResult TPR = isCXXDeclarationSpecifier();
231  if (TPR != TPResult::Ambiguous())
232    return TPR != TPResult::False(); // Returns true for TPResult::True() or
233                                     // TPResult::Error().
234
235  // FIXME: Add statistics about the number of ambiguous statements encountered
236  // and how they were resolved (number of declarations+number of expressions).
237
238  // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
239  // We need tentative parsing...
240
241  TentativeParsingAction PA(*this);
242
243  // type-specifier-seq
244  if (Tok.is(tok::kw_typeof))
245    TryParseTypeofSpecifier();
246  else
247    ConsumeToken();
248  assert(Tok.is(tok::l_paren) && "Expected '('");
249
250  // declarator
251  TPR = TryParseDeclarator(false/*mayBeAbstract*/);
252
253  // In case of an error, let the declaration parsing code handle it.
254  if (TPR == TPResult::Error())
255    TPR = TPResult::True();
256
257  if (TPR == TPResult::Ambiguous()) {
258    // '='
259    // [GNU] simple-asm-expr[opt] attributes[opt]
260    if (Tok.is(tok::equal)  ||
261        Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
262      TPR = TPResult::True();
263    else
264      TPR = TPResult::False();
265  }
266
267  PA.Revert();
268
269  assert(TPR == TPResult::True() || TPR == TPResult::False());
270  return TPR == TPResult::True();
271}
272
273  /// \brief Determine whether the next set of tokens contains a type-id.
274  ///
275  /// The context parameter states what context we're parsing right
276  /// now, which affects how this routine copes with the token
277  /// following the type-id. If the context is TypeIdInParens, we have
278  /// already parsed the '(' and we will cease lookahead when we hit
279  /// the corresponding ')'. If the context is
280  /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
281  /// before this template argument, and will cease lookahead when we
282  /// hit a '>', '>>' (in C++0x), or ','. Returns true for a type-id
283  /// and false for an expression.  If during the disambiguation
284  /// process a parsing error is encountered, the function returns
285  /// true to let the declaration parsing code handle it.
286  ///
287  /// type-id:
288  ///   type-specifier-seq abstract-declarator[opt]
289  ///
290bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
291
292  isAmbiguous = false;
293
294  // C++ 8.2p2:
295  // The ambiguity arising from the similarity between a function-style cast and
296  // a type-id can occur in different contexts. The ambiguity appears as a
297  // choice between a function-style cast expression and a declaration of a
298  // type. The resolution is that any construct that could possibly be a type-id
299  // in its syntactic context shall be considered a type-id.
300
301  TPResult TPR = isCXXDeclarationSpecifier();
302  if (TPR != TPResult::Ambiguous())
303    return TPR != TPResult::False(); // Returns true for TPResult::True() or
304                                     // TPResult::Error().
305
306  // FIXME: Add statistics about the number of ambiguous statements encountered
307  // and how they were resolved (number of declarations+number of expressions).
308
309  // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
310  // We need tentative parsing...
311
312  TentativeParsingAction PA(*this);
313
314  // type-specifier-seq
315  if (Tok.is(tok::kw_typeof))
316    TryParseTypeofSpecifier();
317  else
318    ConsumeToken();
319  assert(Tok.is(tok::l_paren) && "Expected '('");
320
321  // declarator
322  TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
323
324  // In case of an error, let the declaration parsing code handle it.
325  if (TPR == TPResult::Error())
326    TPR = TPResult::True();
327
328  if (TPR == TPResult::Ambiguous()) {
329    // We are supposed to be inside parens, so if after the abstract declarator
330    // we encounter a ')' this is a type-id, otherwise it's an expression.
331    if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
332      TPR = TPResult::True();
333      isAmbiguous = true;
334
335    // We are supposed to be inside a template argument, so if after
336    // the abstract declarator we encounter a '>', '>>' (in C++0x), or
337    // ',', this is a type-id. Otherwise, it's an expression.
338    } else if (Context == TypeIdAsTemplateArgument &&
339               (Tok.is(tok::greater) || Tok.is(tok::comma) ||
340                (getLang().CPlusPlus0x && Tok.is(tok::greatergreater)))) {
341      TPR = TPResult::True();
342      isAmbiguous = true;
343
344    } else
345      TPR = TPResult::False();
346  }
347
348  PA.Revert();
349
350  assert(TPR == TPResult::True() || TPR == TPResult::False());
351  return TPR == TPResult::True();
352}
353
354///         declarator:
355///           direct-declarator
356///           ptr-operator declarator
357///
358///         direct-declarator:
359///           declarator-id
360///           direct-declarator '(' parameter-declaration-clause ')'
361///                 cv-qualifier-seq[opt] exception-specification[opt]
362///           direct-declarator '[' constant-expression[opt] ']'
363///           '(' declarator ')'
364/// [GNU]     '(' attributes declarator ')'
365///
366///         abstract-declarator:
367///           ptr-operator abstract-declarator[opt]
368///           direct-abstract-declarator
369///
370///         direct-abstract-declarator:
371///           direct-abstract-declarator[opt]
372///           '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
373///                 exception-specification[opt]
374///           direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
375///           '(' abstract-declarator ')'
376///
377///         ptr-operator:
378///           '*' cv-qualifier-seq[opt]
379///           '&'
380/// [C++0x]   '&&'                                                        [TODO]
381///           '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
382///
383///         cv-qualifier-seq:
384///           cv-qualifier cv-qualifier-seq[opt]
385///
386///         cv-qualifier:
387///           'const'
388///           'volatile'
389///
390///         declarator-id:
391///           id-expression
392///
393///         id-expression:
394///           unqualified-id
395///           qualified-id                                                [TODO]
396///
397///         unqualified-id:
398///           identifier
399///           operator-function-id                                        [TODO]
400///           conversion-function-id                                      [TODO]
401///           '~' class-name                                              [TODO]
402///           template-id                                                 [TODO]
403///
404Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
405                                            bool mayHaveIdentifier) {
406  // declarator:
407  //   direct-declarator
408  //   ptr-operator declarator
409
410  while (1) {
411    if (Tok.is(tok::coloncolon) || Tok.is(tok::identifier))
412      TryAnnotateCXXScopeToken(true);
413
414    if (Tok.is(tok::star) || Tok.is(tok::amp) || Tok.is(tok::caret) ||
415        (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
416      // ptr-operator
417      ConsumeToken();
418      while (Tok.is(tok::kw_const)    ||
419             Tok.is(tok::kw_volatile) ||
420             Tok.is(tok::kw_restrict))
421        ConsumeToken();
422    } else {
423      break;
424    }
425  }
426
427  // direct-declarator:
428  // direct-abstract-declarator:
429
430  if ((Tok.is(tok::identifier) ||
431       (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) &&
432      mayHaveIdentifier) {
433    // declarator-id
434    if (Tok.is(tok::annot_cxxscope))
435      ConsumeToken();
436    ConsumeToken();
437  } else if (Tok.is(tok::l_paren)) {
438    ConsumeParen();
439    if (mayBeAbstract &&
440        (Tok.is(tok::r_paren) ||       // 'int()' is a function.
441         Tok.is(tok::ellipsis) ||      // 'int(...)' is a function.
442         isDeclarationSpecifier())) {   // 'int(int)' is a function.
443      // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
444      //        exception-specification[opt]
445      TPResult TPR = TryParseFunctionDeclarator();
446      if (TPR != TPResult::Ambiguous())
447        return TPR;
448    } else {
449      // '(' declarator ')'
450      // '(' attributes declarator ')'
451      // '(' abstract-declarator ')'
452      if (Tok.is(tok::kw___attribute))
453        return TPResult::True(); // attributes indicate declaration
454      TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
455      if (TPR != TPResult::Ambiguous())
456        return TPR;
457      if (Tok.isNot(tok::r_paren))
458        return TPResult::False();
459      ConsumeParen();
460    }
461  } else if (!mayBeAbstract) {
462    return TPResult::False();
463  }
464
465  while (1) {
466    TPResult TPR(TPResult::Ambiguous());
467
468    if (Tok.is(tok::l_paren)) {
469      // Check whether we have a function declarator or a possible ctor-style
470      // initializer that follows the declarator. Note that ctor-style
471      // initializers are not possible in contexts where abstract declarators
472      // are allowed.
473      if (!mayBeAbstract && !isCXXFunctionDeclarator(false/*warnIfAmbiguous*/))
474        break;
475
476      // direct-declarator '(' parameter-declaration-clause ')'
477      //        cv-qualifier-seq[opt] exception-specification[opt]
478      ConsumeParen();
479      TPR = TryParseFunctionDeclarator();
480    } else if (Tok.is(tok::l_square)) {
481      // direct-declarator '[' constant-expression[opt] ']'
482      // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
483      TPR = TryParseBracketDeclarator();
484    } else {
485      break;
486    }
487
488    if (TPR != TPResult::Ambiguous())
489      return TPR;
490  }
491
492  return TPResult::Ambiguous();
493}
494
495/// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a declaration
496/// specifier, TPResult::False() if it is not, TPResult::Ambiguous() if it could
497/// be either a decl-specifier or a function-style cast, and TPResult::Error()
498/// if a parsing error was found and reported.
499///
500///         decl-specifier:
501///           storage-class-specifier
502///           type-specifier
503///           function-specifier
504///           'friend'
505///           'typedef'
506/// [C++0x]   'constexpr'
507/// [GNU]     attributes declaration-specifiers[opt]
508///
509///         storage-class-specifier:
510///           'register'
511///           'static'
512///           'extern'
513///           'mutable'
514///           'auto'
515/// [GNU]     '__thread'
516///
517///         function-specifier:
518///           'inline'
519///           'virtual'
520///           'explicit'
521///
522///         typedef-name:
523///           identifier
524///
525///         type-specifier:
526///           simple-type-specifier
527///           class-specifier
528///           enum-specifier
529///           elaborated-type-specifier
530///           typename-specifier
531///           cv-qualifier
532///
533///         simple-type-specifier:
534///           '::'[opt] nested-name-specifier[opt] type-name
535///           '::'[opt] nested-name-specifier 'template'
536///                 simple-template-id                              [TODO]
537///           'char'
538///           'wchar_t'
539///           'bool'
540///           'short'
541///           'int'
542///           'long'
543///           'signed'
544///           'unsigned'
545///           'float'
546///           'double'
547///           'void'
548/// [GNU]     typeof-specifier
549/// [GNU]     '_Complex'
550/// [C++0x]   'auto'                                                [TODO]
551/// [C++0x]   'decltype' ( expression )
552///
553///         type-name:
554///           class-name
555///           enum-name
556///           typedef-name
557///
558///         elaborated-type-specifier:
559///           class-key '::'[opt] nested-name-specifier[opt] identifier
560///           class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
561///               simple-template-id
562///           'enum' '::'[opt] nested-name-specifier[opt] identifier
563///
564///         enum-name:
565///           identifier
566///
567///         enum-specifier:
568///           'enum' identifier[opt] '{' enumerator-list[opt] '}'
569///           'enum' identifier[opt] '{' enumerator-list ',' '}'
570///
571///         class-specifier:
572///           class-head '{' member-specification[opt] '}'
573///
574///         class-head:
575///           class-key identifier[opt] base-clause[opt]
576///           class-key nested-name-specifier identifier base-clause[opt]
577///           class-key nested-name-specifier[opt] simple-template-id
578///               base-clause[opt]
579///
580///         class-key:
581///           'class'
582///           'struct'
583///           'union'
584///
585///         cv-qualifier:
586///           'const'
587///           'volatile'
588/// [GNU]     restrict
589///
590Parser::TPResult Parser::isCXXDeclarationSpecifier() {
591  switch (Tok.getKind()) {
592  case tok::identifier:   // foo::bar
593  case tok::kw_typename:  // typename T::type
594    // Annotate typenames and C++ scope specifiers.  If we get one, just
595    // recurse to handle whatever we get.
596    if (TryAnnotateTypeOrScopeToken())
597      return isCXXDeclarationSpecifier();
598    // Otherwise, not a typename.
599    return TPResult::False();
600
601  case tok::coloncolon:   // ::foo::bar
602      if (NextToken().is(tok::kw_new) ||    // ::new
603          NextToken().is(tok::kw_delete))   // ::delete
604        return TPResult::False();
605
606    // Annotate typenames and C++ scope specifiers.  If we get one, just
607    // recurse to handle whatever we get.
608    if (TryAnnotateTypeOrScopeToken())
609      return isCXXDeclarationSpecifier();
610    // Otherwise, not a typename.
611    return TPResult::False();
612
613    // decl-specifier:
614    //   storage-class-specifier
615    //   type-specifier
616    //   function-specifier
617    //   'friend'
618    //   'typedef'
619    //   'constexpr'
620
621  case tok::kw_friend:
622  case tok::kw_typedef:
623  case tok::kw_constexpr:
624    // storage-class-specifier
625  case tok::kw_register:
626  case tok::kw_static:
627  case tok::kw_extern:
628  case tok::kw_mutable:
629  case tok::kw_auto:
630  case tok::kw___thread:
631    // function-specifier
632  case tok::kw_inline:
633  case tok::kw_virtual:
634  case tok::kw_explicit:
635
636    // type-specifier:
637    //   simple-type-specifier
638    //   class-specifier
639    //   enum-specifier
640    //   elaborated-type-specifier
641    //   typename-specifier
642    //   cv-qualifier
643
644    // class-specifier
645    // elaborated-type-specifier
646  case tok::kw_class:
647  case tok::kw_struct:
648  case tok::kw_union:
649    // enum-specifier
650  case tok::kw_enum:
651    // cv-qualifier
652  case tok::kw_const:
653  case tok::kw_volatile:
654
655    // GNU
656  case tok::kw_restrict:
657  case tok::kw__Complex:
658  case tok::kw___attribute:
659    return TPResult::True();
660
661    // Microsoft
662  case tok::kw___declspec:
663  case tok::kw___cdecl:
664  case tok::kw___stdcall:
665  case tok::kw___fastcall:
666  case tok::kw___w64:
667  case tok::kw___ptr64:
668  case tok::kw___forceinline:
669    return TPResult::True();
670
671    // The ambiguity resides in a simple-type-specifier/typename-specifier
672    // followed by a '('. The '(' could either be the start of:
673    //
674    //   direct-declarator:
675    //     '(' declarator ')'
676    //
677    //   direct-abstract-declarator:
678    //     '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
679    //              exception-specification[opt]
680    //     '(' abstract-declarator ')'
681    //
682    // or part of a function-style cast expression:
683    //
684    //     simple-type-specifier '(' expression-list[opt] ')'
685    //
686
687    // simple-type-specifier:
688
689  case tok::kw_char:
690  case tok::kw_wchar_t:
691  case tok::kw_char16_t:
692  case tok::kw_char32_t:
693  case tok::kw_bool:
694  case tok::kw_short:
695  case tok::kw_int:
696  case tok::kw_long:
697  case tok::kw_signed:
698  case tok::kw_unsigned:
699  case tok::kw_float:
700  case tok::kw_double:
701  case tok::kw_void:
702  case tok::annot_typename:
703    if (NextToken().is(tok::l_paren))
704      return TPResult::Ambiguous();
705
706    return TPResult::True();
707
708  // GNU typeof support.
709  case tok::kw_typeof: {
710    if (NextToken().isNot(tok::l_paren))
711      return TPResult::True();
712
713    TentativeParsingAction PA(*this);
714
715    TPResult TPR = TryParseTypeofSpecifier();
716    bool isFollowedByParen = Tok.is(tok::l_paren);
717
718    PA.Revert();
719
720    if (TPR == TPResult::Error())
721      return TPResult::Error();
722
723    if (isFollowedByParen)
724      return TPResult::Ambiguous();
725
726    return TPResult::True();
727  }
728
729  // C++0x decltype support.
730  case tok::kw_decltype:
731    return TPResult::True();
732
733  default:
734    return TPResult::False();
735  }
736}
737
738/// [GNU] typeof-specifier:
739///         'typeof' '(' expressions ')'
740///         'typeof' '(' type-name ')'
741///
742Parser::TPResult Parser::TryParseTypeofSpecifier() {
743  assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
744  ConsumeToken();
745
746  assert(Tok.is(tok::l_paren) && "Expected '('");
747  // Parse through the parens after 'typeof'.
748  ConsumeParen();
749  if (!SkipUntil(tok::r_paren))
750    return TPResult::Error();
751
752  return TPResult::Ambiguous();
753}
754
755Parser::TPResult Parser::TryParseDeclarationSpecifier() {
756  TPResult TPR = isCXXDeclarationSpecifier();
757  if (TPR != TPResult::Ambiguous())
758    return TPR;
759
760  if (Tok.is(tok::kw_typeof))
761    TryParseTypeofSpecifier();
762  else
763    ConsumeToken();
764
765  assert(Tok.is(tok::l_paren) && "Expected '('!");
766  return TPResult::Ambiguous();
767}
768
769/// isCXXFunctionDeclarator - Disambiguates between a function declarator or
770/// a constructor-style initializer, when parsing declaration statements.
771/// Returns true for function declarator and false for constructor-style
772/// initializer.
773/// If during the disambiguation process a parsing error is encountered,
774/// the function returns true to let the declaration parsing code handle it.
775///
776/// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
777///         exception-specification[opt]
778///
779bool Parser::isCXXFunctionDeclarator(bool warnIfAmbiguous) {
780
781  // C++ 8.2p1:
782  // The ambiguity arising from the similarity between a function-style cast and
783  // a declaration mentioned in 6.8 can also occur in the context of a
784  // declaration. In that context, the choice is between a function declaration
785  // with a redundant set of parentheses around a parameter name and an object
786  // declaration with a function-style cast as the initializer. Just as for the
787  // ambiguities mentioned in 6.8, the resolution is to consider any construct
788  // that could possibly be a declaration a declaration.
789
790  TentativeParsingAction PA(*this);
791
792  ConsumeParen();
793  TPResult TPR = TryParseParameterDeclarationClause();
794  if (TPR == TPResult::Ambiguous() && Tok.isNot(tok::r_paren))
795    TPR = TPResult::False();
796
797  SourceLocation TPLoc = Tok.getLocation();
798  PA.Revert();
799
800  // In case of an error, let the declaration parsing code handle it.
801  if (TPR == TPResult::Error())
802    return true;
803
804  if (TPR == TPResult::Ambiguous()) {
805    // Function declarator has precedence over constructor-style initializer.
806    // Emit a warning just in case the author intended a variable definition.
807    if (warnIfAmbiguous)
808      Diag(Tok, diag::warn_parens_disambiguated_as_function_decl)
809        << SourceRange(Tok.getLocation(), TPLoc);
810    return true;
811  }
812
813  return TPR == TPResult::True();
814}
815
816/// parameter-declaration-clause:
817///   parameter-declaration-list[opt] '...'[opt]
818///   parameter-declaration-list ',' '...'
819///
820/// parameter-declaration-list:
821///   parameter-declaration
822///   parameter-declaration-list ',' parameter-declaration
823///
824/// parameter-declaration:
825///   decl-specifier-seq declarator
826///   decl-specifier-seq declarator '=' assignment-expression
827///   decl-specifier-seq abstract-declarator[opt]
828///   decl-specifier-seq abstract-declarator[opt] '=' assignment-expression
829///
830Parser::TPResult Parser::TryParseParameterDeclarationClause() {
831
832  if (Tok.is(tok::r_paren))
833    return TPResult::True();
834
835  //   parameter-declaration-list[opt] '...'[opt]
836  //   parameter-declaration-list ',' '...'
837  //
838  // parameter-declaration-list:
839  //   parameter-declaration
840  //   parameter-declaration-list ',' parameter-declaration
841  //
842  while (1) {
843    // '...'[opt]
844    if (Tok.is(tok::ellipsis)) {
845      ConsumeToken();
846      return TPResult::True(); // '...' is a sign of a function declarator.
847    }
848
849    // decl-specifier-seq
850    TPResult TPR = TryParseDeclarationSpecifier();
851    if (TPR != TPResult::Ambiguous())
852      return TPR;
853
854    // declarator
855    // abstract-declarator[opt]
856    TPR = TryParseDeclarator(true/*mayBeAbstract*/);
857    if (TPR != TPResult::Ambiguous())
858      return TPR;
859
860    if (Tok.is(tok::equal)) {
861      // '=' assignment-expression
862      // Parse through assignment-expression.
863      tok::TokenKind StopToks[3] ={ tok::comma, tok::ellipsis, tok::r_paren };
864      if (!SkipUntil(StopToks, 3, true/*StopAtSemi*/, true/*DontConsume*/))
865        return TPResult::Error();
866    }
867
868    if (Tok.is(tok::ellipsis)) {
869      ConsumeToken();
870      return TPResult::True(); // '...' is a sign of a function declarator.
871    }
872
873    if (Tok.isNot(tok::comma))
874      break;
875    ConsumeToken(); // the comma.
876  }
877
878  return TPResult::Ambiguous();
879}
880
881/// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
882/// parsing as a function declarator.
883/// If TryParseFunctionDeclarator fully parsed the function declarator, it will
884/// return TPResult::Ambiguous(), otherwise it will return either False() or
885/// Error().
886///
887/// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
888///         exception-specification[opt]
889///
890/// exception-specification:
891///   'throw' '(' type-id-list[opt] ')'
892///
893Parser::TPResult Parser::TryParseFunctionDeclarator() {
894
895  // The '(' is already parsed.
896
897  TPResult TPR = TryParseParameterDeclarationClause();
898  if (TPR == TPResult::Ambiguous() && Tok.isNot(tok::r_paren))
899    TPR = TPResult::False();
900
901  if (TPR == TPResult::False() || TPR == TPResult::Error())
902    return TPR;
903
904  // Parse through the parens.
905  if (!SkipUntil(tok::r_paren))
906    return TPResult::Error();
907
908  // cv-qualifier-seq
909  while (Tok.is(tok::kw_const)    ||
910         Tok.is(tok::kw_volatile) ||
911         Tok.is(tok::kw_restrict)   )
912    ConsumeToken();
913
914  // exception-specification
915  if (Tok.is(tok::kw_throw)) {
916    ConsumeToken();
917    if (Tok.isNot(tok::l_paren))
918      return TPResult::Error();
919
920    // Parse through the parens after 'throw'.
921    ConsumeParen();
922    if (!SkipUntil(tok::r_paren))
923      return TPResult::Error();
924  }
925
926  return TPResult::Ambiguous();
927}
928
929/// '[' constant-expression[opt] ']'
930///
931Parser::TPResult Parser::TryParseBracketDeclarator() {
932  ConsumeBracket();
933  if (!SkipUntil(tok::r_square))
934    return TPResult::Error();
935
936  return TPResult::Ambiguous();
937}
938