1 //===--- ParseDecl.cpp - Declaration 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 Declaration portions of the Parser interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Parse/Parser.h"
15 #include "clang/Parse/ParseDiagnostic.h"
16 #include "clang/Basic/OpenCL.h"
17 #include "clang/Sema/Scope.h"
18 #include "clang/Sema/ParsedTemplate.h"
19 #include "clang/Sema/PrettyDeclStackTrace.h"
20 #include "RAIIObjectsForParser.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringSwitch.h"
24 using namespace clang;
25
26 //===----------------------------------------------------------------------===//
27 // C99 6.7: Declarations.
28 //===----------------------------------------------------------------------===//
29
30 /// ParseTypeName
31 /// type-name: [C99 6.7.6]
32 /// specifier-qualifier-list abstract-declarator[opt]
33 ///
34 /// Called type-id in C++.
ParseTypeName(SourceRange * Range,Declarator::TheContext Context,AccessSpecifier AS,Decl ** OwnedType)35 TypeResult Parser::ParseTypeName(SourceRange *Range,
36 Declarator::TheContext Context,
37 AccessSpecifier AS,
38 Decl **OwnedType) {
39 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
40
41 // Parse the common declaration-specifiers piece.
42 DeclSpec DS(AttrFactory);
43 ParseSpecifierQualifierList(DS, AS, DSC);
44 if (OwnedType)
45 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : 0;
46
47 // Parse the abstract-declarator, if present.
48 Declarator DeclaratorInfo(DS, Context);
49 ParseDeclarator(DeclaratorInfo);
50 if (Range)
51 *Range = DeclaratorInfo.getSourceRange();
52
53 if (DeclaratorInfo.isInvalidType())
54 return true;
55
56 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
57 }
58
59
60 /// isAttributeLateParsed - Return true if the attribute has arguments that
61 /// require late parsing.
isAttributeLateParsed(const IdentifierInfo & II)62 static bool isAttributeLateParsed(const IdentifierInfo &II) {
63 return llvm::StringSwitch<bool>(II.getName())
64 #include "clang/Parse/AttrLateParsed.inc"
65 .Default(false);
66 }
67
68
69 /// ParseGNUAttributes - Parse a non-empty attributes list.
70 ///
71 /// [GNU] attributes:
72 /// attribute
73 /// attributes attribute
74 ///
75 /// [GNU] attribute:
76 /// '__attribute__' '(' '(' attribute-list ')' ')'
77 ///
78 /// [GNU] attribute-list:
79 /// attrib
80 /// attribute_list ',' attrib
81 ///
82 /// [GNU] attrib:
83 /// empty
84 /// attrib-name
85 /// attrib-name '(' identifier ')'
86 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
87 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
88 ///
89 /// [GNU] attrib-name:
90 /// identifier
91 /// typespec
92 /// typequal
93 /// storageclass
94 ///
95 /// FIXME: The GCC grammar/code for this construct implies we need two
96 /// token lookahead. Comment from gcc: "If they start with an identifier
97 /// which is followed by a comma or close parenthesis, then the arguments
98 /// start with that identifier; otherwise they are an expression list."
99 ///
100 /// GCC does not require the ',' between attribs in an attribute-list.
101 ///
102 /// At the moment, I am not doing 2 token lookahead. I am also unaware of
103 /// any attributes that don't work (based on my limited testing). Most
104 /// attributes are very simple in practice. Until we find a bug, I don't see
105 /// a pressing need to implement the 2 token lookahead.
106
ParseGNUAttributes(ParsedAttributes & attrs,SourceLocation * endLoc,LateParsedAttrList * LateAttrs)107 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
108 SourceLocation *endLoc,
109 LateParsedAttrList *LateAttrs) {
110 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
111
112 while (Tok.is(tok::kw___attribute)) {
113 ConsumeToken();
114 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
115 "attribute")) {
116 SkipUntil(tok::r_paren, true); // skip until ) or ;
117 return;
118 }
119 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
120 SkipUntil(tok::r_paren, true); // skip until ) or ;
121 return;
122 }
123 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
124 while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
125 Tok.is(tok::comma)) {
126 if (Tok.is(tok::comma)) {
127 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
128 ConsumeToken();
129 continue;
130 }
131 // we have an identifier or declaration specifier (const, int, etc.)
132 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
133 SourceLocation AttrNameLoc = ConsumeToken();
134
135 if (Tok.is(tok::l_paren)) {
136 // handle "parameterized" attributes
137 if (LateAttrs && isAttributeLateParsed(*AttrName)) {
138 LateParsedAttribute *LA =
139 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
140 LateAttrs->push_back(LA);
141
142 // Attributes in a class are parsed at the end of the class, along
143 // with other late-parsed declarations.
144 if (!ClassStack.empty())
145 getCurrentClass().LateParsedDeclarations.push_back(LA);
146
147 // consume everything up to and including the matching right parens
148 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
149
150 Token Eof;
151 Eof.startToken();
152 Eof.setLocation(Tok.getLocation());
153 LA->Toks.push_back(Eof);
154 } else {
155 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc);
156 }
157 } else {
158 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
159 0, SourceLocation(), 0, 0);
160 }
161 }
162 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
163 SkipUntil(tok::r_paren, false);
164 SourceLocation Loc = Tok.getLocation();
165 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
166 SkipUntil(tok::r_paren, false);
167 }
168 if (endLoc)
169 *endLoc = Loc;
170 }
171 }
172
173
174 /// Parse the arguments to a parameterized GNU attribute
ParseGNUAttributeArgs(IdentifierInfo * AttrName,SourceLocation AttrNameLoc,ParsedAttributes & Attrs,SourceLocation * EndLoc)175 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
176 SourceLocation AttrNameLoc,
177 ParsedAttributes &Attrs,
178 SourceLocation *EndLoc) {
179
180 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
181
182 // Availability attributes have their own grammar.
183 if (AttrName->isStr("availability")) {
184 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
185 return;
186 }
187 // Thread safety attributes fit into the FIXME case above, so we
188 // just parse the arguments as a list of expressions
189 if (IsThreadSafetyAttribute(AttrName->getName())) {
190 ParseThreadSafetyAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
191 return;
192 }
193
194 ConsumeParen(); // ignore the left paren loc for now
195
196 IdentifierInfo *ParmName = 0;
197 SourceLocation ParmLoc;
198 bool BuiltinType = false;
199
200 switch (Tok.getKind()) {
201 case tok::kw_char:
202 case tok::kw_wchar_t:
203 case tok::kw_char16_t:
204 case tok::kw_char32_t:
205 case tok::kw_bool:
206 case tok::kw_short:
207 case tok::kw_int:
208 case tok::kw_long:
209 case tok::kw___int64:
210 case tok::kw___int128:
211 case tok::kw_signed:
212 case tok::kw_unsigned:
213 case tok::kw_float:
214 case tok::kw_double:
215 case tok::kw_void:
216 case tok::kw_typeof:
217 // __attribute__(( vec_type_hint(char) ))
218 // FIXME: Don't just discard the builtin type token.
219 ConsumeToken();
220 BuiltinType = true;
221 break;
222
223 case tok::identifier:
224 ParmName = Tok.getIdentifierInfo();
225 ParmLoc = ConsumeToken();
226 break;
227
228 default:
229 break;
230 }
231
232 ExprVector ArgExprs(Actions);
233
234 if (!BuiltinType &&
235 (ParmLoc.isValid() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren))) {
236 // Eat the comma.
237 if (ParmLoc.isValid())
238 ConsumeToken();
239
240 // Parse the non-empty comma-separated list of expressions.
241 while (1) {
242 ExprResult ArgExpr(ParseAssignmentExpression());
243 if (ArgExpr.isInvalid()) {
244 SkipUntil(tok::r_paren);
245 return;
246 }
247 ArgExprs.push_back(ArgExpr.release());
248 if (Tok.isNot(tok::comma))
249 break;
250 ConsumeToken(); // Eat the comma, move to the next argument
251 }
252 }
253 else if (Tok.is(tok::less) && AttrName->isStr("iboutletcollection")) {
254 if (!ExpectAndConsume(tok::less, diag::err_expected_less_after, "<",
255 tok::greater)) {
256 while (Tok.is(tok::identifier)) {
257 ConsumeToken();
258 if (Tok.is(tok::greater))
259 break;
260 if (Tok.is(tok::comma)) {
261 ConsumeToken();
262 continue;
263 }
264 }
265 if (Tok.isNot(tok::greater))
266 Diag(Tok, diag::err_iboutletcollection_with_protocol);
267 SkipUntil(tok::r_paren, false, true); // skip until ')'
268 }
269 }
270
271 SourceLocation RParen = Tok.getLocation();
272 if (!ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
273 AttributeList *attr =
274 Attrs.addNew(AttrName, SourceRange(AttrNameLoc, RParen), 0, AttrNameLoc,
275 ParmName, ParmLoc, ArgExprs.take(), ArgExprs.size());
276 if (BuiltinType && attr->getKind() == AttributeList::AT_iboutletcollection)
277 Diag(Tok, diag::err_iboutletcollection_builtintype);
278 }
279 }
280
281
282 /// ParseMicrosoftDeclSpec - Parse an __declspec construct
283 ///
284 /// [MS] decl-specifier:
285 /// __declspec ( extended-decl-modifier-seq )
286 ///
287 /// [MS] extended-decl-modifier-seq:
288 /// extended-decl-modifier[opt]
289 /// extended-decl-modifier extended-decl-modifier-seq
290
ParseMicrosoftDeclSpec(ParsedAttributes & attrs)291 void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &attrs) {
292 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
293
294 ConsumeToken();
295 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
296 "declspec")) {
297 SkipUntil(tok::r_paren, true); // skip until ) or ;
298 return;
299 }
300
301 while (Tok.getIdentifierInfo()) {
302 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
303 SourceLocation AttrNameLoc = ConsumeToken();
304
305 // FIXME: Remove this when we have proper __declspec(property()) support.
306 // Just skip everything inside property().
307 if (AttrName->getName() == "property") {
308 ConsumeParen();
309 SkipUntil(tok::r_paren);
310 }
311 if (Tok.is(tok::l_paren)) {
312 ConsumeParen();
313 // FIXME: This doesn't parse __declspec(property(get=get_func_name))
314 // correctly.
315 ExprResult ArgExpr(ParseAssignmentExpression());
316 if (!ArgExpr.isInvalid()) {
317 Expr *ExprList = ArgExpr.take();
318 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
319 SourceLocation(), &ExprList, 1, true);
320 }
321 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
322 SkipUntil(tok::r_paren, false);
323 } else {
324 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
325 0, SourceLocation(), 0, 0, true);
326 }
327 }
328 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
329 SkipUntil(tok::r_paren, false);
330 return;
331 }
332
ParseMicrosoftTypeAttributes(ParsedAttributes & attrs)333 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
334 // Treat these like attributes
335 // FIXME: Allow Sema to distinguish between these and real attributes!
336 while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
337 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl) ||
338 Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) ||
339 Tok.is(tok::kw___ptr32) ||
340 Tok.is(tok::kw___unaligned)) {
341 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
342 SourceLocation AttrNameLoc = ConsumeToken();
343 if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) ||
344 Tok.is(tok::kw___ptr32))
345 // FIXME: Support these properly!
346 continue;
347 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
348 SourceLocation(), 0, 0, true);
349 }
350 }
351
ParseBorlandTypeAttributes(ParsedAttributes & attrs)352 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
353 // Treat these like attributes
354 while (Tok.is(tok::kw___pascal)) {
355 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
356 SourceLocation AttrNameLoc = ConsumeToken();
357 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
358 SourceLocation(), 0, 0, true);
359 }
360 }
361
ParseOpenCLAttributes(ParsedAttributes & attrs)362 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
363 // Treat these like attributes
364 while (Tok.is(tok::kw___kernel)) {
365 SourceLocation AttrNameLoc = ConsumeToken();
366 attrs.addNew(PP.getIdentifierInfo("opencl_kernel_function"),
367 AttrNameLoc, 0, AttrNameLoc, 0,
368 SourceLocation(), 0, 0, false);
369 }
370 }
371
ParseOpenCLQualifiers(DeclSpec & DS)372 void Parser::ParseOpenCLQualifiers(DeclSpec &DS) {
373 SourceLocation Loc = Tok.getLocation();
374 switch(Tok.getKind()) {
375 // OpenCL qualifiers:
376 case tok::kw___private:
377 case tok::kw_private:
378 DS.getAttributes().addNewInteger(
379 Actions.getASTContext(),
380 PP.getIdentifierInfo("address_space"), Loc, 0);
381 break;
382
383 case tok::kw___global:
384 DS.getAttributes().addNewInteger(
385 Actions.getASTContext(),
386 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global);
387 break;
388
389 case tok::kw___local:
390 DS.getAttributes().addNewInteger(
391 Actions.getASTContext(),
392 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local);
393 break;
394
395 case tok::kw___constant:
396 DS.getAttributes().addNewInteger(
397 Actions.getASTContext(),
398 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant);
399 break;
400
401 case tok::kw___read_only:
402 DS.getAttributes().addNewInteger(
403 Actions.getASTContext(),
404 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only);
405 break;
406
407 case tok::kw___write_only:
408 DS.getAttributes().addNewInteger(
409 Actions.getASTContext(),
410 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only);
411 break;
412
413 case tok::kw___read_write:
414 DS.getAttributes().addNewInteger(
415 Actions.getASTContext(),
416 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write);
417 break;
418 default: break;
419 }
420 }
421
422 /// \brief Parse a version number.
423 ///
424 /// version:
425 /// simple-integer
426 /// simple-integer ',' simple-integer
427 /// simple-integer ',' simple-integer ',' simple-integer
ParseVersionTuple(SourceRange & Range)428 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
429 Range = Tok.getLocation();
430
431 if (!Tok.is(tok::numeric_constant)) {
432 Diag(Tok, diag::err_expected_version);
433 SkipUntil(tok::comma, tok::r_paren, true, true, true);
434 return VersionTuple();
435 }
436
437 // Parse the major (and possibly minor and subminor) versions, which
438 // are stored in the numeric constant. We utilize a quirk of the
439 // lexer, which is that it handles something like 1.2.3 as a single
440 // numeric constant, rather than two separate tokens.
441 SmallString<512> Buffer;
442 Buffer.resize(Tok.getLength()+1);
443 const char *ThisTokBegin = &Buffer[0];
444
445 // Get the spelling of the token, which eliminates trigraphs, etc.
446 bool Invalid = false;
447 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
448 if (Invalid)
449 return VersionTuple();
450
451 // Parse the major version.
452 unsigned AfterMajor = 0;
453 unsigned Major = 0;
454 while (AfterMajor < ActualLength && isdigit(ThisTokBegin[AfterMajor])) {
455 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
456 ++AfterMajor;
457 }
458
459 if (AfterMajor == 0) {
460 Diag(Tok, diag::err_expected_version);
461 SkipUntil(tok::comma, tok::r_paren, true, true, true);
462 return VersionTuple();
463 }
464
465 if (AfterMajor == ActualLength) {
466 ConsumeToken();
467
468 // We only had a single version component.
469 if (Major == 0) {
470 Diag(Tok, diag::err_zero_version);
471 return VersionTuple();
472 }
473
474 return VersionTuple(Major);
475 }
476
477 if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) {
478 Diag(Tok, diag::err_expected_version);
479 SkipUntil(tok::comma, tok::r_paren, true, true, true);
480 return VersionTuple();
481 }
482
483 // Parse the minor version.
484 unsigned AfterMinor = AfterMajor + 1;
485 unsigned Minor = 0;
486 while (AfterMinor < ActualLength && isdigit(ThisTokBegin[AfterMinor])) {
487 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
488 ++AfterMinor;
489 }
490
491 if (AfterMinor == ActualLength) {
492 ConsumeToken();
493
494 // We had major.minor.
495 if (Major == 0 && Minor == 0) {
496 Diag(Tok, diag::err_zero_version);
497 return VersionTuple();
498 }
499
500 return VersionTuple(Major, Minor);
501 }
502
503 // If what follows is not a '.', we have a problem.
504 if (ThisTokBegin[AfterMinor] != '.') {
505 Diag(Tok, diag::err_expected_version);
506 SkipUntil(tok::comma, tok::r_paren, true, true, true);
507 return VersionTuple();
508 }
509
510 // Parse the subminor version.
511 unsigned AfterSubminor = AfterMinor + 1;
512 unsigned Subminor = 0;
513 while (AfterSubminor < ActualLength && isdigit(ThisTokBegin[AfterSubminor])) {
514 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
515 ++AfterSubminor;
516 }
517
518 if (AfterSubminor != ActualLength) {
519 Diag(Tok, diag::err_expected_version);
520 SkipUntil(tok::comma, tok::r_paren, true, true, true);
521 return VersionTuple();
522 }
523 ConsumeToken();
524 return VersionTuple(Major, Minor, Subminor);
525 }
526
527 /// \brief Parse the contents of the "availability" attribute.
528 ///
529 /// availability-attribute:
530 /// 'availability' '(' platform ',' version-arg-list, opt-message')'
531 ///
532 /// platform:
533 /// identifier
534 ///
535 /// version-arg-list:
536 /// version-arg
537 /// version-arg ',' version-arg-list
538 ///
539 /// version-arg:
540 /// 'introduced' '=' version
541 /// 'deprecated' '=' version
542 /// 'obsoleted' = version
543 /// 'unavailable'
544 /// opt-message:
545 /// 'message' '=' <string>
ParseAvailabilityAttribute(IdentifierInfo & Availability,SourceLocation AvailabilityLoc,ParsedAttributes & attrs,SourceLocation * endLoc)546 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
547 SourceLocation AvailabilityLoc,
548 ParsedAttributes &attrs,
549 SourceLocation *endLoc) {
550 SourceLocation PlatformLoc;
551 IdentifierInfo *Platform = 0;
552
553 enum { Introduced, Deprecated, Obsoleted, Unknown };
554 AvailabilityChange Changes[Unknown];
555 ExprResult MessageExpr;
556
557 // Opening '('.
558 BalancedDelimiterTracker T(*this, tok::l_paren);
559 if (T.consumeOpen()) {
560 Diag(Tok, diag::err_expected_lparen);
561 return;
562 }
563
564 // Parse the platform name,
565 if (Tok.isNot(tok::identifier)) {
566 Diag(Tok, diag::err_availability_expected_platform);
567 SkipUntil(tok::r_paren);
568 return;
569 }
570 Platform = Tok.getIdentifierInfo();
571 PlatformLoc = ConsumeToken();
572
573 // Parse the ',' following the platform name.
574 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren))
575 return;
576
577 // If we haven't grabbed the pointers for the identifiers
578 // "introduced", "deprecated", and "obsoleted", do so now.
579 if (!Ident_introduced) {
580 Ident_introduced = PP.getIdentifierInfo("introduced");
581 Ident_deprecated = PP.getIdentifierInfo("deprecated");
582 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
583 Ident_unavailable = PP.getIdentifierInfo("unavailable");
584 Ident_message = PP.getIdentifierInfo("message");
585 }
586
587 // Parse the set of introductions/deprecations/removals.
588 SourceLocation UnavailableLoc;
589 do {
590 if (Tok.isNot(tok::identifier)) {
591 Diag(Tok, diag::err_availability_expected_change);
592 SkipUntil(tok::r_paren);
593 return;
594 }
595 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
596 SourceLocation KeywordLoc = ConsumeToken();
597
598 if (Keyword == Ident_unavailable) {
599 if (UnavailableLoc.isValid()) {
600 Diag(KeywordLoc, diag::err_availability_redundant)
601 << Keyword << SourceRange(UnavailableLoc);
602 }
603 UnavailableLoc = KeywordLoc;
604
605 if (Tok.isNot(tok::comma))
606 break;
607
608 ConsumeToken();
609 continue;
610 }
611
612 if (Tok.isNot(tok::equal)) {
613 Diag(Tok, diag::err_expected_equal_after)
614 << Keyword;
615 SkipUntil(tok::r_paren);
616 return;
617 }
618 ConsumeToken();
619 if (Keyword == Ident_message) {
620 if (!isTokenStringLiteral()) {
621 Diag(Tok, diag::err_expected_string_literal);
622 SkipUntil(tok::r_paren);
623 return;
624 }
625 MessageExpr = ParseStringLiteralExpression();
626 break;
627 }
628
629 SourceRange VersionRange;
630 VersionTuple Version = ParseVersionTuple(VersionRange);
631
632 if (Version.empty()) {
633 SkipUntil(tok::r_paren);
634 return;
635 }
636
637 unsigned Index;
638 if (Keyword == Ident_introduced)
639 Index = Introduced;
640 else if (Keyword == Ident_deprecated)
641 Index = Deprecated;
642 else if (Keyword == Ident_obsoleted)
643 Index = Obsoleted;
644 else
645 Index = Unknown;
646
647 if (Index < Unknown) {
648 if (!Changes[Index].KeywordLoc.isInvalid()) {
649 Diag(KeywordLoc, diag::err_availability_redundant)
650 << Keyword
651 << SourceRange(Changes[Index].KeywordLoc,
652 Changes[Index].VersionRange.getEnd());
653 }
654
655 Changes[Index].KeywordLoc = KeywordLoc;
656 Changes[Index].Version = Version;
657 Changes[Index].VersionRange = VersionRange;
658 } else {
659 Diag(KeywordLoc, diag::err_availability_unknown_change)
660 << Keyword << VersionRange;
661 }
662
663 if (Tok.isNot(tok::comma))
664 break;
665
666 ConsumeToken();
667 } while (true);
668
669 // Closing ')'.
670 if (T.consumeClose())
671 return;
672
673 if (endLoc)
674 *endLoc = T.getCloseLocation();
675
676 // The 'unavailable' availability cannot be combined with any other
677 // availability changes. Make sure that hasn't happened.
678 if (UnavailableLoc.isValid()) {
679 bool Complained = false;
680 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
681 if (Changes[Index].KeywordLoc.isValid()) {
682 if (!Complained) {
683 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
684 << SourceRange(Changes[Index].KeywordLoc,
685 Changes[Index].VersionRange.getEnd());
686 Complained = true;
687 }
688
689 // Clear out the availability.
690 Changes[Index] = AvailabilityChange();
691 }
692 }
693 }
694
695 // Record this attribute
696 attrs.addNew(&Availability,
697 SourceRange(AvailabilityLoc, T.getCloseLocation()),
698 0, AvailabilityLoc,
699 Platform, PlatformLoc,
700 Changes[Introduced],
701 Changes[Deprecated],
702 Changes[Obsoleted],
703 UnavailableLoc, MessageExpr.take(),
704 false, false);
705 }
706
707
708 // Late Parsed Attributes:
709 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
710
ParseLexedAttributes()711 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
712
ParseLexedAttributes()713 void Parser::LateParsedClass::ParseLexedAttributes() {
714 Self->ParseLexedAttributes(*Class);
715 }
716
ParseLexedAttributes()717 void Parser::LateParsedAttribute::ParseLexedAttributes() {
718 Self->ParseLexedAttribute(*this, true, false);
719 }
720
721 /// Wrapper class which calls ParseLexedAttribute, after setting up the
722 /// scope appropriately.
ParseLexedAttributes(ParsingClass & Class)723 void Parser::ParseLexedAttributes(ParsingClass &Class) {
724 // Deal with templates
725 // FIXME: Test cases to make sure this does the right thing for templates.
726 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
727 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
728 HasTemplateScope);
729 if (HasTemplateScope)
730 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
731
732 // Set or update the scope flags.
733 bool AlreadyHasClassScope = Class.TopLevelClass;
734 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
735 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
736 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
737
738 // Enter the scope of nested classes
739 if (!AlreadyHasClassScope)
740 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
741 Class.TagOrTemplate);
742 {
743 // Allow 'this' within late-parsed attributes.
744 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
745 /*TypeQuals=*/0);
746
747 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
748 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
749 }
750 }
751
752 if (!AlreadyHasClassScope)
753 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
754 Class.TagOrTemplate);
755 }
756
757
758 /// \brief Parse all attributes in LAs, and attach them to Decl D.
ParseLexedAttributeList(LateParsedAttrList & LAs,Decl * D,bool EnterScope,bool OnDefinition)759 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
760 bool EnterScope, bool OnDefinition) {
761 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
762 LAs[i]->addDecl(D);
763 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
764 delete LAs[i];
765 }
766 LAs.clear();
767 }
768
769
770 /// \brief Finish parsing an attribute for which parsing was delayed.
771 /// This will be called at the end of parsing a class declaration
772 /// for each LateParsedAttribute. We consume the saved tokens and
773 /// create an attribute with the arguments filled in. We add this
774 /// to the Attribute list for the decl.
ParseLexedAttribute(LateParsedAttribute & LA,bool EnterScope,bool OnDefinition)775 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
776 bool EnterScope, bool OnDefinition) {
777 // Save the current token position.
778 SourceLocation OrigLoc = Tok.getLocation();
779
780 // Append the current token at the end of the new token stream so that it
781 // doesn't get lost.
782 LA.Toks.push_back(Tok);
783 PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false);
784 // Consume the previously pushed token.
785 ConsumeAnyToken();
786
787 if (OnDefinition && !IsThreadSafetyAttribute(LA.AttrName.getName())) {
788 Diag(Tok, diag::warn_attribute_on_function_definition)
789 << LA.AttrName.getName();
790 }
791
792 ParsedAttributes Attrs(AttrFactory);
793 SourceLocation endLoc;
794
795 if (LA.Decls.size() == 1) {
796 Decl *D = LA.Decls[0];
797
798 // If the Decl is templatized, add template parameters to scope.
799 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
800 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
801 if (HasTemplateScope)
802 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
803
804 // If the Decl is on a function, add function parameters to the scope.
805 bool HasFunctionScope = EnterScope && D->isFunctionOrFunctionTemplate();
806 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunctionScope);
807 if (HasFunctionScope)
808 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
809
810 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc);
811
812 if (HasFunctionScope) {
813 Actions.ActOnExitFunctionContext();
814 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
815 }
816 if (HasTemplateScope) {
817 TempScope.Exit();
818 }
819 } else if (LA.Decls.size() > 0) {
820 // If there are multiple decls, then the decl cannot be within the
821 // function scope.
822 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc);
823 } else {
824 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
825 }
826
827 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) {
828 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
829 }
830
831 if (Tok.getLocation() != OrigLoc) {
832 // Due to a parsing error, we either went over the cached tokens or
833 // there are still cached tokens left, so we skip the leftover tokens.
834 // Since this is an uncommon situation that should be avoided, use the
835 // expensive isBeforeInTranslationUnit call.
836 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
837 OrigLoc))
838 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
839 ConsumeAnyToken();
840 }
841 }
842
843 /// \brief Wrapper around a case statement checking if AttrName is
844 /// one of the thread safety attributes
IsThreadSafetyAttribute(llvm::StringRef AttrName)845 bool Parser::IsThreadSafetyAttribute(llvm::StringRef AttrName){
846 return llvm::StringSwitch<bool>(AttrName)
847 .Case("guarded_by", true)
848 .Case("guarded_var", true)
849 .Case("pt_guarded_by", true)
850 .Case("pt_guarded_var", true)
851 .Case("lockable", true)
852 .Case("scoped_lockable", true)
853 .Case("no_thread_safety_analysis", true)
854 .Case("acquired_after", true)
855 .Case("acquired_before", true)
856 .Case("exclusive_lock_function", true)
857 .Case("shared_lock_function", true)
858 .Case("exclusive_trylock_function", true)
859 .Case("shared_trylock_function", true)
860 .Case("unlock_function", true)
861 .Case("lock_returned", true)
862 .Case("locks_excluded", true)
863 .Case("exclusive_locks_required", true)
864 .Case("shared_locks_required", true)
865 .Default(false);
866 }
867
868 /// \brief Parse the contents of thread safety attributes. These
869 /// should always be parsed as an expression list.
870 ///
871 /// We need to special case the parsing due to the fact that if the first token
872 /// of the first argument is an identifier, the main parse loop will store
873 /// that token as a "parameter" and the rest of
874 /// the arguments will be added to a list of "arguments". However,
875 /// subsequent tokens in the first argument are lost. We instead parse each
876 /// argument as an expression and add all arguments to the list of "arguments".
877 /// In future, we will take advantage of this special case to also
878 /// deal with some argument scoping issues here (for example, referring to a
879 /// function parameter in the attribute on that function).
ParseThreadSafetyAttribute(IdentifierInfo & AttrName,SourceLocation AttrNameLoc,ParsedAttributes & Attrs,SourceLocation * EndLoc)880 void Parser::ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
881 SourceLocation AttrNameLoc,
882 ParsedAttributes &Attrs,
883 SourceLocation *EndLoc) {
884 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
885
886 BalancedDelimiterTracker T(*this, tok::l_paren);
887 T.consumeOpen();
888
889 ExprVector ArgExprs(Actions);
890 bool ArgExprsOk = true;
891
892 // now parse the list of expressions
893 while (Tok.isNot(tok::r_paren)) {
894 ExprResult ArgExpr(ParseAssignmentExpression());
895 if (ArgExpr.isInvalid()) {
896 ArgExprsOk = false;
897 T.consumeClose();
898 break;
899 } else {
900 ArgExprs.push_back(ArgExpr.release());
901 }
902 if (Tok.isNot(tok::comma))
903 break;
904 ConsumeToken(); // Eat the comma, move to the next argument
905 }
906 // Match the ')'.
907 if (ArgExprsOk && !T.consumeClose()) {
908 Attrs.addNew(&AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
909 ArgExprs.take(), ArgExprs.size());
910 }
911 if (EndLoc)
912 *EndLoc = T.getCloseLocation();
913 }
914
915 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
916 /// of a C++11 attribute-specifier in a location where an attribute is not
917 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
918 /// situation.
919 ///
920 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
921 /// this doesn't appear to actually be an attribute-specifier, and the caller
922 /// should try to parse it.
DiagnoseProhibitedCXX11Attribute()923 bool Parser::DiagnoseProhibitedCXX11Attribute() {
924 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
925
926 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
927 case CAK_NotAttributeSpecifier:
928 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
929 return false;
930
931 case CAK_InvalidAttributeSpecifier:
932 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
933 return false;
934
935 case CAK_AttributeSpecifier:
936 // Parse and discard the attributes.
937 SourceLocation BeginLoc = ConsumeBracket();
938 ConsumeBracket();
939 SkipUntil(tok::r_square, /*StopAtSemi*/ false);
940 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
941 SourceLocation EndLoc = ConsumeBracket();
942 Diag(BeginLoc, diag::err_attributes_not_allowed)
943 << SourceRange(BeginLoc, EndLoc);
944 return true;
945 }
946 llvm_unreachable("All cases handled above.");
947 }
948
DiagnoseProhibitedAttributes(ParsedAttributesWithRange & attrs)949 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
950 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
951 << attrs.Range;
952 }
953
954 /// ParseDeclaration - Parse a full 'declaration', which consists of
955 /// declaration-specifiers, some number of declarators, and a semicolon.
956 /// 'Context' should be a Declarator::TheContext value. This returns the
957 /// location of the semicolon in DeclEnd.
958 ///
959 /// declaration: [C99 6.7]
960 /// block-declaration ->
961 /// simple-declaration
962 /// others [FIXME]
963 /// [C++] template-declaration
964 /// [C++] namespace-definition
965 /// [C++] using-directive
966 /// [C++] using-declaration
967 /// [C++11/C11] static_assert-declaration
968 /// others... [FIXME]
969 ///
ParseDeclaration(StmtVector & Stmts,unsigned Context,SourceLocation & DeclEnd,ParsedAttributesWithRange & attrs)970 Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
971 unsigned Context,
972 SourceLocation &DeclEnd,
973 ParsedAttributesWithRange &attrs) {
974 ParenBraceBracketBalancer BalancerRAIIObj(*this);
975 // Must temporarily exit the objective-c container scope for
976 // parsing c none objective-c decls.
977 ObjCDeclContextSwitch ObjCDC(*this);
978
979 Decl *SingleDecl = 0;
980 Decl *OwnedType = 0;
981 switch (Tok.getKind()) {
982 case tok::kw_template:
983 case tok::kw_export:
984 ProhibitAttributes(attrs);
985 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
986 break;
987 case tok::kw_inline:
988 // Could be the start of an inline namespace. Allowed as an ext in C++03.
989 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
990 ProhibitAttributes(attrs);
991 SourceLocation InlineLoc = ConsumeToken();
992 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
993 break;
994 }
995 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs,
996 true);
997 case tok::kw_namespace:
998 ProhibitAttributes(attrs);
999 SingleDecl = ParseNamespace(Context, DeclEnd);
1000 break;
1001 case tok::kw_using:
1002 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1003 DeclEnd, attrs, &OwnedType);
1004 break;
1005 case tok::kw_static_assert:
1006 case tok::kw__Static_assert:
1007 ProhibitAttributes(attrs);
1008 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1009 break;
1010 default:
1011 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true);
1012 }
1013
1014 // This routine returns a DeclGroup, if the thing we parsed only contains a
1015 // single decl, convert it now. Alias declarations can also declare a type;
1016 // include that too if it is present.
1017 return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
1018 }
1019
1020 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1021 /// declaration-specifiers init-declarator-list[opt] ';'
1022 ///[C90/C++]init-declarator-list ';' [TODO]
1023 /// [OMP] threadprivate-directive [TODO]
1024 ///
1025 /// for-range-declaration: [C++0x 6.5p1: stmt.ranged]
1026 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1027 ///
1028 /// If RequireSemi is false, this does not check for a ';' at the end of the
1029 /// declaration. If it is true, it checks for and eats it.
1030 ///
1031 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1032 /// of a simple-declaration. If we find that we are, we also parse the
1033 /// for-range-initializer, and place it here.
ParseSimpleDeclaration(StmtVector & Stmts,unsigned Context,SourceLocation & DeclEnd,ParsedAttributes & attrs,bool RequireSemi,ForRangeInit * FRI)1034 Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(StmtVector &Stmts,
1035 unsigned Context,
1036 SourceLocation &DeclEnd,
1037 ParsedAttributes &attrs,
1038 bool RequireSemi,
1039 ForRangeInit *FRI) {
1040 // Parse the common declaration-specifiers piece.
1041 ParsingDeclSpec DS(*this);
1042 DS.takeAttributesFrom(attrs);
1043
1044 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
1045 getDeclSpecContextFromDeclaratorContext(Context));
1046
1047 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1048 // declaration-specifiers init-declarator-list[opt] ';'
1049 if (Tok.is(tok::semi)) {
1050 if (RequireSemi) ConsumeToken();
1051 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1052 DS);
1053 DS.complete(TheDecl);
1054 return Actions.ConvertDeclToDeclGroup(TheDecl);
1055 }
1056
1057 return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI);
1058 }
1059
1060 /// Returns true if this might be the start of a declarator, or a common typo
1061 /// for a declarator.
MightBeDeclarator(unsigned Context)1062 bool Parser::MightBeDeclarator(unsigned Context) {
1063 switch (Tok.getKind()) {
1064 case tok::annot_cxxscope:
1065 case tok::annot_template_id:
1066 case tok::caret:
1067 case tok::code_completion:
1068 case tok::coloncolon:
1069 case tok::ellipsis:
1070 case tok::kw___attribute:
1071 case tok::kw_operator:
1072 case tok::l_paren:
1073 case tok::star:
1074 return true;
1075
1076 case tok::amp:
1077 case tok::ampamp:
1078 return getLangOpts().CPlusPlus;
1079
1080 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1081 return Context == Declarator::MemberContext && getLangOpts().CPlusPlus0x &&
1082 NextToken().is(tok::l_square);
1083
1084 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1085 return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
1086
1087 case tok::identifier:
1088 switch (NextToken().getKind()) {
1089 case tok::code_completion:
1090 case tok::coloncolon:
1091 case tok::comma:
1092 case tok::equal:
1093 case tok::equalequal: // Might be a typo for '='.
1094 case tok::kw_alignas:
1095 case tok::kw_asm:
1096 case tok::kw___attribute:
1097 case tok::l_brace:
1098 case tok::l_paren:
1099 case tok::l_square:
1100 case tok::less:
1101 case tok::r_brace:
1102 case tok::r_paren:
1103 case tok::r_square:
1104 case tok::semi:
1105 return true;
1106
1107 case tok::colon:
1108 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1109 // and in block scope it's probably a label. Inside a class definition,
1110 // this is a bit-field.
1111 return Context == Declarator::MemberContext ||
1112 (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
1113
1114 case tok::identifier: // Possible virt-specifier.
1115 return getLangOpts().CPlusPlus0x && isCXX0XVirtSpecifier(NextToken());
1116
1117 default:
1118 return false;
1119 }
1120
1121 default:
1122 return false;
1123 }
1124 }
1125
1126 /// Skip until we reach something which seems like a sensible place to pick
1127 /// up parsing after a malformed declaration. This will sometimes stop sooner
1128 /// than SkipUntil(tok::r_brace) would, but will never stop later.
SkipMalformedDecl()1129 void Parser::SkipMalformedDecl() {
1130 while (true) {
1131 switch (Tok.getKind()) {
1132 case tok::l_brace:
1133 // Skip until matching }, then stop. We've probably skipped over
1134 // a malformed class or function definition or similar.
1135 ConsumeBrace();
1136 SkipUntil(tok::r_brace, /*StopAtSemi*/false);
1137 if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try)) {
1138 // This declaration isn't over yet. Keep skipping.
1139 continue;
1140 }
1141 if (Tok.is(tok::semi))
1142 ConsumeToken();
1143 return;
1144
1145 case tok::l_square:
1146 ConsumeBracket();
1147 SkipUntil(tok::r_square, /*StopAtSemi*/false);
1148 continue;
1149
1150 case tok::l_paren:
1151 ConsumeParen();
1152 SkipUntil(tok::r_paren, /*StopAtSemi*/false);
1153 continue;
1154
1155 case tok::r_brace:
1156 return;
1157
1158 case tok::semi:
1159 ConsumeToken();
1160 return;
1161
1162 case tok::kw_inline:
1163 // 'inline namespace' at the start of a line is almost certainly
1164 // a good place to pick back up parsing.
1165 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace))
1166 return;
1167 break;
1168
1169 case tok::kw_namespace:
1170 // 'namespace' at the start of a line is almost certainly a good
1171 // place to pick back up parsing.
1172 if (Tok.isAtStartOfLine())
1173 return;
1174 break;
1175
1176 case tok::eof:
1177 return;
1178
1179 default:
1180 break;
1181 }
1182
1183 ConsumeAnyToken();
1184 }
1185 }
1186
1187 /// ParseDeclGroup - Having concluded that this is either a function
1188 /// definition or a group of object declarations, actually parse the
1189 /// result.
ParseDeclGroup(ParsingDeclSpec & DS,unsigned Context,bool AllowFunctionDefinitions,SourceLocation * DeclEnd,ForRangeInit * FRI)1190 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1191 unsigned Context,
1192 bool AllowFunctionDefinitions,
1193 SourceLocation *DeclEnd,
1194 ForRangeInit *FRI) {
1195 // Parse the first declarator.
1196 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
1197 ParseDeclarator(D);
1198
1199 // Bail out if the first declarator didn't seem well-formed.
1200 if (!D.hasName() && !D.mayOmitIdentifier()) {
1201 SkipMalformedDecl();
1202 return DeclGroupPtrTy();
1203 }
1204
1205 // Save late-parsed attributes for now; they need to be parsed in the
1206 // appropriate function scope after the function Decl has been constructed.
1207 LateParsedAttrList LateParsedAttrs;
1208 if (D.isFunctionDeclarator())
1209 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1210
1211 // Check to see if we have a function *definition* which must have a body.
1212 if (AllowFunctionDefinitions && D.isFunctionDeclarator() &&
1213 // Look at the next token to make sure that this isn't a function
1214 // declaration. We have to check this because __attribute__ might be the
1215 // start of a function definition in GCC-extended K&R C.
1216 !isDeclarationAfterDeclarator()) {
1217
1218 if (isStartOfFunctionDefinition(D)) {
1219 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1220 Diag(Tok, diag::err_function_declared_typedef);
1221
1222 // Recover by treating the 'typedef' as spurious.
1223 DS.ClearStorageClassSpecs();
1224 }
1225
1226 Decl *TheDecl =
1227 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1228 return Actions.ConvertDeclToDeclGroup(TheDecl);
1229 }
1230
1231 if (isDeclarationSpecifier()) {
1232 // If there is an invalid declaration specifier right after the function
1233 // prototype, then we must be in a missing semicolon case where this isn't
1234 // actually a body. Just fall through into the code that handles it as a
1235 // prototype, and let the top-level code handle the erroneous declspec
1236 // where it would otherwise expect a comma or semicolon.
1237 } else {
1238 Diag(Tok, diag::err_expected_fn_body);
1239 SkipUntil(tok::semi);
1240 return DeclGroupPtrTy();
1241 }
1242 }
1243
1244 if (ParseAsmAttributesAfterDeclarator(D))
1245 return DeclGroupPtrTy();
1246
1247 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1248 // must parse and analyze the for-range-initializer before the declaration is
1249 // analyzed.
1250 if (FRI && Tok.is(tok::colon)) {
1251 FRI->ColonLoc = ConsumeToken();
1252 if (Tok.is(tok::l_brace))
1253 FRI->RangeExpr = ParseBraceInitializer();
1254 else
1255 FRI->RangeExpr = ParseExpression();
1256 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1257 Actions.ActOnCXXForRangeDecl(ThisDecl);
1258 Actions.FinalizeDeclaration(ThisDecl);
1259 D.complete(ThisDecl);
1260 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, &ThisDecl, 1);
1261 }
1262
1263 SmallVector<Decl *, 8> DeclsInGroup;
1264 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D);
1265 if (LateParsedAttrs.size() > 0)
1266 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
1267 D.complete(FirstDecl);
1268 if (FirstDecl)
1269 DeclsInGroup.push_back(FirstDecl);
1270
1271 bool ExpectSemi = Context != Declarator::ForContext;
1272
1273 // If we don't have a comma, it is either the end of the list (a ';') or an
1274 // error, bail out.
1275 while (Tok.is(tok::comma)) {
1276 SourceLocation CommaLoc = ConsumeToken();
1277
1278 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
1279 // This comma was followed by a line-break and something which can't be
1280 // the start of a declarator. The comma was probably a typo for a
1281 // semicolon.
1282 Diag(CommaLoc, diag::err_expected_semi_declaration)
1283 << FixItHint::CreateReplacement(CommaLoc, ";");
1284 ExpectSemi = false;
1285 break;
1286 }
1287
1288 // Parse the next declarator.
1289 D.clear();
1290 D.setCommaLoc(CommaLoc);
1291
1292 // Accept attributes in an init-declarator. In the first declarator in a
1293 // declaration, these would be part of the declspec. In subsequent
1294 // declarators, they become part of the declarator itself, so that they
1295 // don't apply to declarators after *this* one. Examples:
1296 // short __attribute__((common)) var; -> declspec
1297 // short var __attribute__((common)); -> declarator
1298 // short x, __attribute__((common)) var; -> declarator
1299 MaybeParseGNUAttributes(D);
1300
1301 ParseDeclarator(D);
1302 if (!D.isInvalidType()) {
1303 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
1304 D.complete(ThisDecl);
1305 if (ThisDecl)
1306 DeclsInGroup.push_back(ThisDecl);
1307 }
1308 }
1309
1310 if (DeclEnd)
1311 *DeclEnd = Tok.getLocation();
1312
1313 if (ExpectSemi &&
1314 ExpectAndConsume(tok::semi,
1315 Context == Declarator::FileContext
1316 ? diag::err_invalid_token_after_toplevel_declarator
1317 : diag::err_expected_semi_declaration)) {
1318 // Okay, there was no semicolon and one was expected. If we see a
1319 // declaration specifier, just assume it was missing and continue parsing.
1320 // Otherwise things are very confused and we skip to recover.
1321 if (!isDeclarationSpecifier()) {
1322 SkipUntil(tok::r_brace, true, true);
1323 if (Tok.is(tok::semi))
1324 ConsumeToken();
1325 }
1326 }
1327
1328 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
1329 DeclsInGroup.data(),
1330 DeclsInGroup.size());
1331 }
1332
1333 /// Parse an optional simple-asm-expr and attributes, and attach them to a
1334 /// declarator. Returns true on an error.
ParseAsmAttributesAfterDeclarator(Declarator & D)1335 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
1336 // If a simple-asm-expr is present, parse it.
1337 if (Tok.is(tok::kw_asm)) {
1338 SourceLocation Loc;
1339 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1340 if (AsmLabel.isInvalid()) {
1341 SkipUntil(tok::semi, true, true);
1342 return true;
1343 }
1344
1345 D.setAsmLabel(AsmLabel.release());
1346 D.SetRangeEnd(Loc);
1347 }
1348
1349 MaybeParseGNUAttributes(D);
1350 return false;
1351 }
1352
1353 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
1354 /// declarator'. This method parses the remainder of the declaration
1355 /// (including any attributes or initializer, among other things) and
1356 /// finalizes the declaration.
1357 ///
1358 /// init-declarator: [C99 6.7]
1359 /// declarator
1360 /// declarator '=' initializer
1361 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
1362 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1363 /// [C++] declarator initializer[opt]
1364 ///
1365 /// [C++] initializer:
1366 /// [C++] '=' initializer-clause
1367 /// [C++] '(' expression-list ')'
1368 /// [C++0x] '=' 'default' [TODO]
1369 /// [C++0x] '=' 'delete'
1370 /// [C++0x] braced-init-list
1371 ///
1372 /// According to the standard grammar, =default and =delete are function
1373 /// definitions, but that definitely doesn't fit with the parser here.
1374 ///
ParseDeclarationAfterDeclarator(Declarator & D,const ParsedTemplateInfo & TemplateInfo)1375 Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D,
1376 const ParsedTemplateInfo &TemplateInfo) {
1377 if (ParseAsmAttributesAfterDeclarator(D))
1378 return 0;
1379
1380 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
1381 }
1382
ParseDeclarationAfterDeclaratorAndAttributes(Declarator & D,const ParsedTemplateInfo & TemplateInfo)1383 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
1384 const ParsedTemplateInfo &TemplateInfo) {
1385 // Inform the current actions module that we just parsed this declarator.
1386 Decl *ThisDecl = 0;
1387 switch (TemplateInfo.Kind) {
1388 case ParsedTemplateInfo::NonTemplate:
1389 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1390 break;
1391
1392 case ParsedTemplateInfo::Template:
1393 case ParsedTemplateInfo::ExplicitSpecialization:
1394 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
1395 MultiTemplateParamsArg(Actions,
1396 TemplateInfo.TemplateParams->data(),
1397 TemplateInfo.TemplateParams->size()),
1398 D);
1399 break;
1400
1401 case ParsedTemplateInfo::ExplicitInstantiation: {
1402 DeclResult ThisRes
1403 = Actions.ActOnExplicitInstantiation(getCurScope(),
1404 TemplateInfo.ExternLoc,
1405 TemplateInfo.TemplateLoc,
1406 D);
1407 if (ThisRes.isInvalid()) {
1408 SkipUntil(tok::semi, true, true);
1409 return 0;
1410 }
1411
1412 ThisDecl = ThisRes.get();
1413 break;
1414 }
1415 }
1416
1417 bool TypeContainsAuto =
1418 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
1419
1420 // Parse declarator '=' initializer.
1421 // If a '==' or '+=' is found, suggest a fixit to '='.
1422 if (isTokenEqualOrEqualTypo()) {
1423 ConsumeToken();
1424 if (Tok.is(tok::kw_delete)) {
1425 if (D.isFunctionDeclarator())
1426 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1427 << 1 /* delete */;
1428 else
1429 Diag(ConsumeToken(), diag::err_deleted_non_function);
1430 } else if (Tok.is(tok::kw_default)) {
1431 if (D.isFunctionDeclarator())
1432 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1433 << 0 /* default */;
1434 else
1435 Diag(ConsumeToken(), diag::err_default_special_members);
1436 } else {
1437 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1438 EnterScope(0);
1439 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1440 }
1441
1442 if (Tok.is(tok::code_completion)) {
1443 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
1444 cutOffParsing();
1445 return 0;
1446 }
1447
1448 ExprResult Init(ParseInitializer());
1449
1450 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1451 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1452 ExitScope();
1453 }
1454
1455 if (Init.isInvalid()) {
1456 SkipUntil(tok::comma, true, true);
1457 Actions.ActOnInitializerError(ThisDecl);
1458 } else
1459 Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1460 /*DirectInit=*/false, TypeContainsAuto);
1461 }
1462 } else if (Tok.is(tok::l_paren)) {
1463 // Parse C++ direct initializer: '(' expression-list ')'
1464 BalancedDelimiterTracker T(*this, tok::l_paren);
1465 T.consumeOpen();
1466
1467 ExprVector Exprs(Actions);
1468 CommaLocsTy CommaLocs;
1469
1470 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1471 EnterScope(0);
1472 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1473 }
1474
1475 if (ParseExpressionList(Exprs, CommaLocs)) {
1476 SkipUntil(tok::r_paren);
1477
1478 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1479 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1480 ExitScope();
1481 }
1482 } else {
1483 // Match the ')'.
1484 T.consumeClose();
1485
1486 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
1487 "Unexpected number of commas!");
1488
1489 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1490 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1491 ExitScope();
1492 }
1493
1494 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
1495 T.getCloseLocation(),
1496 move_arg(Exprs));
1497 Actions.AddInitializerToDecl(ThisDecl, Initializer.take(),
1498 /*DirectInit=*/true, TypeContainsAuto);
1499 }
1500 } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
1501 // Parse C++0x braced-init-list.
1502 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1503
1504 if (D.getCXXScopeSpec().isSet()) {
1505 EnterScope(0);
1506 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1507 }
1508
1509 ExprResult Init(ParseBraceInitializer());
1510
1511 if (D.getCXXScopeSpec().isSet()) {
1512 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1513 ExitScope();
1514 }
1515
1516 if (Init.isInvalid()) {
1517 Actions.ActOnInitializerError(ThisDecl);
1518 } else
1519 Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1520 /*DirectInit=*/true, TypeContainsAuto);
1521
1522 } else {
1523 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
1524 }
1525
1526 Actions.FinalizeDeclaration(ThisDecl);
1527
1528 return ThisDecl;
1529 }
1530
1531 /// ParseSpecifierQualifierList
1532 /// specifier-qualifier-list:
1533 /// type-specifier specifier-qualifier-list[opt]
1534 /// type-qualifier specifier-qualifier-list[opt]
1535 /// [GNU] attributes specifier-qualifier-list[opt]
1536 ///
ParseSpecifierQualifierList(DeclSpec & DS,AccessSpecifier AS,DeclSpecContext DSC)1537 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
1538 DeclSpecContext DSC) {
1539 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
1540 /// parse declaration-specifiers and complain about extra stuff.
1541 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
1542 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
1543
1544 // Validate declspec for type-name.
1545 unsigned Specs = DS.getParsedSpecifiers();
1546 if (DSC == DSC_type_specifier && !DS.hasTypeSpecifier()) {
1547 Diag(Tok, diag::err_expected_type);
1548 DS.SetTypeSpecError();
1549 } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
1550 !DS.hasAttributes()) {
1551 Diag(Tok, diag::err_typename_requires_specqual);
1552 if (!DS.hasTypeSpecifier())
1553 DS.SetTypeSpecError();
1554 }
1555
1556 // Issue diagnostic and remove storage class if present.
1557 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
1558 if (DS.getStorageClassSpecLoc().isValid())
1559 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
1560 else
1561 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
1562 DS.ClearStorageClassSpecs();
1563 }
1564
1565 // Issue diagnostic and remove function specfier if present.
1566 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
1567 if (DS.isInlineSpecified())
1568 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
1569 if (DS.isVirtualSpecified())
1570 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
1571 if (DS.isExplicitSpecified())
1572 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
1573 DS.ClearFunctionSpecs();
1574 }
1575
1576 // Issue diagnostic and remove constexpr specfier if present.
1577 if (DS.isConstexprSpecified()) {
1578 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
1579 DS.ClearConstexprSpec();
1580 }
1581 }
1582
1583 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
1584 /// specified token is valid after the identifier in a declarator which
1585 /// immediately follows the declspec. For example, these things are valid:
1586 ///
1587 /// int x [ 4]; // direct-declarator
1588 /// int x ( int y); // direct-declarator
1589 /// int(int x ) // direct-declarator
1590 /// int x ; // simple-declaration
1591 /// int x = 17; // init-declarator-list
1592 /// int x , y; // init-declarator-list
1593 /// int x __asm__ ("foo"); // init-declarator-list
1594 /// int x : 4; // struct-declarator
1595 /// int x { 5}; // C++'0x unified initializers
1596 ///
1597 /// This is not, because 'x' does not immediately follow the declspec (though
1598 /// ')' happens to be valid anyway).
1599 /// int (x)
1600 ///
isValidAfterIdentifierInDeclarator(const Token & T)1601 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
1602 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
1603 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
1604 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
1605 }
1606
1607
1608 /// ParseImplicitInt - This method is called when we have an non-typename
1609 /// identifier in a declspec (which normally terminates the decl spec) when
1610 /// the declspec has no type specifier. In this case, the declspec is either
1611 /// malformed or is "implicit int" (in K&R and C89).
1612 ///
1613 /// This method handles diagnosing this prettily and returns false if the
1614 /// declspec is done being processed. If it recovers and thinks there may be
1615 /// other pieces of declspec after it, it returns true.
1616 ///
ParseImplicitInt(DeclSpec & DS,CXXScopeSpec * SS,const ParsedTemplateInfo & TemplateInfo,AccessSpecifier AS,DeclSpecContext DSC)1617 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1618 const ParsedTemplateInfo &TemplateInfo,
1619 AccessSpecifier AS, DeclSpecContext DSC) {
1620 assert(Tok.is(tok::identifier) && "should have identifier");
1621
1622 SourceLocation Loc = Tok.getLocation();
1623 // If we see an identifier that is not a type name, we normally would
1624 // parse it as the identifer being declared. However, when a typename
1625 // is typo'd or the definition is not included, this will incorrectly
1626 // parse the typename as the identifier name and fall over misparsing
1627 // later parts of the diagnostic.
1628 //
1629 // As such, we try to do some look-ahead in cases where this would
1630 // otherwise be an "implicit-int" case to see if this is invalid. For
1631 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
1632 // an identifier with implicit int, we'd get a parse error because the
1633 // next token is obviously invalid for a type. Parse these as a case
1634 // with an invalid type specifier.
1635 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
1636
1637 // Since we know that this either implicit int (which is rare) or an
1638 // error, do lookahead to try to do better recovery. This never applies within
1639 // a type specifier.
1640 // FIXME: Don't bail out here in languages with no implicit int (like
1641 // C++ with no -fms-extensions). This is much more likely to be an undeclared
1642 // type or typo than a use of implicit int.
1643 if (DSC != DSC_type_specifier &&
1644 isValidAfterIdentifierInDeclarator(NextToken())) {
1645 // If this token is valid for implicit int, e.g. "static x = 4", then
1646 // we just avoid eating the identifier, so it will be parsed as the
1647 // identifier in the declarator.
1648 return false;
1649 }
1650
1651 // Otherwise, if we don't consume this token, we are going to emit an
1652 // error anyway. Try to recover from various common problems. Check
1653 // to see if this was a reference to a tag name without a tag specified.
1654 // This is a common problem in C (saying 'foo' instead of 'struct foo').
1655 //
1656 // C++ doesn't need this, and isTagName doesn't take SS.
1657 if (SS == 0) {
1658 const char *TagName = 0, *FixitTagName = 0;
1659 tok::TokenKind TagKind = tok::unknown;
1660
1661 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
1662 default: break;
1663 case DeclSpec::TST_enum:
1664 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
1665 case DeclSpec::TST_union:
1666 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
1667 case DeclSpec::TST_struct:
1668 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
1669 case DeclSpec::TST_class:
1670 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
1671 }
1672
1673 if (TagName) {
1674 Diag(Loc, diag::err_use_of_tag_name_without_tag)
1675 << Tok.getIdentifierInfo() << TagName << getLangOpts().CPlusPlus
1676 << FixItHint::CreateInsertion(Tok.getLocation(),FixitTagName);
1677
1678 // Parse this as a tag as if the missing tag were present.
1679 if (TagKind == tok::kw_enum)
1680 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
1681 else
1682 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
1683 /*EnteringContext*/ false, DSC_normal);
1684 return true;
1685 }
1686 }
1687
1688 // This is almost certainly an invalid type name. Let the action emit a
1689 // diagnostic and attempt to recover.
1690 ParsedType T;
1691 if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc,
1692 getCurScope(), SS, T)) {
1693 // The action emitted a diagnostic, so we don't have to.
1694 if (T) {
1695 // The action has suggested that the type T could be used. Set that as
1696 // the type in the declaration specifiers, consume the would-be type
1697 // name token, and we're done.
1698 const char *PrevSpec;
1699 unsigned DiagID;
1700 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
1701 DS.SetRangeEnd(Tok.getLocation());
1702 ConsumeToken();
1703
1704 // There may be other declaration specifiers after this.
1705 return true;
1706 }
1707
1708 // Fall through; the action had no suggestion for us.
1709 } else {
1710 // The action did not emit a diagnostic, so emit one now.
1711 SourceRange R;
1712 if (SS) R = SS->getRange();
1713 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
1714 }
1715
1716 // Mark this as an error.
1717 DS.SetTypeSpecError();
1718 DS.SetRangeEnd(Tok.getLocation());
1719 ConsumeToken();
1720
1721 // TODO: Could inject an invalid typedef decl in an enclosing scope to
1722 // avoid rippling error messages on subsequent uses of the same type,
1723 // could be useful if #include was forgotten.
1724 return false;
1725 }
1726
1727 /// \brief Determine the declaration specifier context from the declarator
1728 /// context.
1729 ///
1730 /// \param Context the declarator context, which is one of the
1731 /// Declarator::TheContext enumerator values.
1732 Parser::DeclSpecContext
getDeclSpecContextFromDeclaratorContext(unsigned Context)1733 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
1734 if (Context == Declarator::MemberContext)
1735 return DSC_class;
1736 if (Context == Declarator::FileContext)
1737 return DSC_top_level;
1738 if (Context == Declarator::TrailingReturnContext)
1739 return DSC_trailing;
1740 return DSC_normal;
1741 }
1742
1743 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
1744 ///
1745 /// FIXME: Simply returns an alignof() expression if the argument is a
1746 /// type. Ideally, the type should be propagated directly into Sema.
1747 ///
1748 /// [C11] type-id
1749 /// [C11] constant-expression
1750 /// [C++0x] type-id ...[opt]
1751 /// [C++0x] assignment-expression ...[opt]
ParseAlignArgument(SourceLocation Start,SourceLocation & EllipsisLoc)1752 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
1753 SourceLocation &EllipsisLoc) {
1754 ExprResult ER;
1755 if (isTypeIdInParens()) {
1756 SourceLocation TypeLoc = Tok.getLocation();
1757 ParsedType Ty = ParseTypeName().get();
1758 SourceRange TypeRange(Start, Tok.getLocation());
1759 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
1760 Ty.getAsOpaquePtr(), TypeRange);
1761 } else
1762 ER = ParseConstantExpression();
1763
1764 if (getLangOpts().CPlusPlus0x && Tok.is(tok::ellipsis))
1765 EllipsisLoc = ConsumeToken();
1766
1767 return ER;
1768 }
1769
1770 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
1771 /// attribute to Attrs.
1772 ///
1773 /// alignment-specifier:
1774 /// [C11] '_Alignas' '(' type-id ')'
1775 /// [C11] '_Alignas' '(' constant-expression ')'
1776 /// [C++0x] 'alignas' '(' type-id ...[opt] ')'
1777 /// [C++0x] 'alignas' '(' assignment-expression ...[opt] ')'
ParseAlignmentSpecifier(ParsedAttributes & Attrs,SourceLocation * endLoc)1778 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
1779 SourceLocation *endLoc) {
1780 assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) &&
1781 "Not an alignment-specifier!");
1782
1783 SourceLocation KWLoc = Tok.getLocation();
1784 ConsumeToken();
1785
1786 BalancedDelimiterTracker T(*this, tok::l_paren);
1787 if (T.expectAndConsume(diag::err_expected_lparen))
1788 return;
1789
1790 SourceLocation EllipsisLoc;
1791 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
1792 if (ArgExpr.isInvalid()) {
1793 SkipUntil(tok::r_paren);
1794 return;
1795 }
1796
1797 T.consumeClose();
1798 if (endLoc)
1799 *endLoc = T.getCloseLocation();
1800
1801 // FIXME: Handle pack-expansions here.
1802 if (EllipsisLoc.isValid()) {
1803 Diag(EllipsisLoc, diag::err_alignas_pack_exp_unsupported);
1804 return;
1805 }
1806
1807 ExprVector ArgExprs(Actions);
1808 ArgExprs.push_back(ArgExpr.release());
1809 Attrs.addNew(PP.getIdentifierInfo("aligned"), KWLoc, 0, KWLoc,
1810 0, T.getOpenLocation(), ArgExprs.take(), 1, false, true);
1811 }
1812
1813 /// ParseDeclarationSpecifiers
1814 /// declaration-specifiers: [C99 6.7]
1815 /// storage-class-specifier declaration-specifiers[opt]
1816 /// type-specifier declaration-specifiers[opt]
1817 /// [C99] function-specifier declaration-specifiers[opt]
1818 /// [C11] alignment-specifier declaration-specifiers[opt]
1819 /// [GNU] attributes declaration-specifiers[opt]
1820 /// [Clang] '__module_private__' declaration-specifiers[opt]
1821 ///
1822 /// storage-class-specifier: [C99 6.7.1]
1823 /// 'typedef'
1824 /// 'extern'
1825 /// 'static'
1826 /// 'auto'
1827 /// 'register'
1828 /// [C++] 'mutable'
1829 /// [GNU] '__thread'
1830 /// function-specifier: [C99 6.7.4]
1831 /// [C99] 'inline'
1832 /// [C++] 'virtual'
1833 /// [C++] 'explicit'
1834 /// [OpenCL] '__kernel'
1835 /// 'friend': [C++ dcl.friend]
1836 /// 'constexpr': [C++0x dcl.constexpr]
1837
1838 ///
ParseDeclarationSpecifiers(DeclSpec & DS,const ParsedTemplateInfo & TemplateInfo,AccessSpecifier AS,DeclSpecContext DSContext,LateParsedAttrList * LateAttrs)1839 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
1840 const ParsedTemplateInfo &TemplateInfo,
1841 AccessSpecifier AS,
1842 DeclSpecContext DSContext,
1843 LateParsedAttrList *LateAttrs) {
1844 if (DS.getSourceRange().isInvalid()) {
1845 DS.SetRangeStart(Tok.getLocation());
1846 DS.SetRangeEnd(Tok.getLocation());
1847 }
1848
1849 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
1850 while (1) {
1851 bool isInvalid = false;
1852 const char *PrevSpec = 0;
1853 unsigned DiagID = 0;
1854
1855 SourceLocation Loc = Tok.getLocation();
1856
1857 switch (Tok.getKind()) {
1858 default:
1859 DoneWithDeclSpec:
1860 // [C++0x] decl-specifier-seq: decl-specifier attribute-specifier-seq[opt]
1861 MaybeParseCXX0XAttributes(DS.getAttributes());
1862
1863 // If this is not a declaration specifier token, we're done reading decl
1864 // specifiers. First verify that DeclSpec's are consistent.
1865 DS.Finish(Diags, PP);
1866 return;
1867
1868 case tok::code_completion: {
1869 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
1870 if (DS.hasTypeSpecifier()) {
1871 bool AllowNonIdentifiers
1872 = (getCurScope()->getFlags() & (Scope::ControlScope |
1873 Scope::BlockScope |
1874 Scope::TemplateParamScope |
1875 Scope::FunctionPrototypeScope |
1876 Scope::AtCatchScope)) == 0;
1877 bool AllowNestedNameSpecifiers
1878 = DSContext == DSC_top_level ||
1879 (DSContext == DSC_class && DS.isFriendSpecified());
1880
1881 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
1882 AllowNonIdentifiers,
1883 AllowNestedNameSpecifiers);
1884 return cutOffParsing();
1885 }
1886
1887 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
1888 CCC = Sema::PCC_LocalDeclarationSpecifiers;
1889 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
1890 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
1891 : Sema::PCC_Template;
1892 else if (DSContext == DSC_class)
1893 CCC = Sema::PCC_Class;
1894 else if (CurParsedObjCImpl)
1895 CCC = Sema::PCC_ObjCImplementation;
1896
1897 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
1898 return cutOffParsing();
1899 }
1900
1901 case tok::coloncolon: // ::foo::bar
1902 // C++ scope specifier. Annotate and loop, or bail out on error.
1903 if (TryAnnotateCXXScopeToken(true)) {
1904 if (!DS.hasTypeSpecifier())
1905 DS.SetTypeSpecError();
1906 goto DoneWithDeclSpec;
1907 }
1908 if (Tok.is(tok::coloncolon)) // ::new or ::delete
1909 goto DoneWithDeclSpec;
1910 continue;
1911
1912 case tok::annot_cxxscope: {
1913 if (DS.hasTypeSpecifier())
1914 goto DoneWithDeclSpec;
1915
1916 CXXScopeSpec SS;
1917 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1918 Tok.getAnnotationRange(),
1919 SS);
1920
1921 // We are looking for a qualified typename.
1922 Token Next = NextToken();
1923 if (Next.is(tok::annot_template_id) &&
1924 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
1925 ->Kind == TNK_Type_template) {
1926 // We have a qualified template-id, e.g., N::A<int>
1927
1928 // C++ [class.qual]p2:
1929 // In a lookup in which the constructor is an acceptable lookup
1930 // result and the nested-name-specifier nominates a class C:
1931 //
1932 // - if the name specified after the
1933 // nested-name-specifier, when looked up in C, is the
1934 // injected-class-name of C (Clause 9), or
1935 //
1936 // - if the name specified after the nested-name-specifier
1937 // is the same as the identifier or the
1938 // simple-template-id's template-name in the last
1939 // component of the nested-name-specifier,
1940 //
1941 // the name is instead considered to name the constructor of
1942 // class C.
1943 //
1944 // Thus, if the template-name is actually the constructor
1945 // name, then the code is ill-formed; this interpretation is
1946 // reinforced by the NAD status of core issue 635.
1947 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1948 if ((DSContext == DSC_top_level ||
1949 (DSContext == DSC_class && DS.isFriendSpecified())) &&
1950 TemplateId->Name &&
1951 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
1952 if (isConstructorDeclarator()) {
1953 // The user meant this to be an out-of-line constructor
1954 // definition, but template arguments are not allowed
1955 // there. Just allow this as a constructor; we'll
1956 // complain about it later.
1957 goto DoneWithDeclSpec;
1958 }
1959
1960 // The user meant this to name a type, but it actually names
1961 // a constructor with some extraneous template
1962 // arguments. Complain, then parse it as a type as the user
1963 // intended.
1964 Diag(TemplateId->TemplateNameLoc,
1965 diag::err_out_of_line_template_id_names_constructor)
1966 << TemplateId->Name;
1967 }
1968
1969 DS.getTypeSpecScope() = SS;
1970 ConsumeToken(); // The C++ scope.
1971 assert(Tok.is(tok::annot_template_id) &&
1972 "ParseOptionalCXXScopeSpecifier not working");
1973 AnnotateTemplateIdTokenAsType();
1974 continue;
1975 }
1976
1977 if (Next.is(tok::annot_typename)) {
1978 DS.getTypeSpecScope() = SS;
1979 ConsumeToken(); // The C++ scope.
1980 if (Tok.getAnnotationValue()) {
1981 ParsedType T = getTypeAnnotation(Tok);
1982 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
1983 Tok.getAnnotationEndLoc(),
1984 PrevSpec, DiagID, T);
1985 }
1986 else
1987 DS.SetTypeSpecError();
1988 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1989 ConsumeToken(); // The typename
1990 }
1991
1992 if (Next.isNot(tok::identifier))
1993 goto DoneWithDeclSpec;
1994
1995 // If we're in a context where the identifier could be a class name,
1996 // check whether this is a constructor declaration.
1997 if ((DSContext == DSC_top_level ||
1998 (DSContext == DSC_class && DS.isFriendSpecified())) &&
1999 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
2000 &SS)) {
2001 if (isConstructorDeclarator())
2002 goto DoneWithDeclSpec;
2003
2004 // As noted in C++ [class.qual]p2 (cited above), when the name
2005 // of the class is qualified in a context where it could name
2006 // a constructor, its a constructor name. However, we've
2007 // looked at the declarator, and the user probably meant this
2008 // to be a type. Complain that it isn't supposed to be treated
2009 // as a type, then proceed to parse it as a type.
2010 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
2011 << Next.getIdentifierInfo();
2012 }
2013
2014 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
2015 Next.getLocation(),
2016 getCurScope(), &SS,
2017 false, false, ParsedType(),
2018 /*IsCtorOrDtorName=*/false,
2019 /*NonTrivialSourceInfo=*/true);
2020
2021 // If the referenced identifier is not a type, then this declspec is
2022 // erroneous: We already checked about that it has no type specifier, and
2023 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
2024 // typename.
2025 if (TypeRep == 0) {
2026 ConsumeToken(); // Eat the scope spec so the identifier is current.
2027 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext)) continue;
2028 goto DoneWithDeclSpec;
2029 }
2030
2031 DS.getTypeSpecScope() = SS;
2032 ConsumeToken(); // The C++ scope.
2033
2034 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2035 DiagID, TypeRep);
2036 if (isInvalid)
2037 break;
2038
2039 DS.SetRangeEnd(Tok.getLocation());
2040 ConsumeToken(); // The typename.
2041
2042 continue;
2043 }
2044
2045 case tok::annot_typename: {
2046 if (Tok.getAnnotationValue()) {
2047 ParsedType T = getTypeAnnotation(Tok);
2048 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2049 DiagID, T);
2050 } else
2051 DS.SetTypeSpecError();
2052
2053 if (isInvalid)
2054 break;
2055
2056 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2057 ConsumeToken(); // The typename
2058
2059 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2060 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2061 // Objective-C interface.
2062 if (Tok.is(tok::less) && getLangOpts().ObjC1)
2063 ParseObjCProtocolQualifiers(DS);
2064
2065 continue;
2066 }
2067
2068 case tok::kw___is_signed:
2069 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
2070 // typically treats it as a trait. If we see __is_signed as it appears
2071 // in libstdc++, e.g.,
2072 //
2073 // static const bool __is_signed;
2074 //
2075 // then treat __is_signed as an identifier rather than as a keyword.
2076 if (DS.getTypeSpecType() == TST_bool &&
2077 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
2078 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
2079 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
2080 Tok.setKind(tok::identifier);
2081 }
2082
2083 // We're done with the declaration-specifiers.
2084 goto DoneWithDeclSpec;
2085
2086 // typedef-name
2087 case tok::kw_decltype:
2088 case tok::identifier: {
2089 // In C++, check to see if this is a scope specifier like foo::bar::, if
2090 // so handle it as such. This is important for ctor parsing.
2091 if (getLangOpts().CPlusPlus) {
2092 if (TryAnnotateCXXScopeToken(true)) {
2093 if (!DS.hasTypeSpecifier())
2094 DS.SetTypeSpecError();
2095 goto DoneWithDeclSpec;
2096 }
2097 if (!Tok.is(tok::identifier))
2098 continue;
2099 }
2100
2101 // This identifier can only be a typedef name if we haven't already seen
2102 // a type-specifier. Without this check we misparse:
2103 // typedef int X; struct Y { short X; }; as 'short int'.
2104 if (DS.hasTypeSpecifier())
2105 goto DoneWithDeclSpec;
2106
2107 // Check for need to substitute AltiVec keyword tokens.
2108 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
2109 break;
2110
2111 ParsedType TypeRep =
2112 Actions.getTypeName(*Tok.getIdentifierInfo(),
2113 Tok.getLocation(), getCurScope());
2114
2115 // If this is not a typedef name, don't parse it as part of the declspec,
2116 // it must be an implicit int or an error.
2117 if (!TypeRep) {
2118 if (ParseImplicitInt(DS, 0, TemplateInfo, AS, DSContext)) continue;
2119 goto DoneWithDeclSpec;
2120 }
2121
2122 // If we're in a context where the identifier could be a class name,
2123 // check whether this is a constructor declaration.
2124 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2125 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
2126 isConstructorDeclarator())
2127 goto DoneWithDeclSpec;
2128
2129 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2130 DiagID, TypeRep);
2131 if (isInvalid)
2132 break;
2133
2134 DS.SetRangeEnd(Tok.getLocation());
2135 ConsumeToken(); // The identifier
2136
2137 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2138 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2139 // Objective-C interface.
2140 if (Tok.is(tok::less) && getLangOpts().ObjC1)
2141 ParseObjCProtocolQualifiers(DS);
2142
2143 // Need to support trailing type qualifiers (e.g. "id<p> const").
2144 // If a type specifier follows, it will be diagnosed elsewhere.
2145 continue;
2146 }
2147
2148 // type-name
2149 case tok::annot_template_id: {
2150 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2151 if (TemplateId->Kind != TNK_Type_template) {
2152 // This template-id does not refer to a type name, so we're
2153 // done with the type-specifiers.
2154 goto DoneWithDeclSpec;
2155 }
2156
2157 // If we're in a context where the template-id could be a
2158 // constructor name or specialization, check whether this is a
2159 // constructor declaration.
2160 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2161 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
2162 isConstructorDeclarator())
2163 goto DoneWithDeclSpec;
2164
2165 // Turn the template-id annotation token into a type annotation
2166 // token, then try again to parse it as a type-specifier.
2167 AnnotateTemplateIdTokenAsType();
2168 continue;
2169 }
2170
2171 // GNU attributes support.
2172 case tok::kw___attribute:
2173 ParseGNUAttributes(DS.getAttributes(), 0, LateAttrs);
2174 continue;
2175
2176 // Microsoft declspec support.
2177 case tok::kw___declspec:
2178 ParseMicrosoftDeclSpec(DS.getAttributes());
2179 continue;
2180
2181 // Microsoft single token adornments.
2182 case tok::kw___forceinline:
2183 // FIXME: Add handling here!
2184 break;
2185
2186 case tok::kw___ptr64:
2187 case tok::kw___ptr32:
2188 case tok::kw___w64:
2189 case tok::kw___cdecl:
2190 case tok::kw___stdcall:
2191 case tok::kw___fastcall:
2192 case tok::kw___thiscall:
2193 case tok::kw___unaligned:
2194 ParseMicrosoftTypeAttributes(DS.getAttributes());
2195 continue;
2196
2197 // Borland single token adornments.
2198 case tok::kw___pascal:
2199 ParseBorlandTypeAttributes(DS.getAttributes());
2200 continue;
2201
2202 // OpenCL single token adornments.
2203 case tok::kw___kernel:
2204 ParseOpenCLAttributes(DS.getAttributes());
2205 continue;
2206
2207 // storage-class-specifier
2208 case tok::kw_typedef:
2209 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
2210 PrevSpec, DiagID);
2211 break;
2212 case tok::kw_extern:
2213 if (DS.isThreadSpecified())
2214 Diag(Tok, diag::ext_thread_before) << "extern";
2215 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
2216 PrevSpec, DiagID);
2217 break;
2218 case tok::kw___private_extern__:
2219 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
2220 Loc, PrevSpec, DiagID);
2221 break;
2222 case tok::kw_static:
2223 if (DS.isThreadSpecified())
2224 Diag(Tok, diag::ext_thread_before) << "static";
2225 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
2226 PrevSpec, DiagID);
2227 break;
2228 case tok::kw_auto:
2229 if (getLangOpts().CPlusPlus0x) {
2230 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
2231 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2232 PrevSpec, DiagID);
2233 if (!isInvalid)
2234 Diag(Tok, diag::ext_auto_storage_class)
2235 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
2236 } else
2237 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
2238 DiagID);
2239 } else
2240 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2241 PrevSpec, DiagID);
2242 break;
2243 case tok::kw_register:
2244 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
2245 PrevSpec, DiagID);
2246 break;
2247 case tok::kw_mutable:
2248 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
2249 PrevSpec, DiagID);
2250 break;
2251 case tok::kw___thread:
2252 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
2253 break;
2254
2255 // function-specifier
2256 case tok::kw_inline:
2257 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
2258 break;
2259 case tok::kw_virtual:
2260 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
2261 break;
2262 case tok::kw_explicit:
2263 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
2264 break;
2265
2266 // alignment-specifier
2267 case tok::kw__Alignas:
2268 if (!getLangOpts().C11)
2269 Diag(Tok, diag::ext_c11_alignas);
2270 ParseAlignmentSpecifier(DS.getAttributes());
2271 continue;
2272
2273 // friend
2274 case tok::kw_friend:
2275 if (DSContext == DSC_class)
2276 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
2277 else {
2278 PrevSpec = ""; // not actually used by the diagnostic
2279 DiagID = diag::err_friend_invalid_in_context;
2280 isInvalid = true;
2281 }
2282 break;
2283
2284 // Modules
2285 case tok::kw___module_private__:
2286 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
2287 break;
2288
2289 // constexpr
2290 case tok::kw_constexpr:
2291 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
2292 break;
2293
2294 // type-specifier
2295 case tok::kw_short:
2296 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
2297 DiagID);
2298 break;
2299 case tok::kw_long:
2300 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
2301 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
2302 DiagID);
2303 else
2304 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2305 DiagID);
2306 break;
2307 case tok::kw___int64:
2308 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2309 DiagID);
2310 break;
2311 case tok::kw_signed:
2312 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
2313 DiagID);
2314 break;
2315 case tok::kw_unsigned:
2316 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
2317 DiagID);
2318 break;
2319 case tok::kw__Complex:
2320 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
2321 DiagID);
2322 break;
2323 case tok::kw__Imaginary:
2324 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
2325 DiagID);
2326 break;
2327 case tok::kw_void:
2328 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
2329 DiagID);
2330 break;
2331 case tok::kw_char:
2332 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
2333 DiagID);
2334 break;
2335 case tok::kw_int:
2336 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
2337 DiagID);
2338 break;
2339 case tok::kw___int128:
2340 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
2341 DiagID);
2342 break;
2343 case tok::kw_half:
2344 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
2345 DiagID);
2346 break;
2347 case tok::kw_float:
2348 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
2349 DiagID);
2350 break;
2351 case tok::kw_double:
2352 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
2353 DiagID);
2354 break;
2355 case tok::kw_wchar_t:
2356 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
2357 DiagID);
2358 break;
2359 case tok::kw_char16_t:
2360 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
2361 DiagID);
2362 break;
2363 case tok::kw_char32_t:
2364 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
2365 DiagID);
2366 break;
2367 case tok::kw_bool:
2368 case tok::kw__Bool:
2369 if (Tok.is(tok::kw_bool) &&
2370 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
2371 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2372 PrevSpec = ""; // Not used by the diagnostic.
2373 DiagID = diag::err_bool_redeclaration;
2374 // For better error recovery.
2375 Tok.setKind(tok::identifier);
2376 isInvalid = true;
2377 } else {
2378 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
2379 DiagID);
2380 }
2381 break;
2382 case tok::kw__Decimal32:
2383 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
2384 DiagID);
2385 break;
2386 case tok::kw__Decimal64:
2387 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
2388 DiagID);
2389 break;
2390 case tok::kw__Decimal128:
2391 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
2392 DiagID);
2393 break;
2394 case tok::kw___vector:
2395 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
2396 break;
2397 case tok::kw___pixel:
2398 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
2399 break;
2400 case tok::kw___unknown_anytype:
2401 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
2402 PrevSpec, DiagID);
2403 break;
2404
2405 // class-specifier:
2406 case tok::kw_class:
2407 case tok::kw_struct:
2408 case tok::kw_union: {
2409 tok::TokenKind Kind = Tok.getKind();
2410 ConsumeToken();
2411 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
2412 EnteringContext, DSContext);
2413 continue;
2414 }
2415
2416 // enum-specifier:
2417 case tok::kw_enum:
2418 ConsumeToken();
2419 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
2420 continue;
2421
2422 // cv-qualifier:
2423 case tok::kw_const:
2424 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
2425 getLangOpts());
2426 break;
2427 case tok::kw_volatile:
2428 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
2429 getLangOpts());
2430 break;
2431 case tok::kw_restrict:
2432 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
2433 getLangOpts());
2434 break;
2435
2436 // C++ typename-specifier:
2437 case tok::kw_typename:
2438 if (TryAnnotateTypeOrScopeToken()) {
2439 DS.SetTypeSpecError();
2440 goto DoneWithDeclSpec;
2441 }
2442 if (!Tok.is(tok::kw_typename))
2443 continue;
2444 break;
2445
2446 // GNU typeof support.
2447 case tok::kw_typeof:
2448 ParseTypeofSpecifier(DS);
2449 continue;
2450
2451 case tok::annot_decltype:
2452 ParseDecltypeSpecifier(DS);
2453 continue;
2454
2455 case tok::kw___underlying_type:
2456 ParseUnderlyingTypeSpecifier(DS);
2457 continue;
2458
2459 case tok::kw__Atomic:
2460 ParseAtomicSpecifier(DS);
2461 continue;
2462
2463 // OpenCL qualifiers:
2464 case tok::kw_private:
2465 if (!getLangOpts().OpenCL)
2466 goto DoneWithDeclSpec;
2467 case tok::kw___private:
2468 case tok::kw___global:
2469 case tok::kw___local:
2470 case tok::kw___constant:
2471 case tok::kw___read_only:
2472 case tok::kw___write_only:
2473 case tok::kw___read_write:
2474 ParseOpenCLQualifiers(DS);
2475 break;
2476
2477 case tok::less:
2478 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
2479 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
2480 // but we support it.
2481 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
2482 goto DoneWithDeclSpec;
2483
2484 if (!ParseObjCProtocolQualifiers(DS))
2485 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
2486 << FixItHint::CreateInsertion(Loc, "id")
2487 << SourceRange(Loc, DS.getSourceRange().getEnd());
2488
2489 // Need to support trailing type qualifiers (e.g. "id<p> const").
2490 // If a type specifier follows, it will be diagnosed elsewhere.
2491 continue;
2492 }
2493 // If the specifier wasn't legal, issue a diagnostic.
2494 if (isInvalid) {
2495 assert(PrevSpec && "Method did not return previous specifier!");
2496 assert(DiagID);
2497
2498 if (DiagID == diag::ext_duplicate_declspec)
2499 Diag(Tok, DiagID)
2500 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
2501 else
2502 Diag(Tok, DiagID) << PrevSpec;
2503 }
2504
2505 DS.SetRangeEnd(Tok.getLocation());
2506 if (DiagID != diag::err_bool_redeclaration)
2507 ConsumeToken();
2508 }
2509 }
2510
2511 /// ParseStructDeclaration - Parse a struct declaration without the terminating
2512 /// semicolon.
2513 ///
2514 /// struct-declaration:
2515 /// specifier-qualifier-list struct-declarator-list
2516 /// [GNU] __extension__ struct-declaration
2517 /// [GNU] specifier-qualifier-list
2518 /// struct-declarator-list:
2519 /// struct-declarator
2520 /// struct-declarator-list ',' struct-declarator
2521 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
2522 /// struct-declarator:
2523 /// declarator
2524 /// [GNU] declarator attributes[opt]
2525 /// declarator[opt] ':' constant-expression
2526 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
2527 ///
2528 void Parser::
ParseStructDeclaration(DeclSpec & DS,FieldCallback & Fields)2529 ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) {
2530
2531 if (Tok.is(tok::kw___extension__)) {
2532 // __extension__ silences extension warnings in the subexpression.
2533 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2534 ConsumeToken();
2535 return ParseStructDeclaration(DS, Fields);
2536 }
2537
2538 // Parse the common specifier-qualifiers-list piece.
2539 ParseSpecifierQualifierList(DS);
2540
2541 // If there are no declarators, this is a free-standing declaration
2542 // specifier. Let the actions module cope with it.
2543 if (Tok.is(tok::semi)) {
2544 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS);
2545 return;
2546 }
2547
2548 // Read struct-declarators until we find the semicolon.
2549 bool FirstDeclarator = true;
2550 SourceLocation CommaLoc;
2551 while (1) {
2552 ParsingDeclRAIIObject PD(*this);
2553 FieldDeclarator DeclaratorInfo(DS);
2554 DeclaratorInfo.D.setCommaLoc(CommaLoc);
2555
2556 // Attributes are only allowed here on successive declarators.
2557 if (!FirstDeclarator)
2558 MaybeParseGNUAttributes(DeclaratorInfo.D);
2559
2560 /// struct-declarator: declarator
2561 /// struct-declarator: declarator[opt] ':' constant-expression
2562 if (Tok.isNot(tok::colon)) {
2563 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
2564 ColonProtectionRAIIObject X(*this);
2565 ParseDeclarator(DeclaratorInfo.D);
2566 }
2567
2568 if (Tok.is(tok::colon)) {
2569 ConsumeToken();
2570 ExprResult Res(ParseConstantExpression());
2571 if (Res.isInvalid())
2572 SkipUntil(tok::semi, true, true);
2573 else
2574 DeclaratorInfo.BitfieldSize = Res.release();
2575 }
2576
2577 // If attributes exist after the declarator, parse them.
2578 MaybeParseGNUAttributes(DeclaratorInfo.D);
2579
2580 // We're done with this declarator; invoke the callback.
2581 Decl *D = Fields.invoke(DeclaratorInfo);
2582 PD.complete(D);
2583
2584 // If we don't have a comma, it is either the end of the list (a ';')
2585 // or an error, bail out.
2586 if (Tok.isNot(tok::comma))
2587 return;
2588
2589 // Consume the comma.
2590 CommaLoc = ConsumeToken();
2591
2592 FirstDeclarator = false;
2593 }
2594 }
2595
2596 /// ParseStructUnionBody
2597 /// struct-contents:
2598 /// struct-declaration-list
2599 /// [EXT] empty
2600 /// [GNU] "struct-declaration-list" without terminatoring ';'
2601 /// struct-declaration-list:
2602 /// struct-declaration
2603 /// struct-declaration-list struct-declaration
2604 /// [OBC] '@' 'defs' '(' class-name ')'
2605 ///
ParseStructUnionBody(SourceLocation RecordLoc,unsigned TagType,Decl * TagDecl)2606 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
2607 unsigned TagType, Decl *TagDecl) {
2608 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2609 "parsing struct/union body");
2610
2611 BalancedDelimiterTracker T(*this, tok::l_brace);
2612 if (T.consumeOpen())
2613 return;
2614
2615 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
2616 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2617
2618 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
2619 // C++.
2620 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) {
2621 Diag(Tok, diag::ext_empty_struct_union) << (TagType == TST_union);
2622 Diag(Tok, diag::warn_empty_struct_union_compat) << (TagType == TST_union);
2623 }
2624
2625 SmallVector<Decl *, 32> FieldDecls;
2626
2627 // While we still have something to read, read the declarations in the struct.
2628 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2629 // Each iteration of this loop reads one struct-declaration.
2630
2631 // Check for extraneous top-level semicolon.
2632 if (Tok.is(tok::semi)) {
2633 Diag(Tok, diag::ext_extra_struct_semi)
2634 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType)
2635 << FixItHint::CreateRemoval(Tok.getLocation());
2636 ConsumeToken();
2637 continue;
2638 }
2639
2640 // Parse all the comma separated declarators.
2641 DeclSpec DS(AttrFactory);
2642
2643 if (!Tok.is(tok::at)) {
2644 struct CFieldCallback : FieldCallback {
2645 Parser &P;
2646 Decl *TagDecl;
2647 SmallVectorImpl<Decl *> &FieldDecls;
2648
2649 CFieldCallback(Parser &P, Decl *TagDecl,
2650 SmallVectorImpl<Decl *> &FieldDecls) :
2651 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
2652
2653 virtual Decl *invoke(FieldDeclarator &FD) {
2654 // Install the declarator into the current TagDecl.
2655 Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
2656 FD.D.getDeclSpec().getSourceRange().getBegin(),
2657 FD.D, FD.BitfieldSize);
2658 FieldDecls.push_back(Field);
2659 return Field;
2660 }
2661 } Callback(*this, TagDecl, FieldDecls);
2662
2663 ParseStructDeclaration(DS, Callback);
2664 } else { // Handle @defs
2665 ConsumeToken();
2666 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
2667 Diag(Tok, diag::err_unexpected_at);
2668 SkipUntil(tok::semi, true);
2669 continue;
2670 }
2671 ConsumeToken();
2672 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
2673 if (!Tok.is(tok::identifier)) {
2674 Diag(Tok, diag::err_expected_ident);
2675 SkipUntil(tok::semi, true);
2676 continue;
2677 }
2678 SmallVector<Decl *, 16> Fields;
2679 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
2680 Tok.getIdentifierInfo(), Fields);
2681 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
2682 ConsumeToken();
2683 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
2684 }
2685
2686 if (Tok.is(tok::semi)) {
2687 ConsumeToken();
2688 } else if (Tok.is(tok::r_brace)) {
2689 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
2690 break;
2691 } else {
2692 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
2693 // Skip to end of block or statement to avoid ext-warning on extra ';'.
2694 SkipUntil(tok::r_brace, true, true);
2695 // If we stopped at a ';', eat it.
2696 if (Tok.is(tok::semi)) ConsumeToken();
2697 }
2698 }
2699
2700 T.consumeClose();
2701
2702 ParsedAttributes attrs(AttrFactory);
2703 // If attributes exist after struct contents, parse them.
2704 MaybeParseGNUAttributes(attrs);
2705
2706 Actions.ActOnFields(getCurScope(),
2707 RecordLoc, TagDecl, FieldDecls,
2708 T.getOpenLocation(), T.getCloseLocation(),
2709 attrs.getList());
2710 StructScope.Exit();
2711 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
2712 T.getCloseLocation());
2713 }
2714
2715 /// ParseEnumSpecifier
2716 /// enum-specifier: [C99 6.7.2.2]
2717 /// 'enum' identifier[opt] '{' enumerator-list '}'
2718 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
2719 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
2720 /// '}' attributes[opt]
2721 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
2722 /// '}'
2723 /// 'enum' identifier
2724 /// [GNU] 'enum' attributes[opt] identifier
2725 ///
2726 /// [C++11] enum-head '{' enumerator-list[opt] '}'
2727 /// [C++11] enum-head '{' enumerator-list ',' '}'
2728 ///
2729 /// enum-head: [C++11]
2730 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
2731 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
2732 /// identifier enum-base[opt]
2733 ///
2734 /// enum-key: [C++11]
2735 /// 'enum'
2736 /// 'enum' 'class'
2737 /// 'enum' 'struct'
2738 ///
2739 /// enum-base: [C++11]
2740 /// ':' type-specifier-seq
2741 ///
2742 /// [C++] elaborated-type-specifier:
2743 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
2744 ///
ParseEnumSpecifier(SourceLocation StartLoc,DeclSpec & DS,const ParsedTemplateInfo & TemplateInfo,AccessSpecifier AS,DeclSpecContext DSC)2745 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
2746 const ParsedTemplateInfo &TemplateInfo,
2747 AccessSpecifier AS, DeclSpecContext DSC) {
2748 // Parse the tag portion of this.
2749 if (Tok.is(tok::code_completion)) {
2750 // Code completion for an enum name.
2751 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
2752 return cutOffParsing();
2753 }
2754
2755 SourceLocation ScopedEnumKWLoc;
2756 bool IsScopedUsingClassTag = false;
2757
2758 if (getLangOpts().CPlusPlus0x &&
2759 (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) {
2760 Diag(Tok, diag::warn_cxx98_compat_scoped_enum);
2761 IsScopedUsingClassTag = Tok.is(tok::kw_class);
2762 ScopedEnumKWLoc = ConsumeToken();
2763 }
2764
2765 // C++11 [temp.explicit]p12: The usual access controls do not apply to names
2766 // used to specify explicit instantiations. We extend this to also cover
2767 // explicit specializations.
2768 Sema::SuppressAccessChecksRAII SuppressAccess(Actions,
2769 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
2770 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
2771
2772 // If attributes exist after tag, parse them.
2773 ParsedAttributes attrs(AttrFactory);
2774 MaybeParseGNUAttributes(attrs);
2775
2776 // If declspecs exist after tag, parse them.
2777 while (Tok.is(tok::kw___declspec))
2778 ParseMicrosoftDeclSpec(attrs);
2779
2780 // Enum definitions should not be parsed in a trailing-return-type.
2781 bool AllowDeclaration = DSC != DSC_trailing;
2782
2783 bool AllowFixedUnderlyingType = AllowDeclaration &&
2784 (getLangOpts().CPlusPlus0x || getLangOpts().MicrosoftExt ||
2785 getLangOpts().ObjC2);
2786
2787 CXXScopeSpec &SS = DS.getTypeSpecScope();
2788 if (getLangOpts().CPlusPlus) {
2789 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
2790 // if a fixed underlying type is allowed.
2791 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
2792
2793 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
2794 /*EnteringContext=*/false))
2795 return;
2796
2797 if (SS.isSet() && Tok.isNot(tok::identifier)) {
2798 Diag(Tok, diag::err_expected_ident);
2799 if (Tok.isNot(tok::l_brace)) {
2800 // Has no name and is not a definition.
2801 // Skip the rest of this declarator, up until the comma or semicolon.
2802 SkipUntil(tok::comma, true);
2803 return;
2804 }
2805 }
2806 }
2807
2808 // Must have either 'enum name' or 'enum {...}'.
2809 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
2810 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
2811 Diag(Tok, diag::err_expected_ident_lbrace);
2812
2813 // Skip the rest of this declarator, up until the comma or semicolon.
2814 SkipUntil(tok::comma, true);
2815 return;
2816 }
2817
2818 // If an identifier is present, consume and remember it.
2819 IdentifierInfo *Name = 0;
2820 SourceLocation NameLoc;
2821 if (Tok.is(tok::identifier)) {
2822 Name = Tok.getIdentifierInfo();
2823 NameLoc = ConsumeToken();
2824 }
2825
2826 if (!Name && ScopedEnumKWLoc.isValid()) {
2827 // C++0x 7.2p2: The optional identifier shall not be omitted in the
2828 // declaration of a scoped enumeration.
2829 Diag(Tok, diag::err_scoped_enum_missing_identifier);
2830 ScopedEnumKWLoc = SourceLocation();
2831 IsScopedUsingClassTag = false;
2832 }
2833
2834 // Stop suppressing access control now we've parsed the enum name.
2835 SuppressAccess.done();
2836
2837 TypeResult BaseType;
2838
2839 // Parse the fixed underlying type.
2840 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
2841 bool PossibleBitfield = false;
2842 if (getCurScope()->getFlags() & Scope::ClassScope) {
2843 // If we're in class scope, this can either be an enum declaration with
2844 // an underlying type, or a declaration of a bitfield member. We try to
2845 // use a simple disambiguation scheme first to catch the common cases
2846 // (integer literal, sizeof); if it's still ambiguous, we then consider
2847 // anything that's a simple-type-specifier followed by '(' as an
2848 // expression. This suffices because function types are not valid
2849 // underlying types anyway.
2850 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
2851 // If the next token starts an expression, we know we're parsing a
2852 // bit-field. This is the common case.
2853 if (TPR == TPResult::True())
2854 PossibleBitfield = true;
2855 // If the next token starts a type-specifier-seq, it may be either a
2856 // a fixed underlying type or the start of a function-style cast in C++;
2857 // lookahead one more token to see if it's obvious that we have a
2858 // fixed underlying type.
2859 else if (TPR == TPResult::False() &&
2860 GetLookAheadToken(2).getKind() == tok::semi) {
2861 // Consume the ':'.
2862 ConsumeToken();
2863 } else {
2864 // We have the start of a type-specifier-seq, so we have to perform
2865 // tentative parsing to determine whether we have an expression or a
2866 // type.
2867 TentativeParsingAction TPA(*this);
2868
2869 // Consume the ':'.
2870 ConsumeToken();
2871
2872 // If we see a type specifier followed by an open-brace, we have an
2873 // ambiguity between an underlying type and a C++11 braced
2874 // function-style cast. Resolve this by always treating it as an
2875 // underlying type.
2876 // FIXME: The standard is not entirely clear on how to disambiguate in
2877 // this case.
2878 if ((getLangOpts().CPlusPlus &&
2879 isCXXDeclarationSpecifier(TPResult::True()) != TPResult::True()) ||
2880 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
2881 // We'll parse this as a bitfield later.
2882 PossibleBitfield = true;
2883 TPA.Revert();
2884 } else {
2885 // We have a type-specifier-seq.
2886 TPA.Commit();
2887 }
2888 }
2889 } else {
2890 // Consume the ':'.
2891 ConsumeToken();
2892 }
2893
2894 if (!PossibleBitfield) {
2895 SourceRange Range;
2896 BaseType = ParseTypeName(&Range);
2897
2898 if (!getLangOpts().CPlusPlus0x && !getLangOpts().ObjC2)
2899 Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type)
2900 << Range;
2901 if (getLangOpts().CPlusPlus0x)
2902 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
2903 }
2904 }
2905
2906 // There are four options here. If we have 'friend enum foo;' then this is a
2907 // friend declaration, and cannot have an accompanying definition. If we have
2908 // 'enum foo;', then this is a forward declaration. If we have
2909 // 'enum foo {...' then this is a definition. Otherwise we have something
2910 // like 'enum foo xyz', a reference.
2911 //
2912 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
2913 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
2914 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
2915 //
2916 Sema::TagUseKind TUK;
2917 if (DS.isFriendSpecified())
2918 TUK = Sema::TUK_Friend;
2919 else if (!AllowDeclaration)
2920 TUK = Sema::TUK_Reference;
2921 else if (Tok.is(tok::l_brace))
2922 TUK = Sema::TUK_Definition;
2923 else if (Tok.is(tok::semi) && DSC != DSC_type_specifier)
2924 TUK = Sema::TUK_Declaration;
2925 else
2926 TUK = Sema::TUK_Reference;
2927
2928 MultiTemplateParamsArg TParams;
2929 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
2930 TUK != Sema::TUK_Reference) {
2931 if (!getLangOpts().CPlusPlus0x || !SS.isSet()) {
2932 // Skip the rest of this declarator, up until the comma or semicolon.
2933 Diag(Tok, diag::err_enum_template);
2934 SkipUntil(tok::comma, true);
2935 return;
2936 }
2937
2938 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
2939 // Enumerations can't be explicitly instantiated.
2940 DS.SetTypeSpecError();
2941 Diag(StartLoc, diag::err_explicit_instantiation_enum);
2942 return;
2943 }
2944
2945 assert(TemplateInfo.TemplateParams && "no template parameters");
2946 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
2947 TemplateInfo.TemplateParams->size());
2948 }
2949
2950 if (!Name && TUK != Sema::TUK_Definition) {
2951 Diag(Tok, diag::err_enumerator_unnamed_no_def);
2952
2953 // Skip the rest of this declarator, up until the comma or semicolon.
2954 SkipUntil(tok::comma, true);
2955 return;
2956 }
2957
2958 bool Owned = false;
2959 bool IsDependent = false;
2960 const char *PrevSpec = 0;
2961 unsigned DiagID;
2962 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
2963 StartLoc, SS, Name, NameLoc, attrs.getList(),
2964 AS, DS.getModulePrivateSpecLoc(), TParams,
2965 Owned, IsDependent, ScopedEnumKWLoc,
2966 IsScopedUsingClassTag, BaseType);
2967
2968 if (IsDependent) {
2969 // This enum has a dependent nested-name-specifier. Handle it as a
2970 // dependent tag.
2971 if (!Name) {
2972 DS.SetTypeSpecError();
2973 Diag(Tok, diag::err_expected_type_name_after_typename);
2974 return;
2975 }
2976
2977 TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
2978 TUK, SS, Name, StartLoc,
2979 NameLoc);
2980 if (Type.isInvalid()) {
2981 DS.SetTypeSpecError();
2982 return;
2983 }
2984
2985 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
2986 NameLoc.isValid() ? NameLoc : StartLoc,
2987 PrevSpec, DiagID, Type.get()))
2988 Diag(StartLoc, DiagID) << PrevSpec;
2989
2990 return;
2991 }
2992
2993 if (!TagDecl) {
2994 // The action failed to produce an enumeration tag. If this is a
2995 // definition, consume the entire definition.
2996 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
2997 ConsumeBrace();
2998 SkipUntil(tok::r_brace);
2999 }
3000
3001 DS.SetTypeSpecError();
3002 return;
3003 }
3004
3005 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
3006 if (TUK == Sema::TUK_Friend) {
3007 Diag(Tok, diag::err_friend_decl_defines_type)
3008 << SourceRange(DS.getFriendSpecLoc());
3009 ConsumeBrace();
3010 SkipUntil(tok::r_brace);
3011 } else {
3012 ParseEnumBody(StartLoc, TagDecl);
3013 }
3014 }
3015
3016 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
3017 NameLoc.isValid() ? NameLoc : StartLoc,
3018 PrevSpec, DiagID, TagDecl, Owned))
3019 Diag(StartLoc, DiagID) << PrevSpec;
3020 }
3021
3022 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
3023 /// enumerator-list:
3024 /// enumerator
3025 /// enumerator-list ',' enumerator
3026 /// enumerator:
3027 /// enumeration-constant
3028 /// enumeration-constant '=' constant-expression
3029 /// enumeration-constant:
3030 /// identifier
3031 ///
ParseEnumBody(SourceLocation StartLoc,Decl * EnumDecl)3032 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
3033 // Enter the scope of the enum body and start the definition.
3034 ParseScope EnumScope(this, Scope::DeclScope);
3035 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
3036
3037 BalancedDelimiterTracker T(*this, tok::l_brace);
3038 T.consumeOpen();
3039
3040 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
3041 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
3042 Diag(Tok, diag::error_empty_enum);
3043
3044 SmallVector<Decl *, 32> EnumConstantDecls;
3045
3046 Decl *LastEnumConstDecl = 0;
3047
3048 // Parse the enumerator-list.
3049 while (Tok.is(tok::identifier)) {
3050 IdentifierInfo *Ident = Tok.getIdentifierInfo();
3051 SourceLocation IdentLoc = ConsumeToken();
3052
3053 // If attributes exist after the enumerator, parse them.
3054 ParsedAttributes attrs(AttrFactory);
3055 MaybeParseGNUAttributes(attrs);
3056
3057 SourceLocation EqualLoc;
3058 ExprResult AssignedVal;
3059 ParsingDeclRAIIObject PD(*this);
3060
3061 if (Tok.is(tok::equal)) {
3062 EqualLoc = ConsumeToken();
3063 AssignedVal = ParseConstantExpression();
3064 if (AssignedVal.isInvalid())
3065 SkipUntil(tok::comma, tok::r_brace, true, true);
3066 }
3067
3068 // Install the enumerator constant into EnumDecl.
3069 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
3070 LastEnumConstDecl,
3071 IdentLoc, Ident,
3072 attrs.getList(), EqualLoc,
3073 AssignedVal.release());
3074 PD.complete(EnumConstDecl);
3075
3076 EnumConstantDecls.push_back(EnumConstDecl);
3077 LastEnumConstDecl = EnumConstDecl;
3078
3079 if (Tok.is(tok::identifier)) {
3080 // We're missing a comma between enumerators.
3081 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3082 Diag(Loc, diag::err_enumerator_list_missing_comma)
3083 << FixItHint::CreateInsertion(Loc, ", ");
3084 continue;
3085 }
3086
3087 if (Tok.isNot(tok::comma))
3088 break;
3089 SourceLocation CommaLoc = ConsumeToken();
3090
3091 if (Tok.isNot(tok::identifier)) {
3092 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus0x)
3093 Diag(CommaLoc, diag::ext_enumerator_list_comma)
3094 << getLangOpts().CPlusPlus
3095 << FixItHint::CreateRemoval(CommaLoc);
3096 else if (getLangOpts().CPlusPlus0x)
3097 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
3098 << FixItHint::CreateRemoval(CommaLoc);
3099 }
3100 }
3101
3102 // Eat the }.
3103 T.consumeClose();
3104
3105 // If attributes exist after the identifier list, parse them.
3106 ParsedAttributes attrs(AttrFactory);
3107 MaybeParseGNUAttributes(attrs);
3108
3109 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(),
3110 EnumDecl, EnumConstantDecls.data(),
3111 EnumConstantDecls.size(), getCurScope(),
3112 attrs.getList());
3113
3114 EnumScope.Exit();
3115 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl,
3116 T.getCloseLocation());
3117 }
3118
3119 /// isTypeSpecifierQualifier - Return true if the current token could be the
3120 /// start of a type-qualifier-list.
isTypeQualifier() const3121 bool Parser::isTypeQualifier() const {
3122 switch (Tok.getKind()) {
3123 default: return false;
3124
3125 // type-qualifier only in OpenCL
3126 case tok::kw_private:
3127 return getLangOpts().OpenCL;
3128
3129 // type-qualifier
3130 case tok::kw_const:
3131 case tok::kw_volatile:
3132 case tok::kw_restrict:
3133 case tok::kw___private:
3134 case tok::kw___local:
3135 case tok::kw___global:
3136 case tok::kw___constant:
3137 case tok::kw___read_only:
3138 case tok::kw___read_write:
3139 case tok::kw___write_only:
3140 return true;
3141 }
3142 }
3143
3144 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
3145 /// is definitely a type-specifier. Return false if it isn't part of a type
3146 /// specifier or if we're not sure.
isKnownToBeTypeSpecifier(const Token & Tok) const3147 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
3148 switch (Tok.getKind()) {
3149 default: return false;
3150 // type-specifiers
3151 case tok::kw_short:
3152 case tok::kw_long:
3153 case tok::kw___int64:
3154 case tok::kw___int128:
3155 case tok::kw_signed:
3156 case tok::kw_unsigned:
3157 case tok::kw__Complex:
3158 case tok::kw__Imaginary:
3159 case tok::kw_void:
3160 case tok::kw_char:
3161 case tok::kw_wchar_t:
3162 case tok::kw_char16_t:
3163 case tok::kw_char32_t:
3164 case tok::kw_int:
3165 case tok::kw_half:
3166 case tok::kw_float:
3167 case tok::kw_double:
3168 case tok::kw_bool:
3169 case tok::kw__Bool:
3170 case tok::kw__Decimal32:
3171 case tok::kw__Decimal64:
3172 case tok::kw__Decimal128:
3173 case tok::kw___vector:
3174
3175 // struct-or-union-specifier (C99) or class-specifier (C++)
3176 case tok::kw_class:
3177 case tok::kw_struct:
3178 case tok::kw_union:
3179 // enum-specifier
3180 case tok::kw_enum:
3181
3182 // typedef-name
3183 case tok::annot_typename:
3184 return true;
3185 }
3186 }
3187
3188 /// isTypeSpecifierQualifier - Return true if the current token could be the
3189 /// start of a specifier-qualifier-list.
isTypeSpecifierQualifier()3190 bool Parser::isTypeSpecifierQualifier() {
3191 switch (Tok.getKind()) {
3192 default: return false;
3193
3194 case tok::identifier: // foo::bar
3195 if (TryAltiVecVectorToken())
3196 return true;
3197 // Fall through.
3198 case tok::kw_typename: // typename T::type
3199 // Annotate typenames and C++ scope specifiers. If we get one, just
3200 // recurse to handle whatever we get.
3201 if (TryAnnotateTypeOrScopeToken())
3202 return true;
3203 if (Tok.is(tok::identifier))
3204 return false;
3205 return isTypeSpecifierQualifier();
3206
3207 case tok::coloncolon: // ::foo::bar
3208 if (NextToken().is(tok::kw_new) || // ::new
3209 NextToken().is(tok::kw_delete)) // ::delete
3210 return false;
3211
3212 if (TryAnnotateTypeOrScopeToken())
3213 return true;
3214 return isTypeSpecifierQualifier();
3215
3216 // GNU attributes support.
3217 case tok::kw___attribute:
3218 // GNU typeof support.
3219 case tok::kw_typeof:
3220
3221 // type-specifiers
3222 case tok::kw_short:
3223 case tok::kw_long:
3224 case tok::kw___int64:
3225 case tok::kw___int128:
3226 case tok::kw_signed:
3227 case tok::kw_unsigned:
3228 case tok::kw__Complex:
3229 case tok::kw__Imaginary:
3230 case tok::kw_void:
3231 case tok::kw_char:
3232 case tok::kw_wchar_t:
3233 case tok::kw_char16_t:
3234 case tok::kw_char32_t:
3235 case tok::kw_int:
3236 case tok::kw_half:
3237 case tok::kw_float:
3238 case tok::kw_double:
3239 case tok::kw_bool:
3240 case tok::kw__Bool:
3241 case tok::kw__Decimal32:
3242 case tok::kw__Decimal64:
3243 case tok::kw__Decimal128:
3244 case tok::kw___vector:
3245
3246 // struct-or-union-specifier (C99) or class-specifier (C++)
3247 case tok::kw_class:
3248 case tok::kw_struct:
3249 case tok::kw_union:
3250 // enum-specifier
3251 case tok::kw_enum:
3252
3253 // type-qualifier
3254 case tok::kw_const:
3255 case tok::kw_volatile:
3256 case tok::kw_restrict:
3257
3258 // typedef-name
3259 case tok::annot_typename:
3260 return true;
3261
3262 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
3263 case tok::less:
3264 return getLangOpts().ObjC1;
3265
3266 case tok::kw___cdecl:
3267 case tok::kw___stdcall:
3268 case tok::kw___fastcall:
3269 case tok::kw___thiscall:
3270 case tok::kw___w64:
3271 case tok::kw___ptr64:
3272 case tok::kw___ptr32:
3273 case tok::kw___pascal:
3274 case tok::kw___unaligned:
3275
3276 case tok::kw___private:
3277 case tok::kw___local:
3278 case tok::kw___global:
3279 case tok::kw___constant:
3280 case tok::kw___read_only:
3281 case tok::kw___read_write:
3282 case tok::kw___write_only:
3283
3284 return true;
3285
3286 case tok::kw_private:
3287 return getLangOpts().OpenCL;
3288
3289 // C11 _Atomic()
3290 case tok::kw__Atomic:
3291 return true;
3292 }
3293 }
3294
3295 /// isDeclarationSpecifier() - Return true if the current token is part of a
3296 /// declaration specifier.
3297 ///
3298 /// \param DisambiguatingWithExpression True to indicate that the purpose of
3299 /// this check is to disambiguate between an expression and a declaration.
isDeclarationSpecifier(bool DisambiguatingWithExpression)3300 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
3301 switch (Tok.getKind()) {
3302 default: return false;
3303
3304 case tok::kw_private:
3305 return getLangOpts().OpenCL;
3306
3307 case tok::identifier: // foo::bar
3308 // Unfortunate hack to support "Class.factoryMethod" notation.
3309 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
3310 return false;
3311 if (TryAltiVecVectorToken())
3312 return true;
3313 // Fall through.
3314 case tok::kw_decltype: // decltype(T())::type
3315 case tok::kw_typename: // typename T::type
3316 // Annotate typenames and C++ scope specifiers. If we get one, just
3317 // recurse to handle whatever we get.
3318 if (TryAnnotateTypeOrScopeToken())
3319 return true;
3320 if (Tok.is(tok::identifier))
3321 return false;
3322
3323 // If we're in Objective-C and we have an Objective-C class type followed
3324 // by an identifier and then either ':' or ']', in a place where an
3325 // expression is permitted, then this is probably a class message send
3326 // missing the initial '['. In this case, we won't consider this to be
3327 // the start of a declaration.
3328 if (DisambiguatingWithExpression &&
3329 isStartOfObjCClassMessageMissingOpenBracket())
3330 return false;
3331
3332 return isDeclarationSpecifier();
3333
3334 case tok::coloncolon: // ::foo::bar
3335 if (NextToken().is(tok::kw_new) || // ::new
3336 NextToken().is(tok::kw_delete)) // ::delete
3337 return false;
3338
3339 // Annotate typenames and C++ scope specifiers. If we get one, just
3340 // recurse to handle whatever we get.
3341 if (TryAnnotateTypeOrScopeToken())
3342 return true;
3343 return isDeclarationSpecifier();
3344
3345 // storage-class-specifier
3346 case tok::kw_typedef:
3347 case tok::kw_extern:
3348 case tok::kw___private_extern__:
3349 case tok::kw_static:
3350 case tok::kw_auto:
3351 case tok::kw_register:
3352 case tok::kw___thread:
3353
3354 // Modules
3355 case tok::kw___module_private__:
3356
3357 // type-specifiers
3358 case tok::kw_short:
3359 case tok::kw_long:
3360 case tok::kw___int64:
3361 case tok::kw___int128:
3362 case tok::kw_signed:
3363 case tok::kw_unsigned:
3364 case tok::kw__Complex:
3365 case tok::kw__Imaginary:
3366 case tok::kw_void:
3367 case tok::kw_char:
3368 case tok::kw_wchar_t:
3369 case tok::kw_char16_t:
3370 case tok::kw_char32_t:
3371
3372 case tok::kw_int:
3373 case tok::kw_half:
3374 case tok::kw_float:
3375 case tok::kw_double:
3376 case tok::kw_bool:
3377 case tok::kw__Bool:
3378 case tok::kw__Decimal32:
3379 case tok::kw__Decimal64:
3380 case tok::kw__Decimal128:
3381 case tok::kw___vector:
3382
3383 // struct-or-union-specifier (C99) or class-specifier (C++)
3384 case tok::kw_class:
3385 case tok::kw_struct:
3386 case tok::kw_union:
3387 // enum-specifier
3388 case tok::kw_enum:
3389
3390 // type-qualifier
3391 case tok::kw_const:
3392 case tok::kw_volatile:
3393 case tok::kw_restrict:
3394
3395 // function-specifier
3396 case tok::kw_inline:
3397 case tok::kw_virtual:
3398 case tok::kw_explicit:
3399
3400 // static_assert-declaration
3401 case tok::kw__Static_assert:
3402
3403 // GNU typeof support.
3404 case tok::kw_typeof:
3405
3406 // GNU attributes.
3407 case tok::kw___attribute:
3408 return true;
3409
3410 // C++0x decltype.
3411 case tok::annot_decltype:
3412 return true;
3413
3414 // C11 _Atomic()
3415 case tok::kw__Atomic:
3416 return true;
3417
3418 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
3419 case tok::less:
3420 return getLangOpts().ObjC1;
3421
3422 // typedef-name
3423 case tok::annot_typename:
3424 return !DisambiguatingWithExpression ||
3425 !isStartOfObjCClassMessageMissingOpenBracket();
3426
3427 case tok::kw___declspec:
3428 case tok::kw___cdecl:
3429 case tok::kw___stdcall:
3430 case tok::kw___fastcall:
3431 case tok::kw___thiscall:
3432 case tok::kw___w64:
3433 case tok::kw___ptr64:
3434 case tok::kw___ptr32:
3435 case tok::kw___forceinline:
3436 case tok::kw___pascal:
3437 case tok::kw___unaligned:
3438
3439 case tok::kw___private:
3440 case tok::kw___local:
3441 case tok::kw___global:
3442 case tok::kw___constant:
3443 case tok::kw___read_only:
3444 case tok::kw___read_write:
3445 case tok::kw___write_only:
3446
3447 return true;
3448 }
3449 }
3450
isConstructorDeclarator()3451 bool Parser::isConstructorDeclarator() {
3452 TentativeParsingAction TPA(*this);
3453
3454 // Parse the C++ scope specifier.
3455 CXXScopeSpec SS;
3456 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
3457 /*EnteringContext=*/true)) {
3458 TPA.Revert();
3459 return false;
3460 }
3461
3462 // Parse the constructor name.
3463 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
3464 // We already know that we have a constructor name; just consume
3465 // the token.
3466 ConsumeToken();
3467 } else {
3468 TPA.Revert();
3469 return false;
3470 }
3471
3472 // Current class name must be followed by a left parenthesis.
3473 if (Tok.isNot(tok::l_paren)) {
3474 TPA.Revert();
3475 return false;
3476 }
3477 ConsumeParen();
3478
3479 // A right parenthesis, or ellipsis followed by a right parenthesis signals
3480 // that we have a constructor.
3481 if (Tok.is(tok::r_paren) ||
3482 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
3483 TPA.Revert();
3484 return true;
3485 }
3486
3487 // If we need to, enter the specified scope.
3488 DeclaratorScopeObj DeclScopeObj(*this, SS);
3489 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
3490 DeclScopeObj.EnterDeclaratorScope();
3491
3492 // Optionally skip Microsoft attributes.
3493 ParsedAttributes Attrs(AttrFactory);
3494 MaybeParseMicrosoftAttributes(Attrs);
3495
3496 // Check whether the next token(s) are part of a declaration
3497 // specifier, in which case we have the start of a parameter and,
3498 // therefore, we know that this is a constructor.
3499 bool IsConstructor = false;
3500 if (isDeclarationSpecifier())
3501 IsConstructor = true;
3502 else if (Tok.is(tok::identifier) ||
3503 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
3504 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
3505 // This might be a parenthesized member name, but is more likely to
3506 // be a constructor declaration with an invalid argument type. Keep
3507 // looking.
3508 if (Tok.is(tok::annot_cxxscope))
3509 ConsumeToken();
3510 ConsumeToken();
3511
3512 // If this is not a constructor, we must be parsing a declarator,
3513 // which must have one of the following syntactic forms (see the
3514 // grammar extract at the start of ParseDirectDeclarator):
3515 switch (Tok.getKind()) {
3516 case tok::l_paren:
3517 // C(X ( int));
3518 case tok::l_square:
3519 // C(X [ 5]);
3520 // C(X [ [attribute]]);
3521 case tok::coloncolon:
3522 // C(X :: Y);
3523 // C(X :: *p);
3524 case tok::r_paren:
3525 // C(X )
3526 // Assume this isn't a constructor, rather than assuming it's a
3527 // constructor with an unnamed parameter of an ill-formed type.
3528 break;
3529
3530 default:
3531 IsConstructor = true;
3532 break;
3533 }
3534 }
3535
3536 TPA.Revert();
3537 return IsConstructor;
3538 }
3539
3540 /// ParseTypeQualifierListOpt
3541 /// type-qualifier-list: [C99 6.7.5]
3542 /// type-qualifier
3543 /// [vendor] attributes
3544 /// [ only if VendorAttributesAllowed=true ]
3545 /// type-qualifier-list type-qualifier
3546 /// [vendor] type-qualifier-list attributes
3547 /// [ only if VendorAttributesAllowed=true ]
3548 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
3549 /// [ only if CXX0XAttributesAllowed=true ]
3550 /// Note: vendor can be GNU, MS, etc.
3551 ///
ParseTypeQualifierListOpt(DeclSpec & DS,bool VendorAttributesAllowed,bool CXX11AttributesAllowed)3552 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
3553 bool VendorAttributesAllowed,
3554 bool CXX11AttributesAllowed) {
3555 if (getLangOpts().CPlusPlus0x && CXX11AttributesAllowed &&
3556 isCXX11AttributeSpecifier()) {
3557 ParsedAttributesWithRange attrs(AttrFactory);
3558 ParseCXX11Attributes(attrs);
3559 DS.takeAttributesFrom(attrs);
3560 }
3561
3562 SourceLocation EndLoc;
3563
3564 while (1) {
3565 bool isInvalid = false;
3566 const char *PrevSpec = 0;
3567 unsigned DiagID = 0;
3568 SourceLocation Loc = Tok.getLocation();
3569
3570 switch (Tok.getKind()) {
3571 case tok::code_completion:
3572 Actions.CodeCompleteTypeQualifiers(DS);
3573 return cutOffParsing();
3574
3575 case tok::kw_const:
3576 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
3577 getLangOpts());
3578 break;
3579 case tok::kw_volatile:
3580 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3581 getLangOpts());
3582 break;
3583 case tok::kw_restrict:
3584 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3585 getLangOpts());
3586 break;
3587
3588 // OpenCL qualifiers:
3589 case tok::kw_private:
3590 if (!getLangOpts().OpenCL)
3591 goto DoneWithTypeQuals;
3592 case tok::kw___private:
3593 case tok::kw___global:
3594 case tok::kw___local:
3595 case tok::kw___constant:
3596 case tok::kw___read_only:
3597 case tok::kw___write_only:
3598 case tok::kw___read_write:
3599 ParseOpenCLQualifiers(DS);
3600 break;
3601
3602 case tok::kw___w64:
3603 case tok::kw___ptr64:
3604 case tok::kw___ptr32:
3605 case tok::kw___cdecl:
3606 case tok::kw___stdcall:
3607 case tok::kw___fastcall:
3608 case tok::kw___thiscall:
3609 case tok::kw___unaligned:
3610 if (VendorAttributesAllowed) {
3611 ParseMicrosoftTypeAttributes(DS.getAttributes());
3612 continue;
3613 }
3614 goto DoneWithTypeQuals;
3615 case tok::kw___pascal:
3616 if (VendorAttributesAllowed) {
3617 ParseBorlandTypeAttributes(DS.getAttributes());
3618 continue;
3619 }
3620 goto DoneWithTypeQuals;
3621 case tok::kw___attribute:
3622 if (VendorAttributesAllowed) {
3623 ParseGNUAttributes(DS.getAttributes());
3624 continue; // do *not* consume the next token!
3625 }
3626 // otherwise, FALL THROUGH!
3627 default:
3628 DoneWithTypeQuals:
3629 // If this is not a type-qualifier token, we're done reading type
3630 // qualifiers. First verify that DeclSpec's are consistent.
3631 DS.Finish(Diags, PP);
3632 if (EndLoc.isValid())
3633 DS.SetRangeEnd(EndLoc);
3634 return;
3635 }
3636
3637 // If the specifier combination wasn't legal, issue a diagnostic.
3638 if (isInvalid) {
3639 assert(PrevSpec && "Method did not return previous specifier!");
3640 Diag(Tok, DiagID) << PrevSpec;
3641 }
3642 EndLoc = ConsumeToken();
3643 }
3644 }
3645
3646
3647 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
3648 ///
ParseDeclarator(Declarator & D)3649 void Parser::ParseDeclarator(Declarator &D) {
3650 /// This implements the 'declarator' production in the C grammar, then checks
3651 /// for well-formedness and issues diagnostics.
3652 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
3653 }
3654
isPtrOperatorToken(tok::TokenKind Kind,const LangOptions & Lang)3655 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang) {
3656 if (Kind == tok::star || Kind == tok::caret)
3657 return true;
3658
3659 // We parse rvalue refs in C++03, because otherwise the errors are scary.
3660 if (!Lang.CPlusPlus)
3661 return false;
3662
3663 return Kind == tok::amp || Kind == tok::ampamp;
3664 }
3665
3666 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
3667 /// is parsed by the function passed to it. Pass null, and the direct-declarator
3668 /// isn't parsed at all, making this function effectively parse the C++
3669 /// ptr-operator production.
3670 ///
3671 /// If the grammar of this construct is extended, matching changes must also be
3672 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
3673 /// isConstructorDeclarator.
3674 ///
3675 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
3676 /// [C] pointer[opt] direct-declarator
3677 /// [C++] direct-declarator
3678 /// [C++] ptr-operator declarator
3679 ///
3680 /// pointer: [C99 6.7.5]
3681 /// '*' type-qualifier-list[opt]
3682 /// '*' type-qualifier-list[opt] pointer
3683 ///
3684 /// ptr-operator:
3685 /// '*' cv-qualifier-seq[opt]
3686 /// '&'
3687 /// [C++0x] '&&'
3688 /// [GNU] '&' restrict[opt] attributes[opt]
3689 /// [GNU?] '&&' restrict[opt] attributes[opt]
3690 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
ParseDeclaratorInternal(Declarator & D,DirectDeclParseFunction DirectDeclParser)3691 void Parser::ParseDeclaratorInternal(Declarator &D,
3692 DirectDeclParseFunction DirectDeclParser) {
3693 if (Diags.hasAllExtensionsSilenced())
3694 D.setExtension();
3695
3696 // C++ member pointers start with a '::' or a nested-name.
3697 // Member pointers get special handling, since there's no place for the
3698 // scope spec in the generic path below.
3699 if (getLangOpts().CPlusPlus &&
3700 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
3701 Tok.is(tok::annot_cxxscope))) {
3702 bool EnteringContext = D.getContext() == Declarator::FileContext ||
3703 D.getContext() == Declarator::MemberContext;
3704 CXXScopeSpec SS;
3705 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext);
3706
3707 if (SS.isNotEmpty()) {
3708 if (Tok.isNot(tok::star)) {
3709 // The scope spec really belongs to the direct-declarator.
3710 D.getCXXScopeSpec() = SS;
3711 if (DirectDeclParser)
3712 (this->*DirectDeclParser)(D);
3713 return;
3714 }
3715
3716 SourceLocation Loc = ConsumeToken();
3717 D.SetRangeEnd(Loc);
3718 DeclSpec DS(AttrFactory);
3719 ParseTypeQualifierListOpt(DS);
3720 D.ExtendWithDeclSpec(DS);
3721
3722 // Recurse to parse whatever is left.
3723 ParseDeclaratorInternal(D, DirectDeclParser);
3724
3725 // Sema will have to catch (syntactically invalid) pointers into global
3726 // scope. It has to catch pointers into namespace scope anyway.
3727 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
3728 Loc),
3729 DS.getAttributes(),
3730 /* Don't replace range end. */SourceLocation());
3731 return;
3732 }
3733 }
3734
3735 tok::TokenKind Kind = Tok.getKind();
3736 // Not a pointer, C++ reference, or block.
3737 if (!isPtrOperatorToken(Kind, getLangOpts())) {
3738 if (DirectDeclParser)
3739 (this->*DirectDeclParser)(D);
3740 return;
3741 }
3742
3743 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
3744 // '&&' -> rvalue reference
3745 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
3746 D.SetRangeEnd(Loc);
3747
3748 if (Kind == tok::star || Kind == tok::caret) {
3749 // Is a pointer.
3750 DeclSpec DS(AttrFactory);
3751
3752 // FIXME: GNU attributes are not allowed here in a new-type-id.
3753 ParseTypeQualifierListOpt(DS);
3754 D.ExtendWithDeclSpec(DS);
3755
3756 // Recursively parse the declarator.
3757 ParseDeclaratorInternal(D, DirectDeclParser);
3758 if (Kind == tok::star)
3759 // Remember that we parsed a pointer type, and remember the type-quals.
3760 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
3761 DS.getConstSpecLoc(),
3762 DS.getVolatileSpecLoc(),
3763 DS.getRestrictSpecLoc()),
3764 DS.getAttributes(),
3765 SourceLocation());
3766 else
3767 // Remember that we parsed a Block type, and remember the type-quals.
3768 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
3769 Loc),
3770 DS.getAttributes(),
3771 SourceLocation());
3772 } else {
3773 // Is a reference
3774 DeclSpec DS(AttrFactory);
3775
3776 // Complain about rvalue references in C++03, but then go on and build
3777 // the declarator.
3778 if (Kind == tok::ampamp)
3779 Diag(Loc, getLangOpts().CPlusPlus0x ?
3780 diag::warn_cxx98_compat_rvalue_reference :
3781 diag::ext_rvalue_reference);
3782
3783 // GNU-style and C++11 attributes are allowed here, as is restrict.
3784 ParseTypeQualifierListOpt(DS);
3785 D.ExtendWithDeclSpec(DS);
3786
3787 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
3788 // cv-qualifiers are introduced through the use of a typedef or of a
3789 // template type argument, in which case the cv-qualifiers are ignored.
3790 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
3791 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3792 Diag(DS.getConstSpecLoc(),
3793 diag::err_invalid_reference_qualifier_application) << "const";
3794 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3795 Diag(DS.getVolatileSpecLoc(),
3796 diag::err_invalid_reference_qualifier_application) << "volatile";
3797 }
3798
3799 // Recursively parse the declarator.
3800 ParseDeclaratorInternal(D, DirectDeclParser);
3801
3802 if (D.getNumTypeObjects() > 0) {
3803 // C++ [dcl.ref]p4: There shall be no references to references.
3804 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
3805 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
3806 if (const IdentifierInfo *II = D.getIdentifier())
3807 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
3808 << II;
3809 else
3810 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
3811 << "type name";
3812
3813 // Once we've complained about the reference-to-reference, we
3814 // can go ahead and build the (technically ill-formed)
3815 // declarator: reference collapsing will take care of it.
3816 }
3817 }
3818
3819 // Remember that we parsed a reference type. It doesn't have type-quals.
3820 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
3821 Kind == tok::amp),
3822 DS.getAttributes(),
3823 SourceLocation());
3824 }
3825 }
3826
diagnoseMisplacedEllipsis(Parser & P,Declarator & D,SourceLocation EllipsisLoc)3827 static void diagnoseMisplacedEllipsis(Parser &P, Declarator &D,
3828 SourceLocation EllipsisLoc) {
3829 if (EllipsisLoc.isValid()) {
3830 FixItHint Insertion;
3831 if (!D.getEllipsisLoc().isValid()) {
3832 Insertion = FixItHint::CreateInsertion(D.getIdentifierLoc(), "...");
3833 D.setEllipsisLoc(EllipsisLoc);
3834 }
3835 P.Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
3836 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion << !D.hasName();
3837 }
3838 }
3839
3840 /// ParseDirectDeclarator
3841 /// direct-declarator: [C99 6.7.5]
3842 /// [C99] identifier
3843 /// '(' declarator ')'
3844 /// [GNU] '(' attributes declarator ')'
3845 /// [C90] direct-declarator '[' constant-expression[opt] ']'
3846 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
3847 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
3848 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
3849 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
3850 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
3851 /// attribute-specifier-seq[opt]
3852 /// direct-declarator '(' parameter-type-list ')'
3853 /// direct-declarator '(' identifier-list[opt] ')'
3854 /// [GNU] direct-declarator '(' parameter-forward-declarations
3855 /// parameter-type-list[opt] ')'
3856 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
3857 /// cv-qualifier-seq[opt] exception-specification[opt]
3858 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
3859 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
3860 /// ref-qualifier[opt] exception-specification[opt]
3861 /// [C++] declarator-id
3862 /// [C++11] declarator-id attribute-specifier-seq[opt]
3863 ///
3864 /// declarator-id: [C++ 8]
3865 /// '...'[opt] id-expression
3866 /// '::'[opt] nested-name-specifier[opt] type-name
3867 ///
3868 /// id-expression: [C++ 5.1]
3869 /// unqualified-id
3870 /// qualified-id
3871 ///
3872 /// unqualified-id: [C++ 5.1]
3873 /// identifier
3874 /// operator-function-id
3875 /// conversion-function-id
3876 /// '~' class-name
3877 /// template-id
3878 ///
3879 /// Note, any additional constructs added here may need corresponding changes
3880 /// in isConstructorDeclarator.
ParseDirectDeclarator(Declarator & D)3881 void Parser::ParseDirectDeclarator(Declarator &D) {
3882 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
3883
3884 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
3885 // ParseDeclaratorInternal might already have parsed the scope.
3886 if (D.getCXXScopeSpec().isEmpty()) {
3887 bool EnteringContext = D.getContext() == Declarator::FileContext ||
3888 D.getContext() == Declarator::MemberContext;
3889 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(),
3890 EnteringContext);
3891 }
3892
3893 if (D.getCXXScopeSpec().isValid()) {
3894 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
3895 // Change the declaration context for name lookup, until this function
3896 // is exited (and the declarator has been parsed).
3897 DeclScopeObj.EnterDeclaratorScope();
3898 }
3899
3900 // C++0x [dcl.fct]p14:
3901 // There is a syntactic ambiguity when an ellipsis occurs at the end
3902 // of a parameter-declaration-clause without a preceding comma. In
3903 // this case, the ellipsis is parsed as part of the
3904 // abstract-declarator if the type of the parameter names a template
3905 // parameter pack that has not been expanded; otherwise, it is parsed
3906 // as part of the parameter-declaration-clause.
3907 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
3908 !((D.getContext() == Declarator::PrototypeContext ||
3909 D.getContext() == Declarator::BlockLiteralContext) &&
3910 NextToken().is(tok::r_paren) &&
3911 !Actions.containsUnexpandedParameterPacks(D))) {
3912 SourceLocation EllipsisLoc = ConsumeToken();
3913 if (isPtrOperatorToken(Tok.getKind(), getLangOpts())) {
3914 // The ellipsis was put in the wrong place. Recover, and explain to
3915 // the user what they should have done.
3916 ParseDeclarator(D);
3917 diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
3918 return;
3919 } else
3920 D.setEllipsisLoc(EllipsisLoc);
3921
3922 // The ellipsis can't be followed by a parenthesized declarator. We
3923 // check for that in ParseParenDeclarator, after we have disambiguated
3924 // the l_paren token.
3925 }
3926
3927 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
3928 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
3929 // We found something that indicates the start of an unqualified-id.
3930 // Parse that unqualified-id.
3931 bool AllowConstructorName;
3932 if (D.getDeclSpec().hasTypeSpecifier())
3933 AllowConstructorName = false;
3934 else if (D.getCXXScopeSpec().isSet())
3935 AllowConstructorName =
3936 (D.getContext() == Declarator::FileContext ||
3937 (D.getContext() == Declarator::MemberContext &&
3938 D.getDeclSpec().isFriendSpecified()));
3939 else
3940 AllowConstructorName = (D.getContext() == Declarator::MemberContext);
3941
3942 SourceLocation TemplateKWLoc;
3943 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
3944 /*EnteringContext=*/true,
3945 /*AllowDestructorName=*/true,
3946 AllowConstructorName,
3947 ParsedType(),
3948 TemplateKWLoc,
3949 D.getName()) ||
3950 // Once we're past the identifier, if the scope was bad, mark the
3951 // whole declarator bad.
3952 D.getCXXScopeSpec().isInvalid()) {
3953 D.SetIdentifier(0, Tok.getLocation());
3954 D.setInvalidType(true);
3955 } else {
3956 // Parsed the unqualified-id; update range information and move along.
3957 if (D.getSourceRange().getBegin().isInvalid())
3958 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
3959 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
3960 }
3961 goto PastIdentifier;
3962 }
3963 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
3964 assert(!getLangOpts().CPlusPlus &&
3965 "There's a C++-specific check for tok::identifier above");
3966 assert(Tok.getIdentifierInfo() && "Not an identifier?");
3967 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
3968 ConsumeToken();
3969 goto PastIdentifier;
3970 }
3971
3972 if (Tok.is(tok::l_paren)) {
3973 // direct-declarator: '(' declarator ')'
3974 // direct-declarator: '(' attributes declarator ')'
3975 // Example: 'char (*X)' or 'int (*XX)(void)'
3976 ParseParenDeclarator(D);
3977
3978 // If the declarator was parenthesized, we entered the declarator
3979 // scope when parsing the parenthesized declarator, then exited
3980 // the scope already. Re-enter the scope, if we need to.
3981 if (D.getCXXScopeSpec().isSet()) {
3982 // If there was an error parsing parenthesized declarator, declarator
3983 // scope may have been entered before. Don't do it again.
3984 if (!D.isInvalidType() &&
3985 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
3986 // Change the declaration context for name lookup, until this function
3987 // is exited (and the declarator has been parsed).
3988 DeclScopeObj.EnterDeclaratorScope();
3989 }
3990 } else if (D.mayOmitIdentifier()) {
3991 // This could be something simple like "int" (in which case the declarator
3992 // portion is empty), if an abstract-declarator is allowed.
3993 D.SetIdentifier(0, Tok.getLocation());
3994 } else {
3995 if (D.getContext() == Declarator::MemberContext)
3996 Diag(Tok, diag::err_expected_member_name_or_semi)
3997 << D.getDeclSpec().getSourceRange();
3998 else if (getLangOpts().CPlusPlus)
3999 Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus;
4000 else
4001 Diag(Tok, diag::err_expected_ident_lparen);
4002 D.SetIdentifier(0, Tok.getLocation());
4003 D.setInvalidType(true);
4004 }
4005
4006 PastIdentifier:
4007 assert(D.isPastIdentifier() &&
4008 "Haven't past the location of the identifier yet?");
4009
4010 // Don't parse attributes unless we have parsed an unparenthesized name.
4011 if (D.hasName() && !D.getNumTypeObjects())
4012 MaybeParseCXX0XAttributes(D);
4013
4014 while (1) {
4015 if (Tok.is(tok::l_paren)) {
4016 // Enter function-declaration scope, limiting any declarators to the
4017 // function prototype scope, including parameter declarators.
4018 ParseScope PrototypeScope(this,
4019 Scope::FunctionPrototypeScope|Scope::DeclScope);
4020 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
4021 // In such a case, check if we actually have a function declarator; if it
4022 // is not, the declarator has been fully parsed.
4023 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
4024 // When not in file scope, warn for ambiguous function declarators, just
4025 // in case the author intended it as a variable definition.
4026 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
4027 if (!isCXXFunctionDeclarator(warnIfAmbiguous))
4028 break;
4029 }
4030 ParsedAttributes attrs(AttrFactory);
4031 BalancedDelimiterTracker T(*this, tok::l_paren);
4032 T.consumeOpen();
4033 ParseFunctionDeclarator(D, attrs, T);
4034 PrototypeScope.Exit();
4035 } else if (Tok.is(tok::l_square)) {
4036 ParseBracketDeclarator(D);
4037 } else {
4038 break;
4039 }
4040 }
4041 }
4042
4043 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
4044 /// only called before the identifier, so these are most likely just grouping
4045 /// parens for precedence. If we find that these are actually function
4046 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
4047 ///
4048 /// direct-declarator:
4049 /// '(' declarator ')'
4050 /// [GNU] '(' attributes declarator ')'
4051 /// direct-declarator '(' parameter-type-list ')'
4052 /// direct-declarator '(' identifier-list[opt] ')'
4053 /// [GNU] direct-declarator '(' parameter-forward-declarations
4054 /// parameter-type-list[opt] ')'
4055 ///
ParseParenDeclarator(Declarator & D)4056 void Parser::ParseParenDeclarator(Declarator &D) {
4057 BalancedDelimiterTracker T(*this, tok::l_paren);
4058 T.consumeOpen();
4059
4060 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
4061
4062 // Eat any attributes before we look at whether this is a grouping or function
4063 // declarator paren. If this is a grouping paren, the attribute applies to
4064 // the type being built up, for example:
4065 // int (__attribute__(()) *x)(long y)
4066 // If this ends up not being a grouping paren, the attribute applies to the
4067 // first argument, for example:
4068 // int (__attribute__(()) int x)
4069 // In either case, we need to eat any attributes to be able to determine what
4070 // sort of paren this is.
4071 //
4072 ParsedAttributes attrs(AttrFactory);
4073 bool RequiresArg = false;
4074 if (Tok.is(tok::kw___attribute)) {
4075 ParseGNUAttributes(attrs);
4076
4077 // We require that the argument list (if this is a non-grouping paren) be
4078 // present even if the attribute list was empty.
4079 RequiresArg = true;
4080 }
4081 // Eat any Microsoft extensions.
4082 if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
4083 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) ||
4084 Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64) ||
4085 Tok.is(tok::kw___ptr32) || Tok.is(tok::kw___unaligned)) {
4086 ParseMicrosoftTypeAttributes(attrs);
4087 }
4088 // Eat any Borland extensions.
4089 if (Tok.is(tok::kw___pascal))
4090 ParseBorlandTypeAttributes(attrs);
4091
4092 // If we haven't past the identifier yet (or where the identifier would be
4093 // stored, if this is an abstract declarator), then this is probably just
4094 // grouping parens. However, if this could be an abstract-declarator, then
4095 // this could also be the start of function arguments (consider 'void()').
4096 bool isGrouping;
4097
4098 if (!D.mayOmitIdentifier()) {
4099 // If this can't be an abstract-declarator, this *must* be a grouping
4100 // paren, because we haven't seen the identifier yet.
4101 isGrouping = true;
4102 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
4103 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
4104 NextToken().is(tok::r_paren)) || // C++ int(...)
4105 isDeclarationSpecifier() || // 'int(int)' is a function.
4106 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
4107 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
4108 // considered to be a type, not a K&R identifier-list.
4109 isGrouping = false;
4110 } else {
4111 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
4112 isGrouping = true;
4113 }
4114
4115 // If this is a grouping paren, handle:
4116 // direct-declarator: '(' declarator ')'
4117 // direct-declarator: '(' attributes declarator ')'
4118 if (isGrouping) {
4119 SourceLocation EllipsisLoc = D.getEllipsisLoc();
4120 D.setEllipsisLoc(SourceLocation());
4121
4122 bool hadGroupingParens = D.hasGroupingParens();
4123 D.setGroupingParens(true);
4124 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4125 // Match the ')'.
4126 T.consumeClose();
4127 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
4128 T.getCloseLocation()),
4129 attrs, T.getCloseLocation());
4130
4131 D.setGroupingParens(hadGroupingParens);
4132
4133 // An ellipsis cannot be placed outside parentheses.
4134 if (EllipsisLoc.isValid())
4135 diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
4136
4137 return;
4138 }
4139
4140 // Okay, if this wasn't a grouping paren, it must be the start of a function
4141 // argument list. Recognize that this declarator will never have an
4142 // identifier (and remember where it would have been), then call into
4143 // ParseFunctionDeclarator to handle of argument list.
4144 D.SetIdentifier(0, Tok.getLocation());
4145
4146 // Enter function-declaration scope, limiting any declarators to the
4147 // function prototype scope, including parameter declarators.
4148 ParseScope PrototypeScope(this,
4149 Scope::FunctionPrototypeScope|Scope::DeclScope);
4150 ParseFunctionDeclarator(D, attrs, T, RequiresArg);
4151 PrototypeScope.Exit();
4152 }
4153
4154 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
4155 /// declarator D up to a paren, which indicates that we are parsing function
4156 /// arguments.
4157 ///
4158 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
4159 /// immediately after the open paren - they should be considered to be the
4160 /// first argument of a parameter.
4161 ///
4162 /// If RequiresArg is true, then the first argument of the function is required
4163 /// to be present and required to not be an identifier list.
4164 ///
4165 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
4166 /// (C++11) ref-qualifier[opt], exception-specification[opt],
4167 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
4168 ///
4169 /// [C++11] exception-specification:
4170 /// dynamic-exception-specification
4171 /// noexcept-specification
4172 ///
ParseFunctionDeclarator(Declarator & D,ParsedAttributes & FirstArgAttrs,BalancedDelimiterTracker & Tracker,bool RequiresArg)4173 void Parser::ParseFunctionDeclarator(Declarator &D,
4174 ParsedAttributes &FirstArgAttrs,
4175 BalancedDelimiterTracker &Tracker,
4176 bool RequiresArg) {
4177 assert(getCurScope()->isFunctionPrototypeScope() &&
4178 "Should call from a Function scope");
4179 // lparen is already consumed!
4180 assert(D.isPastIdentifier() && "Should not call before identifier!");
4181
4182 // This should be true when the function has typed arguments.
4183 // Otherwise, it is treated as a K&R-style function.
4184 bool HasProto = false;
4185 // Build up an array of information about the parsed arguments.
4186 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
4187 // Remember where we see an ellipsis, if any.
4188 SourceLocation EllipsisLoc;
4189
4190 DeclSpec DS(AttrFactory);
4191 bool RefQualifierIsLValueRef = true;
4192 SourceLocation RefQualifierLoc;
4193 SourceLocation ConstQualifierLoc;
4194 SourceLocation VolatileQualifierLoc;
4195 ExceptionSpecificationType ESpecType = EST_None;
4196 SourceRange ESpecRange;
4197 SmallVector<ParsedType, 2> DynamicExceptions;
4198 SmallVector<SourceRange, 2> DynamicExceptionRanges;
4199 ExprResult NoexceptExpr;
4200 CachedTokens *ExceptionSpecTokens = 0;
4201 ParsedAttributes FnAttrs(AttrFactory);
4202 ParsedType TrailingReturnType;
4203
4204 Actions.ActOnStartFunctionDeclarator();
4205
4206 SourceLocation EndLoc;
4207 if (isFunctionDeclaratorIdentifierList()) {
4208 if (RequiresArg)
4209 Diag(Tok, diag::err_argument_required_after_attribute);
4210
4211 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
4212
4213 Tracker.consumeClose();
4214 EndLoc = Tracker.getCloseLocation();
4215 } else {
4216 if (Tok.isNot(tok::r_paren))
4217 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc);
4218 else if (RequiresArg)
4219 Diag(Tok, diag::err_argument_required_after_attribute);
4220
4221 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
4222
4223 // If we have the closing ')', eat it.
4224 Tracker.consumeClose();
4225 EndLoc = Tracker.getCloseLocation();
4226
4227 if (getLangOpts().CPlusPlus) {
4228 // FIXME: Accept these components in any order, and produce fixits to
4229 // correct the order if the user gets it wrong. Ideally we should deal
4230 // with the virt-specifier-seq and pure-specifier in the same way.
4231
4232 // Parse cv-qualifier-seq[opt].
4233 ParseTypeQualifierListOpt(DS, false /*no attributes*/, false);
4234 if (!DS.getSourceRange().getEnd().isInvalid()) {
4235 EndLoc = DS.getSourceRange().getEnd();
4236 ConstQualifierLoc = DS.getConstSpecLoc();
4237 VolatileQualifierLoc = DS.getVolatileSpecLoc();
4238 }
4239
4240 // Parse ref-qualifier[opt].
4241 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
4242 Diag(Tok, getLangOpts().CPlusPlus0x ?
4243 diag::warn_cxx98_compat_ref_qualifier :
4244 diag::ext_ref_qualifier);
4245
4246 RefQualifierIsLValueRef = Tok.is(tok::amp);
4247 RefQualifierLoc = ConsumeToken();
4248 EndLoc = RefQualifierLoc;
4249 }
4250
4251 // C++11 [expr.prim.general]p3:
4252 // If a declaration declares a member function or member function
4253 // template of a class X, the expression this is a prvalue of type
4254 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
4255 // and the end of the function-definition, member-declarator, or
4256 // declarator.
4257 bool IsCXX11MemberFunction =
4258 getLangOpts().CPlusPlus0x &&
4259 (D.getContext() == Declarator::MemberContext ||
4260 (D.getContext() == Declarator::FileContext &&
4261 D.getCXXScopeSpec().isValid() &&
4262 Actions.CurContext->isRecord()));
4263 Sema::CXXThisScopeRAII ThisScope(Actions,
4264 dyn_cast<CXXRecordDecl>(Actions.CurContext),
4265 DS.getTypeQualifiers(),
4266 IsCXX11MemberFunction);
4267
4268 // Parse exception-specification[opt].
4269 bool Delayed = (D.getContext() == Declarator::MemberContext &&
4270 D.getDeclSpec().getStorageClassSpec()
4271 != DeclSpec::SCS_typedef &&
4272 !D.getDeclSpec().isFriendSpecified());
4273 ESpecType = tryParseExceptionSpecification(Delayed,
4274 ESpecRange,
4275 DynamicExceptions,
4276 DynamicExceptionRanges,
4277 NoexceptExpr,
4278 ExceptionSpecTokens);
4279 if (ESpecType != EST_None)
4280 EndLoc = ESpecRange.getEnd();
4281
4282 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
4283 // after the exception-specification.
4284 MaybeParseCXX0XAttributes(FnAttrs);
4285
4286 // Parse trailing-return-type[opt].
4287 if (getLangOpts().CPlusPlus0x && Tok.is(tok::arrow)) {
4288 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
4289 SourceRange Range;
4290 TrailingReturnType = ParseTrailingReturnType(Range).get();
4291 if (Range.getEnd().isValid())
4292 EndLoc = Range.getEnd();
4293 }
4294 }
4295 }
4296
4297 // Remember that we parsed a function type, and remember the attributes.
4298 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
4299 /*isVariadic=*/EllipsisLoc.isValid(),
4300 EllipsisLoc,
4301 ParamInfo.data(), ParamInfo.size(),
4302 DS.getTypeQualifiers(),
4303 RefQualifierIsLValueRef,
4304 RefQualifierLoc, ConstQualifierLoc,
4305 VolatileQualifierLoc,
4306 /*MutableLoc=*/SourceLocation(),
4307 ESpecType, ESpecRange.getBegin(),
4308 DynamicExceptions.data(),
4309 DynamicExceptionRanges.data(),
4310 DynamicExceptions.size(),
4311 NoexceptExpr.isUsable() ?
4312 NoexceptExpr.get() : 0,
4313 ExceptionSpecTokens,
4314 Tracker.getOpenLocation(),
4315 EndLoc, D,
4316 TrailingReturnType),
4317 FnAttrs, EndLoc);
4318
4319 Actions.ActOnEndFunctionDeclarator();
4320 }
4321
4322 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
4323 /// identifier list form for a K&R-style function: void foo(a,b,c)
4324 ///
4325 /// Note that identifier-lists are only allowed for normal declarators, not for
4326 /// abstract-declarators.
isFunctionDeclaratorIdentifierList()4327 bool Parser::isFunctionDeclaratorIdentifierList() {
4328 return !getLangOpts().CPlusPlus
4329 && Tok.is(tok::identifier)
4330 && !TryAltiVecVectorToken()
4331 // K&R identifier lists can't have typedefs as identifiers, per C99
4332 // 6.7.5.3p11.
4333 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
4334 // Identifier lists follow a really simple grammar: the identifiers can
4335 // be followed *only* by a ", identifier" or ")". However, K&R
4336 // identifier lists are really rare in the brave new modern world, and
4337 // it is very common for someone to typo a type in a non-K&R style
4338 // list. If we are presented with something like: "void foo(intptr x,
4339 // float y)", we don't want to start parsing the function declarator as
4340 // though it is a K&R style declarator just because intptr is an
4341 // invalid type.
4342 //
4343 // To handle this, we check to see if the token after the first
4344 // identifier is a "," or ")". Only then do we parse it as an
4345 // identifier list.
4346 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
4347 }
4348
4349 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
4350 /// we found a K&R-style identifier list instead of a typed parameter list.
4351 ///
4352 /// After returning, ParamInfo will hold the parsed parameters.
4353 ///
4354 /// identifier-list: [C99 6.7.5]
4355 /// identifier
4356 /// identifier-list ',' identifier
4357 ///
ParseFunctionDeclaratorIdentifierList(Declarator & D,SmallVector<DeclaratorChunk::ParamInfo,16> & ParamInfo)4358 void Parser::ParseFunctionDeclaratorIdentifierList(
4359 Declarator &D,
4360 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo) {
4361 // If there was no identifier specified for the declarator, either we are in
4362 // an abstract-declarator, or we are in a parameter declarator which was found
4363 // to be abstract. In abstract-declarators, identifier lists are not valid:
4364 // diagnose this.
4365 if (!D.getIdentifier())
4366 Diag(Tok, diag::ext_ident_list_in_param);
4367
4368 // Maintain an efficient lookup of params we have seen so far.
4369 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
4370
4371 while (1) {
4372 // If this isn't an identifier, report the error and skip until ')'.
4373 if (Tok.isNot(tok::identifier)) {
4374 Diag(Tok, diag::err_expected_ident);
4375 SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true);
4376 // Forget we parsed anything.
4377 ParamInfo.clear();
4378 return;
4379 }
4380
4381 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
4382
4383 // Reject 'typedef int y; int test(x, y)', but continue parsing.
4384 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
4385 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
4386
4387 // Verify that the argument identifier has not already been mentioned.
4388 if (!ParamsSoFar.insert(ParmII)) {
4389 Diag(Tok, diag::err_param_redefinition) << ParmII;
4390 } else {
4391 // Remember this identifier in ParamInfo.
4392 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
4393 Tok.getLocation(),
4394 0));
4395 }
4396
4397 // Eat the identifier.
4398 ConsumeToken();
4399
4400 // The list continues if we see a comma.
4401 if (Tok.isNot(tok::comma))
4402 break;
4403 ConsumeToken();
4404 }
4405 }
4406
4407 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
4408 /// after the opening parenthesis. This function will not parse a K&R-style
4409 /// identifier list.
4410 ///
4411 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
4412 /// caller parsed those arguments immediately after the open paren - they should
4413 /// be considered to be part of the first parameter.
4414 ///
4415 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
4416 /// be the location of the ellipsis, if any was parsed.
4417 ///
4418 /// parameter-type-list: [C99 6.7.5]
4419 /// parameter-list
4420 /// parameter-list ',' '...'
4421 /// [C++] parameter-list '...'
4422 ///
4423 /// parameter-list: [C99 6.7.5]
4424 /// parameter-declaration
4425 /// parameter-list ',' parameter-declaration
4426 ///
4427 /// parameter-declaration: [C99 6.7.5]
4428 /// declaration-specifiers declarator
4429 /// [C++] declaration-specifiers declarator '=' assignment-expression
4430 /// [C++11] initializer-clause
4431 /// [GNU] declaration-specifiers declarator attributes
4432 /// declaration-specifiers abstract-declarator[opt]
4433 /// [C++] declaration-specifiers abstract-declarator[opt]
4434 /// '=' assignment-expression
4435 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
4436 /// [C++11] attribute-specifier-seq parameter-declaration
4437 ///
ParseParameterDeclarationClause(Declarator & D,ParsedAttributes & FirstArgAttrs,SmallVector<DeclaratorChunk::ParamInfo,16> & ParamInfo,SourceLocation & EllipsisLoc)4438 void Parser::ParseParameterDeclarationClause(
4439 Declarator &D,
4440 ParsedAttributes &FirstArgAttrs,
4441 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo,
4442 SourceLocation &EllipsisLoc) {
4443
4444 while (1) {
4445 if (Tok.is(tok::ellipsis)) {
4446 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
4447 // before deciding this was a parameter-declaration-clause.
4448 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
4449 break;
4450 }
4451
4452 // Parse the declaration-specifiers.
4453 // Just use the ParsingDeclaration "scope" of the declarator.
4454 DeclSpec DS(AttrFactory);
4455
4456 // Parse any C++11 attributes.
4457 MaybeParseCXX0XAttributes(DS.getAttributes());
4458
4459 // Skip any Microsoft attributes before a param.
4460 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
4461 ParseMicrosoftAttributes(DS.getAttributes());
4462
4463 SourceLocation DSStart = Tok.getLocation();
4464
4465 // If the caller parsed attributes for the first argument, add them now.
4466 // Take them so that we only apply the attributes to the first parameter.
4467 // FIXME: If we can leave the attributes in the token stream somehow, we can
4468 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
4469 // too much hassle.
4470 DS.takeAttributesFrom(FirstArgAttrs);
4471
4472 ParseDeclarationSpecifiers(DS);
4473
4474 // Parse the declarator. This is "PrototypeContext", because we must
4475 // accept either 'declarator' or 'abstract-declarator' here.
4476 Declarator ParmDecl(DS, Declarator::PrototypeContext);
4477 ParseDeclarator(ParmDecl);
4478
4479 // Parse GNU attributes, if present.
4480 MaybeParseGNUAttributes(ParmDecl);
4481
4482 // Remember this parsed parameter in ParamInfo.
4483 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
4484
4485 // DefArgToks is used when the parsing of default arguments needs
4486 // to be delayed.
4487 CachedTokens *DefArgToks = 0;
4488
4489 // If no parameter was specified, verify that *something* was specified,
4490 // otherwise we have a missing type and identifier.
4491 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
4492 ParmDecl.getNumTypeObjects() == 0) {
4493 // Completely missing, emit error.
4494 Diag(DSStart, diag::err_missing_param);
4495 } else {
4496 // Otherwise, we have something. Add it and let semantic analysis try
4497 // to grok it and add the result to the ParamInfo we are building.
4498
4499 // Inform the actions module about the parameter declarator, so it gets
4500 // added to the current scope.
4501 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
4502
4503 // Parse the default argument, if any. We parse the default
4504 // arguments in all dialects; the semantic analysis in
4505 // ActOnParamDefaultArgument will reject the default argument in
4506 // C.
4507 if (Tok.is(tok::equal)) {
4508 SourceLocation EqualLoc = Tok.getLocation();
4509
4510 // Parse the default argument
4511 if (D.getContext() == Declarator::MemberContext) {
4512 // If we're inside a class definition, cache the tokens
4513 // corresponding to the default argument. We'll actually parse
4514 // them when we see the end of the class definition.
4515 // FIXME: Can we use a smart pointer for Toks?
4516 DefArgToks = new CachedTokens;
4517
4518 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
4519 /*StopAtSemi=*/true,
4520 /*ConsumeFinalToken=*/false)) {
4521 delete DefArgToks;
4522 DefArgToks = 0;
4523 Actions.ActOnParamDefaultArgumentError(Param);
4524 } else {
4525 // Mark the end of the default argument so that we know when to
4526 // stop when we parse it later on.
4527 Token DefArgEnd;
4528 DefArgEnd.startToken();
4529 DefArgEnd.setKind(tok::cxx_defaultarg_end);
4530 DefArgEnd.setLocation(Tok.getLocation());
4531 DefArgToks->push_back(DefArgEnd);
4532 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
4533 (*DefArgToks)[1].getLocation());
4534 }
4535 } else {
4536 // Consume the '='.
4537 ConsumeToken();
4538
4539 // The argument isn't actually potentially evaluated unless it is
4540 // used.
4541 EnterExpressionEvaluationContext Eval(Actions,
4542 Sema::PotentiallyEvaluatedIfUsed,
4543 Param);
4544
4545 ExprResult DefArgResult;
4546 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
4547 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
4548 DefArgResult = ParseBraceInitializer();
4549 } else
4550 DefArgResult = ParseAssignmentExpression();
4551 if (DefArgResult.isInvalid()) {
4552 Actions.ActOnParamDefaultArgumentError(Param);
4553 SkipUntil(tok::comma, tok::r_paren, true, true);
4554 } else {
4555 // Inform the actions module about the default argument
4556 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
4557 DefArgResult.take());
4558 }
4559 }
4560 }
4561
4562 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
4563 ParmDecl.getIdentifierLoc(), Param,
4564 DefArgToks));
4565 }
4566
4567 // If the next token is a comma, consume it and keep reading arguments.
4568 if (Tok.isNot(tok::comma)) {
4569 if (Tok.is(tok::ellipsis)) {
4570 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
4571
4572 if (!getLangOpts().CPlusPlus) {
4573 // We have ellipsis without a preceding ',', which is ill-formed
4574 // in C. Complain and provide the fix.
4575 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
4576 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
4577 }
4578 }
4579
4580 break;
4581 }
4582
4583 // Consume the comma.
4584 ConsumeToken();
4585 }
4586
4587 }
4588
4589 /// [C90] direct-declarator '[' constant-expression[opt] ']'
4590 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
4591 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
4592 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
4593 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
4594 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
4595 /// attribute-specifier-seq[opt]
ParseBracketDeclarator(Declarator & D)4596 void Parser::ParseBracketDeclarator(Declarator &D) {
4597 if (CheckProhibitedCXX11Attribute())
4598 return;
4599
4600 BalancedDelimiterTracker T(*this, tok::l_square);
4601 T.consumeOpen();
4602
4603 // C array syntax has many features, but by-far the most common is [] and [4].
4604 // This code does a fast path to handle some of the most obvious cases.
4605 if (Tok.getKind() == tok::r_square) {
4606 T.consumeClose();
4607 ParsedAttributes attrs(AttrFactory);
4608 MaybeParseCXX0XAttributes(attrs);
4609
4610 // Remember that we parsed the empty array type.
4611 ExprResult NumElements;
4612 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
4613 T.getOpenLocation(),
4614 T.getCloseLocation()),
4615 attrs, T.getCloseLocation());
4616 return;
4617 } else if (Tok.getKind() == tok::numeric_constant &&
4618 GetLookAheadToken(1).is(tok::r_square)) {
4619 // [4] is very common. Parse the numeric constant expression.
4620 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
4621 ConsumeToken();
4622
4623 T.consumeClose();
4624 ParsedAttributes attrs(AttrFactory);
4625 MaybeParseCXX0XAttributes(attrs);
4626
4627 // Remember that we parsed a array type, and remember its features.
4628 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0,
4629 ExprRes.release(),
4630 T.getOpenLocation(),
4631 T.getCloseLocation()),
4632 attrs, T.getCloseLocation());
4633 return;
4634 }
4635
4636 // If valid, this location is the position where we read the 'static' keyword.
4637 SourceLocation StaticLoc;
4638 if (Tok.is(tok::kw_static))
4639 StaticLoc = ConsumeToken();
4640
4641 // If there is a type-qualifier-list, read it now.
4642 // Type qualifiers in an array subscript are a C99 feature.
4643 DeclSpec DS(AttrFactory);
4644 ParseTypeQualifierListOpt(DS, false /*no attributes*/);
4645
4646 // If we haven't already read 'static', check to see if there is one after the
4647 // type-qualifier-list.
4648 if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
4649 StaticLoc = ConsumeToken();
4650
4651 // Handle "direct-declarator [ type-qual-list[opt] * ]".
4652 bool isStar = false;
4653 ExprResult NumElements;
4654
4655 // Handle the case where we have '[*]' as the array size. However, a leading
4656 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
4657 // the the token after the star is a ']'. Since stars in arrays are
4658 // infrequent, use of lookahead is not costly here.
4659 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
4660 ConsumeToken(); // Eat the '*'.
4661
4662 if (StaticLoc.isValid()) {
4663 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
4664 StaticLoc = SourceLocation(); // Drop the static.
4665 }
4666 isStar = true;
4667 } else if (Tok.isNot(tok::r_square)) {
4668 // Note, in C89, this production uses the constant-expr production instead
4669 // of assignment-expr. The only difference is that assignment-expr allows
4670 // things like '=' and '*='. Sema rejects these in C89 mode because they
4671 // are not i-c-e's, so we don't need to distinguish between the two here.
4672
4673 // Parse the constant-expression or assignment-expression now (depending
4674 // on dialect).
4675 if (getLangOpts().CPlusPlus) {
4676 NumElements = ParseConstantExpression();
4677 } else {
4678 EnterExpressionEvaluationContext Unevaluated(Actions,
4679 Sema::ConstantEvaluated);
4680 NumElements = ParseAssignmentExpression();
4681 }
4682 }
4683
4684 // If there was an error parsing the assignment-expression, recover.
4685 if (NumElements.isInvalid()) {
4686 D.setInvalidType(true);
4687 // If the expression was invalid, skip it.
4688 SkipUntil(tok::r_square);
4689 return;
4690 }
4691
4692 T.consumeClose();
4693
4694 ParsedAttributes attrs(AttrFactory);
4695 MaybeParseCXX0XAttributes(attrs);
4696
4697 // Remember that we parsed a array type, and remember its features.
4698 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
4699 StaticLoc.isValid(), isStar,
4700 NumElements.release(),
4701 T.getOpenLocation(),
4702 T.getCloseLocation()),
4703 attrs, T.getCloseLocation());
4704 }
4705
4706 /// [GNU] typeof-specifier:
4707 /// typeof ( expressions )
4708 /// typeof ( type-name )
4709 /// [GNU/C++] typeof unary-expression
4710 ///
ParseTypeofSpecifier(DeclSpec & DS)4711 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
4712 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
4713 Token OpTok = Tok;
4714 SourceLocation StartLoc = ConsumeToken();
4715
4716 const bool hasParens = Tok.is(tok::l_paren);
4717
4718 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
4719
4720 bool isCastExpr;
4721 ParsedType CastTy;
4722 SourceRange CastRange;
4723 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
4724 CastTy, CastRange);
4725 if (hasParens)
4726 DS.setTypeofParensRange(CastRange);
4727
4728 if (CastRange.getEnd().isInvalid())
4729 // FIXME: Not accurate, the range gets one token more than it should.
4730 DS.SetRangeEnd(Tok.getLocation());
4731 else
4732 DS.SetRangeEnd(CastRange.getEnd());
4733
4734 if (isCastExpr) {
4735 if (!CastTy) {
4736 DS.SetTypeSpecError();
4737 return;
4738 }
4739
4740 const char *PrevSpec = 0;
4741 unsigned DiagID;
4742 // Check for duplicate type specifiers (e.g. "int typeof(int)").
4743 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
4744 DiagID, CastTy))
4745 Diag(StartLoc, DiagID) << PrevSpec;
4746 return;
4747 }
4748
4749 // If we get here, the operand to the typeof was an expresion.
4750 if (Operand.isInvalid()) {
4751 DS.SetTypeSpecError();
4752 return;
4753 }
4754
4755 // We might need to transform the operand if it is potentially evaluated.
4756 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
4757 if (Operand.isInvalid()) {
4758 DS.SetTypeSpecError();
4759 return;
4760 }
4761
4762 const char *PrevSpec = 0;
4763 unsigned DiagID;
4764 // Check for duplicate type specifiers (e.g. "int typeof(int)").
4765 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
4766 DiagID, Operand.get()))
4767 Diag(StartLoc, DiagID) << PrevSpec;
4768 }
4769
4770 /// [C11] atomic-specifier:
4771 /// _Atomic ( type-name )
4772 ///
ParseAtomicSpecifier(DeclSpec & DS)4773 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
4774 assert(Tok.is(tok::kw__Atomic) && "Not an atomic specifier");
4775
4776 SourceLocation StartLoc = ConsumeToken();
4777 BalancedDelimiterTracker T(*this, tok::l_paren);
4778 if (T.expectAndConsume(diag::err_expected_lparen_after, "_Atomic")) {
4779 SkipUntil(tok::r_paren);
4780 return;
4781 }
4782
4783 TypeResult Result = ParseTypeName();
4784 if (Result.isInvalid()) {
4785 SkipUntil(tok::r_paren);
4786 return;
4787 }
4788
4789 // Match the ')'
4790 T.consumeClose();
4791
4792 if (T.getCloseLocation().isInvalid())
4793 return;
4794
4795 DS.setTypeofParensRange(T.getRange());
4796 DS.SetRangeEnd(T.getCloseLocation());
4797
4798 const char *PrevSpec = 0;
4799 unsigned DiagID;
4800 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
4801 DiagID, Result.release()))
4802 Diag(StartLoc, DiagID) << PrevSpec;
4803 }
4804
4805
4806 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
4807 /// from TryAltiVecVectorToken.
TryAltiVecVectorTokenOutOfLine()4808 bool Parser::TryAltiVecVectorTokenOutOfLine() {
4809 Token Next = NextToken();
4810 switch (Next.getKind()) {
4811 default: return false;
4812 case tok::kw_short:
4813 case tok::kw_long:
4814 case tok::kw_signed:
4815 case tok::kw_unsigned:
4816 case tok::kw_void:
4817 case tok::kw_char:
4818 case tok::kw_int:
4819 case tok::kw_float:
4820 case tok::kw_double:
4821 case tok::kw_bool:
4822 case tok::kw___pixel:
4823 Tok.setKind(tok::kw___vector);
4824 return true;
4825 case tok::identifier:
4826 if (Next.getIdentifierInfo() == Ident_pixel) {
4827 Tok.setKind(tok::kw___vector);
4828 return true;
4829 }
4830 return false;
4831 }
4832 }
4833
TryAltiVecTokenOutOfLine(DeclSpec & DS,SourceLocation Loc,const char * & PrevSpec,unsigned & DiagID,bool & isInvalid)4834 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
4835 const char *&PrevSpec, unsigned &DiagID,
4836 bool &isInvalid) {
4837 if (Tok.getIdentifierInfo() == Ident_vector) {
4838 Token Next = NextToken();
4839 switch (Next.getKind()) {
4840 case tok::kw_short:
4841 case tok::kw_long:
4842 case tok::kw_signed:
4843 case tok::kw_unsigned:
4844 case tok::kw_void:
4845 case tok::kw_char:
4846 case tok::kw_int:
4847 case tok::kw_float:
4848 case tok::kw_double:
4849 case tok::kw_bool:
4850 case tok::kw___pixel:
4851 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
4852 return true;
4853 case tok::identifier:
4854 if (Next.getIdentifierInfo() == Ident_pixel) {
4855 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
4856 return true;
4857 }
4858 break;
4859 default:
4860 break;
4861 }
4862 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
4863 DS.isTypeAltiVecVector()) {
4864 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
4865 return true;
4866 }
4867 return false;
4868 }
4869