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