]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/llvm/tools/clang/lib/Parse/ParseTentative.cpp
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.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(/*AllowForRangeDecl=*/false);
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 /// (if AllowForRangeDecl specified)
79 /// for ( for-range-declaration : for-range-initializer ) statement
80 /// for-range-declaration: 
81 ///    attribute-specifier-seqopt type-specifier-seq declarator
82 bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) {
83   // C++ 6.8p1:
84   // There is an ambiguity in the grammar involving expression-statements and
85   // declarations: An expression-statement with a function-style explicit type
86   // conversion (5.2.3) as its leftmost subexpression can be indistinguishable
87   // from a declaration where the first declarator starts with a '('. In those
88   // cases the statement is a declaration. [Note: To disambiguate, the whole
89   // statement might have to be examined to determine if it is an
90   // expression-statement or a declaration].
91
92   // C++ 6.8p3:
93   // The disambiguation is purely syntactic; that is, the meaning of the names
94   // occurring in such a statement, beyond whether they are type-names or not,
95   // is not generally used in or changed by the disambiguation. Class
96   // templates are instantiated as necessary to determine if a qualified name
97   // is a type-name. Disambiguation precedes parsing, and a statement
98   // disambiguated as a declaration may be an ill-formed declaration.
99
100   // We don't have to parse all of the decl-specifier-seq part. There's only
101   // an ambiguity if the first decl-specifier is
102   // simple-type-specifier/typename-specifier followed by a '(', which may
103   // indicate a function-style cast expression.
104   // isCXXDeclarationSpecifier will return TPResult::Ambiguous() only in such
105   // a case.
106
107   bool InvalidAsDeclaration = false;
108   TPResult TPR = isCXXDeclarationSpecifier(TPResult::False(),
109                                            &InvalidAsDeclaration);
110   if (TPR != TPResult::Ambiguous())
111     return TPR != TPResult::False(); // Returns true for TPResult::True() or
112                                      // TPResult::Error().
113
114   // FIXME: TryParseSimpleDeclaration doesn't look past the first initializer,
115   // and so gets some cases wrong. We can't carry on if we've already seen
116   // something which makes this statement invalid as a declaration in this case,
117   // since it can cause us to misparse valid code. Revisit this once
118   // TryParseInitDeclaratorList is fixed.
119   if (InvalidAsDeclaration)
120     return false;
121
122   // FIXME: Add statistics about the number of ambiguous statements encountered
123   // and how they were resolved (number of declarations+number of expressions).
124
125   // Ok, we have a simple-type-specifier/typename-specifier followed by a '(',
126   // or an identifier which doesn't resolve as anything. We need tentative
127   // parsing...
128
129   TentativeParsingAction PA(*this);
130   TPR = TryParseSimpleDeclaration(AllowForRangeDecl);
131   PA.Revert();
132
133   // In case of an error, let the declaration parsing code handle it.
134   if (TPR == TPResult::Error())
135     return true;
136
137   // Declarations take precedence over expressions.
138   if (TPR == TPResult::Ambiguous())
139     TPR = TPResult::True();
140
141   assert(TPR == TPResult::True() || TPR == TPResult::False());
142   return TPR == TPResult::True();
143 }
144
145 /// simple-declaration:
146 ///   decl-specifier-seq init-declarator-list[opt] ';'
147 ///
148 /// (if AllowForRangeDecl specified)
149 /// for ( for-range-declaration : for-range-initializer ) statement
150 /// for-range-declaration: 
151 ///    attribute-specifier-seqopt type-specifier-seq declarator
152 ///
153 Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) {
154   if (Tok.is(tok::kw_typeof))
155     TryParseTypeofSpecifier();
156   else {
157     if (Tok.is(tok::annot_cxxscope))
158       ConsumeToken();
159     ConsumeToken();
160
161     if (getLangOpts().ObjC1 && Tok.is(tok::less))
162       TryParseProtocolQualifiers();
163   }
164
165   // Two decl-specifiers in a row conclusively disambiguate this as being a
166   // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the
167   // overwhelmingly common case that the next token is a '('.
168   if (Tok.isNot(tok::l_paren)) {
169     TPResult TPR = isCXXDeclarationSpecifier();
170     if (TPR == TPResult::Ambiguous())
171       return TPResult::True();
172     if (TPR == TPResult::True() || TPR == TPResult::Error())
173       return TPR;
174     assert(TPR == TPResult::False());
175   }
176
177   TPResult TPR = TryParseInitDeclaratorList();
178   if (TPR != TPResult::Ambiguous())
179     return TPR;
180
181   if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon)))
182     return TPResult::False();
183
184   return TPResult::Ambiguous();
185 }
186
187 /// Tentatively parse an init-declarator-list in order to disambiguate it from
188 /// an expression.
189 ///
190 ///       init-declarator-list:
191 ///         init-declarator
192 ///         init-declarator-list ',' init-declarator
193 ///
194 ///       init-declarator:
195 ///         declarator initializer[opt]
196 /// [GNU]   declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
197 ///
198 ///       initializer:
199 ///         brace-or-equal-initializer
200 ///         '(' expression-list ')'
201 ///
202 ///       brace-or-equal-initializer:
203 ///         '=' initializer-clause
204 /// [C++11] braced-init-list
205 ///
206 ///       initializer-clause:
207 ///         assignment-expression
208 ///         braced-init-list
209 ///
210 ///       braced-init-list:
211 ///         '{' initializer-list ','[opt] '}'
212 ///         '{' '}'
213 ///
214 Parser::TPResult Parser::TryParseInitDeclaratorList() {
215   while (1) {
216     // declarator
217     TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
218     if (TPR != TPResult::Ambiguous())
219       return TPR;
220
221     // [GNU] simple-asm-expr[opt] attributes[opt]
222     if (Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
223       return TPResult::True();
224
225     // initializer[opt]
226     if (Tok.is(tok::l_paren)) {
227       // Parse through the parens.
228       ConsumeParen();
229       if (!SkipUntil(tok::r_paren))
230         return TPResult::Error();
231     } else if (Tok.is(tok::l_brace)) {
232       // A left-brace here is sufficient to disambiguate the parse; an
233       // expression can never be followed directly by a braced-init-list.
234       return TPResult::True();
235     } else if (Tok.is(tok::equal) || isTokIdentifier_in()) {
236       // MSVC and g++ won't examine the rest of declarators if '=' is 
237       // encountered; they just conclude that we have a declaration.
238       // EDG parses the initializer completely, which is the proper behavior
239       // for this case.
240       //
241       // At present, Clang follows MSVC and g++, since the parser does not have
242       // the ability to parse an expression fully without recording the
243       // results of that parse.
244       // Also allow 'in' after on objective-c declaration as in: 
245       // for (int (^b)(void) in array). Ideally this should be done in the 
246       // context of parsing for-init-statement of a foreach statement only. But,
247       // in any other context 'in' is invalid after a declaration and parser
248       // issues the error regardless of outcome of this decision.
249       // FIXME. Change if above assumption does not hold.
250       return TPResult::True();
251     }
252
253     if (Tok.isNot(tok::comma))
254       break;
255     ConsumeToken(); // the comma.
256   }
257
258   return TPResult::Ambiguous();
259 }
260
261 /// isCXXConditionDeclaration - Disambiguates between a declaration or an
262 /// expression for a condition of a if/switch/while/for statement.
263 /// If during the disambiguation process a parsing error is encountered,
264 /// the function returns true to let the declaration parsing code handle it.
265 ///
266 ///       condition:
267 ///         expression
268 ///         type-specifier-seq declarator '=' assignment-expression
269 /// [C++11] type-specifier-seq declarator '=' initializer-clause
270 /// [C++11] type-specifier-seq declarator braced-init-list
271 /// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
272 ///             '=' assignment-expression
273 ///
274 bool Parser::isCXXConditionDeclaration() {
275   TPResult TPR = isCXXDeclarationSpecifier();
276   if (TPR != TPResult::Ambiguous())
277     return TPR != TPResult::False(); // Returns true for TPResult::True() or
278                                      // TPResult::Error().
279
280   // FIXME: Add statistics about the number of ambiguous statements encountered
281   // and how they were resolved (number of declarations+number of expressions).
282
283   // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
284   // We need tentative parsing...
285
286   TentativeParsingAction PA(*this);
287
288   // type-specifier-seq
289   if (Tok.is(tok::kw_typeof))
290     TryParseTypeofSpecifier();
291   else {
292     ConsumeToken();
293     
294     if (getLangOpts().ObjC1 && Tok.is(tok::less))
295       TryParseProtocolQualifiers();
296   }
297   assert(Tok.is(tok::l_paren) && "Expected '('");
298
299   // declarator
300   TPR = TryParseDeclarator(false/*mayBeAbstract*/);
301
302   // In case of an error, let the declaration parsing code handle it.
303   if (TPR == TPResult::Error())
304     TPR = TPResult::True();
305
306   if (TPR == TPResult::Ambiguous()) {
307     // '='
308     // [GNU] simple-asm-expr[opt] attributes[opt]
309     if (Tok.is(tok::equal)  ||
310         Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
311       TPR = TPResult::True();
312     else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
313       TPR = TPResult::True();
314     else
315       TPR = TPResult::False();
316   }
317
318   PA.Revert();
319
320   assert(TPR == TPResult::True() || TPR == TPResult::False());
321   return TPR == TPResult::True();
322 }
323
324   /// \brief Determine whether the next set of tokens contains a type-id.
325   ///
326   /// The context parameter states what context we're parsing right
327   /// now, which affects how this routine copes with the token
328   /// following the type-id. If the context is TypeIdInParens, we have
329   /// already parsed the '(' and we will cease lookahead when we hit
330   /// the corresponding ')'. If the context is
331   /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
332   /// before this template argument, and will cease lookahead when we
333   /// hit a '>', '>>' (in C++0x), or ','. Returns true for a type-id
334   /// and false for an expression.  If during the disambiguation
335   /// process a parsing error is encountered, the function returns
336   /// true to let the declaration parsing code handle it.
337   ///
338   /// type-id:
339   ///   type-specifier-seq abstract-declarator[opt]
340   ///
341 bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
342
343   isAmbiguous = false;
344
345   // C++ 8.2p2:
346   // The ambiguity arising from the similarity between a function-style cast and
347   // a type-id can occur in different contexts. The ambiguity appears as a
348   // choice between a function-style cast expression and a declaration of a
349   // type. The resolution is that any construct that could possibly be a type-id
350   // in its syntactic context shall be considered a type-id.
351
352   TPResult TPR = isCXXDeclarationSpecifier();
353   if (TPR != TPResult::Ambiguous())
354     return TPR != TPResult::False(); // Returns true for TPResult::True() or
355                                      // TPResult::Error().
356
357   // FIXME: Add statistics about the number of ambiguous statements encountered
358   // and how they were resolved (number of declarations+number of expressions).
359
360   // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
361   // We need tentative parsing...
362
363   TentativeParsingAction PA(*this);
364
365   // type-specifier-seq
366   if (Tok.is(tok::kw_typeof))
367     TryParseTypeofSpecifier();
368   else {
369     ConsumeToken();
370     
371     if (getLangOpts().ObjC1 && Tok.is(tok::less))
372       TryParseProtocolQualifiers();
373   }
374   
375   assert(Tok.is(tok::l_paren) && "Expected '('");
376
377   // declarator
378   TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
379
380   // In case of an error, let the declaration parsing code handle it.
381   if (TPR == TPResult::Error())
382     TPR = TPResult::True();
383
384   if (TPR == TPResult::Ambiguous()) {
385     // We are supposed to be inside parens, so if after the abstract declarator
386     // we encounter a ')' this is a type-id, otherwise it's an expression.
387     if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
388       TPR = TPResult::True();
389       isAmbiguous = true;
390
391     // We are supposed to be inside a template argument, so if after
392     // the abstract declarator we encounter a '>', '>>' (in C++0x), or
393     // ',', this is a type-id. Otherwise, it's an expression.
394     } else if (Context == TypeIdAsTemplateArgument &&
395                (Tok.is(tok::greater) || Tok.is(tok::comma) ||
396                 (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater)))) {
397       TPR = TPResult::True();
398       isAmbiguous = true;
399
400     } else
401       TPR = TPResult::False();
402   }
403
404   PA.Revert();
405
406   assert(TPR == TPResult::True() || TPR == TPResult::False());
407   return TPR == TPResult::True();
408 }
409
410 /// \brief Returns true if this is a C++11 attribute-specifier. Per
411 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
412 /// always introduce an attribute. In Objective-C++11, this rule does not
413 /// apply if either '[' begins a message-send.
414 ///
415 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
416 /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
417 ///
418 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
419 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
420 /// is not an Obj-C message send.
421 ///
422 /// C++11 [dcl.attr.grammar]:
423 ///
424 ///     attribute-specifier:
425 ///         '[' '[' attribute-list ']' ']'
426 ///         alignment-specifier
427 ///
428 ///     attribute-list:
429 ///         attribute[opt]
430 ///         attribute-list ',' attribute[opt]
431 ///         attribute '...'
432 ///         attribute-list ',' attribute '...'
433 ///
434 ///     attribute:
435 ///         attribute-token attribute-argument-clause[opt]
436 ///
437 ///     attribute-token:
438 ///         identifier
439 ///         identifier '::' identifier
440 ///
441 ///     attribute-argument-clause:
442 ///         '(' balanced-token-seq ')'
443 Parser::CXX11AttributeKind
444 Parser::isCXX11AttributeSpecifier(bool Disambiguate,
445                                   bool OuterMightBeMessageSend) {
446   if (Tok.is(tok::kw_alignas))
447     return CAK_AttributeSpecifier;
448
449   if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
450     return CAK_NotAttributeSpecifier;
451
452   // No tentative parsing if we don't need to look for ']]' or a lambda.
453   if (!Disambiguate && !getLangOpts().ObjC1)
454     return CAK_AttributeSpecifier;
455
456   TentativeParsingAction PA(*this);
457
458   // Opening brackets were checked for above.
459   ConsumeBracket();
460
461   // Outside Obj-C++11, treat anything with a matching ']]' as an attribute.
462   if (!getLangOpts().ObjC1) {
463     ConsumeBracket();
464
465     bool IsAttribute = SkipUntil(tok::r_square, false);
466     IsAttribute &= Tok.is(tok::r_square);
467
468     PA.Revert();
469
470     return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
471   }
472
473   // In Obj-C++11, we need to distinguish four situations:
474   //  1a) int x[[attr]];                     C++11 attribute.
475   //  1b) [[attr]];                          C++11 statement attribute.
476   //   2) int x[[obj](){ return 1; }()];     Lambda in array size/index.
477   //  3a) int x[[obj get]];                  Message send in array size/index.
478   //  3b) [[Class alloc] init];              Message send in message send.
479   //   4) [[obj]{ return self; }() doStuff]; Lambda in message send.
480   // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
481
482   // If we have a lambda-introducer, then this is definitely not a message send.
483   // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
484   // into the tentative attribute parse below.
485   LambdaIntroducer Intro;
486   if (!TryParseLambdaIntroducer(Intro)) {
487     // A lambda cannot end with ']]', and an attribute must.
488     bool IsAttribute = Tok.is(tok::r_square);
489
490     PA.Revert();
491
492     if (IsAttribute)
493       // Case 1: C++11 attribute.
494       return CAK_AttributeSpecifier;
495
496     if (OuterMightBeMessageSend)
497       // Case 4: Lambda in message send.
498       return CAK_NotAttributeSpecifier;
499
500     // Case 2: Lambda in array size / index.
501     return CAK_InvalidAttributeSpecifier;
502   }
503
504   ConsumeBracket();
505
506   // If we don't have a lambda-introducer, then we have an attribute or a
507   // message-send.
508   bool IsAttribute = true;
509   while (Tok.isNot(tok::r_square)) {
510     if (Tok.is(tok::comma)) {
511       // Case 1: Stray commas can only occur in attributes.
512       PA.Revert();
513       return CAK_AttributeSpecifier;
514     }
515
516     // Parse the attribute-token, if present.
517     // C++11 [dcl.attr.grammar]:
518     //   If a keyword or an alternative token that satisfies the syntactic
519     //   requirements of an identifier is contained in an attribute-token,
520     //   it is considered an identifier.
521     SourceLocation Loc;
522     if (!TryParseCXX11AttributeIdentifier(Loc)) {
523       IsAttribute = false;
524       break;
525     }
526     if (Tok.is(tok::coloncolon)) {
527       ConsumeToken();
528       if (!TryParseCXX11AttributeIdentifier(Loc)) {
529         IsAttribute = false;
530         break;
531       }
532     }
533
534     // Parse the attribute-argument-clause, if present.
535     if (Tok.is(tok::l_paren)) {
536       ConsumeParen();
537       if (!SkipUntil(tok::r_paren, false)) {
538         IsAttribute = false;
539         break;
540       }
541     }
542
543     if (Tok.is(tok::ellipsis))
544       ConsumeToken();
545
546     if (Tok.isNot(tok::comma))
547       break;
548
549     ConsumeToken();
550   }
551
552   // An attribute must end ']]'.
553   if (IsAttribute) {
554     if (Tok.is(tok::r_square)) {
555       ConsumeBracket();
556       IsAttribute = Tok.is(tok::r_square);
557     } else {
558       IsAttribute = false;
559     }
560   }
561
562   PA.Revert();
563
564   if (IsAttribute)
565     // Case 1: C++11 statement attribute.
566     return CAK_AttributeSpecifier;
567
568   // Case 3: Message send.
569   return CAK_NotAttributeSpecifier;
570 }
571
572 ///         declarator:
573 ///           direct-declarator
574 ///           ptr-operator declarator
575 ///
576 ///         direct-declarator:
577 ///           declarator-id
578 ///           direct-declarator '(' parameter-declaration-clause ')'
579 ///                 cv-qualifier-seq[opt] exception-specification[opt]
580 ///           direct-declarator '[' constant-expression[opt] ']'
581 ///           '(' declarator ')'
582 /// [GNU]     '(' attributes declarator ')'
583 ///
584 ///         abstract-declarator:
585 ///           ptr-operator abstract-declarator[opt]
586 ///           direct-abstract-declarator
587 ///           ...
588 ///
589 ///         direct-abstract-declarator:
590 ///           direct-abstract-declarator[opt]
591 ///           '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
592 ///                 exception-specification[opt]
593 ///           direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
594 ///           '(' abstract-declarator ')'
595 ///
596 ///         ptr-operator:
597 ///           '*' cv-qualifier-seq[opt]
598 ///           '&'
599 /// [C++0x]   '&&'                                                        [TODO]
600 ///           '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
601 ///
602 ///         cv-qualifier-seq:
603 ///           cv-qualifier cv-qualifier-seq[opt]
604 ///
605 ///         cv-qualifier:
606 ///           'const'
607 ///           'volatile'
608 ///
609 ///         declarator-id:
610 ///           '...'[opt] id-expression
611 ///
612 ///         id-expression:
613 ///           unqualified-id
614 ///           qualified-id                                                [TODO]
615 ///
616 ///         unqualified-id:
617 ///           identifier
618 ///           operator-function-id                                        [TODO]
619 ///           conversion-function-id                                      [TODO]
620 ///           '~' class-name                                              [TODO]
621 ///           template-id                                                 [TODO]
622 ///
623 Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
624                                             bool mayHaveIdentifier) {
625   // declarator:
626   //   direct-declarator
627   //   ptr-operator declarator
628
629   while (1) {
630     if (Tok.is(tok::coloncolon) || Tok.is(tok::identifier))
631       if (TryAnnotateCXXScopeToken(true))
632         return TPResult::Error();
633
634     if (Tok.is(tok::star) || Tok.is(tok::amp) || Tok.is(tok::caret) ||
635         Tok.is(tok::ampamp) ||
636         (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
637       // ptr-operator
638       ConsumeToken();
639       while (Tok.is(tok::kw_const)    ||
640              Tok.is(tok::kw_volatile) ||
641              Tok.is(tok::kw_restrict))
642         ConsumeToken();
643     } else {
644       break;
645     }
646   }
647
648   // direct-declarator:
649   // direct-abstract-declarator:
650   if (Tok.is(tok::ellipsis))
651     ConsumeToken();
652   
653   if ((Tok.is(tok::identifier) ||
654        (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) &&
655       mayHaveIdentifier) {
656     // declarator-id
657     if (Tok.is(tok::annot_cxxscope))
658       ConsumeToken();
659     else
660       TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
661     ConsumeToken();
662   } else if (Tok.is(tok::l_paren)) {
663     ConsumeParen();
664     if (mayBeAbstract &&
665         (Tok.is(tok::r_paren) ||       // 'int()' is a function.
666          // 'int(...)' is a function.
667          (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
668          isDeclarationSpecifier())) {   // 'int(int)' is a function.
669       // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
670       //        exception-specification[opt]
671       TPResult TPR = TryParseFunctionDeclarator();
672       if (TPR != TPResult::Ambiguous())
673         return TPR;
674     } else {
675       // '(' declarator ')'
676       // '(' attributes declarator ')'
677       // '(' abstract-declarator ')'
678       if (Tok.is(tok::kw___attribute) ||
679           Tok.is(tok::kw___declspec) ||
680           Tok.is(tok::kw___cdecl) ||
681           Tok.is(tok::kw___stdcall) ||
682           Tok.is(tok::kw___fastcall) ||
683           Tok.is(tok::kw___thiscall) ||
684           Tok.is(tok::kw___unaligned))
685         return TPResult::True(); // attributes indicate declaration
686       TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
687       if (TPR != TPResult::Ambiguous())
688         return TPR;
689       if (Tok.isNot(tok::r_paren))
690         return TPResult::False();
691       ConsumeParen();
692     }
693   } else if (!mayBeAbstract) {
694     return TPResult::False();
695   }
696
697   while (1) {
698     TPResult TPR(TPResult::Ambiguous());
699
700     // abstract-declarator: ...
701     if (Tok.is(tok::ellipsis))
702       ConsumeToken();
703
704     if (Tok.is(tok::l_paren)) {
705       // Check whether we have a function declarator or a possible ctor-style
706       // initializer that follows the declarator. Note that ctor-style
707       // initializers are not possible in contexts where abstract declarators
708       // are allowed.
709       if (!mayBeAbstract && !isCXXFunctionDeclarator())
710         break;
711
712       // direct-declarator '(' parameter-declaration-clause ')'
713       //        cv-qualifier-seq[opt] exception-specification[opt]
714       ConsumeParen();
715       TPR = TryParseFunctionDeclarator();
716     } else if (Tok.is(tok::l_square)) {
717       // direct-declarator '[' constant-expression[opt] ']'
718       // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
719       TPR = TryParseBracketDeclarator();
720     } else {
721       break;
722     }
723
724     if (TPR != TPResult::Ambiguous())
725       return TPR;
726   }
727
728   return TPResult::Ambiguous();
729 }
730
731 Parser::TPResult 
732 Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) {
733   switch (Kind) {
734   // Obviously starts an expression.
735   case tok::numeric_constant:
736   case tok::char_constant:
737   case tok::wide_char_constant:
738   case tok::utf16_char_constant:
739   case tok::utf32_char_constant:
740   case tok::string_literal:
741   case tok::wide_string_literal:
742   case tok::utf8_string_literal:
743   case tok::utf16_string_literal:
744   case tok::utf32_string_literal:
745   case tok::l_square:
746   case tok::l_paren:
747   case tok::amp:
748   case tok::ampamp:
749   case tok::star:
750   case tok::plus:
751   case tok::plusplus:
752   case tok::minus:
753   case tok::minusminus:
754   case tok::tilde:
755   case tok::exclaim:
756   case tok::kw_sizeof:
757   case tok::kw___func__:
758   case tok::kw_const_cast:
759   case tok::kw_delete:
760   case tok::kw_dynamic_cast:
761   case tok::kw_false:
762   case tok::kw_new:
763   case tok::kw_operator:
764   case tok::kw_reinterpret_cast:
765   case tok::kw_static_cast:
766   case tok::kw_this:
767   case tok::kw_throw:
768   case tok::kw_true:
769   case tok::kw_typeid:
770   case tok::kw_alignof:
771   case tok::kw_noexcept:
772   case tok::kw_nullptr:
773   case tok::kw__Alignof:
774   case tok::kw___null:
775   case tok::kw___alignof:
776   case tok::kw___builtin_choose_expr:
777   case tok::kw___builtin_offsetof:
778   case tok::kw___builtin_types_compatible_p:
779   case tok::kw___builtin_va_arg:
780   case tok::kw___imag:
781   case tok::kw___real:
782   case tok::kw___FUNCTION__:
783   case tok::kw_L__FUNCTION__:
784   case tok::kw___PRETTY_FUNCTION__:
785   case tok::kw___has_nothrow_assign:
786   case tok::kw___has_nothrow_copy:
787   case tok::kw___has_nothrow_constructor:
788   case tok::kw___has_trivial_assign:
789   case tok::kw___has_trivial_copy:
790   case tok::kw___has_trivial_constructor:
791   case tok::kw___has_trivial_destructor:
792   case tok::kw___has_virtual_destructor:
793   case tok::kw___is_abstract:
794   case tok::kw___is_base_of:
795   case tok::kw___is_class:
796   case tok::kw___is_convertible_to:
797   case tok::kw___is_empty:
798   case tok::kw___is_enum:
799   case tok::kw___is_interface_class:
800   case tok::kw___is_final:
801   case tok::kw___is_literal:
802   case tok::kw___is_literal_type:
803   case tok::kw___is_pod:
804   case tok::kw___is_polymorphic:
805   case tok::kw___is_trivial:
806   case tok::kw___is_trivially_assignable:
807   case tok::kw___is_trivially_constructible:
808   case tok::kw___is_trivially_copyable:
809   case tok::kw___is_union:
810   case tok::kw___uuidof:
811     return TPResult::True();
812       
813   // Obviously starts a type-specifier-seq:
814   case tok::kw_char:
815   case tok::kw_const:
816   case tok::kw_double:
817   case tok::kw_enum:
818   case tok::kw_half:
819   case tok::kw_float:
820   case tok::kw_int:
821   case tok::kw_long:
822   case tok::kw___int64:
823   case tok::kw___int128:
824   case tok::kw_restrict:
825   case tok::kw_short:
826   case tok::kw_signed:
827   case tok::kw_struct:
828   case tok::kw_union:
829   case tok::kw_unsigned:
830   case tok::kw_void:
831   case tok::kw_volatile:
832   case tok::kw__Bool:
833   case tok::kw__Complex:
834   case tok::kw_class:
835   case tok::kw_typename:
836   case tok::kw_wchar_t:
837   case tok::kw_char16_t:
838   case tok::kw_char32_t:
839   case tok::kw___underlying_type:
840   case tok::kw__Decimal32:
841   case tok::kw__Decimal64:
842   case tok::kw__Decimal128:
843   case tok::kw___thread:
844   case tok::kw_thread_local:
845   case tok::kw__Thread_local:
846   case tok::kw_typeof:
847   case tok::kw___cdecl:
848   case tok::kw___stdcall:
849   case tok::kw___fastcall:
850   case tok::kw___thiscall:
851   case tok::kw___unaligned:
852   case tok::kw___vector:
853   case tok::kw___pixel:
854   case tok::kw__Atomic:
855   case tok::kw_image1d_t:
856   case tok::kw_image1d_array_t:
857   case tok::kw_image1d_buffer_t:
858   case tok::kw_image2d_t:
859   case tok::kw_image2d_array_t:
860   case tok::kw_image3d_t:
861   case tok::kw_sampler_t:
862   case tok::kw_event_t:
863   case tok::kw___unknown_anytype:
864     return TPResult::False();
865
866   default:
867     break;
868   }
869   
870   return TPResult::Ambiguous();
871 }
872
873 bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
874   return std::find(TentativelyDeclaredIdentifiers.begin(),
875                    TentativelyDeclaredIdentifiers.end(), II)
876       != TentativelyDeclaredIdentifiers.end();
877 }
878
879 /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a declaration
880 /// specifier, TPResult::False() if it is not, TPResult::Ambiguous() if it could
881 /// be either a decl-specifier or a function-style cast, and TPResult::Error()
882 /// if a parsing error was found and reported.
883 ///
884 /// If HasMissingTypename is provided, a name with a dependent scope specifier
885 /// will be treated as ambiguous if the 'typename' keyword is missing. If this
886 /// happens, *HasMissingTypename will be set to 'true'. This will also be used
887 /// as an indicator that undeclared identifiers (which will trigger a later
888 /// parse error) should be treated as types. Returns TPResult::Ambiguous() in
889 /// such cases.
890 ///
891 ///         decl-specifier:
892 ///           storage-class-specifier
893 ///           type-specifier
894 ///           function-specifier
895 ///           'friend'
896 ///           'typedef'
897 /// [C++11]   'constexpr'
898 /// [GNU]     attributes declaration-specifiers[opt]
899 ///
900 ///         storage-class-specifier:
901 ///           'register'
902 ///           'static'
903 ///           'extern'
904 ///           'mutable'
905 ///           'auto'
906 /// [GNU]     '__thread'
907 /// [C++11]   'thread_local'
908 /// [C11]     '_Thread_local'
909 ///
910 ///         function-specifier:
911 ///           'inline'
912 ///           'virtual'
913 ///           'explicit'
914 ///
915 ///         typedef-name:
916 ///           identifier
917 ///
918 ///         type-specifier:
919 ///           simple-type-specifier
920 ///           class-specifier
921 ///           enum-specifier
922 ///           elaborated-type-specifier
923 ///           typename-specifier
924 ///           cv-qualifier
925 ///
926 ///         simple-type-specifier:
927 ///           '::'[opt] nested-name-specifier[opt] type-name
928 ///           '::'[opt] nested-name-specifier 'template'
929 ///                 simple-template-id                              [TODO]
930 ///           'char'
931 ///           'wchar_t'
932 ///           'bool'
933 ///           'short'
934 ///           'int'
935 ///           'long'
936 ///           'signed'
937 ///           'unsigned'
938 ///           'float'
939 ///           'double'
940 ///           'void'
941 /// [GNU]     typeof-specifier
942 /// [GNU]     '_Complex'
943 /// [C++11]   'auto'
944 /// [C++11]   'decltype' ( expression )
945 /// [C++1y]   'decltype' ( 'auto' )
946 ///
947 ///         type-name:
948 ///           class-name
949 ///           enum-name
950 ///           typedef-name
951 ///
952 ///         elaborated-type-specifier:
953 ///           class-key '::'[opt] nested-name-specifier[opt] identifier
954 ///           class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
955 ///               simple-template-id
956 ///           'enum' '::'[opt] nested-name-specifier[opt] identifier
957 ///
958 ///         enum-name:
959 ///           identifier
960 ///
961 ///         enum-specifier:
962 ///           'enum' identifier[opt] '{' enumerator-list[opt] '}'
963 ///           'enum' identifier[opt] '{' enumerator-list ',' '}'
964 ///
965 ///         class-specifier:
966 ///           class-head '{' member-specification[opt] '}'
967 ///
968 ///         class-head:
969 ///           class-key identifier[opt] base-clause[opt]
970 ///           class-key nested-name-specifier identifier base-clause[opt]
971 ///           class-key nested-name-specifier[opt] simple-template-id
972 ///               base-clause[opt]
973 ///
974 ///         class-key:
975 ///           'class'
976 ///           'struct'
977 ///           'union'
978 ///
979 ///         cv-qualifier:
980 ///           'const'
981 ///           'volatile'
982 /// [GNU]     restrict
983 ///
984 Parser::TPResult
985 Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
986                                   bool *HasMissingTypename) {
987   switch (Tok.getKind()) {
988   case tok::identifier: {
989     // Check for need to substitute AltiVec __vector keyword
990     // for "vector" identifier.
991     if (TryAltiVecVectorToken())
992       return TPResult::True();
993
994     const Token &Next = NextToken();
995     // In 'foo bar', 'foo' is always a type name outside of Objective-C.
996     if (!getLangOpts().ObjC1 && Next.is(tok::identifier))
997       return TPResult::True();
998
999     if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
1000       // Determine whether this is a valid expression. If not, we will hit
1001       // a parse error one way or another. In that case, tell the caller that
1002       // this is ambiguous. Typo-correct to type and expression keywords and
1003       // to types and identifiers, in order to try to recover from errors.
1004       CorrectionCandidateCallback TypoCorrection;
1005       TypoCorrection.WantRemainingKeywords = false;
1006       TypoCorrection.WantTypeSpecifiers = Next.isNot(tok::arrow);
1007       switch (TryAnnotateName(false /* no nested name specifier */,
1008                               &TypoCorrection)) {
1009       case ANK_Error:
1010         return TPResult::Error();
1011       case ANK_TentativeDecl:
1012         return TPResult::False();
1013       case ANK_TemplateName:
1014         // A bare type template-name which can't be a template template
1015         // argument is an error, and was probably intended to be a type.
1016         return GreaterThanIsOperator ? TPResult::True() : TPResult::False();
1017       case ANK_Unresolved:
1018         return HasMissingTypename ? TPResult::Ambiguous() : TPResult::False();
1019       case ANK_Success:
1020         break;
1021       }
1022       assert(Tok.isNot(tok::identifier) &&
1023              "TryAnnotateName succeeded without producing an annotation");
1024     } else {
1025       // This might possibly be a type with a dependent scope specifier and
1026       // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
1027       // since it will annotate as a primary expression, and we want to use the
1028       // "missing 'typename'" logic.
1029       if (TryAnnotateTypeOrScopeToken())
1030         return TPResult::Error();
1031       // If annotation failed, assume it's a non-type.
1032       // FIXME: If this happens due to an undeclared identifier, treat it as
1033       // ambiguous.
1034       if (Tok.is(tok::identifier))
1035         return TPResult::False();
1036     }
1037
1038     // We annotated this token as something. Recurse to handle whatever we got.
1039     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1040   }
1041
1042   case tok::kw_typename:  // typename T::type
1043     // Annotate typenames and C++ scope specifiers.  If we get one, just
1044     // recurse to handle whatever we get.
1045     if (TryAnnotateTypeOrScopeToken())
1046       return TPResult::Error();
1047     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1048
1049   case tok::coloncolon: {    // ::foo::bar
1050     const Token &Next = NextToken();
1051     if (Next.is(tok::kw_new) ||    // ::new
1052         Next.is(tok::kw_delete))   // ::delete
1053       return TPResult::False();
1054   }
1055     // Fall through.
1056   case tok::kw_decltype:
1057     // Annotate typenames and C++ scope specifiers.  If we get one, just
1058     // recurse to handle whatever we get.
1059     if (TryAnnotateTypeOrScopeToken())
1060       return TPResult::Error();
1061     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1062
1063     // decl-specifier:
1064     //   storage-class-specifier
1065     //   type-specifier
1066     //   function-specifier
1067     //   'friend'
1068     //   'typedef'
1069     //   'constexpr'
1070   case tok::kw_friend:
1071   case tok::kw_typedef:
1072   case tok::kw_constexpr:
1073     // storage-class-specifier
1074   case tok::kw_register:
1075   case tok::kw_static:
1076   case tok::kw_extern:
1077   case tok::kw_mutable:
1078   case tok::kw_auto:
1079   case tok::kw___thread:
1080   case tok::kw_thread_local:
1081   case tok::kw__Thread_local:
1082     // function-specifier
1083   case tok::kw_inline:
1084   case tok::kw_virtual:
1085   case tok::kw_explicit:
1086
1087     // Modules
1088   case tok::kw___module_private__:
1089
1090     // Debugger support
1091   case tok::kw___unknown_anytype:
1092       
1093     // type-specifier:
1094     //   simple-type-specifier
1095     //   class-specifier
1096     //   enum-specifier
1097     //   elaborated-type-specifier
1098     //   typename-specifier
1099     //   cv-qualifier
1100
1101     // class-specifier
1102     // elaborated-type-specifier
1103   case tok::kw_class:
1104   case tok::kw_struct:
1105   case tok::kw_union:
1106     // enum-specifier
1107   case tok::kw_enum:
1108     // cv-qualifier
1109   case tok::kw_const:
1110   case tok::kw_volatile:
1111
1112     // GNU
1113   case tok::kw_restrict:
1114   case tok::kw__Complex:
1115   case tok::kw___attribute:
1116     return TPResult::True();
1117
1118     // Microsoft
1119   case tok::kw___declspec:
1120   case tok::kw___cdecl:
1121   case tok::kw___stdcall:
1122   case tok::kw___fastcall:
1123   case tok::kw___thiscall:
1124   case tok::kw___w64:
1125   case tok::kw___ptr64:
1126   case tok::kw___ptr32:
1127   case tok::kw___forceinline:
1128   case tok::kw___unaligned:
1129     return TPResult::True();
1130
1131     // Borland
1132   case tok::kw___pascal:
1133     return TPResult::True();
1134   
1135     // AltiVec
1136   case tok::kw___vector:
1137     return TPResult::True();
1138
1139   case tok::annot_template_id: {
1140     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1141     if (TemplateId->Kind != TNK_Type_template)
1142       return TPResult::False();
1143     CXXScopeSpec SS;
1144     AnnotateTemplateIdTokenAsType();
1145     assert(Tok.is(tok::annot_typename));
1146     goto case_typename;
1147   }
1148
1149   case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
1150     // We've already annotated a scope; try to annotate a type.
1151     if (TryAnnotateTypeOrScopeToken())
1152       return TPResult::Error();
1153     if (!Tok.is(tok::annot_typename)) {
1154       // If the next token is an identifier or a type qualifier, then this
1155       // can't possibly be a valid expression either.
1156       if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
1157         CXXScopeSpec SS;
1158         Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1159                                                      Tok.getAnnotationRange(),
1160                                                      SS);
1161         if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
1162           TentativeParsingAction PA(*this);
1163           ConsumeToken();
1164           ConsumeToken();
1165           bool isIdentifier = Tok.is(tok::identifier);
1166           TPResult TPR = TPResult::False();
1167           if (!isIdentifier)
1168             TPR = isCXXDeclarationSpecifier(BracedCastResult,
1169                                             HasMissingTypename);
1170           PA.Revert();
1171
1172           if (isIdentifier ||
1173               TPR == TPResult::True() || TPR == TPResult::Error())
1174             return TPResult::Error();
1175
1176           if (HasMissingTypename) {
1177             // We can't tell whether this is a missing 'typename' or a valid
1178             // expression.
1179             *HasMissingTypename = true;
1180             return TPResult::Ambiguous();
1181           }
1182         } else {
1183           // Try to resolve the name. If it doesn't exist, assume it was
1184           // intended to name a type and keep disambiguating.
1185           switch (TryAnnotateName(false /* SS is not dependent */)) {
1186           case ANK_Error:
1187             return TPResult::Error();
1188           case ANK_TentativeDecl:
1189             return TPResult::False();
1190           case ANK_TemplateName:
1191             // A bare type template-name which can't be a template template
1192             // argument is an error, and was probably intended to be a type.
1193             return GreaterThanIsOperator ? TPResult::True() : TPResult::False();
1194           case ANK_Unresolved:
1195             return HasMissingTypename ? TPResult::Ambiguous()
1196                                       : TPResult::False();
1197           case ANK_Success:
1198             // Annotated it, check again.
1199             assert(Tok.isNot(tok::annot_cxxscope) ||
1200                    NextToken().isNot(tok::identifier));
1201             return isCXXDeclarationSpecifier(BracedCastResult,
1202                                              HasMissingTypename);
1203           }
1204         }
1205       }
1206       return TPResult::False();
1207     }
1208     // If that succeeded, fallthrough into the generic simple-type-id case.
1209
1210     // The ambiguity resides in a simple-type-specifier/typename-specifier
1211     // followed by a '('. The '(' could either be the start of:
1212     //
1213     //   direct-declarator:
1214     //     '(' declarator ')'
1215     //
1216     //   direct-abstract-declarator:
1217     //     '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1218     //              exception-specification[opt]
1219     //     '(' abstract-declarator ')'
1220     //
1221     // or part of a function-style cast expression:
1222     //
1223     //     simple-type-specifier '(' expression-list[opt] ')'
1224     //
1225
1226     // simple-type-specifier:
1227
1228   case tok::annot_typename:
1229   case_typename:
1230     // In Objective-C, we might have a protocol-qualified type.
1231     if (getLangOpts().ObjC1 && NextToken().is(tok::less)) {
1232       // Tentatively parse the 
1233       TentativeParsingAction PA(*this);
1234       ConsumeToken(); // The type token
1235       
1236       TPResult TPR = TryParseProtocolQualifiers();
1237       bool isFollowedByParen = Tok.is(tok::l_paren);
1238       bool isFollowedByBrace = Tok.is(tok::l_brace);
1239       
1240       PA.Revert();
1241       
1242       if (TPR == TPResult::Error())
1243         return TPResult::Error();
1244       
1245       if (isFollowedByParen)
1246         return TPResult::Ambiguous();
1247
1248       if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1249         return BracedCastResult;
1250       
1251       return TPResult::True();
1252     }
1253       
1254   case tok::kw_char:
1255   case tok::kw_wchar_t:
1256   case tok::kw_char16_t:
1257   case tok::kw_char32_t:
1258   case tok::kw_bool:
1259   case tok::kw_short:
1260   case tok::kw_int:
1261   case tok::kw_long:
1262   case tok::kw___int64:
1263   case tok::kw___int128:
1264   case tok::kw_signed:
1265   case tok::kw_unsigned:
1266   case tok::kw_half:
1267   case tok::kw_float:
1268   case tok::kw_double:
1269   case tok::kw_void:
1270   case tok::annot_decltype:
1271     if (NextToken().is(tok::l_paren))
1272       return TPResult::Ambiguous();
1273
1274     // This is a function-style cast in all cases we disambiguate other than
1275     // one:
1276     //   struct S {
1277     //     enum E : int { a = 4 }; // enum
1278     //     enum E : int { 4 };     // bit-field
1279     //   };
1280     if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
1281       return BracedCastResult;
1282
1283     if (isStartOfObjCClassMessageMissingOpenBracket())
1284       return TPResult::False();
1285       
1286     return TPResult::True();
1287
1288   // GNU typeof support.
1289   case tok::kw_typeof: {
1290     if (NextToken().isNot(tok::l_paren))
1291       return TPResult::True();
1292
1293     TentativeParsingAction PA(*this);
1294
1295     TPResult TPR = TryParseTypeofSpecifier();
1296     bool isFollowedByParen = Tok.is(tok::l_paren);
1297     bool isFollowedByBrace = Tok.is(tok::l_brace);
1298
1299     PA.Revert();
1300
1301     if (TPR == TPResult::Error())
1302       return TPResult::Error();
1303
1304     if (isFollowedByParen)
1305       return TPResult::Ambiguous();
1306
1307     if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1308       return BracedCastResult;
1309
1310     return TPResult::True();
1311   }
1312
1313   // C++0x type traits support
1314   case tok::kw___underlying_type:
1315     return TPResult::True();
1316
1317   // C11 _Atomic
1318   case tok::kw__Atomic:
1319     return TPResult::True();
1320
1321   default:
1322     return TPResult::False();
1323   }
1324 }
1325
1326 /// [GNU] typeof-specifier:
1327 ///         'typeof' '(' expressions ')'
1328 ///         'typeof' '(' type-name ')'
1329 ///
1330 Parser::TPResult Parser::TryParseTypeofSpecifier() {
1331   assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
1332   ConsumeToken();
1333
1334   assert(Tok.is(tok::l_paren) && "Expected '('");
1335   // Parse through the parens after 'typeof'.
1336   ConsumeParen();
1337   if (!SkipUntil(tok::r_paren))
1338     return TPResult::Error();
1339
1340   return TPResult::Ambiguous();
1341 }
1342
1343 /// [ObjC] protocol-qualifiers:
1344 ////         '<' identifier-list '>'
1345 Parser::TPResult Parser::TryParseProtocolQualifiers() {
1346   assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1347   ConsumeToken();
1348   do {
1349     if (Tok.isNot(tok::identifier))
1350       return TPResult::Error();
1351     ConsumeToken();
1352     
1353     if (Tok.is(tok::comma)) {
1354       ConsumeToken();
1355       continue;
1356     }
1357     
1358     if (Tok.is(tok::greater)) {
1359       ConsumeToken();
1360       return TPResult::Ambiguous();
1361     }
1362   } while (false);
1363   
1364   return TPResult::Error();
1365 }
1366
1367 Parser::TPResult
1368 Parser::TryParseDeclarationSpecifier(bool *HasMissingTypename) {
1369   TPResult TPR = isCXXDeclarationSpecifier(TPResult::False(),
1370                                            HasMissingTypename);
1371   if (TPR != TPResult::Ambiguous())
1372     return TPR;
1373
1374   if (Tok.is(tok::kw_typeof))
1375     TryParseTypeofSpecifier();
1376   else {
1377     if (Tok.is(tok::annot_cxxscope))
1378       ConsumeToken();
1379     ConsumeToken();
1380     
1381     if (getLangOpts().ObjC1 && Tok.is(tok::less))
1382       TryParseProtocolQualifiers();
1383   }
1384
1385   return TPResult::Ambiguous();
1386 }
1387
1388 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1389 /// a constructor-style initializer, when parsing declaration statements.
1390 /// Returns true for function declarator and false for constructor-style
1391 /// initializer.
1392 /// If during the disambiguation process a parsing error is encountered,
1393 /// the function returns true to let the declaration parsing code handle it.
1394 ///
1395 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1396 ///         exception-specification[opt]
1397 ///
1398 bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
1399
1400   // C++ 8.2p1:
1401   // The ambiguity arising from the similarity between a function-style cast and
1402   // a declaration mentioned in 6.8 can also occur in the context of a
1403   // declaration. In that context, the choice is between a function declaration
1404   // with a redundant set of parentheses around a parameter name and an object
1405   // declaration with a function-style cast as the initializer. Just as for the
1406   // ambiguities mentioned in 6.8, the resolution is to consider any construct
1407   // that could possibly be a declaration a declaration.
1408
1409   TentativeParsingAction PA(*this);
1410
1411   ConsumeParen();
1412   bool InvalidAsDeclaration = false;
1413   TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
1414   if (TPR == TPResult::Ambiguous()) {
1415     if (Tok.isNot(tok::r_paren))
1416       TPR = TPResult::False();
1417     else {
1418       const Token &Next = NextToken();
1419       if (Next.is(tok::amp) || Next.is(tok::ampamp) ||
1420           Next.is(tok::kw_const) || Next.is(tok::kw_volatile) ||
1421           Next.is(tok::kw_throw) || Next.is(tok::kw_noexcept) ||
1422           Next.is(tok::l_square) || isCXX11VirtSpecifier(Next) ||
1423           Next.is(tok::l_brace) || Next.is(tok::kw_try) ||
1424           Next.is(tok::equal) || Next.is(tok::arrow))
1425         // The next token cannot appear after a constructor-style initializer,
1426         // and can appear next in a function definition. This must be a function
1427         // declarator.
1428         TPR = TPResult::True();
1429       else if (InvalidAsDeclaration)
1430         // Use the absence of 'typename' as a tie-breaker.
1431         TPR = TPResult::False();
1432     }
1433   }
1434
1435   PA.Revert();
1436
1437   if (IsAmbiguous && TPR == TPResult::Ambiguous())
1438     *IsAmbiguous = true;
1439
1440   // In case of an error, let the declaration parsing code handle it.
1441   return TPR != TPResult::False();
1442 }
1443
1444 /// parameter-declaration-clause:
1445 ///   parameter-declaration-list[opt] '...'[opt]
1446 ///   parameter-declaration-list ',' '...'
1447 ///
1448 /// parameter-declaration-list:
1449 ///   parameter-declaration
1450 ///   parameter-declaration-list ',' parameter-declaration
1451 ///
1452 /// parameter-declaration:
1453 ///   attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1454 ///   attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1455 ///     '=' assignment-expression
1456 ///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1457 ///     attributes[opt]
1458 ///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1459 ///     attributes[opt] '=' assignment-expression
1460 ///
1461 Parser::TPResult
1462 Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration) {
1463
1464   if (Tok.is(tok::r_paren))
1465     return TPResult::Ambiguous();
1466
1467   //   parameter-declaration-list[opt] '...'[opt]
1468   //   parameter-declaration-list ',' '...'
1469   //
1470   // parameter-declaration-list:
1471   //   parameter-declaration
1472   //   parameter-declaration-list ',' parameter-declaration
1473   //
1474   while (1) {
1475     // '...'[opt]
1476     if (Tok.is(tok::ellipsis)) {
1477       ConsumeToken();
1478       if (Tok.is(tok::r_paren))
1479         return TPResult::True(); // '...)' is a sign of a function declarator.
1480       else
1481         return TPResult::False();
1482     }
1483
1484     // An attribute-specifier-seq here is a sign of a function declarator.
1485     if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
1486                                   /*OuterMightBeMessageSend*/true))
1487       return TPResult::True();
1488
1489     ParsedAttributes attrs(AttrFactory);
1490     MaybeParseMicrosoftAttributes(attrs);
1491
1492     // decl-specifier-seq
1493     // A parameter-declaration's initializer must be preceded by an '=', so
1494     // decl-specifier-seq '{' is not a parameter in C++11.
1495     TPResult TPR = TryParseDeclarationSpecifier(InvalidAsDeclaration);
1496     if (TPR != TPResult::Ambiguous())
1497       return TPR;
1498
1499     // declarator
1500     // abstract-declarator[opt]
1501     TPR = TryParseDeclarator(true/*mayBeAbstract*/);
1502     if (TPR != TPResult::Ambiguous())
1503       return TPR;
1504
1505     // [GNU] attributes[opt]
1506     if (Tok.is(tok::kw___attribute))
1507       return TPResult::True();
1508
1509     if (Tok.is(tok::equal)) {
1510       // '=' assignment-expression
1511       // Parse through assignment-expression.
1512       if (!SkipUntil(tok::comma, tok::r_paren, true/*StopAtSemi*/,
1513                      true/*DontConsume*/))
1514         return TPResult::Error();
1515     }
1516
1517     if (Tok.is(tok::ellipsis)) {
1518       ConsumeToken();
1519       if (Tok.is(tok::r_paren))
1520         return TPResult::True(); // '...)' is a sign of a function declarator.
1521       else
1522         return TPResult::False();
1523     }
1524
1525     if (Tok.isNot(tok::comma))
1526       break;
1527     ConsumeToken(); // the comma.
1528   }
1529
1530   return TPResult::Ambiguous();
1531 }
1532
1533 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
1534 /// parsing as a function declarator.
1535 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
1536 /// return TPResult::Ambiguous(), otherwise it will return either False() or
1537 /// Error().
1538 ///
1539 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1540 ///         exception-specification[opt]
1541 ///
1542 /// exception-specification:
1543 ///   'throw' '(' type-id-list[opt] ')'
1544 ///
1545 Parser::TPResult Parser::TryParseFunctionDeclarator() {
1546
1547   // The '(' is already parsed.
1548
1549   TPResult TPR = TryParseParameterDeclarationClause();
1550   if (TPR == TPResult::Ambiguous() && Tok.isNot(tok::r_paren))
1551     TPR = TPResult::False();
1552
1553   if (TPR == TPResult::False() || TPR == TPResult::Error())
1554     return TPR;
1555
1556   // Parse through the parens.
1557   if (!SkipUntil(tok::r_paren))
1558     return TPResult::Error();
1559
1560   // cv-qualifier-seq
1561   while (Tok.is(tok::kw_const)    ||
1562          Tok.is(tok::kw_volatile) ||
1563          Tok.is(tok::kw_restrict)   )
1564     ConsumeToken();
1565
1566   // ref-qualifier[opt]
1567   if (Tok.is(tok::amp) || Tok.is(tok::ampamp))
1568     ConsumeToken();
1569   
1570   // exception-specification
1571   if (Tok.is(tok::kw_throw)) {
1572     ConsumeToken();
1573     if (Tok.isNot(tok::l_paren))
1574       return TPResult::Error();
1575
1576     // Parse through the parens after 'throw'.
1577     ConsumeParen();
1578     if (!SkipUntil(tok::r_paren))
1579       return TPResult::Error();
1580   }
1581   if (Tok.is(tok::kw_noexcept)) {
1582     ConsumeToken();
1583     // Possibly an expression as well.
1584     if (Tok.is(tok::l_paren)) {
1585       // Find the matching rparen.
1586       ConsumeParen();
1587       if (!SkipUntil(tok::r_paren))
1588         return TPResult::Error();
1589     }
1590   }
1591
1592   return TPResult::Ambiguous();
1593 }
1594
1595 /// '[' constant-expression[opt] ']'
1596 ///
1597 Parser::TPResult Parser::TryParseBracketDeclarator() {
1598   ConsumeBracket();
1599   if (!SkipUntil(tok::r_square))
1600     return TPResult::Error();
1601
1602   return TPResult::Ambiguous();
1603 }