]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/llvm/tools/clang/lib/Parse/ParseTentative.cpp
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / llvm / tools / clang / lib / Parse / ParseTentative.cpp
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"
17 #include "clang/Sema/ParsedTemplate.h"
18 using namespace clang;
19
20 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
21 /// between a declaration or an expression statement, when parsing function
22 /// bodies. Returns true for declaration, false for expression.
23 ///
24 ///         declaration-statement:
25 ///           block-declaration
26 ///
27 ///         block-declaration:
28 ///           simple-declaration
29 ///           asm-definition
30 ///           namespace-alias-definition
31 ///           using-declaration
32 ///           using-directive
33 /// [C++0x]   static_assert-declaration
34 ///
35 ///         asm-definition:
36 ///           'asm' '(' string-literal ')' ';'
37 ///
38 ///         namespace-alias-definition:
39 ///           'namespace' identifier = qualified-namespace-specifier ';'
40 ///
41 ///         using-declaration:
42 ///           'using' typename[opt] '::'[opt] nested-name-specifier
43 ///                 unqualified-id ';'
44 ///           'using' '::' unqualified-id ;
45 ///
46 ///         using-directive:
47 ///           'using' 'namespace' '::'[opt] nested-name-specifier[opt]
48 ///                 namespace-name ';'
49 ///
50 bool Parser::isCXXDeclarationStatement() {
51   switch (Tok.getKind()) {
52     // asm-definition
53   case tok::kw_asm:
54     // namespace-alias-definition
55   case tok::kw_namespace:
56     // using-declaration
57     // using-directive
58   case tok::kw_using:
59     // static_assert-declaration
60   case tok::kw_static_assert:
61   case tok::kw__Static_assert:
62     return true;
63     // simple-declaration
64   default:
65     return isCXXSimpleDeclaration();
66   }
67 }
68
69 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
70 /// between a simple-declaration or an expression-statement.
71 /// If during the disambiguation process a parsing error is encountered,
72 /// the function returns true to let the declaration parsing code handle it.
73 /// Returns false if the statement is disambiguated as expression.
74 ///
75 /// simple-declaration:
76 ///   decl-specifier-seq init-declarator-list[opt] ';'
77 ///
78 bool Parser::isCXXSimpleDeclaration() {
79   // C++ 6.8p1:
80   // There is an ambiguity in the grammar involving expression-statements and
81   // declarations: An expression-statement with a function-style explicit type
82   // conversion (5.2.3) as its leftmost subexpression can be indistinguishable
83   // from a declaration where the first declarator starts with a '('. In those
84   // cases the statement is a declaration. [Note: To disambiguate, the whole
85   // statement might have to be examined to determine if it is an
86   // expression-statement or a declaration].
87
88   // C++ 6.8p3:
89   // The disambiguation is purely syntactic; that is, the meaning of the names
90   // occurring in such a statement, beyond whether they are type-names or not,
91   // is not generally used in or changed by the disambiguation. Class
92   // templates are instantiated as necessary to determine if a qualified name
93   // is a type-name. Disambiguation precedes parsing, and a statement
94   // disambiguated as a declaration may be an ill-formed declaration.
95
96   // We don't have to parse all of the decl-specifier-seq part. There's only
97   // an ambiguity if the first decl-specifier is
98   // simple-type-specifier/typename-specifier followed by a '(', which may
99   // indicate a function-style cast expression.
100   // isCXXDeclarationSpecifier will return TPResult::Ambiguous() only in such
101   // a case.
102
103   TPResult TPR = isCXXDeclarationSpecifier();
104   if (TPR != TPResult::Ambiguous())
105     return TPR != TPResult::False(); // Returns true for TPResult::True() or
106                                      // TPResult::Error().
107
108   // FIXME: Add statistics about the number of ambiguous statements encountered
109   // and how they were resolved (number of declarations+number of expressions).
110
111   // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
112   // We need tentative parsing...
113
114   TentativeParsingAction PA(*this);
115   TPR = TryParseSimpleDeclaration();
116   PA.Revert();
117
118   // In case of an error, let the declaration parsing code handle it.
119   if (TPR == TPResult::Error())
120     return true;
121
122   // Declarations take precedence over expressions.
123   if (TPR == TPResult::Ambiguous())
124     TPR = TPResult::True();
125
126   assert(TPR == TPResult::True() || TPR == TPResult::False());
127   return TPR == TPResult::True();
128 }
129
130 /// simple-declaration:
131 ///   decl-specifier-seq init-declarator-list[opt] ';'
132 ///
133 Parser::TPResult Parser::TryParseSimpleDeclaration() {
134   // We know that we have a simple-type-specifier/typename-specifier followed
135   // by a '('.
136   assert(isCXXDeclarationSpecifier() == TPResult::Ambiguous());
137
138   if (Tok.is(tok::kw_typeof))
139     TryParseTypeofSpecifier();
140   else {
141     ConsumeToken();
142     
143     if (getLang().ObjC1 && Tok.is(tok::less))
144       TryParseProtocolQualifiers();
145   }
146   
147   assert(Tok.is(tok::l_paren) && "Expected '('");
148
149   TPResult TPR = TryParseInitDeclaratorList();
150   if (TPR != TPResult::Ambiguous())
151     return TPR;
152
153   if (Tok.isNot(tok::semi))
154     return TPResult::False();
155
156   return TPResult::Ambiguous();
157 }
158
159 ///       init-declarator-list:
160 ///         init-declarator
161 ///         init-declarator-list ',' init-declarator
162 ///
163 ///       init-declarator:
164 ///         declarator initializer[opt]
165 /// [GNU]   declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
166 ///
167 /// initializer:
168 ///   '=' initializer-clause
169 ///   '(' expression-list ')'
170 ///
171 /// initializer-clause:
172 ///   assignment-expression
173 ///   '{' initializer-list ','[opt] '}'
174 ///   '{' '}'
175 ///
176 Parser::TPResult Parser::TryParseInitDeclaratorList() {
177   while (1) {
178     // declarator
179     TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
180     if (TPR != TPResult::Ambiguous())
181       return TPR;
182
183     // [GNU] simple-asm-expr[opt] attributes[opt]
184     if (Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
185       return TPResult::True();
186
187     // initializer[opt]
188     if (Tok.is(tok::l_paren)) {
189       // Parse through the parens.
190       ConsumeParen();
191       if (!SkipUntil(tok::r_paren))
192         return TPResult::Error();
193     } else if (Tok.is(tok::equal) || isTokIdentifier_in()) {
194       // MSVC and g++ won't examine the rest of declarators if '=' is 
195       // encountered; they just conclude that we have a declaration.
196       // EDG parses the initializer completely, which is the proper behavior
197       // for this case.
198       //
199       // At present, Clang follows MSVC and g++, since the parser does not have
200       // the ability to parse an expression fully without recording the
201       // results of that parse.
202       // Also allow 'in' after on objective-c declaration as in: 
203       // for (int (^b)(void) in array). Ideally this should be done in the 
204       // context of parsing for-init-statement of a foreach statement only. But,
205       // in any other context 'in' is invalid after a declaration and parser
206       // issues the error regardless of outcome of this decision.
207       // FIXME. Change if above assumption does not hold.
208       return TPResult::True();
209     }
210
211     if (Tok.isNot(tok::comma))
212       break;
213     ConsumeToken(); // the comma.
214   }
215
216   return TPResult::Ambiguous();
217 }
218
219 /// isCXXConditionDeclaration - Disambiguates between a declaration or an
220 /// expression for a condition of a if/switch/while/for statement.
221 /// If during the disambiguation process a parsing error is encountered,
222 /// the function returns true to let the declaration parsing code handle it.
223 ///
224 ///       condition:
225 ///         expression
226 ///         type-specifier-seq declarator '=' assignment-expression
227 /// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
228 ///             '=' assignment-expression
229 ///
230 bool Parser::isCXXConditionDeclaration() {
231   TPResult TPR = isCXXDeclarationSpecifier();
232   if (TPR != TPResult::Ambiguous())
233     return TPR != TPResult::False(); // Returns true for TPResult::True() or
234                                      // TPResult::Error().
235
236   // FIXME: Add statistics about the number of ambiguous statements encountered
237   // and how they were resolved (number of declarations+number of expressions).
238
239   // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
240   // We need tentative parsing...
241
242   TentativeParsingAction PA(*this);
243
244   // type-specifier-seq
245   if (Tok.is(tok::kw_typeof))
246     TryParseTypeofSpecifier();
247   else {
248     ConsumeToken();
249     
250     if (getLang().ObjC1 && Tok.is(tok::less))
251       TryParseProtocolQualifiers();
252   }
253   assert(Tok.is(tok::l_paren) && "Expected '('");
254
255   // declarator
256   TPR = TryParseDeclarator(false/*mayBeAbstract*/);
257
258   // In case of an error, let the declaration parsing code handle it.
259   if (TPR == TPResult::Error())
260     TPR = TPResult::True();
261
262   if (TPR == TPResult::Ambiguous()) {
263     // '='
264     // [GNU] simple-asm-expr[opt] attributes[opt]
265     if (Tok.is(tok::equal)  ||
266         Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
267       TPR = TPResult::True();
268     else
269       TPR = TPResult::False();
270   }
271
272   PA.Revert();
273
274   assert(TPR == TPResult::True() || TPR == TPResult::False());
275   return TPR == TPResult::True();
276 }
277
278   /// \brief Determine whether the next set of tokens contains a type-id.
279   ///
280   /// The context parameter states what context we're parsing right
281   /// now, which affects how this routine copes with the token
282   /// following the type-id. If the context is TypeIdInParens, we have
283   /// already parsed the '(' and we will cease lookahead when we hit
284   /// the corresponding ')'. If the context is
285   /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
286   /// before this template argument, and will cease lookahead when we
287   /// hit a '>', '>>' (in C++0x), or ','. Returns true for a type-id
288   /// and false for an expression.  If during the disambiguation
289   /// process a parsing error is encountered, the function returns
290   /// true to let the declaration parsing code handle it.
291   ///
292   /// type-id:
293   ///   type-specifier-seq abstract-declarator[opt]
294   ///
295 bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
296
297   isAmbiguous = false;
298
299   // C++ 8.2p2:
300   // The ambiguity arising from the similarity between a function-style cast and
301   // a type-id can occur in different contexts. The ambiguity appears as a
302   // choice between a function-style cast expression and a declaration of a
303   // type. The resolution is that any construct that could possibly be a type-id
304   // in its syntactic context shall be considered a type-id.
305
306   TPResult TPR = isCXXDeclarationSpecifier();
307   if (TPR != TPResult::Ambiguous())
308     return TPR != TPResult::False(); // Returns true for TPResult::True() or
309                                      // TPResult::Error().
310
311   // FIXME: Add statistics about the number of ambiguous statements encountered
312   // and how they were resolved (number of declarations+number of expressions).
313
314   // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
315   // We need tentative parsing...
316
317   TentativeParsingAction PA(*this);
318
319   // type-specifier-seq
320   if (Tok.is(tok::kw_typeof))
321     TryParseTypeofSpecifier();
322   else {
323     ConsumeToken();
324     
325     if (getLang().ObjC1 && Tok.is(tok::less))
326       TryParseProtocolQualifiers();
327   }
328   
329   assert(Tok.is(tok::l_paren) && "Expected '('");
330
331   // declarator
332   TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
333
334   // In case of an error, let the declaration parsing code handle it.
335   if (TPR == TPResult::Error())
336     TPR = TPResult::True();
337
338   if (TPR == TPResult::Ambiguous()) {
339     // We are supposed to be inside parens, so if after the abstract declarator
340     // we encounter a ')' this is a type-id, otherwise it's an expression.
341     if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
342       TPR = TPResult::True();
343       isAmbiguous = true;
344
345     // We are supposed to be inside a template argument, so if after
346     // the abstract declarator we encounter a '>', '>>' (in C++0x), or
347     // ',', this is a type-id. Otherwise, it's an expression.
348     } else if (Context == TypeIdAsTemplateArgument &&
349                (Tok.is(tok::greater) || Tok.is(tok::comma) ||
350                 (getLang().CPlusPlus0x && Tok.is(tok::greatergreater)))) {
351       TPR = TPResult::True();
352       isAmbiguous = true;
353
354     } else
355       TPR = TPResult::False();
356   }
357
358   PA.Revert();
359
360   assert(TPR == TPResult::True() || TPR == TPResult::False());
361   return TPR == TPResult::True();
362 }
363
364 /// isCXX0XAttributeSpecifier - returns true if this is a C++0x
365 /// attribute-specifier. By default, unless in Obj-C++, only a cursory check is
366 /// performed that will simply return true if a [[ is seen. Currently C++ has no
367 /// syntactical ambiguities from this check, but it may inhibit error recovery.
368 /// If CheckClosing is true, a check is made for closing ]] brackets.
369 ///
370 /// If given, After is set to the token after the attribute-specifier so that
371 /// appropriate parsing decisions can be made; it is left untouched if false is
372 /// returned.
373 ///
374 /// FIXME: If an error is in the closing ]] brackets, the program assumes
375 /// the absence of an attribute-specifier, which can cause very yucky errors
376 /// to occur.
377 ///
378 /// [C++0x] attribute-specifier:
379 ///         '[' '[' attribute-list ']' ']'
380 ///         alignment-specifier
381 ///
382 /// [C++0x] attribute-list:
383 ///         attribute[opt]
384 ///         attribute-list ',' attribute[opt]
385 ///
386 /// [C++0x] attribute:
387 ///         attribute-token attribute-argument-clause[opt]
388 ///
389 /// [C++0x] attribute-token:
390 ///         identifier
391 ///         attribute-scoped-token
392 ///
393 /// [C++0x] attribute-scoped-token:
394 ///         attribute-namespace '::' identifier
395 ///
396 /// [C++0x] attribute-namespace:
397 ///         identifier
398 ///
399 /// [C++0x] attribute-argument-clause:
400 ///         '(' balanced-token-seq ')'
401 ///
402 /// [C++0x] balanced-token-seq:
403 ///         balanced-token
404 ///         balanced-token-seq balanced-token
405 ///
406 /// [C++0x] balanced-token:
407 ///         '(' balanced-token-seq ')'
408 ///         '[' balanced-token-seq ']'
409 ///         '{' balanced-token-seq '}'
410 ///         any token but '(', ')', '[', ']', '{', or '}'
411 bool Parser::isCXX0XAttributeSpecifier (bool CheckClosing,
412                                         tok::TokenKind *After) {
413   if (Tok.is(tok::kw_alignas))
414     return true;
415
416   if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
417     return false;
418   
419   // No tentative parsing if we don't need to look for ]]
420   if (!CheckClosing && !getLang().ObjC1)
421     return true;
422   
423   struct TentativeReverter {
424     TentativeParsingAction PA;
425
426     TentativeReverter (Parser& P)
427       : PA(P)
428     {}
429     ~TentativeReverter () {
430       PA.Revert();
431     }
432   } R(*this);
433
434   // Opening brackets were checked for above.
435   ConsumeBracket();
436   ConsumeBracket();
437
438   // SkipUntil will handle balanced tokens, which are guaranteed in attributes.
439   SkipUntil(tok::r_square, false);
440
441   if (Tok.isNot(tok::r_square))
442     return false;
443   ConsumeBracket();
444
445   if (After)
446     *After = Tok.getKind();
447
448   return true;
449 }
450
451 ///         declarator:
452 ///           direct-declarator
453 ///           ptr-operator declarator
454 ///
455 ///         direct-declarator:
456 ///           declarator-id
457 ///           direct-declarator '(' parameter-declaration-clause ')'
458 ///                 cv-qualifier-seq[opt] exception-specification[opt]
459 ///           direct-declarator '[' constant-expression[opt] ']'
460 ///           '(' declarator ')'
461 /// [GNU]     '(' attributes declarator ')'
462 ///
463 ///         abstract-declarator:
464 ///           ptr-operator abstract-declarator[opt]
465 ///           direct-abstract-declarator
466 ///           ...
467 ///
468 ///         direct-abstract-declarator:
469 ///           direct-abstract-declarator[opt]
470 ///           '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
471 ///                 exception-specification[opt]
472 ///           direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
473 ///           '(' abstract-declarator ')'
474 ///
475 ///         ptr-operator:
476 ///           '*' cv-qualifier-seq[opt]
477 ///           '&'
478 /// [C++0x]   '&&'                                                        [TODO]
479 ///           '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
480 ///
481 ///         cv-qualifier-seq:
482 ///           cv-qualifier cv-qualifier-seq[opt]
483 ///
484 ///         cv-qualifier:
485 ///           'const'
486 ///           'volatile'
487 ///
488 ///         declarator-id:
489 ///           '...'[opt] id-expression
490 ///
491 ///         id-expression:
492 ///           unqualified-id
493 ///           qualified-id                                                [TODO]
494 ///
495 ///         unqualified-id:
496 ///           identifier
497 ///           operator-function-id                                        [TODO]
498 ///           conversion-function-id                                      [TODO]
499 ///           '~' class-name                                              [TODO]
500 ///           template-id                                                 [TODO]
501 ///
502 Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
503                                             bool mayHaveIdentifier) {
504   // declarator:
505   //   direct-declarator
506   //   ptr-operator declarator
507
508   while (1) {
509     if (Tok.is(tok::coloncolon) || Tok.is(tok::identifier))
510       if (TryAnnotateCXXScopeToken(true))
511         return TPResult::Error();
512
513     if (Tok.is(tok::star) || Tok.is(tok::amp) || Tok.is(tok::caret) ||
514         Tok.is(tok::ampamp) ||
515         (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
516       // ptr-operator
517       ConsumeToken();
518       while (Tok.is(tok::kw_const)    ||
519              Tok.is(tok::kw_volatile) ||
520              Tok.is(tok::kw_restrict))
521         ConsumeToken();
522     } else {
523       break;
524     }
525   }
526
527   // direct-declarator:
528   // direct-abstract-declarator:
529   if (Tok.is(tok::ellipsis))
530     ConsumeToken();
531   
532   if ((Tok.is(tok::identifier) ||
533        (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) &&
534       mayHaveIdentifier) {
535     // declarator-id
536     if (Tok.is(tok::annot_cxxscope))
537       ConsumeToken();
538     ConsumeToken();
539   } else if (Tok.is(tok::l_paren)) {
540     ConsumeParen();
541     if (mayBeAbstract &&
542         (Tok.is(tok::r_paren) ||       // 'int()' is a function.
543          Tok.is(tok::ellipsis) ||      // 'int(...)' is a function.
544          isDeclarationSpecifier())) {   // 'int(int)' is a function.
545       // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
546       //        exception-specification[opt]
547       TPResult TPR = TryParseFunctionDeclarator();
548       if (TPR != TPResult::Ambiguous())
549         return TPR;
550     } else {
551       // '(' declarator ')'
552       // '(' attributes declarator ')'
553       // '(' abstract-declarator ')'
554       if (Tok.is(tok::kw___attribute) ||
555           Tok.is(tok::kw___declspec) ||
556           Tok.is(tok::kw___cdecl) ||
557           Tok.is(tok::kw___stdcall) ||
558           Tok.is(tok::kw___fastcall) ||
559           Tok.is(tok::kw___thiscall) ||
560           Tok.is(tok::kw___unaligned))
561         return TPResult::True(); // attributes indicate declaration
562       TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
563       if (TPR != TPResult::Ambiguous())
564         return TPR;
565       if (Tok.isNot(tok::r_paren))
566         return TPResult::False();
567       ConsumeParen();
568     }
569   } else if (!mayBeAbstract) {
570     return TPResult::False();
571   }
572
573   while (1) {
574     TPResult TPR(TPResult::Ambiguous());
575
576     // abstract-declarator: ...
577     if (Tok.is(tok::ellipsis))
578       ConsumeToken();
579
580     if (Tok.is(tok::l_paren)) {
581       // Check whether we have a function declarator or a possible ctor-style
582       // initializer that follows the declarator. Note that ctor-style
583       // initializers are not possible in contexts where abstract declarators
584       // are allowed.
585       if (!mayBeAbstract && !isCXXFunctionDeclarator(false/*warnIfAmbiguous*/))
586         break;
587
588       // direct-declarator '(' parameter-declaration-clause ')'
589       //        cv-qualifier-seq[opt] exception-specification[opt]
590       ConsumeParen();
591       TPR = TryParseFunctionDeclarator();
592     } else if (Tok.is(tok::l_square)) {
593       // direct-declarator '[' constant-expression[opt] ']'
594       // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
595       TPR = TryParseBracketDeclarator();
596     } else {
597       break;
598     }
599
600     if (TPR != TPResult::Ambiguous())
601       return TPR;
602   }
603
604   return TPResult::Ambiguous();
605 }
606
607 Parser::TPResult 
608 Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) {
609   switch (Kind) {
610   // Obviously starts an expression.
611   case tok::numeric_constant:
612   case tok::char_constant:
613   case tok::wide_char_constant:
614   case tok::utf16_char_constant:
615   case tok::utf32_char_constant:
616   case tok::string_literal:
617   case tok::wide_string_literal:
618   case tok::utf8_string_literal:
619   case tok::utf16_string_literal:
620   case tok::utf32_string_literal:
621   case tok::l_square:
622   case tok::l_paren:
623   case tok::amp:
624   case tok::ampamp:
625   case tok::star:
626   case tok::plus:
627   case tok::plusplus:
628   case tok::minus:
629   case tok::minusminus:
630   case tok::tilde:
631   case tok::exclaim:
632   case tok::kw_sizeof:
633   case tok::kw___func__:
634   case tok::kw_const_cast:
635   case tok::kw_delete:
636   case tok::kw_dynamic_cast:
637   case tok::kw_false:
638   case tok::kw_new:
639   case tok::kw_operator:
640   case tok::kw_reinterpret_cast:
641   case tok::kw_static_cast:
642   case tok::kw_this:
643   case tok::kw_throw:
644   case tok::kw_true:
645   case tok::kw_typeid:
646   case tok::kw_alignof:
647   case tok::kw_noexcept:
648   case tok::kw_nullptr:
649   case tok::kw___null:
650   case tok::kw___alignof:
651   case tok::kw___builtin_choose_expr:
652   case tok::kw___builtin_offsetof:
653   case tok::kw___builtin_types_compatible_p:
654   case tok::kw___builtin_va_arg:
655   case tok::kw___imag:
656   case tok::kw___real:
657   case tok::kw___FUNCTION__:
658   case tok::kw___PRETTY_FUNCTION__:
659   case tok::kw___has_nothrow_assign:
660   case tok::kw___has_nothrow_copy:
661   case tok::kw___has_nothrow_constructor:
662   case tok::kw___has_trivial_assign:
663   case tok::kw___has_trivial_copy:
664   case tok::kw___has_trivial_constructor:
665   case tok::kw___has_trivial_destructor:
666   case tok::kw___has_virtual_destructor:
667   case tok::kw___is_abstract:
668   case tok::kw___is_base_of:
669   case tok::kw___is_class:
670   case tok::kw___is_convertible_to:
671   case tok::kw___is_empty:
672   case tok::kw___is_enum:
673   case tok::kw___is_literal:
674   case tok::kw___is_literal_type:
675   case tok::kw___is_pod:
676   case tok::kw___is_polymorphic:
677   case tok::kw___is_trivial:
678   case tok::kw___is_trivially_copyable:
679   case tok::kw___is_union:
680   case tok::kw___uuidof:
681     return TPResult::True();
682       
683   // Obviously starts a type-specifier-seq:
684   case tok::kw_char:
685   case tok::kw_const:
686   case tok::kw_double:
687   case tok::kw_enum:
688   case tok::kw_half:
689   case tok::kw_float:
690   case tok::kw_int:
691   case tok::kw_long:
692   case tok::kw___int64:
693   case tok::kw_restrict:
694   case tok::kw_short:
695   case tok::kw_signed:
696   case tok::kw_struct:
697   case tok::kw_union:
698   case tok::kw_unsigned:
699   case tok::kw_void:
700   case tok::kw_volatile:
701   case tok::kw__Bool:
702   case tok::kw__Complex:
703   case tok::kw_class:
704   case tok::kw_typename:
705   case tok::kw_wchar_t:
706   case tok::kw_char16_t:
707   case tok::kw_char32_t:
708   case tok::kw_decltype:
709   case tok::kw___underlying_type:
710   case tok::kw_thread_local:
711   case tok::kw__Decimal32:
712   case tok::kw__Decimal64:
713   case tok::kw__Decimal128:
714   case tok::kw___thread:
715   case tok::kw_typeof:
716   case tok::kw___cdecl:
717   case tok::kw___stdcall:
718   case tok::kw___fastcall:
719   case tok::kw___thiscall:
720   case tok::kw___unaligned:
721   case tok::kw___vector:
722   case tok::kw___pixel:
723   case tok::kw__Atomic:
724     return TPResult::False();
725
726   default:
727     break;
728   }
729   
730   return TPResult::Ambiguous();
731 }
732
733 /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a declaration
734 /// specifier, TPResult::False() if it is not, TPResult::Ambiguous() if it could
735 /// be either a decl-specifier or a function-style cast, and TPResult::Error()
736 /// if a parsing error was found and reported.
737 ///
738 ///         decl-specifier:
739 ///           storage-class-specifier
740 ///           type-specifier
741 ///           function-specifier
742 ///           'friend'
743 ///           'typedef'
744 /// [C++0x]   'constexpr'
745 /// [GNU]     attributes declaration-specifiers[opt]
746 ///
747 ///         storage-class-specifier:
748 ///           'register'
749 ///           'static'
750 ///           'extern'
751 ///           'mutable'
752 ///           'auto'
753 /// [GNU]     '__thread'
754 ///
755 ///         function-specifier:
756 ///           'inline'
757 ///           'virtual'
758 ///           'explicit'
759 ///
760 ///         typedef-name:
761 ///           identifier
762 ///
763 ///         type-specifier:
764 ///           simple-type-specifier
765 ///           class-specifier
766 ///           enum-specifier
767 ///           elaborated-type-specifier
768 ///           typename-specifier
769 ///           cv-qualifier
770 ///
771 ///         simple-type-specifier:
772 ///           '::'[opt] nested-name-specifier[opt] type-name
773 ///           '::'[opt] nested-name-specifier 'template'
774 ///                 simple-template-id                              [TODO]
775 ///           'char'
776 ///           'wchar_t'
777 ///           'bool'
778 ///           'short'
779 ///           'int'
780 ///           'long'
781 ///           'signed'
782 ///           'unsigned'
783 ///           'float'
784 ///           'double'
785 ///           'void'
786 /// [GNU]     typeof-specifier
787 /// [GNU]     '_Complex'
788 /// [C++0x]   'auto'                                                [TODO]
789 /// [C++0x]   'decltype' ( expression )
790 ///
791 ///         type-name:
792 ///           class-name
793 ///           enum-name
794 ///           typedef-name
795 ///
796 ///         elaborated-type-specifier:
797 ///           class-key '::'[opt] nested-name-specifier[opt] identifier
798 ///           class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
799 ///               simple-template-id
800 ///           'enum' '::'[opt] nested-name-specifier[opt] identifier
801 ///
802 ///         enum-name:
803 ///           identifier
804 ///
805 ///         enum-specifier:
806 ///           'enum' identifier[opt] '{' enumerator-list[opt] '}'
807 ///           'enum' identifier[opt] '{' enumerator-list ',' '}'
808 ///
809 ///         class-specifier:
810 ///           class-head '{' member-specification[opt] '}'
811 ///
812 ///         class-head:
813 ///           class-key identifier[opt] base-clause[opt]
814 ///           class-key nested-name-specifier identifier base-clause[opt]
815 ///           class-key nested-name-specifier[opt] simple-template-id
816 ///               base-clause[opt]
817 ///
818 ///         class-key:
819 ///           'class'
820 ///           'struct'
821 ///           'union'
822 ///
823 ///         cv-qualifier:
824 ///           'const'
825 ///           'volatile'
826 /// [GNU]     restrict
827 ///
828 Parser::TPResult Parser::isCXXDeclarationSpecifier() {
829   switch (Tok.getKind()) {
830   case tok::identifier:   // foo::bar
831     // Check for need to substitute AltiVec __vector keyword
832     // for "vector" identifier.
833     if (TryAltiVecVectorToken())
834       return TPResult::True();
835     // Fall through.
836   case tok::kw_typename:  // typename T::type
837     // Annotate typenames and C++ scope specifiers.  If we get one, just
838     // recurse to handle whatever we get.
839     if (TryAnnotateTypeOrScopeToken())
840       return TPResult::Error();
841     if (Tok.is(tok::identifier))
842       return TPResult::False();
843     return isCXXDeclarationSpecifier();
844
845   case tok::coloncolon: {    // ::foo::bar
846     const Token &Next = NextToken();
847     if (Next.is(tok::kw_new) ||    // ::new
848         Next.is(tok::kw_delete))   // ::delete
849       return TPResult::False();
850
851     // Annotate typenames and C++ scope specifiers.  If we get one, just
852     // recurse to handle whatever we get.
853     if (TryAnnotateTypeOrScopeToken())
854       return TPResult::Error();
855     return isCXXDeclarationSpecifier();
856   }
857       
858     // decl-specifier:
859     //   storage-class-specifier
860     //   type-specifier
861     //   function-specifier
862     //   'friend'
863     //   'typedef'
864     //   'constexpr'
865   case tok::kw_friend:
866   case tok::kw_typedef:
867   case tok::kw_constexpr:
868     // storage-class-specifier
869   case tok::kw_register:
870   case tok::kw_static:
871   case tok::kw_extern:
872   case tok::kw_mutable:
873   case tok::kw_auto:
874   case tok::kw___thread:
875     // function-specifier
876   case tok::kw_inline:
877   case tok::kw_virtual:
878   case tok::kw_explicit:
879
880     // Modules
881   case tok::kw___module_private__:
882       
883     // type-specifier:
884     //   simple-type-specifier
885     //   class-specifier
886     //   enum-specifier
887     //   elaborated-type-specifier
888     //   typename-specifier
889     //   cv-qualifier
890
891     // class-specifier
892     // elaborated-type-specifier
893   case tok::kw_class:
894   case tok::kw_struct:
895   case tok::kw_union:
896     // enum-specifier
897   case tok::kw_enum:
898     // cv-qualifier
899   case tok::kw_const:
900   case tok::kw_volatile:
901
902     // GNU
903   case tok::kw_restrict:
904   case tok::kw__Complex:
905   case tok::kw___attribute:
906     return TPResult::True();
907
908     // Microsoft
909   case tok::kw___declspec:
910   case tok::kw___cdecl:
911   case tok::kw___stdcall:
912   case tok::kw___fastcall:
913   case tok::kw___thiscall:
914   case tok::kw___w64:
915   case tok::kw___ptr64:
916   case tok::kw___ptr32:
917   case tok::kw___forceinline:
918   case tok::kw___unaligned:
919     return TPResult::True();
920
921     // Borland
922   case tok::kw___pascal:
923     return TPResult::True();
924   
925     // AltiVec
926   case tok::kw___vector:
927     return TPResult::True();
928
929   case tok::annot_template_id: {
930     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
931     if (TemplateId->Kind != TNK_Type_template)
932       return TPResult::False();
933     CXXScopeSpec SS;
934     AnnotateTemplateIdTokenAsType();
935     assert(Tok.is(tok::annot_typename));
936     goto case_typename;
937   }
938
939   case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
940     // We've already annotated a scope; try to annotate a type.
941     if (TryAnnotateTypeOrScopeToken())
942       return TPResult::Error();
943     if (!Tok.is(tok::annot_typename))
944       return TPResult::False();
945     // If that succeeded, fallthrough into the generic simple-type-id case.
946
947     // The ambiguity resides in a simple-type-specifier/typename-specifier
948     // followed by a '('. The '(' could either be the start of:
949     //
950     //   direct-declarator:
951     //     '(' declarator ')'
952     //
953     //   direct-abstract-declarator:
954     //     '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
955     //              exception-specification[opt]
956     //     '(' abstract-declarator ')'
957     //
958     // or part of a function-style cast expression:
959     //
960     //     simple-type-specifier '(' expression-list[opt] ')'
961     //
962
963     // simple-type-specifier:
964
965   case tok::annot_typename:
966   case_typename:
967     // In Objective-C, we might have a protocol-qualified type.
968     if (getLang().ObjC1 && NextToken().is(tok::less)) {
969       // Tentatively parse the 
970       TentativeParsingAction PA(*this);
971       ConsumeToken(); // The type token
972       
973       TPResult TPR = TryParseProtocolQualifiers();
974       bool isFollowedByParen = Tok.is(tok::l_paren);
975       
976       PA.Revert();
977       
978       if (TPR == TPResult::Error())
979         return TPResult::Error();
980       
981       if (isFollowedByParen)
982         return TPResult::Ambiguous();
983       
984       return TPResult::True();
985     }
986       
987   case tok::kw_char:
988   case tok::kw_wchar_t:
989   case tok::kw_char16_t:
990   case tok::kw_char32_t:
991   case tok::kw_bool:
992   case tok::kw_short:
993   case tok::kw_int:
994   case tok::kw_long:
995   case tok::kw___int64:
996   case tok::kw_signed:
997   case tok::kw_unsigned:
998   case tok::kw_half:
999   case tok::kw_float:
1000   case tok::kw_double:
1001   case tok::kw_void:
1002     if (NextToken().is(tok::l_paren))
1003       return TPResult::Ambiguous();
1004
1005     if (isStartOfObjCClassMessageMissingOpenBracket())
1006       return TPResult::False();
1007       
1008     return TPResult::True();
1009
1010   // GNU typeof support.
1011   case tok::kw_typeof: {
1012     if (NextToken().isNot(tok::l_paren))
1013       return TPResult::True();
1014
1015     TentativeParsingAction PA(*this);
1016
1017     TPResult TPR = TryParseTypeofSpecifier();
1018     bool isFollowedByParen = Tok.is(tok::l_paren);
1019
1020     PA.Revert();
1021
1022     if (TPR == TPResult::Error())
1023       return TPResult::Error();
1024
1025     if (isFollowedByParen)
1026       return TPResult::Ambiguous();
1027
1028     return TPResult::True();
1029   }
1030
1031   // C++0x decltype support.
1032   case tok::kw_decltype:
1033     return TPResult::True();
1034
1035   // C++0x type traits support
1036   case tok::kw___underlying_type:
1037     return TPResult::True();
1038
1039   // C1x _Atomic
1040   case tok::kw__Atomic:
1041     return TPResult::True();
1042
1043   default:
1044     return TPResult::False();
1045   }
1046 }
1047
1048 /// [GNU] typeof-specifier:
1049 ///         'typeof' '(' expressions ')'
1050 ///         'typeof' '(' type-name ')'
1051 ///
1052 Parser::TPResult Parser::TryParseTypeofSpecifier() {
1053   assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
1054   ConsumeToken();
1055
1056   assert(Tok.is(tok::l_paren) && "Expected '('");
1057   // Parse through the parens after 'typeof'.
1058   ConsumeParen();
1059   if (!SkipUntil(tok::r_paren))
1060     return TPResult::Error();
1061
1062   return TPResult::Ambiguous();
1063 }
1064
1065 /// [ObjC] protocol-qualifiers:
1066 ////         '<' identifier-list '>'
1067 Parser::TPResult Parser::TryParseProtocolQualifiers() {
1068   assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1069   ConsumeToken();
1070   do {
1071     if (Tok.isNot(tok::identifier))
1072       return TPResult::Error();
1073     ConsumeToken();
1074     
1075     if (Tok.is(tok::comma)) {
1076       ConsumeToken();
1077       continue;
1078     }
1079     
1080     if (Tok.is(tok::greater)) {
1081       ConsumeToken();
1082       return TPResult::Ambiguous();
1083     }
1084   } while (false);
1085   
1086   return TPResult::Error();
1087 }
1088
1089 Parser::TPResult Parser::TryParseDeclarationSpecifier() {
1090   TPResult TPR = isCXXDeclarationSpecifier();
1091   if (TPR != TPResult::Ambiguous())
1092     return TPR;
1093
1094   if (Tok.is(tok::kw_typeof))
1095     TryParseTypeofSpecifier();
1096   else {
1097     ConsumeToken();
1098     
1099     if (getLang().ObjC1 && Tok.is(tok::less))
1100       TryParseProtocolQualifiers();
1101   }
1102
1103   assert(Tok.is(tok::l_paren) && "Expected '('!");
1104   return TPResult::Ambiguous();
1105 }
1106
1107 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1108 /// a constructor-style initializer, when parsing declaration statements.
1109 /// Returns true for function declarator and false for constructor-style
1110 /// initializer.
1111 /// If during the disambiguation process a parsing error is encountered,
1112 /// the function returns true to let the declaration parsing code handle it.
1113 ///
1114 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1115 ///         exception-specification[opt]
1116 ///
1117 bool Parser::isCXXFunctionDeclarator(bool warnIfAmbiguous) {
1118
1119   // C++ 8.2p1:
1120   // The ambiguity arising from the similarity between a function-style cast and
1121   // a declaration mentioned in 6.8 can also occur in the context of a
1122   // declaration. In that context, the choice is between a function declaration
1123   // with a redundant set of parentheses around a parameter name and an object
1124   // declaration with a function-style cast as the initializer. Just as for the
1125   // ambiguities mentioned in 6.8, the resolution is to consider any construct
1126   // that could possibly be a declaration a declaration.
1127
1128   TentativeParsingAction PA(*this);
1129
1130   ConsumeParen();
1131   TPResult TPR = TryParseParameterDeclarationClause();
1132   if (TPR == TPResult::Ambiguous() && Tok.isNot(tok::r_paren))
1133     TPR = TPResult::False();
1134
1135   SourceLocation TPLoc = Tok.getLocation();
1136   PA.Revert();
1137
1138   // In case of an error, let the declaration parsing code handle it.
1139   if (TPR == TPResult::Error())
1140     return true;
1141
1142   if (TPR == TPResult::Ambiguous()) {
1143     // Function declarator has precedence over constructor-style initializer.
1144     // Emit a warning just in case the author intended a variable definition.
1145     if (warnIfAmbiguous)
1146       Diag(Tok, diag::warn_parens_disambiguated_as_function_decl)
1147         << SourceRange(Tok.getLocation(), TPLoc);
1148     return true;
1149   }
1150
1151   return TPR == TPResult::True();
1152 }
1153
1154 /// parameter-declaration-clause:
1155 ///   parameter-declaration-list[opt] '...'[opt]
1156 ///   parameter-declaration-list ',' '...'
1157 ///
1158 /// parameter-declaration-list:
1159 ///   parameter-declaration
1160 ///   parameter-declaration-list ',' parameter-declaration
1161 ///
1162 /// parameter-declaration:
1163 ///   decl-specifier-seq declarator attributes[opt]
1164 ///   decl-specifier-seq declarator attributes[opt] '=' assignment-expression
1165 ///   decl-specifier-seq abstract-declarator[opt] attributes[opt]
1166 ///   decl-specifier-seq abstract-declarator[opt] attributes[opt]
1167 ///     '=' assignment-expression
1168 ///
1169 Parser::TPResult Parser::TryParseParameterDeclarationClause() {
1170
1171   if (Tok.is(tok::r_paren))
1172     return TPResult::True();
1173
1174   //   parameter-declaration-list[opt] '...'[opt]
1175   //   parameter-declaration-list ',' '...'
1176   //
1177   // parameter-declaration-list:
1178   //   parameter-declaration
1179   //   parameter-declaration-list ',' parameter-declaration
1180   //
1181   while (1) {
1182     // '...'[opt]
1183     if (Tok.is(tok::ellipsis)) {
1184       ConsumeToken();
1185       return TPResult::True(); // '...' is a sign of a function declarator.
1186     }
1187
1188     ParsedAttributes attrs(AttrFactory);
1189     MaybeParseMicrosoftAttributes(attrs);
1190
1191     // decl-specifier-seq
1192     TPResult TPR = TryParseDeclarationSpecifier();
1193     if (TPR != TPResult::Ambiguous())
1194       return TPR;
1195
1196     // declarator
1197     // abstract-declarator[opt]
1198     TPR = TryParseDeclarator(true/*mayBeAbstract*/);
1199     if (TPR != TPResult::Ambiguous())
1200       return TPR;
1201
1202     // [GNU] attributes[opt]
1203     if (Tok.is(tok::kw___attribute))
1204       return TPResult::True();
1205
1206     if (Tok.is(tok::equal)) {
1207       // '=' assignment-expression
1208       // Parse through assignment-expression.
1209       tok::TokenKind StopToks[2] ={ tok::comma, tok::r_paren };
1210       if (!SkipUntil(StopToks, 2, true/*StopAtSemi*/, true/*DontConsume*/))
1211         return TPResult::Error();
1212     }
1213
1214     if (Tok.is(tok::ellipsis)) {
1215       ConsumeToken();
1216       return TPResult::True(); // '...' is a sign of a function declarator.
1217     }
1218
1219     if (Tok.isNot(tok::comma))
1220       break;
1221     ConsumeToken(); // the comma.
1222   }
1223
1224   return TPResult::Ambiguous();
1225 }
1226
1227 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
1228 /// parsing as a function declarator.
1229 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
1230 /// return TPResult::Ambiguous(), otherwise it will return either False() or
1231 /// Error().
1232 ///
1233 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1234 ///         exception-specification[opt]
1235 ///
1236 /// exception-specification:
1237 ///   'throw' '(' type-id-list[opt] ')'
1238 ///
1239 Parser::TPResult Parser::TryParseFunctionDeclarator() {
1240
1241   // The '(' is already parsed.
1242
1243   TPResult TPR = TryParseParameterDeclarationClause();
1244   if (TPR == TPResult::Ambiguous() && Tok.isNot(tok::r_paren))
1245     TPR = TPResult::False();
1246
1247   if (TPR == TPResult::False() || TPR == TPResult::Error())
1248     return TPR;
1249
1250   // Parse through the parens.
1251   if (!SkipUntil(tok::r_paren))
1252     return TPResult::Error();
1253
1254   // cv-qualifier-seq
1255   while (Tok.is(tok::kw_const)    ||
1256          Tok.is(tok::kw_volatile) ||
1257          Tok.is(tok::kw_restrict)   )
1258     ConsumeToken();
1259
1260   // ref-qualifier[opt]
1261   if (Tok.is(tok::amp) || Tok.is(tok::ampamp))
1262     ConsumeToken();
1263   
1264   // exception-specification
1265   if (Tok.is(tok::kw_throw)) {
1266     ConsumeToken();
1267     if (Tok.isNot(tok::l_paren))
1268       return TPResult::Error();
1269
1270     // Parse through the parens after 'throw'.
1271     ConsumeParen();
1272     if (!SkipUntil(tok::r_paren))
1273       return TPResult::Error();
1274   }
1275   if (Tok.is(tok::kw_noexcept)) {
1276     ConsumeToken();
1277     // Possibly an expression as well.
1278     if (Tok.is(tok::l_paren)) {
1279       // Find the matching rparen.
1280       ConsumeParen();
1281       if (!SkipUntil(tok::r_paren))
1282         return TPResult::Error();
1283     }
1284   }
1285
1286   return TPResult::Ambiguous();
1287 }
1288
1289 /// '[' constant-expression[opt] ']'
1290 ///
1291 Parser::TPResult Parser::TryParseBracketDeclarator() {
1292   ConsumeBracket();
1293   if (!SkipUntil(tok::r_square))
1294     return TPResult::Error();
1295
1296   return TPResult::Ambiguous();
1297 }