blob: 59118b0fd3f493a11f20a0eac5142a328d664826 [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
Richard Smith1fff95c2013-09-12 23:28:08 +0000145/// Try to consume a token sequence that we've already identified as
146/// (potentially) starting a decl-specifier.
147Parser::TPResult Parser::TryConsumeDeclarationSpecifier() {
148 switch (Tok.getKind()) {
149 case tok::kw__Atomic:
150 if (NextToken().isNot(tok::l_paren)) {
151 ConsumeToken();
152 break;
153 }
154 // Fall through.
155 case tok::kw_typeof:
156 case tok::kw___attribute:
157 case tok::kw___underlying_type: {
158 ConsumeToken();
159 if (Tok.isNot(tok::l_paren))
160 return TPResult::Error();
161 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000162 if (!SkipUntil(tok::r_paren))
Richard Smith1fff95c2013-09-12 23:28:08 +0000163 return TPResult::Error();
164 break;
165 }
166
167 case tok::kw_class:
168 case tok::kw_struct:
169 case tok::kw_union:
170 case tok::kw___interface:
171 case tok::kw_enum:
172 // elaborated-type-specifier:
173 // class-key attribute-specifier-seq[opt]
174 // nested-name-specifier[opt] identifier
175 // class-key nested-name-specifier[opt] template[opt] simple-template-id
176 // enum nested-name-specifier[opt] identifier
177 //
178 // FIXME: We don't support class-specifiers nor enum-specifiers here.
179 ConsumeToken();
180
181 // Skip attributes.
182 while (Tok.is(tok::l_square) || Tok.is(tok::kw___attribute) ||
183 Tok.is(tok::kw___declspec) || Tok.is(tok::kw_alignas)) {
184 if (Tok.is(tok::l_square)) {
185 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000186 if (!SkipUntil(tok::r_square))
Richard Smith1fff95c2013-09-12 23:28:08 +0000187 return TPResult::Error();
188 } else {
189 ConsumeToken();
190 if (Tok.isNot(tok::l_paren))
191 return TPResult::Error();
192 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000193 if (!SkipUntil(tok::r_paren))
Richard Smith1fff95c2013-09-12 23:28:08 +0000194 return TPResult::Error();
195 }
196 }
197
198 if (TryAnnotateCXXScopeToken())
199 return TPResult::Error();
200 if (Tok.is(tok::annot_cxxscope))
201 ConsumeToken();
202 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
203 return TPResult::Error();
204 ConsumeToken();
205 break;
206
207 case tok::annot_cxxscope:
208 ConsumeToken();
209 // Fall through.
210 default:
211 ConsumeToken();
212
213 if (getLangOpts().ObjC1 && Tok.is(tok::less))
214 return TryParseProtocolQualifiers();
215 break;
216 }
217
218 return TPResult::Ambiguous();
219}
220
Guy Benyei11169dd2012-12-18 14:30:41 +0000221/// simple-declaration:
222/// decl-specifier-seq init-declarator-list[opt] ';'
223///
224/// (if AllowForRangeDecl specified)
225/// for ( for-range-declaration : for-range-initializer ) statement
226/// for-range-declaration:
227/// attribute-specifier-seqopt type-specifier-seq declarator
228///
229Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) {
Richard Smith1fff95c2013-09-12 23:28:08 +0000230 if (TryConsumeDeclarationSpecifier() == TPResult::Error())
231 return TPResult::Error();
Guy Benyei11169dd2012-12-18 14:30:41 +0000232
233 // Two decl-specifiers in a row conclusively disambiguate this as being a
234 // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the
235 // overwhelmingly common case that the next token is a '('.
236 if (Tok.isNot(tok::l_paren)) {
237 TPResult TPR = isCXXDeclarationSpecifier();
238 if (TPR == TPResult::Ambiguous())
239 return TPResult::True();
240 if (TPR == TPResult::True() || TPR == TPResult::Error())
241 return TPR;
242 assert(TPR == TPResult::False());
243 }
244
245 TPResult TPR = TryParseInitDeclaratorList();
246 if (TPR != TPResult::Ambiguous())
247 return TPR;
248
249 if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon)))
250 return TPResult::False();
251
252 return TPResult::Ambiguous();
253}
254
Richard Smith22c7c412013-03-20 03:35:02 +0000255/// Tentatively parse an init-declarator-list in order to disambiguate it from
256/// an expression.
257///
Guy Benyei11169dd2012-12-18 14:30:41 +0000258/// init-declarator-list:
259/// init-declarator
260/// init-declarator-list ',' init-declarator
261///
262/// init-declarator:
263/// declarator initializer[opt]
264/// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
265///
Richard Smith22c7c412013-03-20 03:35:02 +0000266/// initializer:
267/// brace-or-equal-initializer
268/// '(' expression-list ')'
Guy Benyei11169dd2012-12-18 14:30:41 +0000269///
Richard Smith22c7c412013-03-20 03:35:02 +0000270/// brace-or-equal-initializer:
271/// '=' initializer-clause
272/// [C++11] braced-init-list
273///
274/// initializer-clause:
275/// assignment-expression
276/// braced-init-list
277///
278/// braced-init-list:
279/// '{' initializer-list ','[opt] '}'
280/// '{' '}'
Guy Benyei11169dd2012-12-18 14:30:41 +0000281///
282Parser::TPResult Parser::TryParseInitDeclaratorList() {
283 while (1) {
284 // declarator
285 TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
286 if (TPR != TPResult::Ambiguous())
287 return TPR;
288
289 // [GNU] simple-asm-expr[opt] attributes[opt]
290 if (Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
291 return TPResult::True();
292
293 // initializer[opt]
294 if (Tok.is(tok::l_paren)) {
295 // Parse through the parens.
296 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000297 if (!SkipUntil(tok::r_paren, StopAtSemi))
Guy Benyei11169dd2012-12-18 14:30:41 +0000298 return TPResult::Error();
Richard Smith22c7c412013-03-20 03:35:02 +0000299 } else if (Tok.is(tok::l_brace)) {
300 // A left-brace here is sufficient to disambiguate the parse; an
301 // expression can never be followed directly by a braced-init-list.
302 return TPResult::True();
Guy Benyei11169dd2012-12-18 14:30:41 +0000303 } else if (Tok.is(tok::equal) || isTokIdentifier_in()) {
Richard Smith1fff95c2013-09-12 23:28:08 +0000304 // MSVC and g++ won't examine the rest of declarators if '=' is
Guy Benyei11169dd2012-12-18 14:30:41 +0000305 // encountered; they just conclude that we have a declaration.
306 // EDG parses the initializer completely, which is the proper behavior
307 // for this case.
308 //
309 // At present, Clang follows MSVC and g++, since the parser does not have
310 // the ability to parse an expression fully without recording the
311 // results of that parse.
Richard Smith1fff95c2013-09-12 23:28:08 +0000312 // FIXME: Handle this case correctly.
313 //
314 // Also allow 'in' after an Objective-C declaration as in:
315 // for (int (^b)(void) in array). Ideally this should be done in the
Guy Benyei11169dd2012-12-18 14:30:41 +0000316 // context of parsing for-init-statement of a foreach statement only. But,
317 // in any other context 'in' is invalid after a declaration and parser
318 // issues the error regardless of outcome of this decision.
Richard Smith1fff95c2013-09-12 23:28:08 +0000319 // FIXME: Change if above assumption does not hold.
Guy Benyei11169dd2012-12-18 14:30:41 +0000320 return TPResult::True();
321 }
322
323 if (Tok.isNot(tok::comma))
324 break;
325 ConsumeToken(); // the comma.
326 }
327
328 return TPResult::Ambiguous();
329}
330
331/// isCXXConditionDeclaration - Disambiguates between a declaration or an
332/// expression for a condition of a if/switch/while/for statement.
333/// If during the disambiguation process a parsing error is encountered,
334/// the function returns true to let the declaration parsing code handle it.
335///
336/// condition:
337/// expression
338/// type-specifier-seq declarator '=' assignment-expression
339/// [C++11] type-specifier-seq declarator '=' initializer-clause
340/// [C++11] type-specifier-seq declarator braced-init-list
341/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
342/// '=' assignment-expression
343///
344bool Parser::isCXXConditionDeclaration() {
345 TPResult TPR = isCXXDeclarationSpecifier();
346 if (TPR != TPResult::Ambiguous())
347 return TPR != TPResult::False(); // Returns true for TPResult::True() or
348 // TPResult::Error().
349
350 // FIXME: Add statistics about the number of ambiguous statements encountered
351 // and how they were resolved (number of declarations+number of expressions).
352
353 // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
354 // We need tentative parsing...
355
356 TentativeParsingAction PA(*this);
357
358 // type-specifier-seq
Richard Smith1fff95c2013-09-12 23:28:08 +0000359 TryConsumeDeclarationSpecifier();
Guy Benyei11169dd2012-12-18 14:30:41 +0000360 assert(Tok.is(tok::l_paren) && "Expected '('");
361
362 // declarator
363 TPR = TryParseDeclarator(false/*mayBeAbstract*/);
364
365 // In case of an error, let the declaration parsing code handle it.
366 if (TPR == TPResult::Error())
367 TPR = TPResult::True();
368
369 if (TPR == TPResult::Ambiguous()) {
370 // '='
371 // [GNU] simple-asm-expr[opt] attributes[opt]
372 if (Tok.is(tok::equal) ||
373 Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
374 TPR = TPResult::True();
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000375 else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
Guy Benyei11169dd2012-12-18 14:30:41 +0000376 TPR = TPResult::True();
377 else
378 TPR = TPResult::False();
379 }
380
381 PA.Revert();
382
383 assert(TPR == TPResult::True() || TPR == TPResult::False());
384 return TPR == TPResult::True();
385}
386
387 /// \brief Determine whether the next set of tokens contains a type-id.
388 ///
389 /// The context parameter states what context we're parsing right
390 /// now, which affects how this routine copes with the token
391 /// following the type-id. If the context is TypeIdInParens, we have
392 /// already parsed the '(' and we will cease lookahead when we hit
393 /// the corresponding ')'. If the context is
394 /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
395 /// before this template argument, and will cease lookahead when we
396 /// hit a '>', '>>' (in C++0x), or ','. Returns true for a type-id
397 /// and false for an expression. If during the disambiguation
398 /// process a parsing error is encountered, the function returns
399 /// true to let the declaration parsing code handle it.
400 ///
401 /// type-id:
402 /// type-specifier-seq abstract-declarator[opt]
403 ///
404bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
405
406 isAmbiguous = false;
407
408 // C++ 8.2p2:
409 // The ambiguity arising from the similarity between a function-style cast and
410 // a type-id can occur in different contexts. The ambiguity appears as a
411 // choice between a function-style cast expression and a declaration of a
412 // type. The resolution is that any construct that could possibly be a type-id
413 // in its syntactic context shall be considered a type-id.
414
415 TPResult TPR = isCXXDeclarationSpecifier();
416 if (TPR != TPResult::Ambiguous())
417 return TPR != TPResult::False(); // Returns true for TPResult::True() or
418 // TPResult::Error().
419
420 // FIXME: Add statistics about the number of ambiguous statements encountered
421 // and how they were resolved (number of declarations+number of expressions).
422
423 // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
424 // We need tentative parsing...
425
426 TentativeParsingAction PA(*this);
427
428 // type-specifier-seq
Richard Smith1fff95c2013-09-12 23:28:08 +0000429 TryConsumeDeclarationSpecifier();
Guy Benyei11169dd2012-12-18 14:30:41 +0000430 assert(Tok.is(tok::l_paren) && "Expected '('");
431
432 // declarator
433 TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
434
435 // In case of an error, let the declaration parsing code handle it.
436 if (TPR == TPResult::Error())
437 TPR = TPResult::True();
438
439 if (TPR == TPResult::Ambiguous()) {
440 // We are supposed to be inside parens, so if after the abstract declarator
441 // we encounter a ')' this is a type-id, otherwise it's an expression.
442 if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
443 TPR = TPResult::True();
444 isAmbiguous = true;
445
446 // We are supposed to be inside a template argument, so if after
447 // the abstract declarator we encounter a '>', '>>' (in C++0x), or
448 // ',', this is a type-id. Otherwise, it's an expression.
449 } else if (Context == TypeIdAsTemplateArgument &&
450 (Tok.is(tok::greater) || Tok.is(tok::comma) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000451 (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater)))) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000452 TPR = TPResult::True();
453 isAmbiguous = true;
454
455 } else
456 TPR = TPResult::False();
457 }
458
459 PA.Revert();
460
461 assert(TPR == TPResult::True() || TPR == TPResult::False());
462 return TPR == TPResult::True();
463}
464
465/// \brief Returns true if this is a C++11 attribute-specifier. Per
466/// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
467/// always introduce an attribute. In Objective-C++11, this rule does not
468/// apply if either '[' begins a message-send.
469///
470/// If Disambiguate is true, we try harder to determine whether a '[[' starts
471/// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
472///
473/// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
474/// Obj-C message send or the start of an attribute. Otherwise, we assume it
475/// is not an Obj-C message send.
476///
477/// C++11 [dcl.attr.grammar]:
478///
479/// attribute-specifier:
480/// '[' '[' attribute-list ']' ']'
481/// alignment-specifier
482///
483/// attribute-list:
484/// attribute[opt]
485/// attribute-list ',' attribute[opt]
486/// attribute '...'
487/// attribute-list ',' attribute '...'
488///
489/// attribute:
490/// attribute-token attribute-argument-clause[opt]
491///
492/// attribute-token:
493/// identifier
494/// identifier '::' identifier
495///
496/// attribute-argument-clause:
497/// '(' balanced-token-seq ')'
498Parser::CXX11AttributeKind
499Parser::isCXX11AttributeSpecifier(bool Disambiguate,
500 bool OuterMightBeMessageSend) {
501 if (Tok.is(tok::kw_alignas))
502 return CAK_AttributeSpecifier;
503
504 if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
505 return CAK_NotAttributeSpecifier;
506
507 // No tentative parsing if we don't need to look for ']]' or a lambda.
508 if (!Disambiguate && !getLangOpts().ObjC1)
509 return CAK_AttributeSpecifier;
510
511 TentativeParsingAction PA(*this);
512
513 // Opening brackets were checked for above.
514 ConsumeBracket();
515
516 // Outside Obj-C++11, treat anything with a matching ']]' as an attribute.
517 if (!getLangOpts().ObjC1) {
518 ConsumeBracket();
519
Alexey Bataevee6507d2013-11-18 08:17:37 +0000520 bool IsAttribute = SkipUntil(tok::r_square);
Guy Benyei11169dd2012-12-18 14:30:41 +0000521 IsAttribute &= Tok.is(tok::r_square);
522
523 PA.Revert();
524
525 return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
526 }
527
528 // In Obj-C++11, we need to distinguish four situations:
529 // 1a) int x[[attr]]; C++11 attribute.
530 // 1b) [[attr]]; C++11 statement attribute.
531 // 2) int x[[obj](){ return 1; }()]; Lambda in array size/index.
532 // 3a) int x[[obj get]]; Message send in array size/index.
533 // 3b) [[Class alloc] init]; Message send in message send.
534 // 4) [[obj]{ return self; }() doStuff]; Lambda in message send.
535 // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
536
537 // If we have a lambda-introducer, then this is definitely not a message send.
538 // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
539 // into the tentative attribute parse below.
540 LambdaIntroducer Intro;
541 if (!TryParseLambdaIntroducer(Intro)) {
542 // A lambda cannot end with ']]', and an attribute must.
543 bool IsAttribute = Tok.is(tok::r_square);
544
545 PA.Revert();
546
547 if (IsAttribute)
548 // Case 1: C++11 attribute.
549 return CAK_AttributeSpecifier;
550
551 if (OuterMightBeMessageSend)
552 // Case 4: Lambda in message send.
553 return CAK_NotAttributeSpecifier;
554
555 // Case 2: Lambda in array size / index.
556 return CAK_InvalidAttributeSpecifier;
557 }
558
559 ConsumeBracket();
560
561 // If we don't have a lambda-introducer, then we have an attribute or a
562 // message-send.
563 bool IsAttribute = true;
564 while (Tok.isNot(tok::r_square)) {
565 if (Tok.is(tok::comma)) {
566 // Case 1: Stray commas can only occur in attributes.
567 PA.Revert();
568 return CAK_AttributeSpecifier;
569 }
570
571 // Parse the attribute-token, if present.
572 // C++11 [dcl.attr.grammar]:
573 // If a keyword or an alternative token that satisfies the syntactic
574 // requirements of an identifier is contained in an attribute-token,
575 // it is considered an identifier.
576 SourceLocation Loc;
577 if (!TryParseCXX11AttributeIdentifier(Loc)) {
578 IsAttribute = false;
579 break;
580 }
581 if (Tok.is(tok::coloncolon)) {
582 ConsumeToken();
583 if (!TryParseCXX11AttributeIdentifier(Loc)) {
584 IsAttribute = false;
585 break;
586 }
587 }
588
589 // Parse the attribute-argument-clause, if present.
590 if (Tok.is(tok::l_paren)) {
591 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +0000592 if (!SkipUntil(tok::r_paren)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000593 IsAttribute = false;
594 break;
595 }
596 }
597
598 if (Tok.is(tok::ellipsis))
599 ConsumeToken();
600
601 if (Tok.isNot(tok::comma))
602 break;
603
604 ConsumeToken();
605 }
606
607 // An attribute must end ']]'.
608 if (IsAttribute) {
609 if (Tok.is(tok::r_square)) {
610 ConsumeBracket();
611 IsAttribute = Tok.is(tok::r_square);
612 } else {
613 IsAttribute = false;
614 }
615 }
616
617 PA.Revert();
618
619 if (IsAttribute)
620 // Case 1: C++11 statement attribute.
621 return CAK_AttributeSpecifier;
622
623 // Case 3: Message send.
624 return CAK_NotAttributeSpecifier;
625}
626
Richard Smith1fff95c2013-09-12 23:28:08 +0000627Parser::TPResult Parser::TryParsePtrOperatorSeq() {
628 while (true) {
629 if (Tok.is(tok::coloncolon) || Tok.is(tok::identifier))
630 if (TryAnnotateCXXScopeToken(true))
631 return TPResult::Error();
632
633 if (Tok.is(tok::star) || Tok.is(tok::amp) || Tok.is(tok::caret) ||
634 Tok.is(tok::ampamp) ||
635 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
636 // ptr-operator
637 ConsumeToken();
638 while (Tok.is(tok::kw_const) ||
639 Tok.is(tok::kw_volatile) ||
640 Tok.is(tok::kw_restrict))
641 ConsumeToken();
642 } else {
643 return TPResult::True();
644 }
645 }
646}
647
648/// operator-function-id:
649/// 'operator' operator
650///
651/// operator: one of
652/// new delete new[] delete[] + - * / % ^ [...]
653///
654/// conversion-function-id:
655/// 'operator' conversion-type-id
656///
657/// conversion-type-id:
658/// type-specifier-seq conversion-declarator[opt]
659///
660/// conversion-declarator:
661/// ptr-operator conversion-declarator[opt]
662///
663/// literal-operator-id:
664/// 'operator' string-literal identifier
665/// 'operator' user-defined-string-literal
666Parser::TPResult Parser::TryParseOperatorId() {
667 assert(Tok.is(tok::kw_operator));
668 ConsumeToken();
669
670 // Maybe this is an operator-function-id.
671 switch (Tok.getKind()) {
672 case tok::kw_new: case tok::kw_delete:
673 ConsumeToken();
674 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
675 ConsumeBracket();
676 ConsumeBracket();
677 }
678 return TPResult::True();
679
680#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
681 case tok::Token:
682#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
683#include "clang/Basic/OperatorKinds.def"
684 ConsumeToken();
685 return TPResult::True();
686
687 case tok::l_square:
688 if (NextToken().is(tok::r_square)) {
689 ConsumeBracket();
690 ConsumeBracket();
691 return TPResult::True();
692 }
693 break;
694
695 case tok::l_paren:
696 if (NextToken().is(tok::r_paren)) {
697 ConsumeParen();
698 ConsumeParen();
699 return TPResult::True();
700 }
701 break;
702
703 default:
704 break;
705 }
706
707 // Maybe this is a literal-operator-id.
708 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
709 bool FoundUDSuffix = false;
710 do {
711 FoundUDSuffix |= Tok.hasUDSuffix();
712 ConsumeStringToken();
713 } while (isTokenStringLiteral());
714
715 if (!FoundUDSuffix) {
716 if (Tok.is(tok::identifier))
717 ConsumeToken();
718 else
719 return TPResult::Error();
720 }
721 return TPResult::True();
722 }
723
724 // Maybe this is a conversion-function-id.
725 bool AnyDeclSpecifiers = false;
726 while (true) {
727 TPResult TPR = isCXXDeclarationSpecifier();
728 if (TPR == TPResult::Error())
729 return TPR;
730 if (TPR == TPResult::False()) {
731 if (!AnyDeclSpecifiers)
732 return TPResult::Error();
733 break;
734 }
735 if (TryConsumeDeclarationSpecifier() == TPResult::Error())
736 return TPResult::Error();
737 AnyDeclSpecifiers = true;
738 }
739 return TryParsePtrOperatorSeq();
740}
741
Guy Benyei11169dd2012-12-18 14:30:41 +0000742/// declarator:
743/// direct-declarator
744/// ptr-operator declarator
745///
746/// direct-declarator:
747/// declarator-id
748/// direct-declarator '(' parameter-declaration-clause ')'
749/// cv-qualifier-seq[opt] exception-specification[opt]
750/// direct-declarator '[' constant-expression[opt] ']'
751/// '(' declarator ')'
752/// [GNU] '(' attributes declarator ')'
753///
754/// abstract-declarator:
755/// ptr-operator abstract-declarator[opt]
756/// direct-abstract-declarator
757/// ...
758///
759/// direct-abstract-declarator:
760/// direct-abstract-declarator[opt]
761/// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
762/// exception-specification[opt]
763/// direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
764/// '(' abstract-declarator ')'
765///
766/// ptr-operator:
767/// '*' cv-qualifier-seq[opt]
768/// '&'
769/// [C++0x] '&&' [TODO]
770/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
771///
772/// cv-qualifier-seq:
773/// cv-qualifier cv-qualifier-seq[opt]
774///
775/// cv-qualifier:
776/// 'const'
777/// 'volatile'
778///
779/// declarator-id:
780/// '...'[opt] id-expression
781///
782/// id-expression:
783/// unqualified-id
784/// qualified-id [TODO]
785///
786/// unqualified-id:
787/// identifier
Richard Smith1fff95c2013-09-12 23:28:08 +0000788/// operator-function-id
789/// conversion-function-id
790/// literal-operator-id
Guy Benyei11169dd2012-12-18 14:30:41 +0000791/// '~' class-name [TODO]
Richard Smith1fff95c2013-09-12 23:28:08 +0000792/// '~' decltype-specifier [TODO]
Guy Benyei11169dd2012-12-18 14:30:41 +0000793/// template-id [TODO]
794///
795Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
796 bool mayHaveIdentifier) {
797 // declarator:
798 // direct-declarator
799 // ptr-operator declarator
Richard Smith1fff95c2013-09-12 23:28:08 +0000800 if (TryParsePtrOperatorSeq() == TPResult::Error())
801 return TPResult::Error();
Guy Benyei11169dd2012-12-18 14:30:41 +0000802
803 // direct-declarator:
804 // direct-abstract-declarator:
805 if (Tok.is(tok::ellipsis))
806 ConsumeToken();
Richard Smith1fff95c2013-09-12 23:28:08 +0000807
808 if ((Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
809 (Tok.is(tok::annot_cxxscope) && (NextToken().is(tok::identifier) ||
810 NextToken().is(tok::kw_operator)))) &&
Guy Benyei11169dd2012-12-18 14:30:41 +0000811 mayHaveIdentifier) {
812 // declarator-id
813 if (Tok.is(tok::annot_cxxscope))
814 ConsumeToken();
Richard Smith1fff95c2013-09-12 23:28:08 +0000815 else if (Tok.is(tok::identifier))
Guy Benyei11169dd2012-12-18 14:30:41 +0000816 TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
Richard Smith1fff95c2013-09-12 23:28:08 +0000817 if (Tok.is(tok::kw_operator)) {
818 if (TryParseOperatorId() == TPResult::Error())
819 return TPResult::Error();
820 } else
821 ConsumeToken();
Guy Benyei11169dd2012-12-18 14:30:41 +0000822 } else if (Tok.is(tok::l_paren)) {
823 ConsumeParen();
824 if (mayBeAbstract &&
825 (Tok.is(tok::r_paren) || // 'int()' is a function.
826 // 'int(...)' is a function.
827 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
828 isDeclarationSpecifier())) { // 'int(int)' is a function.
829 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
830 // exception-specification[opt]
831 TPResult TPR = TryParseFunctionDeclarator();
832 if (TPR != TPResult::Ambiguous())
833 return TPR;
834 } else {
835 // '(' declarator ')'
836 // '(' attributes declarator ')'
837 // '(' abstract-declarator ')'
838 if (Tok.is(tok::kw___attribute) ||
839 Tok.is(tok::kw___declspec) ||
840 Tok.is(tok::kw___cdecl) ||
841 Tok.is(tok::kw___stdcall) ||
842 Tok.is(tok::kw___fastcall) ||
843 Tok.is(tok::kw___thiscall) ||
844 Tok.is(tok::kw___unaligned))
845 return TPResult::True(); // attributes indicate declaration
846 TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
847 if (TPR != TPResult::Ambiguous())
848 return TPR;
849 if (Tok.isNot(tok::r_paren))
850 return TPResult::False();
851 ConsumeParen();
852 }
853 } else if (!mayBeAbstract) {
854 return TPResult::False();
855 }
856
857 while (1) {
858 TPResult TPR(TPResult::Ambiguous());
859
860 // abstract-declarator: ...
861 if (Tok.is(tok::ellipsis))
862 ConsumeToken();
863
864 if (Tok.is(tok::l_paren)) {
865 // Check whether we have a function declarator or a possible ctor-style
866 // initializer that follows the declarator. Note that ctor-style
867 // initializers are not possible in contexts where abstract declarators
868 // are allowed.
869 if (!mayBeAbstract && !isCXXFunctionDeclarator())
870 break;
871
872 // direct-declarator '(' parameter-declaration-clause ')'
873 // cv-qualifier-seq[opt] exception-specification[opt]
874 ConsumeParen();
875 TPR = TryParseFunctionDeclarator();
876 } else if (Tok.is(tok::l_square)) {
877 // direct-declarator '[' constant-expression[opt] ']'
878 // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
879 TPR = TryParseBracketDeclarator();
880 } else {
881 break;
882 }
883
884 if (TPR != TPResult::Ambiguous())
885 return TPR;
886 }
887
888 return TPResult::Ambiguous();
889}
890
891Parser::TPResult
892Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) {
893 switch (Kind) {
894 // Obviously starts an expression.
895 case tok::numeric_constant:
896 case tok::char_constant:
897 case tok::wide_char_constant:
898 case tok::utf16_char_constant:
899 case tok::utf32_char_constant:
900 case tok::string_literal:
901 case tok::wide_string_literal:
902 case tok::utf8_string_literal:
903 case tok::utf16_string_literal:
904 case tok::utf32_string_literal:
905 case tok::l_square:
906 case tok::l_paren:
907 case tok::amp:
908 case tok::ampamp:
909 case tok::star:
910 case tok::plus:
911 case tok::plusplus:
912 case tok::minus:
913 case tok::minusminus:
914 case tok::tilde:
915 case tok::exclaim:
916 case tok::kw_sizeof:
917 case tok::kw___func__:
918 case tok::kw_const_cast:
919 case tok::kw_delete:
920 case tok::kw_dynamic_cast:
921 case tok::kw_false:
922 case tok::kw_new:
923 case tok::kw_operator:
924 case tok::kw_reinterpret_cast:
925 case tok::kw_static_cast:
926 case tok::kw_this:
927 case tok::kw_throw:
928 case tok::kw_true:
929 case tok::kw_typeid:
930 case tok::kw_alignof:
931 case tok::kw_noexcept:
932 case tok::kw_nullptr:
933 case tok::kw__Alignof:
934 case tok::kw___null:
935 case tok::kw___alignof:
936 case tok::kw___builtin_choose_expr:
937 case tok::kw___builtin_offsetof:
Guy Benyei11169dd2012-12-18 14:30:41 +0000938 case tok::kw___builtin_va_arg:
939 case tok::kw___imag:
940 case tok::kw___real:
941 case tok::kw___FUNCTION__:
David Majnemerbed356a2013-11-06 23:31:56 +0000942 case tok::kw___FUNCDNAME__:
Guy Benyei11169dd2012-12-18 14:30:41 +0000943 case tok::kw_L__FUNCTION__:
944 case tok::kw___PRETTY_FUNCTION__:
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 case tok::kw___uuidof:
Alp Toker40f9b1c2013-12-12 21:23:03 +0000946#define TYPE_TRAIT(N,Spelling,K) \
947 case tok::kw_##Spelling:
948#include "clang/Basic/TokenKinds.def"
Guy Benyei11169dd2012-12-18 14:30:41 +0000949 return TPResult::True();
950
951 // Obviously starts a type-specifier-seq:
952 case tok::kw_char:
953 case tok::kw_const:
954 case tok::kw_double:
955 case tok::kw_enum:
956 case tok::kw_half:
957 case tok::kw_float:
958 case tok::kw_int:
959 case tok::kw_long:
960 case tok::kw___int64:
961 case tok::kw___int128:
962 case tok::kw_restrict:
963 case tok::kw_short:
964 case tok::kw_signed:
965 case tok::kw_struct:
966 case tok::kw_union:
967 case tok::kw_unsigned:
968 case tok::kw_void:
969 case tok::kw_volatile:
970 case tok::kw__Bool:
971 case tok::kw__Complex:
972 case tok::kw_class:
973 case tok::kw_typename:
974 case tok::kw_wchar_t:
975 case tok::kw_char16_t:
976 case tok::kw_char32_t:
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 case tok::kw__Decimal32:
978 case tok::kw__Decimal64:
979 case tok::kw__Decimal128:
Richard Smith1fff95c2013-09-12 23:28:08 +0000980 case tok::kw___interface:
Guy Benyei11169dd2012-12-18 14:30:41 +0000981 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +0000982 case tok::kw_thread_local:
983 case tok::kw__Thread_local:
Guy Benyei11169dd2012-12-18 14:30:41 +0000984 case tok::kw_typeof:
Richard Smith1fff95c2013-09-12 23:28:08 +0000985 case tok::kw___underlying_type:
Guy Benyei11169dd2012-12-18 14:30:41 +0000986 case tok::kw___cdecl:
987 case tok::kw___stdcall:
988 case tok::kw___fastcall:
989 case tok::kw___thiscall:
990 case tok::kw___unaligned:
991 case tok::kw___vector:
992 case tok::kw___pixel:
993 case tok::kw__Atomic:
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000994 case tok::kw_image1d_t:
995 case tok::kw_image1d_array_t:
996 case tok::kw_image1d_buffer_t:
997 case tok::kw_image2d_t:
998 case tok::kw_image2d_array_t:
999 case tok::kw_image3d_t:
Guy Benyei61054192013-02-07 10:55:47 +00001000 case tok::kw_sampler_t:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001001 case tok::kw_event_t:
Guy Benyei11169dd2012-12-18 14:30:41 +00001002 case tok::kw___unknown_anytype:
1003 return TPResult::False();
1004
1005 default:
1006 break;
1007 }
1008
1009 return TPResult::Ambiguous();
1010}
1011
1012bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
1013 return std::find(TentativelyDeclaredIdentifiers.begin(),
1014 TentativelyDeclaredIdentifiers.end(), II)
1015 != TentativelyDeclaredIdentifiers.end();
1016}
1017
1018/// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a declaration
1019/// specifier, TPResult::False() if it is not, TPResult::Ambiguous() if it could
1020/// be either a decl-specifier or a function-style cast, and TPResult::Error()
1021/// if a parsing error was found and reported.
1022///
1023/// If HasMissingTypename is provided, a name with a dependent scope specifier
1024/// will be treated as ambiguous if the 'typename' keyword is missing. If this
1025/// happens, *HasMissingTypename will be set to 'true'. This will also be used
1026/// as an indicator that undeclared identifiers (which will trigger a later
1027/// parse error) should be treated as types. Returns TPResult::Ambiguous() in
1028/// such cases.
1029///
1030/// decl-specifier:
1031/// storage-class-specifier
1032/// type-specifier
1033/// function-specifier
1034/// 'friend'
1035/// 'typedef'
Richard Smithb4a9e862013-04-12 22:46:28 +00001036/// [C++11] 'constexpr'
Guy Benyei11169dd2012-12-18 14:30:41 +00001037/// [GNU] attributes declaration-specifiers[opt]
1038///
1039/// storage-class-specifier:
1040/// 'register'
1041/// 'static'
1042/// 'extern'
1043/// 'mutable'
1044/// 'auto'
1045/// [GNU] '__thread'
Richard Smithb4a9e862013-04-12 22:46:28 +00001046/// [C++11] 'thread_local'
1047/// [C11] '_Thread_local'
Guy Benyei11169dd2012-12-18 14:30:41 +00001048///
1049/// function-specifier:
1050/// 'inline'
1051/// 'virtual'
1052/// 'explicit'
1053///
1054/// typedef-name:
1055/// identifier
1056///
1057/// type-specifier:
1058/// simple-type-specifier
1059/// class-specifier
1060/// enum-specifier
1061/// elaborated-type-specifier
1062/// typename-specifier
1063/// cv-qualifier
1064///
1065/// simple-type-specifier:
1066/// '::'[opt] nested-name-specifier[opt] type-name
1067/// '::'[opt] nested-name-specifier 'template'
1068/// simple-template-id [TODO]
1069/// 'char'
1070/// 'wchar_t'
1071/// 'bool'
1072/// 'short'
1073/// 'int'
1074/// 'long'
1075/// 'signed'
1076/// 'unsigned'
1077/// 'float'
1078/// 'double'
1079/// 'void'
1080/// [GNU] typeof-specifier
1081/// [GNU] '_Complex'
Richard Smithb4a9e862013-04-12 22:46:28 +00001082/// [C++11] 'auto'
1083/// [C++11] 'decltype' ( expression )
Richard Smith74aeef52013-04-26 16:15:35 +00001084/// [C++1y] 'decltype' ( 'auto' )
Guy Benyei11169dd2012-12-18 14:30:41 +00001085///
1086/// type-name:
1087/// class-name
1088/// enum-name
1089/// typedef-name
1090///
1091/// elaborated-type-specifier:
1092/// class-key '::'[opt] nested-name-specifier[opt] identifier
1093/// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
1094/// simple-template-id
1095/// 'enum' '::'[opt] nested-name-specifier[opt] identifier
1096///
1097/// enum-name:
1098/// identifier
1099///
1100/// enum-specifier:
1101/// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
1102/// 'enum' identifier[opt] '{' enumerator-list ',' '}'
1103///
1104/// class-specifier:
1105/// class-head '{' member-specification[opt] '}'
1106///
1107/// class-head:
1108/// class-key identifier[opt] base-clause[opt]
1109/// class-key nested-name-specifier identifier base-clause[opt]
1110/// class-key nested-name-specifier[opt] simple-template-id
1111/// base-clause[opt]
1112///
1113/// class-key:
1114/// 'class'
1115/// 'struct'
1116/// 'union'
1117///
1118/// cv-qualifier:
1119/// 'const'
1120/// 'volatile'
1121/// [GNU] restrict
1122///
1123Parser::TPResult
1124Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
1125 bool *HasMissingTypename) {
1126 switch (Tok.getKind()) {
1127 case tok::identifier: {
1128 // Check for need to substitute AltiVec __vector keyword
1129 // for "vector" identifier.
1130 if (TryAltiVecVectorToken())
1131 return TPResult::True();
1132
1133 const Token &Next = NextToken();
1134 // In 'foo bar', 'foo' is always a type name outside of Objective-C.
1135 if (!getLangOpts().ObjC1 && Next.is(tok::identifier))
1136 return TPResult::True();
1137
1138 if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
1139 // Determine whether this is a valid expression. If not, we will hit
1140 // a parse error one way or another. In that case, tell the caller that
1141 // this is ambiguous. Typo-correct to type and expression keywords and
1142 // to types and identifiers, in order to try to recover from errors.
1143 CorrectionCandidateCallback TypoCorrection;
1144 TypoCorrection.WantRemainingKeywords = false;
Kaelyn Uhrain989b7ca2013-04-03 16:59:49 +00001145 TypoCorrection.WantTypeSpecifiers = Next.isNot(tok::arrow);
Guy Benyei11169dd2012-12-18 14:30:41 +00001146 switch (TryAnnotateName(false /* no nested name specifier */,
1147 &TypoCorrection)) {
1148 case ANK_Error:
1149 return TPResult::Error();
1150 case ANK_TentativeDecl:
1151 return TPResult::False();
1152 case ANK_TemplateName:
1153 // A bare type template-name which can't be a template template
1154 // argument is an error, and was probably intended to be a type.
1155 return GreaterThanIsOperator ? TPResult::True() : TPResult::False();
1156 case ANK_Unresolved:
1157 return HasMissingTypename ? TPResult::Ambiguous() : TPResult::False();
1158 case ANK_Success:
1159 break;
1160 }
1161 assert(Tok.isNot(tok::identifier) &&
1162 "TryAnnotateName succeeded without producing an annotation");
1163 } else {
1164 // This might possibly be a type with a dependent scope specifier and
1165 // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
1166 // since it will annotate as a primary expression, and we want to use the
1167 // "missing 'typename'" logic.
1168 if (TryAnnotateTypeOrScopeToken())
1169 return TPResult::Error();
1170 // If annotation failed, assume it's a non-type.
1171 // FIXME: If this happens due to an undeclared identifier, treat it as
1172 // ambiguous.
1173 if (Tok.is(tok::identifier))
1174 return TPResult::False();
1175 }
1176
1177 // We annotated this token as something. Recurse to handle whatever we got.
1178 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1179 }
1180
1181 case tok::kw_typename: // typename T::type
1182 // Annotate typenames and C++ scope specifiers. If we get one, just
1183 // recurse to handle whatever we get.
1184 if (TryAnnotateTypeOrScopeToken())
1185 return TPResult::Error();
1186 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1187
1188 case tok::coloncolon: { // ::foo::bar
1189 const Token &Next = NextToken();
1190 if (Next.is(tok::kw_new) || // ::new
1191 Next.is(tok::kw_delete)) // ::delete
1192 return TPResult::False();
1193 }
1194 // Fall through.
1195 case tok::kw_decltype:
1196 // Annotate typenames and C++ scope specifiers. If we get one, just
1197 // recurse to handle whatever we get.
1198 if (TryAnnotateTypeOrScopeToken())
1199 return TPResult::Error();
1200 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1201
1202 // decl-specifier:
1203 // storage-class-specifier
1204 // type-specifier
1205 // function-specifier
1206 // 'friend'
1207 // 'typedef'
1208 // 'constexpr'
1209 case tok::kw_friend:
1210 case tok::kw_typedef:
1211 case tok::kw_constexpr:
1212 // storage-class-specifier
1213 case tok::kw_register:
1214 case tok::kw_static:
1215 case tok::kw_extern:
1216 case tok::kw_mutable:
1217 case tok::kw_auto:
1218 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00001219 case tok::kw_thread_local:
1220 case tok::kw__Thread_local:
Guy Benyei11169dd2012-12-18 14:30:41 +00001221 // function-specifier
1222 case tok::kw_inline:
1223 case tok::kw_virtual:
1224 case tok::kw_explicit:
1225
1226 // Modules
1227 case tok::kw___module_private__:
1228
1229 // Debugger support
1230 case tok::kw___unknown_anytype:
1231
1232 // type-specifier:
1233 // simple-type-specifier
1234 // class-specifier
1235 // enum-specifier
1236 // elaborated-type-specifier
1237 // typename-specifier
1238 // cv-qualifier
1239
1240 // class-specifier
1241 // elaborated-type-specifier
1242 case tok::kw_class:
1243 case tok::kw_struct:
1244 case tok::kw_union:
Richard Smith1fff95c2013-09-12 23:28:08 +00001245 case tok::kw___interface:
Guy Benyei11169dd2012-12-18 14:30:41 +00001246 // enum-specifier
1247 case tok::kw_enum:
1248 // cv-qualifier
1249 case tok::kw_const:
1250 case tok::kw_volatile:
1251
1252 // GNU
1253 case tok::kw_restrict:
1254 case tok::kw__Complex:
1255 case tok::kw___attribute:
1256 return TPResult::True();
1257
1258 // Microsoft
1259 case tok::kw___declspec:
1260 case tok::kw___cdecl:
1261 case tok::kw___stdcall:
1262 case tok::kw___fastcall:
1263 case tok::kw___thiscall:
1264 case tok::kw___w64:
Aaron Ballman317a77f2013-05-22 23:25:32 +00001265 case tok::kw___sptr:
1266 case tok::kw___uptr:
Guy Benyei11169dd2012-12-18 14:30:41 +00001267 case tok::kw___ptr64:
1268 case tok::kw___ptr32:
1269 case tok::kw___forceinline:
1270 case tok::kw___unaligned:
1271 return TPResult::True();
1272
1273 // Borland
1274 case tok::kw___pascal:
1275 return TPResult::True();
1276
1277 // AltiVec
1278 case tok::kw___vector:
1279 return TPResult::True();
1280
1281 case tok::annot_template_id: {
1282 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1283 if (TemplateId->Kind != TNK_Type_template)
1284 return TPResult::False();
1285 CXXScopeSpec SS;
1286 AnnotateTemplateIdTokenAsType();
1287 assert(Tok.is(tok::annot_typename));
1288 goto case_typename;
1289 }
1290
1291 case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
1292 // We've already annotated a scope; try to annotate a type.
1293 if (TryAnnotateTypeOrScopeToken())
1294 return TPResult::Error();
1295 if (!Tok.is(tok::annot_typename)) {
1296 // If the next token is an identifier or a type qualifier, then this
1297 // can't possibly be a valid expression either.
1298 if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
1299 CXXScopeSpec SS;
1300 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1301 Tok.getAnnotationRange(),
1302 SS);
1303 if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
1304 TentativeParsingAction PA(*this);
1305 ConsumeToken();
1306 ConsumeToken();
1307 bool isIdentifier = Tok.is(tok::identifier);
1308 TPResult TPR = TPResult::False();
1309 if (!isIdentifier)
1310 TPR = isCXXDeclarationSpecifier(BracedCastResult,
1311 HasMissingTypename);
1312 PA.Revert();
1313
1314 if (isIdentifier ||
1315 TPR == TPResult::True() || TPR == TPResult::Error())
1316 return TPResult::Error();
1317
1318 if (HasMissingTypename) {
1319 // We can't tell whether this is a missing 'typename' or a valid
1320 // expression.
1321 *HasMissingTypename = true;
1322 return TPResult::Ambiguous();
1323 }
1324 } else {
1325 // Try to resolve the name. If it doesn't exist, assume it was
1326 // intended to name a type and keep disambiguating.
1327 switch (TryAnnotateName(false /* SS is not dependent */)) {
1328 case ANK_Error:
1329 return TPResult::Error();
1330 case ANK_TentativeDecl:
1331 return TPResult::False();
1332 case ANK_TemplateName:
1333 // A bare type template-name which can't be a template template
1334 // argument is an error, and was probably intended to be a type.
1335 return GreaterThanIsOperator ? TPResult::True() : TPResult::False();
1336 case ANK_Unresolved:
1337 return HasMissingTypename ? TPResult::Ambiguous()
1338 : TPResult::False();
1339 case ANK_Success:
1340 // Annotated it, check again.
1341 assert(Tok.isNot(tok::annot_cxxscope) ||
1342 NextToken().isNot(tok::identifier));
1343 return isCXXDeclarationSpecifier(BracedCastResult,
1344 HasMissingTypename);
1345 }
1346 }
1347 }
1348 return TPResult::False();
1349 }
1350 // If that succeeded, fallthrough into the generic simple-type-id case.
1351
1352 // The ambiguity resides in a simple-type-specifier/typename-specifier
1353 // followed by a '('. The '(' could either be the start of:
1354 //
1355 // direct-declarator:
1356 // '(' declarator ')'
1357 //
1358 // direct-abstract-declarator:
1359 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1360 // exception-specification[opt]
1361 // '(' abstract-declarator ')'
1362 //
1363 // or part of a function-style cast expression:
1364 //
1365 // simple-type-specifier '(' expression-list[opt] ')'
1366 //
1367
1368 // simple-type-specifier:
1369
1370 case tok::annot_typename:
1371 case_typename:
1372 // In Objective-C, we might have a protocol-qualified type.
1373 if (getLangOpts().ObjC1 && NextToken().is(tok::less)) {
1374 // Tentatively parse the
1375 TentativeParsingAction PA(*this);
1376 ConsumeToken(); // The type token
1377
1378 TPResult TPR = TryParseProtocolQualifiers();
1379 bool isFollowedByParen = Tok.is(tok::l_paren);
1380 bool isFollowedByBrace = Tok.is(tok::l_brace);
1381
1382 PA.Revert();
1383
1384 if (TPR == TPResult::Error())
1385 return TPResult::Error();
1386
1387 if (isFollowedByParen)
1388 return TPResult::Ambiguous();
1389
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001390 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
Guy Benyei11169dd2012-12-18 14:30:41 +00001391 return BracedCastResult;
1392
1393 return TPResult::True();
1394 }
1395
1396 case tok::kw_char:
1397 case tok::kw_wchar_t:
1398 case tok::kw_char16_t:
1399 case tok::kw_char32_t:
1400 case tok::kw_bool:
1401 case tok::kw_short:
1402 case tok::kw_int:
1403 case tok::kw_long:
1404 case tok::kw___int64:
1405 case tok::kw___int128:
1406 case tok::kw_signed:
1407 case tok::kw_unsigned:
1408 case tok::kw_half:
1409 case tok::kw_float:
1410 case tok::kw_double:
1411 case tok::kw_void:
1412 case tok::annot_decltype:
1413 if (NextToken().is(tok::l_paren))
1414 return TPResult::Ambiguous();
1415
1416 // This is a function-style cast in all cases we disambiguate other than
1417 // one:
1418 // struct S {
1419 // enum E : int { a = 4 }; // enum
1420 // enum E : int { 4 }; // bit-field
1421 // };
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001422 if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
Guy Benyei11169dd2012-12-18 14:30:41 +00001423 return BracedCastResult;
1424
1425 if (isStartOfObjCClassMessageMissingOpenBracket())
1426 return TPResult::False();
1427
1428 return TPResult::True();
1429
1430 // GNU typeof support.
1431 case tok::kw_typeof: {
1432 if (NextToken().isNot(tok::l_paren))
1433 return TPResult::True();
1434
1435 TentativeParsingAction PA(*this);
1436
1437 TPResult TPR = TryParseTypeofSpecifier();
1438 bool isFollowedByParen = Tok.is(tok::l_paren);
1439 bool isFollowedByBrace = Tok.is(tok::l_brace);
1440
1441 PA.Revert();
1442
1443 if (TPR == TPResult::Error())
1444 return TPResult::Error();
1445
1446 if (isFollowedByParen)
1447 return TPResult::Ambiguous();
1448
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001449 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
Guy Benyei11169dd2012-12-18 14:30:41 +00001450 return BracedCastResult;
1451
1452 return TPResult::True();
1453 }
1454
1455 // C++0x type traits support
1456 case tok::kw___underlying_type:
1457 return TPResult::True();
1458
1459 // C11 _Atomic
1460 case tok::kw__Atomic:
1461 return TPResult::True();
1462
1463 default:
1464 return TPResult::False();
1465 }
1466}
1467
Richard Smith1fff95c2013-09-12 23:28:08 +00001468bool Parser::isCXXDeclarationSpecifierAType() {
1469 switch (Tok.getKind()) {
1470 // typename-specifier
1471 case tok::annot_decltype:
1472 case tok::annot_template_id:
1473 case tok::annot_typename:
1474 case tok::kw_typeof:
1475 case tok::kw___underlying_type:
1476 return true;
1477
1478 // elaborated-type-specifier
1479 case tok::kw_class:
1480 case tok::kw_struct:
1481 case tok::kw_union:
1482 case tok::kw___interface:
1483 case tok::kw_enum:
1484 return true;
1485
1486 // simple-type-specifier
1487 case tok::kw_char:
1488 case tok::kw_wchar_t:
1489 case tok::kw_char16_t:
1490 case tok::kw_char32_t:
1491 case tok::kw_bool:
1492 case tok::kw_short:
1493 case tok::kw_int:
1494 case tok::kw_long:
1495 case tok::kw___int64:
1496 case tok::kw___int128:
1497 case tok::kw_signed:
1498 case tok::kw_unsigned:
1499 case tok::kw_half:
1500 case tok::kw_float:
1501 case tok::kw_double:
1502 case tok::kw_void:
1503 case tok::kw___unknown_anytype:
1504 return true;
1505
1506 case tok::kw_auto:
1507 return getLangOpts().CPlusPlus11;
1508
1509 case tok::kw__Atomic:
1510 // "_Atomic foo"
1511 return NextToken().is(tok::l_paren);
1512
1513 default:
1514 return false;
1515 }
1516}
1517
Guy Benyei11169dd2012-12-18 14:30:41 +00001518/// [GNU] typeof-specifier:
1519/// 'typeof' '(' expressions ')'
1520/// 'typeof' '(' type-name ')'
1521///
1522Parser::TPResult Parser::TryParseTypeofSpecifier() {
1523 assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
1524 ConsumeToken();
1525
1526 assert(Tok.is(tok::l_paren) && "Expected '('");
1527 // Parse through the parens after 'typeof'.
1528 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001529 if (!SkipUntil(tok::r_paren, StopAtSemi))
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 return TPResult::Error();
1531
1532 return TPResult::Ambiguous();
1533}
1534
1535/// [ObjC] protocol-qualifiers:
1536//// '<' identifier-list '>'
1537Parser::TPResult Parser::TryParseProtocolQualifiers() {
1538 assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1539 ConsumeToken();
1540 do {
1541 if (Tok.isNot(tok::identifier))
1542 return TPResult::Error();
1543 ConsumeToken();
1544
1545 if (Tok.is(tok::comma)) {
1546 ConsumeToken();
1547 continue;
1548 }
1549
1550 if (Tok.is(tok::greater)) {
1551 ConsumeToken();
1552 return TPResult::Ambiguous();
1553 }
1554 } while (false);
1555
1556 return TPResult::Error();
1557}
1558
Guy Benyei11169dd2012-12-18 14:30:41 +00001559/// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1560/// a constructor-style initializer, when parsing declaration statements.
1561/// Returns true for function declarator and false for constructor-style
1562/// initializer.
1563/// If during the disambiguation process a parsing error is encountered,
1564/// the function returns true to let the declaration parsing code handle it.
1565///
1566/// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1567/// exception-specification[opt]
1568///
1569bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
1570
1571 // C++ 8.2p1:
1572 // The ambiguity arising from the similarity between a function-style cast and
1573 // a declaration mentioned in 6.8 can also occur in the context of a
1574 // declaration. In that context, the choice is between a function declaration
1575 // with a redundant set of parentheses around a parameter name and an object
1576 // declaration with a function-style cast as the initializer. Just as for the
1577 // ambiguities mentioned in 6.8, the resolution is to consider any construct
1578 // that could possibly be a declaration a declaration.
1579
1580 TentativeParsingAction PA(*this);
1581
1582 ConsumeParen();
1583 bool InvalidAsDeclaration = false;
1584 TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
1585 if (TPR == TPResult::Ambiguous()) {
1586 if (Tok.isNot(tok::r_paren))
1587 TPR = TPResult::False();
1588 else {
1589 const Token &Next = NextToken();
1590 if (Next.is(tok::amp) || Next.is(tok::ampamp) ||
1591 Next.is(tok::kw_const) || Next.is(tok::kw_volatile) ||
1592 Next.is(tok::kw_throw) || Next.is(tok::kw_noexcept) ||
Richard Smith89645bc2013-01-02 12:01:23 +00001593 Next.is(tok::l_square) || isCXX11VirtSpecifier(Next) ||
Guy Benyei11169dd2012-12-18 14:30:41 +00001594 Next.is(tok::l_brace) || Next.is(tok::kw_try) ||
1595 Next.is(tok::equal) || Next.is(tok::arrow))
1596 // The next token cannot appear after a constructor-style initializer,
1597 // and can appear next in a function definition. This must be a function
1598 // declarator.
1599 TPR = TPResult::True();
1600 else if (InvalidAsDeclaration)
1601 // Use the absence of 'typename' as a tie-breaker.
1602 TPR = TPResult::False();
1603 }
1604 }
1605
1606 PA.Revert();
1607
1608 if (IsAmbiguous && TPR == TPResult::Ambiguous())
1609 *IsAmbiguous = true;
1610
1611 // In case of an error, let the declaration parsing code handle it.
1612 return TPR != TPResult::False();
1613}
1614
1615/// parameter-declaration-clause:
1616/// parameter-declaration-list[opt] '...'[opt]
1617/// parameter-declaration-list ',' '...'
1618///
1619/// parameter-declaration-list:
1620/// parameter-declaration
1621/// parameter-declaration-list ',' parameter-declaration
1622///
1623/// parameter-declaration:
1624/// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1625/// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1626/// '=' assignment-expression
1627/// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1628/// attributes[opt]
1629/// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1630/// attributes[opt] '=' assignment-expression
1631///
1632Parser::TPResult
Richard Smith1fff95c2013-09-12 23:28:08 +00001633Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration,
1634 bool VersusTemplateArgument) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001635
1636 if (Tok.is(tok::r_paren))
1637 return TPResult::Ambiguous();
1638
1639 // parameter-declaration-list[opt] '...'[opt]
1640 // parameter-declaration-list ',' '...'
1641 //
1642 // parameter-declaration-list:
1643 // parameter-declaration
1644 // parameter-declaration-list ',' parameter-declaration
1645 //
1646 while (1) {
1647 // '...'[opt]
1648 if (Tok.is(tok::ellipsis)) {
1649 ConsumeToken();
1650 if (Tok.is(tok::r_paren))
1651 return TPResult::True(); // '...)' is a sign of a function declarator.
1652 else
1653 return TPResult::False();
1654 }
1655
1656 // An attribute-specifier-seq here is a sign of a function declarator.
1657 if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
1658 /*OuterMightBeMessageSend*/true))
1659 return TPResult::True();
1660
1661 ParsedAttributes attrs(AttrFactory);
1662 MaybeParseMicrosoftAttributes(attrs);
1663
1664 // decl-specifier-seq
1665 // A parameter-declaration's initializer must be preceded by an '=', so
1666 // decl-specifier-seq '{' is not a parameter in C++11.
Richard Smith1fff95c2013-09-12 23:28:08 +00001667 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False(),
1668 InvalidAsDeclaration);
1669
1670 if (VersusTemplateArgument && TPR == TPResult::True()) {
1671 // Consume the decl-specifier-seq. We have to look past it, since a
1672 // type-id might appear here in a template argument.
1673 bool SeenType = false;
1674 do {
1675 SeenType |= isCXXDeclarationSpecifierAType();
1676 if (TryConsumeDeclarationSpecifier() == TPResult::Error())
1677 return TPResult::Error();
1678
1679 // If we see a parameter name, this can't be a template argument.
1680 if (SeenType && Tok.is(tok::identifier))
1681 return TPResult::True();
1682
1683 TPR = isCXXDeclarationSpecifier(TPResult::False(),
1684 InvalidAsDeclaration);
1685 if (TPR == TPResult::Error())
1686 return TPR;
1687 } while (TPR != TPResult::False());
1688 } else if (TPR == TPResult::Ambiguous()) {
1689 // Disambiguate what follows the decl-specifier.
1690 if (TryConsumeDeclarationSpecifier() == TPResult::Error())
1691 return TPResult::Error();
1692 } else
Guy Benyei11169dd2012-12-18 14:30:41 +00001693 return TPR;
1694
1695 // declarator
1696 // abstract-declarator[opt]
1697 TPR = TryParseDeclarator(true/*mayBeAbstract*/);
1698 if (TPR != TPResult::Ambiguous())
1699 return TPR;
1700
1701 // [GNU] attributes[opt]
1702 if (Tok.is(tok::kw___attribute))
1703 return TPResult::True();
1704
Richard Smith1fff95c2013-09-12 23:28:08 +00001705 // If we're disambiguating a template argument in a default argument in
1706 // a class definition versus a parameter declaration, an '=' here
1707 // disambiguates the parse one way or the other.
1708 // If this is a parameter, it must have a default argument because
1709 // (a) the previous parameter did, and
1710 // (b) this must be the first declaration of the function, so we can't
1711 // inherit any default arguments from elsewhere.
1712 // If we see an ')', then we've reached the end of a
1713 // parameter-declaration-clause, and the last param is missing its default
1714 // argument.
1715 if (VersusTemplateArgument)
1716 return (Tok.is(tok::equal) || Tok.is(tok::r_paren)) ? TPResult::True()
1717 : TPResult::False();
1718
Guy Benyei11169dd2012-12-18 14:30:41 +00001719 if (Tok.is(tok::equal)) {
1720 // '=' assignment-expression
1721 // Parse through assignment-expression.
Richard Smith1fff95c2013-09-12 23:28:08 +00001722 // FIXME: assignment-expression may contain an unparenthesized comma.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001723 if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch))
Guy Benyei11169dd2012-12-18 14:30:41 +00001724 return TPResult::Error();
1725 }
1726
1727 if (Tok.is(tok::ellipsis)) {
1728 ConsumeToken();
1729 if (Tok.is(tok::r_paren))
1730 return TPResult::True(); // '...)' is a sign of a function declarator.
1731 else
1732 return TPResult::False();
1733 }
1734
1735 if (Tok.isNot(tok::comma))
1736 break;
1737 ConsumeToken(); // the comma.
1738 }
1739
1740 return TPResult::Ambiguous();
1741}
1742
1743/// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
1744/// parsing as a function declarator.
1745/// If TryParseFunctionDeclarator fully parsed the function declarator, it will
1746/// return TPResult::Ambiguous(), otherwise it will return either False() or
1747/// Error().
1748///
1749/// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1750/// exception-specification[opt]
1751///
1752/// exception-specification:
1753/// 'throw' '(' type-id-list[opt] ')'
1754///
1755Parser::TPResult Parser::TryParseFunctionDeclarator() {
1756
1757 // The '(' is already parsed.
1758
1759 TPResult TPR = TryParseParameterDeclarationClause();
1760 if (TPR == TPResult::Ambiguous() && Tok.isNot(tok::r_paren))
1761 TPR = TPResult::False();
1762
1763 if (TPR == TPResult::False() || TPR == TPResult::Error())
1764 return TPR;
1765
1766 // Parse through the parens.
Alexey Bataevee6507d2013-11-18 08:17:37 +00001767 if (!SkipUntil(tok::r_paren, StopAtSemi))
Guy Benyei11169dd2012-12-18 14:30:41 +00001768 return TPResult::Error();
1769
1770 // cv-qualifier-seq
1771 while (Tok.is(tok::kw_const) ||
1772 Tok.is(tok::kw_volatile) ||
1773 Tok.is(tok::kw_restrict) )
1774 ConsumeToken();
1775
1776 // ref-qualifier[opt]
1777 if (Tok.is(tok::amp) || Tok.is(tok::ampamp))
1778 ConsumeToken();
1779
1780 // exception-specification
1781 if (Tok.is(tok::kw_throw)) {
1782 ConsumeToken();
1783 if (Tok.isNot(tok::l_paren))
1784 return TPResult::Error();
1785
1786 // Parse through the parens after 'throw'.
1787 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001788 if (!SkipUntil(tok::r_paren, StopAtSemi))
Guy Benyei11169dd2012-12-18 14:30:41 +00001789 return TPResult::Error();
1790 }
1791 if (Tok.is(tok::kw_noexcept)) {
1792 ConsumeToken();
1793 // Possibly an expression as well.
1794 if (Tok.is(tok::l_paren)) {
1795 // Find the matching rparen.
1796 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001797 if (!SkipUntil(tok::r_paren, StopAtSemi))
Guy Benyei11169dd2012-12-18 14:30:41 +00001798 return TPResult::Error();
1799 }
1800 }
1801
1802 return TPResult::Ambiguous();
1803}
1804
1805/// '[' constant-expression[opt] ']'
1806///
1807Parser::TPResult Parser::TryParseBracketDeclarator() {
1808 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001809 if (!SkipUntil(tok::r_square, StopAtSemi))
Guy Benyei11169dd2012-12-18 14:30:41 +00001810 return TPResult::Error();
1811
1812 return TPResult::Ambiguous();
1813}