clang 17.0.0git
ParseDecl.cpp
Go to the documentation of this file.
1//===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Declaration portions of the Parser interfaces.
10//
11//===----------------------------------------------------------------------===//
12
22#include "clang/Parse/Parser.h"
24#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Scope.h"
28#include "llvm/ADT/SmallSet.h"
29#include "llvm/ADT/SmallString.h"
30#include "llvm/ADT/StringSwitch.h"
31#include <optional>
32
33using namespace clang;
34
35//===----------------------------------------------------------------------===//
36// C99 6.7: Declarations.
37//===----------------------------------------------------------------------===//
38
39/// ParseTypeName
40/// type-name: [C99 6.7.6]
41/// specifier-qualifier-list abstract-declarator[opt]
42///
43/// Called type-id in C++.
45 AccessSpecifier AS, Decl **OwnedType,
46 ParsedAttributes *Attrs) {
47 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
48 if (DSC == DeclSpecContext::DSC_normal)
49 DSC = DeclSpecContext::DSC_type_specifier;
50
51 // Parse the common declaration-specifiers piece.
52 DeclSpec DS(AttrFactory);
53 if (Attrs)
54 DS.addAttributes(*Attrs);
55 ParseSpecifierQualifierList(DS, AS, DSC);
56 if (OwnedType)
57 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
58
59 // Move declspec attributes to ParsedAttributes
60 if (Attrs) {
62 for (ParsedAttr &AL : DS.getAttributes()) {
63 if (AL.isDeclspecAttribute())
64 ToBeMoved.push_back(&AL);
65 }
66
67 for (ParsedAttr *AL : ToBeMoved)
68 Attrs->takeOneFrom(DS.getAttributes(), AL);
69 }
70
71 // Parse the abstract-declarator, if present.
72 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), Context);
73 ParseDeclarator(DeclaratorInfo);
74 if (Range)
75 *Range = DeclaratorInfo.getSourceRange();
76
77 if (DeclaratorInfo.isInvalidType())
78 return true;
79
80 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
81}
82
83/// Normalizes an attribute name by dropping prefixed and suffixed __.
84static StringRef normalizeAttrName(StringRef Name) {
85 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
86 return Name.drop_front(2).drop_back(2);
87 return Name;
88}
89
90/// isAttributeLateParsed - Return true if the attribute has arguments that
91/// require late parsing.
92static bool isAttributeLateParsed(const IdentifierInfo &II) {
93#define CLANG_ATTR_LATE_PARSED_LIST
94 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
95#include "clang/Parse/AttrParserStringSwitches.inc"
96 .Default(false);
97#undef CLANG_ATTR_LATE_PARSED_LIST
98}
99
100/// Check if the a start and end source location expand to the same macro.
102 SourceLocation EndLoc) {
103 if (!StartLoc.isMacroID() || !EndLoc.isMacroID())
104 return false;
105
107 if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
108 return false;
109
110 bool AttrStartIsInMacro =
112 bool AttrEndIsInMacro =
114 return AttrStartIsInMacro && AttrEndIsInMacro;
115}
116
117void Parser::ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
118 LateParsedAttrList *LateAttrs) {
119 bool MoreToParse;
120 do {
121 // Assume there's nothing left to parse, but if any attributes are in fact
122 // parsed, loop to ensure all specified attribute combinations are parsed.
123 MoreToParse = false;
124 if (WhichAttrKinds & PAKM_CXX11)
125 MoreToParse |= MaybeParseCXX11Attributes(Attrs);
126 if (WhichAttrKinds & PAKM_GNU)
127 MoreToParse |= MaybeParseGNUAttributes(Attrs, LateAttrs);
128 if (WhichAttrKinds & PAKM_Declspec)
129 MoreToParse |= MaybeParseMicrosoftDeclSpecs(Attrs);
130 } while (MoreToParse);
131}
132
133/// ParseGNUAttributes - Parse a non-empty attributes list.
134///
135/// [GNU] attributes:
136/// attribute
137/// attributes attribute
138///
139/// [GNU] attribute:
140/// '__attribute__' '(' '(' attribute-list ')' ')'
141///
142/// [GNU] attribute-list:
143/// attrib
144/// attribute_list ',' attrib
145///
146/// [GNU] attrib:
147/// empty
148/// attrib-name
149/// attrib-name '(' identifier ')'
150/// attrib-name '(' identifier ',' nonempty-expr-list ')'
151/// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
152///
153/// [GNU] attrib-name:
154/// identifier
155/// typespec
156/// typequal
157/// storageclass
158///
159/// Whether an attribute takes an 'identifier' is determined by the
160/// attrib-name. GCC's behavior here is not worth imitating:
161///
162/// * In C mode, if the attribute argument list starts with an identifier
163/// followed by a ',' or an ')', and the identifier doesn't resolve to
164/// a type, it is parsed as an identifier. If the attribute actually
165/// wanted an expression, it's out of luck (but it turns out that no
166/// attributes work that way, because C constant expressions are very
167/// limited).
168/// * In C++ mode, if the attribute argument list starts with an identifier,
169/// and the attribute *wants* an identifier, it is parsed as an identifier.
170/// At block scope, any additional tokens between the identifier and the
171/// ',' or ')' are ignored, otherwise they produce a parse error.
172///
173/// We follow the C++ model, but don't allow junk after the identifier.
174void Parser::ParseGNUAttributes(ParsedAttributes &Attrs,
175 LateParsedAttrList *LateAttrs, Declarator *D) {
176 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
177
178 SourceLocation StartLoc = Tok.getLocation();
179 SourceLocation EndLoc = StartLoc;
180
181 while (Tok.is(tok::kw___attribute)) {
182 SourceLocation AttrTokLoc = ConsumeToken();
183 unsigned OldNumAttrs = Attrs.size();
184 unsigned OldNumLateAttrs = LateAttrs ? LateAttrs->size() : 0;
185
186 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
187 "attribute")) {
188 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
189 return;
190 }
191 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
192 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
193 return;
194 }
195 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
196 do {
197 // Eat preceeding commas to allow __attribute__((,,,foo))
198 while (TryConsumeToken(tok::comma))
199 ;
200
201 // Expect an identifier or declaration specifier (const, int, etc.)
202 if (Tok.isAnnotation())
203 break;
204 if (Tok.is(tok::code_completion)) {
205 cutOffParsing();
207 break;
208 }
209 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
210 if (!AttrName)
211 break;
212
213 SourceLocation AttrNameLoc = ConsumeToken();
214
215 if (Tok.isNot(tok::l_paren)) {
216 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
218 continue;
219 }
220
221 // Handle "parameterized" attributes
222 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
223 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, &EndLoc, nullptr,
225 continue;
226 }
227
228 // Handle attributes with arguments that require late parsing.
229 LateParsedAttribute *LA =
230 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
231 LateAttrs->push_back(LA);
232
233 // Attributes in a class are parsed at the end of the class, along
234 // with other late-parsed declarations.
235 if (!ClassStack.empty() && !LateAttrs->parseSoon())
236 getCurrentClass().LateParsedDeclarations.push_back(LA);
237
238 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
239 // recursively consumes balanced parens.
240 LA->Toks.push_back(Tok);
241 ConsumeParen();
242 // Consume everything up to and including the matching right parens.
243 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
244
245 Token Eof;
246 Eof.startToken();
247 Eof.setLocation(Tok.getLocation());
248 LA->Toks.push_back(Eof);
249 } while (Tok.is(tok::comma));
250
251 if (ExpectAndConsume(tok::r_paren))
252 SkipUntil(tok::r_paren, StopAtSemi);
253 SourceLocation Loc = Tok.getLocation();
254 if (ExpectAndConsume(tok::r_paren))
255 SkipUntil(tok::r_paren, StopAtSemi);
256 EndLoc = Loc;
257
258 // If this was declared in a macro, attach the macro IdentifierInfo to the
259 // parsed attribute.
260 auto &SM = PP.getSourceManager();
261 if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
262 FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
263 CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
264 StringRef FoundName =
265 Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
266 IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
267
268 for (unsigned i = OldNumAttrs; i < Attrs.size(); ++i)
269 Attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
270
271 if (LateAttrs) {
272 for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); ++i)
273 (*LateAttrs)[i]->MacroII = MacroII;
274 }
275 }
276 }
277
278 Attrs.Range = SourceRange(StartLoc, EndLoc);
279}
280
281/// Determine whether the given attribute has an identifier argument.
283#define CLANG_ATTR_IDENTIFIER_ARG_LIST
284 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
285#include "clang/Parse/AttrParserStringSwitches.inc"
286 .Default(false);
287#undef CLANG_ATTR_IDENTIFIER_ARG_LIST
288}
289
290/// Determine whether the given attribute has a variadic identifier argument.
292#define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
293 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
294#include "clang/Parse/AttrParserStringSwitches.inc"
295 .Default(false);
296#undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
297}
298
299/// Determine whether the given attribute treats kw_this as an identifier.
301#define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
302 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
303#include "clang/Parse/AttrParserStringSwitches.inc"
304 .Default(false);
305#undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
306}
307
308/// Determine if an attribute accepts parameter packs.
310#define CLANG_ATTR_ACCEPTS_EXPR_PACK
311 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
312#include "clang/Parse/AttrParserStringSwitches.inc"
313 .Default(false);
314#undef CLANG_ATTR_ACCEPTS_EXPR_PACK
315}
316
317/// Determine whether the given attribute parses a type argument.
319#define CLANG_ATTR_TYPE_ARG_LIST
320 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
321#include "clang/Parse/AttrParserStringSwitches.inc"
322 .Default(false);
323#undef CLANG_ATTR_TYPE_ARG_LIST
324}
325
326/// Determine whether the given attribute requires parsing its arguments
327/// in an unevaluated context or not.
329#define CLANG_ATTR_ARG_CONTEXT_LIST
330 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
331#include "clang/Parse/AttrParserStringSwitches.inc"
332 .Default(false);
333#undef CLANG_ATTR_ARG_CONTEXT_LIST
334}
335
336IdentifierLoc *Parser::ParseIdentifierLoc() {
337 assert(Tok.is(tok::identifier) && "expected an identifier");
339 Tok.getLocation(),
340 Tok.getIdentifierInfo());
341 ConsumeToken();
342 return IL;
343}
344
345void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
346 SourceLocation AttrNameLoc,
347 ParsedAttributes &Attrs,
348 IdentifierInfo *ScopeName,
349 SourceLocation ScopeLoc,
350 ParsedAttr::Syntax Syntax) {
351 BalancedDelimiterTracker Parens(*this, tok::l_paren);
352 Parens.consumeOpen();
353
354 TypeResult T;
355 if (Tok.isNot(tok::r_paren))
356 T = ParseTypeName();
357
358 if (Parens.consumeClose())
359 return;
360
361 if (T.isInvalid())
362 return;
363
364 if (T.isUsable())
365 Attrs.addNewTypeAttr(&AttrName,
366 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
367 ScopeName, ScopeLoc, T.get(), Syntax);
368 else
369 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
370 ScopeName, ScopeLoc, nullptr, 0, Syntax);
371}
372
373unsigned Parser::ParseAttributeArgsCommon(
374 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
375 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
376 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
377 // Ignore the left paren location for now.
378 ConsumeParen();
379
380 bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
381 bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
382 bool AttributeHasVariadicIdentifierArg =
384
385 // Interpret "kw_this" as an identifier if the attributed requests it.
386 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
387 Tok.setKind(tok::identifier);
388
389 ArgsVector ArgExprs;
390 if (Tok.is(tok::identifier)) {
391 // If this attribute wants an 'identifier' argument, make it so.
392 bool IsIdentifierArg = AttributeHasVariadicIdentifierArg ||
393 attributeHasIdentifierArg(*AttrName);
394 ParsedAttr::Kind AttrKind =
395 ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
396
397 // If we don't know how to parse this attribute, but this is the only
398 // token in this argument, assume it's meant to be an identifier.
399 if (AttrKind == ParsedAttr::UnknownAttribute ||
400 AttrKind == ParsedAttr::IgnoredAttribute) {
401 const Token &Next = NextToken();
402 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
403 }
404
405 if (IsIdentifierArg)
406 ArgExprs.push_back(ParseIdentifierLoc());
407 }
408
409 ParsedType TheParsedType;
410 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
411 // Eat the comma.
412 if (!ArgExprs.empty())
413 ConsumeToken();
414
415 if (AttributeIsTypeArgAttr) {
416 // FIXME: Multiple type arguments are not implemented.
418 if (T.isInvalid()) {
419 SkipUntil(tok::r_paren, StopAtSemi);
420 return 0;
421 }
422 if (T.isUsable())
423 TheParsedType = T.get();
424 } else if (AttributeHasVariadicIdentifierArg) {
425 // Parse variadic identifier arg. This can either consume identifiers or
426 // expressions. Variadic identifier args do not support parameter packs
427 // because those are typically used for attributes with enumeration
428 // arguments, and those enumerations are not something the user could
429 // express via a pack.
430 do {
431 // Interpret "kw_this" as an identifier if the attributed requests it.
432 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
433 Tok.setKind(tok::identifier);
434
435 ExprResult ArgExpr;
436 if (Tok.is(tok::identifier)) {
437 ArgExprs.push_back(ParseIdentifierLoc());
438 } else {
439 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
441 Actions,
444
445 ExprResult ArgExpr(
447
448 if (ArgExpr.isInvalid()) {
449 SkipUntil(tok::r_paren, StopAtSemi);
450 return 0;
451 }
452 ArgExprs.push_back(ArgExpr.get());
453 }
454 // Eat the comma, move to the next argument
455 } while (TryConsumeToken(tok::comma));
456 } else {
457 // General case. Parse all available expressions.
458 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
460 Actions, Uneval
463
464 ExprVector ParsedExprs;
465 if (ParseExpressionList(ParsedExprs, llvm::function_ref<void()>(),
466 /*FailImmediatelyOnInvalidExpr=*/true,
467 /*EarlyTypoCorrection=*/true)) {
468 SkipUntil(tok::r_paren, StopAtSemi);
469 return 0;
470 }
471
472 // Pack expansion must currently be explicitly supported by an attribute.
473 for (size_t I = 0; I < ParsedExprs.size(); ++I) {
474 if (!isa<PackExpansionExpr>(ParsedExprs[I]))
475 continue;
476
477 if (!attributeAcceptsExprPack(*AttrName)) {
478 Diag(Tok.getLocation(),
479 diag::err_attribute_argument_parm_pack_not_supported)
480 << AttrName;
481 SkipUntil(tok::r_paren, StopAtSemi);
482 return 0;
483 }
484 }
485
486 ArgExprs.insert(ArgExprs.end(), ParsedExprs.begin(), ParsedExprs.end());
487 }
488 }
489
490 SourceLocation RParen = Tok.getLocation();
491 if (!ExpectAndConsume(tok::r_paren)) {
492 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
493
494 if (AttributeIsTypeArgAttr && !TheParsedType.get().isNull()) {
495 Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
496 ScopeName, ScopeLoc, TheParsedType, Syntax);
497 } else {
498 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
499 ArgExprs.data(), ArgExprs.size(), Syntax);
500 }
501 }
502
503 if (EndLoc)
504 *EndLoc = RParen;
505
506 return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
507}
508
509/// Parse the arguments to a parameterized GNU attribute or
510/// a C++11 attribute in "gnu" namespace.
511void Parser::ParseGNUAttributeArgs(
512 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
513 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
514 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax, Declarator *D) {
515
516 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
517
518 ParsedAttr::Kind AttrKind =
519 ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
520
521 if (AttrKind == ParsedAttr::AT_Availability) {
522 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
523 ScopeLoc, Syntax);
524 return;
525 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
526 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
527 ScopeName, ScopeLoc, Syntax);
528 return;
529 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
530 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
531 ScopeName, ScopeLoc, Syntax);
532 return;
533 } else if (AttrKind == ParsedAttr::AT_SwiftNewType) {
534 ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
535 ScopeLoc, Syntax);
536 return;
537 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
538 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
539 ScopeName, ScopeLoc, Syntax);
540 return;
541 } else if (attributeIsTypeArgAttr(*AttrName)) {
542 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, ScopeName,
543 ScopeLoc, Syntax);
544 return;
545 }
546
547 // These may refer to the function arguments, but need to be parsed early to
548 // participate in determining whether it's a redeclaration.
549 std::optional<ParseScope> PrototypeScope;
550 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
551 D && D->isFunctionDeclarator()) {
553 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
556 for (unsigned i = 0; i != FTI.NumParams; ++i) {
557 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
559 }
560 }
561
562 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
563 ScopeLoc, Syntax);
564}
565
566unsigned Parser::ParseClangAttributeArgs(
567 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
568 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
569 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
570 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
571
572 ParsedAttr::Kind AttrKind =
573 ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
574
575 switch (AttrKind) {
576 default:
577 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
578 ScopeName, ScopeLoc, Syntax);
579 case ParsedAttr::AT_ExternalSourceSymbol:
580 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
581 ScopeName, ScopeLoc, Syntax);
582 break;
583 case ParsedAttr::AT_Availability:
584 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
585 ScopeLoc, Syntax);
586 break;
587 case ParsedAttr::AT_ObjCBridgeRelated:
588 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
589 ScopeName, ScopeLoc, Syntax);
590 break;
591 case ParsedAttr::AT_SwiftNewType:
592 ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
593 ScopeLoc, Syntax);
594 break;
595 case ParsedAttr::AT_TypeTagForDatatype:
596 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
597 ScopeName, ScopeLoc, Syntax);
598 break;
599 }
600 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
601}
602
603bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
604 SourceLocation AttrNameLoc,
605 ParsedAttributes &Attrs) {
606 unsigned ExistingAttrs = Attrs.size();
607
608 // If the attribute isn't known, we will not attempt to parse any
609 // arguments.
612 // Eat the left paren, then skip to the ending right paren.
613 ConsumeParen();
614 SkipUntil(tok::r_paren);
615 return false;
616 }
617
618 SourceLocation OpenParenLoc = Tok.getLocation();
619
620 if (AttrName->getName() == "property") {
621 // The property declspec is more complex in that it can take one or two
622 // assignment expressions as a parameter, but the lhs of the assignment
623 // must be named get or put.
624
625 BalancedDelimiterTracker T(*this, tok::l_paren);
626 T.expectAndConsume(diag::err_expected_lparen_after,
627 AttrName->getNameStart(), tok::r_paren);
628
629 enum AccessorKind {
630 AK_Invalid = -1,
631 AK_Put = 0,
632 AK_Get = 1 // indices into AccessorNames
633 };
634 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
635 bool HasInvalidAccessor = false;
636
637 // Parse the accessor specifications.
638 while (true) {
639 // Stop if this doesn't look like an accessor spec.
640 if (!Tok.is(tok::identifier)) {
641 // If the user wrote a completely empty list, use a special diagnostic.
642 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
643 AccessorNames[AK_Put] == nullptr &&
644 AccessorNames[AK_Get] == nullptr) {
645 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
646 break;
647 }
648
649 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
650 break;
651 }
652
653 AccessorKind Kind;
654 SourceLocation KindLoc = Tok.getLocation();
655 StringRef KindStr = Tok.getIdentifierInfo()->getName();
656 if (KindStr == "get") {
657 Kind = AK_Get;
658 } else if (KindStr == "put") {
659 Kind = AK_Put;
660
661 // Recover from the common mistake of using 'set' instead of 'put'.
662 } else if (KindStr == "set") {
663 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
664 << FixItHint::CreateReplacement(KindLoc, "put");
665 Kind = AK_Put;
666
667 // Handle the mistake of forgetting the accessor kind by skipping
668 // this accessor.
669 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
670 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
671 ConsumeToken();
672 HasInvalidAccessor = true;
673 goto next_property_accessor;
674
675 // Otherwise, complain about the unknown accessor kind.
676 } else {
677 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
678 HasInvalidAccessor = true;
679 Kind = AK_Invalid;
680
681 // Try to keep parsing unless it doesn't look like an accessor spec.
682 if (!NextToken().is(tok::equal))
683 break;
684 }
685
686 // Consume the identifier.
687 ConsumeToken();
688
689 // Consume the '='.
690 if (!TryConsumeToken(tok::equal)) {
691 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
692 << KindStr;
693 break;
694 }
695
696 // Expect the method name.
697 if (!Tok.is(tok::identifier)) {
698 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
699 break;
700 }
701
702 if (Kind == AK_Invalid) {
703 // Just drop invalid accessors.
704 } else if (AccessorNames[Kind] != nullptr) {
705 // Complain about the repeated accessor, ignore it, and keep parsing.
706 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
707 } else {
708 AccessorNames[Kind] = Tok.getIdentifierInfo();
709 }
710 ConsumeToken();
711
712 next_property_accessor:
713 // Keep processing accessors until we run out.
714 if (TryConsumeToken(tok::comma))
715 continue;
716
717 // If we run into the ')', stop without consuming it.
718 if (Tok.is(tok::r_paren))
719 break;
720
721 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
722 break;
723 }
724
725 // Only add the property attribute if it was well-formed.
726 if (!HasInvalidAccessor)
727 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
728 AccessorNames[AK_Get], AccessorNames[AK_Put],
730 T.skipToEnd();
731 return !HasInvalidAccessor;
732 }
733
734 unsigned NumArgs =
735 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
737
738 // If this attribute's args were parsed, and it was expected to have
739 // arguments but none were provided, emit a diagnostic.
740 if (ExistingAttrs < Attrs.size() && Attrs.back().getMaxArgs() && !NumArgs) {
741 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
742 return false;
743 }
744 return true;
745}
746
747/// [MS] decl-specifier:
748/// __declspec ( extended-decl-modifier-seq )
749///
750/// [MS] extended-decl-modifier-seq:
751/// extended-decl-modifier[opt]
752/// extended-decl-modifier extended-decl-modifier-seq
753void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
754 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
755 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
756
757 SourceLocation StartLoc = Tok.getLocation();
758 SourceLocation EndLoc = StartLoc;
759
760 while (Tok.is(tok::kw___declspec)) {
761 ConsumeToken();
762 BalancedDelimiterTracker T(*this, tok::l_paren);
763 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
764 tok::r_paren))
765 return;
766
767 // An empty declspec is perfectly legal and should not warn. Additionally,
768 // you can specify multiple attributes per declspec.
769 while (Tok.isNot(tok::r_paren)) {
770 // Attribute not present.
771 if (TryConsumeToken(tok::comma))
772 continue;
773
774 if (Tok.is(tok::code_completion)) {
775 cutOffParsing();
777 return;
778 }
779
780 // We expect either a well-known identifier or a generic string. Anything
781 // else is a malformed declspec.
782 bool IsString = Tok.getKind() == tok::string_literal;
783 if (!IsString && Tok.getKind() != tok::identifier &&
784 Tok.getKind() != tok::kw_restrict) {
785 Diag(Tok, diag::err_ms_declspec_type);
786 T.skipToEnd();
787 return;
788 }
789
790 IdentifierInfo *AttrName;
791 SourceLocation AttrNameLoc;
792 if (IsString) {
793 SmallString<8> StrBuffer;
794 bool Invalid = false;
795 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
796 if (Invalid) {
797 T.skipToEnd();
798 return;
799 }
800 AttrName = PP.getIdentifierInfo(Str);
801 AttrNameLoc = ConsumeStringToken();
802 } else {
803 AttrName = Tok.getIdentifierInfo();
804 AttrNameLoc = ConsumeToken();
805 }
806
807 bool AttrHandled = false;
808
809 // Parse attribute arguments.
810 if (Tok.is(tok::l_paren))
811 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
812 else if (AttrName->getName() == "property")
813 // The property attribute must have an argument list.
814 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
815 << AttrName->getName();
816
817 if (!AttrHandled)
818 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
820 }
821 T.consumeClose();
822 EndLoc = T.getCloseLocation();
823 }
824
825 Attrs.Range = SourceRange(StartLoc, EndLoc);
826}
827
828void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
829 // Treat these like attributes
830 while (true) {
831 switch (Tok.getKind()) {
832 case tok::kw___fastcall:
833 case tok::kw___stdcall:
834 case tok::kw___thiscall:
835 case tok::kw___regcall:
836 case tok::kw___cdecl:
837 case tok::kw___vectorcall:
838 case tok::kw___ptr64:
839 case tok::kw___w64:
840 case tok::kw___ptr32:
841 case tok::kw___sptr:
842 case tok::kw___uptr: {
843 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
844 SourceLocation AttrNameLoc = ConsumeToken();
845 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
847 break;
848 }
849 default:
850 return;
851 }
852 }
853}
854
855void Parser::ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &attrs) {
856 assert(Tok.is(tok::kw___funcref));
857 SourceLocation StartLoc = Tok.getLocation();
858 if (!getTargetInfo().getTriple().isWasm()) {
859 ConsumeToken();
860 Diag(StartLoc, diag::err_wasm_funcref_not_wasm);
861 return;
862 }
863
864 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
865 SourceLocation AttrNameLoc = ConsumeToken();
866 attrs.addNew(AttrName, AttrNameLoc, /*ScopeName=*/nullptr,
867 /*ScopeLoc=*/SourceLocation{}, /*Args=*/nullptr, /*numArgs=*/0,
869}
870
871void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
872 SourceLocation StartLoc = Tok.getLocation();
873 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
874
875 if (EndLoc.isValid()) {
876 SourceRange Range(StartLoc, EndLoc);
877 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
878 }
879}
880
881SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
882 SourceLocation EndLoc;
883
884 while (true) {
885 switch (Tok.getKind()) {
886 case tok::kw_const:
887 case tok::kw_volatile:
888 case tok::kw___fastcall:
889 case tok::kw___stdcall:
890 case tok::kw___thiscall:
891 case tok::kw___cdecl:
892 case tok::kw___vectorcall:
893 case tok::kw___ptr32:
894 case tok::kw___ptr64:
895 case tok::kw___w64:
896 case tok::kw___unaligned:
897 case tok::kw___sptr:
898 case tok::kw___uptr:
899 EndLoc = ConsumeToken();
900 break;
901 default:
902 return EndLoc;
903 }
904 }
905}
906
907void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
908 // Treat these like attributes
909 while (Tok.is(tok::kw___pascal)) {
910 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
911 SourceLocation AttrNameLoc = ConsumeToken();
912 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
914 }
915}
916
917void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
918 // Treat these like attributes
919 while (Tok.is(tok::kw___kernel)) {
920 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
921 SourceLocation AttrNameLoc = ConsumeToken();
922 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
924 }
925}
926
927void Parser::ParseCUDAFunctionAttributes(ParsedAttributes &attrs) {
928 while (Tok.is(tok::kw___noinline__)) {
929 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
930 SourceLocation AttrNameLoc = ConsumeToken();
931 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
933 }
934}
935
936void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
937 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
938 SourceLocation AttrNameLoc = Tok.getLocation();
939 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
941}
942
943bool Parser::isHLSLQualifier(const Token &Tok) const {
944 return Tok.is(tok::kw_groupshared);
945}
946
947void Parser::ParseHLSLQualifiers(ParsedAttributes &Attrs) {
948 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
949 SourceLocation AttrNameLoc = ConsumeToken();
950 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
952}
953
954void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
955 // Treat these like attributes, even though they're type specifiers.
956 while (true) {
957 switch (Tok.getKind()) {
958 case tok::kw__Nonnull:
959 case tok::kw__Nullable:
960 case tok::kw__Nullable_result:
961 case tok::kw__Null_unspecified: {
962 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
963 SourceLocation AttrNameLoc = ConsumeToken();
964 if (!getLangOpts().ObjC)
965 Diag(AttrNameLoc, diag::ext_nullability)
966 << AttrName;
967 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
969 break;
970 }
971 default:
972 return;
973 }
974 }
975}
976
977static bool VersionNumberSeparator(const char Separator) {
978 return (Separator == '.' || Separator == '_');
979}
980
981/// Parse a version number.
982///
983/// version:
984/// simple-integer
985/// simple-integer '.' simple-integer
986/// simple-integer '_' simple-integer
987/// simple-integer '.' simple-integer '.' simple-integer
988/// simple-integer '_' simple-integer '_' simple-integer
989VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
990 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
991
992 if (!Tok.is(tok::numeric_constant)) {
993 Diag(Tok, diag::err_expected_version);
994 SkipUntil(tok::comma, tok::r_paren,
996 return VersionTuple();
997 }
998
999 // Parse the major (and possibly minor and subminor) versions, which
1000 // are stored in the numeric constant. We utilize a quirk of the
1001 // lexer, which is that it handles something like 1.2.3 as a single
1002 // numeric constant, rather than two separate tokens.
1003 SmallString<512> Buffer;
1004 Buffer.resize(Tok.getLength()+1);
1005 const char *ThisTokBegin = &Buffer[0];
1006
1007 // Get the spelling of the token, which eliminates trigraphs, etc.
1008 bool Invalid = false;
1009 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1010 if (Invalid)
1011 return VersionTuple();
1012
1013 // Parse the major version.
1014 unsigned AfterMajor = 0;
1015 unsigned Major = 0;
1016 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
1017 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
1018 ++AfterMajor;
1019 }
1020
1021 if (AfterMajor == 0) {
1022 Diag(Tok, diag::err_expected_version);
1023 SkipUntil(tok::comma, tok::r_paren,
1025 return VersionTuple();
1026 }
1027
1028 if (AfterMajor == ActualLength) {
1029 ConsumeToken();
1030
1031 // We only had a single version component.
1032 if (Major == 0) {
1033 Diag(Tok, diag::err_zero_version);
1034 return VersionTuple();
1035 }
1036
1037 return VersionTuple(Major);
1038 }
1039
1040 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
1041 if (!VersionNumberSeparator(AfterMajorSeparator)
1042 || (AfterMajor + 1 == ActualLength)) {
1043 Diag(Tok, diag::err_expected_version);
1044 SkipUntil(tok::comma, tok::r_paren,
1046 return VersionTuple();
1047 }
1048
1049 // Parse the minor version.
1050 unsigned AfterMinor = AfterMajor + 1;
1051 unsigned Minor = 0;
1052 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
1053 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
1054 ++AfterMinor;
1055 }
1056
1057 if (AfterMinor == ActualLength) {
1058 ConsumeToken();
1059
1060 // We had major.minor.
1061 if (Major == 0 && Minor == 0) {
1062 Diag(Tok, diag::err_zero_version);
1063 return VersionTuple();
1064 }
1065
1066 return VersionTuple(Major, Minor);
1067 }
1068
1069 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
1070 // If what follows is not a '.' or '_', we have a problem.
1071 if (!VersionNumberSeparator(AfterMinorSeparator)) {
1072 Diag(Tok, diag::err_expected_version);
1073 SkipUntil(tok::comma, tok::r_paren,
1075 return VersionTuple();
1076 }
1077
1078 // Warn if separators, be it '.' or '_', do not match.
1079 if (AfterMajorSeparator != AfterMinorSeparator)
1080 Diag(Tok, diag::warn_expected_consistent_version_separator);
1081
1082 // Parse the subminor version.
1083 unsigned AfterSubminor = AfterMinor + 1;
1084 unsigned Subminor = 0;
1085 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
1086 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
1087 ++AfterSubminor;
1088 }
1089
1090 if (AfterSubminor != ActualLength) {
1091 Diag(Tok, diag::err_expected_version);
1092 SkipUntil(tok::comma, tok::r_paren,
1094 return VersionTuple();
1095 }
1096 ConsumeToken();
1097 return VersionTuple(Major, Minor, Subminor);
1098}
1099
1100/// Parse the contents of the "availability" attribute.
1101///
1102/// availability-attribute:
1103/// 'availability' '(' platform ',' opt-strict version-arg-list,
1104/// opt-replacement, opt-message')'
1105///
1106/// platform:
1107/// identifier
1108///
1109/// opt-strict:
1110/// 'strict' ','
1111///
1112/// version-arg-list:
1113/// version-arg
1114/// version-arg ',' version-arg-list
1115///
1116/// version-arg:
1117/// 'introduced' '=' version
1118/// 'deprecated' '=' version
1119/// 'obsoleted' = version
1120/// 'unavailable'
1121/// opt-replacement:
1122/// 'replacement' '=' <string>
1123/// opt-message:
1124/// 'message' '=' <string>
1125void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
1126 SourceLocation AvailabilityLoc,
1127 ParsedAttributes &attrs,
1128 SourceLocation *endLoc,
1129 IdentifierInfo *ScopeName,
1130 SourceLocation ScopeLoc,
1131 ParsedAttr::Syntax Syntax) {
1132 enum { Introduced, Deprecated, Obsoleted, Unknown };
1133 AvailabilityChange Changes[Unknown];
1134 ExprResult MessageExpr, ReplacementExpr;
1135
1136 // Opening '('.
1137 BalancedDelimiterTracker T(*this, tok::l_paren);
1138 if (T.consumeOpen()) {
1139 Diag(Tok, diag::err_expected) << tok::l_paren;
1140 return;
1141 }
1142
1143 // Parse the platform name.
1144 if (Tok.isNot(tok::identifier)) {
1145 Diag(Tok, diag::err_availability_expected_platform);
1146 SkipUntil(tok::r_paren, StopAtSemi);
1147 return;
1148 }
1149 IdentifierLoc *Platform = ParseIdentifierLoc();
1150 if (const IdentifierInfo *const Ident = Platform->Ident) {
1151 // Canonicalize platform name from "macosx" to "macos".
1152 if (Ident->getName() == "macosx")
1153 Platform->Ident = PP.getIdentifierInfo("macos");
1154 // Canonicalize platform name from "macosx_app_extension" to
1155 // "macos_app_extension".
1156 else if (Ident->getName() == "macosx_app_extension")
1157 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1158 else
1159 Platform->Ident = PP.getIdentifierInfo(
1160 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1161 }
1162
1163 // Parse the ',' following the platform name.
1164 if (ExpectAndConsume(tok::comma)) {
1165 SkipUntil(tok::r_paren, StopAtSemi);
1166 return;
1167 }
1168
1169 // If we haven't grabbed the pointers for the identifiers
1170 // "introduced", "deprecated", and "obsoleted", do so now.
1171 if (!Ident_introduced) {
1172 Ident_introduced = PP.getIdentifierInfo("introduced");
1173 Ident_deprecated = PP.getIdentifierInfo("deprecated");
1174 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1175 Ident_unavailable = PP.getIdentifierInfo("unavailable");
1176 Ident_message = PP.getIdentifierInfo("message");
1177 Ident_strict = PP.getIdentifierInfo("strict");
1178 Ident_replacement = PP.getIdentifierInfo("replacement");
1179 }
1180
1181 // Parse the optional "strict", the optional "replacement" and the set of
1182 // introductions/deprecations/removals.
1183 SourceLocation UnavailableLoc, StrictLoc;
1184 do {
1185 if (Tok.isNot(tok::identifier)) {
1186 Diag(Tok, diag::err_availability_expected_change);
1187 SkipUntil(tok::r_paren, StopAtSemi);
1188 return;
1189 }
1190 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1191 SourceLocation KeywordLoc = ConsumeToken();
1192
1193 if (Keyword == Ident_strict) {
1194 if (StrictLoc.isValid()) {
1195 Diag(KeywordLoc, diag::err_availability_redundant)
1196 << Keyword << SourceRange(StrictLoc);
1197 }
1198 StrictLoc = KeywordLoc;
1199 continue;
1200 }
1201
1202 if (Keyword == Ident_unavailable) {
1203 if (UnavailableLoc.isValid()) {
1204 Diag(KeywordLoc, diag::err_availability_redundant)
1205 << Keyword << SourceRange(UnavailableLoc);
1206 }
1207 UnavailableLoc = KeywordLoc;
1208 continue;
1209 }
1210
1211 if (Keyword == Ident_deprecated && Platform->Ident &&
1212 Platform->Ident->isStr("swift")) {
1213 // For swift, we deprecate for all versions.
1214 if (Changes[Deprecated].KeywordLoc.isValid()) {
1215 Diag(KeywordLoc, diag::err_availability_redundant)
1216 << Keyword
1217 << SourceRange(Changes[Deprecated].KeywordLoc);
1218 }
1219
1220 Changes[Deprecated].KeywordLoc = KeywordLoc;
1221 // Use a fake version here.
1222 Changes[Deprecated].Version = VersionTuple(1);
1223 continue;
1224 }
1225
1226 if (Tok.isNot(tok::equal)) {
1227 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1228 SkipUntil(tok::r_paren, StopAtSemi);
1229 return;
1230 }
1231 ConsumeToken();
1232 if (Keyword == Ident_message || Keyword == Ident_replacement) {
1233 if (Tok.isNot(tok::string_literal)) {
1234 Diag(Tok, diag::err_expected_string_literal)
1235 << /*Source='availability attribute'*/2;
1236 SkipUntil(tok::r_paren, StopAtSemi);
1237 return;
1238 }
1239 if (Keyword == Ident_message)
1240 MessageExpr = ParseStringLiteralExpression();
1241 else
1242 ReplacementExpr = ParseStringLiteralExpression();
1243 // Also reject wide string literals.
1244 if (StringLiteral *MessageStringLiteral =
1245 cast_or_null<StringLiteral>(MessageExpr.get())) {
1246 if (!MessageStringLiteral->isOrdinary()) {
1247 Diag(MessageStringLiteral->getSourceRange().getBegin(),
1248 diag::err_expected_string_literal)
1249 << /*Source='availability attribute'*/ 2;
1250 SkipUntil(tok::r_paren, StopAtSemi);
1251 return;
1252 }
1253 }
1254 if (Keyword == Ident_message)
1255 break;
1256 else
1257 continue;
1258 }
1259
1260 // Special handling of 'NA' only when applied to introduced or
1261 // deprecated.
1262 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1263 Tok.is(tok::identifier)) {
1265 if (NA->getName() == "NA") {
1266 ConsumeToken();
1267 if (Keyword == Ident_introduced)
1268 UnavailableLoc = KeywordLoc;
1269 continue;
1270 }
1271 }
1272
1273 SourceRange VersionRange;
1274 VersionTuple Version = ParseVersionTuple(VersionRange);
1275
1276 if (Version.empty()) {
1277 SkipUntil(tok::r_paren, StopAtSemi);
1278 return;
1279 }
1280
1281 unsigned Index;
1282 if (Keyword == Ident_introduced)
1283 Index = Introduced;
1284 else if (Keyword == Ident_deprecated)
1285 Index = Deprecated;
1286 else if (Keyword == Ident_obsoleted)
1287 Index = Obsoleted;
1288 else
1289 Index = Unknown;
1290
1291 if (Index < Unknown) {
1292 if (!Changes[Index].KeywordLoc.isInvalid()) {
1293 Diag(KeywordLoc, diag::err_availability_redundant)
1294 << Keyword
1295 << SourceRange(Changes[Index].KeywordLoc,
1296 Changes[Index].VersionRange.getEnd());
1297 }
1298
1299 Changes[Index].KeywordLoc = KeywordLoc;
1300 Changes[Index].Version = Version;
1301 Changes[Index].VersionRange = VersionRange;
1302 } else {
1303 Diag(KeywordLoc, diag::err_availability_unknown_change)
1304 << Keyword << VersionRange;
1305 }
1306
1307 } while (TryConsumeToken(tok::comma));
1308
1309 // Closing ')'.
1310 if (T.consumeClose())
1311 return;
1312
1313 if (endLoc)
1314 *endLoc = T.getCloseLocation();
1315
1316 // The 'unavailable' availability cannot be combined with any other
1317 // availability changes. Make sure that hasn't happened.
1318 if (UnavailableLoc.isValid()) {
1319 bool Complained = false;
1320 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1321 if (Changes[Index].KeywordLoc.isValid()) {
1322 if (!Complained) {
1323 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1324 << SourceRange(Changes[Index].KeywordLoc,
1325 Changes[Index].VersionRange.getEnd());
1326 Complained = true;
1327 }
1328
1329 // Clear out the availability.
1330 Changes[Index] = AvailabilityChange();
1331 }
1332 }
1333 }
1334
1335 // Record this attribute
1336 attrs.addNew(&Availability,
1337 SourceRange(AvailabilityLoc, T.getCloseLocation()),
1338 ScopeName, ScopeLoc,
1339 Platform,
1340 Changes[Introduced],
1341 Changes[Deprecated],
1342 Changes[Obsoleted],
1343 UnavailableLoc, MessageExpr.get(),
1344 Syntax, StrictLoc, ReplacementExpr.get());
1345}
1346
1347/// Parse the contents of the "external_source_symbol" attribute.
1348///
1349/// external-source-symbol-attribute:
1350/// 'external_source_symbol' '(' keyword-arg-list ')'
1351///
1352/// keyword-arg-list:
1353/// keyword-arg
1354/// keyword-arg ',' keyword-arg-list
1355///
1356/// keyword-arg:
1357/// 'language' '=' <string>
1358/// 'defined_in' '=' <string>
1359/// 'USR' '=' <string>
1360/// 'generated_declaration'
1361void Parser::ParseExternalSourceSymbolAttribute(
1362 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1363 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1364 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1365 // Opening '('.
1366 BalancedDelimiterTracker T(*this, tok::l_paren);
1367 if (T.expectAndConsume())
1368 return;
1369
1370 // Initialize the pointers for the keyword identifiers when required.
1371 if (!Ident_language) {
1372 Ident_language = PP.getIdentifierInfo("language");
1373 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1374 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1375 Ident_USR = PP.getIdentifierInfo("USR");
1376 }
1377
1379 bool HasLanguage = false;
1380 ExprResult DefinedInExpr;
1381 bool HasDefinedIn = false;
1382 IdentifierLoc *GeneratedDeclaration = nullptr;
1383 ExprResult USR;
1384 bool HasUSR = false;
1385
1386 // Parse the language/defined_in/generated_declaration keywords
1387 do {
1388 if (Tok.isNot(tok::identifier)) {
1389 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1390 SkipUntil(tok::r_paren, StopAtSemi);
1391 return;
1392 }
1393
1394 SourceLocation KeywordLoc = Tok.getLocation();
1395 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1396 if (Keyword == Ident_generated_declaration) {
1397 if (GeneratedDeclaration) {
1398 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1399 SkipUntil(tok::r_paren, StopAtSemi);
1400 return;
1401 }
1402 GeneratedDeclaration = ParseIdentifierLoc();
1403 continue;
1404 }
1405
1406 if (Keyword != Ident_language && Keyword != Ident_defined_in &&
1407 Keyword != Ident_USR) {
1408 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1409 SkipUntil(tok::r_paren, StopAtSemi);
1410 return;
1411 }
1412
1413 ConsumeToken();
1414 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1415 Keyword->getName())) {
1416 SkipUntil(tok::r_paren, StopAtSemi);
1417 return;
1418 }
1419
1420 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn,
1421 HadUSR = HasUSR;
1422 if (Keyword == Ident_language)
1423 HasLanguage = true;
1424 else if (Keyword == Ident_USR)
1425 HasUSR = true;
1426 else
1427 HasDefinedIn = true;
1428
1429 if (Tok.isNot(tok::string_literal)) {
1430 Diag(Tok, diag::err_expected_string_literal)
1431 << /*Source='external_source_symbol attribute'*/ 3
1432 << /*language | source container | USR*/ (
1433 Keyword == Ident_language
1434 ? 0
1435 : (Keyword == Ident_defined_in ? 1 : 2));
1436 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1437 continue;
1438 }
1439 if (Keyword == Ident_language) {
1440 if (HadLanguage) {
1441 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1442 << Keyword;
1444 continue;
1445 }
1447 } else if (Keyword == Ident_USR) {
1448 if (HadUSR) {
1449 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1450 << Keyword;
1452 continue;
1453 }
1455 } else {
1456 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1457 if (HadDefinedIn) {
1458 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1459 << Keyword;
1461 continue;
1462 }
1463 DefinedInExpr = ParseStringLiteralExpression();
1464 }
1465 } while (TryConsumeToken(tok::comma));
1466
1467 // Closing ')'.
1468 if (T.consumeClose())
1469 return;
1470 if (EndLoc)
1471 *EndLoc = T.getCloseLocation();
1472
1473 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(), GeneratedDeclaration,
1474 USR.get()};
1475 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1476 ScopeName, ScopeLoc, Args, std::size(Args), Syntax);
1477}
1478
1479/// Parse the contents of the "objc_bridge_related" attribute.
1480/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1481/// related_class:
1482/// Identifier
1483///
1484/// opt-class_method:
1485/// Identifier: | <empty>
1486///
1487/// opt-instance_method:
1488/// Identifier | <empty>
1489///
1490void Parser::ParseObjCBridgeRelatedAttribute(
1491 IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc,
1492 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1493 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1494 // Opening '('.
1495 BalancedDelimiterTracker T(*this, tok::l_paren);
1496 if (T.consumeOpen()) {
1497 Diag(Tok, diag::err_expected) << tok::l_paren;
1498 return;
1499 }
1500
1501 // Parse the related class name.
1502 if (Tok.isNot(tok::identifier)) {
1503 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1504 SkipUntil(tok::r_paren, StopAtSemi);
1505 return;
1506 }
1507 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1508 if (ExpectAndConsume(tok::comma)) {
1509 SkipUntil(tok::r_paren, StopAtSemi);
1510 return;
1511 }
1512
1513 // Parse class method name. It's non-optional in the sense that a trailing
1514 // comma is required, but it can be the empty string, and then we record a
1515 // nullptr.
1516 IdentifierLoc *ClassMethod = nullptr;
1517 if (Tok.is(tok::identifier)) {
1518 ClassMethod = ParseIdentifierLoc();
1519 if (!TryConsumeToken(tok::colon)) {
1520 Diag(Tok, diag::err_objcbridge_related_selector_name);
1521 SkipUntil(tok::r_paren, StopAtSemi);
1522 return;
1523 }
1524 }
1525 if (!TryConsumeToken(tok::comma)) {
1526 if (Tok.is(tok::colon))
1527 Diag(Tok, diag::err_objcbridge_related_selector_name);
1528 else
1529 Diag(Tok, diag::err_expected) << tok::comma;
1530 SkipUntil(tok::r_paren, StopAtSemi);
1531 return;
1532 }
1533
1534 // Parse instance method name. Also non-optional but empty string is
1535 // permitted.
1536 IdentifierLoc *InstanceMethod = nullptr;
1537 if (Tok.is(tok::identifier))
1538 InstanceMethod = ParseIdentifierLoc();
1539 else if (Tok.isNot(tok::r_paren)) {
1540 Diag(Tok, diag::err_expected) << tok::r_paren;
1541 SkipUntil(tok::r_paren, StopAtSemi);
1542 return;
1543 }
1544
1545 // Closing ')'.
1546 if (T.consumeClose())
1547 return;
1548
1549 if (EndLoc)
1550 *EndLoc = T.getCloseLocation();
1551
1552 // Record this attribute
1553 Attrs.addNew(&ObjCBridgeRelated,
1554 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1555 ScopeName, ScopeLoc, RelatedClass, ClassMethod, InstanceMethod,
1556 Syntax);
1557}
1558
1559void Parser::ParseSwiftNewTypeAttribute(
1560 IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1561 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1562 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1563 BalancedDelimiterTracker T(*this, tok::l_paren);
1564
1565 // Opening '('
1566 if (T.consumeOpen()) {
1567 Diag(Tok, diag::err_expected) << tok::l_paren;
1568 return;
1569 }
1570
1571 if (Tok.is(tok::r_paren)) {
1572 Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
1573 T.consumeClose();
1574 return;
1575 }
1576 if (Tok.isNot(tok::kw_struct) && Tok.isNot(tok::kw_enum)) {
1577 Diag(Tok, diag::warn_attribute_type_not_supported)
1578 << &AttrName << Tok.getIdentifierInfo();
1579 if (!isTokenSpecial())
1580 ConsumeToken();
1581 T.consumeClose();
1582 return;
1583 }
1584
1585 auto *SwiftType = IdentifierLoc::create(Actions.Context, Tok.getLocation(),
1586 Tok.getIdentifierInfo());
1587 ConsumeToken();
1588
1589 // Closing ')'
1590 if (T.consumeClose())
1591 return;
1592 if (EndLoc)
1593 *EndLoc = T.getCloseLocation();
1594
1595 ArgsUnion Args[] = {SwiftType};
1596 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, T.getCloseLocation()),
1597 ScopeName, ScopeLoc, Args, std::size(Args), Syntax);
1598}
1599
1600void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1601 SourceLocation AttrNameLoc,
1602 ParsedAttributes &Attrs,
1603 SourceLocation *EndLoc,
1604 IdentifierInfo *ScopeName,
1605 SourceLocation ScopeLoc,
1606 ParsedAttr::Syntax Syntax) {
1607 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1608
1609 BalancedDelimiterTracker T(*this, tok::l_paren);
1610 T.consumeOpen();
1611
1612 if (Tok.isNot(tok::identifier)) {
1613 Diag(Tok, diag::err_expected) << tok::identifier;
1614 T.skipToEnd();
1615 return;
1616 }
1617 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1618
1619 if (ExpectAndConsume(tok::comma)) {
1620 T.skipToEnd();
1621 return;
1622 }
1623
1624 SourceRange MatchingCTypeRange;
1625 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1626 if (MatchingCType.isInvalid()) {
1627 T.skipToEnd();
1628 return;
1629 }
1630
1631 bool LayoutCompatible = false;
1632 bool MustBeNull = false;
1633 while (TryConsumeToken(tok::comma)) {
1634 if (Tok.isNot(tok::identifier)) {
1635 Diag(Tok, diag::err_expected) << tok::identifier;
1636 T.skipToEnd();
1637 return;
1638 }
1639 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1640 if (Flag->isStr("layout_compatible"))
1641 LayoutCompatible = true;
1642 else if (Flag->isStr("must_be_null"))
1643 MustBeNull = true;
1644 else {
1645 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1646 T.skipToEnd();
1647 return;
1648 }
1649 ConsumeToken(); // consume flag
1650 }
1651
1652 if (!T.consumeClose()) {
1653 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1654 ArgumentKind, MatchingCType.get(),
1655 LayoutCompatible, MustBeNull, Syntax);
1656 }
1657
1658 if (EndLoc)
1659 *EndLoc = T.getCloseLocation();
1660}
1661
1662/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1663/// of a C++11 attribute-specifier in a location where an attribute is not
1664/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1665/// situation.
1666///
1667/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1668/// this doesn't appear to actually be an attribute-specifier, and the caller
1669/// should try to parse it.
1670bool Parser::DiagnoseProhibitedCXX11Attribute() {
1671 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1672
1673 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1674 case CAK_NotAttributeSpecifier:
1675 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1676 return false;
1677
1678 case CAK_InvalidAttributeSpecifier:
1679 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1680 return false;
1681
1682 case CAK_AttributeSpecifier:
1683 // Parse and discard the attributes.
1684 SourceLocation BeginLoc = ConsumeBracket();
1685 ConsumeBracket();
1686 SkipUntil(tok::r_square);
1687 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1688 SourceLocation EndLoc = ConsumeBracket();
1689 Diag(BeginLoc, diag::err_attributes_not_allowed)
1690 << SourceRange(BeginLoc, EndLoc);
1691 return true;
1692 }
1693 llvm_unreachable("All cases handled above.");
1694}
1695
1696/// We have found the opening square brackets of a C++11
1697/// attribute-specifier in a location where an attribute is not permitted, but
1698/// we know where the attributes ought to be written. Parse them anyway, and
1699/// provide a fixit moving them to the right place.
1700void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs,
1701 SourceLocation CorrectLocation) {
1702 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1703 Tok.is(tok::kw_alignas));
1704
1705 // Consume the attributes.
1706 SourceLocation Loc = Tok.getLocation();
1707 ParseCXX11Attributes(Attrs);
1708 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1709 // FIXME: use err_attributes_misplaced
1710 Diag(Loc, diag::err_attributes_not_allowed)
1711 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1712 << FixItHint::CreateRemoval(AttrRange);
1713}
1714
1715void Parser::DiagnoseProhibitedAttributes(
1716 const SourceRange &Range, const SourceLocation CorrectLocation) {
1717 if (CorrectLocation.isValid()) {
1718 CharSourceRange AttrRange(Range, true);
1719 Diag(CorrectLocation, diag::err_attributes_misplaced)
1720 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1721 << FixItHint::CreateRemoval(AttrRange);
1722 } else
1723 Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
1724}
1725
1726void Parser::ProhibitCXX11Attributes(ParsedAttributes &Attrs, unsigned DiagID,
1727 bool DiagnoseEmptyAttrs,
1728 bool WarnOnUnknownAttrs) {
1729
1730 if (DiagnoseEmptyAttrs && Attrs.empty() && Attrs.Range.isValid()) {
1731 // An attribute list has been parsed, but it was empty.
1732 // This is the case for [[]].
1733 const auto &LangOpts = getLangOpts();
1734 auto &SM = PP.getSourceManager();
1735 Token FirstLSquare;
1736 Lexer::getRawToken(Attrs.Range.getBegin(), FirstLSquare, SM, LangOpts);
1737
1738 if (FirstLSquare.is(tok::l_square)) {
1739 std::optional<Token> SecondLSquare =
1740 Lexer::findNextToken(FirstLSquare.getLocation(), SM, LangOpts);
1741
1742 if (SecondLSquare && SecondLSquare->is(tok::l_square)) {
1743 // The attribute range starts with [[, but is empty. So this must
1744 // be [[]], which we are supposed to diagnose because
1745 // DiagnoseEmptyAttrs is true.
1746 Diag(Attrs.Range.getBegin(), DiagID) << Attrs.Range;
1747 return;
1748 }
1749 }
1750 }
1751
1752 for (const ParsedAttr &AL : Attrs) {
1753 if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
1754 continue;
1755 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
1756 if (WarnOnUnknownAttrs)
1757 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
1758 << AL << AL.getRange();
1759 } else {
1760 Diag(AL.getLoc(), DiagID) << AL;
1761 AL.setInvalid();
1762 }
1763 }
1764}
1765
1766void Parser::DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs) {
1767 for (const ParsedAttr &PA : Attrs) {
1768 if (PA.isCXX11Attribute() || PA.isC2xAttribute())
1769 Diag(PA.getLoc(), diag::ext_cxx11_attr_placement) << PA << PA.getRange();
1770 }
1771}
1772
1773// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1774// applies to var, not the type Foo.
1775// As an exception to the rule, __declspec(align(...)) before the
1776// class-key affects the type instead of the variable.
1777// Also, Microsoft-style [attributes] seem to affect the type instead of the
1778// variable.
1779// This function moves attributes that should apply to the type off DS to Attrs.
1780void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs,
1781 DeclSpec &DS,
1782 Sema::TagUseKind TUK) {
1783 if (TUK == Sema::TUK_Reference)
1784 return;
1785
1787
1788 for (ParsedAttr &AL : DS.getAttributes()) {
1789 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1790 AL.isDeclspecAttribute()) ||
1791 AL.isMicrosoftAttribute())
1792 ToBeMoved.push_back(&AL);
1793 }
1794
1795 for (ParsedAttr *AL : ToBeMoved) {
1796 DS.getAttributes().remove(AL);
1797 Attrs.addAtEnd(AL);
1798 }
1799}
1800
1801/// ParseDeclaration - Parse a full 'declaration', which consists of
1802/// declaration-specifiers, some number of declarators, and a semicolon.
1803/// 'Context' should be a DeclaratorContext value. This returns the
1804/// location of the semicolon in DeclEnd.
1805///
1806/// declaration: [C99 6.7]
1807/// block-declaration ->
1808/// simple-declaration
1809/// others [FIXME]
1810/// [C++] template-declaration
1811/// [C++] namespace-definition
1812/// [C++] using-directive
1813/// [C++] using-declaration
1814/// [C++11/C11] static_assert-declaration
1815/// others... [FIXME]
1816///
1817Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
1818 SourceLocation &DeclEnd,
1819 ParsedAttributes &DeclAttrs,
1820 ParsedAttributes &DeclSpecAttrs,
1821 SourceLocation *DeclSpecStart) {
1822 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1823 // Must temporarily exit the objective-c container scope for
1824 // parsing c none objective-c decls.
1825 ObjCDeclContextSwitch ObjCDC(*this);
1826
1827 Decl *SingleDecl = nullptr;
1828 switch (Tok.getKind()) {
1829 case tok::kw_template:
1830 case tok::kw_export:
1831 ProhibitAttributes(DeclAttrs);
1832 ProhibitAttributes(DeclSpecAttrs);
1833 SingleDecl =
1834 ParseDeclarationStartingWithTemplate(Context, DeclEnd, DeclAttrs);
1835 break;
1836 case tok::kw_inline:
1837 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1838 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1839 ProhibitAttributes(DeclAttrs);
1840 ProhibitAttributes(DeclSpecAttrs);
1841 SourceLocation InlineLoc = ConsumeToken();
1842 return ParseNamespace(Context, DeclEnd, InlineLoc);
1843 }
1844 return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
1845 true, nullptr, DeclSpecStart);
1846
1847 case tok::kw_cbuffer:
1848 case tok::kw_tbuffer:
1849 SingleDecl = ParseHLSLBuffer(DeclEnd);
1850 break;
1851 case tok::kw_namespace:
1852 ProhibitAttributes(DeclAttrs);
1853 ProhibitAttributes(DeclSpecAttrs);
1854 return ParseNamespace(Context, DeclEnd);
1855 case tok::kw_using: {
1856 ParsedAttributes Attrs(AttrFactory);
1857 takeAndConcatenateAttrs(DeclAttrs, DeclSpecAttrs, Attrs);
1858 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1859 DeclEnd, Attrs);
1860 }
1861 case tok::kw_static_assert:
1862 case tok::kw__Static_assert:
1863 ProhibitAttributes(DeclAttrs);
1864 ProhibitAttributes(DeclSpecAttrs);
1865 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1866 break;
1867 default:
1868 return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
1869 true, nullptr, DeclSpecStart);
1870 }
1871
1872 // This routine returns a DeclGroup, if the thing we parsed only contains a
1873 // single decl, convert it now.
1874 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1875}
1876
1877/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1878/// declaration-specifiers init-declarator-list[opt] ';'
1879/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1880/// init-declarator-list ';'
1881///[C90/C++]init-declarator-list ';' [TODO]
1882/// [OMP] threadprivate-directive
1883/// [OMP] allocate-directive [TODO]
1884///
1885/// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1886/// attribute-specifier-seq[opt] type-specifier-seq declarator
1887///
1888/// If RequireSemi is false, this does not check for a ';' at the end of the
1889/// declaration. If it is true, it checks for and eats it.
1890///
1891/// If FRI is non-null, we might be parsing a for-range-declaration instead
1892/// of a simple-declaration. If we find that we are, we also parse the
1893/// for-range-initializer, and place it here.
1894///
1895/// DeclSpecStart is used when decl-specifiers are parsed before parsing
1896/// the Declaration. The SourceLocation for this Decl is set to
1897/// DeclSpecStart if DeclSpecStart is non-null.
1898Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
1899 DeclaratorContext Context, SourceLocation &DeclEnd,
1900 ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs,
1901 bool RequireSemi, ForRangeInit *FRI, SourceLocation *DeclSpecStart) {
1902 // Need to retain these for diagnostics before we add them to the DeclSepc.
1903 ParsedAttributesView OriginalDeclSpecAttrs;
1904 OriginalDeclSpecAttrs.addAll(DeclSpecAttrs.begin(), DeclSpecAttrs.end());
1905 OriginalDeclSpecAttrs.Range = DeclSpecAttrs.Range;
1906
1907 // Parse the common declaration-specifiers piece.
1908 ParsingDeclSpec DS(*this);
1909 DS.takeAttributesFrom(DeclSpecAttrs);
1910
1911 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1912 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1913
1914 // If we had a free-standing type definition with a missing semicolon, we
1915 // may get this far before the problem becomes obvious.
1916 if (DS.hasTagDefinition() &&
1917 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1918 return nullptr;
1919
1920 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1921 // declaration-specifiers init-declarator-list[opt] ';'
1922 if (Tok.is(tok::semi)) {
1923 ProhibitAttributes(DeclAttrs);
1924 DeclEnd = Tok.getLocation();
1925 if (RequireSemi) ConsumeToken();
1926 RecordDecl *AnonRecord = nullptr;
1927 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1928 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
1929 DS.complete(TheDecl);
1930 if (AnonRecord) {
1931 Decl* decls[] = {AnonRecord, TheDecl};
1932 return Actions.BuildDeclaratorGroup(decls);
1933 }
1934 return Actions.ConvertDeclToDeclGroup(TheDecl);
1935 }
1936
1937 if (DeclSpecStart)
1938 DS.SetRangeStart(*DeclSpecStart);
1939
1940 return ParseDeclGroup(DS, Context, DeclAttrs, &DeclEnd, FRI);
1941}
1942
1943/// Returns true if this might be the start of a declarator, or a common typo
1944/// for a declarator.
1945bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1946 switch (Tok.getKind()) {
1947 case tok::annot_cxxscope:
1948 case tok::annot_template_id:
1949 case tok::caret:
1950 case tok::code_completion:
1951 case tok::coloncolon:
1952 case tok::ellipsis:
1953 case tok::kw___attribute:
1954 case tok::kw_operator:
1955 case tok::l_paren:
1956 case tok::star:
1957 return true;
1958
1959 case tok::amp:
1960 case tok::ampamp:
1961 return getLangOpts().CPlusPlus;
1962
1963 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1964 return Context == DeclaratorContext::Member && getLangOpts().CPlusPlus11 &&
1965 NextToken().is(tok::l_square);
1966
1967 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1968 return Context == DeclaratorContext::Member || getLangOpts().CPlusPlus;
1969
1970 case tok::identifier:
1971 switch (NextToken().getKind()) {
1972 case tok::code_completion:
1973 case tok::coloncolon:
1974 case tok::comma:
1975 case tok::equal:
1976 case tok::equalequal: // Might be a typo for '='.
1977 case tok::kw_alignas:
1978 case tok::kw_asm:
1979 case tok::kw___attribute:
1980 case tok::l_brace:
1981 case tok::l_paren:
1982 case tok::l_square:
1983 case tok::less:
1984 case tok::r_brace:
1985 case tok::r_paren:
1986 case tok::r_square:
1987 case tok::semi:
1988 return true;
1989
1990 case tok::colon:
1991 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1992 // and in block scope it's probably a label. Inside a class definition,
1993 // this is a bit-field.
1994 return Context == DeclaratorContext::Member ||
1995 (getLangOpts().CPlusPlus && Context == DeclaratorContext::File);
1996
1997 case tok::identifier: // Possible virt-specifier.
1998 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1999
2000 default:
2001 return false;
2002 }
2003
2004 default:
2005 return false;
2006 }
2007}
2008
2009/// Skip until we reach something which seems like a sensible place to pick
2010/// up parsing after a malformed declaration. This will sometimes stop sooner
2011/// than SkipUntil(tok::r_brace) would, but will never stop later.
2013 while (true) {
2014 switch (Tok.getKind()) {
2015 case tok::l_brace:
2016 // Skip until matching }, then stop. We've probably skipped over
2017 // a malformed class or function definition or similar.
2018 ConsumeBrace();
2019 SkipUntil(tok::r_brace);
2020 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
2021 // This declaration isn't over yet. Keep skipping.
2022 continue;
2023 }
2024 TryConsumeToken(tok::semi);
2025 return;
2026
2027 case tok::l_square:
2028 ConsumeBracket();
2029 SkipUntil(tok::r_square);
2030 continue;
2031
2032 case tok::l_paren:
2033 ConsumeParen();
2034 SkipUntil(tok::r_paren);
2035 continue;
2036
2037 case tok::r_brace:
2038 return;
2039
2040 case tok::semi:
2041 ConsumeToken();
2042 return;
2043
2044 case tok::kw_inline:
2045 // 'inline namespace' at the start of a line is almost certainly
2046 // a good place to pick back up parsing, except in an Objective-C
2047 // @interface context.
2048 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
2049 (!ParsingInObjCContainer || CurParsedObjCImpl))
2050 return;
2051 break;
2052
2053 case tok::kw_namespace:
2054 // 'namespace' at the start of a line is almost certainly a good
2055 // place to pick back up parsing, except in an Objective-C
2056 // @interface context.
2057 if (Tok.isAtStartOfLine() &&
2058 (!ParsingInObjCContainer || CurParsedObjCImpl))
2059 return;
2060 break;
2061
2062 case tok::at:
2063 // @end is very much like } in Objective-C contexts.
2064 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
2065 ParsingInObjCContainer)
2066 return;
2067 break;
2068
2069 case tok::minus:
2070 case tok::plus:
2071 // - and + probably start new method declarations in Objective-C contexts.
2072 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
2073 return;
2074 break;
2075
2076 case tok::eof:
2077 case tok::annot_module_begin:
2078 case tok::annot_module_end:
2079 case tok::annot_module_include:
2080 return;
2081
2082 default:
2083 break;
2084 }
2085
2087 }
2088}
2089
2090/// ParseDeclGroup - Having concluded that this is either a function
2091/// definition or a group of object declarations, actually parse the
2092/// result.
2093Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
2094 DeclaratorContext Context,
2095 ParsedAttributes &Attrs,
2096 SourceLocation *DeclEnd,
2097 ForRangeInit *FRI) {
2098 // Parse the first declarator.
2099 // Consume all of the attributes from `Attrs` by moving them to our own local
2100 // list. This ensures that we will not attempt to interpret them as statement
2101 // attributes higher up the callchain.
2102 ParsedAttributes LocalAttrs(AttrFactory);
2103 LocalAttrs.takeAllFrom(Attrs);
2104 ParsingDeclarator D(*this, DS, LocalAttrs, Context);
2105 ParseDeclarator(D);
2106
2107 // Bail out if the first declarator didn't seem well-formed.
2108 if (!D.hasName() && !D.mayOmitIdentifier()) {
2110 return nullptr;
2111 }
2112
2113 if (getLangOpts().HLSL)
2114 MaybeParseHLSLSemantics(D);
2115
2116 if (Tok.is(tok::kw_requires))
2117 ParseTrailingRequiresClause(D);
2118
2119 // Save late-parsed attributes for now; they need to be parsed in the
2120 // appropriate function scope after the function Decl has been constructed.
2121 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
2122 LateParsedAttrList LateParsedAttrs(true);
2123 if (D.isFunctionDeclarator()) {
2124 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2125
2126 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2127 // attribute. If we find the keyword here, tell the user to put it
2128 // at the start instead.
2129 if (Tok.is(tok::kw__Noreturn)) {
2131 const char *PrevSpec;
2132 unsigned DiagID;
2133
2134 // We can offer a fixit if it's valid to mark this function as _Noreturn
2135 // and we don't have any other declarators in this declaration.
2136 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2137 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2138 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2139
2140 Diag(Loc, diag::err_c11_noreturn_misplaced)
2141 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
2142 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2143 : FixItHint());
2144 }
2145
2146 // Check to see if we have a function *definition* which must have a body.
2147 if (Tok.is(tok::equal) && NextToken().is(tok::code_completion)) {
2148 cutOffParsing();
2150 return nullptr;
2151 }
2152 // We're at the point where the parsing of function declarator is finished.
2153 //
2154 // A common error is that users accidently add a virtual specifier
2155 // (e.g. override) in an out-line method definition.
2156 // We attempt to recover by stripping all these specifiers coming after
2157 // the declarator.
2158 while (auto Specifier = isCXX11VirtSpecifier()) {
2159 Diag(Tok, diag::err_virt_specifier_outside_class)
2162 ConsumeToken();
2163 }
2164 // Look at the next token to make sure that this isn't a function
2165 // declaration. We have to check this because __attribute__ might be the
2166 // start of a function definition in GCC-extended K&R C.
2167 if (!isDeclarationAfterDeclarator()) {
2168
2169 // Function definitions are only allowed at file scope and in C++ classes.
2170 // The C++ inline method definition case is handled elsewhere, so we only
2171 // need to handle the file scope definition case.
2172 if (Context == DeclaratorContext::File) {
2173 if (isStartOfFunctionDefinition(D)) {
2175 Diag(Tok, diag::err_function_declared_typedef);
2176
2177 // Recover by treating the 'typedef' as spurious.
2179 }
2180
2181 Decl *TheDecl = ParseFunctionDefinition(D, ParsedTemplateInfo(),
2182 &LateParsedAttrs);
2183 return Actions.ConvertDeclToDeclGroup(TheDecl);
2184 }
2185
2186 if (isDeclarationSpecifier(ImplicitTypenameContext::No)) {
2187 // If there is an invalid declaration specifier right after the
2188 // function prototype, then we must be in a missing semicolon case
2189 // where this isn't actually a body. Just fall through into the code
2190 // that handles it as a prototype, and let the top-level code handle
2191 // the erroneous declspec where it would otherwise expect a comma or
2192 // semicolon.
2193 } else {
2194 Diag(Tok, diag::err_expected_fn_body);
2195 SkipUntil(tok::semi);
2196 return nullptr;
2197 }
2198 } else {
2199 if (Tok.is(tok::l_brace)) {
2200 Diag(Tok, diag::err_function_definition_not_allowed);
2202 return nullptr;
2203 }
2204 }
2205 }
2206 }
2207
2208 if (ParseAsmAttributesAfterDeclarator(D))
2209 return nullptr;
2210
2211 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2212 // must parse and analyze the for-range-initializer before the declaration is
2213 // analyzed.
2214 //
2215 // Handle the Objective-C for-in loop variable similarly, although we
2216 // don't need to parse the container in advance.
2217 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2218 bool IsForRangeLoop = false;
2219 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2220 IsForRangeLoop = true;
2221 if (getLangOpts().OpenMP)
2222 Actions.startOpenMPCXXRangeFor();
2223 if (Tok.is(tok::l_brace))
2224 FRI->RangeExpr = ParseBraceInitializer();
2225 else
2226 FRI->RangeExpr = ParseExpression();
2227 }
2228
2229 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2230 if (IsForRangeLoop) {
2231 Actions.ActOnCXXForRangeDecl(ThisDecl);
2232 } else {
2233 // Obj-C for loop
2234 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2235 VD->setObjCForDecl(true);
2236 }
2237 Actions.FinalizeDeclaration(ThisDecl);
2238 D.complete(ThisDecl);
2239 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2240 }
2241
2242 SmallVector<Decl *, 8> DeclsInGroup;
2243 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2244 D, ParsedTemplateInfo(), FRI);
2245 if (LateParsedAttrs.size() > 0)
2246 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2247 D.complete(FirstDecl);
2248 if (FirstDecl)
2249 DeclsInGroup.push_back(FirstDecl);
2250
2251 bool ExpectSemi = Context != DeclaratorContext::ForInit;
2252
2253 // If we don't have a comma, it is either the end of the list (a ';') or an
2254 // error, bail out.
2255 SourceLocation CommaLoc;
2256 while (TryConsumeToken(tok::comma, CommaLoc)) {
2257 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2258 // This comma was followed by a line-break and something which can't be
2259 // the start of a declarator. The comma was probably a typo for a
2260 // semicolon.
2261 Diag(CommaLoc, diag::err_expected_semi_declaration)
2262 << FixItHint::CreateReplacement(CommaLoc, ";");
2263 ExpectSemi = false;
2264 break;
2265 }
2266
2267 // Parse the next declarator.
2268 D.clear();
2269 D.setCommaLoc(CommaLoc);
2270
2271 // Accept attributes in an init-declarator. In the first declarator in a
2272 // declaration, these would be part of the declspec. In subsequent
2273 // declarators, they become part of the declarator itself, so that they
2274 // don't apply to declarators after *this* one. Examples:
2275 // short __attribute__((common)) var; -> declspec
2276 // short var __attribute__((common)); -> declarator
2277 // short x, __attribute__((common)) var; -> declarator
2278 MaybeParseGNUAttributes(D);
2279
2280 // MSVC parses but ignores qualifiers after the comma as an extension.
2281 if (getLangOpts().MicrosoftExt)
2282 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2283
2284 ParseDeclarator(D);
2285
2286 if (getLangOpts().HLSL)
2287 MaybeParseHLSLSemantics(D);
2288
2289 if (!D.isInvalidType()) {
2290 // C++2a [dcl.decl]p1
2291 // init-declarator:
2292 // declarator initializer[opt]
2293 // declarator requires-clause
2294 if (Tok.is(tok::kw_requires))
2295 ParseTrailingRequiresClause(D);
2296 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2297 D.complete(ThisDecl);
2298 if (ThisDecl)
2299 DeclsInGroup.push_back(ThisDecl);
2300 }
2301 }
2302
2303 if (DeclEnd)
2304 *DeclEnd = Tok.getLocation();
2305
2306 if (ExpectSemi && ExpectAndConsumeSemi(
2307 Context == DeclaratorContext::File
2308 ? diag::err_invalid_token_after_toplevel_declarator
2309 : diag::err_expected_semi_declaration)) {
2310 // Okay, there was no semicolon and one was expected. If we see a
2311 // declaration specifier, just assume it was missing and continue parsing.
2312 // Otherwise things are very confused and we skip to recover.
2313 if (!isDeclarationSpecifier(ImplicitTypenameContext::No)) {
2314 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2315 TryConsumeToken(tok::semi);
2316 }
2317 }
2318
2319 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2320}
2321
2322/// Parse an optional simple-asm-expr and attributes, and attach them to a
2323/// declarator. Returns true on an error.
2324bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2325 // If a simple-asm-expr is present, parse it.
2326 if (Tok.is(tok::kw_asm)) {
2327 SourceLocation Loc;
2328 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2329 if (AsmLabel.isInvalid()) {
2330 SkipUntil(tok::semi, StopBeforeMatch);
2331 return true;
2332 }
2333
2334 D.setAsmLabel(AsmLabel.get());
2335 D.SetRangeEnd(Loc);
2336 }
2337
2338 MaybeParseGNUAttributes(D);
2339 return false;
2340}
2341
2342/// Parse 'declaration' after parsing 'declaration-specifiers
2343/// declarator'. This method parses the remainder of the declaration
2344/// (including any attributes or initializer, among other things) and
2345/// finalizes the declaration.
2346///
2347/// init-declarator: [C99 6.7]
2348/// declarator
2349/// declarator '=' initializer
2350/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2351/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2352/// [C++] declarator initializer[opt]
2353///
2354/// [C++] initializer:
2355/// [C++] '=' initializer-clause
2356/// [C++] '(' expression-list ')'
2357/// [C++0x] '=' 'default' [TODO]
2358/// [C++0x] '=' 'delete'
2359/// [C++0x] braced-init-list
2360///
2361/// According to the standard grammar, =default and =delete are function
2362/// definitions, but that definitely doesn't fit with the parser here.
2363///
2364Decl *Parser::ParseDeclarationAfterDeclarator(
2365 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2366 if (ParseAsmAttributesAfterDeclarator(D))
2367 return nullptr;
2368
2369 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2370}
2371
2372Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2373 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2374 // RAII type used to track whether we're inside an initializer.
2375 struct InitializerScopeRAII {
2376 Parser &P;
2377 Declarator &D;
2378 Decl *ThisDecl;
2379
2380 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2381 : P(P), D(D), ThisDecl(ThisDecl) {
2382 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2383 Scope *S = nullptr;
2384 if (D.getCXXScopeSpec().isSet()) {
2385 P.EnterScope(0);
2386 S = P.getCurScope();
2387 }
2388 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2389 }
2390 }
2391 ~InitializerScopeRAII() { pop(); }
2392 void pop() {
2393 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2394 Scope *S = nullptr;
2395 if (D.getCXXScopeSpec().isSet())
2396 S = P.getCurScope();
2397 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2398 if (S)
2399 P.ExitScope();
2400 }
2401 ThisDecl = nullptr;
2402 }
2403 };
2404
2405 enum class InitKind { Uninitialized, Equal, CXXDirect, CXXBraced };
2406 InitKind TheInitKind;
2407 // If a '==' or '+=' is found, suggest a fixit to '='.
2408 if (isTokenEqualOrEqualTypo())
2409 TheInitKind = InitKind::Equal;
2410 else if (Tok.is(tok::l_paren))
2411 TheInitKind = InitKind::CXXDirect;
2412 else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2413 (!CurParsedObjCImpl || !D.isFunctionDeclarator()))
2414 TheInitKind = InitKind::CXXBraced;
2415 else
2416 TheInitKind = InitKind::Uninitialized;
2417 if (TheInitKind != InitKind::Uninitialized)
2419
2420 // Inform Sema that we just parsed this declarator.
2421 Decl *ThisDecl = nullptr;
2422 Decl *OuterDecl = nullptr;
2423 switch (TemplateInfo.Kind) {
2424 case ParsedTemplateInfo::NonTemplate:
2425 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2426 break;
2427
2428 case ParsedTemplateInfo::Template:
2429 case ParsedTemplateInfo::ExplicitSpecialization: {
2430 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2431 *TemplateInfo.TemplateParams,
2432 D);
2433 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) {
2434 // Re-direct this decl to refer to the templated decl so that we can
2435 // initialize it.
2436 ThisDecl = VT->getTemplatedDecl();
2437 OuterDecl = VT;
2438 }
2439 break;
2440 }
2441 case ParsedTemplateInfo::ExplicitInstantiation: {
2442 if (Tok.is(tok::semi)) {
2443 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2444 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2445 if (ThisRes.isInvalid()) {
2446 SkipUntil(tok::semi, StopBeforeMatch);
2447 return nullptr;
2448 }
2449 ThisDecl = ThisRes.get();
2450 } else {
2451 // FIXME: This check should be for a variable template instantiation only.
2452
2453 // Check that this is a valid instantiation
2455 // If the declarator-id is not a template-id, issue a diagnostic and
2456 // recover by ignoring the 'template' keyword.
2457 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2458 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2459 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2460 } else {
2461 SourceLocation LAngleLoc =
2462 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2464 diag::err_explicit_instantiation_with_definition)
2465 << SourceRange(TemplateInfo.TemplateLoc)
2466 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2467
2468 // Recover as if it were an explicit specialization.
2469 TemplateParameterLists FakedParamLists;
2470 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2471 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc,
2472 std::nullopt, LAngleLoc, nullptr));
2473
2474 ThisDecl =
2475 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2476 }
2477 }
2478 break;
2479 }
2480 }
2481
2482 switch (TheInitKind) {
2483 // Parse declarator '=' initializer.
2484 case InitKind::Equal: {
2485 SourceLocation EqualLoc = ConsumeToken();
2486
2487 if (Tok.is(tok::kw_delete)) {
2488 if (D.isFunctionDeclarator())
2489 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2490 << 1 /* delete */;
2491 else
2492 Diag(ConsumeToken(), diag::err_deleted_non_function);
2493 } else if (Tok.is(tok::kw_default)) {
2494 if (D.isFunctionDeclarator())
2495 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2496 << 0 /* default */;
2497 else
2498 Diag(ConsumeToken(), diag::err_default_special_members)
2499 << getLangOpts().CPlusPlus20;
2500 } else {
2501 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2502
2503 if (Tok.is(tok::code_completion)) {
2504 cutOffParsing();
2505 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2506 Actions.FinalizeDeclaration(ThisDecl);
2507 return nullptr;
2508 }
2509
2510 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2511 ExprResult Init = ParseInitializer();
2512
2513 // If this is the only decl in (possibly) range based for statement,
2514 // our best guess is that the user meant ':' instead of '='.
2515 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2516 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2517 << FixItHint::CreateReplacement(EqualLoc, ":");
2518 // We are trying to stop parser from looking for ';' in this for
2519 // statement, therefore preventing spurious errors to be issued.
2520 FRI->ColonLoc = EqualLoc;
2521 Init = ExprError();
2522 FRI->RangeExpr = Init;
2523 }
2524
2525 InitScope.pop();
2526
2527 if (Init.isInvalid()) {
2529 StopTokens.push_back(tok::comma);
2532 StopTokens.push_back(tok::r_paren);
2533 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2534 Actions.ActOnInitializerError(ThisDecl);
2535 } else
2536 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2537 /*DirectInit=*/false);
2538 }
2539 break;
2540 }
2541 case InitKind::CXXDirect: {
2542 // Parse C++ direct initializer: '(' expression-list ')'
2543 BalancedDelimiterTracker T(*this, tok::l_paren);
2544 T.consumeOpen();
2545
2546 ExprVector Exprs;
2547
2548 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2549
2550 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2551 auto RunSignatureHelp = [&]() {
2552 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2553 ThisVarDecl->getType()->getCanonicalTypeInternal(),
2554 ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2555 /*Braced=*/false);
2556 CalledSignatureHelp = true;
2557 return PreferredType;
2558 };
2559 auto SetPreferredType = [&] {
2560 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2561 };
2562
2563 llvm::function_ref<void()> ExpressionStarts;
2564 if (ThisVarDecl) {
2565 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2566 // VarDecl. This is an error and it is reported in a call to
2567 // Actions.ActOnInitializerError(). However, we call
2568 // ProduceConstructorSignatureHelp only on VarDecls.
2569 ExpressionStarts = SetPreferredType;
2570 }
2571 if (ParseExpressionList(Exprs, ExpressionStarts)) {
2572 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2574 ThisVarDecl->getType()->getCanonicalTypeInternal(),
2575 ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2576 /*Braced=*/false);
2577 CalledSignatureHelp = true;
2578 }
2579 Actions.ActOnInitializerError(ThisDecl);
2580 SkipUntil(tok::r_paren, StopAtSemi);
2581 } else {
2582 // Match the ')'.
2583 T.consumeClose();
2584 InitScope.pop();
2585
2586 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2587 T.getCloseLocation(),
2588 Exprs);
2589 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2590 /*DirectInit=*/true);
2591 }
2592 break;
2593 }
2594 case InitKind::CXXBraced: {
2595 // Parse C++0x braced-init-list.
2596 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2597
2598 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2599
2600 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2601 ExprResult Init(ParseBraceInitializer());
2602
2603 InitScope.pop();
2604
2605 if (Init.isInvalid()) {
2606 Actions.ActOnInitializerError(ThisDecl);
2607 } else
2608 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2609 break;
2610 }
2611 case InitKind::Uninitialized: {
2612 Actions.ActOnUninitializedDecl(ThisDecl);
2613 break;
2614 }
2615 }
2616
2617 Actions.FinalizeDeclaration(ThisDecl);
2618 return OuterDecl ? OuterDecl : ThisDecl;
2619}
2620
2621/// ParseSpecifierQualifierList
2622/// specifier-qualifier-list:
2623/// type-specifier specifier-qualifier-list[opt]
2624/// type-qualifier specifier-qualifier-list[opt]
2625/// [GNU] attributes specifier-qualifier-list[opt]
2626///
2627void Parser::ParseSpecifierQualifierList(
2628 DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename,
2629 AccessSpecifier AS, DeclSpecContext DSC) {
2630 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2631 /// parse declaration-specifiers and complain about extra stuff.
2632 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2633 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC, nullptr,
2634 AllowImplicitTypename);
2635
2636 // Validate declspec for type-name.
2637 unsigned Specs = DS.getParsedSpecifiers();
2638 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2639 Diag(Tok, diag::err_expected_type);
2640 DS.SetTypeSpecError();
2641 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2642 Diag(Tok, diag::err_typename_requires_specqual);
2643 if (!DS.hasTypeSpecifier())
2644 DS.SetTypeSpecError();
2645 }
2646
2647 // Issue diagnostic and remove storage class if present.
2650 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2651 else
2653 diag::err_typename_invalid_storageclass);
2655 }
2656
2657 // Issue diagnostic and remove function specifier if present.
2658 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2659 if (DS.isInlineSpecified())
2660 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2661 if (DS.isVirtualSpecified())
2662 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2663 if (DS.hasExplicitSpecifier())
2664 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2665 if (DS.isNoreturnSpecified())
2666 Diag(DS.getNoreturnSpecLoc(), diag::err_typename_invalid_functionspec);
2667 DS.ClearFunctionSpecs();
2668 }
2669
2670 // Issue diagnostic and remove constexpr specifier if present.
2671 if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2672 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2673 << static_cast<int>(DS.getConstexprSpecifier());
2674 DS.ClearConstexprSpec();
2675 }
2676}
2677
2678/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2679/// specified token is valid after the identifier in a declarator which
2680/// immediately follows the declspec. For example, these things are valid:
2681///
2682/// int x [ 4]; // direct-declarator
2683/// int x ( int y); // direct-declarator
2684/// int(int x ) // direct-declarator
2685/// int x ; // simple-declaration
2686/// int x = 17; // init-declarator-list
2687/// int x , y; // init-declarator-list
2688/// int x __asm__ ("foo"); // init-declarator-list
2689/// int x : 4; // struct-declarator
2690/// int x { 5}; // C++'0x unified initializers
2691///
2692/// This is not, because 'x' does not immediately follow the declspec (though
2693/// ')' happens to be valid anyway).
2694/// int (x)
2695///
2697 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2698 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2699 tok::colon);
2700}
2701
2702/// ParseImplicitInt - This method is called when we have an non-typename
2703/// identifier in a declspec (which normally terminates the decl spec) when
2704/// the declspec has no type specifier. In this case, the declspec is either
2705/// malformed or is "implicit int" (in K&R and C89).
2706///
2707/// This method handles diagnosing this prettily and returns false if the
2708/// declspec is done being processed. If it recovers and thinks there may be
2709/// other pieces of declspec after it, it returns true.
2710///
2711bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2712 const ParsedTemplateInfo &TemplateInfo,
2713 AccessSpecifier AS, DeclSpecContext DSC,
2714 ParsedAttributes &Attrs) {
2715 assert(Tok.is(tok::identifier) && "should have identifier");
2716
2717 SourceLocation Loc = Tok.getLocation();
2718 // If we see an identifier that is not a type name, we normally would
2719 // parse it as the identifier being declared. However, when a typename
2720 // is typo'd or the definition is not included, this will incorrectly
2721 // parse the typename as the identifier name and fall over misparsing
2722 // later parts of the diagnostic.
2723 //
2724 // As such, we try to do some look-ahead in cases where this would
2725 // otherwise be an "implicit-int" case to see if this is invalid. For
2726 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2727 // an identifier with implicit int, we'd get a parse error because the
2728 // next token is obviously invalid for a type. Parse these as a case
2729 // with an invalid type specifier.
2730 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2731
2732 // Since we know that this either implicit int (which is rare) or an
2733 // error, do lookahead to try to do better recovery. This never applies
2734 // within a type specifier. Outside of C++, we allow this even if the
2735 // language doesn't "officially" support implicit int -- we support
2736 // implicit int as an extension in some language modes.
2737 if (!isTypeSpecifier(DSC) && getLangOpts().isImplicitIntAllowed() &&
2739 // If this token is valid for implicit int, e.g. "static x = 4", then
2740 // we just avoid eating the identifier, so it will be parsed as the
2741 // identifier in the declarator.
2742 return false;
2743 }
2744
2745 // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2746 // for incomplete declarations such as `pipe p`.
2747 if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2748 return false;
2749
2750 if (getLangOpts().CPlusPlus &&
2752 // Don't require a type specifier if we have the 'auto' storage class
2753 // specifier in C++98 -- we'll promote it to a type specifier.
2754 if (SS)
2755 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2756 return false;
2757 }
2758
2759 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2760 getLangOpts().MSVCCompat) {
2761 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2762 // Give Sema a chance to recover if we are in a template with dependent base
2763 // classes.
2764 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2765 *Tok.getIdentifierInfo(), Tok.getLocation(),
2766 DSC == DeclSpecContext::DSC_template_type_arg)) {
2767 const char *PrevSpec;
2768 unsigned DiagID;
2769 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2770 Actions.getASTContext().getPrintingPolicy());
2771 DS.SetRangeEnd(Tok.getLocation());
2772 ConsumeToken();
2773 return false;
2774 }
2775 }
2776
2777 // Otherwise, if we don't consume this token, we are going to emit an
2778 // error anyway. Try to recover from various common problems. Check
2779 // to see if this was a reference to a tag name without a tag specified.
2780 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2781 //
2782 // C++ doesn't need this, and isTagName doesn't take SS.
2783 if (SS == nullptr) {
2784 const char *TagName = nullptr, *FixitTagName = nullptr;
2785 tok::TokenKind TagKind = tok::unknown;
2786
2787 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2788 default: break;
2789 case DeclSpec::TST_enum:
2790 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2792 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2794 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2796 TagName="__interface"; FixitTagName = "__interface ";
2797 TagKind=tok::kw___interface;break;
2799 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2800 }
2801
2802 if (TagName) {
2803 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2804 LookupResult R(Actions, TokenName, SourceLocation(),
2806
2807 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2808 << TokenName << TagName << getLangOpts().CPlusPlus
2809 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2810
2811 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2812 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2813 I != IEnd; ++I)
2814 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2815 << TokenName << TagName;
2816 }
2817
2818 // Parse this as a tag as if the missing tag were present.
2819 if (TagKind == tok::kw_enum)
2820 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2821 DeclSpecContext::DSC_normal);
2822 else
2823 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2824 /*EnteringContext*/ false,
2825 DeclSpecContext::DSC_normal, Attrs);
2826 return true;
2827 }
2828 }
2829
2830 // Determine whether this identifier could plausibly be the name of something
2831 // being declared (with a missing type).
2832 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2833 DSC == DeclSpecContext::DSC_class)) {
2834 // Look ahead to the next token to try to figure out what this declaration
2835 // was supposed to be.
2836 switch (NextToken().getKind()) {
2837 case tok::l_paren: {
2838 // static x(4); // 'x' is not a type
2839 // x(int n); // 'x' is not a type
2840 // x (*p)[]; // 'x' is a type
2841 //
2842 // Since we're in an error case, we can afford to perform a tentative
2843 // parse to determine which case we're in.
2844 TentativeParsingAction PA(*this);
2845 ConsumeToken();
2846 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2847 PA.Revert();
2848
2849 if (TPR != TPResult::False) {
2850 // The identifier is followed by a parenthesized declarator.
2851 // It's supposed to be a type.
2852 break;
2853 }
2854
2855 // If we're in a context where we could be declaring a constructor,
2856 // check whether this is a constructor declaration with a bogus name.
2857 if (DSC == DeclSpecContext::DSC_class ||
2858 (DSC == DeclSpecContext::DSC_top_level && SS)) {
2860 if (Actions.isCurrentClassNameTypo(II, SS)) {
2861 Diag(Loc, diag::err_constructor_bad_name)
2862 << Tok.getIdentifierInfo() << II
2864 Tok.setIdentifierInfo(II);
2865 }
2866 }
2867 // Fall through.
2868 [[fallthrough]];
2869 }
2870 case tok::comma:
2871 case tok::equal:
2872 case tok::kw_asm:
2873 case tok::l_brace:
2874 case tok::l_square:
2875 case tok::semi:
2876 // This looks like a variable or function declaration. The type is
2877 // probably missing. We're done parsing decl-specifiers.
2878 // But only if we are not in a function prototype scope.
2879 if (getCurScope()->isFunctionPrototypeScope())
2880 break;
2881 if (SS)
2882 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2883 return false;
2884
2885 default:
2886 // This is probably supposed to be a type. This includes cases like:
2887 // int f(itn);
2888 // struct S { unsigned : 4; };
2889 break;
2890 }
2891 }
2892
2893 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2894 // and attempt to recover.
2895 ParsedType T;
2897 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2898 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2899 IsTemplateName);
2900 if (T) {
2901 // The action has suggested that the type T could be used. Set that as
2902 // the type in the declaration specifiers, consume the would-be type
2903 // name token, and we're done.
2904 const char *PrevSpec;
2905 unsigned DiagID;
2906 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2907 Actions.getASTContext().getPrintingPolicy());
2908 DS.SetRangeEnd(Tok.getLocation());
2909 ConsumeToken();
2910 // There may be other declaration specifiers after this.
2911 return true;
2912 } else if (II != Tok.getIdentifierInfo()) {
2913 // If no type was suggested, the correction is to a keyword
2914 Tok.setKind(II->getTokenID());
2915 // There may be other declaration specifiers after this.
2916 return true;
2917 }
2918
2919 // Otherwise, the action had no suggestion for us. Mark this as an error.
2920 DS.SetTypeSpecError();
2921 DS.SetRangeEnd(Tok.getLocation());
2922 ConsumeToken();
2923
2924 // Eat any following template arguments.
2925 if (IsTemplateName) {
2926 SourceLocation LAngle, RAngle;
2927 TemplateArgList Args;
2928 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2929 }
2930
2931 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2932 // avoid rippling error messages on subsequent uses of the same type,
2933 // could be useful if #include was forgotten.
2934 return true;
2935}
2936
2937/// Determine the declaration specifier context from the declarator
2938/// context.
2939///
2940/// \param Context the declarator context, which is one of the
2941/// DeclaratorContext enumerator values.
2942Parser::DeclSpecContext
2943Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2944 switch (Context) {
2946 return DeclSpecContext::DSC_class;
2948 return DeclSpecContext::DSC_top_level;
2950 return DeclSpecContext::DSC_template_param;
2952 return DeclSpecContext::DSC_template_arg;
2954 return DeclSpecContext::DSC_template_type_arg;
2957 return DeclSpecContext::DSC_trailing;
2960 return DeclSpecContext::DSC_alias_declaration;
2962 return DeclSpecContext::DSC_association;
2964 return DeclSpecContext::DSC_type_specifier;
2966 return DeclSpecContext::DSC_condition;
2968 return DeclSpecContext::DSC_conv_operator;
2984 return DeclSpecContext::DSC_normal;
2985 }
2986
2987 llvm_unreachable("Missing DeclaratorContext case");
2988}
2989
2990/// ParseAlignArgument - Parse the argument to an alignment-specifier.
2991///
2992/// FIXME: Simply returns an alignof() expression if the argument is a
2993/// type. Ideally, the type should be propagated directly into Sema.
2994///
2995/// [C11] type-id
2996/// [C11] constant-expression
2997/// [C++0x] type-id ...[opt]
2998/// [C++0x] assignment-expression ...[opt]
2999ExprResult Parser::ParseAlignArgument(SourceLocation Start,
3000 SourceLocation &EllipsisLoc) {
3001 ExprResult ER;
3002 if (isTypeIdInParens()) {
3004 ParsedType Ty = ParseTypeName().get();
3005 SourceRange TypeRange(Start, Tok.getLocation());
3006 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
3007 Ty.getAsOpaquePtr(), TypeRange);
3008 } else
3010
3012 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3013
3014 return ER;
3015}
3016
3017/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
3018/// attribute to Attrs.
3019///
3020/// alignment-specifier:
3021/// [C11] '_Alignas' '(' type-id ')'
3022/// [C11] '_Alignas' '(' constant-expression ')'
3023/// [C++11] 'alignas' '(' type-id ...[opt] ')'
3024/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
3025void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
3026 SourceLocation *EndLoc) {
3027 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
3028 "Not an alignment-specifier!");
3029
3030 IdentifierInfo *KWName = Tok.getIdentifierInfo();
3031 SourceLocation KWLoc = ConsumeToken();
3032
3033 BalancedDelimiterTracker T(*this, tok::l_paren);
3034 if (T.expectAndConsume())
3035 return;
3036
3037 SourceLocation EllipsisLoc;
3038 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
3039 if (ArgExpr.isInvalid()) {
3040 T.skipToEnd();
3041 return;
3042 }
3043
3044 T.consumeClose();
3045 if (EndLoc)
3046 *EndLoc = T.getCloseLocation();
3047
3048 ArgsVector ArgExprs;
3049 ArgExprs.push_back(ArgExpr.get());
3050 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
3051 ParsedAttr::AS_Keyword, EllipsisLoc);
3052}
3053
3054ExprResult Parser::ParseExtIntegerArgument() {
3055 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
3056 "Not an extended int type");
3057 ConsumeToken();
3058
3059 BalancedDelimiterTracker T(*this, tok::l_paren);
3060 if (T.expectAndConsume())
3061 return ExprError();
3062
3064 if (ER.isInvalid()) {
3065 T.skipToEnd();
3066 return ExprError();
3067 }
3068
3069 if(T.consumeClose())
3070 return ExprError();
3071 return ER;
3072}
3073
3074/// Determine whether we're looking at something that might be a declarator
3075/// in a simple-declaration. If it can't possibly be a declarator, maybe
3076/// diagnose a missing semicolon after a prior tag definition in the decl
3077/// specifier.
3078///
3079/// \return \c true if an error occurred and this can't be any kind of
3080/// declaration.
3081bool
3082Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
3083 DeclSpecContext DSContext,
3084 LateParsedAttrList *LateAttrs) {
3085 assert(DS.hasTagDefinition() && "shouldn't call this");
3086
3087 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3088 DSContext == DeclSpecContext::DSC_top_level);
3089
3090 if (getLangOpts().CPlusPlus &&
3091 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
3092 tok::annot_template_id) &&
3093 TryAnnotateCXXScopeToken(EnteringContext)) {
3095 return true;
3096 }
3097
3098 bool HasScope = Tok.is(tok::annot_cxxscope);
3099 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
3100 Token AfterScope = HasScope ? NextToken() : Tok;
3101
3102 // Determine whether the following tokens could possibly be a
3103 // declarator.
3104 bool MightBeDeclarator = true;
3105 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
3106 // A declarator-id can't start with 'typename'.
3107 MightBeDeclarator = false;
3108 } else if (AfterScope.is(tok::annot_template_id)) {
3109 // If we have a type expressed as a template-id, this cannot be a
3110 // declarator-id (such a type cannot be redeclared in a simple-declaration).
3111 TemplateIdAnnotation *Annot =
3112 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
3113 if (Annot->Kind == TNK_Type_template)
3114 MightBeDeclarator = false;
3115 } else if (AfterScope.is(tok::identifier)) {
3116 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
3117
3118 // These tokens cannot come after the declarator-id in a
3119 // simple-declaration, and are likely to come after a type-specifier.
3120 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
3121 tok::annot_cxxscope, tok::coloncolon)) {
3122 // Missing a semicolon.
3123 MightBeDeclarator = false;
3124 } else if (HasScope) {
3125 // If the declarator-id has a scope specifier, it must redeclare a
3126 // previously-declared entity. If that's a type (and this is not a
3127 // typedef), that's an error.
3128 CXXScopeSpec SS;
3130 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3131 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
3132 Sema::NameClassification Classification = Actions.ClassifyName(
3133 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
3134 /*CCC=*/nullptr);
3135 switch (Classification.getKind()) {
3136 case Sema::NC_Error:
3138 return true;
3139
3140 case Sema::NC_Keyword:
3141 llvm_unreachable("typo correction is not possible here");
3142
3143 case Sema::NC_Type:
3147 // Not a previously-declared non-type entity.
3148 MightBeDeclarator = false;
3149 break;
3150
3151 case Sema::NC_Unknown:
3152 case Sema::NC_NonType:
3157 case Sema::NC_Concept:
3158 // Might be a redeclaration of a prior entity.
3159 break;
3160 }
3161 }
3162 }
3163
3164 if (MightBeDeclarator)
3165 return false;
3166
3167 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
3169 diag::err_expected_after)
3170 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
3171
3172 // Try to recover from the typo, by dropping the tag definition and parsing
3173 // the problematic tokens as a type.
3174 //
3175 // FIXME: Split the DeclSpec into pieces for the standalone
3176 // declaration and pieces for the following declaration, instead
3177 // of assuming that all the other pieces attach to new declaration,
3178 // and call ParsedFreeStandingDeclSpec as appropriate.
3179 DS.ClearTypeSpecType();
3180 ParsedTemplateInfo NotATemplate;
3181 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
3182 return false;
3183}
3184
3185// Choose the apprpriate diagnostic error for why fixed point types are
3186// disabled, set the previous specifier, and mark as invalid.
3187static void SetupFixedPointError(const LangOptions &LangOpts,
3188 const char *&PrevSpec, unsigned &DiagID,
3189 bool &isInvalid) {
3190 assert(!LangOpts.FixedPoint);
3191 DiagID = diag::err_fixed_point_not_enabled;
3192 PrevSpec = ""; // Not used by diagnostic
3193 isInvalid = true;
3194}
3195
3196/// ParseDeclarationSpecifiers
3197/// declaration-specifiers: [C99 6.7]
3198/// storage-class-specifier declaration-specifiers[opt]
3199/// type-specifier declaration-specifiers[opt]
3200/// [C99] function-specifier declaration-specifiers[opt]
3201/// [C11] alignment-specifier declaration-specifiers[opt]
3202/// [GNU] attributes declaration-specifiers[opt]
3203/// [Clang] '__module_private__' declaration-specifiers[opt]
3204/// [ObjC1] '__kindof' declaration-specifiers[opt]
3205///
3206/// storage-class-specifier: [C99 6.7.1]
3207/// 'typedef'
3208/// 'extern'
3209/// 'static'
3210/// 'auto'
3211/// 'register'
3212/// [C++] 'mutable'
3213/// [C++11] 'thread_local'
3214/// [C11] '_Thread_local'
3215/// [GNU] '__thread'
3216/// function-specifier: [C99 6.7.4]
3217/// [C99] 'inline'
3218/// [C++] 'virtual'
3219/// [C++] 'explicit'
3220/// [OpenCL] '__kernel'
3221/// 'friend': [C++ dcl.friend]
3222/// 'constexpr': [C++0x dcl.constexpr]
3223void Parser::ParseDeclarationSpecifiers(
3224 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
3225 DeclSpecContext DSContext, LateParsedAttrList *LateAttrs,
3226 ImplicitTypenameContext AllowImplicitTypename) {
3227 if (DS.getSourceRange().isInvalid()) {
3228 // Start the range at the current token but make the end of the range
3229 // invalid. This will make the entire range invalid unless we successfully
3230 // consume a token.
3231 DS.SetRangeStart(Tok.getLocation());
3233 }
3234
3235 // If we are in a operator context, convert it back into a type specifier
3236 // context for better error handling later on.
3237 if (DSContext == DeclSpecContext::DSC_conv_operator) {
3238 // No implicit typename here.
3239 AllowImplicitTypename = ImplicitTypenameContext::No;
3240 DSContext = DeclSpecContext::DSC_type_specifier;
3241 }
3242
3243 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3244 DSContext == DeclSpecContext::DSC_top_level);
3245 bool AttrsLastTime = false;
3246 ParsedAttributes attrs(AttrFactory);
3247 // We use Sema's policy to get bool macros right.
3248 PrintingPolicy Policy = Actions.getPrintingPolicy();
3249 while (true) {
3250 bool isInvalid = false;
3251 bool isStorageClass = false;
3252 const char *PrevSpec = nullptr;
3253 unsigned DiagID = 0;
3254
3255 // This value needs to be set to the location of the last token if the last
3256 // token of the specifier is already consumed.
3257 SourceLocation ConsumedEnd;
3258
3259 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3260 // implementation for VS2013 uses _Atomic as an identifier for one of the
3261 // classes in <atomic>.
3262 //
3263 // A typedef declaration containing _Atomic<...> is among the places where
3264 // the class is used. If we are currently parsing such a declaration, treat
3265 // the token as an identifier.
3266 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3268 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3269 Tok.setKind(tok::identifier);
3270
3271 SourceLocation Loc = Tok.getLocation();
3272
3273 // Helper for image types in OpenCL.
3274 auto handleOpenCLImageKW = [&] (StringRef Ext, TypeSpecifierType ImageTypeSpec) {
3275 // Check if the image type is supported and otherwise turn the keyword into an identifier
3276 // because image types from extensions are not reserved identifiers.
3277 if (!StringRef(Ext).empty() && !getActions().getOpenCLOptions().isSupported(Ext, getLangOpts())) {
3279 Tok.setKind(tok::identifier);
3280 return false;
3281 }
3282 isInvalid = DS.SetTypeSpecType(ImageTypeSpec, Loc, PrevSpec, DiagID, Policy);
3283 return true;
3284 };
3285
3286 // Turn off usual access checking for template specializations and
3287 // instantiations.
3288 bool IsTemplateSpecOrInst =
3289 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3290 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3291
3292 switch (Tok.getKind()) {
3293 default:
3294 DoneWithDeclSpec:
3295 if (!AttrsLastTime)
3296 ProhibitAttributes(attrs);
3297 else {
3298 // Reject C++11 / C2x attributes that aren't type attributes.
3299 for (const ParsedAttr &PA : attrs) {
3300 if (!PA.isCXX11Attribute() && !PA.isC2xAttribute())
3301 continue;
3302 if (PA.getKind() == ParsedAttr::UnknownAttribute)
3303 // We will warn about the unknown attribute elsewhere (in
3304 // SemaDeclAttr.cpp)
3305 continue;
3306 // GCC ignores this attribute when placed on the DeclSpec in [[]]
3307 // syntax, so we do the same.
3308 if (PA.getKind() == ParsedAttr::AT_VectorSize) {
3309 Diag(PA.getLoc(), diag::warn_attribute_ignored) << PA;
3310 PA.setInvalid();
3311 continue;
3312 }
3313 // We reject AT_LifetimeBound and AT_AnyX86NoCfCheck, even though they
3314 // are type attributes, because we historically haven't allowed these
3315 // to be used as type attributes in C++11 / C2x syntax.
3316 if (PA.isTypeAttr() && PA.getKind() != ParsedAttr::AT_LifetimeBound &&
3317 PA.getKind() != ParsedAttr::AT_AnyX86NoCfCheck)
3318 continue;
3319 Diag(PA.getLoc(), diag::err_attribute_not_type_attr) << PA;
3320 PA.setInvalid();
3321 }
3322
3323 DS.takeAttributesFrom(attrs);
3324 }
3325
3326 // If this is not a declaration specifier token, we're done reading decl
3327 // specifiers. First verify that DeclSpec's are consistent.
3328 DS.Finish(Actions, Policy);
3329 return;
3330
3331 case tok::l_square:
3332 case tok::kw_alignas:
3333 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
3334 goto DoneWithDeclSpec;
3335
3336 ProhibitAttributes(attrs);
3337 // FIXME: It would be good to recover by accepting the attributes,
3338 // but attempting to do that now would cause serious
3339 // madness in terms of diagnostics.
3340 attrs.clear();
3341 attrs.Range = SourceRange();
3342
3343 ParseCXX11Attributes(attrs);
3344 AttrsLastTime = true;
3345 continue;
3346
3347 case tok::code_completion: {
3349 if (DS.hasTypeSpecifier()) {
3350 bool AllowNonIdentifiers
3355 Scope::AtCatchScope)) == 0;
3356 bool AllowNestedNameSpecifiers
3357 = DSContext == DeclSpecContext::DSC_top_level ||
3358 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3359
3360 cutOffParsing();
3361 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3362 AllowNonIdentifiers,
3363 AllowNestedNameSpecifiers);
3364 return;
3365 }
3366
3367 // Class context can appear inside a function/block, so prioritise that.
3368 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3369 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3371 else if (DSContext == DeclSpecContext::DSC_class)
3372 CCC = Sema::PCC_Class;
3373 else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3375 else if (CurParsedObjCImpl)
3377
3378 cutOffParsing();
3379 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3380 return;
3381 }
3382
3383 case tok::coloncolon: // ::foo::bar
3384 // C++ scope specifier. Annotate and loop, or bail out on error.
3385 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3386 if (!DS.hasTypeSpecifier())
3387 DS.SetTypeSpecError();
3388 goto DoneWithDeclSpec;
3389 }
3390 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3391 goto DoneWithDeclSpec;
3392 continue;
3393
3394 case tok::annot_cxxscope: {
3395 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3396 goto DoneWithDeclSpec;
3397
3398 CXXScopeSpec SS;
3399 if (TemplateInfo.TemplateParams)
3400 SS.setTemplateParamLists(*TemplateInfo.TemplateParams);
3402 Tok.getAnnotationRange(),
3403 SS);
3404
3405 // We are looking for a qualified typename.
3406 Token Next = NextToken();
3407
3408 TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
3409 ? takeTemplateIdAnnotation(Next)
3410 : nullptr;
3411 if (TemplateId && TemplateId->hasInvalidName()) {
3412 // We found something like 'T::U<Args> x', but U is not a template.
3413 // Assume it was supposed to be a type.
3414 DS.SetTypeSpecError();
3415 ConsumeAnnotationToken();
3416 break;
3417 }
3418
3419 if (TemplateId && TemplateId->Kind == TNK_Type_template) {
3420 // We have a qualified template-id, e.g., N::A<int>
3421
3422 // If this would be a valid constructor declaration with template
3423 // arguments, we will reject the attempt to form an invalid type-id
3424 // referring to the injected-class-name when we annotate the token,
3425 // per C++ [class.qual]p2.
3426 //
3427 // To improve diagnostics for this case, parse the declaration as a
3428 // constructor (and reject the extra template arguments later).
3429 if ((DSContext == DeclSpecContext::DSC_top_level ||
3430 DSContext == DeclSpecContext::DSC_class) &&
3431 TemplateId->Name &&
3432 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3433 isConstructorDeclarator(/*Unqualified=*/false,
3434 /*DeductionGuide=*/false,
3435 DS.isFriendSpecified())) {
3436 // The user meant this to be an out-of-line constructor
3437 // definition, but template arguments are not allowed
3438 // there. Just allow this as a constructor; we'll
3439 // complain about it later.
3440 goto DoneWithDeclSpec;
3441 }
3442
3443 DS.getTypeSpecScope() = SS;
3444 ConsumeAnnotationToken(); // The C++ scope.
3445 assert(Tok.is(tok::annot_template_id) &&
3446 "ParseOptionalCXXScopeSpecifier not working");
3447 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3448 continue;
3449 }
3450
3451 if (TemplateId && TemplateId->Kind == TNK_Concept_template &&
3452 GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype)) {
3453 DS.getTypeSpecScope() = SS;
3454 // This is a qualified placeholder-specifier, e.g., ::C<int> auto ...
3455 // Consume the scope annotation and continue to consume the template-id
3456 // as a placeholder-specifier.
3457 ConsumeAnnotationToken();
3458 continue;
3459 }
3460
3461 if (Next.is(tok::annot_typename)) {
3462 DS.getTypeSpecScope() = SS;
3463 ConsumeAnnotationToken(); // The C++ scope.
3466 Tok.getAnnotationEndLoc(),
3467 PrevSpec, DiagID, T, Policy);
3468 if (isInvalid)
3469 break;
3471 ConsumeAnnotationToken(); // The typename
3472 }
3473
3474 if (AllowImplicitTypename == ImplicitTypenameContext::Yes &&
3475 Next.is(tok::annot_template_id) &&
3476 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3478 DS.getTypeSpecScope() = SS;
3479 ConsumeAnnotationToken(); // The C++ scope.
3480 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3481 continue;
3482 }
3483
3484 if (Next.isNot(tok::identifier))
3485 goto DoneWithDeclSpec;
3486
3487 // Check whether this is a constructor declaration. If we're in a
3488 // context where the identifier could be a class name, and it has the
3489 // shape of a constructor declaration, process it as one.
3490 if ((DSContext == DeclSpecContext::DSC_top_level ||
3491 DSContext == DeclSpecContext::DSC_class) &&
3492 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3493 &SS) &&
3494 isConstructorDeclarator(/*Unqualified=*/false,
3495 /*DeductionGuide=*/false,
3496 DS.isFriendSpecified(),
3497 &TemplateInfo))
3498 goto DoneWithDeclSpec;
3499
3500 // C++20 [temp.spec] 13.9/6.
3501 // This disables the access checking rules for function template explicit
3502 // instantiation and explicit specialization:
3503 // - `return type`.
3504 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3505
3506 ParsedType TypeRep = Actions.getTypeName(
3507 *Next.getIdentifierInfo(), Next.getLocation(), getCurScope(), &SS,
3508 false, false, nullptr,
3509 /*IsCtorOrDtorName=*/false,
3510 /*WantNontrivialTypeSourceInfo=*/true,
3511 isClassTemplateDeductionContext(DSContext), AllowImplicitTypename);
3512
3513 if (IsTemplateSpecOrInst)
3514 SAC.done();
3515
3516 // If the referenced identifier is not a type, then this declspec is
3517 // erroneous: We already checked about that it has no type specifier, and
3518 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3519 // typename.
3520 if (!TypeRep) {
3521 if (TryAnnotateTypeConstraint())
3522 goto DoneWithDeclSpec;
3523 if (Tok.isNot(tok::annot_cxxscope) ||
3524 NextToken().isNot(tok::identifier))
3525 continue;
3526 // Eat the scope spec so the identifier is current.
3527 ConsumeAnnotationToken();
3528 ParsedAttributes Attrs(AttrFactory);
3529 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3530 if (!Attrs.empty()) {
3531 AttrsLastTime = true;
3532 attrs.takeAllFrom(Attrs);
3533 }
3534 continue;
3535 }
3536 goto DoneWithDeclSpec;
3537 }
3538
3539 DS.getTypeSpecScope() = SS;
3540 ConsumeAnnotationToken(); // The C++ scope.
3541
3543 DiagID, TypeRep, Policy);
3544 if (isInvalid)
3545 break;
3546
3547 DS.SetRangeEnd(Tok.getLocation());
3548 ConsumeToken(); // The typename.
3549
3550 continue;
3551 }
3552
3553 case tok::annot_typename: {
3554 // If we've previously seen a tag definition, we were almost surely
3555 // missing a semicolon after it.
3556 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3557 goto DoneWithDeclSpec;
3558
3561 DiagID, T, Policy);
3562 if (isInvalid)
3563 break;
3564
3566 ConsumeAnnotationToken(); // The typename
3567
3568 continue;
3569 }
3570
3571 case tok::kw___is_signed:
3572 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3573 // typically treats it as a trait. If we see __is_signed as it appears
3574 // in libstdc++, e.g.,
3575 //
3576 // static const bool __is_signed;
3577 //
3578 // then treat __is_signed as an identifier rather than as a keyword.
3579 if (DS.getTypeSpecType() == TST_bool &&
3582 TryKeywordIdentFallback(true);
3583
3584 // We're done with the declaration-specifiers.
3585 goto DoneWithDeclSpec;
3586
3587 // typedef-name
3588 case tok::kw___super:
3589 case tok::kw_decltype:
3590 case tok::identifier:
3591 ParseIdentifier: {
3592 // This identifier can only be a typedef name if we haven't already seen
3593 // a type-specifier. Without this check we misparse:
3594 // typedef int X; struct Y { short X; }; as 'short int'.
3595 if (DS.hasTypeSpecifier())
3596 goto DoneWithDeclSpec;
3597
3598 // If the token is an identifier named "__declspec" and Microsoft
3599 // extensions are not enabled, it is likely that there will be cascading
3600 // parse errors if this really is a __declspec attribute. Attempt to
3601 // recognize that scenario and recover gracefully.
3602 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3603 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3604 Diag(Loc, diag::err_ms_attributes_not_enabled);
3605
3606 // The next token should be an open paren. If it is, eat the entire
3607 // attribute declaration and continue.
3608 if (NextToken().is(tok::l_paren)) {
3609 // Consume the __declspec identifier.
3610 ConsumeToken();
3611
3612 // Eat the parens and everything between them.
3613 BalancedDelimiterTracker T(*this, tok::l_paren);
3614 if (T.consumeOpen()) {
3615 assert(false && "Not a left paren?");
3616 return;
3617 }
3618 T.skipToEnd();
3619 continue;
3620 }
3621 }
3622
3623 // In C++, check to see if this is a scope specifier like foo::bar::, if
3624 // so handle it as such. This is important for ctor parsing.
3625 if (getLangOpts().CPlusPlus) {
3626 // C++20 [temp.spec] 13.9/6.
3627 // This disables the access checking rules for function template
3628 // explicit instantiation and explicit specialization:
3629 // - `return type`.
3630 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3631
3632 const bool Success = TryAnnotateCXXScopeToken(EnteringContext);
3633
3634 if (IsTemplateSpecOrInst)
3635 SAC.done();
3636
3637 if (Success) {
3638 if (IsTemplateSpecOrInst)
3639 SAC.redelay();
3640 DS.SetTypeSpecError();
3641 goto DoneWithDeclSpec;
3642 }
3643
3644 if (!Tok.is(tok::identifier))
3645 continue;
3646 }
3647
3648 // Check for need to substitute AltiVec keyword tokens.
3649 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3650 break;
3651
3652 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3653 // allow the use of a typedef name as a type specifier.
3654 if (DS.isTypeAltiVecVector())
3655 goto DoneWithDeclSpec;
3656
3657 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3658 isObjCInstancetype()) {
3659 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3660 assert(TypeRep);
3662 DiagID, TypeRep, Policy);
3663 if (isInvalid)
3664 break;
3665
3666 DS.SetRangeEnd(Loc);
3667 ConsumeToken();
3668 continue;
3669 }
3670
3671 // If we're in a context where the identifier could be a class name,
3672 // check whether this is a constructor declaration.
3673 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3675 isConstructorDeclarator(/*Unqualified=*/true,
3676 /*DeductionGuide=*/false,
3677 DS.isFriendSpecified()))
3678 goto DoneWithDeclSpec;
3679
3680 ParsedType TypeRep = Actions.getTypeName(
3681 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3682 false, false, nullptr, false, false,
3683 isClassTemplateDeductionContext(DSContext));
3684
3685 // If this is not a typedef name, don't parse it as part of the declspec,
3686 // it must be an implicit int or an error.
3687 if (!TypeRep) {
3688 if (TryAnnotateTypeConstraint())
3689 goto DoneWithDeclSpec;
3690 if (Tok.isNot(tok::identifier))
3691 continue;
3692 ParsedAttributes Attrs(AttrFactory);
3693 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3694 if (!Attrs.empty()) {
3695 AttrsLastTime = true;
3696 attrs.takeAllFrom(Attrs);
3697 }
3698 continue;
3699 }
3700 goto DoneWithDeclSpec;
3701 }
3702
3703 // Likewise, if this is a context where the identifier could be a template
3704 // name, check whether this is a deduction guide declaration.
3705 if (getLangOpts().CPlusPlus17 &&
3706 (DSContext == DeclSpecContext::DSC_class ||
3707 DSContext == DeclSpecContext::DSC_top_level) &&
3709 Tok.getLocation()) &&
3710 isConstructorDeclarator(/*Unqualified*/ true,
3711 /*DeductionGuide*/ true))
3712 goto DoneWithDeclSpec;
3713
3715 DiagID, TypeRep, Policy);
3716 if (isInvalid)
3717 break;
3718
3719 DS.SetRangeEnd(Tok.getLocation());
3720 ConsumeToken(); // The identifier
3721
3722 // Objective-C supports type arguments and protocol references
3723 // following an Objective-C object or object pointer
3724 // type. Handle either one of them.
3725 if (Tok.is(tok::less) && getLangOpts().ObjC) {
3726 SourceLocation NewEndLoc;
3727 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3728 Loc, TypeRep, /*consumeLastToken=*/true,
3729 NewEndLoc);
3730 if (NewTypeRep.isUsable()) {
3731 DS.UpdateTypeRep(NewTypeRep.get());
3732 DS.SetRangeEnd(NewEndLoc);
3733 }
3734 }
3735
3736 // Need to support trailing type qualifiers (e.g. "id<p> const").
3737 // If a type specifier follows, it will be diagnosed elsewhere.
3738 continue;
3739 }
3740
3741 // type-name or placeholder-specifier
3742 case tok::annot_template_id: {
3743 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3744
3745 if (TemplateId->hasInvalidName()) {
3746 DS.SetTypeSpecError();
3747 break;
3748 }
3749
3750 if (TemplateId->Kind == TNK_Concept_template) {
3751 // If we've already diagnosed that this type-constraint has invalid
3752 // arguments, drop it and just form 'auto' or 'decltype(auto)'.
3753 if (TemplateId->hasInvalidArgs())
3754 TemplateId = nullptr;
3755
3756 // Any of the following tokens are likely the start of the user
3757 // forgetting 'auto' or 'decltype(auto)', so diagnose.
3758 // Note: if updating this list, please make sure we update
3759 // isCXXDeclarationSpecifier's check for IsPlaceholderSpecifier to have
3760 // a matching list.
3761 if (NextToken().isOneOf(tok::identifier, tok::kw_const,
3762 tok::kw_volatile, tok::kw_restrict, tok::amp,
3763 tok::ampamp)) {
3764 Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
3765 << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
3766 // Attempt to continue as if 'auto' was placed here.
3767 isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3768 TemplateId, Policy);
3769 break;
3770 }
3771 if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
3772 goto DoneWithDeclSpec;
3773 ConsumeAnnotationToken();
3774 SourceLocation AutoLoc = Tok.getLocation();
3775 if (TryConsumeToken(tok::kw_decltype)) {
3776 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3777 if (Tracker.consumeOpen()) {
3778 // Something like `void foo(Iterator decltype i)`
3779 Diag(Tok, diag::err_expected) << tok::l_paren;
3780 } else {
3781 if (!TryConsumeToken(tok::kw_auto)) {
3782 // Something like `void foo(Iterator decltype(int) i)`
3783 Tracker.skipToEnd();
3784 Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
3786 Tok.getLocation()),
3787 "auto");
3788 } else {
3789 Tracker.consumeClose();
3790 }
3791 }
3792 ConsumedEnd = Tok.getLocation();
3793 DS.setTypeArgumentRange(Tracker.getRange());
3794 // Even if something went wrong above, continue as if we've seen
3795 // `decltype(auto)`.
3796 isInvalid = DS.SetTypeSpecType(TST_decltype_auto, Loc, PrevSpec,
3797 DiagID, TemplateId, Policy);
3798 } else {
3799 isInvalid = DS.SetTypeSpecType(TST_auto, AutoLoc, PrevSpec, DiagID,
3800 TemplateId, Policy);
3801 }
3802 break;
3803 }
3804
3805 if (TemplateId->Kind != TNK_Type_template &&
3806 TemplateId->Kind != TNK_Undeclared_template) {
3807 // This template-id does not refer to a type name, so we're
3808 // done with the type-specifiers.
3809 goto DoneWithDeclSpec;
3810 }
3811
3812 // If we're in a context where the template-id could be a
3813 // constructor name or specialization, check whether this is a
3814 // constructor declaration.
3815 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3816 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3817 isConstructorDeclarator(/*Unqualified=*/true,
3818 /*DeductionGuide=*/false,
3819 DS.isFriendSpecified()))
3820 goto DoneWithDeclSpec;
3821
3822 // Turn the template-id annotation token into a type annotation
3823 // token, then try again to parse it as a type-specifier.
3824 CXXScopeSpec SS;
3825 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3826 continue;
3827 }
3828
3829 // Attributes support.
3830 case tok::kw___attribute:
3831 case tok::kw___declspec:
3832 ParseAttributes(PAKM_GNU | PAKM_Declspec, DS.getAttributes(), LateAttrs);
3833 continue;
3834
3835 // Microsoft single token adornments.
3836 case tok::kw___forceinline: {
3837 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3838 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3839 SourceLocation AttrNameLoc = Tok.getLocation();
3840 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3841 nullptr, 0, ParsedAttr::AS_Keyword);
3842 break;
3843 }
3844
3845 case tok::kw___unaligned:
3846 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3847 getLangOpts());
3848 break;
3849
3850 case tok::kw___sptr:
3851 case tok::kw___uptr:
3852 case tok::kw___ptr64:
3853 case tok::kw___ptr32:
3854 case tok::kw___w64:
3855 case tok::kw___cdecl:
3856 case tok::kw___stdcall:
3857 case tok::kw___fastcall:
3858 case tok::kw___thiscall:
3859 case tok::kw___regcall:
3860 case tok::kw___vectorcall:
3861 ParseMicrosoftTypeAttributes(DS.getAttributes());
3862 continue;
3863
3864 case tok::kw___funcref:
3865 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
3866 continue;
3867
3868 // Borland single token adornments.
3869 case tok::kw___pascal:
3870 ParseBorlandTypeAttributes(DS.getAttributes());
3871 continue;
3872
3873 // OpenCL single token adornments.
3874 case tok::kw___kernel:
3875 ParseOpenCLKernelAttributes(DS.getAttributes());
3876 continue;
3877
3878 // CUDA/HIP single token adornments.
3879 case tok::kw___noinline__:
3880 ParseCUDAFunctionAttributes(DS.getAttributes());
3881 continue;
3882
3883 // Nullability type specifiers.
3884 case tok::kw__Nonnull:
3885 case tok::kw__Nullable:
3886 case tok::kw__Nullable_result:
3887 case tok::kw__Null_unspecified:
3888 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3889 continue;
3890
3891 // Objective-C 'kindof' types.
3892 case tok::kw___kindof:
3893 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3894 nullptr, 0, ParsedAttr::AS_Keyword);
3895 (void)ConsumeToken();
3896 continue;
3897
3898 // storage-class-specifier
3899 case tok::kw_typedef:
3901 PrevSpec, DiagID, Policy);
3902 isStorageClass = true;
3903 break;
3904 case tok::kw_extern:
3906 Diag(Tok, diag::ext_thread_before) << "extern";
3908 PrevSpec, DiagID, Policy);
3909 isStorageClass = true;
3910 break;
3911 case tok::kw___private_extern__:
3913 Loc, PrevSpec, DiagID, Policy);
3914 isStorageClass = true;
3915 break;
3916 case tok::kw_static:
3918 Diag(Tok, diag::ext_thread_before) << "static";
3920 PrevSpec, DiagID, Policy);
3921 isStorageClass = true;
3922 break;
3923 case tok::kw_auto:
3924 if (getLangOpts().CPlusPlus11) {
3925 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3927 PrevSpec, DiagID, Policy);
3928 if (!isInvalid)
3929 Diag(Tok, diag::ext_auto_storage_class)
3931 } else
3932 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3933 DiagID, Policy);
3934 } else
3936 PrevSpec, DiagID, Policy);
3937 isStorageClass = true;
3938 break;
3939 case tok::kw___auto_type:
3940 Diag(Tok, diag::ext_auto_type);
3942 DiagID, Policy);
3943 break;
3944 case tok::kw_register:
3946 PrevSpec, DiagID, Policy);
3947 isStorageClass = true;
3948 break;
3949 case tok::kw_mutable:
3951 PrevSpec, DiagID, Policy);
3952 isStorageClass = true;
3953 break;
3954 case tok::kw___thread:
3956 PrevSpec, DiagID);
3957 isStorageClass = true;
3958 break;
3959 case tok::kw_thread_local:
3960 if (getLangOpts().C2x)
3961 Diag(Tok, diag::warn_c2x_compat_keyword) << Tok.getName();
3963 PrevSpec, DiagID);
3964 isStorageClass = true;
3965 break;
3966 case tok::kw__Thread_local:
3967 if (!getLangOpts().C11)
3968 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3970 Loc, PrevSpec, DiagID);
3971 isStorageClass = true;
3972 break;
3973
3974 // function-specifier
3975 case tok::kw_inline:
3976 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3977 break;
3978 case tok::kw_virtual:
3979 // C++ for OpenCL does not allow virtual function qualifier, to avoid
3980 // function pointers restricted in OpenCL v2.0 s6.9.a.
3981 if (getLangOpts().OpenCLCPlusPlus &&
3982 !getActions().getOpenCLOptions().isAvailableOption(
3983 "__cl_clang_function_pointers", getLangOpts())) {
3984 DiagID = diag::err_openclcxx_virtual_function;
3985 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3986 isInvalid = true;
3987 } else {
3988 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3989 }
3990 break;
3991 case tok::kw_explicit: {
3992 SourceLocation ExplicitLoc = Loc;
3993 SourceLocation CloseParenLoc;
3995 ConsumedEnd = ExplicitLoc;
3996 ConsumeToken(); // kw_explicit
3997 if (Tok.is(tok::l_paren)) {
3998 if (getLangOpts().CPlusPlus20 || isExplicitBool() == TPResult::True) {
4000 ? diag::warn_cxx17_compat_explicit_bool
4001 : diag::ext_explicit_bool);
4002
4003 ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
4004 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
4005 Tracker.consumeOpen();
4006 ExplicitExpr = ParseConstantExpression();
4007 ConsumedEnd = Tok.getLocation();
4008 if (ExplicitExpr.isUsable()) {
4009 CloseParenLoc = Tok.getLocation();
4010 Tracker.consumeClose();
4011 ExplicitSpec =
4012 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
4013 } else
4014 Tracker.skipToEnd();
4015 } else {
4016 Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
4017 }
4018 }
4019 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
4020 ExplicitSpec, CloseParenLoc);
4021 break;
4022 }
4023 case tok::kw__Noreturn:
4024 if (!getLangOpts().C11)
4025 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4026 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
4027 break;
4028
4029 // alignment-specifier
4030 case tok::kw__Alignas:
4031 if (!getLangOpts().C11)
4032 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4033 ParseAlignmentSpecifier(DS.getAttributes());
4034 continue;
4035
4036 // friend
4037 case tok::kw_friend:
4038 if (DSContext == DeclSpecContext::DSC_class)
4039 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
4040 else {
4041 PrevSpec = ""; // not actually used by the diagnostic
4042 DiagID = diag::err_friend_invalid_in_context;
4043 isInvalid = true;
4044 }
4045 break;
4046
4047 // Modules
4048 case tok::kw___module_private__:
4049 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
4050 break;
4051
4052 // constexpr, consteval, constinit specifiers
4053 case tok::kw_constexpr:
4055 PrevSpec, DiagID);
4056 break;
4057 case tok::kw_consteval:
4059 PrevSpec, DiagID);
4060 break;
4061 case tok::kw_constinit:
4063 PrevSpec, DiagID);
4064 break;
4065
4066 // type-specifier
4067 case tok::kw_short:
4069 DiagID, Policy);
4070 break;
4071 case tok::kw_long:
4074 DiagID, Policy);
4075 else
4077 PrevSpec, DiagID, Policy);
4078 break;
4079 case tok::kw___int64:
4081 PrevSpec, DiagID, Policy);
4082 break;
4083 case tok::kw_signed:
4084 isInvalid =
4085 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
4086 break;
4087 case tok::kw_unsigned:
4089 DiagID);
4090 break;
4091 case tok::kw__Complex:
4092 if (!getLangOpts().C99)
4093 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4095 DiagID);
4096 break;
4097 case tok::kw__Imaginary:
4098 if (!getLangOpts().C99)
4099 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4101 DiagID);
4102 break;
4103 case tok::kw_void:
4104 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
4105 DiagID, Policy);
4106 break;
4107 case tok::kw_char:
4108 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
4109 DiagID, Policy);
4110 break;
4111 case tok::kw_int:
4112 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
4113 DiagID, Policy);
4114 break;
4115 case tok::kw__ExtInt:
4116 case tok::kw__BitInt: {
4117 DiagnoseBitIntUse(Tok);
4118 ExprResult ER = ParseExtIntegerArgument();
4119 if (ER.isInvalid())
4120 continue;
4121 isInvalid = DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
4122 ConsumedEnd = PrevTokLocation;
4123 break;
4124 }
4125 case tok::kw___int128:
4127 DiagID, Policy);
4128 break;
4129 case tok::kw_half:
4130 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
4131 DiagID, Policy);
4132 break;
4133 case tok::kw___bf16:
4135 DiagID, Policy);
4136 break;
4137 case tok::kw_float:
4138 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
4139 DiagID, Policy);
4140 break;
4141 case tok::kw_double:
4143 DiagID, Policy);
4144 break;
4145 case tok::kw__Float16:
4147 DiagID, Policy);
4148 break;
4149 case tok::kw__Accum:
4150 if (!getLangOpts().FixedPoint) {
4151 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4152 } else {
4153 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
4154 DiagID, Policy);
4155 }
4156 break;
4157 case tok::kw__Fract:
4158 if (!getLangOpts().FixedPoint) {
4159 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4160 } else {
4161 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
4162 DiagID, Policy);
4163 }
4164 break;
4165 case tok::kw__Sat:
4166 if (!getLangOpts().FixedPoint) {
4167 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4168 } else {
4169 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
4170 }
4171 break;
4172 case tok::kw___float128:
4174 DiagID, Policy);
4175 break;
4176 case tok::kw___ibm128:
4178 DiagID, Policy);
4179 break;
4180 case tok::kw_wchar_t:
4181 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
4182 DiagID, Policy);
4183 break;
4184 case tok::kw_char8_t:
4185 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
4186 DiagID, Policy);
4187 break;
4188 case tok::kw_char16_t:
4190 DiagID, Policy);
4191 break;
4192 case tok::kw_char32_t:
4194 DiagID, Policy);
4195 break;
4196 case tok::kw_bool:
4197 if (getLangOpts().C2x)
4198 Diag(Tok, diag::warn_c2x_compat_keyword) << Tok.getName();
4199 [[fallthrough]];
4200 case tok::kw__Bool:
4201 if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
4202 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4203
4204 if (Tok.is(tok::kw_bool) &&
4207 PrevSpec = ""; // Not used by the diagnostic.
4208 DiagID = diag::err_bool_redeclaration;
4209 // For better error recovery.
4210 Tok.setKind(tok::identifier);
4211 isInvalid = true;
4212 } else {
4213 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
4214 DiagID, Policy);
4215 }
4216 break;
4217 case tok::kw__Decimal32:
4219 DiagID, Policy);
4220 break;
4221 case tok::kw__Decimal64:
4223 DiagID, Policy);
4224 break;
4225 case tok::kw__Decimal128:
4227 DiagID, Policy);
4228 break;
4229 case tok::kw___vector:
4230 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
4231 break;
4232 case tok::kw___pixel:
4233 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
4234 break;
4235 case tok::kw___bool:
4236 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
4237 break;
4238 case tok::kw_pipe:
4239 if (!getLangOpts().OpenCL ||
4240 getLangOpts().getOpenCLCompatibleVersion() < 200) {
4241 // OpenCL 2.0 and later define this keyword. OpenCL 1.2 and earlier
4242 // should support the "pipe" word as identifier.
4244 Tok.setKind(tok::identifier);
4245 goto DoneWithDeclSpec;
4246 } else if (!getLangOpts().OpenCLPipes) {
4247 DiagID = diag::err_opencl_unknown_type_specifier;
4248 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4249 isInvalid = true;
4250 } else
4251 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
4252 break;
4253// We only need to enumerate each image type once.
4254#define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
4255#define IMAGE_WRITE_TYPE(Type, Id, Ext)
4256#define IMAGE_READ_TYPE(ImgType, Id, Ext) \
4257 case tok::kw_##ImgType##_t: \
4258 if (!handleOpenCLImageKW(Ext, DeclSpec::TST_##ImgType##_t)) \
4259 goto DoneWithDeclSpec; \
4260 break;
4261#include "clang/Basic/OpenCLImageTypes.def"
4262 case tok::kw___unknown_anytype:
4264 PrevSpec, DiagID, Policy);
4265 break;
4266
4267 // class-specifier:
4268 case tok::kw_class:
4269 case tok::kw_struct:
4270 case tok::kw___interface:
4271 case tok::kw_union: {
4272 tok::TokenKind Kind = Tok.getKind();
4273 ConsumeToken();
4274
4275 // These are attributes following class specifiers.
4276 // To produce better diagnostic, we parse them when
4277 // parsing class specifier.
4278 ParsedAttributes Attributes(AttrFactory);
4279 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
4280 EnteringContext, DSContext, Attributes);
4281
4282 // If there are attributes following class specifier,
4283 // take them over and handle them here.
4284 if (!Attributes.empty()) {
4285 AttrsLastTime = true;
4286 attrs.takeAllFrom(Attributes);
4287 }
4288 continue;
4289 }
4290
4291 // enum-specifier:
4292 case tok::kw_enum:
4293 ConsumeToken();
4294 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
4295 continue;
4296
4297 // cv-qualifier:
4298 case tok::kw_const:
4299 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
4300 getLangOpts());
4301 break;
4302 case tok::kw_volatile:
4303 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4304 getLangOpts());
4305 break;
4306 case tok::kw_restrict:
4307 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4308 getLangOpts());
4309 break;
4310
4311 // C++ typename-specifier:
4312 case tok::kw_typename:
4314 DS.SetTypeSpecError();
4315 goto DoneWithDeclSpec;
4316 }
4317 if (!Tok.is(tok::kw_typename))
4318 continue;
4319 break;
4320
4321 // C2x/GNU typeof support.
4322 case tok::kw_typeof:
4323 case tok::kw_typeof_unqual:
4324 ParseTypeofSpecifier(DS);
4325 continue;
4326
4327 case tok::annot_decltype:
4328 ParseDecltypeSpecifier(DS);
4329 continue;
4330
4331 case tok::annot_pragma_pack:
4332 HandlePragmaPack();
4333 continue;
4334
4335 case tok::annot_pragma_ms_pragma:
4336 HandlePragmaMSPragma();
4337 continue;
4338
4339 case tok::annot_pragma_ms_vtordisp:
4340 HandlePragmaMSVtorDisp();
4341 continue;
4342
4343 case tok::annot_pragma_ms_pointers_to_members:
4344 HandlePragmaMSPointersToMembers();
4345 continue;
4346
4347#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
4348#include "clang/Basic/TransformTypeTraits.def"
4349 // HACK: libstdc++ already uses '__remove_cv' as an alias template so we
4350 // work around this by expecting all transform type traits to be suffixed
4351 // with '('. They're an identifier otherwise.
4352 if (!MaybeParseTypeTransformTypeSpecifier(DS))
4353 goto ParseIdentifier;
4354 continue;
4355
4356 case tok::kw__Atomic:
4357 // C11 6.7.2.4/4:
4358 // If the _Atomic keyword is immediately followed by a left parenthesis,
4359 // it is interpreted as a type specifier (with a type name), not as a
4360 // type qualifier.
4361 if (!getLangOpts().C11)
4362 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4363
4364 if (NextToken().is(tok::l_paren)) {
4365 ParseAtomicSpecifier(DS);
4366 continue;
4367 }
4368 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4369 getLangOpts());
4370 break;
4371
4372 // OpenCL address space qualifiers:
4373 case tok::kw___generic:
4374 // generic address space is introduced only in OpenCL v2.0
4375 // see OpenCL C Spec v2.0 s6.5.5
4376 // OpenCL v3.0 introduces __opencl_c_generic_address_space
4377 // feature macro to indicate if generic address space is supported
4378 if (!Actions.getLangOpts().OpenCLGenericAddressSpace) {
4379 DiagID = diag::err_opencl_unknown_type_specifier;
4380 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4381 isInvalid = true;
4382 break;
4383 }
4384 [[fallthrough]];
4385 case tok::kw_private:
4386 // It's fine (but redundant) to check this for __generic on the
4387 // fallthrough path; we only form the __generic token in OpenCL mode.
4388 if (!getLangOpts().OpenCL)
4389 goto DoneWithDeclSpec;
4390 [[fallthrough]];
4391 case tok::kw___private:
4392 case tok::kw___global:
4393 case tok::kw___local:
4394 case tok::kw___constant:
4395 // OpenCL access qualifiers:
4396 case tok::kw___read_only:
4397 case tok::kw___write_only:
4398 case tok::kw___read_write:
4399 ParseOpenCLQualifiers(DS.getAttributes());
4400 break;
4401
4402 case tok::kw_groupshared:
4403 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
4404 ParseHLSLQualifiers(DS.getAttributes());
4405 continue;
4406
4407 case tok::less:
4408 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4409 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
4410 // but we support it.
4411 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
4412 goto DoneWithDeclSpec;
4413
4414 SourceLocation StartLoc = Tok.getLocation();
4415 SourceLocation EndLoc;
4416 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4417 if (Type.isUsable()) {
4418 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4419 PrevSpec, DiagID, Type.get(),
4420 Actions.getASTContext().getPrintingPolicy()))
4421 Diag(StartLoc, DiagID) << PrevSpec;
4422
4423 DS.SetRangeEnd(EndLoc);
4424 } else {
4425 DS.SetTypeSpecError();
4426 }
4427
4428 // Need to support trailing type qualifiers (e.g. "id<p> const").
4429 // If a type specifier follows, it will be diagnosed elsewhere.
4430 continue;
4431 }
4432
4433 DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4434
4435 // If the specifier wasn't legal, issue a diagnostic.
4436 if (isInvalid) {
4437 assert(PrevSpec && "Method did not return previous specifier!");
4438 assert(DiagID);
4439
4440 if (DiagID == diag::ext_duplicate_declspec ||
4441 DiagID == diag::ext_warn_duplicate_declspec ||
4442 DiagID == diag::err_duplicate_declspec)
4443 Diag(Loc, DiagID) << PrevSpec
4445 SourceRange(Loc, DS.getEndLoc()));
4446 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4447 Diag(Loc, DiagID) << getLangOpts().getOpenCLVersionString() << PrevSpec
4448 << isStorageClass;
4449 } else
4450 Diag(Loc, DiagID) << PrevSpec;
4451 }
4452
4453 if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4454 // After an error the next token can be an annotation token.
4456
4457 AttrsLastTime = false;
4458 }
4459}
4460
4461/// ParseStructDeclaration - Parse a struct declaration without the terminating
4462/// semicolon.
4463///
4464/// Note that a struct declaration refers to a declaration in a struct,
4465/// not to the declaration of a struct.
4466///
4467/// struct-declaration:
4468/// [C2x] attributes-specifier-seq[opt]
4469/// specifier-qualifier-list struct-declarator-list
4470/// [GNU] __extension__ struct-declaration
4471/// [GNU] specifier-qualifier-list
4472/// struct-declarator-list:
4473/// struct-declarator
4474/// struct-declarator-list ',' struct-declarator
4475/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
4476/// struct-declarator:
4477/// declarator
4478/// [GNU] declarator attributes[opt]
4479/// declarator[opt] ':' constant-expression
4480/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
4481///
4482void Parser::ParseStructDeclaration(
4483 ParsingDeclSpec &DS,
4484 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4485
4486 if (Tok.is(tok::kw___extension__)) {
4487 // __extension__ silences extension warnings in the subexpression.
4488 ExtensionRAIIObject O(Diags); // Use RAII to do this.
4489 ConsumeToken();
4490 return ParseStructDeclaration(DS, FieldsCallback);
4491 }
4492
4493 // Parse leading attributes.
4494 ParsedAttributes Attrs(AttrFactory);
4495 MaybeParseCXX11Attributes(Attrs);
4496
4497 // Parse the common specifier-qualifiers-list piece.
4498 ParseSpecifierQualifierList(DS);
4499
4500 // If there are no declarators, this is a free-standing declaration
4501 // specifier. Let the actions module cope with it.
4502 if (Tok.is(tok::semi)) {
4503 // C2x 6.7.2.1p9 : "The optional attribute specifier sequence in a
4504 // member declaration appertains to each of the members declared by the
4505 // member declarator list; it shall not appear if the optional member
4506 // declarator list is omitted."
4507 ProhibitAttributes(Attrs);
4508 RecordDecl *AnonRecord = nullptr;
4509 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
4510 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
4511 assert(!AnonRecord && "Did not expect anonymous struct or union here");
4512 DS.complete(TheDecl);
4513 return;
4514 }
4515
4516 // Read struct-declarators until we find the semicolon.
4517 bool FirstDeclarator = true;
4518 SourceLocation CommaLoc;
4519 while (true) {
4520 ParsingFieldDeclarator DeclaratorInfo(*this, DS, Attrs);
4521 DeclaratorInfo.D.setCommaLoc(CommaLoc);
4522
4523 // Attributes are only allowed here on successive declarators.
4524 if (!FirstDeclarator) {
4525 // However, this does not apply for [[]] attributes (which could show up
4526 // before or after the __attribute__ attributes).
4527 DiagnoseAndSkipCXX11Attributes();
4528 MaybeParseGNUAttributes(DeclaratorInfo.D);
4529 DiagnoseAndSkipCXX11Attributes();
4530 }
4531
4532 /// struct-declarator: declarator
4533 /// struct-declarator: declarator[opt] ':' constant-expression
4534 if (Tok.isNot(tok::colon)) {
4535 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4537 ParseDeclarator(DeclaratorInfo.D);
4538 } else
4539 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4540
4541 if (TryConsumeToken(tok::colon)) {
4543 if (Res.isInvalid())
4544 SkipUntil(tok::semi, StopBeforeMatch);
4545 else
4546 DeclaratorInfo.BitfieldSize = Res.get();
4547 }
4548
4549 // If attributes exist after the declarator, parse them.
4550 MaybeParseGNUAttributes(DeclaratorInfo.D);
4551
4552 // We're done with this declarator; invoke the callback.
4553 FieldsCallback(DeclaratorInfo);
4554
4555 // If we don't have a comma, it is either the end of the list (a ';')
4556 // or an error, bail out.
4557 if (!TryConsumeToken(tok::comma, CommaLoc))
4558 return;
4559
4560 FirstDeclarator = false;
4561 }
4562}
4563
4564/// ParseStructUnionBody
4565/// struct-contents:
4566/// struct-declaration-list
4567/// [EXT] empty
4568/// [GNU] "struct-declaration-list" without terminating ';'
4569/// struct-declaration-list:
4570/// struct-declaration
4571/// struct-declaration-list struct-declaration
4572/// [OBC] '@' 'defs' '(' class-name ')'
4573///
4574void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4576 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4577 "parsing struct/union body");
4578 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4579
4580 BalancedDelimiterTracker T(*this, tok::l_brace);
4581 if (T.consumeOpen())
4582 return;
4583
4584 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4586
4587 // While we still have something to read, read the declarations in the struct.
4588 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4589 Tok.isNot(tok::eof)) {
4590 // Each iteration of this loop reads one struct-declaration.
4591
4592 // Check for extraneous top-level semicolon.
4593 if (Tok.is(tok::semi)) {
4594 ConsumeExtraSemi(InsideStruct, TagType);
4595 continue;
4596 }
4597
4598 // Parse _Static_assert declaration.
4599 if (Tok.isOneOf(tok::kw__Static_assert, tok::kw_static_assert)) {
4600 SourceLocation DeclEnd;
4601 ParseStaticAssertDeclaration(DeclEnd);
4602 continue;
4603 }
4604
4605 if (Tok.is(tok::annot_pragma_pack)) {
4606 HandlePragmaPack();
4607 continue;
4608 }
4609
4610 if (Tok.is(tok::annot_pragma_align)) {
4611 HandlePragmaAlign();
4612 continue;
4613 }
4614
4615 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
4616 // Result can be ignored, because it must be always empty.
4618 ParsedAttributes Attrs(AttrFactory);
4619 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4620 continue;
4621 }
4622
4623 if (tok::isPragmaAnnotation(Tok.getKind())) {
4624 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4627 ConsumeAnnotationToken();
4628 continue;
4629 }
4630
4631 if (!Tok.is(tok::at)) {
4632 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4633 // Install the declarator into the current TagDecl.
4634 Decl *Field =
4635 Actions.ActOnField(getCurScope(), TagDecl,
4636 FD.D.getDeclSpec().getSourceRange().getBegin(),
4637 FD.D, FD.BitfieldSize);
4638 FD.complete(Field);
4639 };
4640
4641 // Parse all the comma separated declarators.
4642 ParsingDeclSpec DS(*this);
4643 ParseStructDeclaration(DS, CFieldCallback);
4644 } else { // Handle @defs
4645 ConsumeToken();
4646 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4647 Diag(Tok, diag::err_unexpected_at);
4648 SkipUntil(tok::semi);
4649 continue;
4650 }
4651 ConsumeToken();
4652 ExpectAndConsume(tok::l_paren);
4653 if (!Tok.is(tok::identifier)) {
4654 Diag(Tok, diag::err_expected) << tok::identifier;
4655 SkipUntil(tok::semi);
4656 continue;
4657 }
4659 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4660 Tok.getIdentifierInfo(), Fields);
4661 ConsumeToken();
4662 ExpectAndConsume(tok::r_paren);
4663 }
4664
4665 if (TryConsumeToken(tok::semi))
4666 continue;
4667
4668 if (Tok.is(tok::r_brace)) {
4669 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4670 break;
4671 }
4672
4673 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4674 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4675 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4676 // If we stopped at a ';', eat it.
4677 TryConsumeToken(tok::semi);
4678 }
4679
4680 T.consumeClose();
4681
4682 ParsedAttributes attrs(AttrFactory);
4683 // If attributes exist after struct contents, parse them.
4684 MaybeParseGNUAttributes(attrs);
4685
4686 SmallVector<Decl *, 32> FieldDecls(TagDecl->fields());
4687
4688 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4689 T.getOpenLocation(), T.getCloseLocation(), attrs);
4690 StructScope.Exit();
4691 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4692}
4693
4694/// ParseEnumSpecifier
4695/// enum-specifier: [C99 6.7.2.2]
4696/// 'enum' identifier[opt] '{' enumerator-list '}'
4697///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4698/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4699/// '}' attributes[opt]
4700/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4701/// '}'
4702/// 'enum' identifier
4703/// [GNU] 'enum' attributes[opt] identifier
4704///
4705/// [C++11] enum-head '{' enumerator-list[opt] '}'
4706/// [C++11] enum-head '{' enumerator-list ',' '}'
4707///
4708/// enum-head: [C++11]
4709/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4710/// enum-key attribute-specifier-seq[opt] nested-name-specifier
4711/// identifier enum-base[opt]
4712///
4713/// enum-key: [C++11]
4714/// 'enum'
4715/// 'enum' 'class'
4716/// 'enum' 'struct'
4717///
4718/// enum-base: [C++11]
4719/// ':' type-specifier-seq
4720///
4721/// [C++] elaborated-type-specifier:
4722/// [C++] 'enum' nested-name-specifier[opt] identifier
4723///
4724void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4725 const ParsedTemplateInfo &TemplateInfo,
4726 AccessSpecifier AS, DeclSpecContext DSC) {
4727 // Parse the tag portion of this.
4728 if (Tok.is(tok::code_completion)) {
4729 // Code completion for an enum name.
4730 cutOffParsing();
4732 DS.SetTypeSpecError(); // Needed by ActOnUsingDeclaration.
4733 return;
4734 }
4735
4736 // If attributes exist after tag, parse them.
4737 ParsedAttributes attrs(AttrFactory);
4738 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
4739
4740 SourceLocation ScopedEnumKWLoc;
4741 bool IsScopedUsingClassTag = false;
4742
4743 // In C++11, recognize 'enum class' and 'enum struct'.
4744 if (Tok.isOneOf(tok::kw_class, tok::kw_struct) && getLangOpts().CPlusPlus) {
4745 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4746 : diag::ext_scoped_enum);
4747 IsScopedUsingClassTag = Tok.is(tok::kw_class);
4748 ScopedEnumKWLoc = ConsumeToken();
4749
4750 // Attributes are not allowed between these keywords. Diagnose,
4751 // but then just treat them like they appeared in the right place.
4752 ProhibitAttributes(attrs);
4753
4754 // They are allowed afterwards, though.
4755 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
4756 }
4757
4758 // C++11 [temp.explicit]p12:
4759 // The usual access controls do not apply to names used to specify
4760 // explicit instantiations.
4761 // We extend this to also cover explicit specializations. Note that
4762 // we don't suppress if this turns out to be an elaborated type
4763 // specifier.
4764 bool shouldDelayDiagsInTag =
4765 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4766 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4767 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4768
4769 // Determine whether this declaration is permitted to have an enum-base.
4770 AllowDefiningTypeSpec AllowEnumSpecifier =
4771 isDefiningTypeSpecifierContext(DSC, getLangOpts().CPlusPlus);
4772 bool CanBeOpaqueEnumDeclaration =
4773 DS.isEmpty() && isOpaqueEnumDeclarationContext(DSC);
4774 bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || getLangOpts().ObjC ||
4775 getLangOpts().MicrosoftExt) &&
4776 (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
4777 CanBeOpaqueEnumDeclaration);
4778
4779 CXXScopeSpec &SS = DS.getTypeSpecScope();
4780 if (getLangOpts().CPlusPlus) {
4781 // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
4783
4784 CXXScopeSpec Spec;
4785 if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
4786 /*ObjectHasErrors=*/false,
4787 /*EnteringContext=*/true))
4788 return;
4789
4790 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4791 Diag(Tok, diag::err_expected) << tok::identifier;
4792 DS.SetTypeSpecError();
4793 if (Tok.isNot(tok::l_brace)) {
4794 // Has no name and is not a definition.
4795 // Skip the rest of this declarator, up until the comma or semicolon.
4796 SkipUntil(tok::comma, StopAtSemi);
4797 return;
4798 }
4799 }
4800
4801 SS = Spec;
4802 }
4803
4804 // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
4805 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4806 Tok.isNot(tok::colon)) {
4807 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4808
4809 DS.SetTypeSpecError();
4810 // Skip the rest of this declarator, up until the comma or semicolon.
4811 SkipUntil(tok::comma, StopAtSemi);
4812 return;
4813 }
4814
4815 // If an identifier is present, consume and remember it.
4816 IdentifierInfo *Name = nullptr;
4817 SourceLocation NameLoc;
4818 if (Tok.is(tok::identifier)) {
4819 Name = Tok.getIdentifierInfo();
4820 NameLoc = ConsumeToken();
4821 }
4822
4823 if (!Name && ScopedEnumKWLoc.isValid()) {
4824 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4825 // declaration of a scoped enumeration.
4826 Diag(Tok, diag::err_scoped_enum_missing_identifier);
4827 ScopedEnumKWLoc = SourceLocation();
4828 IsScopedUsingClassTag = false;
4829 }
4830
4831 // Okay, end the suppression area. We'll decide whether to emit the
4832 // diagnostics in a second.
4833 if (shouldDelayDiagsInTag)
4834 diagsFromTag.done();
4835
4836 TypeResult BaseType;
4837 SourceRange BaseRange;
4838
4839 bool CanBeBitfield =
4840 getCurScope()->isClassScope() && ScopedEnumKWLoc.isInvalid() && Name;
4841
4842 // Parse the fixed underlying type.
4843 if (Tok.is(tok::colon)) {
4844 // This might be an enum-base or part of some unrelated enclosing context.
4845 //
4846 // 'enum E : base' is permitted in two circumstances:
4847 //
4848 // 1) As a defining-type-specifier, when followed by '{'.
4849 // 2) As the sole constituent of a complete declaration -- when DS is empty
4850 // and the next token is ';'.
4851 //
4852 // The restriction to defining-type-specifiers is important to allow parsing
4853 // a ? new enum E : int{}
4854 // _Generic(a, enum E : int{})
4855 // properly.
4856 //
4857 // One additional consideration applies:
4858 //
4859 // C++ [dcl.enum]p1:
4860 // A ':' following "enum nested-name-specifier[opt] identifier" within
4861 // the decl-specifier-seq of a member-declaration is parsed as part of
4862 // an enum-base.
4863 //
4864 // Other language modes supporting enumerations with fixed underlying types
4865 // do not have clear rules on this, so we disambiguate to determine whether
4866 // the tokens form a bit-field width or an enum-base.
4867
4868 if (CanBeBitfield && !isEnumBase(CanBeOpaqueEnumDeclaration)) {
4869 // Outside C++11, do not interpret the tokens as an enum-base if they do
4870 // not make sense as one. In C++11, it's an error if this happens.
4872 Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
4873 } else if (CanHaveEnumBase || !ColonIsSacred) {
4874 SourceLocation ColonLoc = ConsumeToken();
4875
4876 // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
4877 // because under -fms-extensions,
4878 // enum E : int *p;
4879 // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
4880 DeclSpec DS(AttrFactory);
4881 // enum-base is not assumed to be a type and therefore requires the
4882 // typename keyword [p0634r3].
4883 ParseSpecifierQualifierList(DS, ImplicitTypenameContext::No, AS,
4884 DeclSpecContext::DSC_type_specifier);
4885 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
4887 BaseType = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
4888
4889 BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
4890
4891 if (!getLangOpts().ObjC) {
4893 Diag(ColonLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type)
4894 << BaseRange;
4895 else if (getLangOpts().CPlusPlus)
4896 Diag(ColonLoc, diag::ext_cxx11_enum_fixed_underlying_type)
4897 << BaseRange;
4898 else if (getLangOpts().MicrosoftExt)
4899 Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
4900 << BaseRange;
4901 else
4902 Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
4903 << BaseRange;
4904 }
4905 }
4906 }
4907
4908 // There are four options here. If we have 'friend enum foo;' then this is a
4909 // friend declaration, and cannot have an accompanying definition. If we have
4910 // 'enum foo;', then this is a forward declaration. If we have
4911 // 'enum foo {...' then this is a definition. Otherwise we have something
4912 // like 'enum foo xyz', a reference.
4913 //
4914 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4915 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4916 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4917 //
4918 Sema::TagUseKind TUK;
4919 if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
4920 TUK = Sema::TUK_Reference;
4921 else if (Tok.is(tok::l_brace)) {
4922 if (DS.isFriendSpecified()) {
4923 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4925 ConsumeBrace();
4926 SkipUntil(tok::r_brace, StopAtSemi);
4927 // Discard any other definition-only pieces.
4928 attrs.clear();
4929 ScopedEnumKWLoc = SourceLocation();
4930 IsScopedUsingClassTag = false;
4931 BaseType = TypeResult();
4932 TUK = Sema::TUK_Friend;
4933 } else {
4935 }
4936 } else if (!isTypeSpecifier(DSC) &&
4937 (Tok.is(tok::semi) ||
4938 (Tok.isAtStartOfLine() &&
4939 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4940 // An opaque-enum-declaration is required to be standalone (no preceding or
4941 // following tokens in the declaration). Sema enforces this separately by
4942 // diagnosing anything else in the DeclSpec.
4944 if (Tok.isNot(tok::semi)) {
4945 // A semicolon was missing after this declaration. Diagnose and recover.
4946 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4947 PP.EnterToken(Tok, /*IsReinject=*/true);
4948 Tok.setKind(tok::semi);
4949 }
4950 } else {
4951 TUK = Sema::TUK_Reference;
4952 }
4953
4954 bool IsElaboratedTypeSpecifier =
4955 TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend;
4956
4957 // If this is an elaborated type specifier nested in a larger declaration,
4958 // and we delayed diagnostics before, just merge them into the current pool.
4959 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4960 diagsFromTag.redelay();
4961 }
4962
4963 MultiTemplateParamsArg TParams;
4964 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4965 TUK != Sema::TUK_Reference) {
4966 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4967 // Skip the rest of this declarator, up until the comma or semicolon.
4968 Diag(Tok, diag::err_enum_template);
4969 SkipUntil(tok::comma, StopAtSemi);
4970 return;
4971 }
4972
4973 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4974 // Enumerations can't be explicitly instantiated.
4975 DS.SetTypeSpecError();
4976 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4977 return;
4978 }
4979
4980 assert(TemplateInfo.TemplateParams && "no template parameters");
4981 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4982 TemplateInfo.TemplateParams->size());
4983 SS.setTemplateParamLists(TParams);
4984 }
4985
4986 if (!Name && TUK != Sema::TUK_Definition) {
4987 Diag(Tok, diag::err_enumerator_unnamed_no_def);
4988
4989 DS.SetTypeSpecError();
4990 // Skip the rest of this declarator, up until the comma or semicolon.
4991 SkipUntil(tok::comma, StopAtSemi);
4992 return;
4993 }
4994
4995 // An elaborated-type-specifier has a much more constrained grammar:
4996 //
4997 // 'enum' nested-name-specifier[opt] identifier
4998 //
4999 // If we parsed any other bits, reject them now.
5000 //
5001 // MSVC and (for now at least) Objective-C permit a full enum-specifier
5002 // or opaque-enum-declaration anywhere.
5003 if (IsElaboratedTypeSpecifier && !getLangOpts().MicrosoftExt &&
5004 !getLangOpts().ObjC) {
5005 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
5006 /*DiagnoseEmptyAttrs=*/true);
5007 if (BaseType.isUsable())
5008 Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
5009 << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
5010 else if (ScopedEnumKWLoc.isValid())
5011 Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
5012 << FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
5013 }
5014
5015 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
5016
5017 Sema::SkipBodyInfo SkipBody;
5018 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
5019 NextToken().is(tok::identifier))
5020 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
5021 NextToken().getIdentifierInfo(),
5022 NextToken().getLocation());
5023
5024 bool Owned = false;
5025 bool IsDependent = false;
5026 const char *PrevSpec = nullptr;
5027 unsigned DiagID;
5028 Decl *TagDecl =
5029 Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS,
5030 Name, NameLoc, attrs, AS, DS.getModulePrivateSpecLoc(),
5031 TParams, Owned, IsDependent, ScopedEnumKWLoc,
5032 IsScopedUsingClassTag,
5033 BaseType, DSC == DeclSpecContext::DSC_type_specifier,
5034 DSC == DeclSpecContext::DSC_template_param ||
5035 DSC == DeclSpecContext::DSC_template_type_arg,
5036 OffsetOfState, &SkipBody).get();
5037
5038 if (SkipBody.ShouldSkip) {
5039 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
5040
5041 BalancedDelimiterTracker T(*this, tok::l_brace);
5042 T.consumeOpen();
5043 T.skipToEnd();
5044
5045 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5046 NameLoc.isValid() ? NameLoc : StartLoc,
5047 PrevSpec, DiagID, TagDecl, Owned,
5048 Actions.getASTContext().getPrintingPolicy()))
5049 Diag(StartLoc, DiagID) << PrevSpec;
5050 return;
5051 }
5052
5053 if (IsDependent) {
5054 // This enum has a dependent nested-name-specifier. Handle it as a
5055 // dependent tag.
5056 if (!Name) {
5057 DS.SetTypeSpecError();
5058 Diag(Tok, diag::err_expected_type_name_after_typename);
5059 return;
5060 }
5061
5063 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
5064 if (Type.isInvalid()) {
5065 DS.SetTypeSpecError();
5066 return;
5067 }
5068
5069 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
5070 NameLoc.isValid() ? NameLoc : StartLoc,
5071 PrevSpec, DiagID, Type.get(),
5072 Actions.getASTContext().getPrintingPolicy()))
5073 Diag(StartLoc, DiagID) << PrevSpec;
5074
5075 return;
5076 }
5077
5078 if (!TagDecl) {
5079 // The action failed to produce an enumeration tag. If this is a
5080 // definition, consume the entire definition.
5081 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
5082 ConsumeBrace();
5083 SkipUntil(tok::r_brace, StopAtSemi);
5084 }
5085
5086 DS.SetTypeSpecError();
5087 return;
5088 }
5089
5090 if (Tok.is(tok::l_brace) && TUK == Sema::TUK_Definition) {
5091 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
5092 ParseEnumBody(StartLoc, D);
5093 if (SkipBody.CheckSameAsPrevious &&
5094 !Actions.ActOnDuplicateDefinition(TagDecl, SkipBody)) {
5095 DS.SetTypeSpecError();
5096 return;
5097 }
5098 }
5099
5100 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5101 NameLoc.isValid() ? NameLoc : StartLoc,
5102 PrevSpec, DiagID, TagDecl, Owned,
5103 Actions.getASTContext().getPrintingPolicy()))
5104 Diag(StartLoc, DiagID) << PrevSpec;
5105}
5106
5107/// ParseEnumBody - Parse a {} enclosed enumerator-list.
5108/// enumerator-list:
5109/// enumerator
5110/// enumerator-list ',' enumerator
5111/// enumerator:
5112/// enumeration-constant attributes[opt]
5113/// enumeration-constant attributes[opt] '=' constant-expression
5114/// enumeration-constant:
5115/// identifier
5116///
5117void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
5118 // Enter the scope of the enum body and start the definition.
5119 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
5121
5122 BalancedDelimiterTracker T(*this, tok::l_brace);
5123 T.consumeOpen();
5124
5125 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
5126 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
5127 Diag(Tok, diag::err_empty_enum);
5128
5129 SmallVector<Decl *, 32> EnumConstantDecls;
5130 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
5131
5132 Decl *LastEnumConstDecl = nullptr;
5133
5134 // Parse the enumerator-list.
5135 while (Tok.isNot(tok::r_brace)) {
5136 // Parse enumerator. If failed, try skipping till the start of the next
5137 // enumerator definition.
5138 if (Tok.isNot(tok::identifier)) {
5139 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
5140 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
5141 TryConsumeToken(tok::comma))
5142 continue;
5143 break;
5144 }
5145 IdentifierInfo *Ident = Tok.getIdentifierInfo();
5146 SourceLocation IdentLoc = ConsumeToken();
5147
5148 // If attributes exist after the enumerator, parse them.
5149 ParsedAttributes attrs(AttrFactory);
5150 MaybeParseGNUAttributes(attrs);
5151 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
5152 if (getLangOpts().CPlusPlus)
5154 ? diag::warn_cxx14_compat_ns_enum_attribute
5155 : diag::ext_ns_enum_attribute)
5156 << 1 /*enumerator*/;
5157 ParseCXX11Attributes(attrs);
5158 }
5159
5160 SourceLocation EqualLoc;
5161 ExprResult AssignedVal;
5162 EnumAvailabilityDiags.emplace_back(*this);
5163
5164 EnterExpressionEvaluationContext ConstantEvaluated(
5166 if (TryConsumeToken(tok::equal, EqualLoc)) {
5168 if (AssignedVal.isInvalid())
5169 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
5170 }
5171
5172 // Install the enumerator constant into EnumDecl.
5173 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
5174 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
5175 EqualLoc, AssignedVal.get());
5176 EnumAvailabilityDiags.back().done();
5177
5178 EnumConstantDecls.push_back(EnumConstDecl);
5179 LastEnumConstDecl = EnumConstDecl;
5180
5181 if (Tok.is(tok::identifier)) {
5182 // We're missing a comma between enumerators.
5184 Diag(Loc, diag::err_enumerator_list_missing_comma)
5185 << FixItHint::CreateInsertion(Loc, ", ");
5186 continue;
5187 }
5188
5189 // Emumerator definition must be finished, only comma or r_brace are
5190 // allowed here.
5191 SourceLocation CommaLoc;
5192 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
5193 if (EqualLoc.isValid())
5194 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
5195 << tok::comma;
5196 else
5197 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
5198 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
5199 if (TryConsumeToken(tok::comma, CommaLoc))
5200 continue;
5201 } else {
5202 break;
5203 }
5204 }
5205
5206 // If comma is followed by r_brace, emit appropriate warning.
5207 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
5209 Diag(CommaLoc, getLangOpts().CPlusPlus ?
5210 diag::ext_enumerator_list_comma_cxx :
5211 diag::ext_enumerator_list_comma_c)
5212 << FixItHint::CreateRemoval(CommaLoc);
5213 else if (getLangOpts().CPlusPlus11)
5214 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
5215 << FixItHint::CreateRemoval(CommaLoc);
5216 break;
5217 }
5218 }
5219
5220 // Eat the }.
5221 T.consumeClose();
5222
5223 // If attributes exist after the identifier list, parse them.
5224 ParsedAttributes attrs(AttrFactory);
5225 MaybeParseGNUAttributes(attrs);
5226
5227 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
5228 getCurScope(), attrs);
5229
5230 // Now handle enum constant availability diagnostics.
5231 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
5232 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
5234 EnumAvailabilityDiags[i].redelay();
5235 PD.complete(EnumConstantDecls[i]);
5236 }
5237
5238 EnumScope.Exit();
5239 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
5240
5241 // The next token must be valid after an enum definition. If not, a ';'
5242 // was probably forgotten.
5243 bool CanBeBitfield = getCurScope()->isClassScope();
5244 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
5245 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
5246 // Push this token back into the preprocessor and change our current token
5247 // to ';' so that the rest of the code recovers as though there were an
5248 // ';' after the definition.
5249 PP.EnterToken(Tok, /*IsReinject=*/true);
5250 Tok.setKind(tok::semi);
5251 }
5252}
5253
5254/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
5255/// is definitely a type-specifier. Return false if it isn't part of a type
5256/// specifier or if we're not sure.
5257bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
5258 switch (Tok.getKind()) {
5259 default: return false;
5260 // type-specifiers
5261 case tok::kw_short:
5262 case tok::kw_long:
5263 case tok::kw___int64:
5264 case tok::kw___int128:
5265 case tok::kw_signed:
5266 case tok::kw_unsigned:
5267 case tok::kw__Complex:
5268 case tok::kw__Imaginary:
5269 case tok::kw_void:
5270 case tok::kw_char:
5271 case tok::kw_wchar_t:
5272 case tok::kw_char8_t:
5273 case tok::kw_char16_t:
5274 case tok::kw_char32_t:
5275 case tok::kw_int:
5276 case tok::kw__ExtInt:
5277 case tok::kw__BitInt:
5278 case tok::kw___bf16:
5279 case tok::kw_half:
5280 case tok::kw_float:
5281 case tok::kw_double:
5282 case tok::kw__Accum:
5283 case tok::kw__Fract:
5284 case tok::kw__Float16:
5285 case tok::kw___float128:
5286 case tok::kw___ibm128:
5287 case tok::kw_bool:
5288 case tok::kw__Bool:
5289 case tok::kw__Decimal32:
5290 case tok::kw__Decimal64:
5291 case tok::kw__Decimal128:
5292 case tok::kw___vector:
5293#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5294#include "clang/Basic/OpenCLImageTypes.def"
5295
5296 // struct-or-union-specifier (C99) or class-specifier (C++)
5297 case tok::kw_class:
5298 case tok::kw_struct:
5299 case tok::kw___interface:
5300 case tok::kw_union:
5301 // enum-specifier
5302 case tok::kw_enum:
5303
5304 // typedef-name
5305 case tok::annot_typename:
5306 return true;
5307 }
5308}
5309
5310/// isTypeSpecifierQualifier - Return true if the current token could be the
5311/// start of a specifier-qualifier-list.
5312bool Parser::isTypeSpecifierQualifier() {
5313 switch (Tok.getKind()) {
5314 default: return false;
5315
5316 case tok::identifier: // foo::bar
5317 if (TryAltiVecVectorToken())
5318 return true;
5319 [[fallthrough]];
5320 case tok::kw_typename: // typename T::type
5321 // Annotate typenames and C++ scope specifiers. If we get one, just
5322 // recurse to handle whatever we get.
5324 return true;
5325 if (Tok.is(tok::identifier))
5326 return false;
5327 return isTypeSpecifierQualifier();
5328
5329 case tok::coloncolon: // ::foo::bar
5330 if (NextToken().is(tok::kw_new) || // ::new
5331 NextToken().is(tok::kw_delete)) // ::delete
5332 return false;
5333
5335 return true;
5336 return isTypeSpecifierQualifier();
5337
5338 // GNU attributes support.
5339 case tok::kw___attribute:
5340 // C2x/GNU typeof support.
5341 case tok::kw_typeof:
5342 case tok::kw_typeof_unqual:
5343
5344 // type-specifiers
5345 case tok::kw_short:
5346 case tok::kw_long:
5347 case tok::kw___int64:
5348 case tok::kw___int128:
5349 case tok::kw_signed:
5350 case tok::kw_unsigned:
5351 case tok::kw__Complex:
5352 case tok::kw__Imaginary:
5353 case tok::kw_void:
5354 case tok::kw_char:
5355 case tok::kw_wchar_t:
5356 case tok::kw_char8_t:
5357 case tok::kw_char16_t:
5358 case tok::kw_char32_t:
5359 case tok::kw_int:
5360 case tok::kw__ExtInt:
5361 case tok::kw__BitInt:
5362 case tok::kw_half:
5363 case tok::kw___bf16:
5364 case tok::kw_float:
5365 case tok::kw_double:
5366 case tok::kw__Accum:
5367 case tok::kw__Fract:
5368 case tok::kw__Float16:
5369 case tok::kw___float128:
5370 case tok::kw___ibm128:
5371 case tok::kw_bool:
5372 case tok::kw__Bool:
5373 case tok::kw__Decimal32:
5374 case tok::kw__Decimal64:
5375 case tok::kw__Decimal128:
5376 case tok::kw___vector:
5377#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5378#include "clang/Basic/OpenCLImageTypes.def"
5379
5380 // struct-or-union-specifier (C99) or class-specifier (C++)
5381 case tok::kw_class:
5382 case tok::kw_struct:
5383 case tok::kw___interface:
5384 case tok::kw_union:
5385 // enum-specifier
5386 case tok::kw_enum:
5387
5388 // type-qualifier
5389 case tok::kw_const:
5390 case tok::kw_volatile:
5391 case tok::kw_restrict:
5392 case tok::kw__Sat:
5393
5394 // Debugger support.
5395 case tok::kw___unknown_anytype:
5396
5397 // typedef-name
5398 case tok::annot_typename:
5399 return true;
5400
5401 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5402 case tok::less:
5403 return getLangOpts().ObjC;
5404
5405 case tok::kw___cdecl:
5406 case tok::kw___stdcall:
5407 case tok::kw___fastcall:
5408 case tok::kw___thiscall:
5409 case tok::kw___regcall:
5410 case tok::kw___vectorcall:
5411 case tok::kw___w64:
5412 case tok::kw___ptr64:
5413 case tok::kw___ptr32:
5414 case tok::kw___pascal:
5415 case tok::kw___unaligned:
5416
5417 case tok::kw__Nonnull:
5418 case tok::kw__Nullable:
5419 case tok::kw__Nullable_result:
5420 case tok::kw__Null_unspecified:
5421
5422 case tok::kw___kindof:
5423
5424 case tok::kw___private:
5425 case tok::kw___local:
5426 case tok::kw___global:
5427 case tok::kw___constant:
5428 case tok::kw___generic:
5429 case tok::kw___read_only:
5430 case tok::kw___read_write:
5431 case tok::kw___write_only:
5432 case tok::kw___funcref:
5433 case tok::kw_groupshared:
5434 return true;
5435
5436 case tok::kw_private:
5437 return getLangOpts().OpenCL;
5438
5439 // C11 _Atomic
5440 case tok::kw__Atomic:
5441 return true;
5442 }
5443}
5444
5445Parser::DeclGroupPtrTy Parser::ParseTopLevelStmtDecl() {
5446 assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode");
5447
5448 // Parse a top-level-stmt.
5449 Parser::StmtVector Stmts;
5450 ParsedStmtContext SubStmtCtx = ParsedStmtContext();
5451 Actions.PushFunctionScope();
5452 StmtResult R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
5453 Actions.PopFunctionScopeInfo();
5454 if (!R.isUsable())
5455 return nullptr;
5456
5457 SmallVector<Decl *, 2> DeclsInGroup;
5458 DeclsInGroup.push_back(Actions.ActOnTopLevelStmtDecl(R.get()));
5459 // Currently happens for things like -fms-extensions and use `__if_exists`.
5460 for (Stmt *S : Stmts)
5461 DeclsInGroup.push_back(Actions.ActOnTopLevelStmtDecl(S));
5462
5463 return Actions.BuildDeclaratorGroup(DeclsInGroup);
5464}
5465
5466/// isDeclarationSpecifier() - Return true if the current token is part of a
5467/// declaration specifier.
5468///
5469/// \param AllowImplicitTypename whether this is a context where T::type [T
5470/// dependent] can appear.
5471/// \param DisambiguatingWithExpression True to indicate that the purpose of
5472/// this check is to disambiguate between an expression and a declaration.
5473bool Parser::isDeclarationSpecifier(
5474 ImplicitTypenameContext AllowImplicitTypename,
5475 bool DisambiguatingWithExpression) {
5476 switch (Tok.getKind()) {
5477 default: return false;
5478
5479 // OpenCL 2.0 and later define this keyword.
5480 case tok::kw_pipe:
5481 return getLangOpts().OpenCL &&