blob: 5e0ef2b83f67ed87b4a18f4776741aca54dbe451 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- 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"
18using 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///
50bool 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
82bool 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///
153Parser::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
Richard Smith22c7c412013-03-20 03:35:02 +0000187/// Tentatively parse an init-declarator-list in order to disambiguate it from
188/// an expression.
189///
Guy Benyei11169dd2012-12-18 14:30:41 +0000190/// 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///
Richard Smith22c7c412013-03-20 03:35:02 +0000198/// initializer:
199/// brace-or-equal-initializer
200/// '(' expression-list ')'
Guy Benyei11169dd2012-12-18 14:30:41 +0000201///
Richard Smith22c7c412013-03-20 03:35:02 +0000202/// 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/// '{' '}'
Guy Benyei11169dd2012-12-18 14:30:41 +0000213///
214Parser::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();
Richard Smith22c7c412013-03-20 03:35:02 +0000231 } 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();
Guy Benyei11169dd2012-12-18 14:30:41 +0000235 } 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///
274bool 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();
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000312 else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
Guy Benyei11169dd2012-12-18 14:30:41 +0000313 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 ///
341bool 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) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000396 (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater)))) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000397 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 ')'
443Parser::CXX11AttributeKind
444Parser::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///
623Parser::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
731Parser::TPResult
732Parser::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_thread_local:
841 case tok::kw__Decimal32:
842 case tok::kw__Decimal64:
843 case tok::kw__Decimal128:
844 case tok::kw___thread:
845 case tok::kw_typeof:
846 case tok::kw___cdecl:
847 case tok::kw___stdcall:
848 case tok::kw___fastcall:
849 case tok::kw___thiscall:
850 case tok::kw___unaligned:
851 case tok::kw___vector:
852 case tok::kw___pixel:
853 case tok::kw__Atomic:
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000854 case tok::kw_image1d_t:
855 case tok::kw_image1d_array_t:
856 case tok::kw_image1d_buffer_t:
857 case tok::kw_image2d_t:
858 case tok::kw_image2d_array_t:
859 case tok::kw_image3d_t:
Guy Benyei61054192013-02-07 10:55:47 +0000860 case tok::kw_sampler_t:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000861 case tok::kw_event_t:
Guy Benyei11169dd2012-12-18 14:30:41 +0000862 case tok::kw___unknown_anytype:
863 return TPResult::False();
864
865 default:
866 break;
867 }
868
869 return TPResult::Ambiguous();
870}
871
872bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
873 return std::find(TentativelyDeclaredIdentifiers.begin(),
874 TentativelyDeclaredIdentifiers.end(), II)
875 != TentativelyDeclaredIdentifiers.end();
876}
877
878/// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a declaration
879/// specifier, TPResult::False() if it is not, TPResult::Ambiguous() if it could
880/// be either a decl-specifier or a function-style cast, and TPResult::Error()
881/// if a parsing error was found and reported.
882///
883/// If HasMissingTypename is provided, a name with a dependent scope specifier
884/// will be treated as ambiguous if the 'typename' keyword is missing. If this
885/// happens, *HasMissingTypename will be set to 'true'. This will also be used
886/// as an indicator that undeclared identifiers (which will trigger a later
887/// parse error) should be treated as types. Returns TPResult::Ambiguous() in
888/// such cases.
889///
890/// decl-specifier:
891/// storage-class-specifier
892/// type-specifier
893/// function-specifier
894/// 'friend'
895/// 'typedef'
896/// [C++0x] 'constexpr'
897/// [GNU] attributes declaration-specifiers[opt]
898///
899/// storage-class-specifier:
900/// 'register'
901/// 'static'
902/// 'extern'
903/// 'mutable'
904/// 'auto'
905/// [GNU] '__thread'
906///
907/// function-specifier:
908/// 'inline'
909/// 'virtual'
910/// 'explicit'
911///
912/// typedef-name:
913/// identifier
914///
915/// type-specifier:
916/// simple-type-specifier
917/// class-specifier
918/// enum-specifier
919/// elaborated-type-specifier
920/// typename-specifier
921/// cv-qualifier
922///
923/// simple-type-specifier:
924/// '::'[opt] nested-name-specifier[opt] type-name
925/// '::'[opt] nested-name-specifier 'template'
926/// simple-template-id [TODO]
927/// 'char'
928/// 'wchar_t'
929/// 'bool'
930/// 'short'
931/// 'int'
932/// 'long'
933/// 'signed'
934/// 'unsigned'
935/// 'float'
936/// 'double'
937/// 'void'
938/// [GNU] typeof-specifier
939/// [GNU] '_Complex'
940/// [C++0x] 'auto' [TODO]
941/// [C++0x] 'decltype' ( expression )
942///
943/// type-name:
944/// class-name
945/// enum-name
946/// typedef-name
947///
948/// elaborated-type-specifier:
949/// class-key '::'[opt] nested-name-specifier[opt] identifier
950/// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
951/// simple-template-id
952/// 'enum' '::'[opt] nested-name-specifier[opt] identifier
953///
954/// enum-name:
955/// identifier
956///
957/// enum-specifier:
958/// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
959/// 'enum' identifier[opt] '{' enumerator-list ',' '}'
960///
961/// class-specifier:
962/// class-head '{' member-specification[opt] '}'
963///
964/// class-head:
965/// class-key identifier[opt] base-clause[opt]
966/// class-key nested-name-specifier identifier base-clause[opt]
967/// class-key nested-name-specifier[opt] simple-template-id
968/// base-clause[opt]
969///
970/// class-key:
971/// 'class'
972/// 'struct'
973/// 'union'
974///
975/// cv-qualifier:
976/// 'const'
977/// 'volatile'
978/// [GNU] restrict
979///
980Parser::TPResult
981Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
982 bool *HasMissingTypename) {
983 switch (Tok.getKind()) {
984 case tok::identifier: {
985 // Check for need to substitute AltiVec __vector keyword
986 // for "vector" identifier.
987 if (TryAltiVecVectorToken())
988 return TPResult::True();
989
990 const Token &Next = NextToken();
991 // In 'foo bar', 'foo' is always a type name outside of Objective-C.
992 if (!getLangOpts().ObjC1 && Next.is(tok::identifier))
993 return TPResult::True();
994
995 if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
996 // Determine whether this is a valid expression. If not, we will hit
997 // a parse error one way or another. In that case, tell the caller that
998 // this is ambiguous. Typo-correct to type and expression keywords and
999 // to types and identifiers, in order to try to recover from errors.
1000 CorrectionCandidateCallback TypoCorrection;
1001 TypoCorrection.WantRemainingKeywords = false;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00001002 TypoCorrection.WantTypeSpecifiers = Next.isNot(tok::arrow);
Guy Benyei11169dd2012-12-18 14:30:41 +00001003 switch (TryAnnotateName(false /* no nested name specifier */,
1004 &TypoCorrection)) {
1005 case ANK_Error:
1006 return TPResult::Error();
1007 case ANK_TentativeDecl:
1008 return TPResult::False();
1009 case ANK_TemplateName:
1010 // A bare type template-name which can't be a template template
1011 // argument is an error, and was probably intended to be a type.
1012 return GreaterThanIsOperator ? TPResult::True() : TPResult::False();
1013 case ANK_Unresolved:
1014 return HasMissingTypename ? TPResult::Ambiguous() : TPResult::False();
1015 case ANK_Success:
1016 break;
1017 }
1018 assert(Tok.isNot(tok::identifier) &&
1019 "TryAnnotateName succeeded without producing an annotation");
1020 } else {
1021 // This might possibly be a type with a dependent scope specifier and
1022 // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
1023 // since it will annotate as a primary expression, and we want to use the
1024 // "missing 'typename'" logic.
1025 if (TryAnnotateTypeOrScopeToken())
1026 return TPResult::Error();
1027 // If annotation failed, assume it's a non-type.
1028 // FIXME: If this happens due to an undeclared identifier, treat it as
1029 // ambiguous.
1030 if (Tok.is(tok::identifier))
1031 return TPResult::False();
1032 }
1033
1034 // We annotated this token as something. Recurse to handle whatever we got.
1035 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1036 }
1037
1038 case tok::kw_typename: // typename T::type
1039 // Annotate typenames and C++ scope specifiers. If we get one, just
1040 // recurse to handle whatever we get.
1041 if (TryAnnotateTypeOrScopeToken())
1042 return TPResult::Error();
1043 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1044
1045 case tok::coloncolon: { // ::foo::bar
1046 const Token &Next = NextToken();
1047 if (Next.is(tok::kw_new) || // ::new
1048 Next.is(tok::kw_delete)) // ::delete
1049 return TPResult::False();
1050 }
1051 // Fall through.
1052 case tok::kw_decltype:
1053 // Annotate typenames and C++ scope specifiers. If we get one, just
1054 // recurse to handle whatever we get.
1055 if (TryAnnotateTypeOrScopeToken())
1056 return TPResult::Error();
1057 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1058
1059 // decl-specifier:
1060 // storage-class-specifier
1061 // type-specifier
1062 // function-specifier
1063 // 'friend'
1064 // 'typedef'
1065 // 'constexpr'
1066 case tok::kw_friend:
1067 case tok::kw_typedef:
1068 case tok::kw_constexpr:
1069 // storage-class-specifier
1070 case tok::kw_register:
1071 case tok::kw_static:
1072 case tok::kw_extern:
1073 case tok::kw_mutable:
1074 case tok::kw_auto:
1075 case tok::kw___thread:
1076 // function-specifier
1077 case tok::kw_inline:
1078 case tok::kw_virtual:
1079 case tok::kw_explicit:
1080
1081 // Modules
1082 case tok::kw___module_private__:
1083
1084 // Debugger support
1085 case tok::kw___unknown_anytype:
1086
1087 // type-specifier:
1088 // simple-type-specifier
1089 // class-specifier
1090 // enum-specifier
1091 // elaborated-type-specifier
1092 // typename-specifier
1093 // cv-qualifier
1094
1095 // class-specifier
1096 // elaborated-type-specifier
1097 case tok::kw_class:
1098 case tok::kw_struct:
1099 case tok::kw_union:
1100 // enum-specifier
1101 case tok::kw_enum:
1102 // cv-qualifier
1103 case tok::kw_const:
1104 case tok::kw_volatile:
1105
1106 // GNU
1107 case tok::kw_restrict:
1108 case tok::kw__Complex:
1109 case tok::kw___attribute:
1110 return TPResult::True();
1111
1112 // Microsoft
1113 case tok::kw___declspec:
1114 case tok::kw___cdecl:
1115 case tok::kw___stdcall:
1116 case tok::kw___fastcall:
1117 case tok::kw___thiscall:
1118 case tok::kw___w64:
1119 case tok::kw___ptr64:
1120 case tok::kw___ptr32:
1121 case tok::kw___forceinline:
1122 case tok::kw___unaligned:
1123 return TPResult::True();
1124
1125 // Borland
1126 case tok::kw___pascal:
1127 return TPResult::True();
1128
1129 // AltiVec
1130 case tok::kw___vector:
1131 return TPResult::True();
1132
1133 case tok::annot_template_id: {
1134 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1135 if (TemplateId->Kind != TNK_Type_template)
1136 return TPResult::False();
1137 CXXScopeSpec SS;
1138 AnnotateTemplateIdTokenAsType();
1139 assert(Tok.is(tok::annot_typename));
1140 goto case_typename;
1141 }
1142
1143 case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
1144 // We've already annotated a scope; try to annotate a type.
1145 if (TryAnnotateTypeOrScopeToken())
1146 return TPResult::Error();
1147 if (!Tok.is(tok::annot_typename)) {
1148 // If the next token is an identifier or a type qualifier, then this
1149 // can't possibly be a valid expression either.
1150 if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
1151 CXXScopeSpec SS;
1152 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1153 Tok.getAnnotationRange(),
1154 SS);
1155 if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
1156 TentativeParsingAction PA(*this);
1157 ConsumeToken();
1158 ConsumeToken();
1159 bool isIdentifier = Tok.is(tok::identifier);
1160 TPResult TPR = TPResult::False();
1161 if (!isIdentifier)
1162 TPR = isCXXDeclarationSpecifier(BracedCastResult,
1163 HasMissingTypename);
1164 PA.Revert();
1165
1166 if (isIdentifier ||
1167 TPR == TPResult::True() || TPR == TPResult::Error())
1168 return TPResult::Error();
1169
1170 if (HasMissingTypename) {
1171 // We can't tell whether this is a missing 'typename' or a valid
1172 // expression.
1173 *HasMissingTypename = true;
1174 return TPResult::Ambiguous();
1175 }
1176 } else {
1177 // Try to resolve the name. If it doesn't exist, assume it was
1178 // intended to name a type and keep disambiguating.
1179 switch (TryAnnotateName(false /* SS is not dependent */)) {
1180 case ANK_Error:
1181 return TPResult::Error();
1182 case ANK_TentativeDecl:
1183 return TPResult::False();
1184 case ANK_TemplateName:
1185 // A bare type template-name which can't be a template template
1186 // argument is an error, and was probably intended to be a type.
1187 return GreaterThanIsOperator ? TPResult::True() : TPResult::False();
1188 case ANK_Unresolved:
1189 return HasMissingTypename ? TPResult::Ambiguous()
1190 : TPResult::False();
1191 case ANK_Success:
1192 // Annotated it, check again.
1193 assert(Tok.isNot(tok::annot_cxxscope) ||
1194 NextToken().isNot(tok::identifier));
1195 return isCXXDeclarationSpecifier(BracedCastResult,
1196 HasMissingTypename);
1197 }
1198 }
1199 }
1200 return TPResult::False();
1201 }
1202 // If that succeeded, fallthrough into the generic simple-type-id case.
1203
1204 // The ambiguity resides in a simple-type-specifier/typename-specifier
1205 // followed by a '('. The '(' could either be the start of:
1206 //
1207 // direct-declarator:
1208 // '(' declarator ')'
1209 //
1210 // direct-abstract-declarator:
1211 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1212 // exception-specification[opt]
1213 // '(' abstract-declarator ')'
1214 //
1215 // or part of a function-style cast expression:
1216 //
1217 // simple-type-specifier '(' expression-list[opt] ')'
1218 //
1219
1220 // simple-type-specifier:
1221
1222 case tok::annot_typename:
1223 case_typename:
1224 // In Objective-C, we might have a protocol-qualified type.
1225 if (getLangOpts().ObjC1 && NextToken().is(tok::less)) {
1226 // Tentatively parse the
1227 TentativeParsingAction PA(*this);
1228 ConsumeToken(); // The type token
1229
1230 TPResult TPR = TryParseProtocolQualifiers();
1231 bool isFollowedByParen = Tok.is(tok::l_paren);
1232 bool isFollowedByBrace = Tok.is(tok::l_brace);
1233
1234 PA.Revert();
1235
1236 if (TPR == TPResult::Error())
1237 return TPResult::Error();
1238
1239 if (isFollowedByParen)
1240 return TPResult::Ambiguous();
1241
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001242 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
Guy Benyei11169dd2012-12-18 14:30:41 +00001243 return BracedCastResult;
1244
1245 return TPResult::True();
1246 }
1247
1248 case tok::kw_char:
1249 case tok::kw_wchar_t:
1250 case tok::kw_char16_t:
1251 case tok::kw_char32_t:
1252 case tok::kw_bool:
1253 case tok::kw_short:
1254 case tok::kw_int:
1255 case tok::kw_long:
1256 case tok::kw___int64:
1257 case tok::kw___int128:
1258 case tok::kw_signed:
1259 case tok::kw_unsigned:
1260 case tok::kw_half:
1261 case tok::kw_float:
1262 case tok::kw_double:
1263 case tok::kw_void:
1264 case tok::annot_decltype:
1265 if (NextToken().is(tok::l_paren))
1266 return TPResult::Ambiguous();
1267
1268 // This is a function-style cast in all cases we disambiguate other than
1269 // one:
1270 // struct S {
1271 // enum E : int { a = 4 }; // enum
1272 // enum E : int { 4 }; // bit-field
1273 // };
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001274 if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
Guy Benyei11169dd2012-12-18 14:30:41 +00001275 return BracedCastResult;
1276
1277 if (isStartOfObjCClassMessageMissingOpenBracket())
1278 return TPResult::False();
1279
1280 return TPResult::True();
1281
1282 // GNU typeof support.
1283 case tok::kw_typeof: {
1284 if (NextToken().isNot(tok::l_paren))
1285 return TPResult::True();
1286
1287 TentativeParsingAction PA(*this);
1288
1289 TPResult TPR = TryParseTypeofSpecifier();
1290 bool isFollowedByParen = Tok.is(tok::l_paren);
1291 bool isFollowedByBrace = Tok.is(tok::l_brace);
1292
1293 PA.Revert();
1294
1295 if (TPR == TPResult::Error())
1296 return TPResult::Error();
1297
1298 if (isFollowedByParen)
1299 return TPResult::Ambiguous();
1300
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001301 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
Guy Benyei11169dd2012-12-18 14:30:41 +00001302 return BracedCastResult;
1303
1304 return TPResult::True();
1305 }
1306
1307 // C++0x type traits support
1308 case tok::kw___underlying_type:
1309 return TPResult::True();
1310
1311 // C11 _Atomic
1312 case tok::kw__Atomic:
1313 return TPResult::True();
1314
1315 default:
1316 return TPResult::False();
1317 }
1318}
1319
1320/// [GNU] typeof-specifier:
1321/// 'typeof' '(' expressions ')'
1322/// 'typeof' '(' type-name ')'
1323///
1324Parser::TPResult Parser::TryParseTypeofSpecifier() {
1325 assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
1326 ConsumeToken();
1327
1328 assert(Tok.is(tok::l_paren) && "Expected '('");
1329 // Parse through the parens after 'typeof'.
1330 ConsumeParen();
1331 if (!SkipUntil(tok::r_paren))
1332 return TPResult::Error();
1333
1334 return TPResult::Ambiguous();
1335}
1336
1337/// [ObjC] protocol-qualifiers:
1338//// '<' identifier-list '>'
1339Parser::TPResult Parser::TryParseProtocolQualifiers() {
1340 assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1341 ConsumeToken();
1342 do {
1343 if (Tok.isNot(tok::identifier))
1344 return TPResult::Error();
1345 ConsumeToken();
1346
1347 if (Tok.is(tok::comma)) {
1348 ConsumeToken();
1349 continue;
1350 }
1351
1352 if (Tok.is(tok::greater)) {
1353 ConsumeToken();
1354 return TPResult::Ambiguous();
1355 }
1356 } while (false);
1357
1358 return TPResult::Error();
1359}
1360
1361Parser::TPResult
1362Parser::TryParseDeclarationSpecifier(bool *HasMissingTypename) {
1363 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False(),
1364 HasMissingTypename);
1365 if (TPR != TPResult::Ambiguous())
1366 return TPR;
1367
1368 if (Tok.is(tok::kw_typeof))
1369 TryParseTypeofSpecifier();
1370 else {
1371 if (Tok.is(tok::annot_cxxscope))
1372 ConsumeToken();
1373 ConsumeToken();
1374
1375 if (getLangOpts().ObjC1 && Tok.is(tok::less))
1376 TryParseProtocolQualifiers();
1377 }
1378
1379 return TPResult::Ambiguous();
1380}
1381
1382/// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1383/// a constructor-style initializer, when parsing declaration statements.
1384/// Returns true for function declarator and false for constructor-style
1385/// initializer.
1386/// If during the disambiguation process a parsing error is encountered,
1387/// the function returns true to let the declaration parsing code handle it.
1388///
1389/// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1390/// exception-specification[opt]
1391///
1392bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
1393
1394 // C++ 8.2p1:
1395 // The ambiguity arising from the similarity between a function-style cast and
1396 // a declaration mentioned in 6.8 can also occur in the context of a
1397 // declaration. In that context, the choice is between a function declaration
1398 // with a redundant set of parentheses around a parameter name and an object
1399 // declaration with a function-style cast as the initializer. Just as for the
1400 // ambiguities mentioned in 6.8, the resolution is to consider any construct
1401 // that could possibly be a declaration a declaration.
1402
1403 TentativeParsingAction PA(*this);
1404
1405 ConsumeParen();
1406 bool InvalidAsDeclaration = false;
1407 TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
1408 if (TPR == TPResult::Ambiguous()) {
1409 if (Tok.isNot(tok::r_paren))
1410 TPR = TPResult::False();
1411 else {
1412 const Token &Next = NextToken();
1413 if (Next.is(tok::amp) || Next.is(tok::ampamp) ||
1414 Next.is(tok::kw_const) || Next.is(tok::kw_volatile) ||
1415 Next.is(tok::kw_throw) || Next.is(tok::kw_noexcept) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001416 Next.is(tok::l_square) || isCXX11VirtSpecifier(Next) ||
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 Next.is(tok::l_brace) || Next.is(tok::kw_try) ||
1418 Next.is(tok::equal) || Next.is(tok::arrow))
1419 // The next token cannot appear after a constructor-style initializer,
1420 // and can appear next in a function definition. This must be a function
1421 // declarator.
1422 TPR = TPResult::True();
1423 else if (InvalidAsDeclaration)
1424 // Use the absence of 'typename' as a tie-breaker.
1425 TPR = TPResult::False();
1426 }
1427 }
1428
1429 PA.Revert();
1430
1431 if (IsAmbiguous && TPR == TPResult::Ambiguous())
1432 *IsAmbiguous = true;
1433
1434 // In case of an error, let the declaration parsing code handle it.
1435 return TPR != TPResult::False();
1436}
1437
1438/// parameter-declaration-clause:
1439/// parameter-declaration-list[opt] '...'[opt]
1440/// parameter-declaration-list ',' '...'
1441///
1442/// parameter-declaration-list:
1443/// parameter-declaration
1444/// parameter-declaration-list ',' parameter-declaration
1445///
1446/// parameter-declaration:
1447/// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1448/// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1449/// '=' assignment-expression
1450/// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1451/// attributes[opt]
1452/// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1453/// attributes[opt] '=' assignment-expression
1454///
1455Parser::TPResult
1456Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration) {
1457
1458 if (Tok.is(tok::r_paren))
1459 return TPResult::Ambiguous();
1460
1461 // parameter-declaration-list[opt] '...'[opt]
1462 // parameter-declaration-list ',' '...'
1463 //
1464 // parameter-declaration-list:
1465 // parameter-declaration
1466 // parameter-declaration-list ',' parameter-declaration
1467 //
1468 while (1) {
1469 // '...'[opt]
1470 if (Tok.is(tok::ellipsis)) {
1471 ConsumeToken();
1472 if (Tok.is(tok::r_paren))
1473 return TPResult::True(); // '...)' is a sign of a function declarator.
1474 else
1475 return TPResult::False();
1476 }
1477
1478 // An attribute-specifier-seq here is a sign of a function declarator.
1479 if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
1480 /*OuterMightBeMessageSend*/true))
1481 return TPResult::True();
1482
1483 ParsedAttributes attrs(AttrFactory);
1484 MaybeParseMicrosoftAttributes(attrs);
1485
1486 // decl-specifier-seq
1487 // A parameter-declaration's initializer must be preceded by an '=', so
1488 // decl-specifier-seq '{' is not a parameter in C++11.
1489 TPResult TPR = TryParseDeclarationSpecifier(InvalidAsDeclaration);
1490 if (TPR != TPResult::Ambiguous())
1491 return TPR;
1492
1493 // declarator
1494 // abstract-declarator[opt]
1495 TPR = TryParseDeclarator(true/*mayBeAbstract*/);
1496 if (TPR != TPResult::Ambiguous())
1497 return TPR;
1498
1499 // [GNU] attributes[opt]
1500 if (Tok.is(tok::kw___attribute))
1501 return TPResult::True();
1502
1503 if (Tok.is(tok::equal)) {
1504 // '=' assignment-expression
1505 // Parse through assignment-expression.
1506 if (!SkipUntil(tok::comma, tok::r_paren, true/*StopAtSemi*/,
1507 true/*DontConsume*/))
1508 return TPResult::Error();
1509 }
1510
1511 if (Tok.is(tok::ellipsis)) {
1512 ConsumeToken();
1513 if (Tok.is(tok::r_paren))
1514 return TPResult::True(); // '...)' is a sign of a function declarator.
1515 else
1516 return TPResult::False();
1517 }
1518
1519 if (Tok.isNot(tok::comma))
1520 break;
1521 ConsumeToken(); // the comma.
1522 }
1523
1524 return TPResult::Ambiguous();
1525}
1526
1527/// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
1528/// parsing as a function declarator.
1529/// If TryParseFunctionDeclarator fully parsed the function declarator, it will
1530/// return TPResult::Ambiguous(), otherwise it will return either False() or
1531/// Error().
1532///
1533/// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1534/// exception-specification[opt]
1535///
1536/// exception-specification:
1537/// 'throw' '(' type-id-list[opt] ')'
1538///
1539Parser::TPResult Parser::TryParseFunctionDeclarator() {
1540
1541 // The '(' is already parsed.
1542
1543 TPResult TPR = TryParseParameterDeclarationClause();
1544 if (TPR == TPResult::Ambiguous() && Tok.isNot(tok::r_paren))
1545 TPR = TPResult::False();
1546
1547 if (TPR == TPResult::False() || TPR == TPResult::Error())
1548 return TPR;
1549
1550 // Parse through the parens.
1551 if (!SkipUntil(tok::r_paren))
1552 return TPResult::Error();
1553
1554 // cv-qualifier-seq
1555 while (Tok.is(tok::kw_const) ||
1556 Tok.is(tok::kw_volatile) ||
1557 Tok.is(tok::kw_restrict) )
1558 ConsumeToken();
1559
1560 // ref-qualifier[opt]
1561 if (Tok.is(tok::amp) || Tok.is(tok::ampamp))
1562 ConsumeToken();
1563
1564 // exception-specification
1565 if (Tok.is(tok::kw_throw)) {
1566 ConsumeToken();
1567 if (Tok.isNot(tok::l_paren))
1568 return TPResult::Error();
1569
1570 // Parse through the parens after 'throw'.
1571 ConsumeParen();
1572 if (!SkipUntil(tok::r_paren))
1573 return TPResult::Error();
1574 }
1575 if (Tok.is(tok::kw_noexcept)) {
1576 ConsumeToken();
1577 // Possibly an expression as well.
1578 if (Tok.is(tok::l_paren)) {
1579 // Find the matching rparen.
1580 ConsumeParen();
1581 if (!SkipUntil(tok::r_paren))
1582 return TPResult::Error();
1583 }
1584 }
1585
1586 return TPResult::Ambiguous();
1587}
1588
1589/// '[' constant-expression[opt] ']'
1590///
1591Parser::TPResult Parser::TryParseBracketDeclarator() {
1592 ConsumeBracket();
1593 if (!SkipUntil(tok::r_square))
1594 return TPResult::Error();
1595
1596 return TPResult::Ambiguous();
1597}