clang 20.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"
29#include "clang/Sema/SemaCUDA.h"
32#include "clang/Sema/SemaObjC.h"
34#include "llvm/ADT/SmallSet.h"
35#include "llvm/ADT/SmallString.h"
36#include "llvm/ADT/StringSwitch.h"
37#include <optional>
38
39using namespace clang;
40
41//===----------------------------------------------------------------------===//
42// C99 6.7: Declarations.
43//===----------------------------------------------------------------------===//
44
45/// ParseTypeName
46/// type-name: [C99 6.7.6]
47/// specifier-qualifier-list abstract-declarator[opt]
48///
49/// Called type-id in C++.
51 AccessSpecifier AS, Decl **OwnedType,
52 ParsedAttributes *Attrs) {
53 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
54 if (DSC == DeclSpecContext::DSC_normal)
55 DSC = DeclSpecContext::DSC_type_specifier;
56
57 // Parse the common declaration-specifiers piece.
58 DeclSpec DS(AttrFactory);
59 if (Attrs)
60 DS.addAttributes(*Attrs);
61 ParseSpecifierQualifierList(DS, AS, DSC);
62 if (OwnedType)
63 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
64
65 // Move declspec attributes to ParsedAttributes
66 if (Attrs) {
68 for (ParsedAttr &AL : DS.getAttributes()) {
69 if (AL.isDeclspecAttribute())
70 ToBeMoved.push_back(&AL);
71 }
72
73 for (ParsedAttr *AL : ToBeMoved)
74 Attrs->takeOneFrom(DS.getAttributes(), AL);
75 }
76
77 // Parse the abstract-declarator, if present.
78 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), Context);
79 ParseDeclarator(DeclaratorInfo);
80 if (Range)
81 *Range = DeclaratorInfo.getSourceRange();
82
83 if (DeclaratorInfo.isInvalidType())
84 return true;
85
86 return Actions.ActOnTypeName(DeclaratorInfo);
87}
88
89/// Normalizes an attribute name by dropping prefixed and suffixed __.
90static StringRef normalizeAttrName(StringRef Name) {
91 if (Name.size() >= 4 && Name.starts_with("__") && Name.ends_with("__"))
92 return Name.drop_front(2).drop_back(2);
93 return Name;
94}
95
96/// returns true iff attribute is annotated with `LateAttrParseExperimentalExt`
97/// in `Attr.td`.
99#define CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST
100 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
101#include "clang/Parse/AttrParserStringSwitches.inc"
102 .Default(false);
103#undef CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST
104}
105
106/// returns true iff attribute is annotated with `LateAttrParseStandard` in
107/// `Attr.td`.
109#define CLANG_ATTR_LATE_PARSED_LIST
110 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
111#include "clang/Parse/AttrParserStringSwitches.inc"
112 .Default(false);
113#undef CLANG_ATTR_LATE_PARSED_LIST
114}
115
116/// Check if the a start and end source location expand to the same macro.
118 SourceLocation EndLoc) {
119 if (!StartLoc.isMacroID() || !EndLoc.isMacroID())
120 return false;
121
123 if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
124 return false;
125
126 bool AttrStartIsInMacro =
128 bool AttrEndIsInMacro =
130 return AttrStartIsInMacro && AttrEndIsInMacro;
131}
132
133void Parser::ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
134 LateParsedAttrList *LateAttrs) {
135 bool MoreToParse;
136 do {
137 // Assume there's nothing left to parse, but if any attributes are in fact
138 // parsed, loop to ensure all specified attribute combinations are parsed.
139 MoreToParse = false;
140 if (WhichAttrKinds & PAKM_CXX11)
141 MoreToParse |= MaybeParseCXX11Attributes(Attrs);
142 if (WhichAttrKinds & PAKM_GNU)
143 MoreToParse |= MaybeParseGNUAttributes(Attrs, LateAttrs);
144 if (WhichAttrKinds & PAKM_Declspec)
145 MoreToParse |= MaybeParseMicrosoftDeclSpecs(Attrs);
146 } while (MoreToParse);
147}
148
149/// ParseSingleGNUAttribute - Parse a single GNU attribute.
150///
151/// [GNU] attrib:
152/// empty
153/// attrib-name
154/// attrib-name '(' identifier ')'
155/// attrib-name '(' identifier ',' nonempty-expr-list ')'
156/// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
157///
158/// [GNU] attrib-name:
159/// identifier
160/// typespec
161/// typequal
162/// storageclass
163bool Parser::ParseSingleGNUAttribute(ParsedAttributes &Attrs,
164 SourceLocation &EndLoc,
165 LateParsedAttrList *LateAttrs,
166 Declarator *D) {
167 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
168 if (!AttrName)
169 return true;
170
171 SourceLocation AttrNameLoc = ConsumeToken();
172
173 if (Tok.isNot(tok::l_paren)) {
174 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
175 ParsedAttr::Form::GNU());
176 return false;
177 }
178
179 bool LateParse = false;
180 if (!LateAttrs)
181 LateParse = false;
182 else if (LateAttrs->lateAttrParseExperimentalExtOnly()) {
183 // The caller requested that this attribute **only** be late
184 // parsed for `LateAttrParseExperimentalExt` attributes. This will
185 // only be late parsed if the experimental language option is enabled.
186 LateParse = getLangOpts().ExperimentalLateParseAttributes &&
188 } else {
189 // The caller did not restrict late parsing to only
190 // `LateAttrParseExperimentalExt` attributes so late parse
191 // both `LateAttrParseStandard` and `LateAttrParseExperimentalExt`
192 // attributes.
193 LateParse = IsAttributeLateParsedExperimentalExt(*AttrName) ||
195 }
196
197 // Handle "parameterized" attributes
198 if (!LateParse) {
199 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, &EndLoc, nullptr,
200 SourceLocation(), ParsedAttr::Form::GNU(), D);
201 return false;
202 }
203
204 // Handle attributes with arguments that require late parsing.
205 LateParsedAttribute *LA =
206 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
207 LateAttrs->push_back(LA);
208
209 // Attributes in a class are parsed at the end of the class, along
210 // with other late-parsed declarations.
211 if (!ClassStack.empty() && !LateAttrs->parseSoon())
212 getCurrentClass().LateParsedDeclarations.push_back(LA);
213
214 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
215 // recursively consumes balanced parens.
216 LA->Toks.push_back(Tok);
217 ConsumeParen();
218 // Consume everything up to and including the matching right parens.
219 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
220
221 Token Eof;
222 Eof.startToken();
223 Eof.setLocation(Tok.getLocation());
224 LA->Toks.push_back(Eof);
225
226 return false;
227}
228
229/// ParseGNUAttributes - Parse a non-empty attributes list.
230///
231/// [GNU] attributes:
232/// attribute
233/// attributes attribute
234///
235/// [GNU] attribute:
236/// '__attribute__' '(' '(' attribute-list ')' ')'
237///
238/// [GNU] attribute-list:
239/// attrib
240/// attribute_list ',' attrib
241///
242/// [GNU] attrib:
243/// empty
244/// attrib-name
245/// attrib-name '(' identifier ')'
246/// attrib-name '(' identifier ',' nonempty-expr-list ')'
247/// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
248///
249/// [GNU] attrib-name:
250/// identifier
251/// typespec
252/// typequal
253/// storageclass
254///
255/// Whether an attribute takes an 'identifier' is determined by the
256/// attrib-name. GCC's behavior here is not worth imitating:
257///
258/// * In C mode, if the attribute argument list starts with an identifier
259/// followed by a ',' or an ')', and the identifier doesn't resolve to
260/// a type, it is parsed as an identifier. If the attribute actually
261/// wanted an expression, it's out of luck (but it turns out that no
262/// attributes work that way, because C constant expressions are very
263/// limited).
264/// * In C++ mode, if the attribute argument list starts with an identifier,
265/// and the attribute *wants* an identifier, it is parsed as an identifier.
266/// At block scope, any additional tokens between the identifier and the
267/// ',' or ')' are ignored, otherwise they produce a parse error.
268///
269/// We follow the C++ model, but don't allow junk after the identifier.
270void Parser::ParseGNUAttributes(ParsedAttributes &Attrs,
271 LateParsedAttrList *LateAttrs, Declarator *D) {
272 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
273
274 SourceLocation StartLoc = Tok.getLocation();
275 SourceLocation EndLoc = StartLoc;
276
277 while (Tok.is(tok::kw___attribute)) {
278 SourceLocation AttrTokLoc = ConsumeToken();
279 unsigned OldNumAttrs = Attrs.size();
280 unsigned OldNumLateAttrs = LateAttrs ? LateAttrs->size() : 0;
281
282 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
283 "attribute")) {
284 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
285 return;
286 }
287 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
288 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
289 return;
290 }
291 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
292 do {
293 // Eat preceeding commas to allow __attribute__((,,,foo))
294 while (TryConsumeToken(tok::comma))
295 ;
296
297 // Expect an identifier or declaration specifier (const, int, etc.)
298 if (Tok.isAnnotation())
299 break;
300 if (Tok.is(tok::code_completion)) {
301 cutOffParsing();
304 break;
305 }
306
307 if (ParseSingleGNUAttribute(Attrs, EndLoc, LateAttrs, D))
308 break;
309 } while (Tok.is(tok::comma));
310
311 if (ExpectAndConsume(tok::r_paren))
312 SkipUntil(tok::r_paren, StopAtSemi);
314 if (ExpectAndConsume(tok::r_paren))
315 SkipUntil(tok::r_paren, StopAtSemi);
316 EndLoc = Loc;
317
318 // If this was declared in a macro, attach the macro IdentifierInfo to the
319 // parsed attribute.
320 auto &SM = PP.getSourceManager();
321 if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
322 FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
323 CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
324 StringRef FoundName =
325 Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
326 IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
327
328 for (unsigned i = OldNumAttrs; i < Attrs.size(); ++i)
329 Attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
330
331 if (LateAttrs) {
332 for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); ++i)
333 (*LateAttrs)[i]->MacroII = MacroII;
334 }
335 }
336 }
337
338 Attrs.Range = SourceRange(StartLoc, EndLoc);
339}
340
341/// Determine whether the given attribute has an identifier argument.
342static bool attributeHasIdentifierArg(const llvm::Triple &T,
343 const IdentifierInfo &II,
344 ParsedAttr::Syntax Syntax,
345 IdentifierInfo *ScopeName) {
346#define CLANG_ATTR_IDENTIFIER_ARG_LIST
347 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
348#include "clang/Parse/AttrParserStringSwitches.inc"
349 .Default(false);
350#undef CLANG_ATTR_IDENTIFIER_ARG_LIST
351}
352
353/// Determine whether the given attribute has string arguments.
355attributeStringLiteralListArg(const llvm::Triple &T, const IdentifierInfo &II,
356 ParsedAttr::Syntax Syntax,
357 IdentifierInfo *ScopeName) {
358#define CLANG_ATTR_STRING_LITERAL_ARG_LIST
359 return llvm::StringSwitch<uint32_t>(normalizeAttrName(II.getName()))
360#include "clang/Parse/AttrParserStringSwitches.inc"
361 .Default(0);
362#undef CLANG_ATTR_STRING_LITERAL_ARG_LIST
363}
364
365/// Determine whether the given attribute has a variadic identifier argument.
367 ParsedAttr::Syntax Syntax,
368 IdentifierInfo *ScopeName) {
369#define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
370 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
371#include "clang/Parse/AttrParserStringSwitches.inc"
372 .Default(false);
373#undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
374}
375
376/// Determine whether the given attribute treats kw_this as an identifier.
378 ParsedAttr::Syntax Syntax,
379 IdentifierInfo *ScopeName) {
380#define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
381 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
382#include "clang/Parse/AttrParserStringSwitches.inc"
383 .Default(false);
384#undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
385}
386
387/// Determine if an attribute accepts parameter packs.
389 ParsedAttr::Syntax Syntax,
390 IdentifierInfo *ScopeName) {
391#define CLANG_ATTR_ACCEPTS_EXPR_PACK
392 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
393#include "clang/Parse/AttrParserStringSwitches.inc"
394 .Default(false);
395#undef CLANG_ATTR_ACCEPTS_EXPR_PACK
396}
397
398/// Determine whether the given attribute parses a type argument.
400 ParsedAttr::Syntax Syntax,
401 IdentifierInfo *ScopeName) {
402#define CLANG_ATTR_TYPE_ARG_LIST
403 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
404#include "clang/Parse/AttrParserStringSwitches.inc"
405 .Default(false);
406#undef CLANG_ATTR_TYPE_ARG_LIST
407}
408
409/// Determine whether the given attribute takes a strict identifier argument.
411 ParsedAttr::Syntax Syntax,
412 IdentifierInfo *ScopeName) {
413#define CLANG_ATTR_STRICT_IDENTIFIER_ARG_LIST
414 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
415#include "clang/Parse/AttrParserStringSwitches.inc"
416 .Default(false);
417#undef CLANG_ATTR_STRICT_IDENTIFIER_ARG_LIST
418}
419
420/// Determine whether the given attribute requires parsing its arguments
421/// in an unevaluated context or not.
423 ParsedAttr::Syntax Syntax,
424 IdentifierInfo *ScopeName) {
425#define CLANG_ATTR_ARG_CONTEXT_LIST
426 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
427#include "clang/Parse/AttrParserStringSwitches.inc"
428 .Default(false);
429#undef CLANG_ATTR_ARG_CONTEXT_LIST
430}
431
432IdentifierLoc *Parser::ParseIdentifierLoc() {
433 assert(Tok.is(tok::identifier) && "expected an identifier");
435 Tok.getLocation(),
436 Tok.getIdentifierInfo());
437 ConsumeToken();
438 return IL;
439}
440
441void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
442 SourceLocation AttrNameLoc,
443 ParsedAttributes &Attrs,
444 IdentifierInfo *ScopeName,
445 SourceLocation ScopeLoc,
446 ParsedAttr::Form Form) {
447 BalancedDelimiterTracker Parens(*this, tok::l_paren);
448 Parens.consumeOpen();
449
451 if (Tok.isNot(tok::r_paren))
452 T = ParseTypeName();
453
454 if (Parens.consumeClose())
455 return;
456
457 if (T.isInvalid())
458 return;
459
460 if (T.isUsable())
461 Attrs.addNewTypeAttr(&AttrName,
462 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
463 ScopeName, ScopeLoc, T.get(), Form);
464 else
465 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
466 ScopeName, ScopeLoc, nullptr, 0, Form);
467}
468
470Parser::ParseUnevaluatedStringInAttribute(const IdentifierInfo &AttrName) {
471 if (Tok.is(tok::l_paren)) {
472 BalancedDelimiterTracker Paren(*this, tok::l_paren);
473 Paren.consumeOpen();
474 ExprResult Res = ParseUnevaluatedStringInAttribute(AttrName);
475 Paren.consumeClose();
476 return Res;
477 }
478 if (!isTokenStringLiteral()) {
479 Diag(Tok.getLocation(), diag::err_expected_string_literal)
480 << /*in attribute...*/ 4 << AttrName.getName();
481 return ExprError();
482 }
484}
485
486bool Parser::ParseAttributeArgumentList(
487 const IdentifierInfo &AttrName, SmallVectorImpl<Expr *> &Exprs,
488 ParsedAttributeArgumentsProperties ArgsProperties) {
489 bool SawError = false;
490 unsigned Arg = 0;
491 while (true) {
493 if (ArgsProperties.isStringLiteralArg(Arg)) {
494 Expr = ParseUnevaluatedStringInAttribute(AttrName);
495 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
496 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
497 Expr = ParseBraceInitializer();
498 } else {
500 }
502
503 if (Tok.is(tok::ellipsis))
504 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
505 else if (Tok.is(tok::code_completion)) {
506 // There's nothing to suggest in here as we parsed a full expression.
507 // Instead fail and propagate the error since caller might have something
508 // the suggest, e.g. signature help in function call. Note that this is
509 // performed before pushing the \p Expr, so that signature help can report
510 // current argument correctly.
511 SawError = true;
512 cutOffParsing();
513 break;
514 }
515
516 if (Expr.isInvalid()) {
517 SawError = true;
518 break;
519 }
520
521 if (Actions.DiagnoseUnexpandedParameterPack(Expr.get())) {
522 SawError = true;
523 break;
524 }
525
526 Exprs.push_back(Expr.get());
527
528 if (Tok.isNot(tok::comma))
529 break;
530 // Move to the next argument, remember where the comma was.
531 Token Comma = Tok;
532 ConsumeToken();
533 checkPotentialAngleBracketDelimiter(Comma);
534 Arg++;
535 }
536
537 if (SawError) {
538 // Ensure typos get diagnosed when errors were encountered while parsing the
539 // expression list.
540 for (auto &E : Exprs) {
542 if (Expr.isUsable())
543 E = Expr.get();
544 }
545 }
546 return SawError;
547}
548
549unsigned Parser::ParseAttributeArgsCommon(
550 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
551 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
552 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
553 // Ignore the left paren location for now.
554 ConsumeParen();
555
556 bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(
557 *AttrName, Form.getSyntax(), ScopeName);
558 bool AttributeIsTypeArgAttr =
559 attributeIsTypeArgAttr(*AttrName, Form.getSyntax(), ScopeName);
560 bool AttributeHasVariadicIdentifierArg =
561 attributeHasVariadicIdentifierArg(*AttrName, Form.getSyntax(), ScopeName);
562
563 // Interpret "kw_this" as an identifier if the attributed requests it.
564 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
565 Tok.setKind(tok::identifier);
566
567 ArgsVector ArgExprs;
568 if (Tok.is(tok::identifier)) {
569 // If this attribute wants an 'identifier' argument, make it so.
570 bool IsIdentifierArg =
571 AttributeHasVariadicIdentifierArg ||
572 attributeHasIdentifierArg(getTargetInfo().getTriple(), *AttrName,
573 Form.getSyntax(), ScopeName);
574 ParsedAttr::Kind AttrKind =
575 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
576
577 // If we don't know how to parse this attribute, but this is the only
578 // token in this argument, assume it's meant to be an identifier.
579 if (AttrKind == ParsedAttr::UnknownAttribute ||
580 AttrKind == ParsedAttr::IgnoredAttribute) {
581 const Token &Next = NextToken();
582 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
583 }
584
585 if (IsIdentifierArg)
586 ArgExprs.push_back(ParseIdentifierLoc());
587 }
588
589 ParsedType TheParsedType;
590 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
591 // Eat the comma.
592 if (!ArgExprs.empty())
593 ConsumeToken();
594
595 if (AttributeIsTypeArgAttr) {
596 // FIXME: Multiple type arguments are not implemented.
598 if (T.isInvalid()) {
599 SkipUntil(tok::r_paren, StopAtSemi);
600 return 0;
601 }
602 if (T.isUsable())
603 TheParsedType = T.get();
604 } else if (AttributeHasVariadicIdentifierArg ||
606 ScopeName)) {
607 // Parse variadic identifier arg. This can either consume identifiers or
608 // expressions. Variadic identifier args do not support parameter packs
609 // because those are typically used for attributes with enumeration
610 // arguments, and those enumerations are not something the user could
611 // express via a pack.
612 do {
613 // Interpret "kw_this" as an identifier if the attributed requests it.
614 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
615 Tok.setKind(tok::identifier);
616
617 ExprResult ArgExpr;
618 if (Tok.is(tok::identifier)) {
619 ArgExprs.push_back(ParseIdentifierLoc());
620 } else {
621 bool Uneval = attributeParsedArgsUnevaluated(
622 *AttrName, Form.getSyntax(), ScopeName);
624 Actions,
627 nullptr,
629
630 ExprResult ArgExpr(
632
633 if (ArgExpr.isInvalid()) {
634 SkipUntil(tok::r_paren, StopAtSemi);
635 return 0;
636 }
637 ArgExprs.push_back(ArgExpr.get());
638 }
639 // Eat the comma, move to the next argument
640 } while (TryConsumeToken(tok::comma));
641 } else {
642 // General case. Parse all available expressions.
643 bool Uneval = attributeParsedArgsUnevaluated(*AttrName, Form.getSyntax(),
644 ScopeName);
646 Actions,
649 nullptr,
651 EK_AttrArgument);
652
653 ExprVector ParsedExprs;
655 attributeStringLiteralListArg(getTargetInfo().getTriple(), *AttrName,
656 Form.getSyntax(), ScopeName);
657 if (ParseAttributeArgumentList(*AttrName, ParsedExprs, ArgProperties)) {
658 SkipUntil(tok::r_paren, StopAtSemi);
659 return 0;
660 }
661
662 // Pack expansion must currently be explicitly supported by an attribute.
663 for (size_t I = 0; I < ParsedExprs.size(); ++I) {
664 if (!isa<PackExpansionExpr>(ParsedExprs[I]))
665 continue;
666
667 if (!attributeAcceptsExprPack(*AttrName, Form.getSyntax(), ScopeName)) {
668 Diag(Tok.getLocation(),
669 diag::err_attribute_argument_parm_pack_not_supported)
670 << AttrName;
671 SkipUntil(tok::r_paren, StopAtSemi);
672 return 0;
673 }
674 }
675
676 ArgExprs.insert(ArgExprs.end(), ParsedExprs.begin(), ParsedExprs.end());
677 }
678 }
679
680 SourceLocation RParen = Tok.getLocation();
681 if (!ExpectAndConsume(tok::r_paren)) {
682 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
683
684 if (AttributeIsTypeArgAttr && !TheParsedType.get().isNull()) {
685 Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
686 ScopeName, ScopeLoc, TheParsedType, Form);
687 } else {
688 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
689 ArgExprs.data(), ArgExprs.size(), Form);
690 }
691 }
692
693 if (EndLoc)
694 *EndLoc = RParen;
695
696 return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
697}
698
699/// Parse the arguments to a parameterized GNU attribute or
700/// a C++11 attribute in "gnu" namespace.
701void Parser::ParseGNUAttributeArgs(
702 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
703 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
704 SourceLocation ScopeLoc, ParsedAttr::Form Form, Declarator *D) {
705
706 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
707
708 ParsedAttr::Kind AttrKind =
709 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
710
711 if (AttrKind == ParsedAttr::AT_Availability) {
712 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
713 ScopeLoc, Form);
714 return;
715 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
716 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
717 ScopeName, ScopeLoc, Form);
718 return;
719 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
720 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
721 ScopeName, ScopeLoc, Form);
722 return;
723 } else if (AttrKind == ParsedAttr::AT_SwiftNewType) {
724 ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
725 ScopeLoc, Form);
726 return;
727 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
728 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
729 ScopeName, ScopeLoc, Form);
730 return;
731 } else if (attributeIsTypeArgAttr(*AttrName, Form.getSyntax(), ScopeName)) {
732 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, ScopeName,
733 ScopeLoc, Form);
734 return;
735 } else if (AttrKind == ParsedAttr::AT_CountedBy ||
736 AttrKind == ParsedAttr::AT_CountedByOrNull ||
737 AttrKind == ParsedAttr::AT_SizedBy ||
738 AttrKind == ParsedAttr::AT_SizedByOrNull) {
739 ParseBoundsAttribute(*AttrName, AttrNameLoc, Attrs, ScopeName, ScopeLoc,
740 Form);
741 return;
742 } else if (AttrKind == ParsedAttr::AT_CXXAssume) {
743 ParseCXXAssumeAttributeArg(Attrs, AttrName, AttrNameLoc, EndLoc, Form);
744 return;
745 }
746
747 // These may refer to the function arguments, but need to be parsed early to
748 // participate in determining whether it's a redeclaration.
749 std::optional<ParseScope> PrototypeScope;
750 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
751 D && D->isFunctionDeclarator()) {
752 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
753 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
756 for (unsigned i = 0; i != FTI.NumParams; ++i) {
757 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
759 }
760 }
761
762 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
763 ScopeLoc, Form);
764}
765
766unsigned Parser::ParseClangAttributeArgs(
767 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
768 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
769 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
770 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
771
772 ParsedAttr::Kind AttrKind =
773 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
774
775 switch (AttrKind) {
776 default:
777 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
778 ScopeName, ScopeLoc, Form);
779 case ParsedAttr::AT_ExternalSourceSymbol:
780 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
781 ScopeName, ScopeLoc, Form);
782 break;
783 case ParsedAttr::AT_Availability:
784 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
785 ScopeLoc, Form);
786 break;
787 case ParsedAttr::AT_ObjCBridgeRelated:
788 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
789 ScopeName, ScopeLoc, Form);
790 break;
791 case ParsedAttr::AT_SwiftNewType:
792 ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
793 ScopeLoc, Form);
794 break;
795 case ParsedAttr::AT_TypeTagForDatatype:
796 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
797 ScopeName, ScopeLoc, Form);
798 break;
799
800 case ParsedAttr::AT_CXXAssume:
801 ParseCXXAssumeAttributeArg(Attrs, AttrName, AttrNameLoc, EndLoc, Form);
802 break;
803 }
804 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
805}
806
807bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
808 SourceLocation AttrNameLoc,
809 ParsedAttributes &Attrs) {
810 unsigned ExistingAttrs = Attrs.size();
811
812 // If the attribute isn't known, we will not attempt to parse any
813 // arguments.
816 // Eat the left paren, then skip to the ending right paren.
817 ConsumeParen();
818 SkipUntil(tok::r_paren);
819 return false;
820 }
821
822 SourceLocation OpenParenLoc = Tok.getLocation();
823
824 if (AttrName->getName() == "property") {
825 // The property declspec is more complex in that it can take one or two
826 // assignment expressions as a parameter, but the lhs of the assignment
827 // must be named get or put.
828
829 BalancedDelimiterTracker T(*this, tok::l_paren);
830 T.expectAndConsume(diag::err_expected_lparen_after,
831 AttrName->getNameStart(), tok::r_paren);
832
833 enum AccessorKind {
834 AK_Invalid = -1,
835 AK_Put = 0,
836 AK_Get = 1 // indices into AccessorNames
837 };
838 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
839 bool HasInvalidAccessor = false;
840
841 // Parse the accessor specifications.
842 while (true) {
843 // Stop if this doesn't look like an accessor spec.
844 if (!Tok.is(tok::identifier)) {
845 // If the user wrote a completely empty list, use a special diagnostic.
846 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
847 AccessorNames[AK_Put] == nullptr &&
848 AccessorNames[AK_Get] == nullptr) {
849 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
850 break;
851 }
852
853 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
854 break;
855 }
856
857 AccessorKind Kind;
858 SourceLocation KindLoc = Tok.getLocation();
859 StringRef KindStr = Tok.getIdentifierInfo()->getName();
860 if (KindStr == "get") {
861 Kind = AK_Get;
862 } else if (KindStr == "put") {
863 Kind = AK_Put;
864
865 // Recover from the common mistake of using 'set' instead of 'put'.
866 } else if (KindStr == "set") {
867 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
868 << FixItHint::CreateReplacement(KindLoc, "put");
869 Kind = AK_Put;
870
871 // Handle the mistake of forgetting the accessor kind by skipping
872 // this accessor.
873 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
874 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
875 ConsumeToken();
876 HasInvalidAccessor = true;
877 goto next_property_accessor;
878
879 // Otherwise, complain about the unknown accessor kind.
880 } else {
881 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
882 HasInvalidAccessor = true;
883 Kind = AK_Invalid;
884
885 // Try to keep parsing unless it doesn't look like an accessor spec.
886 if (!NextToken().is(tok::equal))
887 break;
888 }
889
890 // Consume the identifier.
891 ConsumeToken();
892
893 // Consume the '='.
894 if (!TryConsumeToken(tok::equal)) {
895 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
896 << KindStr;
897 break;
898 }
899
900 // Expect the method name.
901 if (!Tok.is(tok::identifier)) {
902 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
903 break;
904 }
905
906 if (Kind == AK_Invalid) {
907 // Just drop invalid accessors.
908 } else if (AccessorNames[Kind] != nullptr) {
909 // Complain about the repeated accessor, ignore it, and keep parsing.
910 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
911 } else {
912 AccessorNames[Kind] = Tok.getIdentifierInfo();
913 }
914 ConsumeToken();
915
916 next_property_accessor:
917 // Keep processing accessors until we run out.
918 if (TryConsumeToken(tok::comma))
919 continue;
920
921 // If we run into the ')', stop without consuming it.
922 if (Tok.is(tok::r_paren))
923 break;
924
925 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
926 break;
927 }
928
929 // Only add the property attribute if it was well-formed.
930 if (!HasInvalidAccessor)
931 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
932 AccessorNames[AK_Get], AccessorNames[AK_Put],
933 ParsedAttr::Form::Declspec());
934 T.skipToEnd();
935 return !HasInvalidAccessor;
936 }
937
938 unsigned NumArgs =
939 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
940 SourceLocation(), ParsedAttr::Form::Declspec());
941
942 // If this attribute's args were parsed, and it was expected to have
943 // arguments but none were provided, emit a diagnostic.
944 if (ExistingAttrs < Attrs.size() && Attrs.back().getMaxArgs() && !NumArgs) {
945 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
946 return false;
947 }
948 return true;
949}
950
951/// [MS] decl-specifier:
952/// __declspec ( extended-decl-modifier-seq )
953///
954/// [MS] extended-decl-modifier-seq:
955/// extended-decl-modifier[opt]
956/// extended-decl-modifier extended-decl-modifier-seq
957void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
958 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
959 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
960
961 SourceLocation StartLoc = Tok.getLocation();
962 SourceLocation EndLoc = StartLoc;
963
964 while (Tok.is(tok::kw___declspec)) {
965 ConsumeToken();
966 BalancedDelimiterTracker T(*this, tok::l_paren);
967 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
968 tok::r_paren))
969 return;
970
971 // An empty declspec is perfectly legal and should not warn. Additionally,
972 // you can specify multiple attributes per declspec.
973 while (Tok.isNot(tok::r_paren)) {
974 // Attribute not present.
975 if (TryConsumeToken(tok::comma))
976 continue;
977
978 if (Tok.is(tok::code_completion)) {
979 cutOffParsing();
982 return;
983 }
984
985 // We expect either a well-known identifier or a generic string. Anything
986 // else is a malformed declspec.
987 bool IsString = Tok.getKind() == tok::string_literal;
988 if (!IsString && Tok.getKind() != tok::identifier &&
989 Tok.getKind() != tok::kw_restrict) {
990 Diag(Tok, diag::err_ms_declspec_type);
991 T.skipToEnd();
992 return;
993 }
994
995 IdentifierInfo *AttrName;
996 SourceLocation AttrNameLoc;
997 if (IsString) {
998 SmallString<8> StrBuffer;
999 bool Invalid = false;
1000 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
1001 if (Invalid) {
1002 T.skipToEnd();
1003 return;
1004 }
1005 AttrName = PP.getIdentifierInfo(Str);
1006 AttrNameLoc = ConsumeStringToken();
1007 } else {
1008 AttrName = Tok.getIdentifierInfo();
1009 AttrNameLoc = ConsumeToken();
1010 }
1011
1012 bool AttrHandled = false;
1013
1014 // Parse attribute arguments.
1015 if (Tok.is(tok::l_paren))
1016 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
1017 else if (AttrName->getName() == "property")
1018 // The property attribute must have an argument list.
1019 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
1020 << AttrName->getName();
1021
1022 if (!AttrHandled)
1023 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1024 ParsedAttr::Form::Declspec());
1025 }
1026 T.consumeClose();
1027 EndLoc = T.getCloseLocation();
1028 }
1029
1030 Attrs.Range = SourceRange(StartLoc, EndLoc);
1031}
1032
1033void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
1034 // Treat these like attributes
1035 while (true) {
1036 auto Kind = Tok.getKind();
1037 switch (Kind) {
1038 case tok::kw___fastcall:
1039 case tok::kw___stdcall:
1040 case tok::kw___thiscall:
1041 case tok::kw___regcall:
1042 case tok::kw___cdecl:
1043 case tok::kw___vectorcall:
1044 case tok::kw___ptr64:
1045 case tok::kw___w64:
1046 case tok::kw___ptr32:
1047 case tok::kw___sptr:
1048 case tok::kw___uptr: {
1049 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1050 SourceLocation AttrNameLoc = ConsumeToken();
1051 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1052 Kind);
1053 break;
1054 }
1055 default:
1056 return;
1057 }
1058 }
1059}
1060
1061void Parser::ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &attrs) {
1062 assert(Tok.is(tok::kw___funcref));
1063 SourceLocation StartLoc = Tok.getLocation();
1064 if (!getTargetInfo().getTriple().isWasm()) {
1065 ConsumeToken();
1066 Diag(StartLoc, diag::err_wasm_funcref_not_wasm);
1067 return;
1068 }
1069
1070 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1071 SourceLocation AttrNameLoc = ConsumeToken();
1072 attrs.addNew(AttrName, AttrNameLoc, /*ScopeName=*/nullptr,
1073 /*ScopeLoc=*/SourceLocation{}, /*Args=*/nullptr, /*numArgs=*/0,
1074 tok::kw___funcref);
1075}
1076
1077void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
1078 SourceLocation StartLoc = Tok.getLocation();
1079 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
1080
1081 if (EndLoc.isValid()) {
1082 SourceRange Range(StartLoc, EndLoc);
1083 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
1084 }
1085}
1086
1087SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
1088 SourceLocation EndLoc;
1089
1090 while (true) {
1091 switch (Tok.getKind()) {
1092 case tok::kw_const:
1093 case tok::kw_volatile:
1094 case tok::kw___fastcall:
1095 case tok::kw___stdcall:
1096 case tok::kw___thiscall:
1097 case tok::kw___cdecl:
1098 case tok::kw___vectorcall:
1099 case tok::kw___ptr32:
1100 case tok::kw___ptr64:
1101 case tok::kw___w64:
1102 case tok::kw___unaligned:
1103 case tok::kw___sptr:
1104 case tok::kw___uptr:
1105 EndLoc = ConsumeToken();
1106 break;
1107 default:
1108 return EndLoc;
1109 }
1110 }
1111}
1112
1113void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
1114 // Treat these like attributes
1115 while (Tok.is(tok::kw___pascal)) {
1116 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1117 SourceLocation AttrNameLoc = ConsumeToken();
1118 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1119 tok::kw___pascal);
1120 }
1121}
1122
1123void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
1124 // Treat these like attributes
1125 while (Tok.is(tok::kw___kernel)) {
1126 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1127 SourceLocation AttrNameLoc = ConsumeToken();
1128 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1129 tok::kw___kernel);
1130 }
1131}
1132
1133void Parser::ParseCUDAFunctionAttributes(ParsedAttributes &attrs) {
1134 while (Tok.is(tok::kw___noinline__)) {
1135 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1136 SourceLocation AttrNameLoc = ConsumeToken();
1137 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1138 tok::kw___noinline__);
1139 }
1140}
1141
1142void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
1143 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1144 SourceLocation AttrNameLoc = Tok.getLocation();
1145 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1146 Tok.getKind());
1147}
1148
1149bool Parser::isHLSLQualifier(const Token &Tok) const {
1150 return Tok.is(tok::kw_groupshared);
1151}
1152
1153void Parser::ParseHLSLQualifiers(ParsedAttributes &Attrs) {
1154 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1155 auto Kind = Tok.getKind();
1156 SourceLocation AttrNameLoc = ConsumeToken();
1157 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, Kind);
1158}
1159
1160void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
1161 // Treat these like attributes, even though they're type specifiers.
1162 while (true) {
1163 auto Kind = Tok.getKind();
1164 switch (Kind) {
1165 case tok::kw__Nonnull:
1166 case tok::kw__Nullable:
1167 case tok::kw__Nullable_result:
1168 case tok::kw__Null_unspecified: {
1169 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1170 SourceLocation AttrNameLoc = ConsumeToken();
1171 if (!getLangOpts().ObjC)
1172 Diag(AttrNameLoc, diag::ext_nullability)
1173 << AttrName;
1174 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1175 Kind);
1176 break;
1177 }
1178 default:
1179 return;
1180 }
1181 }
1182}
1183
1184static bool VersionNumberSeparator(const char Separator) {
1185 return (Separator == '.' || Separator == '_');
1186}
1187
1188/// Parse a version number.
1189///
1190/// version:
1191/// simple-integer
1192/// simple-integer '.' simple-integer
1193/// simple-integer '_' simple-integer
1194/// simple-integer '.' simple-integer '.' simple-integer
1195/// simple-integer '_' simple-integer '_' simple-integer
1196VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
1197 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
1198
1199 if (!Tok.is(tok::numeric_constant)) {
1200 Diag(Tok, diag::err_expected_version);
1201 SkipUntil(tok::comma, tok::r_paren,
1203 return VersionTuple();
1204 }
1205
1206 // Parse the major (and possibly minor and subminor) versions, which
1207 // are stored in the numeric constant. We utilize a quirk of the
1208 // lexer, which is that it handles something like 1.2.3 as a single
1209 // numeric constant, rather than two separate tokens.
1210 SmallString<512> Buffer;
1211 Buffer.resize(Tok.getLength()+1);
1212 const char *ThisTokBegin = &Buffer[0];
1213
1214 // Get the spelling of the token, which eliminates trigraphs, etc.
1215 bool Invalid = false;
1216 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1217 if (Invalid)
1218 return VersionTuple();
1219
1220 // Parse the major version.
1221 unsigned AfterMajor = 0;
1222 unsigned Major = 0;
1223 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
1224 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
1225 ++AfterMajor;
1226 }
1227
1228 if (AfterMajor == 0) {
1229 Diag(Tok, diag::err_expected_version);
1230 SkipUntil(tok::comma, tok::r_paren,
1232 return VersionTuple();
1233 }
1234
1235 if (AfterMajor == ActualLength) {
1236 ConsumeToken();
1237
1238 // We only had a single version component.
1239 if (Major == 0) {
1240 Diag(Tok, diag::err_zero_version);
1241 return VersionTuple();
1242 }
1243
1244 return VersionTuple(Major);
1245 }
1246
1247 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
1248 if (!VersionNumberSeparator(AfterMajorSeparator)
1249 || (AfterMajor + 1 == ActualLength)) {
1250 Diag(Tok, diag::err_expected_version);
1251 SkipUntil(tok::comma, tok::r_paren,
1253 return VersionTuple();
1254 }
1255
1256 // Parse the minor version.
1257 unsigned AfterMinor = AfterMajor + 1;
1258 unsigned Minor = 0;
1259 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
1260 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
1261 ++AfterMinor;
1262 }
1263
1264 if (AfterMinor == ActualLength) {
1265 ConsumeToken();
1266
1267 // We had major.minor.
1268 if (Major == 0 && Minor == 0) {
1269 Diag(Tok, diag::err_zero_version);
1270 return VersionTuple();
1271 }
1272
1273 return VersionTuple(Major, Minor);
1274 }
1275
1276 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
1277 // If what follows is not a '.' or '_', we have a problem.
1278 if (!VersionNumberSeparator(AfterMinorSeparator)) {
1279 Diag(Tok, diag::err_expected_version);
1280 SkipUntil(tok::comma, tok::r_paren,
1282 return VersionTuple();
1283 }
1284
1285 // Warn if separators, be it '.' or '_', do not match.
1286 if (AfterMajorSeparator != AfterMinorSeparator)
1287 Diag(Tok, diag::warn_expected_consistent_version_separator);
1288
1289 // Parse the subminor version.
1290 unsigned AfterSubminor = AfterMinor + 1;
1291 unsigned Subminor = 0;
1292 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
1293 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
1294 ++AfterSubminor;
1295 }
1296
1297 if (AfterSubminor != ActualLength) {
1298 Diag(Tok, diag::err_expected_version);
1299 SkipUntil(tok::comma, tok::r_paren,
1301 return VersionTuple();
1302 }
1303 ConsumeToken();
1304 return VersionTuple(Major, Minor, Subminor);
1305}
1306
1307/// Parse the contents of the "availability" attribute.
1308///
1309/// availability-attribute:
1310/// 'availability' '(' platform ',' opt-strict version-arg-list,
1311/// opt-replacement, opt-message')'
1312///
1313/// platform:
1314/// identifier
1315///
1316/// opt-strict:
1317/// 'strict' ','
1318///
1319/// version-arg-list:
1320/// version-arg
1321/// version-arg ',' version-arg-list
1322///
1323/// version-arg:
1324/// 'introduced' '=' version
1325/// 'deprecated' '=' version
1326/// 'obsoleted' = version
1327/// 'unavailable'
1328/// opt-replacement:
1329/// 'replacement' '=' <string>
1330/// opt-message:
1331/// 'message' '=' <string>
1332void Parser::ParseAvailabilityAttribute(
1333 IdentifierInfo &Availability, SourceLocation AvailabilityLoc,
1334 ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName,
1335 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1336 enum { Introduced, Deprecated, Obsoleted, Unknown };
1337 AvailabilityChange Changes[Unknown];
1338 ExprResult MessageExpr, ReplacementExpr;
1339 IdentifierLoc *EnvironmentLoc = nullptr;
1340
1341 // Opening '('.
1342 BalancedDelimiterTracker T(*this, tok::l_paren);
1343 if (T.consumeOpen()) {
1344 Diag(Tok, diag::err_expected) << tok::l_paren;
1345 return;
1346 }
1347
1348 // Parse the platform name.
1349 if (Tok.isNot(tok::identifier)) {
1350 Diag(Tok, diag::err_availability_expected_platform);
1351 SkipUntil(tok::r_paren, StopAtSemi);
1352 return;
1353 }
1354 IdentifierLoc *Platform = ParseIdentifierLoc();
1355 if (const IdentifierInfo *const Ident = Platform->Ident) {
1356 // Disallow xrOS for availability attributes.
1357 if (Ident->getName().contains("xrOS") || Ident->getName().contains("xros"))
1358 Diag(Platform->Loc, diag::warn_availability_unknown_platform) << Ident;
1359 // Canonicalize platform name from "macosx" to "macos".
1360 else if (Ident->getName() == "macosx")
1361 Platform->Ident = PP.getIdentifierInfo("macos");
1362 // Canonicalize platform name from "macosx_app_extension" to
1363 // "macos_app_extension".
1364 else if (Ident->getName() == "macosx_app_extension")
1365 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1366 else
1367 Platform->Ident = PP.getIdentifierInfo(
1368 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1369 }
1370
1371 // Parse the ',' following the platform name.
1372 if (ExpectAndConsume(tok::comma)) {
1373 SkipUntil(tok::r_paren, StopAtSemi);
1374 return;
1375 }
1376
1377 // If we haven't grabbed the pointers for the identifiers
1378 // "introduced", "deprecated", and "obsoleted", do so now.
1379 if (!Ident_introduced) {
1380 Ident_introduced = PP.getIdentifierInfo("introduced");
1381 Ident_deprecated = PP.getIdentifierInfo("deprecated");
1382 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1383 Ident_unavailable = PP.getIdentifierInfo("unavailable");
1384 Ident_message = PP.getIdentifierInfo("message");
1385 Ident_strict = PP.getIdentifierInfo("strict");
1386 Ident_replacement = PP.getIdentifierInfo("replacement");
1387 Ident_environment = PP.getIdentifierInfo("environment");
1388 }
1389
1390 // Parse the optional "strict", the optional "replacement" and the set of
1391 // introductions/deprecations/removals.
1392 SourceLocation UnavailableLoc, StrictLoc;
1393 do {
1394 if (Tok.isNot(tok::identifier)) {
1395 Diag(Tok, diag::err_availability_expected_change);
1396 SkipUntil(tok::r_paren, StopAtSemi);
1397 return;
1398 }
1399 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1400 SourceLocation KeywordLoc = ConsumeToken();
1401
1402 if (Keyword == Ident_strict) {
1403 if (StrictLoc.isValid()) {
1404 Diag(KeywordLoc, diag::err_availability_redundant)
1405 << Keyword << SourceRange(StrictLoc);
1406 }
1407 StrictLoc = KeywordLoc;
1408 continue;
1409 }
1410
1411 if (Keyword == Ident_unavailable) {
1412 if (UnavailableLoc.isValid()) {
1413 Diag(KeywordLoc, diag::err_availability_redundant)
1414 << Keyword << SourceRange(UnavailableLoc);
1415 }
1416 UnavailableLoc = KeywordLoc;
1417 continue;
1418 }
1419
1420 if (Keyword == Ident_deprecated && Platform->Ident &&
1421 Platform->Ident->isStr("swift")) {
1422 // For swift, we deprecate for all versions.
1423 if (Changes[Deprecated].KeywordLoc.isValid()) {
1424 Diag(KeywordLoc, diag::err_availability_redundant)
1425 << Keyword
1426 << SourceRange(Changes[Deprecated].KeywordLoc);
1427 }
1428
1429 Changes[Deprecated].KeywordLoc = KeywordLoc;
1430 // Use a fake version here.
1431 Changes[Deprecated].Version = VersionTuple(1);
1432 continue;
1433 }
1434
1435 if (Keyword == Ident_environment) {
1436 if (EnvironmentLoc != nullptr) {
1437 Diag(KeywordLoc, diag::err_availability_redundant)
1438 << Keyword << SourceRange(EnvironmentLoc->Loc);
1439 }
1440 }
1441
1442 if (Tok.isNot(tok::equal)) {
1443 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1444 SkipUntil(tok::r_paren, StopAtSemi);
1445 return;
1446 }
1447 ConsumeToken();
1448 if (Keyword == Ident_message || Keyword == Ident_replacement) {
1449 if (!isTokenStringLiteral()) {
1450 Diag(Tok, diag::err_expected_string_literal)
1451 << /*Source='availability attribute'*/2;
1452 SkipUntil(tok::r_paren, StopAtSemi);
1453 return;
1454 }
1455 if (Keyword == Ident_message) {
1457 break;
1458 } else {
1459 ReplacementExpr = ParseUnevaluatedStringLiteralExpression();
1460 continue;
1461 }
1462 }
1463 if (Keyword == Ident_environment) {
1464 if (Tok.isNot(tok::identifier)) {
1465 Diag(Tok, diag::err_availability_expected_environment);
1466 SkipUntil(tok::r_paren, StopAtSemi);
1467 return;
1468 }
1469 EnvironmentLoc = ParseIdentifierLoc();
1470 continue;
1471 }
1472
1473 // Special handling of 'NA' only when applied to introduced or
1474 // deprecated.
1475 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1476 Tok.is(tok::identifier)) {
1478 if (NA->getName() == "NA") {
1479 ConsumeToken();
1480 if (Keyword == Ident_introduced)
1481 UnavailableLoc = KeywordLoc;
1482 continue;
1483 }
1484 }
1485
1486 SourceRange VersionRange;
1487 VersionTuple Version = ParseVersionTuple(VersionRange);
1488
1489 if (Version.empty()) {
1490 SkipUntil(tok::r_paren, StopAtSemi);
1491 return;
1492 }
1493
1494 unsigned Index;
1495 if (Keyword == Ident_introduced)
1496 Index = Introduced;
1497 else if (Keyword == Ident_deprecated)
1498 Index = Deprecated;
1499 else if (Keyword == Ident_obsoleted)
1500 Index = Obsoleted;
1501 else
1502 Index = Unknown;
1503
1504 if (Index < Unknown) {
1505 if (!Changes[Index].KeywordLoc.isInvalid()) {
1506 Diag(KeywordLoc, diag::err_availability_redundant)
1507 << Keyword
1508 << SourceRange(Changes[Index].KeywordLoc,
1509 Changes[Index].VersionRange.getEnd());
1510 }
1511
1512 Changes[Index].KeywordLoc = KeywordLoc;
1513 Changes[Index].Version = Version;
1514 Changes[Index].VersionRange = VersionRange;
1515 } else {
1516 Diag(KeywordLoc, diag::err_availability_unknown_change)
1517 << Keyword << VersionRange;
1518 }
1519
1520 } while (TryConsumeToken(tok::comma));
1521
1522 // Closing ')'.
1523 if (T.consumeClose())
1524 return;
1525
1526 if (endLoc)
1527 *endLoc = T.getCloseLocation();
1528
1529 // The 'unavailable' availability cannot be combined with any other
1530 // availability changes. Make sure that hasn't happened.
1531 if (UnavailableLoc.isValid()) {
1532 bool Complained = false;
1533 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1534 if (Changes[Index].KeywordLoc.isValid()) {
1535 if (!Complained) {
1536 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1537 << SourceRange(Changes[Index].KeywordLoc,
1538 Changes[Index].VersionRange.getEnd());
1539 Complained = true;
1540 }
1541
1542 // Clear out the availability.
1543 Changes[Index] = AvailabilityChange();
1544 }
1545 }
1546 }
1547
1548 // Record this attribute
1549 attrs.addNew(&Availability,
1550 SourceRange(AvailabilityLoc, T.getCloseLocation()), ScopeName,
1551 ScopeLoc, Platform, Changes[Introduced], Changes[Deprecated],
1552 Changes[Obsoleted], UnavailableLoc, MessageExpr.get(), Form,
1553 StrictLoc, ReplacementExpr.get(), EnvironmentLoc);
1554}
1555
1556/// Parse the contents of the "external_source_symbol" attribute.
1557///
1558/// external-source-symbol-attribute:
1559/// 'external_source_symbol' '(' keyword-arg-list ')'
1560///
1561/// keyword-arg-list:
1562/// keyword-arg
1563/// keyword-arg ',' keyword-arg-list
1564///
1565/// keyword-arg:
1566/// 'language' '=' <string>
1567/// 'defined_in' '=' <string>
1568/// 'USR' '=' <string>
1569/// 'generated_declaration'
1570void Parser::ParseExternalSourceSymbolAttribute(
1571 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1572 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1573 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1574 // Opening '('.
1575 BalancedDelimiterTracker T(*this, tok::l_paren);
1576 if (T.expectAndConsume())
1577 return;
1578
1579 // Initialize the pointers for the keyword identifiers when required.
1580 if (!Ident_language) {
1581 Ident_language = PP.getIdentifierInfo("language");
1582 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1583 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1584 Ident_USR = PP.getIdentifierInfo("USR");
1585 }
1586
1588 bool HasLanguage = false;
1589 ExprResult DefinedInExpr;
1590 bool HasDefinedIn = false;
1591 IdentifierLoc *GeneratedDeclaration = nullptr;
1592 ExprResult USR;
1593 bool HasUSR = false;
1594
1595 // Parse the language/defined_in/generated_declaration keywords
1596 do {
1597 if (Tok.isNot(tok::identifier)) {
1598 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1599 SkipUntil(tok::r_paren, StopAtSemi);
1600 return;
1601 }
1602
1603 SourceLocation KeywordLoc = Tok.getLocation();
1604 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1605 if (Keyword == Ident_generated_declaration) {
1606 if (GeneratedDeclaration) {
1607 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1608 SkipUntil(tok::r_paren, StopAtSemi);
1609 return;
1610 }
1611 GeneratedDeclaration = ParseIdentifierLoc();
1612 continue;
1613 }
1614
1615 if (Keyword != Ident_language && Keyword != Ident_defined_in &&
1616 Keyword != Ident_USR) {
1617 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1618 SkipUntil(tok::r_paren, StopAtSemi);
1619 return;
1620 }
1621
1622 ConsumeToken();
1623 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1624 Keyword->getName())) {
1625 SkipUntil(tok::r_paren, StopAtSemi);
1626 return;
1627 }
1628
1629 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn,
1630 HadUSR = HasUSR;
1631 if (Keyword == Ident_language)
1632 HasLanguage = true;
1633 else if (Keyword == Ident_USR)
1634 HasUSR = true;
1635 else
1636 HasDefinedIn = true;
1637
1638 if (!isTokenStringLiteral()) {
1639 Diag(Tok, diag::err_expected_string_literal)
1640 << /*Source='external_source_symbol attribute'*/ 3
1641 << /*language | source container | USR*/ (
1642 Keyword == Ident_language
1643 ? 0
1644 : (Keyword == Ident_defined_in ? 1 : 2));
1645 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1646 continue;
1647 }
1648 if (Keyword == Ident_language) {
1649 if (HadLanguage) {
1650 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1651 << Keyword;
1653 continue;
1654 }
1656 } else if (Keyword == Ident_USR) {
1657 if (HadUSR) {
1658 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1659 << Keyword;
1661 continue;
1662 }
1664 } else {
1665 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1666 if (HadDefinedIn) {
1667 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1668 << Keyword;
1670 continue;
1671 }
1673 }
1674 } while (TryConsumeToken(tok::comma));
1675
1676 // Closing ')'.
1677 if (T.consumeClose())
1678 return;
1679 if (EndLoc)
1680 *EndLoc = T.getCloseLocation();
1681
1682 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(), GeneratedDeclaration,
1683 USR.get()};
1684 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1685 ScopeName, ScopeLoc, Args, std::size(Args), Form);
1686}
1687
1688/// Parse the contents of the "objc_bridge_related" attribute.
1689/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1690/// related_class:
1691/// Identifier
1692///
1693/// opt-class_method:
1694/// Identifier: | <empty>
1695///
1696/// opt-instance_method:
1697/// Identifier | <empty>
1698///
1699void Parser::ParseObjCBridgeRelatedAttribute(
1700 IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc,
1701 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1702 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1703 // Opening '('.
1704 BalancedDelimiterTracker T(*this, tok::l_paren);
1705 if (T.consumeOpen()) {
1706 Diag(Tok, diag::err_expected) << tok::l_paren;
1707 return;
1708 }
1709
1710 // Parse the related class name.
1711 if (Tok.isNot(tok::identifier)) {
1712 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1713 SkipUntil(tok::r_paren, StopAtSemi);
1714 return;
1715 }
1716 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1717 if (ExpectAndConsume(tok::comma)) {
1718 SkipUntil(tok::r_paren, StopAtSemi);
1719 return;
1720 }
1721
1722 // Parse class method name. It's non-optional in the sense that a trailing
1723 // comma is required, but it can be the empty string, and then we record a
1724 // nullptr.
1725 IdentifierLoc *ClassMethod = nullptr;
1726 if (Tok.is(tok::identifier)) {
1727 ClassMethod = ParseIdentifierLoc();
1728 if (!TryConsumeToken(tok::colon)) {
1729 Diag(Tok, diag::err_objcbridge_related_selector_name);
1730 SkipUntil(tok::r_paren, StopAtSemi);
1731 return;
1732 }
1733 }
1734 if (!TryConsumeToken(tok::comma)) {
1735 if (Tok.is(tok::colon))
1736 Diag(Tok, diag::err_objcbridge_related_selector_name);
1737 else
1738 Diag(Tok, diag::err_expected) << tok::comma;
1739 SkipUntil(tok::r_paren, StopAtSemi);
1740 return;
1741 }
1742
1743 // Parse instance method name. Also non-optional but empty string is
1744 // permitted.
1745 IdentifierLoc *InstanceMethod = nullptr;
1746 if (Tok.is(tok::identifier))
1747 InstanceMethod = ParseIdentifierLoc();
1748 else if (Tok.isNot(tok::r_paren)) {
1749 Diag(Tok, diag::err_expected) << tok::r_paren;
1750 SkipUntil(tok::r_paren, StopAtSemi);
1751 return;
1752 }
1753
1754 // Closing ')'.
1755 if (T.consumeClose())
1756 return;
1757
1758 if (EndLoc)
1759 *EndLoc = T.getCloseLocation();
1760
1761 // Record this attribute
1762 Attrs.addNew(&ObjCBridgeRelated,
1763 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1764 ScopeName, ScopeLoc, RelatedClass, ClassMethod, InstanceMethod,
1765 Form);
1766}
1767
1768void Parser::ParseSwiftNewTypeAttribute(
1769 IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1770 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1771 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1772 BalancedDelimiterTracker T(*this, tok::l_paren);
1773
1774 // Opening '('
1775 if (T.consumeOpen()) {
1776 Diag(Tok, diag::err_expected) << tok::l_paren;
1777 return;
1778 }
1779
1780 if (Tok.is(tok::r_paren)) {
1781 Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
1782 T.consumeClose();
1783 return;
1784 }
1785 if (Tok.isNot(tok::kw_struct) && Tok.isNot(tok::kw_enum)) {
1786 Diag(Tok, diag::warn_attribute_type_not_supported)
1787 << &AttrName << Tok.getIdentifierInfo();
1788 if (!isTokenSpecial())
1789 ConsumeToken();
1790 T.consumeClose();
1791 return;
1792 }
1793
1794 auto *SwiftType = IdentifierLoc::create(Actions.Context, Tok.getLocation(),
1795 Tok.getIdentifierInfo());
1796 ConsumeToken();
1797
1798 // Closing ')'
1799 if (T.consumeClose())
1800 return;
1801 if (EndLoc)
1802 *EndLoc = T.getCloseLocation();
1803
1804 ArgsUnion Args[] = {SwiftType};
1805 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, T.getCloseLocation()),
1806 ScopeName, ScopeLoc, Args, std::size(Args), Form);
1807}
1808
1809void Parser::ParseTypeTagForDatatypeAttribute(
1810 IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1811 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1812 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1813 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1814
1815 BalancedDelimiterTracker T(*this, tok::l_paren);
1816 T.consumeOpen();
1817
1818 if (Tok.isNot(tok::identifier)) {
1819 Diag(Tok, diag::err_expected) << tok::identifier;
1820 T.skipToEnd();
1821 return;
1822 }
1823 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1824
1825 if (ExpectAndConsume(tok::comma)) {
1826 T.skipToEnd();
1827 return;
1828 }
1829
1830 SourceRange MatchingCTypeRange;
1831 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1832 if (MatchingCType.isInvalid()) {
1833 T.skipToEnd();
1834 return;
1835 }
1836
1837 bool LayoutCompatible = false;
1838 bool MustBeNull = false;
1839 while (TryConsumeToken(tok::comma)) {
1840 if (Tok.isNot(tok::identifier)) {
1841 Diag(Tok, diag::err_expected) << tok::identifier;
1842 T.skipToEnd();
1843 return;
1844 }
1845 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1846 if (Flag->isStr("layout_compatible"))
1847 LayoutCompatible = true;
1848 else if (Flag->isStr("must_be_null"))
1849 MustBeNull = true;
1850 else {
1851 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1852 T.skipToEnd();
1853 return;
1854 }
1855 ConsumeToken(); // consume flag
1856 }
1857
1858 if (!T.consumeClose()) {
1859 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1860 ArgumentKind, MatchingCType.get(),
1861 LayoutCompatible, MustBeNull, Form);
1862 }
1863
1864 if (EndLoc)
1865 *EndLoc = T.getCloseLocation();
1866}
1867
1868/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1869/// of a C++11 attribute-specifier in a location where an attribute is not
1870/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1871/// situation.
1872///
1873/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1874/// this doesn't appear to actually be an attribute-specifier, and the caller
1875/// should try to parse it.
1876bool Parser::DiagnoseProhibitedCXX11Attribute() {
1877 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1878
1879 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1880 case CAK_NotAttributeSpecifier:
1881 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1882 return false;
1883
1884 case CAK_InvalidAttributeSpecifier:
1885 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1886 return false;
1887
1888 case CAK_AttributeSpecifier:
1889 // Parse and discard the attributes.
1890 SourceLocation BeginLoc = ConsumeBracket();
1891 ConsumeBracket();
1892 SkipUntil(tok::r_square);
1893 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1894 SourceLocation EndLoc = ConsumeBracket();
1895 Diag(BeginLoc, diag::err_attributes_not_allowed)
1896 << SourceRange(BeginLoc, EndLoc);
1897 return true;
1898 }
1899 llvm_unreachable("All cases handled above.");
1900}
1901
1902/// We have found the opening square brackets of a C++11
1903/// attribute-specifier in a location where an attribute is not permitted, but
1904/// we know where the attributes ought to be written. Parse them anyway, and
1905/// provide a fixit moving them to the right place.
1906void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs,
1907 SourceLocation CorrectLocation) {
1908 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1909 Tok.is(tok::kw_alignas) || Tok.isRegularKeywordAttribute());
1910
1911 // Consume the attributes.
1912 auto Keyword =
1913 Tok.isRegularKeywordAttribute() ? Tok.getIdentifierInfo() : nullptr;
1915 ParseCXX11Attributes(Attrs);
1916 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1917 // FIXME: use err_attributes_misplaced
1918 (Keyword ? Diag(Loc, diag::err_keyword_not_allowed) << Keyword
1919 : Diag(Loc, diag::err_attributes_not_allowed))
1920 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1921 << FixItHint::CreateRemoval(AttrRange);
1922}
1923
1924void Parser::DiagnoseProhibitedAttributes(
1925 const ParsedAttributesView &Attrs, const SourceLocation CorrectLocation) {
1926 auto *FirstAttr = Attrs.empty() ? nullptr : &Attrs.front();
1927 if (CorrectLocation.isValid()) {
1928 CharSourceRange AttrRange(Attrs.Range, true);
1929 (FirstAttr && FirstAttr->isRegularKeywordAttribute()
1930 ? Diag(CorrectLocation, diag::err_keyword_misplaced) << FirstAttr
1931 : Diag(CorrectLocation, diag::err_attributes_misplaced))
1932 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1933 << FixItHint::CreateRemoval(AttrRange);
1934 } else {
1935 const SourceRange &Range = Attrs.Range;
1936 (FirstAttr && FirstAttr->isRegularKeywordAttribute()
1937 ? Diag(Range.getBegin(), diag::err_keyword_not_allowed) << FirstAttr
1938 : Diag(Range.getBegin(), diag::err_attributes_not_allowed))
1939 << Range;
1940 }
1941}
1942
1943void Parser::ProhibitCXX11Attributes(ParsedAttributes &Attrs,
1944 unsigned AttrDiagID,
1945 unsigned KeywordDiagID,
1946 bool DiagnoseEmptyAttrs,
1947 bool WarnOnUnknownAttrs) {
1948
1949 if (DiagnoseEmptyAttrs && Attrs.empty() && Attrs.Range.isValid()) {
1950 // An attribute list has been parsed, but it was empty.
1951 // This is the case for [[]].
1952 const auto &LangOpts = getLangOpts();
1953 auto &SM = PP.getSourceManager();
1954 Token FirstLSquare;
1955 Lexer::getRawToken(Attrs.Range.getBegin(), FirstLSquare, SM, LangOpts);
1956
1957 if (FirstLSquare.is(tok::l_square)) {
1958 std::optional<Token> SecondLSquare =
1959 Lexer::findNextToken(FirstLSquare.getLocation(), SM, LangOpts);
1960
1961 if (SecondLSquare && SecondLSquare->is(tok::l_square)) {
1962 // The attribute range starts with [[, but is empty. So this must
1963 // be [[]], which we are supposed to diagnose because
1964 // DiagnoseEmptyAttrs is true.
1965 Diag(Attrs.Range.getBegin(), AttrDiagID) << Attrs.Range;
1966 return;
1967 }
1968 }
1969 }
1970
1971 for (const ParsedAttr &AL : Attrs) {
1972 if (AL.isRegularKeywordAttribute()) {
1973 Diag(AL.getLoc(), KeywordDiagID) << AL;
1974 AL.setInvalid();
1975 continue;
1976 }
1977 if (!AL.isStandardAttributeSyntax())
1978 continue;
1979 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
1980 if (WarnOnUnknownAttrs)
1981 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
1982 << AL << AL.getRange();
1983 } else {
1984 Diag(AL.getLoc(), AttrDiagID) << AL;
1985 AL.setInvalid();
1986 }
1987 }
1988}
1989
1990void Parser::DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs) {
1991 for (const ParsedAttr &PA : Attrs) {
1992 if (PA.isStandardAttributeSyntax() || PA.isRegularKeywordAttribute())
1993 Diag(PA.getLoc(), diag::ext_cxx11_attr_placement)
1994 << PA << PA.isRegularKeywordAttribute() << PA.getRange();
1995 }
1996}
1997
1998// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1999// applies to var, not the type Foo.
2000// As an exception to the rule, __declspec(align(...)) before the
2001// class-key affects the type instead of the variable.
2002// Also, Microsoft-style [attributes] seem to affect the type instead of the
2003// variable.
2004// This function moves attributes that should apply to the type off DS to Attrs.
2005void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs,
2006 DeclSpec &DS, TagUseKind TUK) {
2007 if (TUK == TagUseKind::Reference)
2008 return;
2009
2011
2012 for (ParsedAttr &AL : DS.getAttributes()) {
2013 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
2014 AL.isDeclspecAttribute()) ||
2015 AL.isMicrosoftAttribute())
2016 ToBeMoved.push_back(&AL);
2017 }
2018
2019 for (ParsedAttr *AL : ToBeMoved) {
2020 DS.getAttributes().remove(AL);
2021 Attrs.addAtEnd(AL);
2022 }
2023}
2024
2025/// ParseDeclaration - Parse a full 'declaration', which consists of
2026/// declaration-specifiers, some number of declarators, and a semicolon.
2027/// 'Context' should be a DeclaratorContext value. This returns the
2028/// location of the semicolon in DeclEnd.
2029///
2030/// declaration: [C99 6.7]
2031/// block-declaration ->
2032/// simple-declaration
2033/// others [FIXME]
2034/// [C++] template-declaration
2035/// [C++] namespace-definition
2036/// [C++] using-directive
2037/// [C++] using-declaration
2038/// [C++11/C11] static_assert-declaration
2039/// others... [FIXME]
2040///
2041Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
2042 SourceLocation &DeclEnd,
2043 ParsedAttributes &DeclAttrs,
2044 ParsedAttributes &DeclSpecAttrs,
2045 SourceLocation *DeclSpecStart) {
2046 ParenBraceBracketBalancer BalancerRAIIObj(*this);
2047 // Must temporarily exit the objective-c container scope for
2048 // parsing c none objective-c decls.
2049 ObjCDeclContextSwitch ObjCDC(*this);
2050
2051 Decl *SingleDecl = nullptr;
2052 switch (Tok.getKind()) {
2053 case tok::kw_template:
2054 case tok::kw_export:
2055 ProhibitAttributes(DeclAttrs);
2056 ProhibitAttributes(DeclSpecAttrs);
2057 return ParseDeclarationStartingWithTemplate(Context, DeclEnd, DeclAttrs);
2058 case tok::kw_inline:
2059 // Could be the start of an inline namespace. Allowed as an ext in C++03.
2060 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
2061 ProhibitAttributes(DeclAttrs);
2062 ProhibitAttributes(DeclSpecAttrs);
2063 SourceLocation InlineLoc = ConsumeToken();
2064 return ParseNamespace(Context, DeclEnd, InlineLoc);
2065 }
2066 return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
2067 true, nullptr, DeclSpecStart);
2068
2069 case tok::kw_cbuffer:
2070 case tok::kw_tbuffer:
2071 SingleDecl = ParseHLSLBuffer(DeclEnd);
2072 break;
2073 case tok::kw_namespace:
2074 ProhibitAttributes(DeclAttrs);
2075 ProhibitAttributes(DeclSpecAttrs);
2076 return ParseNamespace(Context, DeclEnd);
2077 case tok::kw_using: {
2078 ParsedAttributes Attrs(AttrFactory);
2079 takeAndConcatenateAttrs(DeclAttrs, DeclSpecAttrs, Attrs);
2080 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
2081 DeclEnd, Attrs);
2082 }
2083 case tok::kw_static_assert:
2084 case tok::kw__Static_assert:
2085 ProhibitAttributes(DeclAttrs);
2086 ProhibitAttributes(DeclSpecAttrs);
2087 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
2088 break;
2089 default:
2090 return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
2091 true, nullptr, DeclSpecStart);
2092 }
2093
2094 // This routine returns a DeclGroup, if the thing we parsed only contains a
2095 // single decl, convert it now.
2096 return Actions.ConvertDeclToDeclGroup(SingleDecl);
2097}
2098
2099/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
2100/// declaration-specifiers init-declarator-list[opt] ';'
2101/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
2102/// init-declarator-list ';'
2103///[C90/C++]init-declarator-list ';' [TODO]
2104/// [OMP] threadprivate-directive
2105/// [OMP] allocate-directive [TODO]
2106///
2107/// for-range-declaration: [C++11 6.5p1: stmt.ranged]
2108/// attribute-specifier-seq[opt] type-specifier-seq declarator
2109///
2110/// If RequireSemi is false, this does not check for a ';' at the end of the
2111/// declaration. If it is true, it checks for and eats it.
2112///
2113/// If FRI is non-null, we might be parsing a for-range-declaration instead
2114/// of a simple-declaration. If we find that we are, we also parse the
2115/// for-range-initializer, and place it here.
2116///
2117/// DeclSpecStart is used when decl-specifiers are parsed before parsing
2118/// the Declaration. The SourceLocation for this Decl is set to
2119/// DeclSpecStart if DeclSpecStart is non-null.
2120Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
2121 DeclaratorContext Context, SourceLocation &DeclEnd,
2122 ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs,
2123 bool RequireSemi, ForRangeInit *FRI, SourceLocation *DeclSpecStart) {
2124 // Need to retain these for diagnostics before we add them to the DeclSepc.
2125 ParsedAttributesView OriginalDeclSpecAttrs;
2126 OriginalDeclSpecAttrs.addAll(DeclSpecAttrs.begin(), DeclSpecAttrs.end());
2127 OriginalDeclSpecAttrs.Range = DeclSpecAttrs.Range;
2128
2129 // Parse the common declaration-specifiers piece.
2130 ParsingDeclSpec DS(*this);
2131 DS.takeAttributesFrom(DeclSpecAttrs);
2132
2133 ParsedTemplateInfo TemplateInfo;
2134 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
2135 ParseDeclarationSpecifiers(DS, TemplateInfo, AS_none, DSContext);
2136
2137 // If we had a free-standing type definition with a missing semicolon, we
2138 // may get this far before the problem becomes obvious.
2139 if (DS.hasTagDefinition() &&
2140 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
2141 return nullptr;
2142
2143 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
2144 // declaration-specifiers init-declarator-list[opt] ';'
2145 if (Tok.is(tok::semi)) {
2146 ProhibitAttributes(DeclAttrs);
2147 DeclEnd = Tok.getLocation();
2148 if (RequireSemi) ConsumeToken();
2149 RecordDecl *AnonRecord = nullptr;
2150 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2151 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
2152 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
2153 DS.complete(TheDecl);
2154 if (AnonRecord) {
2155 Decl* decls[] = {AnonRecord, TheDecl};
2156 return Actions.BuildDeclaratorGroup(decls);
2157 }
2158 return Actions.ConvertDeclToDeclGroup(TheDecl);
2159 }
2160
2161 if (DS.hasTagDefinition())
2163
2164 if (DeclSpecStart)
2165 DS.SetRangeStart(*DeclSpecStart);
2166
2167 return ParseDeclGroup(DS, Context, DeclAttrs, TemplateInfo, &DeclEnd, FRI);
2168}
2169
2170/// Returns true if this might be the start of a declarator, or a common typo
2171/// for a declarator.
2172bool Parser::MightBeDeclarator(DeclaratorContext Context) {
2173 switch (Tok.getKind()) {
2174 case tok::annot_cxxscope:
2175 case tok::annot_template_id:
2176 case tok::caret:
2177 case tok::code_completion:
2178 case tok::coloncolon:
2179 case tok::ellipsis:
2180 case tok::kw___attribute:
2181 case tok::kw_operator:
2182 case tok::l_paren:
2183 case tok::star:
2184 return true;
2185
2186 case tok::amp:
2187 case tok::ampamp:
2188 return getLangOpts().CPlusPlus;
2189
2190 case tok::l_square: // Might be an attribute on an unnamed bit-field.
2191 return Context == DeclaratorContext::Member && getLangOpts().CPlusPlus11 &&
2192 NextToken().is(tok::l_square);
2193
2194 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
2195 return Context == DeclaratorContext::Member || getLangOpts().CPlusPlus;
2196
2197 case tok::identifier:
2198 switch (NextToken().getKind()) {
2199 case tok::code_completion:
2200 case tok::coloncolon:
2201 case tok::comma:
2202 case tok::equal:
2203 case tok::equalequal: // Might be a typo for '='.
2204 case tok::kw_alignas:
2205 case tok::kw_asm:
2206 case tok::kw___attribute:
2207 case tok::l_brace:
2208 case tok::l_paren:
2209 case tok::l_square:
2210 case tok::less:
2211 case tok::r_brace:
2212 case tok::r_paren:
2213 case tok::r_square:
2214 case tok::semi:
2215 return true;
2216
2217 case tok::colon:
2218 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
2219 // and in block scope it's probably a label. Inside a class definition,
2220 // this is a bit-field.
2221 return Context == DeclaratorContext::Member ||
2222 (getLangOpts().CPlusPlus && Context == DeclaratorContext::File);
2223
2224 case tok::identifier: // Possible virt-specifier.
2225 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
2226
2227 default:
2228 return Tok.isRegularKeywordAttribute();
2229 }
2230
2231 default:
2232 return Tok.isRegularKeywordAttribute();
2233 }
2234}
2235
2236/// Skip until we reach something which seems like a sensible place to pick
2237/// up parsing after a malformed declaration. This will sometimes stop sooner
2238/// than SkipUntil(tok::r_brace) would, but will never stop later.
2240 while (true) {
2241 switch (Tok.getKind()) {
2242 case tok::l_brace:
2243 // Skip until matching }, then stop. We've probably skipped over
2244 // a malformed class or function definition or similar.
2245 ConsumeBrace();
2246 SkipUntil(tok::r_brace);
2247 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
2248 // This declaration isn't over yet. Keep skipping.
2249 continue;
2250 }
2251 TryConsumeToken(tok::semi);
2252 return;
2253
2254 case tok::l_square:
2255 ConsumeBracket();
2256 SkipUntil(tok::r_square);
2257 continue;
2258
2259 case tok::l_paren:
2260 ConsumeParen();
2261 SkipUntil(tok::r_paren);
2262 continue;
2263
2264 case tok::r_brace:
2265 return;
2266
2267 case tok::semi:
2268 ConsumeToken();
2269 return;
2270
2271 case tok::kw_inline:
2272 // 'inline namespace' at the start of a line is almost certainly
2273 // a good place to pick back up parsing, except in an Objective-C
2274 // @interface context.
2275 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
2276 (!ParsingInObjCContainer || CurParsedObjCImpl))
2277 return;
2278 break;
2279
2280 case tok::kw_namespace:
2281 // 'namespace' at the start of a line is almost certainly a good
2282 // place to pick back up parsing, except in an Objective-C
2283 // @interface context.
2284 if (Tok.isAtStartOfLine() &&
2285 (!ParsingInObjCContainer || CurParsedObjCImpl))
2286 return;
2287 break;
2288
2289 case tok::at:
2290 // @end is very much like } in Objective-C contexts.
2291 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
2292 ParsingInObjCContainer)
2293 return;
2294 break;
2295
2296 case tok::minus:
2297 case tok::plus:
2298 // - and + probably start new method declarations in Objective-C contexts.
2299 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
2300 return;
2301 break;
2302
2303 case tok::eof:
2304 case tok::annot_module_begin:
2305 case tok::annot_module_end:
2306 case tok::annot_module_include:
2307 case tok::annot_repl_input_end:
2308 return;
2309
2310 default:
2311 break;
2312 }
2313
2315 }
2316}
2317
2318/// ParseDeclGroup - Having concluded that this is either a function
2319/// definition or a group of object declarations, actually parse the
2320/// result.
2321Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
2322 DeclaratorContext Context,
2323 ParsedAttributes &Attrs,
2324 ParsedTemplateInfo &TemplateInfo,
2325 SourceLocation *DeclEnd,
2326 ForRangeInit *FRI) {
2327 // Parse the first declarator.
2328 // Consume all of the attributes from `Attrs` by moving them to our own local
2329 // list. This ensures that we will not attempt to interpret them as statement
2330 // attributes higher up the callchain.
2331 ParsedAttributes LocalAttrs(AttrFactory);
2332 LocalAttrs.takeAllFrom(Attrs);
2333 ParsingDeclarator D(*this, DS, LocalAttrs, Context);
2334 if (TemplateInfo.TemplateParams)
2335 D.setTemplateParameterLists(*TemplateInfo.TemplateParams);
2336
2337 bool IsTemplateSpecOrInst =
2338 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
2339 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
2340 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
2341
2342 ParseDeclarator(D);
2343
2344 if (IsTemplateSpecOrInst)
2345 SAC.done();
2346
2347 // Bail out if the first declarator didn't seem well-formed.
2348 if (!D.hasName() && !D.mayOmitIdentifier()) {
2350 return nullptr;
2351 }
2352
2353 if (getLangOpts().HLSL)
2354 while (MaybeParseHLSLAnnotations(D))
2355 ;
2356
2357 if (Tok.is(tok::kw_requires))
2358 ParseTrailingRequiresClause(D);
2359
2360 // Save late-parsed attributes for now; they need to be parsed in the
2361 // appropriate function scope after the function Decl has been constructed.
2362 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
2363 LateParsedAttrList LateParsedAttrs(true);
2364 if (D.isFunctionDeclarator()) {
2365 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2366
2367 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2368 // attribute. If we find the keyword here, tell the user to put it
2369 // at the start instead.
2370 if (Tok.is(tok::kw__Noreturn)) {
2372 const char *PrevSpec;
2373 unsigned DiagID;
2374
2375 // We can offer a fixit if it's valid to mark this function as _Noreturn
2376 // and we don't have any other declarators in this declaration.
2377 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2378 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2379 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2380
2381 Diag(Loc, diag::err_c11_noreturn_misplaced)
2382 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
2383 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2384 : FixItHint());
2385 }
2386
2387 // Check to see if we have a function *definition* which must have a body.
2388 if (Tok.is(tok::equal) && NextToken().is(tok::code_completion)) {
2389 cutOffParsing();
2391 return nullptr;
2392 }
2393 // We're at the point where the parsing of function declarator is finished.
2394 //
2395 // A common error is that users accidently add a virtual specifier
2396 // (e.g. override) in an out-line method definition.
2397 // We attempt to recover by stripping all these specifiers coming after
2398 // the declarator.
2399 while (auto Specifier = isCXX11VirtSpecifier()) {
2400 Diag(Tok, diag::err_virt_specifier_outside_class)
2403 ConsumeToken();
2404 }
2405 // Look at the next token to make sure that this isn't a function
2406 // declaration. We have to check this because __attribute__ might be the
2407 // start of a function definition in GCC-extended K&R C.
2408 if (!isDeclarationAfterDeclarator()) {
2409
2410 // Function definitions are only allowed at file scope and in C++ classes.
2411 // The C++ inline method definition case is handled elsewhere, so we only
2412 // need to handle the file scope definition case.
2413 if (Context == DeclaratorContext::File) {
2414 if (isStartOfFunctionDefinition(D)) {
2415 // C++23 [dcl.typedef] p1:
2416 // The typedef specifier shall not be [...], and it shall not be
2417 // used in the decl-specifier-seq of a parameter-declaration nor in
2418 // the decl-specifier-seq of a function-definition.
2420 // If the user intended to write 'typename', we should have already
2421 // suggested adding it elsewhere. In any case, recover by ignoring
2422 // 'typedef' and suggest removing it.
2424 diag::err_function_declared_typedef)
2427 }
2428 Decl *TheDecl = nullptr;
2429
2430 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
2431 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2432 // If the declarator-id is not a template-id, issue a diagnostic
2433 // and recover by ignoring the 'template' keyword.
2434 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
2435 TheDecl = ParseFunctionDefinition(D, ParsedTemplateInfo(),
2436 &LateParsedAttrs);
2437 } else {
2438 SourceLocation LAngleLoc =
2439 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2440 Diag(D.getIdentifierLoc(),
2441 diag::err_explicit_instantiation_with_definition)
2442 << SourceRange(TemplateInfo.TemplateLoc)
2443 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2444
2445 // Recover as if it were an explicit specialization.
2446 TemplateParameterLists FakedParamLists;
2447 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2448 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, {},
2449 LAngleLoc, nullptr));
2450
2451 TheDecl = ParseFunctionDefinition(
2452 D,
2453 ParsedTemplateInfo(&FakedParamLists,
2454 /*isSpecialization=*/true,
2455 /*lastParameterListWasEmpty=*/true),
2456 &LateParsedAttrs);
2457 }
2458 } else {
2459 TheDecl =
2460 ParseFunctionDefinition(D, TemplateInfo, &LateParsedAttrs);
2461 }
2462
2463 return Actions.ConvertDeclToDeclGroup(TheDecl);
2464 }
2465
2466 if (isDeclarationSpecifier(ImplicitTypenameContext::No) ||
2467 Tok.is(tok::kw_namespace)) {
2468 // If there is an invalid declaration specifier or a namespace
2469 // definition right after the function prototype, then we must be in a
2470 // missing semicolon case where this isn't actually a body. Just fall
2471 // through into the code that handles it as a prototype, and let the
2472 // top-level code handle the erroneous declspec where it would
2473 // otherwise expect a comma or semicolon. Note that
2474 // isDeclarationSpecifier already covers 'inline namespace', since
2475 // 'inline' can be a declaration specifier.
2476 } else {
2477 Diag(Tok, diag::err_expected_fn_body);
2478 SkipUntil(tok::semi);
2479 return nullptr;
2480 }
2481 } else {
2482 if (Tok.is(tok::l_brace)) {
2483 Diag(Tok, diag::err_function_definition_not_allowed);
2485 return nullptr;
2486 }
2487 }
2488 }
2489 }
2490
2491 if (ParseAsmAttributesAfterDeclarator(D))
2492 return nullptr;
2493
2494 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2495 // must parse and analyze the for-range-initializer before the declaration is
2496 // analyzed.
2497 //
2498 // Handle the Objective-C for-in loop variable similarly, although we
2499 // don't need to parse the container in advance.
2500 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2501 bool IsForRangeLoop = false;
2502 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2503 IsForRangeLoop = true;
2504 EnterExpressionEvaluationContext ForRangeInitContext(
2506 /*LambdaContextDecl=*/nullptr,
2509
2510 // P2718R0 - Lifetime extension in range-based for loops.
2511 if (getLangOpts().CPlusPlus23) {
2512 auto &LastRecord = Actions.currentEvaluationContext();
2513 LastRecord.InLifetimeExtendingContext = true;
2514 LastRecord.RebuildDefaultArgOrDefaultInit = true;
2515 }
2516
2517 if (getLangOpts().OpenMP)
2518 Actions.OpenMP().startOpenMPCXXRangeFor();
2519 if (Tok.is(tok::l_brace))
2520 FRI->RangeExpr = ParseBraceInitializer();
2521 else
2522 FRI->RangeExpr = ParseExpression();
2523
2524 // Before c++23, ForRangeLifetimeExtendTemps should be empty.
2525 assert(
2527 Actions.ExprEvalContexts.back().ForRangeLifetimeExtendTemps.empty());
2528
2529 // Move the collected materialized temporaries into ForRangeInit before
2530 // ForRangeInitContext exit.
2531 FRI->LifetimeExtendTemps = std::move(
2532 Actions.ExprEvalContexts.back().ForRangeLifetimeExtendTemps);
2533 }
2534
2535 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2536 if (IsForRangeLoop) {
2537 Actions.ActOnCXXForRangeDecl(ThisDecl);
2538 } else {
2539 // Obj-C for loop
2540 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2541 VD->setObjCForDecl(true);
2542 }
2543 Actions.FinalizeDeclaration(ThisDecl);
2544 D.complete(ThisDecl);
2545 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2546 }
2547
2548 SmallVector<Decl *, 8> DeclsInGroup;
2549 Decl *FirstDecl =
2550 ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo, FRI);
2551 if (LateParsedAttrs.size() > 0)
2552 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2553 D.complete(FirstDecl);
2554 if (FirstDecl)
2555 DeclsInGroup.push_back(FirstDecl);
2556
2557 bool ExpectSemi = Context != DeclaratorContext::ForInit;
2558
2559 // If we don't have a comma, it is either the end of the list (a ';') or an
2560 // error, bail out.
2561 SourceLocation CommaLoc;
2562 while (TryConsumeToken(tok::comma, CommaLoc)) {
2563 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2564 // This comma was followed by a line-break and something which can't be
2565 // the start of a declarator. The comma was probably a typo for a
2566 // semicolon.
2567 Diag(CommaLoc, diag::err_expected_semi_declaration)
2568 << FixItHint::CreateReplacement(CommaLoc, ";");
2569 ExpectSemi = false;
2570 break;
2571 }
2572
2573 // C++23 [temp.pre]p5:
2574 // In a template-declaration, explicit specialization, or explicit
2575 // instantiation the init-declarator-list in the declaration shall
2576 // contain at most one declarator.
2577 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
2578 D.isFirstDeclarator()) {
2579 Diag(CommaLoc, diag::err_multiple_template_declarators)
2580 << TemplateInfo.Kind;
2581 }
2582
2583 // Parse the next declarator.
2584 D.clear();
2585 D.setCommaLoc(CommaLoc);
2586
2587 // Accept attributes in an init-declarator. In the first declarator in a
2588 // declaration, these would be part of the declspec. In subsequent
2589 // declarators, they become part of the declarator itself, so that they
2590 // don't apply to declarators after *this* one. Examples:
2591 // short __attribute__((common)) var; -> declspec
2592 // short var __attribute__((common)); -> declarator
2593 // short x, __attribute__((common)) var; -> declarator
2594 MaybeParseGNUAttributes(D);
2595
2596 // MSVC parses but ignores qualifiers after the comma as an extension.
2597 if (getLangOpts().MicrosoftExt)
2598 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2599
2600 ParseDeclarator(D);
2601
2602 if (getLangOpts().HLSL)
2603 MaybeParseHLSLAnnotations(D);
2604
2605 if (!D.isInvalidType()) {
2606 // C++2a [dcl.decl]p1
2607 // init-declarator:
2608 // declarator initializer[opt]
2609 // declarator requires-clause
2610 if (Tok.is(tok::kw_requires))
2611 ParseTrailingRequiresClause(D);
2612 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D, TemplateInfo);
2613 D.complete(ThisDecl);
2614 if (ThisDecl)
2615 DeclsInGroup.push_back(ThisDecl);
2616 }
2617 }
2618
2619 if (DeclEnd)
2620 *DeclEnd = Tok.getLocation();
2621
2622 if (ExpectSemi && ExpectAndConsumeSemi(
2623 Context == DeclaratorContext::File
2624 ? diag::err_invalid_token_after_toplevel_declarator
2625 : diag::err_expected_semi_declaration)) {
2626 // Okay, there was no semicolon and one was expected. If we see a
2627 // declaration specifier, just assume it was missing and continue parsing.
2628 // Otherwise things are very confused and we skip to recover.
2629 if (!isDeclarationSpecifier(ImplicitTypenameContext::No))
2631 }
2632
2633 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2634}
2635
2636/// Parse an optional simple-asm-expr and attributes, and attach them to a
2637/// declarator. Returns true on an error.
2638bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2639 // If a simple-asm-expr is present, parse it.
2640 if (Tok.is(tok::kw_asm)) {
2642 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2643 if (AsmLabel.isInvalid()) {
2644 SkipUntil(tok::semi, StopBeforeMatch);
2645 return true;
2646 }
2647
2648 D.setAsmLabel(AsmLabel.get());
2649 D.SetRangeEnd(Loc);
2650 }
2651
2652 MaybeParseGNUAttributes(D);
2653 return false;
2654}
2655
2656/// Parse 'declaration' after parsing 'declaration-specifiers
2657/// declarator'. This method parses the remainder of the declaration
2658/// (including any attributes or initializer, among other things) and
2659/// finalizes the declaration.
2660///
2661/// init-declarator: [C99 6.7]
2662/// declarator
2663/// declarator '=' initializer
2664/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2665/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2666/// [C++] declarator initializer[opt]
2667///
2668/// [C++] initializer:
2669/// [C++] '=' initializer-clause
2670/// [C++] '(' expression-list ')'
2671/// [C++0x] '=' 'default' [TODO]
2672/// [C++0x] '=' 'delete'
2673/// [C++0x] braced-init-list
2674///
2675/// According to the standard grammar, =default and =delete are function
2676/// definitions, but that definitely doesn't fit with the parser here.
2677///
2678Decl *Parser::ParseDeclarationAfterDeclarator(
2679 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2680 if (ParseAsmAttributesAfterDeclarator(D))
2681 return nullptr;
2682
2683 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2684}
2685
2686Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2687 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2688 // RAII type used to track whether we're inside an initializer.
2689 struct InitializerScopeRAII {
2690 Parser &P;
2691 Declarator &D;
2692 Decl *ThisDecl;
2693 bool Entered;
2694
2695 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2696 : P(P), D(D), ThisDecl(ThisDecl), Entered(false) {
2697 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2698 Scope *S = nullptr;
2699 if (D.getCXXScopeSpec().isSet()) {
2700 P.EnterScope(0);
2701 S = P.getCurScope();
2702 }
2703 if (ThisDecl && !ThisDecl->isInvalidDecl()) {
2704 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2705 Entered = true;
2706 }
2707 }
2708 }
2709 ~InitializerScopeRAII() {
2710 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2711 Scope *S = nullptr;
2712 if (D.getCXXScopeSpec().isSet())
2713 S = P.getCurScope();
2714
2715 if (Entered)
2716 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2717 if (S)
2718 P.ExitScope();
2719 }
2720 ThisDecl = nullptr;
2721 }
2722 };
2723
2724 enum class InitKind { Uninitialized, Equal, CXXDirect, CXXBraced };
2725 InitKind TheInitKind;
2726 // If a '==' or '+=' is found, suggest a fixit to '='.
2727 if (isTokenEqualOrEqualTypo())
2728 TheInitKind = InitKind::Equal;
2729 else if (Tok.is(tok::l_paren))
2730 TheInitKind = InitKind::CXXDirect;
2731 else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2732 (!CurParsedObjCImpl || !D.isFunctionDeclarator()))
2733 TheInitKind = InitKind::CXXBraced;
2734 else
2735 TheInitKind = InitKind::Uninitialized;
2736 if (TheInitKind != InitKind::Uninitialized)
2737 D.setHasInitializer();
2738
2739 // Inform Sema that we just parsed this declarator.
2740 Decl *ThisDecl = nullptr;
2741 Decl *OuterDecl = nullptr;
2742 switch (TemplateInfo.Kind) {
2743 case ParsedTemplateInfo::NonTemplate:
2744 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2745 break;
2746
2747 case ParsedTemplateInfo::Template:
2748 case ParsedTemplateInfo::ExplicitSpecialization: {
2749 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2750 *TemplateInfo.TemplateParams,
2751 D);
2752 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) {
2753 // Re-direct this decl to refer to the templated decl so that we can
2754 // initialize it.
2755 ThisDecl = VT->getTemplatedDecl();
2756 OuterDecl = VT;
2757 }
2758 break;
2759 }
2760 case ParsedTemplateInfo::ExplicitInstantiation: {
2761 if (Tok.is(tok::semi)) {
2762 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2763 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2764 if (ThisRes.isInvalid()) {
2765 SkipUntil(tok::semi, StopBeforeMatch);
2766 return nullptr;
2767 }
2768 ThisDecl = ThisRes.get();
2769 } else {
2770 // FIXME: This check should be for a variable template instantiation only.
2771
2772 // Check that this is a valid instantiation
2773 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2774 // If the declarator-id is not a template-id, issue a diagnostic and
2775 // recover by ignoring the 'template' keyword.
2776 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2777 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2778 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2779 } else {
2780 SourceLocation LAngleLoc =
2781 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2782 Diag(D.getIdentifierLoc(),
2783 diag::err_explicit_instantiation_with_definition)
2784 << SourceRange(TemplateInfo.TemplateLoc)
2785 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2786
2787 // Recover as if it were an explicit specialization.
2788 TemplateParameterLists FakedParamLists;
2789 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2790 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, {},
2791 LAngleLoc, nullptr));
2792
2793 ThisDecl =
2794 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2795 }
2796 }
2797 break;
2798 }
2799 }
2800
2803 switch (TheInitKind) {
2804 // Parse declarator '=' initializer.
2805 case InitKind::Equal: {
2806 SourceLocation EqualLoc = ConsumeToken();
2807
2808 if (Tok.is(tok::kw_delete)) {
2809 if (D.isFunctionDeclarator())
2810 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2811 << 1 /* delete */;
2812 else
2813 Diag(ConsumeToken(), diag::err_deleted_non_function);
2814 SkipDeletedFunctionBody();
2815 } else if (Tok.is(tok::kw_default)) {
2816 if (D.isFunctionDeclarator())
2817 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2818 << 0 /* default */;
2819 else
2820 Diag(ConsumeToken(), diag::err_default_special_members)
2821 << getLangOpts().CPlusPlus20;
2822 } else {
2823 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2824
2825 if (Tok.is(tok::code_completion)) {
2826 cutOffParsing();
2828 ThisDecl);
2829 Actions.FinalizeDeclaration(ThisDecl);
2830 return nullptr;
2831 }
2832
2833 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2834 ExprResult Init = ParseInitializer();
2835
2836 // If this is the only decl in (possibly) range based for statement,
2837 // our best guess is that the user meant ':' instead of '='.
2838 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2839 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2840 << FixItHint::CreateReplacement(EqualLoc, ":");
2841 // We are trying to stop parser from looking for ';' in this for
2842 // statement, therefore preventing spurious errors to be issued.
2843 FRI->ColonLoc = EqualLoc;
2844 Init = ExprError();
2845 FRI->RangeExpr = Init;
2846 }
2847
2848 if (Init.isInvalid()) {
2850 StopTokens.push_back(tok::comma);
2851 if (D.getContext() == DeclaratorContext::ForInit ||
2852 D.getContext() == DeclaratorContext::SelectionInit)
2853 StopTokens.push_back(tok::r_paren);
2854 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2855 Actions.ActOnInitializerError(ThisDecl);
2856 } else
2857 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2858 /*DirectInit=*/false);
2859 }
2860 break;
2861 }
2862 case InitKind::CXXDirect: {
2863 // Parse C++ direct initializer: '(' expression-list ')'
2864 BalancedDelimiterTracker T(*this, tok::l_paren);
2865 T.consumeOpen();
2866
2867 ExprVector Exprs;
2868
2869 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2870
2871 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2872 auto RunSignatureHelp = [&]() {
2873 QualType PreferredType =
2875 ThisVarDecl->getType()->getCanonicalTypeInternal(),
2876 ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2877 /*Braced=*/false);
2878 CalledSignatureHelp = true;
2879 return PreferredType;
2880 };
2881 auto SetPreferredType = [&] {
2882 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2883 };
2884
2885 llvm::function_ref<void()> ExpressionStarts;
2886 if (ThisVarDecl) {
2887 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2888 // VarDecl. This is an error and it is reported in a call to
2889 // Actions.ActOnInitializerError(). However, we call
2890 // ProduceConstructorSignatureHelp only on VarDecls.
2891 ExpressionStarts = SetPreferredType;
2892 }
2893
2894 bool SawError = ParseExpressionList(Exprs, ExpressionStarts);
2895
2896 if (SawError) {
2897 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2899 ThisVarDecl->getType()->getCanonicalTypeInternal(),
2900 ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2901 /*Braced=*/false);
2902 CalledSignatureHelp = true;
2903 }
2904 Actions.ActOnInitializerError(ThisDecl);
2905 SkipUntil(tok::r_paren, StopAtSemi);
2906 } else {
2907 // Match the ')'.
2908 T.consumeClose();
2909
2910 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2911 T.getCloseLocation(),
2912 Exprs);
2913 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2914 /*DirectInit=*/true);
2915 }
2916 break;
2917 }
2918 case InitKind::CXXBraced: {
2919 // Parse C++0x braced-init-list.
2920 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2921
2922 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2923
2924 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2925 ExprResult Init(ParseBraceInitializer());
2926
2927 if (Init.isInvalid()) {
2928 Actions.ActOnInitializerError(ThisDecl);
2929 } else
2930 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2931 break;
2932 }
2933 case InitKind::Uninitialized: {
2934 Actions.ActOnUninitializedDecl(ThisDecl);
2935 break;
2936 }
2937 }
2938
2939 Actions.FinalizeDeclaration(ThisDecl);
2940 return OuterDecl ? OuterDecl : ThisDecl;
2941}
2942
2943/// ParseSpecifierQualifierList
2944/// specifier-qualifier-list:
2945/// type-specifier specifier-qualifier-list[opt]
2946/// type-qualifier specifier-qualifier-list[opt]
2947/// [GNU] attributes specifier-qualifier-list[opt]
2948///
2949void Parser::ParseSpecifierQualifierList(
2950 DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename,
2951 AccessSpecifier AS, DeclSpecContext DSC) {
2952 ParsedTemplateInfo TemplateInfo;
2953 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2954 /// parse declaration-specifiers and complain about extra stuff.
2955 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2956 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC, nullptr,
2957 AllowImplicitTypename);
2958
2959 // Validate declspec for type-name.
2960 unsigned Specs = DS.getParsedSpecifiers();
2961 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2962 Diag(Tok, diag::err_expected_type);
2963 DS.SetTypeSpecError();
2964 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2965 Diag(Tok, diag::err_typename_requires_specqual);
2966 if (!DS.hasTypeSpecifier())
2967 DS.SetTypeSpecError();
2968 }
2969
2970 // Issue diagnostic and remove storage class if present.
2973 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2974 else
2976 diag::err_typename_invalid_storageclass);
2978 }
2979
2980 // Issue diagnostic and remove function specifier if present.
2981 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2982 if (DS.isInlineSpecified())
2983 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2984 if (DS.isVirtualSpecified())
2985 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2986 if (DS.hasExplicitSpecifier())
2987 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2988 if (DS.isNoreturnSpecified())
2989 Diag(DS.getNoreturnSpecLoc(), diag::err_typename_invalid_functionspec);
2990 DS.ClearFunctionSpecs();
2991 }
2992
2993 // Issue diagnostic and remove constexpr specifier if present.
2994 if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2995 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2996 << static_cast<int>(DS.getConstexprSpecifier());
2997 DS.ClearConstexprSpec();
2998 }
2999}
3000
3001/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
3002/// specified token is valid after the identifier in a declarator which
3003/// immediately follows the declspec. For example, these things are valid:
3004///
3005/// int x [ 4]; // direct-declarator
3006/// int x ( int y); // direct-declarator
3007/// int(int x ) // direct-declarator
3008/// int x ; // simple-declaration
3009/// int x = 17; // init-declarator-list
3010/// int x , y; // init-declarator-list
3011/// int x __asm__ ("foo"); // init-declarator-list
3012/// int x : 4; // struct-declarator
3013/// int x { 5}; // C++'0x unified initializers
3014///
3015/// This is not, because 'x' does not immediately follow the declspec (though
3016/// ')' happens to be valid anyway).
3017/// int (x)
3018///
3020 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
3021 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
3022 tok::colon);
3023}
3024
3025/// ParseImplicitInt - This method is called when we have an non-typename
3026/// identifier in a declspec (which normally terminates the decl spec) when
3027/// the declspec has no type specifier. In this case, the declspec is either
3028/// malformed or is "implicit int" (in K&R and C89).
3029///
3030/// This method handles diagnosing this prettily and returns false if the
3031/// declspec is done being processed. If it recovers and thinks there may be
3032/// other pieces of declspec after it, it returns true.
3033///
3034bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
3035 ParsedTemplateInfo &TemplateInfo,
3036 AccessSpecifier AS, DeclSpecContext DSC,
3037 ParsedAttributes &Attrs) {
3038 assert(Tok.is(tok::identifier) && "should have identifier");
3039
3041 // If we see an identifier that is not a type name, we normally would
3042 // parse it as the identifier being declared. However, when a typename
3043 // is typo'd or the definition is not included, this will incorrectly
3044 // parse the typename as the identifier name and fall over misparsing
3045 // later parts of the diagnostic.
3046 //
3047 // As such, we try to do some look-ahead in cases where this would
3048 // otherwise be an "implicit-int" case to see if this is invalid. For
3049 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
3050 // an identifier with implicit int, we'd get a parse error because the
3051 // next token is obviously invalid for a type. Parse these as a case
3052 // with an invalid type specifier.
3053 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
3054
3055 // Since we know that this either implicit int (which is rare) or an
3056 // error, do lookahead to try to do better recovery. This never applies
3057 // within a type specifier. Outside of C++, we allow this even if the
3058 // language doesn't "officially" support implicit int -- we support
3059 // implicit int as an extension in some language modes.
3060 if (!isTypeSpecifier(DSC) && getLangOpts().isImplicitIntAllowed() &&
3062 // If this token is valid for implicit int, e.g. "static x = 4", then
3063 // we just avoid eating the identifier, so it will be parsed as the
3064 // identifier in the declarator.
3065 return false;
3066 }
3067
3068 // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
3069 // for incomplete declarations such as `pipe p`.
3070 if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
3071 return false;
3072
3073 if (getLangOpts().CPlusPlus &&
3075 // Don't require a type specifier if we have the 'auto' storage class
3076 // specifier in C++98 -- we'll promote it to a type specifier.
3077 if (SS)
3078 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
3079 return false;
3080 }
3081
3082 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
3083 getLangOpts().MSVCCompat) {
3084 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
3085 // Give Sema a chance to recover if we are in a template with dependent base
3086 // classes.
3088 *Tok.getIdentifierInfo(), Tok.getLocation(),
3089 DSC == DeclSpecContext::DSC_template_type_arg)) {
3090 const char *PrevSpec;
3091 unsigned DiagID;
3092 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
3093 Actions.getASTContext().getPrintingPolicy());
3094 DS.SetRangeEnd(Tok.getLocation());
3095 ConsumeToken();
3096 return false;
3097 }
3098 }
3099
3100 // Otherwise, if we don't consume this token, we are going to emit an
3101 // error anyway. Try to recover from various common problems. Check
3102 // to see if this was a reference to a tag name without a tag specified.
3103 // This is a common problem in C (saying 'foo' instead of 'struct foo').
3104 //
3105 // C++ doesn't need this, and isTagName doesn't take SS.
3106 if (SS == nullptr) {
3107 const char *TagName = nullptr, *FixitTagName = nullptr;
3108 tok::TokenKind TagKind = tok::unknown;
3109
3110 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
3111 default: break;
3112 case DeclSpec::TST_enum:
3113 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
3115 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
3117 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
3119 TagName="__interface"; FixitTagName = "__interface ";
3120 TagKind=tok::kw___interface;break;
3122 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
3123 }
3124
3125 if (TagName) {
3126 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
3127 LookupResult R(Actions, TokenName, SourceLocation(),
3129
3130 Diag(Loc, diag::err_use_of_tag_name_without_tag)
3131 << TokenName << TagName << getLangOpts().CPlusPlus
3132 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
3133
3134 if (Actions.LookupName(R, getCurScope())) {
3135 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
3136 I != IEnd; ++I)
3137 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
3138 << TokenName << TagName;
3139 }
3140
3141 // Parse this as a tag as if the missing tag were present.
3142 if (TagKind == tok::kw_enum)
3143 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
3144 DeclSpecContext::DSC_normal);
3145 else
3146 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
3147 /*EnteringContext*/ false,
3148 DeclSpecContext::DSC_normal, Attrs);
3149 return true;
3150 }
3151 }
3152
3153 // Determine whether this identifier could plausibly be the name of something
3154 // being declared (with a missing type).
3155 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
3156 DSC == DeclSpecContext::DSC_class)) {
3157 // Look ahead to the next token to try to figure out what this declaration
3158 // was supposed to be.
3159 switch (NextToken().getKind()) {
3160 case tok::l_paren: {
3161 // static x(4); // 'x' is not a type
3162 // x(int n); // 'x' is not a type
3163 // x (*p)[]; // 'x' is a type
3164 //
3165 // Since we're in an error case, we can afford to perform a tentative
3166 // parse to determine which case we're in.
3167 TentativeParsingAction PA(*this);
3168 ConsumeToken();
3169 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
3170 PA.Revert();
3171
3172 if (TPR != TPResult::False) {
3173 // The identifier is followed by a parenthesized declarator.
3174 // It's supposed to be a type.
3175 break;
3176 }
3177
3178 // If we're in a context where we could be declaring a constructor,
3179 // check whether this is a constructor declaration with a bogus name.
3180 if (DSC == DeclSpecContext::DSC_class ||
3181 (DSC == DeclSpecContext::DSC_top_level && SS)) {
3183 if (Actions.isCurrentClassNameTypo(II, SS)) {
3184 Diag(Loc, diag::err_constructor_bad_name)
3185 << Tok.getIdentifierInfo() << II
3187 Tok.setIdentifierInfo(II);
3188 }
3189 }
3190 // Fall through.
3191 [[fallthrough]];
3192 }
3193 case tok::comma:
3194 case tok::equal:
3195 case tok::kw_asm:
3196 case tok::l_brace:
3197 case tok::l_square:
3198 case tok::semi:
3199 // This looks like a variable or function declaration. The type is
3200 // probably missing. We're done parsing decl-specifiers.
3201 // But only if we are not in a function prototype scope.
3202 if (getCurScope()->isFunctionPrototypeScope())
3203 break;
3204 if (SS)
3205 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
3206 return false;
3207
3208 default:
3209 // This is probably supposed to be a type. This includes cases like:
3210 // int f(itn);
3211 // struct S { unsigned : 4; };
3212 break;
3213 }
3214 }
3215
3216 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
3217 // and attempt to recover.
3218 ParsedType T;
3220 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
3221 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
3222 IsTemplateName);
3223 if (T) {
3224 // The action has suggested that the type T could be used. Set that as
3225 // the type in the declaration specifiers, consume the would-be type
3226 // name token, and we're done.
3227 const char *PrevSpec;
3228 unsigned DiagID;
3229 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
3230 Actions.getASTContext().getPrintingPolicy());
3231 DS.SetRangeEnd(Tok.getLocation());
3232 ConsumeToken();
3233 // There may be other declaration specifiers after this.
3234 return true;
3235 } else if (II != Tok.getIdentifierInfo()) {
3236 // If no type was suggested, the correction is to a keyword
3237 Tok.setKind(II->getTokenID());
3238 // There may be other declaration specifiers after this.
3239 return true;
3240 }
3241
3242 // Otherwise, the action had no suggestion for us. Mark this as an error.
3243 DS.SetTypeSpecError();
3244 DS.SetRangeEnd(Tok.getLocation());
3245 ConsumeToken();
3246
3247 // Eat any following template arguments.
3248 if (IsTemplateName) {
3249 SourceLocation LAngle, RAngle;
3250 TemplateArgList Args;
3251 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
3252 }
3253
3254 // TODO: Could inject an invalid typedef decl in an enclosing scope to
3255 // avoid rippling error messages on subsequent uses of the same type,
3256 // could be useful if #include was forgotten.
3257 return true;
3258}
3259
3260/// Determine the declaration specifier context from the declarator
3261/// context.
3262///
3263/// \param Context the declarator context, which is one of the
3264/// DeclaratorContext enumerator values.
3265Parser::DeclSpecContext
3266Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
3267 switch (Context) {
3269 return DeclSpecContext::DSC_class;
3271 return DeclSpecContext::DSC_top_level;
3273 return DeclSpecContext::DSC_template_param;
3275 return DeclSpecContext::DSC_template_arg;
3277 return DeclSpecContext::DSC_template_type_arg;
3280 return DeclSpecContext::DSC_trailing;
3283 return DeclSpecContext::DSC_alias_declaration;
3285 return DeclSpecContext::DSC_association;
3287 return DeclSpecContext::DSC_type_specifier;
3289 return DeclSpecContext::DSC_condition;
3291 return DeclSpecContext::DSC_conv_operator;
3293 return DeclSpecContext::DSC_new;
3308 return DeclSpecContext::DSC_normal;
3309 }
3310
3311 llvm_unreachable("Missing DeclaratorContext case");
3312}
3313
3314/// ParseAlignArgument - Parse the argument to an alignment-specifier.
3315///
3316/// [C11] type-id
3317/// [C11] constant-expression
3318/// [C++0x] type-id ...[opt]
3319/// [C++0x] assignment-expression ...[opt]
3320ExprResult Parser::ParseAlignArgument(StringRef KWName, SourceLocation Start,
3321 SourceLocation &EllipsisLoc, bool &IsType,
3323 ExprResult ER;
3324 if (isTypeIdInParens()) {
3326 ParsedType Ty = ParseTypeName().get();
3327 SourceRange TypeRange(Start, Tok.getLocation());
3328 if (Actions.ActOnAlignasTypeArgument(KWName, Ty, TypeLoc, TypeRange))
3329 return ExprError();
3330 TypeResult = Ty;
3331 IsType = true;
3332 } else {
3334 IsType = false;
3335 }
3336
3338 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3339
3340 return ER;
3341}
3342
3343/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
3344/// attribute to Attrs.
3345///
3346/// alignment-specifier:
3347/// [C11] '_Alignas' '(' type-id ')'
3348/// [C11] '_Alignas' '(' constant-expression ')'
3349/// [C++11] 'alignas' '(' type-id ...[opt] ')'
3350/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
3351void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
3352 SourceLocation *EndLoc) {
3353 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
3354 "Not an alignment-specifier!");
3355 Token KWTok = Tok;
3356 IdentifierInfo *KWName = KWTok.getIdentifierInfo();
3357 auto Kind = KWTok.getKind();
3358 SourceLocation KWLoc = ConsumeToken();
3359
3360 BalancedDelimiterTracker T(*this, tok::l_paren);
3361 if (T.expectAndConsume())
3362 return;
3363
3364 bool IsType;
3366 SourceLocation EllipsisLoc;
3367 ExprResult ArgExpr =
3368 ParseAlignArgument(PP.getSpelling(KWTok), T.getOpenLocation(),
3369 EllipsisLoc, IsType, TypeResult);
3370 if (ArgExpr.isInvalid()) {
3371 T.skipToEnd();
3372 return;
3373 }
3374
3375 T.consumeClose();
3376 if (EndLoc)
3377 *EndLoc = T.getCloseLocation();
3378
3379 if (IsType) {
3380 Attrs.addNewTypeAttr(KWName, KWLoc, nullptr, KWLoc, TypeResult, Kind,
3381 EllipsisLoc);
3382 } else {
3383 ArgsVector ArgExprs;
3384 ArgExprs.push_back(ArgExpr.get());
3385 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1, Kind,
3386 EllipsisLoc);
3387 }
3388}
3389
3390void Parser::DistributeCLateParsedAttrs(Decl *Dcl,
3391 LateParsedAttrList *LateAttrs) {
3392 if (!LateAttrs)
3393 return;
3394
3395 if (Dcl) {
3396 for (auto *LateAttr : *LateAttrs) {
3397 if (LateAttr->Decls.empty())
3398 LateAttr->addDecl(Dcl);
3399 }
3400 }
3401}
3402
3403/// Bounds attributes (e.g., counted_by):
3404/// AttrName '(' expression ')'
3405void Parser::ParseBoundsAttribute(IdentifierInfo &AttrName,
3406 SourceLocation AttrNameLoc,
3407 ParsedAttributes &Attrs,
3408 IdentifierInfo *ScopeName,
3409 SourceLocation ScopeLoc,
3410 ParsedAttr::Form Form) {
3411 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
3412
3413 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3414 Parens.consumeOpen();
3415
3416 if (Tok.is(tok::r_paren)) {
3417 Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
3418 Parens.consumeClose();
3419 return;
3420 }
3421
3422 ArgsVector ArgExprs;
3423 // Don't evaluate argument when the attribute is ignored.
3424 using ExpressionKind =
3428 ExpressionKind::EK_AttrArgument);
3429
3430 ExprResult ArgExpr(
3432
3433 if (ArgExpr.isInvalid()) {
3434 Parens.skipToEnd();
3435 return;
3436 }
3437
3438 ArgExprs.push_back(ArgExpr.get());
3439 Parens.consumeClose();
3440
3441 ASTContext &Ctx = Actions.getASTContext();
3442
3443 ArgExprs.push_back(IntegerLiteral::Create(
3444 Ctx, llvm::APInt(Ctx.getTypeSize(Ctx.getSizeType()), 0),
3445 Ctx.getSizeType(), SourceLocation()));
3446
3447 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
3448 ScopeName, ScopeLoc, ArgExprs.data(), ArgExprs.size(), Form);
3449}
3450
3451ExprResult Parser::ParseExtIntegerArgument() {
3452 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
3453 "Not an extended int type");
3454 ConsumeToken();
3455
3456 BalancedDelimiterTracker T(*this, tok::l_paren);
3457 if (T.expectAndConsume())
3458 return ExprError();
3459
3461 if (ER.isInvalid()) {
3462 T.skipToEnd();
3463 return ExprError();
3464 }
3465
3466 if(T.consumeClose())
3467 return ExprError();
3468 return ER;
3469}
3470
3471/// Determine whether we're looking at something that might be a declarator
3472/// in a simple-declaration. If it can't possibly be a declarator, maybe
3473/// diagnose a missing semicolon after a prior tag definition in the decl
3474/// specifier.
3475///
3476/// \return \c true if an error occurred and this can't be any kind of
3477/// declaration.
3478bool
3479Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
3480 DeclSpecContext DSContext,
3481 LateParsedAttrList *LateAttrs) {
3482 assert(DS.hasTagDefinition() && "shouldn't call this");
3483
3484 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3485 DSContext == DeclSpecContext::DSC_top_level);
3486
3487 if (getLangOpts().CPlusPlus &&
3488 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
3489 tok::annot_template_id) &&
3490 TryAnnotateCXXScopeToken(EnteringContext)) {
3492 return true;
3493 }
3494
3495 bool HasScope = Tok.is(tok::annot_cxxscope);
3496 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
3497 Token AfterScope = HasScope ? NextToken() : Tok;
3498
3499 // Determine whether the following tokens could possibly be a
3500 // declarator.
3501 bool MightBeDeclarator = true;
3502 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
3503 // A declarator-id can't start with 'typename'.
3504 MightBeDeclarator = false;
3505 } else if (AfterScope.is(tok::annot_template_id)) {
3506 // If we have a type expressed as a template-id, this cannot be a
3507 // declarator-id (such a type cannot be redeclared in a simple-declaration).
3508 TemplateIdAnnotation *Annot =
3509 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
3510 if (Annot->Kind == TNK_Type_template)
3511 MightBeDeclarator = false;
3512 } else if (AfterScope.is(tok::identifier)) {
3513 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
3514
3515 // These tokens cannot come after the declarator-id in a
3516 // simple-declaration, and are likely to come after a type-specifier.
3517 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
3518 tok::annot_cxxscope, tok::coloncolon)) {
3519 // Missing a semicolon.
3520 MightBeDeclarator = false;
3521 } else if (HasScope) {
3522 // If the declarator-id has a scope specifier, it must redeclare a
3523 // previously-declared entity. If that's a type (and this is not a
3524 // typedef), that's an error.
3525 CXXScopeSpec SS;
3527 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3528 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
3529 Sema::NameClassification Classification = Actions.ClassifyName(
3530 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
3531 /*CCC=*/nullptr);
3532 switch (Classification.getKind()) {
3533 case Sema::NC_Error:
3535 return true;
3536
3537 case Sema::NC_Keyword:
3538 llvm_unreachable("typo correction is not possible here");
3539
3540 case Sema::NC_Type:
3544 // Not a previously-declared non-type entity.
3545 MightBeDeclarator = false;
3546 break;
3547
3548 case Sema::NC_Unknown:
3549 case Sema::NC_NonType:
3554 case Sema::NC_Concept:
3555 // Might be a redeclaration of a prior entity.
3556 break;
3557 }
3558 }
3559 }
3560
3561 if (MightBeDeclarator)
3562 return false;
3563
3564 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
3566 diag::err_expected_after)
3567 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
3568
3569 // Try to recover from the typo, by dropping the tag definition and parsing
3570 // the problematic tokens as a type.
3571 //
3572 // FIXME: Split the DeclSpec into pieces for the standalone
3573 // declaration and pieces for the following declaration, instead
3574 // of assuming that all the other pieces attach to new declaration,
3575 // and call ParsedFreeStandingDeclSpec as appropriate.
3576 DS.ClearTypeSpecType();
3577 ParsedTemplateInfo NotATemplate;
3578 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
3579 return false;
3580}
3581
3582/// ParseDeclarationSpecifiers
3583/// declaration-specifiers: [C99 6.7]
3584/// storage-class-specifier declaration-specifiers[opt]
3585/// type-specifier declaration-specifiers[opt]
3586/// [C99] function-specifier declaration-specifiers[opt]
3587/// [C11] alignment-specifier declaration-specifiers[opt]
3588/// [GNU] attributes declaration-specifiers[opt]
3589/// [Clang] '__module_private__' declaration-specifiers[opt]
3590/// [ObjC1] '__kindof' declaration-specifiers[opt]
3591///
3592/// storage-class-specifier: [C99 6.7.1]
3593/// 'typedef'
3594/// 'extern'
3595/// 'static'
3596/// 'auto'
3597/// 'register'
3598/// [C++] 'mutable'
3599/// [C++11] 'thread_local'
3600/// [C11] '_Thread_local'
3601/// [GNU] '__thread'
3602/// function-specifier: [C99 6.7.4]
3603/// [C99] 'inline'
3604/// [C++] 'virtual'
3605/// [C++] 'explicit'
3606/// [OpenCL] '__kernel'
3607/// 'friend': [C++ dcl.friend]
3608/// 'constexpr': [C++0x dcl.constexpr]
3609void Parser::ParseDeclarationSpecifiers(
3610 DeclSpec &DS, ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
3611 DeclSpecContext DSContext, LateParsedAttrList *LateAttrs,
3612 ImplicitTypenameContext AllowImplicitTypename) {
3613 if (DS.getSourceRange().isInvalid()) {
3614 // Start the range at the current token but make the end of the range
3615 // invalid. This will make the entire range invalid unless we successfully
3616 // consume a token.
3617 DS.SetRangeStart(Tok.getLocation());
3619 }
3620
3621 // If we are in a operator context, convert it back into a type specifier
3622 // context for better error handling later on.
3623 if (DSContext == DeclSpecContext::DSC_conv_operator) {
3624 // No implicit typename here.
3625 AllowImplicitTypename = ImplicitTypenameContext::No;
3626 DSContext = DeclSpecContext::DSC_type_specifier;
3627 }
3628
3629 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3630 DSContext == DeclSpecContext::DSC_top_level);
3631 bool AttrsLastTime = false;
3632 ParsedAttributes attrs(AttrFactory);
3633 // We use Sema's policy to get bool macros right.
3634 PrintingPolicy Policy = Actions.getPrintingPolicy();
3635 while (true) {
3636 bool isInvalid = false;
3637 bool isStorageClass = false;
3638 const char *PrevSpec = nullptr;
3639 unsigned DiagID = 0;
3640
3641 // This value needs to be set to the location of the last token if the last
3642 // token of the specifier is already consumed.
3643 SourceLocation ConsumedEnd;
3644
3645 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3646 // implementation for VS2013 uses _Atomic as an identifier for one of the
3647 // classes in <atomic>.
3648 //
3649 // A typedef declaration containing _Atomic<...> is among the places where
3650 // the class is used. If we are currently parsing such a declaration, treat
3651 // the token as an identifier.
3652 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3654 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3655 Tok.setKind(tok::identifier);
3656
3658
3659 // Helper for image types in OpenCL.
3660 auto handleOpenCLImageKW = [&] (StringRef Ext, TypeSpecifierType ImageTypeSpec) {
3661 // Check if the image type is supported and otherwise turn the keyword into an identifier
3662 // because image types from extensions are not reserved identifiers.
3663 if (!StringRef(Ext).empty() && !getActions().getOpenCLOptions().isSupported(Ext, getLangOpts())) {
3665 Tok.setKind(tok::identifier);
3666 return false;
3667 }
3668 isInvalid = DS.SetTypeSpecType(ImageTypeSpec, Loc, PrevSpec, DiagID, Policy);
3669 return true;
3670 };
3671
3672 // Turn off usual access checking for template specializations and
3673 // instantiations.
3674 bool IsTemplateSpecOrInst =
3675 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3676 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3677
3678 switch (Tok.getKind()) {
3679 default:
3680 if (Tok.isRegularKeywordAttribute())
3681 goto Attribute;
3682
3683 DoneWithDeclSpec:
3684 if (!AttrsLastTime)
3685 ProhibitAttributes(attrs);
3686 else {
3687 // Reject C++11 / C23 attributes that aren't type attributes.
3688 for (const ParsedAttr &PA : attrs) {
3689 if (!PA.isCXX11Attribute() && !PA.isC23Attribute() &&
3690 !PA.isRegularKeywordAttribute())
3691 continue;
3692 if (PA.getKind() == ParsedAttr::UnknownAttribute)
3693 // We will warn about the unknown attribute elsewhere (in
3694 // SemaDeclAttr.cpp)
3695 continue;
3696 // GCC ignores this attribute when placed on the DeclSpec in [[]]
3697 // syntax, so we do the same.
3698 if (PA.getKind() == ParsedAttr::AT_VectorSize) {
3699 Diag(PA.getLoc(), diag::warn_attribute_ignored) << PA;
3700 PA.setInvalid();
3701 continue;
3702 }
3703 // We reject AT_LifetimeBound and AT_AnyX86NoCfCheck, even though they
3704 // are type attributes, because we historically haven't allowed these
3705 // to be used as type attributes in C++11 / C23 syntax.
3706 if (PA.isTypeAttr() && PA.getKind() != ParsedAttr::AT_LifetimeBound &&
3707 PA.getKind() != ParsedAttr::AT_AnyX86NoCfCheck)
3708 continue;
3709 Diag(PA.getLoc(), diag::err_attribute_not_type_attr)
3710 << PA << PA.isRegularKeywordAttribute();
3711 PA.setInvalid();
3712 }
3713
3714 DS.takeAttributesFrom(attrs);
3715 }
3716
3717 // If this is not a declaration specifier token, we're done reading decl
3718 // specifiers. First verify that DeclSpec's are consistent.
3719 DS.Finish(Actions, Policy);
3720 return;
3721
3722 // alignment-specifier
3723 case tok::kw__Alignas:
3724 diagnoseUseOfC11Keyword(Tok);
3725 [[fallthrough]];
3726 case tok::kw_alignas:
3727 // _Alignas and alignas (C23, not C++) should parse the same way. The C++
3728 // parsing for alignas happens through the usual attribute parsing. This
3729 // ensures that an alignas specifier can appear in a type position in C
3730 // despite that not being valid in C++.
3731 if (getLangOpts().C23 || Tok.getKind() == tok::kw__Alignas) {
3732 if (Tok.getKind() == tok::kw_alignas)
3733 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
3734 ParseAlignmentSpecifier(DS.getAttributes());
3735 continue;
3736 }
3737 [[fallthrough]];
3738 case tok::l_square:
3739 if (!isAllowedCXX11AttributeSpecifier())
3740 goto DoneWithDeclSpec;
3741
3742 Attribute:
3743 ProhibitAttributes(attrs);
3744 // FIXME: It would be good to recover by accepting the attributes,
3745 // but attempting to do that now would cause serious
3746 // madness in terms of diagnostics.
3747 attrs.clear();
3748 attrs.Range = SourceRange();
3749
3750 ParseCXX11Attributes(attrs);
3751 AttrsLastTime = true;
3752 continue;
3753
3754 case tok::code_completion: {
3757 if (DS.hasTypeSpecifier()) {
3758 bool AllowNonIdentifiers
3763 Scope::AtCatchScope)) == 0;
3764 bool AllowNestedNameSpecifiers
3765 = DSContext == DeclSpecContext::DSC_top_level ||
3766 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3767
3768 cutOffParsing();
3770 getCurScope(), DS, AllowNonIdentifiers, AllowNestedNameSpecifiers);
3771 return;
3772 }
3773
3774 // Class context can appear inside a function/block, so prioritise that.
3775 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3776 CCC = DSContext == DeclSpecContext::DSC_class
3779 else if (DSContext == DeclSpecContext::DSC_class)
3781 else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3783 else if (CurParsedObjCImpl)
3785
3786 cutOffParsing();
3788 return;
3789 }
3790
3791 case tok::coloncolon: // ::foo::bar
3792 // C++ scope specifier. Annotate and loop, or bail out on error.
3793 if (getLangOpts().CPlusPlus &&
3794 TryAnnotateCXXScopeToken(EnteringContext)) {
3795 if (!DS.hasTypeSpecifier())
3796 DS.SetTypeSpecError();
3797 goto DoneWithDeclSpec;
3798 }
3799 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3800 goto DoneWithDeclSpec;
3801 continue;
3802
3803 case tok::annot_cxxscope: {
3804 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3805 goto DoneWithDeclSpec;
3806
3807 CXXScopeSpec SS;
3808 if (TemplateInfo.TemplateParams)
3809 SS.setTemplateParamLists(*TemplateInfo.TemplateParams);
3811 Tok.getAnnotationRange(),
3812 SS);
3813
3814 // We are looking for a qualified typename.
3815 Token Next = NextToken();
3816
3817 TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
3818 ? takeTemplateIdAnnotation(Next)
3819 : nullptr;
3820 if (TemplateId && TemplateId->hasInvalidName()) {
3821 // We found something like 'T::U<Args> x', but U is not a template.
3822 // Assume it was supposed to be a type.
3823 DS.SetTypeSpecError();
3824 ConsumeAnnotationToken();
3825 break;
3826 }
3827
3828 if (TemplateId && TemplateId->Kind == TNK_Type_template) {
3829 // We have a qualified template-id, e.g., N::A<int>
3830
3831 // If this would be a valid constructor declaration with template
3832 // arguments, we will reject the attempt to form an invalid type-id
3833 // referring to the injected-class-name when we annotate the token,
3834 // per C++ [class.qual]p2.
3835 //
3836 // To improve diagnostics for this case, parse the declaration as a
3837 // constructor (and reject the extra template arguments later).
3838 if ((DSContext == DeclSpecContext::DSC_top_level ||
3839 DSContext == DeclSpecContext::DSC_class) &&
3840 TemplateId->Name &&
3841 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3842 isConstructorDeclarator(/*Unqualified=*/false,
3843 /*DeductionGuide=*/false,
3844 DS.isFriendSpecified())) {
3845 // The user meant this to be an out-of-line constructor
3846 // definition, but template arguments are not allowed
3847 // there. Just allow this as a constructor; we'll
3848 // complain about it later.
3849 goto DoneWithDeclSpec;
3850 }
3851
3852 DS.getTypeSpecScope() = SS;
3853 ConsumeAnnotationToken(); // The C++ scope.
3854 assert(Tok.is(tok::annot_template_id) &&
3855 "ParseOptionalCXXScopeSpecifier not working");
3856 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3857 continue;
3858 }
3859
3860 if (TemplateId && TemplateId->Kind == TNK_Concept_template) {
3861 DS.getTypeSpecScope() = SS;
3862 // This is probably a qualified placeholder-specifier, e.g., ::C<int>
3863 // auto ... Consume the scope annotation and continue to consume the
3864 // template-id as a placeholder-specifier. Let the next iteration
3865 // diagnose a missing auto.
3866 ConsumeAnnotationToken();
3867 continue;
3868 }
3869
3870 if (Next.is(tok::annot_typename)) {
3871 DS.getTypeSpecScope() = SS;
3872 ConsumeAnnotationToken(); // The C++ scope.
3875 Tok.getAnnotationEndLoc(),
3876 PrevSpec, DiagID, T, Policy);
3877 if (isInvalid)
3878 break;
3880 ConsumeAnnotationToken(); // The typename
3881 }
3882
3883 if (AllowImplicitTypename == ImplicitTypenameContext::Yes &&
3884 Next.is(tok::annot_template_id) &&
3885 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3887 DS.getTypeSpecScope() = SS;
3888 ConsumeAnnotationToken(); // The C++ scope.
3889 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3890 continue;
3891 }
3892
3893 if (Next.isNot(tok::identifier))
3894 goto DoneWithDeclSpec;
3895
3896 // Check whether this is a constructor declaration. If we're in a
3897 // context where the identifier could be a class name, and it has the
3898 // shape of a constructor declaration, process it as one.
3899 if ((DSContext == DeclSpecContext::DSC_top_level ||
3900 DSContext == DeclSpecContext::DSC_class) &&
3901 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3902 &SS) &&
3903 isConstructorDeclarator(/*Unqualified=*/false,
3904 /*DeductionGuide=*/false,
3905 DS.isFriendSpecified(),
3906 &TemplateInfo))
3907 goto DoneWithDeclSpec;
3908
3909 // C++20 [temp.spec] 13.9/6.
3910 // This disables the access checking rules for function template explicit
3911 // instantiation and explicit specialization:
3912 // - `return type`.
3913 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3914
3915 ParsedType TypeRep = Actions.getTypeName(
3916 *Next.getIdentifierInfo(), Next.getLocation(), getCurScope(), &SS,
3917 false, false, nullptr,
3918 /*IsCtorOrDtorName=*/false,
3919 /*WantNontrivialTypeSourceInfo=*/true,
3920 isClassTemplateDeductionContext(DSContext), AllowImplicitTypename);
3921
3922 if (IsTemplateSpecOrInst)
3923 SAC.done();
3924
3925 // If the referenced identifier is not a type, then this declspec is
3926 // erroneous: We already checked about that it has no type specifier, and
3927 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3928 // typename.
3929 if (!TypeRep) {
3930 if (TryAnnotateTypeConstraint())
3931 goto DoneWithDeclSpec;
3932 if (Tok.isNot(tok::annot_cxxscope) ||
3933 NextToken().isNot(tok::identifier))
3934 continue;
3935 // Eat the scope spec so the identifier is current.
3936 ConsumeAnnotationToken();
3937 ParsedAttributes Attrs(AttrFactory);
3938 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3939 if (!Attrs.empty()) {
3940 AttrsLastTime = true;
3941 attrs.takeAllFrom(Attrs);
3942 }
3943 continue;
3944 }
3945 goto DoneWithDeclSpec;
3946 }
3947
3948 DS.getTypeSpecScope() = SS;
3949 ConsumeAnnotationToken(); // The C++ scope.
3950
3952 DiagID, TypeRep, Policy);
3953 if (isInvalid)
3954 break;
3955
3956 DS.SetRangeEnd(Tok.getLocation());
3957 ConsumeToken(); // The typename.
3958
3959 continue;
3960 }
3961
3962 case tok::annot_typename: {
3963 // If we've previously seen a tag definition, we were almost surely
3964 // missing a semicolon after it.
3965 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3966 goto DoneWithDeclSpec;
3967
3970 DiagID, T, Policy);
3971 if (isInvalid)
3972 break;
3973
3975 ConsumeAnnotationToken(); // The typename
3976
3977 continue;
3978 }
3979
3980 case tok::kw___is_signed:
3981 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3982 // typically treats it as a trait. If we see __is_signed as it appears
3983 // in libstdc++, e.g.,
3984 //
3985 // static const bool __is_signed;
3986 //
3987 // then treat __is_signed as an identifier rather than as a keyword.
3988 if (DS.getTypeSpecType() == TST_bool &&
3991 TryKeywordIdentFallback(true);
3992
3993 // We're done with the declaration-specifiers.
3994 goto DoneWithDeclSpec;
3995
3996 // typedef-name
3997 case tok::kw___super:
3998 case tok::kw_decltype:
3999 case tok::identifier:
4000 ParseIdentifier: {
4001 // This identifier can only be a typedef name if we haven't already seen
4002 // a type-specifier. Without this check we misparse:
4003 // typedef int X; struct Y { short X; }; as 'short int'.
4004 if (DS.hasTypeSpecifier())
4005 goto DoneWithDeclSpec;
4006
4007 // If the token is an identifier named "__declspec" and Microsoft
4008 // extensions are not enabled, it is likely that there will be cascading
4009 // parse errors if this really is a __declspec attribute. Attempt to
4010 // recognize that scenario and recover gracefully.
4011 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
4012 Tok.getIdentifierInfo()->getName() == "__declspec") {
4013 Diag(Loc, diag::err_ms_attributes_not_enabled);
4014
4015 // The next token should be an open paren. If it is, eat the entire
4016 // attribute declaration and continue.
4017 if (NextToken().is(tok::l_paren)) {
4018 // Consume the __declspec identifier.
4019 ConsumeToken();
4020
4021 // Eat the parens and everything between them.
4022 BalancedDelimiterTracker T(*this, tok::l_paren);
4023 if (T.consumeOpen()) {
4024 assert(false && "Not a left paren?");
4025 return;
4026 }
4027 T.skipToEnd();
4028 continue;
4029 }
4030 }
4031
4032 // In C++, check to see if this is a scope specifier like foo::bar::, if
4033 // so handle it as such. This is important for ctor parsing.
4034 if (getLangOpts().CPlusPlus) {
4035 // C++20 [temp.spec] 13.9/6.
4036 // This disables the access checking rules for function template
4037 // explicit instantiation and explicit specialization:
4038 // - `return type`.
4039 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
4040
4041 const bool Success = TryAnnotateCXXScopeToken(EnteringContext);
4042
4043 if (IsTemplateSpecOrInst)
4044 SAC.done();
4045
4046 if (Success) {
4047 if (IsTemplateSpecOrInst)
4048 SAC.redelay();
4049 DS.SetTypeSpecError();
4050 goto DoneWithDeclSpec;
4051 }
4052
4053 if (!Tok.is(tok::identifier))
4054 continue;
4055 }
4056
4057 // Check for need to substitute AltiVec keyword tokens.
4058 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
4059 break;
4060
4061 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
4062 // allow the use of a typedef name as a type specifier.
4063 if (DS.isTypeAltiVecVector())
4064 goto DoneWithDeclSpec;
4065
4066 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
4067 isObjCInstancetype()) {
4068 ParsedType TypeRep = Actions.ObjC().ActOnObjCInstanceType(Loc);
4069 assert(TypeRep);
4071 DiagID, TypeRep, Policy);
4072 if (isInvalid)
4073 break;
4074
4075 DS.SetRangeEnd(Loc);
4076 ConsumeToken();
4077 continue;
4078 }
4079
4080 // If we're in a context where the identifier could be a class name,
4081 // check whether this is a constructor declaration.
4082 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
4084 isConstructorDeclarator(/*Unqualified=*/true,
4085 /*DeductionGuide=*/false,
4086 DS.isFriendSpecified()))
4087 goto DoneWithDeclSpec;
4088
4089 ParsedType TypeRep = Actions.getTypeName(
4090 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
4091 false, false, nullptr, false, false,
4092 isClassTemplateDeductionContext(DSContext));
4093
4094 // If this is not a typedef name, don't parse it as part of the declspec,
4095 // it must be an implicit int or an error.
4096 if (!TypeRep) {
4097 if (TryAnnotateTypeConstraint())
4098 goto DoneWithDeclSpec;
4099 if (Tok.isNot(tok::identifier))
4100 continue;
4101 ParsedAttributes Attrs(AttrFactory);
4102 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
4103 if (!Attrs.empty()) {
4104 AttrsLastTime = true;
4105 attrs.takeAllFrom(Attrs);
4106 }
4107 continue;
4108 }
4109 goto DoneWithDeclSpec;
4110 }
4111
4112 // Likewise, if this is a context where the identifier could be a template
4113 // name, check whether this is a deduction guide declaration.
4114 CXXScopeSpec SS;
4115 if (getLangOpts().CPlusPlus17 &&
4116 (DSContext == DeclSpecContext::DSC_class ||
4117 DSContext == DeclSpecContext::DSC_top_level) &&
4119 Tok.getLocation(), SS) &&
4120 isConstructorDeclarator(/*Unqualified*/ true,
4121 /*DeductionGuide*/ true))
4122 goto DoneWithDeclSpec;
4123
4125 DiagID, TypeRep, Policy);
4126 if (isInvalid)
4127 break;
4128
4129 DS.SetRangeEnd(Tok.getLocation());
4130 ConsumeToken(); // The identifier
4131
4132 // Objective-C supports type arguments and protocol references
4133 // following an Objective-C object or object pointer
4134 // type. Handle either one of them.
4135 if (Tok.is(tok::less) && getLangOpts().ObjC) {
4136 SourceLocation NewEndLoc;
4137 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
4138 Loc, TypeRep, /*consumeLastToken=*/true,
4139 NewEndLoc);
4140 if (NewTypeRep.isUsable()) {
4141 DS.UpdateTypeRep(NewTypeRep.get());
4142 DS.SetRangeEnd(NewEndLoc);
4143 }
4144 }
4145
4146 // Need to support trailing type qualifiers (e.g. "id<p> const").
4147 // If a type specifier follows, it will be diagnosed elsewhere.
4148 continue;
4149 }
4150
4151 // type-name or placeholder-specifier
4152 case tok::annot_template_id: {
4153 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
4154
4155 if (TemplateId->hasInvalidName()) {
4156 DS.SetTypeSpecError();
4157 break;
4158 }
4159
4160 if (TemplateId->Kind == TNK_Concept_template) {
4161 // If we've already diagnosed that this type-constraint has invalid
4162 // arguments, drop it and just form 'auto' or 'decltype(auto)'.
4163 if (TemplateId->hasInvalidArgs())
4164 TemplateId = nullptr;
4165
4166 // Any of the following tokens are likely the start of the user
4167 // forgetting 'auto' or 'decltype(auto)', so diagnose.
4168 // Note: if updating this list, please make sure we update
4169 // isCXXDeclarationSpecifier's check for IsPlaceholderSpecifier to have
4170 // a matching list.
4171 if (NextToken().isOneOf(tok::identifier, tok::kw_const,
4172 tok::kw_volatile, tok::kw_restrict, tok::amp,
4173 tok::ampamp)) {
4174 Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
4175 << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
4176 // Attempt to continue as if 'auto' was placed here.
4177 isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
4178 TemplateId, Policy);
4179 break;
4180 }
4181 if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
4182 goto DoneWithDeclSpec;
4183
4184 if (TemplateId && !isInvalid && Actions.CheckTypeConstraint(TemplateId))
4185 TemplateId = nullptr;
4186
4187 ConsumeAnnotationToken();
4188 SourceLocation AutoLoc = Tok.getLocation();
4189 if (TryConsumeToken(tok::kw_decltype)) {
4190 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
4191 if (Tracker.consumeOpen()) {
4192 // Something like `void foo(Iterator decltype i)`
4193 Diag(Tok, diag::err_expected) << tok::l_paren;
4194 } else {
4195 if (!TryConsumeToken(tok::kw_auto)) {
4196 // Something like `void foo(Iterator decltype(int) i)`
4197 Tracker.skipToEnd();
4198 Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
4200 Tok.getLocation()),
4201 "auto");
4202 } else {
4203 Tracker.consumeClose();
4204 }
4205 }
4206 ConsumedEnd = Tok.getLocation();
4207 DS.setTypeArgumentRange(Tracker.getRange());
4208 // Even if something went wrong above, continue as if we've seen
4209 // `decltype(auto)`.
4211 DiagID, TemplateId, Policy);
4212 } else {
4213 isInvalid = DS.SetTypeSpecType(TST_auto, AutoLoc, PrevSpec, DiagID,
4214 TemplateId, Policy);
4215 }
4216 break;
4217 }
4218
4219 if (TemplateId->Kind != TNK_Type_template &&
4220 TemplateId->Kind != TNK_Undeclared_template) {
4221 // This template-id does not refer to a type name, so we're
4222 // done with the type-specifiers.
4223 goto DoneWithDeclSpec;
4224 }
4225
4226 // If we're in a context where the template-id could be a
4227 // constructor name or specialization, check whether this is a
4228 // constructor declaration.
4229 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
4230 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
4231 isConstructorDeclarator(/*Unqualified=*/true,
4232 /*DeductionGuide=*/false,
4233 DS.isFriendSpecified()))
4234 goto DoneWithDeclSpec;
4235
4236 // Turn the template-id annotation token into a type annotation
4237 // token, then try again to parse it as a type-specifier.
4238 CXXScopeSpec SS;
4239 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
4240 continue;
4241 }
4242
4243 // Attributes support.
4244 case tok::kw___attribute:
4245 case tok::kw___declspec:
4246 ParseAttributes(PAKM_GNU | PAKM_Declspec, DS.getAttributes(), LateAttrs);
4247 continue;
4248
4249 // Microsoft single token adornments.
4250 case tok::kw___forceinline: {
4251 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
4252 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
4253 SourceLocation AttrNameLoc = Tok.getLocation();
4254 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
4255 nullptr, 0, tok::kw___forceinline);
4256 break;
4257 }
4258
4259 case tok::kw___unaligned:
4260 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
4261 getLangOpts());
4262 break;
4263
4264 case tok::kw___sptr:
4265 case tok::kw___uptr:
4266 case tok::kw___ptr64:
4267 case tok::kw___ptr32:
4268 case tok::kw___w64:
4269 case tok::kw___cdecl:
4270 case tok::kw___stdcall:
4271 case tok::kw___fastcall:
4272 case tok::kw___thiscall:
4273 case tok::kw___regcall:
4274 case tok::kw___vectorcall:
4275 ParseMicrosoftTypeAttributes(DS.getAttributes());
4276 continue;
4277
4278 case tok::kw___funcref:
4279 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
4280 continue;
4281
4282 // Borland single token adornments.
4283 case tok::kw___pascal:
4284 ParseBorlandTypeAttributes(DS.getAttributes());
4285 continue;
4286
4287 // OpenCL single token adornments.
4288 case tok::kw___kernel:
4289 ParseOpenCLKernelAttributes(DS.getAttributes());
4290 continue;
4291
4292 // CUDA/HIP single token adornments.
4293 case tok::kw___noinline__:
4294 ParseCUDAFunctionAttributes(DS.getAttributes());
4295 continue;
4296
4297 // Nullability type specifiers.
4298 case tok::kw__Nonnull:
4299 case tok::kw__Nullable:
4300 case tok::kw__Nullable_result:
4301 case tok::kw__Null_unspecified:
4302 ParseNullabilityTypeSpecifiers(DS.getAttributes());
4303 continue;
4304
4305 // Objective-C 'kindof' types.
4306 case tok::kw___kindof:
4307 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
4308 nullptr, 0, tok::kw___kindof);
4309 (void)ConsumeToken();
4310 continue;
4311
4312 // storage-class-specifier
4313 case tok::kw_typedef:
4315 PrevSpec, DiagID, Policy);
4316 isStorageClass = true;
4317 break;
4318 case tok::kw_extern:
4320 Diag(Tok, diag::ext_thread_before) << "extern";
4322 PrevSpec, DiagID, Policy);
4323 isStorageClass = true;
4324 break;
4325 case tok::kw___private_extern__:
4327 Loc, PrevSpec, DiagID, Policy);
4328 isStorageClass = true;
4329 break;
4330 case tok::kw_static:
4332 Diag(Tok, diag::ext_thread_before) << "static";
4334 PrevSpec, DiagID, Policy);
4335 isStorageClass = true;
4336 break;
4337 case tok::kw_auto:
4338 if (getLangOpts().CPlusPlus11 || getLangOpts().C23) {
4339 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
4341 PrevSpec, DiagID, Policy);
4342 if (!isInvalid && !getLangOpts().C23)
4343 Diag(Tok, diag::ext_auto_storage_class)
4345 } else
4347 DiagID, Policy);
4348 } else
4350 PrevSpec, DiagID, Policy);
4351 isStorageClass = true;
4352 break;
4353 case tok::kw___auto_type:
4354 Diag(Tok, diag::ext_auto_type);
4356 DiagID, Policy);
4357 break;
4358 case tok::kw_register:
4360 PrevSpec, DiagID, Policy);
4361 isStorageClass = true;
4362 break;
4363 case tok::kw_mutable:
4365 PrevSpec, DiagID, Policy);
4366 isStorageClass = true;
4367 break;
4368 case tok::kw___thread:
4370 PrevSpec, DiagID);
4371 isStorageClass = true;
4372 break;
4373 case tok::kw_thread_local:
4374 if (getLangOpts().C23)
4375 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4376 // We map thread_local to _Thread_local in C23 mode so it retains the C
4377 // semantics rather than getting the C++ semantics.
4378 // FIXME: diagnostics will show _Thread_local when the user wrote
4379 // thread_local in source in C23 mode; we need some general way to
4380 // identify which way the user spelled the keyword in source.
4384 Loc, PrevSpec, DiagID);
4385 isStorageClass = true;
4386 break;
4387 case tok::kw__Thread_local:
4388 diagnoseUseOfC11Keyword(Tok);
4390 Loc, PrevSpec, DiagID);
4391 isStorageClass = true;
4392 break;
4393
4394 // function-specifier
4395 case tok::kw_inline:
4396 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
4397 break;
4398 case tok::kw_virtual:
4399 // C++ for OpenCL does not allow virtual function qualifier, to avoid
4400 // function pointers restricted in OpenCL v2.0 s6.9.a.
4401 if (getLangOpts().OpenCLCPlusPlus &&
4402 !getActions().getOpenCLOptions().isAvailableOption(
4403 "__cl_clang_function_pointers", getLangOpts())) {
4404 DiagID = diag::err_openclcxx_virtual_function;
4405 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4406 isInvalid = true;
4407 } else {
4408 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
4409 }
4410 break;
4411 case tok::kw_explicit: {
4412 SourceLocation ExplicitLoc = Loc;
4413 SourceLocation CloseParenLoc;
4415 ConsumedEnd = ExplicitLoc;
4416 ConsumeToken(); // kw_explicit
4417 if (Tok.is(tok::l_paren)) {
4418 if (getLangOpts().CPlusPlus20 || isExplicitBool() == TPResult::True) {
4420 ? diag::warn_cxx17_compat_explicit_bool
4421 : diag::ext_explicit_bool);
4422
4423 ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
4424 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
4425 Tracker.consumeOpen();
4426
4427 EnterExpressionEvaluationContext ConstantEvaluated(
4429
4431 ConsumedEnd = Tok.getLocation();
4432 if (ExplicitExpr.isUsable()) {
4433 CloseParenLoc = Tok.getLocation();
4434 Tracker.consumeClose();
4435 ExplicitSpec =
4436 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
4437 } else
4438 Tracker.skipToEnd();
4439 } else {
4440 Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
4441 }
4442 }
4443 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
4444 ExplicitSpec, CloseParenLoc);
4445 break;
4446 }
4447 case tok::kw__Noreturn:
4448 diagnoseUseOfC11Keyword(Tok);
4449 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
4450 break;
4451
4452 // friend
4453 case tok::kw_friend:
4454 if (DSContext == DeclSpecContext::DSC_class) {
4455 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
4456 Scope *CurS = getCurScope();
4457 if (!isInvalid && CurS)
4458 CurS->setFlags(CurS->getFlags() | Scope::FriendScope);
4459 } else {
4460 PrevSpec = ""; // not actually used by the diagnostic
4461 DiagID = diag::err_friend_invalid_in_context;
4462 isInvalid = true;
4463 }
4464 break;
4465
4466 // Modules
4467 case tok::kw___module_private__:
4468 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
4469 break;
4470
4471 // constexpr, consteval, constinit specifiers
4472 case tok::kw_constexpr:
4473 if (getLangOpts().C23)
4474 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4476 PrevSpec, DiagID);
4477 break;
4478 case tok::kw_consteval:
4480 PrevSpec, DiagID);
4481 break;
4482 case tok::kw_constinit:
4484 PrevSpec, DiagID);
4485 break;
4486
4487 // type-specifier
4488 case tok::kw_short:
4490 DiagID, Policy);
4491 break;
4492 case tok::kw_long:
4495 DiagID, Policy);
4496 else
4498 PrevSpec, DiagID, Policy);
4499 break;
4500 case tok::kw___int64:
4502 PrevSpec, DiagID, Policy);
4503 break;
4504 case tok::kw_signed:
4505 isInvalid =
4506 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
4507 break;
4508 case tok::kw_unsigned:
4510 DiagID);
4511 break;
4512 case tok::kw__Complex:
4513 if (!getLangOpts().C99)
4514 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4516 DiagID);
4517 break;
4518 case tok::kw__Imaginary:
4519 if (!getLangOpts().C99)
4520 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4522 DiagID);
4523 break;
4524 case tok::kw_void:
4526 DiagID, Policy);
4527 break;
4528 case tok::kw_char:
4530 DiagID, Policy);
4531 break;
4532 case tok::kw_int:
4534 DiagID, Policy);
4535 break;
4536 case tok::kw__ExtInt:
4537 case tok::kw__BitInt: {
4538 DiagnoseBitIntUse(Tok);
4539 ExprResult ER = ParseExtIntegerArgument();
4540 if (ER.isInvalid())
4541 continue;
4542 isInvalid = DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
4543 ConsumedEnd = PrevTokLocation;
4544 break;
4545 }
4546 case tok::kw___int128:
4548 DiagID, Policy);
4549 break;
4550 case tok::kw_half:
4552 DiagID, Policy);
4553 break;
4554 case tok::kw___bf16:
4556 DiagID, Policy);
4557 break;
4558 case tok::kw_float:
4560 DiagID, Policy);
4561 break;
4562 case tok::kw_double:
4564 DiagID, Policy);
4565 break;
4566 case tok::kw__Float16:
4568 DiagID, Policy);
4569 break;
4570 case tok::kw__Accum:
4571 assert(getLangOpts().FixedPoint &&
4572 "This keyword is only used when fixed point types are enabled "
4573 "with `-ffixed-point`");
4574 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec, DiagID,
4575 Policy);
4576 break;
4577 case tok::kw__Fract:
4578 assert(getLangOpts().FixedPoint &&
4579 "This keyword is only used when fixed point types are enabled "
4580 "with `-ffixed-point`");
4581 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec, DiagID,
4582 Policy);
4583 break;
4584 case tok::kw__Sat:
4585 assert(getLangOpts().FixedPoint &&
4586 "This keyword is only used when fixed point types are enabled "
4587 "with `-ffixed-point`");
4588 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
4589 break;
4590 case tok::kw___float128:
4592 DiagID, Policy);
4593 break;
4594 case tok::kw___ibm128:
4596 DiagID, Policy);
4597 break;
4598 case tok::kw_wchar_t:
4600 DiagID, Policy);
4601 break;
4602 case tok::kw_char8_t:
4604 DiagID, Policy);
4605 break;
4606 case tok::kw_char16_t:
4608 DiagID, Policy);
4609 break;
4610 case tok::kw_char32_t:
4612 DiagID, Policy);
4613 break;
4614 case tok::kw_bool:
4615 if (getLangOpts().C23)
4616 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4617 [[fallthrough]];
4618 case tok::kw__Bool:
4619 if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
4620 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4621
4622 if (Tok.is(tok::kw_bool) &&
4625 PrevSpec = ""; // Not used by the diagnostic.
4626 DiagID = diag::err_bool_redeclaration;
4627 // For better error recovery.
4628 Tok.setKind(tok::identifier);
4629 isInvalid = true;
4630 } else {
4632 DiagID, Policy);
4633 }
4634 break;
4635 case tok::kw__Decimal32:
4637 DiagID, Policy);
4638 break;
4639 case tok::kw__Decimal64:
4641 DiagID, Policy);
4642 break;
4643 case tok::kw__Decimal128:
4645 DiagID, Policy);
4646 break;
4647 case tok::kw___vector:
4648 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
4649 break;
4650 case tok::kw___pixel:
4651 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
4652 break;
4653 case tok::kw___bool:
4654 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
4655 break;
4656 case tok::kw_pipe:
4657 if (!getLangOpts().OpenCL ||
4658 getLangOpts().getOpenCLCompatibleVersion() < 200) {
4659 // OpenCL 2.0 and later define this keyword. OpenCL 1.2 and earlier
4660 // should support the "pipe" word as identifier.
4662 Tok.setKind(tok::identifier);
4663 goto DoneWithDeclSpec;
4664 } else if (!getLangOpts().OpenCLPipes) {
4665 DiagID = diag::err_opencl_unknown_type_specifier;
4666 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4667 isInvalid = true;
4668 } else
4669 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
4670 break;
4671// We only need to enumerate each image type once.
4672#define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
4673#define IMAGE_WRITE_TYPE(Type, Id, Ext)
4674#define IMAGE_READ_TYPE(ImgType, Id, Ext) \
4675 case tok::kw_##ImgType##_t: \
4676 if (!handleOpenCLImageKW(Ext, DeclSpec::TST_##ImgType##_t)) \
4677 goto DoneWithDeclSpec; \
4678 break;
4679#include "clang/Basic/OpenCLImageTypes.def"
4680 case tok::kw___unknown_anytype:
4682 PrevSpec, DiagID, Policy);
4683 break;
4684
4685 // class-specifier:
4686 case tok::kw_class:
4687 case tok::kw_struct:
4688 case tok::kw___interface:
4689 case tok::kw_union: {
4690 tok::TokenKind Kind = Tok.getKind();
4691 ConsumeToken();
4692
4693 // These are attributes following class specifiers.
4694 // To produce better diagnostic, we parse them when
4695 // parsing class specifier.
4696 ParsedAttributes Attributes(AttrFactory);
4697 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
4698 EnteringContext, DSContext, Attributes);
4699
4700 // If there are attributes following class specifier,
4701 // take them over and handle them here.
4702 if (!Attributes.empty()) {
4703 AttrsLastTime = true;
4704 attrs.takeAllFrom(Attributes);
4705 }
4706 continue;
4707 }
4708
4709 // enum-specifier:
4710 case tok::kw_enum:
4711 ConsumeToken();
4712 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
4713 continue;
4714
4715 // cv-qualifier:
4716 case tok::kw_const:
4717 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
4718 getLangOpts());
4719 break;
4720 case tok::kw_volatile:
4721 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4722 getLangOpts());
4723 break;
4724 case tok::kw_restrict:
4725 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4726 getLangOpts());
4727 break;
4728
4729 // C++ typename-specifier:
4730 case tok::kw_typename:
4732 DS.SetTypeSpecError();
4733 goto DoneWithDeclSpec;
4734 }
4735 if (!Tok.is(tok::kw_typename))
4736 continue;
4737 break;
4738
4739 // C23/GNU typeof support.
4740 case tok::kw_typeof:
4741 case tok::kw_typeof_unqual:
4742 ParseTypeofSpecifier(DS);
4743 continue;
4744
4745 case tok::annot_decltype:
4746 ParseDecltypeSpecifier(DS);
4747 continue;
4748
4749 case tok::annot_pack_indexing_type:
4750 ParsePackIndexingType(DS);
4751 continue;
4752
4753 case tok::annot_pragma_pack:
4754 HandlePragmaPack();
4755 continue;
4756
4757 case tok::annot_pragma_ms_pragma:
4758 HandlePragmaMSPragma();
4759 continue;
4760
4761 case tok::annot_pragma_ms_vtordisp:
4762 HandlePragmaMSVtorDisp();
4763 continue;
4764
4765 case tok::annot_pragma_ms_pointers_to_members:
4766 HandlePragmaMSPointersToMembers();
4767 continue;
4768
4769#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
4770#include "clang/Basic/TransformTypeTraits.def"
4771 // HACK: libstdc++ already uses '__remove_cv' as an alias template so we
4772 // work around this by expecting all transform type traits to be suffixed
4773 // with '('. They're an identifier otherwise.
4774 if (!MaybeParseTypeTransformTypeSpecifier(DS))
4775 goto ParseIdentifier;
4776 continue;
4777
4778 case tok::kw__Atomic:
4779 // C11 6.7.2.4/4:
4780 // If the _Atomic keyword is immediately followed by a left parenthesis,
4781 // it is interpreted as a type specifier (with a type name), not as a
4782 // type qualifier.
4783 diagnoseUseOfC11Keyword(Tok);
4784 if (NextToken().is(tok::l_paren)) {
4785 ParseAtomicSpecifier(DS);
4786 continue;
4787 }
4788 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4789 getLangOpts());
4790 break;
4791
4792 // OpenCL address space qualifiers:
4793 case tok::kw___generic:
4794 // generic address space is introduced only in OpenCL v2.0
4795 // see OpenCL C Spec v2.0 s6.5.5
4796 // OpenCL v3.0 introduces __opencl_c_generic_address_space
4797 // feature macro to indicate if generic address space is supported
4798 if (!Actions.getLangOpts().OpenCLGenericAddressSpace) {
4799 DiagID = diag::err_opencl_unknown_type_specifier;
4800 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4801 isInvalid = true;
4802 break;
4803 }
4804 [[fallthrough]];
4805 case tok::kw_private:
4806 // It's fine (but redundant) to check this for __generic on the
4807 // fallthrough path; we only form the __generic token in OpenCL mode.
4808 if (!getLangOpts().OpenCL)
4809 goto DoneWithDeclSpec;
4810 [[fallthrough]];
4811 case tok::kw___private:
4812 case tok::kw___global:
4813 case tok::kw___local:
4814 case tok::kw___constant:
4815 // OpenCL access qualifiers:
4816 case tok::kw___read_only:
4817 case tok::kw___write_only:
4818 case tok::kw___read_write:
4819 ParseOpenCLQualifiers(DS.getAttributes());
4820 break;
4821
4822 case tok::kw_groupshared:
4823 case tok::kw_in:
4824 case tok::kw_inout:
4825 case tok::kw_out:
4826 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
4827 ParseHLSLQualifiers(DS.getAttributes());
4828 continue;
4829
4830#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
4831 case tok::kw_##Name: \
4832 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##Name, Loc, PrevSpec, \
4833 DiagID, Policy); \
4834 break;
4835#include "clang/Basic/HLSLIntangibleTypes.def"
4836
4837 case tok::less:
4838 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4839 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
4840 // but we support it.
4841 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
4842 goto DoneWithDeclSpec;
4843
4844 SourceLocation StartLoc = Tok.getLocation();
4845 SourceLocation EndLoc;
4846 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4847 if (Type.isUsable()) {
4848 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4849 PrevSpec, DiagID, Type.get(),
4850 Actions.getASTContext().getPrintingPolicy()))
4851 Diag(StartLoc, DiagID) << PrevSpec;
4852
4853 DS.SetRangeEnd(EndLoc);
4854 } else {
4855 DS.SetTypeSpecError();
4856 }
4857
4858 // Need to support trailing type qualifiers (e.g. "id<p> const").
4859 // If a type specifier follows, it will be diagnosed elsewhere.
4860 continue;
4861 }
4862
4863 DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4864
4865 // If the specifier wasn't legal, issue a diagnostic.
4866 if (isInvalid) {
4867 assert(PrevSpec && "Method did not return previous specifier!");
4868 assert(DiagID);
4869
4870 if (DiagID == diag::ext_duplicate_declspec ||
4871 DiagID == diag::ext_warn_duplicate_declspec ||
4872 DiagID == diag::err_duplicate_declspec)
4873 Diag(Loc, DiagID) << PrevSpec
4875 SourceRange(Loc, DS.getEndLoc()));
4876 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4877 Diag(Loc, DiagID) << getLangOpts().getOpenCLVersionString() << PrevSpec
4878 << isStorageClass;
4879 } else
4880 Diag(Loc, DiagID) << PrevSpec;
4881 }
4882
4883 if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4884 // After an error the next token can be an annotation token.
4886
4887 AttrsLastTime = false;
4888 }
4889}
4890
4892 Parser &P) {
4893
4895 return;
4896
4897 auto *RD = dyn_cast<RecordDecl>(DS.getRepAsDecl());
4898 // We're only interested in unnamed, non-anonymous struct
4899 if (!RD || !RD->getName().empty() || RD->isAnonymousStructOrUnion())
4900 return;
4901
4902 for (auto *I : RD->decls()) {
4903 auto *VD = dyn_cast<ValueDecl>(I);
4904 if (!VD)
4905 continue;
4906
4907 auto *CAT = VD->getType()->getAs<CountAttributedType>();
4908 if (!CAT)
4909 continue;
4910
4911 for (const auto &DD : CAT->dependent_decls()) {
4912 if (!RD->containsDecl(DD.getDecl())) {
4913 P.Diag(VD->getBeginLoc(), diag::err_count_attr_param_not_in_same_struct)
4914 << DD.getDecl() << CAT->getKind() << CAT->isArrayType();
4915 P.Diag(DD.getDecl()->getBeginLoc(),
4916 diag::note_flexible_array_counted_by_attr_field)
4917 << DD.getDecl();
4918 }
4919 }
4920 }
4921}
4922
4923/// ParseStructDeclaration - Parse a struct declaration without the terminating
4924/// semicolon.
4925///
4926/// Note that a struct declaration refers to a declaration in a struct,
4927/// not to the declaration of a struct.
4928///
4929/// struct-declaration:
4930/// [C23] attributes-specifier-seq[opt]
4931/// specifier-qualifier-list struct-declarator-list
4932/// [GNU] __extension__ struct-declaration
4933/// [GNU] specifier-qualifier-list
4934/// struct-declarator-list:
4935/// struct-declarator
4936/// struct-declarator-list ',' struct-declarator
4937/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
4938/// struct-declarator:
4939/// declarator
4940/// [GNU] declarator attributes[opt]
4941/// declarator[opt] ':' constant-expression
4942/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
4943///
4944void Parser::ParseStructDeclaration(
4945 ParsingDeclSpec &DS,
4946 llvm::function_ref<Decl *(ParsingFieldDeclarator &)> FieldsCallback,
4947 LateParsedAttrList *LateFieldAttrs) {
4948
4949 if (Tok.is(tok::kw___extension__)) {
4950 // __extension__ silences extension warnings in the subexpression.
4951 ExtensionRAIIObject O(Diags); // Use RAII to do this.
4952 ConsumeToken();
4953 return ParseStructDeclaration(DS, FieldsCallback, LateFieldAttrs);
4954 }
4955
4956 // Parse leading attributes.
4957 ParsedAttributes Attrs(AttrFactory);
4958 MaybeParseCXX11Attributes(Attrs);
4959
4960 // Parse the common specifier-qualifiers-list piece.
4961 ParseSpecifierQualifierList(DS);
4962
4963 // If there are no declarators, this is a free-standing declaration
4964 // specifier. Let the actions module cope with it.
4965 if (Tok.is(tok::semi)) {
4966 // C23 6.7.2.1p9 : "The optional attribute specifier sequence in a
4967 // member declaration appertains to each of the members declared by the
4968 // member declarator list; it shall not appear if the optional member
4969 // declarator list is omitted."
4970 ProhibitAttributes(Attrs);
4971 RecordDecl *AnonRecord = nullptr;
4972 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
4973 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
4974 assert(!AnonRecord && "Did not expect anonymous struct or union here");
4975 DS.complete(TheDecl);
4976 return;
4977 }
4978
4979 // Read struct-declarators until we find the semicolon.
4980 bool FirstDeclarator = true;
4981 SourceLocation CommaLoc;
4982 while (true) {
4983 ParsingFieldDeclarator DeclaratorInfo(*this, DS, Attrs);
4984 DeclaratorInfo.D.setCommaLoc(CommaLoc);
4985
4986 // Attributes are only allowed here on successive declarators.
4987 if (!FirstDeclarator) {
4988 // However, this does not apply for [[]] attributes (which could show up
4989 // before or after the __attribute__ attributes).
4990 DiagnoseAndSkipCXX11Attributes();
4991 MaybeParseGNUAttributes(DeclaratorInfo.D);
4992 DiagnoseAndSkipCXX11Attributes();
4993 }
4994
4995 /// struct-declarator: declarator
4996 /// struct-declarator: declarator[opt] ':' constant-expression
4997 if (Tok.isNot(tok::colon)) {
4998 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
5000 ParseDeclarator(DeclaratorInfo.D);
5001 } else
5002 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
5003
5004 // Here, we now know that the unnamed struct is not an anonymous struct.
5005 // Report an error if a counted_by attribute refers to a field in a
5006 // different named struct.
5008
5009 if (TryConsumeToken(tok::colon)) {
5011 if (Res.isInvalid())
5012 SkipUntil(tok::semi, StopBeforeMatch);
5013 else
5014 DeclaratorInfo.BitfieldSize = Res.get();
5015 }
5016
5017 // If attributes exist after the declarator, parse them.
5018 MaybeParseGNUAttributes(DeclaratorInfo.D, LateFieldAttrs);
5019
5020 // We're done with this declarator; invoke the callback.
5021 Decl *Field = FieldsCallback(DeclaratorInfo);
5022 if (Field)
5023 DistributeCLateParsedAttrs(Field, LateFieldAttrs);
5024
5025 // If we don't have a comma, it is either the end of the list (a ';')
5026 // or an error, bail out.
5027 if (!TryConsumeToken(tok::comma, CommaLoc))
5028 return;
5029
5030 FirstDeclarator = false;
5031 }
5032}
5033
5034// TODO: All callers of this function should be moved to
5035// `Parser::ParseLexedAttributeList`.
5036void Parser::ParseLexedCAttributeList(LateParsedAttrList &LAs, bool EnterScope,
5037 ParsedAttributes *OutAttrs) {
5038 assert(LAs.parseSoon() &&
5039 "Attribute list should be marked for immediate parsing.");
5040 for (auto *LA : LAs) {
5041 ParseLexedCAttribute(*LA, EnterScope, OutAttrs);
5042 delete LA;
5043 }
5044 LAs.clear();
5045}
5046
5047/// Finish parsing an attribute for which parsing was delayed.
5048/// This will be called at the end of parsing a class declaration
5049/// for each LateParsedAttribute. We consume the saved tokens and
5050/// create an attribute with the arguments filled in. We add this
5051/// to the Attribute list for the decl.
5052void Parser::ParseLexedCAttribute(LateParsedAttribute &LA, bool EnterScope,
5053 ParsedAttributes *OutAttrs) {
5054 // Create a fake EOF so that attribute parsing won't go off the end of the
5055 // attribute.
5056 Token AttrEnd;
5057 AttrEnd.startToken();
5058 AttrEnd.setKind(tok::eof);
5059 AttrEnd.setLocation(Tok.getLocation());
5060 AttrEnd.setEofData(LA.Toks.data());
5061 LA.Toks.push_back(AttrEnd);
5062
5063 // Append the current token at the end of the new token stream so that it
5064 // doesn't get lost.
5065 LA.Toks.push_back(Tok);
5066 PP.EnterTokenStream(LA.Toks, /*DisableMacroExpansion=*/true,
5067 /*IsReinject=*/true);
5068 // Drop the current token and bring the first cached one. It's the same token
5069 // as when we entered this function.
5070 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
5071
5072 // TODO: Use `EnterScope`
5073 (void)EnterScope;
5074
5075 ParsedAttributes Attrs(AttrFactory);
5076
5077 assert(LA.Decls.size() <= 1 &&
5078 "late field attribute expects to have at most one declaration.");
5079
5080 // Dispatch based on the attribute and parse it
5081 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, nullptr, nullptr,
5082 SourceLocation(), ParsedAttr::Form::GNU(), nullptr);
5083
5084 for (auto *D : LA.Decls)
5085 Actions.ActOnFinishDelayedAttribute(getCurScope(), D, Attrs);
5086
5087 // Due to a parsing error, we either went over the cached tokens or
5088 // there are still cached tokens left, so we skip the leftover tokens.
5089 while (Tok.isNot(tok::eof))
5091
5092 // Consume the fake EOF token if it's there
5093 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
5095
5096 if (OutAttrs) {
5097 OutAttrs->takeAllFrom(Attrs);
5098 }
5099}
5100
5101/// ParseStructUnionBody
5102/// struct-contents:
5103/// struct-declaration-list
5104/// [EXT] empty
5105/// [GNU] "struct-declaration-list" without terminating ';'
5106/// struct-declaration-list:
5107/// struct-declaration
5108/// struct-declaration-list struct-declaration
5109/// [OBC] '@' 'defs' '(' class-name ')'
5110///
5111void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
5114 "parsing struct/union body");
5115 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
5116
5117 BalancedDelimiterTracker T(*this, tok::l_brace);
5118 if (T.consumeOpen())
5119 return;
5120
5121 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
5123
5124 // `LateAttrParseExperimentalExtOnly=true` requests that only attributes
5125 // marked with `LateAttrParseExperimentalExt` are late parsed.
5126 LateParsedAttrList LateFieldAttrs(/*PSoon=*/true,
5127 /*LateAttrParseExperimentalExtOnly=*/true);
5128
5129 // While we still have something to read, read the declarations in the struct.
5130 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
5131 Tok.isNot(tok::eof)) {
5132 // Each iteration of this loop reads one struct-declaration.
5133
5134 // Check for extraneous top-level semicolon.
5135 if (Tok.is(tok::semi)) {
5136 ConsumeExtraSemi(InsideStruct, TagType);
5137 continue;
5138 }
5139
5140 // Parse _Static_assert declaration.
5141 if (Tok.isOneOf(tok::kw__Static_assert, tok::kw_static_assert)) {
5142 SourceLocation DeclEnd;
5143 ParseStaticAssertDeclaration(DeclEnd);
5144 continue;
5145 }
5146
5147 if (Tok.is(tok::annot_pragma_pack)) {
5148 HandlePragmaPack();
5149 continue;
5150 }
5151
5152 if (Tok.is(tok::annot_pragma_align)) {
5153 HandlePragmaAlign();
5154 continue;
5155 }
5156
5157 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
5158 // Result can be ignored, because it must be always empty.
5160 ParsedAttributes Attrs(AttrFactory);
5161 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
5162 continue;
5163 }
5164
5165 if (Tok.is(tok::annot_pragma_openacc)) {
5167 continue;
5168 }
5169
5170 if (tok::isPragmaAnnotation(Tok.getKind())) {
5171 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
5174 ConsumeAnnotationToken();
5175 continue;
5176 }
5177
5178 if (!Tok.is(tok::at)) {
5179 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) -> Decl * {
5180 // Install the declarator into the current TagDecl.
5181 Decl *Field =
5182 Actions.ActOnField(getCurScope(), TagDecl,
5183 FD.D.getDeclSpec().getSourceRange().getBegin(),
5184 FD.D, FD.BitfieldSize);
5185 FD.complete(Field);
5186 return Field;
5187 };
5188
5189 // Parse all the comma separated declarators.
5190 ParsingDeclSpec DS(*this);
5191 ParseStructDeclaration(DS, CFieldCallback, &LateFieldAttrs);
5192 } else { // Handle @defs
5193 ConsumeToken();
5194 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
5195 Diag(Tok, diag::err_unexpected_at);
5196 SkipUntil(tok::semi);
5197 continue;
5198 }
5199 ConsumeToken();
5200 ExpectAndConsume(tok::l_paren);
5201 if (!Tok.is(tok::identifier)) {
5202 Diag(Tok, diag::err_expected) << tok::identifier;
5203 SkipUntil(tok::semi);
5204 continue;
5205 }
5207 Actions.ObjC().ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
5208 Tok.getIdentifierInfo(), Fields);
5209 ConsumeToken();
5210 ExpectAndConsume(tok::r_paren);
5211 }
5212
5213 if (TryConsumeToken(tok::semi))
5214 continue;
5215
5216 if (Tok.is(tok::r_brace)) {
5217 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
5218 break;
5219 }
5220
5221 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
5222 // Skip to end of block or statement to avoid ext-warning on extra ';'.
5223 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
5224 // If we stopped at a ';', eat it.
5225 TryConsumeToken(tok::semi);
5226 }
5227
5228 T.consumeClose();
5229
5230 ParsedAttributes attrs(AttrFactory);
5231 // If attributes exist after struct contents, parse them.
5232 MaybeParseGNUAttributes(attrs, &LateFieldAttrs);
5233
5234 // Late parse field attributes if necessary.
5235 ParseLexedCAttributeList(LateFieldAttrs, /*EnterScope=*/false);
5236
5237 SmallVector<Decl *, 32> FieldDecls(TagDecl->fields());
5238
5239 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
5240 T.getOpenLocation(), T.getCloseLocation(), attrs);
5241 StructScope.Exit();
5242 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
5243}
5244
5245/// ParseEnumSpecifier
5246/// enum-specifier: [C99 6.7.2.2]
5247/// 'enum' identifier[opt] '{' enumerator-list '}'
5248///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
5249/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
5250/// '}' attributes[opt]
5251/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
5252/// '}'
5253/// 'enum' identifier
5254/// [GNU] 'enum' attributes[opt] identifier
5255///
5256/// [C++11] enum-head '{' enumerator-list[opt] '}'
5257/// [C++11] enum-head '{' enumerator-list ',' '}'
5258///
5259/// enum-head: [C++11]
5260/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
5261/// enum-key attribute-specifier-seq[opt] nested-name-specifier
5262/// identifier enum-base[opt]
5263///
5264/// enum-key: [C++11]
5265/// 'enum'
5266/// 'enum' 'class'
5267/// 'enum' 'struct'
5268///
5269/// enum-base: [C++11]
5270/// ':' type-specifier-seq
5271///
5272/// [C++] elaborated-type-specifier:
5273/// [C++] 'enum' nested-name-specifier[opt] identifier
5274///
5275void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
5276 const ParsedTemplateInfo &TemplateInfo,
5277 AccessSpecifier AS, DeclSpecContext DSC) {
5278 // Parse the tag portion of this.
5279 if (Tok.is(tok::code_completion)) {
5280 // Code completion for an enum name.
5281 cutOffParsing();
5283 DS.SetTypeSpecError(); // Needed by ActOnUsingDeclaration.
5284 return;
5285 }
5286
5287 // If attributes exist after tag, parse them.
5288 ParsedAttributes attrs(AttrFactory);
5289 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
5290
5291 SourceLocation ScopedEnumKWLoc;
5292 bool IsScopedUsingClassTag = false;
5293
5294 // In C++11, recognize 'enum class' and 'enum struct'.
5295 if (Tok.isOneOf(tok::kw_class, tok::kw_struct) && getLangOpts().CPlusPlus) {
5296 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
5297 : diag::ext_scoped_enum);
5298 IsScopedUsingClassTag = Tok.is(tok::kw_class);
5299 ScopedEnumKWLoc = ConsumeToken();
5300
5301 // Attributes are not allowed between these keywords. Diagnose,
5302 // but then just treat them like they appeared in the right place.
5303 ProhibitAttributes(attrs);
5304
5305 // They are allowed afterwards, though.
5306 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
5307 }
5308
5309 // C++11 [temp.explicit]p12:
5310 // The usual access controls do not apply to names used to specify
5311 // explicit instantiations.
5312 // We extend this to also cover explicit specializations. Note that
5313 // we don't suppress if this turns out to be an elaborated type
5314 // specifier.
5315 bool shouldDelayDiagsInTag =
5316 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
5317 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
5318 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
5319
5320 // Determine whether this declaration is permitted to have an enum-base.
5321 AllowDefiningTypeSpec AllowEnumSpecifier =
5322 isDefiningTypeSpecifierContext(DSC, getLangOpts().CPlusPlus);
5323 bool CanBeOpaqueEnumDeclaration =
5324 DS.isEmpty() && isOpaqueEnumDeclarationContext(DSC);
5325 bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || getLangOpts().ObjC ||
5326 getLangOpts().MicrosoftExt) &&
5327 (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
5328 CanBeOpaqueEnumDeclaration);
5329
5330 CXXScopeSpec &SS = DS.getTypeSpecScope();
5331 if (getLangOpts().CPlusPlus) {
5332 // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
5334
5335 CXXScopeSpec Spec;
5336 if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
5337 /*ObjectHasErrors=*/false,
5338 /*EnteringContext=*/true))
5339 return;
5340
5341 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
5342 Diag(Tok, diag::err_expected) << tok::identifier;
5343 DS.SetTypeSpecError();
5344 if (Tok.isNot(tok::l_brace)) {
5345 // Has no name and is not a definition.
5346 // Skip the rest of this declarator, up until the comma or semicolon.
5347 SkipUntil(tok::comma, StopAtSemi);
5348 return;
5349 }
5350 }
5351
5352 SS = Spec;
5353 }
5354
5355 // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
5356 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
5357 Tok.isNot(tok::colon)) {
5358 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
5359
5360 DS.SetTypeSpecError();
5361 // Skip the rest of this declarator, up until the comma or semicolon.
5362 SkipUntil(tok::comma, StopAtSemi);
5363 return;
5364 }
5365
5366 // If an identifier is present, consume and remember it.
5367 IdentifierInfo *Name = nullptr;
5368 SourceLocation NameLoc;
5369 if (Tok.is(tok::identifier)) {
5370 Name = Tok.getIdentifierInfo();
5371 NameLoc = ConsumeToken();
5372 }
5373
5374 if (!Name && ScopedEnumKWLoc.isValid()) {
5375 // C++0x 7.2p2: The optional identifier shall not be omitted in the
5376 // declaration of a scoped enumeration.
5377 Diag(Tok, diag::err_scoped_enum_missing_identifier);
5378 ScopedEnumKWLoc = SourceLocation();
5379 IsScopedUsingClassTag = false;
5380 }
5381
5382 // Okay, end the suppression area. We'll decide whether to emit the
5383 // diagnostics in a second.
5384 if (shouldDelayDiagsInTag)
5385 diagsFromTag.done();
5386
5387 TypeResult BaseType;
5388 SourceRange BaseRange;
5389
5390 bool CanBeBitfield =
5391 getCurScope()->isClassScope() && ScopedEnumKWLoc.isInvalid() && Name;
5392
5393 // Parse the fixed underlying type.
5394 if (Tok.is(tok::colon)) {
5395 // This might be an enum-base or part of some unrelated enclosing context.
5396 //
5397 // 'enum E : base' is permitted in two circumstances:
5398 //
5399 // 1) As a defining-type-specifier, when followed by '{'.
5400 // 2) As the sole constituent of a complete declaration -- when DS is empty
5401 // and the next token is ';'.
5402 //
5403 // The restriction to defining-type-specifiers is important to allow parsing
5404 // a ? new enum E : int{}
5405 // _Generic(a, enum E : int{})
5406 // properly.
5407 //
5408 // One additional consideration applies:
5409 //
5410 // C++ [dcl.enum]p1:
5411 // A ':' following "enum nested-name-specifier[opt] identifier" within
5412 // the decl-specifier-seq of a member-declaration is parsed as part of
5413 // an enum-base.
5414 //
5415 // Other language modes supporting enumerations with fixed underlying types
5416 // do not have clear rules on this, so we disambiguate to determine whether
5417 // the tokens form a bit-field width or an enum-base.
5418
5419 if (CanBeBitfield && !isEnumBase(CanBeOpaqueEnumDeclaration)) {
5420 // Outside C++11, do not interpret the tokens as an enum-base if they do
5421 // not make sense as one. In C++11, it's an error if this happens.
5423 Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
5424 } else if (CanHaveEnumBase || !ColonIsSacred) {
5425 SourceLocation ColonLoc = ConsumeToken();
5426
5427 // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
5428 // because under -fms-extensions,
5429 // enum E : int *p;
5430 // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
5431 DeclSpec DS(AttrFactory);
5432 // enum-base is not assumed to be a type and therefore requires the
5433 // typename keyword [p0634r3].
5434 ParseSpecifierQualifierList(DS, ImplicitTypenameContext::No, AS,
5435 DeclSpecContext::DSC_type_specifier);
5436 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
5438 BaseType = Actions.ActOnTypeName(DeclaratorInfo);
5439
5440 BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
5441
5442 if (!getLangOpts().ObjC) {
5444 Diag(ColonLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type)
5445 << BaseRange;
5446 else if (getLangOpts().CPlusPlus)
5447 Diag(ColonLoc, diag::ext_cxx11_enum_fixed_underlying_type)
5448 << BaseRange;
5449 else if (getLangOpts().MicrosoftExt && !getLangOpts().C23)
5450 Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
5451 << BaseRange;
5452 else
5453 Diag(ColonLoc, getLangOpts().C23
5454 ? diag::warn_c17_compat_enum_fixed_underlying_type
5455 : diag::ext_c23_enum_fixed_underlying_type)
5456 << BaseRange;
5457 }
5458 }
5459 }
5460
5461 // There are four options here. If we have 'friend enum foo;' then this is a
5462 // friend declaration, and cannot have an accompanying definition. If we have
5463 // 'enum foo;', then this is a forward declaration. If we have
5464 // 'enum foo {...' then this is a definition. Otherwise we have something
5465 // like 'enum foo xyz', a reference.
5466 //
5467 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
5468 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
5469 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
5470 //
5471 TagUseKind TUK;
5472 if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
5474 else if (Tok.is(tok::l_brace)) {
5475 if (DS.isFriendSpecified()) {
5476 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
5478 ConsumeBrace();
5479 SkipUntil(tok::r_brace, StopAtSemi);
5480 // Discard any other definition-only pieces.
5481 attrs.clear();
5482 ScopedEnumKWLoc = SourceLocation();
5483 IsScopedUsingClassTag = false;
5484 BaseType = TypeResult();
5485 TUK = TagUseKind::Friend;
5486 } else {
5488 }
5489 } else if (!isTypeSpecifier(DSC) &&
5490 (Tok.is(tok::semi) ||
5491 (Tok.isAtStartOfLine() &&
5492 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
5493 // An opaque-enum-declaration is required to be standalone (no preceding or
5494 // following tokens in the declaration). Sema enforces this separately by
5495 // diagnosing anything else in the DeclSpec.
5497 if (Tok.isNot(tok::semi)) {
5498 // A semicolon was missing after this declaration. Diagnose and recover.
5499 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
5500 PP.EnterToken(Tok, /*IsReinject=*/true);
5501 Tok.setKind(tok::semi);
5502 }
5503 } else {
5505 }
5506
5507 bool IsElaboratedTypeSpecifier =
5509
5510 // If this is an elaborated type specifier nested in a larger declaration,
5511 // and we delayed diagnostics before, just merge them into the current pool.
5512 if (TUK == TagUseKind::Reference && shouldDelayDiagsInTag) {
5513 diagsFromTag.redelay();
5514 }
5515
5516 MultiTemplateParamsArg TParams;
5517 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
5518 TUK != TagUseKind::Reference) {
5519 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
5520 // Skip the rest of this declarator, up until the comma or semicolon.
5521 Diag(Tok, diag::err_enum_template);
5522 SkipUntil(tok::comma, StopAtSemi);
5523 return;
5524 }
5525
5526 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
5527 // Enumerations can't be explicitly instantiated.
5528 DS.SetTypeSpecError();
5529 Diag(StartLoc, diag::err_explicit_instantiation_enum);
5530 return;
5531 }
5532
5533 assert(TemplateInfo.TemplateParams && "no template parameters");
5534 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
5535 TemplateInfo.TemplateParams->size());
5536 SS.setTemplateParamLists(TParams);
5537 }
5538
5539 if (!Name && TUK != TagUseKind::Definition) {
5540 Diag(Tok, diag::err_enumerator_unnamed_no_def);
5541
5542 DS.SetTypeSpecError();
5543 // Skip the rest of this declarator, up until the comma or semicolon.
5544 SkipUntil(tok::comma, StopAtSemi);
5545 return;
5546 }
5547
5548 // An elaborated-type-specifier has a much more constrained grammar:
5549 //
5550 // 'enum' nested-name-specifier[opt] identifier
5551 //
5552 // If we parsed any other bits, reject them now.
5553 //
5554 // MSVC and (for now at least) Objective-C permit a full enum-specifier
5555 // or opaque-enum-declaration anywhere.
5556 if (IsElaboratedTypeSpecifier && !getLangOpts().MicrosoftExt &&
5557 !getLangOpts().ObjC) {
5558 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
5559 diag::err_keyword_not_allowed,
5560 /*DiagnoseEmptyAttrs=*/true);
5561 if (BaseType.isUsable())
5562 Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
5563 << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
5564 else if (ScopedEnumKWLoc.isValid())
5565 Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
5566 << FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
5567 }
5568
5569 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
5570
5571 SkipBodyInfo SkipBody;
5572 if (!Name && TUK == TagUseKind::Definition && Tok.is(tok::l_brace) &&
5573 NextToken().is(tok::identifier))
5574 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
5575 NextToken().getIdentifierInfo(),
5576 NextToken().getLocation());
5577
5578 bool Owned = false;
5579 bool IsDependent = false;
5580 const char *PrevSpec = nullptr;
5581 unsigned DiagID;
5582 Decl *TagDecl =
5583 Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS,
5584 Name, NameLoc, attrs, AS, DS.getModulePrivateSpecLoc(),
5585 TParams, Owned, IsDependent, ScopedEnumKWLoc,
5586 IsScopedUsingClassTag,
5587 BaseType, DSC == DeclSpecContext::DSC_type_specifier,
5588 DSC == DeclSpecContext::DSC_template_param ||
5589 DSC == DeclSpecContext::DSC_template_type_arg,
5590 OffsetOfState, &SkipBody).get();
5591
5592 if (SkipBody.ShouldSkip) {
5593 assert(TUK == TagUseKind::Definition && "can only skip a definition");
5594
5595 BalancedDelimiterTracker T(*this, tok::l_brace);
5596 T.consumeOpen();
5597 T.skipToEnd();
5598
5599 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5600 NameLoc.isValid() ? NameLoc : StartLoc,
5601 PrevSpec, DiagID, TagDecl, Owned,
5602 Actions.getASTContext().getPrintingPolicy()))
5603 Diag(StartLoc, DiagID) << PrevSpec;
5604 return;
5605 }
5606
5607 if (IsDependent) {
5608 // This enum has a dependent nested-name-specifier. Handle it as a
5609 // dependent tag.
5610 if (!Name) {
5611 DS.SetTypeSpecError();
5612 Diag(Tok, diag::err_expected_type_name_after_typename);
5613 return;
5614 }
5615
5617 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
5618 if (Type.isInvalid()) {
5619 DS.SetTypeSpecError();
5620 return;
5621 }
5622
5623 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
5624 NameLoc.isValid() ? NameLoc : StartLoc,
5625 PrevSpec, DiagID, Type.get(),
5626 Actions.getASTContext().getPrintingPolicy()))
5627 Diag(StartLoc, DiagID) << PrevSpec;
5628
5629 return;
5630 }
5631
5632 if (!TagDecl) {
5633 // The action failed to produce an enumeration tag. If this is a
5634 // definition, consume the entire definition.
5635 if (Tok.is(tok::l_brace) && TUK != TagUseKind::Reference) {
5636 ConsumeBrace();
5637 SkipUntil(tok::r_brace, StopAtSemi);
5638 }
5639
5640 DS.SetTypeSpecError();
5641 return;
5642 }
5643
5644 if (Tok.is(tok::l_brace) && TUK == TagUseKind::Definition) {
5645 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
5646 ParseEnumBody(StartLoc, D);
5647 if (SkipBody.CheckSameAsPrevious &&
5648 !Actions.ActOnDuplicateDefinition(TagDecl, SkipBody)) {
5649 DS.SetTypeSpecError();
5650 return;
5651 }
5652 }
5653
5654 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5655 NameLoc.isValid() ? NameLoc : StartLoc,
5656 PrevSpec, DiagID, TagDecl, Owned,
5657 Actions.getASTContext().getPrintingPolicy()))
5658 Diag(StartLoc, DiagID) << PrevSpec;
5659}
5660
5661/// ParseEnumBody - Parse a {} enclosed enumerator-list.
5662/// enumerator-list:
5663/// enumerator
5664/// enumerator-list ',' enumerator
5665/// enumerator:
5666/// enumeration-constant attributes[opt]
5667/// enumeration-constant attributes[opt] '=' constant-expression
5668/// enumeration-constant:
5669/// identifier
5670///
5671void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
5672 // Enter the scope of the enum body and start the definition.
5673 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
5675
5676 BalancedDelimiterTracker T(*this, tok::l_brace);
5677 T.consumeOpen();
5678
5679 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
5680 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
5681 Diag(Tok, diag::err_empty_enum);
5682
5683 SmallVector<Decl *, 32> EnumConstantDecls;
5684 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
5685
5686 Decl *LastEnumConstDecl = nullptr;
5687
5688 // Parse the enumerator-list.
5689 while (Tok.isNot(tok::r_brace)) {
5690 // Parse enumerator. If failed, try skipping till the start of the next
5691 // enumerator definition.
5692 if (Tok.isNot(tok::identifier)) {
5693 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
5694 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
5695 TryConsumeToken(tok::comma))
5696 continue;
5697 break;
5698 }
5699 IdentifierInfo *Ident = Tok.getIdentifierInfo();
5700 SourceLocation IdentLoc = ConsumeToken();
5701
5702 // If attributes exist after the enumerator, parse them.
5703 ParsedAttributes attrs(AttrFactory);
5704 MaybeParseGNUAttributes(attrs);
5705 if (isAllowedCXX11AttributeSpecifier()) {
5706 if (getLangOpts().CPlusPlus)
5708 ? diag::warn_cxx14_compat_ns_enum_attribute
5709 : diag::ext_ns_enum_attribute)
5710 << 1 /*enumerator*/;
5711 ParseCXX11Attributes(attrs);
5712 }
5713
5714 SourceLocation EqualLoc;
5715 ExprResult AssignedVal;
5716 EnumAvailabilityDiags.emplace_back(*this);
5717
5718 EnterExpressionEvaluationContext ConstantEvaluated(
5720 if (TryConsumeToken(tok::equal, EqualLoc)) {
5722 if (AssignedVal.isInvalid())
5723 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
5724 }
5725
5726 // Install the enumerator constant into EnumDecl.
5727 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
5728 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
5729 EqualLoc, AssignedVal.get());
5730 EnumAvailabilityDiags.back().done();
5731
5732 EnumConstantDecls.push_back(EnumConstDecl);
5733 LastEnumConstDecl = EnumConstDecl;
5734
5735 if (Tok.is(tok::identifier)) {
5736 // We're missing a comma between enumerators.
5738 Diag(Loc, diag::err_enumerator_list_missing_comma)
5740 continue;
5741 }
5742
5743 // Emumerator definition must be finished, only comma or r_brace are
5744 // allowed here.
5745 SourceLocation CommaLoc;
5746 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
5747 if (EqualLoc.isValid())
5748 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
5749 << tok::comma;
5750 else
5751 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
5752 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
5753 if (TryConsumeToken(tok::comma, CommaLoc))
5754 continue;
5755 } else {
5756 break;
5757 }
5758 }
5759
5760 // If comma is followed by r_brace, emit appropriate warning.
5761 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
5763 Diag(CommaLoc, getLangOpts().CPlusPlus ?
5764 diag::ext_enumerator_list_comma_cxx :
5765 diag::ext_enumerator_list_comma_c)
5766 << FixItHint::CreateRemoval(CommaLoc);
5767 else if (getLangOpts().CPlusPlus11)
5768 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
5769 << FixItHint::CreateRemoval(CommaLoc);
5770 break;
5771 }
5772 }
5773
5774 // Eat the }.
5775 T.consumeClose();
5776
5777 // If attributes exist after the identifier list, parse them.
5778 ParsedAttributes attrs(AttrFactory);
5779 MaybeParseGNUAttributes(attrs);
5780
5781 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
5782 getCurScope(), attrs);
5783
5784 // Now handle enum constant availability diagnostics.
5785 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
5786 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
5788 EnumAvailabilityDiags[i].redelay();
5789 PD.complete(EnumConstantDecls[i]);
5790 }
5791
5792 EnumScope.Exit();
5793 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
5794
5795 // The next token must be valid after an enum definition. If not, a ';'
5796 // was probably forgotten.
5797 bool CanBeBitfield = getCurScope()->isClassScope();
5798 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
5799 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
5800 // Push this token back into the preprocessor and change our current token
5801 // to ';' so that the rest of the code recovers as though there were an
5802 // ';' after the definition.
5803 PP.EnterToken(Tok, /*IsReinject=*/true);
5804 Tok.setKind(tok::semi);
5805 }
5806}
5807
5808/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
5809/// is definitely a type-specifier. Return false if it isn't part of a type
5810/// specifier or if we're not sure.
5811bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
5812 switch (Tok.getKind()) {
5813 default: return false;
5814 // type-specifiers
5815 case tok::kw_short:
5816 case tok::kw_long:
5817 case tok::kw___int64:
5818 case tok::kw___int128:
5819 case tok::kw_signed:
5820 case tok::kw_unsigned:
5821 case tok::kw__Complex:
5822 case tok::kw__Imaginary:
5823 case tok::kw_void:
5824 case tok::kw_char:
5825 case tok::kw_wchar_t:
5826 case tok::kw_char8_t:
5827 case tok::kw_char16_t:
5828 case tok::kw_char32_t:
5829 case tok::kw_int:
5830 case tok::kw__ExtInt:
5831 case tok::kw__BitInt:
5832 case tok::kw___bf16:
5833 case tok::kw_half:
5834 case tok::kw_float:
5835 case tok::kw_double:
5836 case tok::kw__Accum:
5837 case tok::kw__Fract:
5838 case tok::kw__Float16:
5839 case tok::kw___float128:
5840 case tok::kw___ibm128:
5841 case tok::kw_bool:
5842 case tok::kw__Bool:
5843 case tok::kw__Decimal32:
5844 case tok::kw__Decimal64:
5845 case tok::kw__Decimal128:
5846 case tok::kw___vector:
5847#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5848#include "clang/Basic/OpenCLImageTypes.def"
5849#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
5850#include "clang/Basic/HLSLIntangibleTypes.def"
5851
5852 // struct-or-union-specifier (C99) or class-specifier (C++)
5853 case tok::kw_class:
5854 case tok::kw_struct:
5855 case tok::kw___interface:
5856 case tok::kw_union:
5857 // enum-specifier
5858 case tok::kw_enum:
5859
5860 // typedef-name
5861 case tok::annot_typename:
5862 return true;
5863 }
5864}
5865
5866/// isTypeSpecifierQualifier - Return true if the current token could be the
5867/// start of a specifier-qualifier-list.
5868bool Parser::isTypeSpecifierQualifier() {
5869 switch (Tok.getKind()) {
5870 default: return false;
5871
5872 case tok::identifier: // foo::bar
5873 if (TryAltiVecVectorToken())
5874 return true;
5875 [[fallthrough]];
5876 case tok::kw_typename: // typename T::type
5877 // Annotate typenames and C++ scope specifiers. If we get one, just
5878 // recurse to handle whatever we get.
5880 return true;
5881 if (Tok.is(tok::identifier))
5882 return false;
5883 return isTypeSpecifierQualifier();
5884
5885 case tok::coloncolon: // ::foo::bar
5886 if (NextToken().is(tok::kw_new) || // ::new
5887 NextToken().is(tok::kw_delete)) // ::delete
5888 return false;
5889
5891 return true;
5892 return isTypeSpecifierQualifier();
5893
5894 // GNU attributes support.
5895 case tok::kw___attribute:
5896 // C23/GNU typeof support.
5897 case tok::kw_typeof:
5898 case tok::kw_typeof_unqual:
5899
5900 // type-specifiers
5901 case tok::kw_short:
5902 case tok::kw_long:
5903 case tok::kw___int64:
5904 case tok::kw___int128:
5905 case tok::kw_signed:
5906 case tok::kw_unsigned:
5907 case tok::kw__Complex:
5908 case tok::kw__Imaginary:
5909 case tok::kw_void:
5910 case tok::kw_char:
5911 case tok::kw_wchar_t:
5912 case tok::kw_char8_t:
5913 case tok::kw_char16_t:
5914 case tok::kw_char32_t:
5915 case tok::kw_int:
5916 case tok::kw__ExtInt:
5917 case tok::kw__BitInt:
5918 case tok::kw_half:
5919 case tok::kw___bf16:
5920 case tok::kw_float:
5921 case tok::kw_double:
5922 case tok::kw__Accum:
5923 case tok::kw__Fract:
5924 case tok::kw__Float16:
5925 case tok::kw___float128:
5926 case tok::kw___ibm128:
5927 case tok::kw_bool:
5928 case tok::kw__Bool:
5929 case tok::kw__Decimal32:
5930 case tok::kw__Decimal64:
5931 case tok::kw__Decimal128:
5932 case tok::kw___vector:
5933#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5934#include "clang/Basic/OpenCLImageTypes.def"
5935#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
5936#include "clang/Basic/HLSLIntangibleTypes.def"
5937
5938 // struct-or-union-specifier (C99) or class-specifier (C++)
5939 case tok::kw_class:
5940 case tok::kw_struct:
5941 case tok::kw___interface:
5942 case tok::kw_union:
5943 // enum-specifier
5944 case tok::kw_enum:
5945
5946 // type-qualifier
5947 case tok::kw_const:
5948 case tok::kw_volatile:
5949 case tok::kw_restrict:
5950 case tok::kw__Sat:
5951
5952 // Debugger support.
5953 case tok::kw___unknown_anytype:
5954
5955 // typedef-name
5956 case tok::annot_typename:
5957 return true;
5958
5959 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5960 case tok::less:
5961 return getLangOpts().ObjC;
5962
5963 case tok::kw___cdecl:
5964 case tok::kw___stdcall:
5965 case tok::kw___fastcall:
5966 case tok::kw___thiscall:
5967 case tok::kw___regcall:
5968 case tok::kw___vectorcall:
5969 case tok::kw___w64:
5970 case tok::kw___ptr64:
5971 case tok::kw___ptr32:
5972 case tok::kw___pascal:
5973 case tok::kw___unaligned:
5974
5975 case tok::kw__Nonnull:
5976 case tok::kw__Nullable:
5977 case tok::kw__Nullable_result:
5978 case tok::kw__Null_unspecified:
5979
5980 case tok::kw___kindof:
5981
5982 case tok::kw___private:
5983 case tok::kw___local:
5984 case tok::kw___global:
5985 case tok::kw___constant:
5986 case tok::kw___generic:
5987 case tok::kw___read_only:
5988 case tok::kw___read_write:
5989 case tok::kw___write_only:
5990 case tok::kw___funcref:
5991 return true;
5992
5993 case tok::kw_private:
5994 return getLangOpts().OpenCL;
5995
5996 // C11 _Atomic
5997 case tok::kw__Atomic:
5998 return true;
5999
6000 // HLSL type qualifiers
6001 case tok::kw_groupshared:
6002 case tok::kw_in:
6003 case tok::kw_inout:
6004 case tok::kw_out:
6005 return getLangOpts().HLSL;
6006 }
6007}
6008
6009Parser::DeclGroupPtrTy Parser::ParseTopLevelStmtDecl() {
6010 assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode");
6011
6012 // Parse a top-level-stmt.
6013 Parser::StmtVector Stmts;
6014 ParsedStmtContext SubStmtCtx = ParsedStmtContext();
6015 ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
6018 StmtResult R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
6019 if (!R.isUsable())
6020 return nullptr;
6021
6022 Actions.ActOnFinishTopLevelStmtDecl(TLSD, R.get());
6023
6024 if (Tok.is(tok::annot_repl_input_end) &&
6025 Tok.getAnnotationValue() != nullptr) {
6026 ConsumeAnnotationToken();
6027 TLSD->setSemiMissing();
6028 }
6029
6030 SmallVector<Decl *, 2> DeclsInGroup;
6031 DeclsInGroup.push_back(TLSD);
6032
6033 // Currently happens for things like -fms-extensions and use `__if_exists`.
6034 for (Stmt *S : Stmts) {
6035 // Here we should be safe as `__if_exists` and friends are not introducing
6036 // new variables which need to live outside file scope.
6038 Actions.ActOnFinishTopLevelStmtDecl(D, S);
6039 DeclsInGroup.push_back(D);
6040 }
6041
6042 return Actions.BuildDeclaratorGroup(DeclsInGroup);
6043}
6044
6045/// isDeclarationSpecifier() - Return true if the current token is part of a
6046/// declaration specifier.
6047///
6048/// \param AllowImplicitTypename whether this is a context where T::type [T
6049/// dependent] can appear.
6050/// \param DisambiguatingWithExpression True to indicate that the purpose of
6051/// this check is to disambiguate between an expression and a declaration.
6052bool Parser::isDeclarationSpecifier(
6053 ImplicitTypenameContext AllowImplicitTypename,
6054 bool DisambiguatingWithExpression) {
6055 switch (Tok.getKind()) {
6056 default: return false;
6057
6058 // OpenCL 2.0 and later define this keyword.
6059 case tok::kw_pipe:
6060 return getLangOpts().OpenCL &&
6062
6063 case tok::identifier: // foo::bar
6064 // Unfortunate hack to support "Class.factoryMethod" notation.
6065 if (getLangOpts().ObjC && NextToken().is(tok::period))
6066 return false;
6067 if (TryAltiVecVectorToken())
6068 return true;
6069 [[fallthrough]];
6070 case tok::kw_decltype: // decltype(T())::type
6071 case tok::kw_typename: // typename T::type
6072 // Annotate typenames and C++ scope specifiers. If we get one, just
6073 // recurse to handle whatever we get.
6074 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename))
6075 return true;
6076 if (TryAnnotateTypeConstraint())
6077 return true;
6078 if (Tok.is(tok::identifier))
6079 return false;
6080
6081 // If we're in Objective-C and we have an Objective-C class type followed
6082 // by an identifier and then either ':' or ']', in a place where an
6083 // expression is permitted, then this is probably a class message send
6084 // missing the initial '['. In this case, we won't consider this to be
6085 // the start of a declaration.
6086 if (DisambiguatingWithExpression &&
6087 isStartOfObjCClassMessageMissingOpenBracket())
6088 return false;
6089
6090 return isDeclarationSpecifier(AllowImplicitTypename);
6091
6092 case tok::coloncolon: // ::foo::bar
6093 if (!getLangOpts().CPlusPlus)
6094 return false;
6095 if (NextToken().is(tok::kw_new) || // ::new
6096 NextToken().is(tok::kw_delete)) // ::delete
6097 return false;
6098
6099 // Annotate typenames and C++ scope specifiers. If we get one, just
6100 // recurse to handle whatever we get.
6102 return true;
6103 return isDeclarationSpecifier(ImplicitTypenameContext::No);
6104
6105 // storage-class-specifier
6106 case tok::kw_typedef:
6107 case tok::kw_extern:
6108 case tok::kw___private_extern__:
6109 case tok::kw_static:
6110 case tok::kw_auto:
6111 case tok::kw___auto_type:
6112 case tok::kw_register:
6113 case tok::kw___thread:
6114 case tok::kw_thread_local:
6115 case tok::kw__Thread_local:
6116
6117 // Modules
6118 case tok::kw___module_private__:
6119
6120 // Debugger support
6121 case tok::kw___unknown_anytype:
6122
6123 // type-specifiers
6124 case tok::kw_short:
6125 case tok::kw_long:
6126 case tok::kw___int64:
6127 case tok::kw___int128:
6128 case tok::kw_signed:
6129 case tok::kw_unsigned:
6130 case tok::kw__Complex:
6131 case tok::kw__Imaginary:
6132 case tok::kw_void:
6133 case tok::kw_char:
6134 case tok::kw_wchar_t:
6135 case tok::kw_char8_t:
6136 case tok::kw_char16_t:
6137 case tok::kw_char32_t:
6138
6139 case tok::kw_int:
6140 case tok::kw__ExtInt:
6141 case tok::kw__BitInt:
6142 case tok::kw_half:
6143 case tok::kw___bf16:
6144 case tok::kw_float:
6145 case tok::kw_double:
6146 case tok::kw__Accum:
6147 case tok::kw__Fract:
6148 case tok::kw__Float16:
6149 case tok::kw___float128:
6150 case tok::kw___ibm128:
6151 case tok::kw_bool:
6152 case tok::kw__Bool:
6153 case tok::kw__Decimal32:
6154 case tok::kw__Decimal64:
6155 case tok::kw__Decimal128:
6156 case tok::kw___vector:
6157
6158 // struct-or-union-specifier (C99) or class-specifier (C++)
6159 case tok::kw_class:
6160 case tok::kw_struct:
6161 case tok::kw_union:
6162 case tok::kw___interface:
6163 // enum-specifier
6164 case tok::kw_enum:
6165
6166 // type-qualifier
6167 case tok::kw_const:
6168 case tok::kw_volatile:
6169 case tok::kw_restrict:
6170 case tok::kw__Sat:
6171
6172 // function-specifier
6173 case tok::kw_inline:
6174 case tok::kw_virtual:
6175 case tok::kw_explicit:
6176 case tok::kw__Noreturn:
6177
6178 // alignment-specifier
6179 case tok::kw__Alignas:
6180
6181 // friend keyword.
6182 case tok::kw_friend:
6183
6184 // static_assert-declaration
6185 case tok::kw_static_assert:
6186 case tok::kw__Static_assert:
6187
6188 // C23/GNU typeof support.
6189 case tok::kw_typeof:
6190 case tok::kw_typeof_unqual:
6191
6192 // GNU attributes.
6193 case tok::kw___attribute:
6194
6195 // C++11 decltype and constexpr.
6196 case tok::annot_decltype:
6197 case tok::annot_pack_indexing_type:
6198 case tok::kw_constexpr:
6199
6200 // C++20 consteval and constinit.
6201 case tok::kw_consteval:
6202 case tok::kw_constinit:
6203
6204 // C11 _Atomic
6205 case tok::kw__Atomic:
6206 return true;
6207
6208 case tok::kw_alignas:
6209 // alignas is a type-specifier-qualifier in C23, which is a kind of
6210 // declaration-specifier. Outside of C23 mode (including in C++), it is not.
6211 return getLangOpts().C23;
6212
6213 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
6214 case tok::less:
6215 return getLangOpts().ObjC;
6216
6217 // typedef-name
6218 case tok::annot_typename:
6219 return !DisambiguatingWithExpression ||
6220 !isStartOfObjCClassMessageMissingOpenBracket();
6221
6222 // placeholder-type-specifier
6223 case tok::annot_template_id: {
6224 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
6225 if (TemplateId->hasInvalidName())
6226 return true;
6227 // FIXME: What about type templates that have only been annotated as
6228 // annot_template_id, not as annot_typename?
6229 return isTypeConstraintAnnotation() &&
6230 (NextToken().is(tok::kw_auto) || NextToken().is(tok::kw_decltype));
6231 }
6232
6233 case tok::annot_cxxscope: {
6234 TemplateIdAnnotation *TemplateId =
6235 NextToken().is(tok::annot_template_id)
6236 ? takeTemplateIdAnnotation(NextToken())
6237 : nullptr;
6238 if (TemplateId && TemplateId->hasInvalidName())
6239 return true;
6240 // FIXME: What about type templates that have only been annotated as
6241 // annot_template_id, not as annot_typename?
6242 if (NextToken().is(tok::identifier) && TryAnnotateTypeConstraint())
6243 return true;
6244 return isTypeConstraintAnnotation() &&
6245 GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype);
6246 }
6247
6248 case tok::kw___declspec:
6249 case tok::kw___cdecl:
6250 case tok::kw___stdcall:
6251 case tok::kw___fastcall:
6252 case tok::kw___thiscall:
6253 case tok::kw___regcall:
6254 case tok::kw___vectorcall:
6255 case tok::kw___w64:
6256 case tok::kw___sptr:
6257 case tok::kw___uptr:
6258 case tok::kw___ptr64:
6259 case tok::kw___ptr32:
6260 case tok::kw___forceinline:
6261 case tok::kw___pascal:
6262 case tok::kw___unaligned:
6263
6264 case tok::kw__Nonnull:
6265 case tok::kw__Nullable:
6266 case tok::kw__Nullable_result:
6267 case tok::kw__Null_unspecified:
6268
6269 case tok::kw___kindof:
6270
6271 case tok::kw___private:
6272 case tok::kw___local:
6273 case tok::kw___global:
6274 case tok::kw___constant:
6275 case tok::kw___generic:
6276 case tok::kw___read_only:
6277 case tok::kw___read_write:
6278 case tok::kw___write_only:
6279#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
6280#include "clang/Basic/OpenCLImageTypes.def"
6281#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
6282#include "clang/Basic/HLSLIntangibleTypes.def"
6283
6284 case tok::kw___funcref:
6285 case tok::kw_groupshared:
6286 return true;
6287
6288 case tok::kw_private:
6289 return getLangOpts().OpenCL;
6290 }
6291}
6292
6293bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide,
6295 const ParsedTemplateInfo *TemplateInfo) {
6296 RevertingTentativeParsingAction TPA(*this);
6297 // Parse the C++ scope specifier.
6298 CXXScopeSpec SS;
6299 if (TemplateInfo && TemplateInfo->TemplateParams)
6300 SS.setTemplateParamLists(*TemplateInfo->TemplateParams);
6301
6302 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6303 /*ObjectHasErrors=*/false,
6304 /*EnteringContext=*/true)) {
6305 return false;
6306 }
6307
6308 // Parse the constructor name.
6309 if (Tok.is(tok::identifier)) {
6310 // We already know that we have a constructor name; just consume
6311 // the token.
6312 ConsumeToken();
6313 } else if (Tok.is(tok::annot_template_id)) {
6314 ConsumeAnnotationToken();
6315 } else {
6316 return false;
6317 }
6318
6319 // There may be attributes here, appertaining to the constructor name or type
6320 // we just stepped past.
6321 SkipCXX11Attributes();
6322
6323 // Current class name must be followed by a left parenthesis.
6324 if (Tok.isNot(tok::l_paren)) {
6325 return false;
6326 }
6327 ConsumeParen();
6328
6329 // A right parenthesis, or ellipsis followed by a right parenthesis signals
6330 // that we have a constructor.
6331 if (Tok.is(tok::r_paren) ||
6332 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
6333 return true;
6334 }
6335
6336 // A C++11 attribute here signals that we have a constructor, and is an
6337 // attribute on the first constructor parameter.
6338 if (getLangOpts().CPlusPlus11 &&
6339 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
6340 /*OuterMightBeMessageSend*/ true)) {
6341 return true;
6342 }
6343
6344 // If we need to, enter the specified scope.
6345 DeclaratorScopeObj DeclScopeObj(*this, SS);
6346 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
6347 DeclScopeObj.EnterDeclaratorScope();
6348
6349 // Optionally skip Microsoft attributes.
6350 ParsedAttributes Attrs(AttrFactory);
6351 MaybeParseMicrosoftAttributes(Attrs);
6352
6353 // Check whether the next token(s) are part of a declaration
6354 // specifier, in which case we have the start of a parameter and,
6355 // therefore, we know that this is a constructor.
6356 // Due to an ambiguity with implicit typename, the above is not enough.
6357 // Additionally, check to see if we are a friend.
6358 // If we parsed a scope specifier as well as friend,
6359 // we might be parsing a friend constructor.
6360 bool IsConstructor = false;
6361 ImplicitTypenameContext ITC = IsFriend && !SS.isSet()
6364 // Constructors cannot have this parameters, but we support that scenario here
6365 // to improve diagnostic.
6366 if (Tok.is(tok::kw_this)) {
6367 ConsumeToken();
6368 return isDeclarationSpecifier(ITC);
6369 }
6370
6371 if (isDeclarationSpecifier(ITC))
6372 IsConstructor = true;
6373 else if (Tok.is(tok::identifier) ||
6374 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
6375 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
6376 // This might be a parenthesized member name, but is more likely to
6377 // be a constructor declaration with an invalid argument type. Keep
6378 // looking.
6379 if (Tok.is(tok::annot_cxxscope))
6380 ConsumeAnnotationToken();
6381 ConsumeToken();
6382
6383 // If this is not a constructor, we must be parsing a declarator,
6384 // which must have one of the following syntactic forms (see the
6385 // grammar extract at the start of ParseDirectDeclarator):
6386 switch (Tok.getKind()) {
6387 case tok::l_paren:
6388 // C(X ( int));
6389 case tok::l_square:
6390 // C(X [ 5]);
6391 // C(X [ [attribute]]);
6392 case tok::coloncolon:
6393 // C(X :: Y);
6394 // C(X :: *p);
6395 // Assume this isn't a constructor, rather than assuming it's a
6396 // constructor with an unnamed parameter of an ill-formed type.
6397 break;
6398
6399 case tok::r_paren:
6400 // C(X )
6401
6402 // Skip past the right-paren and any following attributes to get to
6403 // the function body or trailing-return-type.
6404 ConsumeParen();
6405 SkipCXX11Attributes();
6406
6407 if (DeductionGuide) {
6408 // C(X) -> ... is a deduction guide.
6409 IsConstructor = Tok.is(tok::arrow);
6410 break;
6411 }
6412 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
6413 // Assume these were meant to be constructors:
6414 // C(X) : (the name of a bit-field cannot be parenthesized).
6415 // C(X) try (this is otherwise ill-formed).
6416 IsConstructor = true;
6417 }
6418 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
6419 // If we have a constructor name within the class definition,
6420 // assume these were meant to be constructors:
6421 // C(X) {
6422 // C(X) ;
6423 // ... because otherwise we would be declaring a non-static data
6424 // member that is ill-formed because it's of the same type as its
6425 // surrounding class.
6426 //
6427 // FIXME: We can actually do this whether or not the name is qualified,
6428 // because if it is qualified in this context it must be being used as
6429 // a constructor name.
6430 // currently, so we're somewhat conservative here.
6431 IsConstructor = IsUnqualified;
6432 }
6433 break;
6434
6435 default:
6436 IsConstructor = true;
6437 break;
6438 }
6439 }
6440 return IsConstructor;
6441}
6442
6443/// ParseTypeQualifierListOpt
6444/// type-qualifier-list: [C99 6.7.5]
6445/// type-qualifier
6446/// [vendor] attributes
6447/// [ only if AttrReqs & AR_VendorAttributesParsed ]
6448/// type-qualifier-list type-qualifier
6449/// [vendor] type-qualifier-list attributes
6450/// [ only if AttrReqs & AR_VendorAttributesParsed ]
6451/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
6452/// [ only if AttReqs & AR_CXX11AttributesParsed ]
6453/// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
6454/// AttrRequirements bitmask values.
6455void Parser::ParseTypeQualifierListOpt(
6456 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
6457 bool IdentifierRequired,
6458 std::optional<llvm::function_ref<void()>> CodeCompletionHandler) {
6459 if ((AttrReqs & AR_CXX11AttributesParsed) &&
6460 isAllowedCXX11AttributeSpecifier()) {
6461 ParsedAttributes Attrs(AttrFactory);
6462 ParseCXX11Attributes(Attrs);
6463 DS.takeAttributesFrom(Attrs);
6464 }
6465
6466 SourceLocation EndLoc;
6467
6468 while (true) {
6469 bool isInvalid = false;
6470 const char *PrevSpec = nullptr;
6471 unsigned DiagID = 0;
6473
6474 switch (Tok.getKind()) {
6475 case tok::code_completion:
6476 cutOffParsing();
6478 (*CodeCompletionHandler)();
6479 else
6481 return;
6482
6483 case tok::kw_const:
6484 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
6485 getLangOpts());
6486 break;
6487 case tok::kw_volatile:
6488 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
6489 getLangOpts());
6490 break;
6491 case tok::kw_restrict:
6492 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
6493 getLangOpts());
6494 break;
6495 case tok::kw__Atomic:
6496 if (!AtomicAllowed)
6497 goto DoneWithTypeQuals;
6498 diagnoseUseOfC11Keyword(Tok);
6499 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
6500 getLangOpts());
6501 break;
6502
6503 // OpenCL qualifiers:
6504 case tok::kw_private:
6505 if (!getLangOpts().OpenCL)
6506 goto DoneWithTypeQuals;
6507 [[fallthrough]];
6508 case tok::kw___private:
6509 case tok::kw___global:
6510 case tok::kw___local:
6511 case tok::kw___constant:
6512 case tok::kw___generic:
6513 case tok::kw___read_only:
6514 case tok::kw___write_only:
6515 case tok::kw___read_write:
6516 ParseOpenCLQualifiers(DS.getAttributes());
6517 break;
6518
6519 case tok::kw_groupshared:
6520 case tok::kw_in:
6521 case tok::kw_inout:
6522 case tok::kw_out:
6523 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
6524 ParseHLSLQualifiers(DS.getAttributes());
6525 continue;
6526
6527 case tok::kw___unaligned:
6528 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
6529 getLangOpts());
6530 break;
6531 case tok::kw___uptr:
6532 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
6533 // with the MS modifier keyword.
6534 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
6535 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
6536 if (TryKeywordIdentFallback(false))
6537 continue;
6538 }
6539 [[fallthrough]];
6540 case tok::kw___sptr:
6541 case tok::kw___w64:
6542 case tok::kw___ptr64:
6543 case tok::kw___ptr32:
6544 case tok::kw___cdecl:
6545 case tok::kw___stdcall:
6546 case tok::kw___fastcall:
6547 case tok::kw___thiscall:
6548 case tok::kw___regcall:
6549 case tok::kw___vectorcall:
6550 if (AttrReqs & AR_DeclspecAttributesParsed) {
6551 ParseMicrosoftTypeAttributes(DS.getAttributes());
6552 continue;
6553 }
6554 goto DoneWithTypeQuals;
6555
6556 case tok::kw___funcref:
6557 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
6558 continue;
6559 goto DoneWithTypeQuals;
6560
6561 case tok::kw___pascal:
6562 if (AttrReqs & AR_VendorAttributesParsed) {
6563 ParseBorlandTypeAttributes(DS.getAttributes());
6564 continue;
6565 }
6566 goto DoneWithTypeQuals;
6567
6568 // Nullability type specifiers.
6569 case tok::kw__Nonnull:
6570 case tok::kw__Nullable:
6571 case tok::kw__Nullable_result:
6572 case tok::kw__Null_unspecified:
6573 ParseNullabilityTypeSpecifiers(DS.getAttributes());
6574 continue;
6575
6576 // Objective-C 'kindof' types.
6577 case tok::kw___kindof:
6578 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
6579 nullptr, 0, tok::kw___kindof);
6580 (void)ConsumeToken();
6581 continue;
6582
6583 case tok::kw___attribute:
6584 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
6585 // When GNU attributes are expressly forbidden, diagnose their usage.
6586 Diag(Tok, diag::err_attributes_not_allowed);
6587
6588 // Parse the attributes even if they are rejected to ensure that error
6589 // recovery is graceful.
6590 if (AttrReqs & AR_GNUAttributesParsed ||
6591 AttrReqs & AR_GNUAttributesParsedAndRejected) {
6592 ParseGNUAttributes(DS.getAttributes());
6593 continue; // do *not* consume the next token!
6594 }
6595 // otherwise, FALL THROUGH!
6596 [[fallthrough]];
6597 default:
6598 DoneWithTypeQuals:
6599 // If this is not a type-qualifier token, we're done reading type
6600 // qualifiers. First verify that DeclSpec's are consistent.
6601 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
6602 if (EndLoc.isValid())
6603 DS.SetRangeEnd(EndLoc);
6604 return;
6605 }
6606
6607 // If the specifier combination wasn't legal, issue a diagnostic.
6608 if (isInvalid) {
6609 assert(PrevSpec && "Method did not return previous specifier!");
6610 Diag(Tok, DiagID) << PrevSpec;
6611 }
6612 EndLoc = ConsumeToken();
6613 }
6614}
6615
6616/// ParseDeclarator - Parse and verify a newly-initialized declarator.
6617void Parser::ParseDeclarator(Declarator &D) {
6618 /// This implements the 'declarator' production in the C grammar, then checks
6619 /// for well-formedness and issues diagnostics.
6621 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6622 });
6623}
6624
6625static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
6626 DeclaratorContext TheContext) {
6627 if (Kind == tok::star || Kind == tok::caret)
6628 return true;
6629
6630 // OpenCL 2.0 and later define this keyword.
6631 if (Kind == tok::kw_pipe && Lang.OpenCL &&
6632 Lang.getOpenCLCompatibleVersion() >= 200)
6633 return true;
6634
6635 if (!Lang.CPlusPlus)
6636 return false;
6637
6638 if (Kind == tok::amp)
6639 return true;
6640
6641 // We parse rvalue refs in C++03, because otherwise the errors are scary.
6642 // But we must not parse them in conversion-type-ids and new-type-ids, since
6643 // those can be legitimately followed by a && operator.
6644 // (The same thing can in theory happen after a trailing-return-type, but
6645 // since those are a C++11 feature, there is no rejects-valid issue there.)
6646 if (Kind == tok::ampamp)
6647 return Lang.CPlusPlus11 || (TheContext != DeclaratorContext::ConversionId &&
6648 TheContext != DeclaratorContext::CXXNew);
6649
6650 return false;
6651}
6652
6653// Indicates whether the given declarator is a pipe declarator.
6654static bool isPipeDeclarator(const Declarator &D) {
6655 const unsigned NumTypes = D.getNumTypeObjects();
6656
6657 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
6658 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
6659 return true;
6660
6661 return false;
6662}
6663
6664/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
6665/// is parsed by the function passed to it. Pass null, and the direct-declarator
6666/// isn't parsed at all, making this function effectively parse the C++
6667/// ptr-operator production.
6668///
6669/// If the grammar of this construct is extended, matching changes must also be
6670/// made to TryParseDeclarator and MightBeDeclarator, and possibly to
6671/// isConstructorDeclarator.
6672///
6673/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
6674/// [C] pointer[opt] direct-declarator
6675/// [C++] direct-declarator
6676/// [C++] ptr-operator declarator
6677///
6678/// pointer: [C99 6.7.5]
6679/// '*' type-qualifier-list[opt]
6680/// '*' type-qualifier-list[opt] pointer
6681///
6682/// ptr-operator:
6683/// '*' cv-qualifier-seq[opt]
6684/// '&'
6685/// [C++0x] '&&'
6686/// [GNU] '&' restrict[opt] attributes[opt]
6687/// [GNU?] '&&' restrict[opt] attributes[opt]
6688/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
6689void Parser::ParseDeclaratorInternal(Declarator &D,
6690 DirectDeclParseFunction DirectDeclParser) {
6691 if (Diags.hasAllExtensionsSilenced())
6692 D.setExtension();
6693
6694 // C++ member pointers start with a '::' or a nested-name.
6695 // Member pointers get special handling, since there's no place for the
6696 // scope spec in the generic path below.
6697 if (getLangOpts().CPlusPlus &&
6698 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
6699 (Tok.is(tok::identifier) &&
6700 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
6701 Tok.is(tok::annot_cxxscope))) {
6702 TentativeParsingAction TPA(*this, /*Unannotated=*/true);
6703 bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6704 D.getContext() == DeclaratorContext::Member;
6705 CXXScopeSpec SS;
6706 SS.setTemplateParamLists(D.getTemplateParameterLists());
6707
6708 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6709 /*ObjectHasErrors=*/false,
6710 /*EnteringContext=*/false,
6711 /*MayBePseudoDestructor=*/nullptr,
6712 /*IsTypename=*/false, /*LastII=*/nullptr,
6713 /*OnlyNamespace=*/false,
6714 /*InUsingDeclaration=*/false,
6715 /*Disambiguation=*/EnteringContext) ||
6716
6717 SS.isEmpty() || SS.isInvalid() || !EnteringContext ||
6718 Tok.is(tok::star)) {
6719 TPA.Commit();
6720 if (SS.isNotEmpty() && Tok.is(tok::star)) {
6721 if (SS.isValid()) {
6722 checkCompoundToken(SS.getEndLoc(), tok::coloncolon,
6723 CompoundToken::MemberPtr);
6724 }
6725
6726 SourceLocation StarLoc = ConsumeToken();
6727 D.SetRangeEnd(StarLoc);
6728 DeclSpec DS(AttrFactory);
6729 ParseTypeQualifierListOpt(DS);
6730 D.ExtendWithDeclSpec(DS);
6731
6732 // Recurse to parse whatever is left.
6734 ParseDeclaratorInternal(D, DirectDeclParser);
6735 });
6736
6737 // Sema will have to catch (syntactically invalid) pointers into global
6738 // scope. It has to catch pointers into namespace scope anyway.
6740 SS, DS.getTypeQualifiers(), StarLoc, DS.getEndLoc()),
6741 std::move(DS.getAttributes()),
6742 /*EndLoc=*/SourceLocation());
6743 return;
6744 }
6745 } else {
6746 TPA.Revert();
6747 SS.clear();
6748 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6749 /*ObjectHasErrors=*/false,
6750 /*EnteringContext=*/true);
6751 }
6752
6753 if (SS.isNotEmpty()) {
6754 // The scope spec really belongs to the direct-declarator.
6755 if (D.mayHaveIdentifier())
6756 D.getCXXScopeSpec() = SS;
6757 else
6758 AnnotateScopeToken(SS, true);
6759
6760 if (DirectDeclParser)
6761 (this->*DirectDeclParser)(D);
6762 return;
6763 }
6764 }
6765
6766 tok::TokenKind Kind = Tok.getKind();
6767
6768 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclarator(D)) {
6769 DeclSpec DS(AttrFactory);
6770 ParseTypeQualifierListOpt(DS);
6771
6772 D.AddTypeInfo(
6774 std::move(DS.getAttributes()), SourceLocation());
6775 }
6776
6777 // Not a pointer, C++ reference, or block.
6778 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
6779 if (DirectDeclParser)
6780 (this->*DirectDeclParser)(D);
6781 return;
6782 }
6783
6784 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
6785 // '&&' -> rvalue reference
6786 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
6787 D.SetRangeEnd(Loc);
6788
6789 if (Kind == tok::star || Kind == tok::caret) {
6790 // Is a pointer.
6791 DeclSpec DS(AttrFactory);
6792
6793 // GNU attributes are not allowed here in a new-type-id, but Declspec and
6794 // C++11 attributes are allowed.
6795 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
6796 ((D.getContext() != DeclaratorContext::CXXNew)
6797 ? AR_GNUAttributesParsed
6798 : AR_GNUAttributesParsedAndRejected);
6799 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
6800 D.ExtendWithDeclSpec(DS);
6801
6802 // Recursively parse the declarator.
6804 D.getBeginLoc(), [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
6805 if (Kind == tok::star)
6806 // Remember that we parsed a pointer type, and remember the type-quals.
6807 D.AddTypeInfo(DeclaratorChunk::getPointer(
6811 std::move(DS.getAttributes()), SourceLocation());
6812 else
6813 // Remember that we parsed a Block type, and remember the type-quals.
6814 D.AddTypeInfo(
6816 std::move(DS.getAttributes()), SourceLocation());
6817 } else {
6818 // Is a reference
6819 DeclSpec DS(AttrFactory);
6820
6821 // Complain about rvalue references in C++03, but then go on and build
6822 // the declarator.
6823 if (Kind == tok::ampamp)
6825 diag::warn_cxx98_compat_rvalue_reference :
6826 diag::ext_rvalue_reference);
6827
6828 // GNU-style and C++11 attributes are allowed here, as is restrict.
6829 ParseTypeQualifierListOpt(DS);
6830 D.ExtendWithDeclSpec(DS);
6831
6832 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
6833 // cv-qualifiers are introduced through the use of a typedef or of a
6834 // template type argument, in which case the cv-qualifiers are ignored.
6837 Diag(DS.getConstSpecLoc(),
6838 diag::err_invalid_reference_qualifier_application) << "const";
6841 diag::err_invalid_reference_qualifier_application) << "volatile";
6842 // 'restrict' is permitted as an extension.
6845 diag::err_invalid_reference_qualifier_application) << "_Atomic";
6846 }
6847
6848 // Recursively parse the declarator.
6850 D.getBeginLoc(), [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
6851
6852 if (D.getNumTypeObjects() > 0) {
6853 // C++ [dcl.ref]p4: There shall be no references to references.
6854 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
6855 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
6856 if (const IdentifierInfo *II = D.getIdentifier())
6857 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
6858 << II;
6859 else
6860 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
6861 << "type name";
6862
6863 // Once we've complained about the reference-to-reference, we
6864 // can go ahead and build the (technically ill-formed)
6865 // declarator: reference collapsing will take care of it.
6866 }
6867 }
6868
6869 // Remember that we parsed a reference type.
6871 Kind == tok::amp),
6872 std::move(DS.getAttributes()), SourceLocation());
6873 }
6874}
6875
6876// When correcting from misplaced brackets before the identifier, the location
6877// is saved inside the declarator so that other diagnostic messages can use
6878// them. This extracts and returns that location, or returns the provided
6879// location if a stored location does not exist.
6882 if (D.getName().StartLocation.isInvalid() &&
6883 D.getName().EndLocation.isValid())
6884 return D.getName().EndLocation;
6885
6886 return Loc;
6887}
6888
6889/// ParseDirectDeclarator
6890/// direct-declarator: [C99 6.7.5]
6891/// [C99] identifier
6892/// '(' declarator ')'
6893/// [GNU] '(' attributes declarator ')'
6894/// [C90] direct-declarator '[' constant-expression[opt] ']'
6895/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6896/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6897/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6898/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
6899/// [C++11] direct-declarator '[' constant-expression[opt] ']'
6900/// attribute-specifier-seq[opt]
6901/// direct-declarator '(' parameter-type-list ')'
6902/// direct-declarator '(' identifier-list[opt] ')'
6903/// [GNU] direct-declarator '(' parameter-forward-declarations
6904/// parameter-type-list[opt] ')'
6905/// [C++] direct-declarator '(' parameter-declaration-clause ')'
6906/// cv-qualifier-seq[opt] exception-specification[opt]
6907/// [C++11] direct-declarator '(' parameter-declaration-clause ')'
6908/// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
6909/// ref-qualifier[opt] exception-specification[opt]
6910/// [C++] declarator-id
6911/// [C++11] declarator-id attribute-specifier-seq[opt]
6912///
6913/// declarator-id: [C++ 8]
6914/// '...'[opt] id-expression
6915/// '::'[opt] nested-name-specifier[opt] type-name
6916///
6917/// id-expression: [C++ 5.1]
6918/// unqualified-id
6919/// qualified-id
6920///
6921/// unqualified-id: [C++ 5.1]
6922/// identifier
6923/// operator-function-id
6924/// conversion-function-id
6925/// '~' class-name
6926/// template-id
6927///
6928/// C++17 adds the following, which we also handle here:
6929///
6930/// simple-declaration:
6931/// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
6932///
6933/// Note, any additional constructs added here may need corresponding changes
6934/// in isConstructorDeclarator.
6935void Parser::ParseDirectDeclarator(Declarator &D) {
6936 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
6937
6938 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
6939 // This might be a C++17 structured binding.
6940 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
6941 D.getCXXScopeSpec().isEmpty())
6942 return ParseDecompositionDeclarator(D);
6943
6944 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
6945 // this context it is a bitfield. Also in range-based for statement colon
6946 // may delimit for-range-declaration.
6948 *this, D.getContext() == DeclaratorContext::Member ||
6949 (D.getContext() == DeclaratorContext::ForInit &&
6951
6952 // ParseDeclaratorInternal might already have parsed the scope.
6953 if (D.getCXXScopeSpec().isEmpty()) {
6954 bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6955 D.getContext() == DeclaratorContext::Member;
6956 ParseOptionalCXXScopeSpecifier(
6957 D.getCXXScopeSpec(), /*ObjectType=*/nullptr,
6958 /*ObjectHasErrors=*/false, EnteringContext);
6959 }
6960
6961 // C++23 [basic.scope.namespace]p1:
6962 // For each non-friend redeclaration or specialization whose target scope
6963 // is or is contained by the scope, the portion after the declarator-id,
6964 // class-head-name, or enum-head-name is also included in the scope.
6965 // C++23 [basic.scope.class]p1:
6966 // For each non-friend redeclaration or specialization whose target scope
6967 // is or is contained by the scope, the portion after the declarator-id,
6968 // class-head-name, or enum-head-name is also included in the scope.
6969 //
6970 // FIXME: We should not be doing this for friend declarations; they have
6971 // their own special lookup semantics specified by [basic.lookup.unqual]p6.
6972 if (D.getCXXScopeSpec().isValid()) {
6974 D.getCXXScopeSpec()))
6975 // Change the declaration context for name lookup, until this function
6976 // is exited (and the declarator has been parsed).
6977 DeclScopeObj.EnterDeclaratorScope();
6978 else if (getObjCDeclContext()) {
6979 // Ensure that we don't interpret the next token as an identifier when
6980 // dealing with declarations in an Objective-C container.
6981 D.SetIdentifier(nullptr, Tok.getLocation());
6982 D.setInvalidType(true);
6983 ConsumeToken();
6984 goto PastIdentifier;
6985 }
6986 }
6987
6988 // C++0x [dcl.fct]p14:
6989 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
6990 // parameter-declaration-clause without a preceding comma. In this case,
6991 // the ellipsis is parsed as part of the abstract-declarator if the type
6992 // of the parameter either names a template parameter pack that has not
6993 // been expanded or contains auto; otherwise, it is parsed as part of the
6994 // parameter-declaration-clause.
6995 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
6996 !((D.getContext() == DeclaratorContext::Prototype ||
6997 D.getContext() == DeclaratorContext::LambdaExprParameter ||
6998 D.getContext() == DeclaratorContext::BlockLiteral) &&
6999 NextToken().is(tok::r_paren) && !D.hasGroupingParens() &&
7001 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
7002 SourceLocation EllipsisLoc = ConsumeToken();
7003 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
7004 // The ellipsis was put in the wrong place. Recover, and explain to
7005 // the user what they should have done.
7006 ParseDeclarator(D);
7007 if (EllipsisLoc.isValid())
7008 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
7009 return;
7010 } else
7011 D.setEllipsisLoc(EllipsisLoc);
7012
7013 // The ellipsis can't be followed by a parenthesized declarator. We
7014 // check for that in ParseParenDeclarator, after we have disambiguated
7015 // the l_paren token.
7016 }
7017
7018 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
7019 tok::tilde)) {
7020 // We found something that indicates the start of an unqualified-id.
7021 // Parse that unqualified-id.
7022 bool AllowConstructorName;
7023 bool AllowDeductionGuide;
7024 if (D.getDeclSpec().hasTypeSpecifier()) {
7025 AllowConstructorName = false;
7026 AllowDeductionGuide = false;
7027 } else if (D.getCXXScopeSpec().isSet()) {
7028 AllowConstructorName = (D.getContext() == DeclaratorContext::File ||
7029 D.getContext() == DeclaratorContext::Member);
7030 AllowDeductionGuide = false;
7031 } else {
7032 AllowConstructorName = (D.getContext() == DeclaratorContext::Member);
7033 AllowDeductionGuide = (D.getContext() == DeclaratorContext::File ||
7034 D.getContext() == DeclaratorContext::Member);
7035 }
7036
7037 bool HadScope = D.getCXXScopeSpec().isValid();
7038 SourceLocation TemplateKWLoc;
7039 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
7040 /*ObjectType=*/nullptr,
7041 /*ObjectHadErrors=*/false,
7042 /*EnteringContext=*/true,
7043 /*AllowDestructorName=*/true, AllowConstructorName,
7044 AllowDeductionGuide, &TemplateKWLoc,
7045 D.getName()) ||
7046 // Once we're past the identifier, if the scope was bad, mark the
7047 // whole declarator bad.
7048 D.getCXXScopeSpec().isInvalid()) {
7049 D.SetIdentifier(nullptr, Tok.getLocation());
7050 D.setInvalidType(true);
7051 } else {
7052 // ParseUnqualifiedId might have parsed a scope specifier during error
7053 // recovery. If it did so, enter that scope.
7054 if (!HadScope && D.getCXXScopeSpec().isValid() &&
7056 D.getCXXScopeSpec()))
7057 DeclScopeObj.EnterDeclaratorScope();
7058
7059 // Parsed the unqualified-id; update range information and move along.
7061 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
7062 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
7063 }
7064 goto PastIdentifier;
7065 }
7066
7067 if (D.getCXXScopeSpec().isNotEmpty()) {
7068 // We have a scope specifier but no following unqualified-id.
7069 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
7070 diag::err_expected_unqualified_id)
7071 << /*C++*/1;
7072 D.SetIdentifier(nullptr, Tok.getLocation());
7073 goto PastIdentifier;
7074 }
7075 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
7076 assert(!getLangOpts().CPlusPlus &&
7077 "There's a C++-specific check for tok::identifier above");
7078 assert(Tok.getIdentifierInfo() && "Not an identifier?");
7079 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
7080 D.SetRangeEnd(Tok.getLocation());
7081 ConsumeToken();
7082 goto PastIdentifier;
7083 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
7084 // We're not allowed an identifier here, but we got one. Try to figure out
7085 // if the user was trying to attach a name to the type, or whether the name
7086 // is some unrelated trailing syntax.
7087 bool DiagnoseIdentifier = false;
7088 if (D.hasGroupingParens())
7089 // An identifier within parens is unlikely to be intended to be anything
7090 // other than a name being "declared".
7091 DiagnoseIdentifier = true;
7092 else if (D.getContext() == DeclaratorContext::TemplateArg)
7093 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
7094 DiagnoseIdentifier =
7095 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
7096 else if (D.getContext() == DeclaratorContext::AliasDecl ||
7097 D.getContext() == DeclaratorContext::AliasTemplate)
7098 // The most likely error is that the ';' was forgotten.
7099 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
7100 else if ((D.getContext() == DeclaratorContext::TrailingReturn ||
7101 D.getContext() == DeclaratorContext::TrailingReturnVar) &&
7102 !isCXX11VirtSpecifier(Tok))
7103 DiagnoseIdentifier = NextToken().isOneOf(
7104 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
7105 if (DiagnoseIdentifier) {
7106 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
7108 D.SetIdentifier(nullptr, Tok.getLocation());
7109 ConsumeToken();
7110 goto PastIdentifier;
7111 }
7112 }
7113
7114 if (Tok.is(tok::l_paren)) {
7115 // If this might be an abstract-declarator followed by a direct-initializer,
7116 // check whether this is a valid declarator chunk. If it can't be, assume
7117 // that it's an initializer instead.
7118 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
7119 RevertingTentativeParsingAction PA(*this);
7120 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true,
7121 D.getDeclSpec().getTypeSpecType() == TST_auto) ==
7122 TPResult::False) {
7123 D.SetIdentifier(nullptr, Tok.getLocation());
7124 goto PastIdentifier;
7125 }
7126 }
7127
7128 // direct-declarator: '(' declarator ')'
7129 // direct-declarator: '(' attributes declarator ')'
7130 // Example: 'char (*X)' or 'int (*XX)(void)'
7131 ParseParenDeclarator(D);
7132
7133 // If the declarator was parenthesized, we entered the declarator
7134 // scope when parsing the parenthesized declarator, then exited
7135 // the scope already. Re-enter the scope, if we need to.
7136 if (D.getCXXScopeSpec().isSet()) {
7137 // If there was an error parsing parenthesized declarator, declarator
7138 // scope may have been entered before. Don't do it again.
7139 if (!D.isInvalidType() &&
7141 D.getCXXScopeSpec()))
7142 // Change the declaration context for name lookup, until this function
7143 // is exited (and the declarator has been parsed).
7144 DeclScopeObj.EnterDeclaratorScope();
7145 }
7146 } else if (D.mayOmitIdentifier()) {
7147 // This could be something simple like "int" (in which case the declarator
7148 // portion is empty), if an abstract-declarator is allowed.
7149 D.SetIdentifier(nullptr, Tok.getLocation());
7150
7151 // The grammar for abstract-pack-declarator does not allow grouping parens.
7152 // FIXME: Revisit this once core issue 1488 is resolved.
7153 if (D.hasEllipsis() && D.hasGroupingParens())
7154 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
7155 diag::ext_abstract_pack_declarator_parens);
7156 } else {
7157 if (Tok.getKind() == tok::annot_pragma_parser_crash)
7158 LLVM_BUILTIN_TRAP;
7159 if (Tok.is(tok::l_square))
7160 return ParseMisplacedBracketDeclarator(D);
7161 if (D.getContext() == DeclaratorContext::Member) {
7162 // Objective-C++: Detect C++ keywords and try to prevent further errors by
7163 // treating these keyword as valid member names.
7165 !Tok.isAnnotation() && Tok.getIdentifierInfo() &&
7168 diag::err_expected_member_name_or_semi_objcxx_keyword)
7169 << Tok.getIdentifierInfo()
7170 << (D.getDeclSpec().isEmpty() ? SourceRange()
7171 : D.getDeclSpec().getSourceRange());
7172 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
7173 D.SetRangeEnd(Tok.getLocation());
7174 ConsumeToken();
7175 goto PastIdentifier;
7176 }
7178 diag::err_expected_member_name_or_semi)
7179 << (D.getDeclSpec().isEmpty() ? SourceRange()
7180 : D.getDeclSpec().getSourceRange());
7181 } else {
7182 if (Tok.getKind() == tok::TokenKind::kw_while) {
7183 Diag(Tok, diag::err_while_loop_outside_of_a_function);
7184 } else if (getLangOpts().CPlusPlus) {
7185 if (Tok.isOneOf(tok::period, tok::arrow))
7186 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
7187 else {
7188 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
7189 if (Tok.isAtStartOfLine() && Loc.isValid())
7190 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
7191 << getLangOpts().CPlusPlus;
7192 else
7194 diag::err_expected_unqualified_id)
7195 << getLangOpts().CPlusPlus;
7196 }
7197 } else {
7199 diag::err_expected_either)
7200 << tok::identifier << tok::l_paren;
7201 }
7202 }
7203 D.SetIdentifier(nullptr, Tok.getLocation());
7204 D.setInvalidType(true);
7205 }
7206
7207 PastIdentifier:
7208 assert(D.isPastIdentifier() &&
7209 "Haven't past the location of the identifier yet?");
7210
7211 // Don't parse attributes unless we have parsed an unparenthesized name.
7212 if (D.hasName() && !D.getNumTypeObjects())
7213 MaybeParseCXX11Attributes(D);
7214
7215 while (true) {
7216 if (Tok.is(tok::l_paren)) {
7217 bool IsFunctionDeclaration = D.isFunctionDeclaratorAFunctionDeclaration();
7218 // Enter function-declaration scope, limiting any declarators to the
7219 // function prototype scope, including parameter declarators.
7220 ParseScope PrototypeScope(this,
7222 (IsFunctionDeclaration
7224
7225 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
7226 // In such a case, check if we actually have a function declarator; if it
7227 // is not, the declarator has been fully parsed.
7228 bool IsAmbiguous = false;
7229 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
7230 // C++2a [temp.res]p5
7231 // A qualified-id is assumed to name a type if
7232 // - [...]
7233 // - it is a decl-specifier of the decl-specifier-seq of a
7234 // - [...]
7235 // - parameter-declaration in a member-declaration [...]
7236 // - parameter-declaration in a declarator of a function or function
7237 // template declaration whose declarator-id is qualified [...]
7238 auto AllowImplicitTypename = ImplicitTypenameContext::No;
7239 if (D.getCXXScopeSpec().isSet())
7240 AllowImplicitTypename =
7242 else if (D.getContext() == DeclaratorContext::Member) {
7243 AllowImplicitTypename = ImplicitTypenameContext::Yes;
7244 }
7245
7246 // The name of the declarator, if any, is tentatively declared within
7247 // a possible direct initializer.
7248 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
7249 bool IsFunctionDecl =
7250 isCXXFunctionDeclarator(&IsAmbiguous, AllowImplicitTypename);
7251 TentativelyDeclaredIdentifiers.pop_back();
7252 if (!IsFunctionDecl)
7253 break;
7254 }
7255 ParsedAttributes attrs(AttrFactory);
7256 BalancedDelimiterTracker T(*this, tok::l_paren);
7257 T.consumeOpen();
7258 if (IsFunctionDeclaration)
7260 TemplateParameterDepth);
7261 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
7262 if (IsFunctionDeclaration)
7264 PrototypeScope.Exit();
7265 } else if (Tok.is(tok::l_square)) {
7266 ParseBracketDeclarator(D);
7267 } else if (Tok.isRegularKeywordAttribute()) {
7268 // For consistency with attribute parsing.
7269 Diag(Tok, diag::err_keyword_not_allowed) << Tok.getIdentifierInfo();
7270 bool TakesArgs = doesKeywordAttributeTakeArgs(Tok.getKind());
7271 ConsumeToken();
7272 if (TakesArgs) {
7273 BalancedDelimiterTracker T(*this, tok::l_paren);
7274 if (!T.consumeOpen())
7275 T.skipToEnd();
7276 }
7277 } else if (Tok.is(tok::kw_requires) && D.hasGroupingParens()) {
7278 // This declarator is declaring a function, but the requires clause is
7279 // in the wrong place:
7280 // void (f() requires true);
7281 // instead of
7282 // void f() requires true;
7283 // or
7284 // void (f()) requires true;
7285 Diag(Tok, diag::err_requires_clause_inside_parens);
7286 ConsumeToken();
7287 ExprResult TrailingRequiresClause = Actions.CorrectDelayedTyposInExpr(
7288 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
7289 if (TrailingRequiresClause.isUsable() && D.isFunctionDeclarator() &&
7290 !D.hasTrailingRequiresClause())
7291 // We're already ill-formed if we got here but we'll accept it anyway.
7292 D.setTrailingRequiresClause(TrailingRequiresClause.get());
7293 } else {
7294 break;
7295 }
7296 }
7297}
7298
7299void Parser::ParseDecompositionDeclarator(Declarator &D) {
7300 assert(Tok.is(tok::l_square));
7301
7302 TentativeParsingAction PA(*this);
7303 BalancedDelimiterTracker T(*this, tok::l_square);
7304 T.consumeOpen();
7305
7306 if (isCXX11AttributeSpecifier())
7307 DiagnoseAndSkipCXX11Attributes();
7308
7309 // If this doesn't look like a structured binding, maybe it's a misplaced
7310 // array declarator.
7311 if (!(Tok.is(tok::identifier) &&
7312 NextToken().isOneOf(tok::comma, tok::r_square, tok::kw_alignas,
7313 tok::l_square)) &&
7314 !(Tok.is(tok::r_square) &&
7315 NextToken().isOneOf(tok::equal, tok::l_brace))) {
7316 PA.Revert();
7317 return ParseMisplacedBracketDeclarator(D);
7318 }
7319
7321 while (Tok.isNot(tok::r_square)) {
7322 if (!Bindings.empty()) {
7323 if (Tok.is(tok::comma))
7324 ConsumeToken();
7325 else {
7326 if (Tok.is(tok::identifier)) {
7328 Diag(EndLoc, diag::err_expected)
7329 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
7330 } else {
7331 Diag(Tok, diag::err_expected_comma_or_rsquare);
7332 }
7333
7334 SkipUntil(tok::r_square, tok::comma, tok::identifier,
7336 if (Tok.is(tok::comma))
7337 ConsumeToken();
7338 else if (Tok.isNot(tok::identifier))
7339 break;
7340 }
7341 }
7342
7343 if (isCXX11AttributeSpecifier())
7344 DiagnoseAndSkipCXX11Attributes();
7345
7346 if (Tok.isNot(tok::identifier)) {
7347 Diag(Tok, diag::err_expected) << tok::identifier;
7348 break;
7349 }
7350
7353 ConsumeToken();
7354
7355 ParsedAttributes Attrs(AttrFactory);
7356 if (isCXX11AttributeSpecifier()) {
7358 ? diag::warn_cxx23_compat_decl_attrs_on_binding
7359 : diag::ext_decl_attrs_on_binding);
7360 MaybeParseCXX11Attributes(Attrs);
7361 }
7362
7363 Bindings.push_back({II, Loc, std::move(Attrs)});
7364 }
7365
7366 if (Tok.isNot(tok::r_square))
7367 // We've already diagnosed a problem here.
7368 T.skipToEnd();
7369 else {
7370 // C++17 does not allow the identifier-list in a structured binding
7371 // to be empty.
7372 if (Bindings.empty())
7373 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
7374
7375 T.consumeClose();
7376 }
7377
7378 PA.Commit();
7379
7380 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
7381 T.getCloseLocation());
7382}
7383
7384/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
7385/// only called before the identifier, so these are most likely just grouping
7386/// parens for precedence. If we find that these are actually function
7387/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
7388///
7389/// direct-declarator:
7390/// '(' declarator ')'
7391/// [GNU] '(' attributes declarator ')'
7392/// direct-declarator '(' parameter-type-list ')'
7393/// direct-declarator '(' identifier-list[opt] ')'
7394/// [GNU] direct-declarator '(' parameter-forward-declarations
7395/// parameter-type-list[opt] ')'
7396///
7397void Parser::ParseParenDeclarator(Declarator &D) {
7398 BalancedDelimiterTracker T(*this, tok::l_paren);
7399 T.consumeOpen();
7400
7401 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
7402
7403 // Eat any attributes before we look at whether this is a grouping or function
7404 // declarator paren. If this is a grouping paren, the attribute applies to
7405 // the type being built up, for example:
7406 // int (__attribute__(()) *x)(long y)
7407 // If this ends up not being a grouping paren, the attribute applies to the
7408 // first argument, for example:
7409 // int (__attribute__(()) int x)
7410 // In either case, we need to eat any attributes to be able to determine what
7411 // sort of paren this is.
7412 //
7413 ParsedAttributes attrs(AttrFactory);
7414 bool RequiresArg = false;
7415 if (Tok.is(tok::kw___attribute)) {
7416 ParseGNUAttributes(attrs);
7417
7418 // We require that the argument list (if this is a non-grouping paren) be
7419 // present even if the attribute list was empty.
7420 RequiresArg = true;
7421 }
7422
7423 // Eat any Microsoft extensions.
7424 ParseMicrosoftTypeAttributes(attrs);
7425
7426 // Eat any Borland extensions.
7427 if (Tok.is(tok::kw___pascal))
7428 ParseBorlandTypeAttributes(attrs);
7429
7430 // If we haven't past the identifier yet (or where the identifier would be
7431 // stored, if this is an abstract declarator), then this is probably just
7432 // grouping parens. However, if this could be an abstract-declarator, then
7433 // this could also be the start of function arguments (consider 'void()').
7434 bool isGrouping;
7435
7436 if (!D.mayOmitIdentifier()) {
7437 // If this can't be an abstract-declarator, this *must* be a grouping
7438 // paren, because we haven't seen the identifier yet.
7439 isGrouping = true;
7440 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
7441 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
7442 NextToken().is(tok::r_paren)) || // C++ int(...)
7443 isDeclarationSpecifier(
7444 ImplicitTypenameContext::No) || // 'int(int)' is a function.
7445 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
7446 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
7447 // considered to be a type, not a K&R identifier-list.
7448 isGrouping = false;
7449 } else {
7450 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
7451 isGrouping = true;
7452 }
7453
7454 // If this is a grouping paren, handle:
7455 // direct-declarator: '(' declarator ')'
7456 // direct-declarator: '(' attributes declarator ')'
7457 if (isGrouping) {
7458 SourceLocation EllipsisLoc = D.getEllipsisLoc();
7459 D.setEllipsisLoc(SourceLocation());
7460
7461 bool hadGroupingParens = D.hasGroupingParens();
7462 D.setGroupingParens(true);
7463 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
7464 // Match the ')'.
7465 T.consumeClose();
7466 D.AddTypeInfo(
7467 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
7468 std::move(attrs), T.getCloseLocation());
7469
7470 D.setGroupingParens(hadGroupingParens);
7471
7472 // An ellipsis cannot be placed outside parentheses.
7473 if (EllipsisLoc.isValid())
7474 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
7475
7476 return;
7477 }
7478
7479 // Okay, if this wasn't a grouping paren, it must be the start of a function
7480 // argument list. Recognize that this declarator will never have an
7481 // identifier (and remember where it would have been), then call into
7482 // ParseFunctionDeclarator to handle of argument list.
7483 D.SetIdentifier(nullptr, Tok.getLocation());
7484
7485 // Enter function-declaration scope, limiting any declarators to the
7486 // function prototype scope, including parameter declarators.
7487 ParseScope PrototypeScope(this,
7489 (D.isFunctionDeclaratorAFunctionDeclaration()
7491 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
7492 PrototypeScope.Exit();
7493}
7494
7495void Parser::InitCXXThisScopeForDeclaratorIfRelevant(
7496 const Declarator &D, const DeclSpec &DS,
7497 std::optional<Sema::CXXThisScopeRAII> &ThisScope) {
7498 // C++11 [expr.prim.general]p3:
7499 // If a declaration declares a member function or member function
7500 // template of a class X, the expression this is a prvalue of type
7501 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
7502 // and the end of the function-definition, member-declarator, or
7503 // declarator.
7504 // FIXME: currently, "static" case isn't handled correctly.
7505 bool IsCXX11MemberFunction =
7506 getLangOpts().CPlusPlus11 &&
7507 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7508 (D.getContext() == DeclaratorContext::Member
7509 ? !D.getDeclSpec().isFriendSpecified()
7510 : D.getContext() == DeclaratorContext::File &&
7511 D.getCXXScopeSpec().isValid() &&
7512 Actions.CurContext->isRecord());
7513 if (!IsCXX11MemberFunction)
7514 return;
7515
7517 if (D.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14)
7518 Q.addConst();
7519 // FIXME: Collect C++ address spaces.
7520 // If there are multiple different address spaces, the source is invalid.
7521 // Carry on using the first addr space for the qualifiers of 'this'.
7522 // The diagnostic will be given later while creating the function
7523 // prototype for the method.
7524 if (getLangOpts().OpenCLCPlusPlus) {
7525 for (ParsedAttr &attr : DS.getAttributes()) {
7526 LangAS ASIdx = attr.asOpenCLLangAS();
7527 if (ASIdx != LangAS::Default) {
7528 Q.addAddressSpace(ASIdx);
7529 break;
7530 }
7531 }
7532 }
7533 ThisScope.emplace(Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
7534 IsCXX11MemberFunction);
7535}
7536
7537/// ParseFunctionDeclarator - We are after the identifier and have parsed the
7538/// declarator D up to a paren, which indicates that we are parsing function
7539/// arguments.
7540///
7541/// If FirstArgAttrs is non-null, then the caller parsed those attributes
7542/// immediately after the open paren - they will be applied to the DeclSpec
7543/// of the first parameter.
7544///
7545/// If RequiresArg is true, then the first argument of the function is required
7546/// to be present and required to not be an identifier list.
7547///
7548/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
7549/// (C++11) ref-qualifier[opt], exception-specification[opt],
7550/// (C++11) attribute-specifier-seq[opt], (C++11) trailing-return-type[opt] and
7551/// (C++2a) the trailing requires-clause.
7552///
7553/// [C++11] exception-specification:
7554/// dynamic-exception-specification
7555/// noexcept-specification
7556///
7557void Parser::ParseFunctionDeclarator(Declarator &D,
7558 ParsedAttributes &FirstArgAttrs,
7559 BalancedDelimiterTracker &Tracker,
7560 bool IsAmbiguous,
7561 bool RequiresArg) {
7562 assert(getCurScope()->isFunctionPrototypeScope() &&
7563 "Should call from a Function scope");
7564 // lparen is already consumed!
7565 assert(D.isPastIdentifier() && "Should not call before identifier!");
7566
7567 // This should be true when the function has typed arguments.
7568 // Otherwise, it is treated as a K&R-style function.
7569 bool HasProto = false;
7570 // Build up an array of information about the parsed arguments.
7572 // Remember where we see an ellipsis, if any.
7573 SourceLocation EllipsisLoc;
7574
7575 DeclSpec DS(AttrFactory);
7576 bool RefQualifierIsLValueRef = true;
7577 SourceLocation RefQualifierLoc;
7579 SourceRange ESpecRange;
7580 SmallVector<ParsedType, 2> DynamicExceptions;
7581 SmallVector<SourceRange, 2> DynamicExceptionRanges;
7582 ExprResult NoexceptExpr;
7583 CachedTokens *ExceptionSpecTokens = nullptr;
7584 ParsedAttributes FnAttrs(AttrFactory);
7585 TypeResult TrailingReturnType;
7586 SourceLocation TrailingReturnTypeLoc;
7587
7588 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
7589 EndLoc is the end location for the function declarator.
7590 They differ for trailing return types. */
7591 SourceLocation StartLoc, LocalEndLoc, EndLoc;
7592 SourceLocation LParenLoc, RParenLoc;
7593 LParenLoc = Tracker.getOpenLocation();
7594 StartLoc = LParenLoc;
7595
7596 if (isFunctionDeclaratorIdentifierList()) {
7597 if (RequiresArg)
7598 Diag(Tok, diag::err_argument_required_after_attribute);
7599
7600 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
7601
7602 Tracker.consumeClose();
7603 RParenLoc = Tracker.getCloseLocation();
7604 LocalEndLoc = RParenLoc;
7605 EndLoc = RParenLoc;
7606
7607 // If there are attributes following the identifier list, parse them and
7608 // prohibit them.
7609 MaybeParseCXX11Attributes(FnAttrs);
7610 ProhibitAttributes(FnAttrs);
7611 } else {
7612 if (Tok.isNot(tok::r_paren))
7613 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc);
7614 else if (RequiresArg)
7615 Diag(Tok, diag::err_argument_required_after_attribute);
7616
7617 // OpenCL disallows functions without a prototype, but it doesn't enforce
7618 // strict prototypes as in C23 because it allows a function definition to
7619 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
7620 HasProto = ParamInfo.size() || getLangOpts().requiresStrictPrototypes() ||
7621 getLangOpts().OpenCL;
7622
7623 // If we have the closing ')', eat it.
7624 Tracker.consumeClose();
7625 RParenLoc = Tracker.getCloseLocation();
7626 LocalEndLoc = RParenLoc;
7627 EndLoc = RParenLoc;
7628
7629 if (getLangOpts().CPlusPlus) {
7630 // FIXME: Accept these components in any order, and produce fixits to
7631 // correct the order if the user gets it wrong. Ideally we should deal
7632 // with the pure-specifier in the same way.
7633
7634 // Parse cv-qualifier-seq[opt].
7635 ParseTypeQualifierListOpt(
7636 DS, AR_NoAttributesParsed,
7637 /*AtomicAllowed*/ false,
7638 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
7639 Actions.CodeCompletion().CodeCompleteFunctionQualifiers(DS, D);
7640 }));
7641 if (!DS.getSourceRange().getEnd().isInvalid()) {
7642 EndLoc = DS.getSourceRange().getEnd();
7643 }
7644
7645 // Parse ref-qualifier[opt].
7646 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
7647 EndLoc = RefQualifierLoc;
7648
7649 std::optional<Sema::CXXThisScopeRAII> ThisScope;
7650 InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope);
7651
7652 // C++ [class.mem.general]p8:
7653 // A complete-class context of a class (template) is a
7654 // - function body,
7655 // - default argument,
7656 // - default template argument,
7657 // - noexcept-specifier, or
7658 // - default member initializer
7659 // within the member-specification of the class or class template.
7660 //
7661 // Parse exception-specification[opt]. If we are in the
7662 // member-specification of a class or class template, this is a
7663 // complete-class context and parsing of the noexcept-specifier should be
7664 // delayed (even if this is a friend declaration).
7665 bool Delayed = D.getContext() == DeclaratorContext::Member &&
7666 D.isFunctionDeclaratorAFunctionDeclaration();
7667 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
7668 GetLookAheadToken(0).is(tok::kw_noexcept) &&
7669 GetLookAheadToken(1).is(tok::l_paren) &&
7670 GetLookAheadToken(2).is(tok::kw_noexcept) &&
7671 GetLookAheadToken(3).is(tok::l_paren) &&
7672 GetLookAheadToken(4).is(tok::identifier) &&
7673 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
7674 // HACK: We've got an exception-specification
7675 // noexcept(noexcept(swap(...)))
7676 // or
7677 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
7678 // on a 'swap' member function. This is a libstdc++ bug; the lookup
7679 // for 'swap' will only find the function we're currently declaring,
7680 // whereas it expects to find a non-member swap through ADL. Turn off
7681 // delayed parsing to give it a chance to find what it expects.
7682 Delayed = false;
7683 }
7684 ESpecType = tryParseExceptionSpecification(Delayed,
7685 ESpecRange,
7686 DynamicExceptions,
7687 DynamicExceptionRanges,
7688 NoexceptExpr,
7689 ExceptionSpecTokens);
7690 if (ESpecType != EST_None)
7691 EndLoc = ESpecRange.getEnd();
7692
7693 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
7694 // after the exception-specification.
7695 MaybeParseCXX11Attributes(FnAttrs);
7696
7697 // Parse trailing-return-type[opt].
7698 LocalEndLoc = EndLoc;
7699 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
7700 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
7701 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
7702 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
7703 LocalEndLoc = Tok.getLocation();
7705 TrailingReturnType =
7706 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
7707 TrailingReturnTypeLoc = Range.getBegin();
7708 EndLoc = Range.getEnd();
7709 }
7710 } else {
7711 MaybeParseCXX11Attributes(FnAttrs);
7712 }
7713 }
7714
7715 // Collect non-parameter declarations from the prototype if this is a function
7716 // declaration. They will be moved into the scope of the function. Only do
7717 // this in C and not C++, where the decls will continue to live in the
7718 // surrounding context.
7719 SmallVector<NamedDecl *, 0> DeclsInPrototype;
7720 if (getCurScope()->isFunctionDeclarationScope() && !getLangOpts().CPlusPlus) {
7721 for (Decl *D : getCurScope()->decls()) {
7722 NamedDecl *ND = dyn_cast<NamedDecl>(D);
7723 if (!ND || isa<ParmVarDecl>(ND))
7724 continue;
7725 DeclsInPrototype.push_back(ND);
7726 }
7727 // Sort DeclsInPrototype based on raw encoding of the source location.
7728 // Scope::decls() is iterating over a SmallPtrSet so sort the Decls before
7729 // moving to DeclContext. This provides a stable ordering for traversing
7730 // Decls in DeclContext, which is important for tasks like ASTWriter for
7731 // deterministic output.
7732 llvm::sort(DeclsInPrototype, [](Decl *D1, Decl *D2) {
7733 return D1->getLocation().getRawEncoding() <
7735 });
7736 }
7737
7738 // Remember that we parsed a function type, and remember the attributes.
7739 D.AddTypeInfo(DeclaratorChunk::getFunction(
7740 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
7741 ParamInfo.size(), EllipsisLoc, RParenLoc,
7742 RefQualifierIsLValueRef, RefQualifierLoc,
7743 /*MutableLoc=*/SourceLocation(),
7744 ESpecType, ESpecRange, DynamicExceptions.data(),
7745 DynamicExceptionRanges.data(), DynamicExceptions.size(),
7746 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
7747 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
7748 LocalEndLoc, D, TrailingReturnType, TrailingReturnTypeLoc,
7749 &DS),
7750 std::move(FnAttrs), EndLoc);
7751}
7752
7753/// ParseRefQualifier - Parses a member function ref-qualifier. Returns
7754/// true if a ref-qualifier is found.
7755bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
7756 SourceLocation &RefQualifierLoc) {
7757 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
7759 diag::warn_cxx98_compat_ref_qualifier :
7760 diag::ext_ref_qualifier);
7761
7762 RefQualifierIsLValueRef = Tok.is(tok::amp);
7763 RefQualifierLoc = ConsumeToken();
7764 return true;
7765 }
7766 return false;
7767}
7768
7769/// isFunctionDeclaratorIdentifierList - This parameter list may have an
7770/// identifier list form for a K&R-style function: void foo(a,b,c)
7771///
7772/// Note that identifier-lists are only allowed for normal declarators, not for
7773/// abstract-declarators.
7774bool Parser::isFunctionDeclaratorIdentifierList() {
7776 && Tok.is(tok::identifier)
7777 && !TryAltiVecVectorToken()
7778 // K&R identifier lists can't have typedefs as identifiers, per C99
7779 // 6.7.5.3p11.
7780 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
7781 // Identifier lists follow a really simple grammar: the identifiers can
7782 // be followed *only* by a ", identifier" or ")". However, K&R
7783 // identifier lists are really rare in the brave new modern world, and
7784 // it is very common for someone to typo a type in a non-K&R style
7785 // list. If we are presented with something like: "void foo(intptr x,
7786 // float y)", we don't want to start parsing the function declarator as
7787 // though it is a K&R style declarator just because intptr is an
7788 // invalid type.
7789 //
7790 // To handle this, we check to see if the token after the first
7791 // identifier is a "," or ")". Only then do we parse it as an
7792 // identifier list.
7793 && (!Tok.is(tok::eof) &&
7794 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
7795}
7796
7797/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
7798/// we found a K&R-style identifier list instead of a typed parameter list.
7799///
7800/// After returning, ParamInfo will hold the parsed parameters.
7801///
7802/// identifier-list: [C99 6.7.5]
7803/// identifier
7804/// identifier-list ',' identifier
7805///
7806void Parser::ParseFunctionDeclaratorIdentifierList(
7807 Declarator &D,
7809 // We should never reach this point in C23 or C++.
7810 assert(!getLangOpts().requiresStrictPrototypes() &&
7811 "Cannot parse an identifier list in C23 or C++");
7812
7813 // If there was no identifier specified for the declarator, either we are in
7814 // an abstract-declarator, or we are in a parameter declarator which was found
7815 // to be abstract. In abstract-declarators, identifier lists are not valid:
7816 // diagnose this.
7817 if (!D.getIdentifier())
7818 Diag(Tok, diag::ext_ident_list_in_param);
7819
7820 // Maintain an efficient lookup of params we have seen so far.
7821 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
7822
7823 do {
7824 // If this isn't an identifier, report the error and skip until ')'.
7825 if (Tok.isNot(tok::identifier)) {
7826 Diag(Tok, diag::err_expected) << tok::identifier;
7827 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
7828 // Forget we parsed anything.
7829 ParamInfo.clear();
7830 return;
7831 }
7832
7833 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
7834
7835 // Reject 'typedef int y; int test(x, y)', but continue parsing.
7836 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
7837 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
7838
7839 // Verify that the argument identifier has not already been mentioned.
7840 if (!ParamsSoFar.insert(ParmII).second) {
7841 Diag(Tok, diag::err_param_redefinition) << ParmII;
7842 } else {
7843 // Remember this identifier in ParamInfo.
7844 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
7845 Tok.getLocation(),
7846 nullptr));
7847 }
7848
7849 // Eat the identifier.
7850 ConsumeToken();
7851 // The list continues if we see a comma.
7852 } while (TryConsumeToken(tok::comma));
7853}
7854
7855/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
7856/// after the opening parenthesis. This function will not parse a K&R-style
7857/// identifier list.
7858///
7859/// DeclContext is the context of the declarator being parsed. If FirstArgAttrs
7860/// is non-null, then the caller parsed those attributes immediately after the
7861/// open paren - they will be applied to the DeclSpec of the first parameter.
7862///
7863/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
7864/// be the location of the ellipsis, if any was parsed.
7865///
7866/// parameter-type-list: [C99 6.7.5]
7867/// parameter-list
7868/// parameter-list ',' '...'
7869/// [C++] parameter-list '...'
7870///
7871/// parameter-list: [C99 6.7.5]
7872/// parameter-declaration
7873/// parameter-list ',' parameter-declaration
7874///
7875/// parameter-declaration: [C99 6.7.5]
7876/// declaration-specifiers declarator
7877/// [C++] declaration-specifiers declarator '=' assignment-expression
7878/// [C++11] initializer-clause
7879/// [GNU] declaration-specifiers declarator attributes
7880/// declaration-specifiers abstract-declarator[opt]
7881/// [C++] declaration-specifiers abstract-declarator[opt]
7882/// '=' assignment-expression
7883/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
7884/// [C++11] attribute-specifier-seq parameter-declaration
7885/// [C++2b] attribute-specifier-seq 'this' parameter-declaration
7886///
7887void Parser::ParseParameterDeclarationClause(
7888 DeclaratorContext DeclaratorCtx, ParsedAttributes &FirstArgAttrs,
7890 SourceLocation &EllipsisLoc, bool IsACXXFunctionDeclaration) {
7891
7892 // Avoid exceeding the maximum function scope depth.
7893 // See https://bugs.llvm.org/show_bug.cgi?id=19607
7894 // Note Sema::ActOnParamDeclarator calls ParmVarDecl::setScopeInfo with
7895 // getFunctionPrototypeDepth() - 1.
7896 if (getCurScope()->getFunctionPrototypeDepth() - 1 >
7898 Diag(Tok.getLocation(), diag::err_function_scope_depth_exceeded)
7900 cutOffParsing();
7901 return;
7902 }
7903
7904 // C++2a [temp.res]p5
7905 // A qualified-id is assumed to name a type if
7906 // - [...]
7907 // - it is a decl-specifier of the decl-specifier-seq of a
7908 // - [...]
7909 // - parameter-declaration in a member-declaration [...]
7910 // - parameter-declaration in a declarator of a function or function
7911 // template declaration whose declarator-id is qualified [...]
7912 // - parameter-declaration in a lambda-declarator [...]
7913 auto AllowImplicitTypename = ImplicitTypenameContext::No;
7914 if (DeclaratorCtx == DeclaratorContext::Member ||
7915 DeclaratorCtx == DeclaratorContext::LambdaExpr ||
7916 DeclaratorCtx == DeclaratorContext::RequiresExpr ||
7917 IsACXXFunctionDeclaration) {
7918 AllowImplicitTypename = ImplicitTypenameContext::Yes;
7919 }
7920
7921 do {
7922 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
7923 // before deciding this was a parameter-declaration-clause.
7924 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
7925 break;
7926
7927 // Parse the declaration-specifiers.
7928 // Just use the ParsingDeclaration "scope" of the declarator.
7929 DeclSpec DS(AttrFactory);
7930
7931 ParsedAttributes ArgDeclAttrs(AttrFactory);
7932 ParsedAttributes ArgDeclSpecAttrs(AttrFactory);
7933
7934 if (FirstArgAttrs.Range.isValid()) {
7935 // If the caller parsed attributes for the first argument, add them now.
7936 // Take them so that we only apply the attributes to the first parameter.
7937 // We have already started parsing the decl-specifier sequence, so don't
7938 // parse any parameter-declaration pieces that precede it.
7939 ArgDeclSpecAttrs.takeAllFrom(FirstArgAttrs);
7940 } else {
7941 // Parse any C++11 attributes.
7942 MaybeParseCXX11Attributes(ArgDeclAttrs);
7943
7944 // Skip any Microsoft attributes before a param.
7945 MaybeParseMicrosoftAttributes(ArgDeclSpecAttrs);
7946 }
7947
7948 SourceLocation DSStart = Tok.getLocation();
7949
7950 // Parse a C++23 Explicit Object Parameter
7951 // We do that in all language modes to produce a better diagnostic.
7952 SourceLocation ThisLoc;
7953 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_this))
7954 ThisLoc = ConsumeToken();
7955
7956 ParsedTemplateInfo TemplateInfo;
7957 ParseDeclarationSpecifiers(DS, TemplateInfo, AS_none,
7958 DeclSpecContext::DSC_normal,
7959 /*LateAttrs=*/nullptr, AllowImplicitTypename);
7960
7961 DS.takeAttributesFrom(ArgDeclSpecAttrs);
7962
7963 // Parse the declarator. This is "PrototypeContext" or
7964 // "LambdaExprParameterContext", because we must accept either
7965 // 'declarator' or 'abstract-declarator' here.
7966 Declarator ParmDeclarator(DS, ArgDeclAttrs,
7967 DeclaratorCtx == DeclaratorContext::RequiresExpr
7969 : DeclaratorCtx == DeclaratorContext::LambdaExpr
7972 ParseDeclarator(ParmDeclarator);
7973
7974 if (ThisLoc.isValid())
7975 ParmDeclarator.SetRangeBegin(ThisLoc);
7976
7977 // Parse GNU attributes, if present.
7978 MaybeParseGNUAttributes(ParmDeclarator);
7979 if (getLangOpts().HLSL)
7980 MaybeParseHLSLAnnotations(DS.getAttributes());
7981
7982 if (Tok.is(tok::kw_requires)) {
7983 // User tried to define a requires clause in a parameter declaration,
7984 // which is surely not a function declaration.
7985 // void f(int (*g)(int, int) requires true);
7986 Diag(Tok,
7987 diag::err_requires_clause_on_declarator_not_declaring_a_function);
7988 ConsumeToken();
7990 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
7991 }
7992
7993 // Remember this parsed parameter in ParamInfo.
7994 const IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
7995
7996 // DefArgToks is used when the parsing of default arguments needs
7997 // to be delayed.
7998 std::unique_ptr<CachedTokens> DefArgToks;
7999
8000 // If no parameter was specified, verify that *something* was specified,
8001 // otherwise we have a missing type and identifier.
8002 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
8003 ParmDeclarator.getNumTypeObjects() == 0) {
8004 // Completely missing, emit error.
8005 Diag(DSStart, diag::err_missing_param);
8006 } else {
8007 // Otherwise, we have something. Add it and let semantic analysis try
8008 // to grok it and add the result to the ParamInfo we are building.
8009
8010 // Last chance to recover from a misplaced ellipsis in an attempted
8011 // parameter pack declaration.
8012 if (Tok.is(tok::ellipsis) &&
8013 (NextToken().isNot(tok::r_paren) ||
8014 (!ParmDeclarator.getEllipsisLoc().isValid() &&
8016 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
8017 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
8018
8019 // Now we are at the point where declarator parsing is finished.
8020 //
8021 // Try to catch keywords in place of the identifier in a declarator, and
8022 // in particular the common case where:
8023 // 1 identifier comes at the end of the declarator
8024 // 2 if the identifier is dropped, the declarator is valid but anonymous
8025 // (no identifier)
8026 // 3 declarator parsing succeeds, and then we have a trailing keyword,
8027 // which is never valid in a param list (e.g. missing a ',')
8028 // And we can't handle this in ParseDeclarator because in general keywords
8029 // may be allowed to follow the declarator. (And in some cases there'd be
8030 // better recovery like inserting punctuation). ParseDeclarator is just
8031 // treating this as an anonymous parameter, and fortunately at this point
8032 // we've already almost done that.
8033 //
8034 // We care about case 1) where the declarator type should be known, and
8035 // the identifier should be null.
8036 if (!ParmDeclarator.isInvalidType() && !ParmDeclarator.hasName() &&
8037 Tok.isNot(tok::raw_identifier) && !Tok.isAnnotation() &&
8038 Tok.getIdentifierInfo() &&
8040 Diag(Tok, diag::err_keyword_as_parameter) << PP.getSpelling(Tok);
8041 // Consume the keyword.
8042 ConsumeToken();
8043 }
8044
8045 // We can only store so many parameters
8046 // Skip until the the end of the parameter list, ignoring
8047 // parameters that would overflow.
8048 if (ParamInfo.size() == Type::FunctionTypeNumParamsLimit) {
8049 Diag(ParmDeclarator.getBeginLoc(),
8050 diag::err_function_parameter_limit_exceeded);
8052 break;
8053 }
8054
8055 // Inform the actions module about the parameter declarator, so it gets
8056 // added to the current scope.
8057 Decl *Param =
8058 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator, ThisLoc);
8059 // Parse the default argument, if any. We parse the default
8060 // arguments in all dialects; the semantic analysis in
8061 // ActOnParamDefaultArgument will reject the default argument in
8062 // C.
8063 if (Tok.is(tok::equal)) {
8064 SourceLocation EqualLoc = Tok.getLocation();
8065
8066 // Parse the default argument
8067 if (DeclaratorCtx == DeclaratorContext::Member) {
8068 // If we're inside a class definition, cache the tokens
8069 // corresponding to the default argument. We'll actually parse
8070 // them when we see the end of the class definition.
8071 DefArgToks.reset(new CachedTokens);
8072
8073 SourceLocation ArgStartLoc = NextToken().getLocation();
8074 ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument);
8075 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
8076 ArgStartLoc);
8077 } else {
8078 // Consume the '='.
8079 ConsumeToken();
8080
8081 // The argument isn't actually potentially evaluated unless it is
8082 // used.
8084 Actions,
8086 Param);
8087
8088 ExprResult DefArgResult;
8089 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
8090 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
8091 DefArgResult = ParseBraceInitializer();
8092 } else {
8093 if (Tok.is(tok::l_paren) && NextToken().is(tok::l_brace)) {
8094 Diag(Tok, diag::err_stmt_expr_in_default_arg) << 0;
8095 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
8096 /*DefaultArg=*/nullptr);
8097 // Skip the statement expression and continue parsing
8098 SkipUntil(tok::comma, StopBeforeMatch);
8099 continue;
8100 }
8101 DefArgResult = ParseAssignmentExpression();
8102 }
8103 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
8104 if (DefArgResult.isInvalid()) {
8105 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
8106 /*DefaultArg=*/nullptr);
8107 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
8108 } else {
8109 // Inform the actions module about the default argument
8110 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
8111 DefArgResult.get());
8112 }
8113 }
8114 }
8115
8116 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
8117 ParmDeclarator.getIdentifierLoc(),
8118 Param, std::move(DefArgToks)));
8119 }
8120
8121 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
8122 if (getLangOpts().CPlusPlus26) {
8123 // C++26 [dcl.dcl.fct]p3:
8124 // A parameter-declaration-clause of the form
8125 // parameter-list '...' is deprecated.
8126 Diag(EllipsisLoc, diag::warn_deprecated_missing_comma_before_ellipsis)
8127 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
8128 }
8129
8130 if (!getLangOpts().CPlusPlus) {
8131 // We have ellipsis without a preceding ',', which is ill-formed
8132 // in C. Complain and provide the fix.
8133 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
8134 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
8135 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
8136 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
8137 // It looks like this was supposed to be a parameter pack. Warn and
8138 // point out where the ellipsis should have gone.
8139 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
8140 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
8141 << ParmEllipsis.isValid() << ParmEllipsis;
8142 if (ParmEllipsis.isValid()) {
8143 Diag(ParmEllipsis,
8144 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
8145 } else {
8146 Diag(ParmDeclarator.getIdentifierLoc(),
8147 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
8148 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
8149 "...")
8150 << !ParmDeclarator.hasName();
8151 }
8152 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
8153 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
8154 }
8155
8156 // We can't have any more parameters after an ellipsis.
8157 break;
8158 }
8159
8160 // If the next token is a comma, consume it and keep reading arguments.
8161 } while (TryConsumeToken(tok::comma));
8162}
8163
8164/// [C90] direct-declarator '[' constant-expression[opt] ']'
8165/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
8166/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
8167/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
8168/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
8169/// [C++11] direct-declarator '[' constant-expression[opt] ']'
8170/// attribute-specifier-seq[opt]
8171void Parser::ParseBracketDeclarator(Declarator &D) {
8172 if (CheckProhibitedCXX11Attribute())
8173 return;
8174
8175 BalancedDelimiterTracker T(*this, tok::l_square);
8176 T.consumeOpen();
8177
8178 // C array syntax has many features, but by-far the most common is [] and [4].
8179 // This code does a fast path to handle some of the most obvious cases.
8180 if (Tok.getKind() == tok::r_square) {
8181 T.consumeClose();
8182 ParsedAttributes attrs(AttrFactory);
8183 MaybeParseCXX11Attributes(attrs);
8184
8185 // Remember that we parsed the empty array type.
8186 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
8187 T.getOpenLocation(),
8188 T.getCloseLocation()),
8189 std::move(attrs), T.getCloseLocation());
8190 return;
8191 } else if (Tok.getKind() == tok::numeric_constant &&
8192 GetLookAheadToken(1).is(tok::r_square)) {
8193 // [4] is very common. Parse the numeric constant expression.
8194 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
8195 ConsumeToken();
8196
8197 T.consumeClose();
8198 ParsedAttributes attrs(AttrFactory);
8199 MaybeParseCXX11Attributes(attrs);
8200
8201 // Remember that we parsed a array type, and remember its features.
8202 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
8203 T.getOpenLocation(),
8204 T.getCloseLocation()),
8205 std::move(attrs), T.getCloseLocation());
8206 return;
8207 } else if (Tok.getKind() == tok::code_completion) {
8208 cutOffParsing();
8210 return;
8211 }
8212
8213 // If valid, this location is the position where we read the 'static' keyword.
8214 SourceLocation StaticLoc;
8215 TryConsumeToken(tok::kw_static, StaticLoc);
8216
8217 // If there is a type-qualifier-list, read it now.
8218 // Type qualifiers in an array subscript are a C99 feature.
8219 DeclSpec DS(AttrFactory);
8220 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
8221
8222 // If we haven't already read 'static', check to see if there is one after the
8223 // type-qualifier-list.
8224 if (!StaticLoc.isValid())
8225 TryConsumeToken(tok::kw_static, StaticLoc);
8226
8227 // Handle "direct-declarator [ type-qual-list[opt] * ]".
8228 bool isStar = false;
8229 ExprResult NumElements;
8230
8231 // Handle the case where we have '[*]' as the array size. However, a leading
8232 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
8233 // the token after the star is a ']'. Since stars in arrays are
8234 // infrequent, use of lookahead is not costly here.
8235 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
8236 ConsumeToken(); // Eat the '*'.
8237
8238 if (StaticLoc.isValid()) {
8239 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
8240 StaticLoc = SourceLocation(); // Drop the static.
8241 }
8242 isStar = true;
8243 } else if (Tok.isNot(tok::r_square)) {
8244 // Note, in C89, this production uses the constant-expr production instead
8245 // of assignment-expr. The only difference is that assignment-expr allows
8246 // things like '=' and '*='. Sema rejects these in C89 mode because they
8247 // are not i-c-e's, so we don't need to distinguish between the two here.
8248
8249 // Parse the constant-expression or assignment-expression now (depending
8250 // on dialect).
8251 if (getLangOpts().CPlusPlus) {
8252 NumElements = ParseArrayBoundExpression();
8253 } else {
8256 NumElements =
8258 }
8259 } else {
8260 if (StaticLoc.isValid()) {
8261 Diag(StaticLoc, diag::err_unspecified_size_with_static);
8262 StaticLoc = SourceLocation(); // Drop the static.
8263 }
8264 }
8265
8266 // If there was an error parsing the assignment-expression, recover.
8267 if (NumElements.isInvalid()) {
8268 D.setInvalidType(true);
8269 // If the expression was invalid, skip it.
8270 SkipUntil(tok::r_square, StopAtSemi);
8271 return;
8272 }
8273
8274 T.consumeClose();
8275
8276 MaybeParseCXX11Attributes(DS.getAttributes());
8277
8278 // Remember that we parsed a array type, and remember its features.
8279 D.AddTypeInfo(
8281 isStar, NumElements.get(), T.getOpenLocation(),
8282 T.getCloseLocation()),
8283 std::move(DS.getAttributes()), T.getCloseLocation());
8284}
8285
8286/// Diagnose brackets before an identifier.
8287void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
8288 assert(Tok.is(tok::l_square) && "Missing opening bracket");
8289 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
8290
8291 SourceLocation StartBracketLoc = Tok.getLocation();
8292 Declarator TempDeclarator(D.getDeclSpec(), ParsedAttributesView::none(),
8293 D.getContext());
8294
8295 while (Tok.is(tok::l_square)) {
8296 ParseBracketDeclarator(TempDeclarator);
8297 }
8298
8299 // Stuff the location of the start of the brackets into the Declarator.
8300 // The diagnostics from ParseDirectDeclarator will make more sense if
8301 // they use this location instead.
8302 if (Tok.is(tok::semi))
8303 D.getName().EndLocation = StartBracketLoc;
8304
8305 SourceLocation SuggestParenLoc = Tok.getLocation();
8306
8307 // Now that the brackets are removed, try parsing the declarator again.
8308 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
8309
8310 // Something went wrong parsing the brackets, in which case,
8311 // ParseBracketDeclarator has emitted an error, and we don't need to emit
8312 // one here.
8313 if (TempDeclarator.getNumTypeObjects() == 0)
8314 return;
8315
8316 // Determine if parens will need to be suggested in the diagnostic.
8317 bool NeedParens = false;
8318 if (D.getNumTypeObjects() != 0) {
8319 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
8325 NeedParens = true;
8326 break;
8330 break;
8331 }
8332 }
8333
8334 if (NeedParens) {
8335 // Create a DeclaratorChunk for the inserted parens.
8337 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
8338 SourceLocation());
8339 }
8340
8341 // Adding back the bracket info to the end of the Declarator.
8342 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
8343 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
8344 D.AddTypeInfo(Chunk, TempDeclarator.getAttributePool(), SourceLocation());
8345 }
8346
8347 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
8348 // If parentheses are required, always suggest them.
8349 if (!D.getIdentifier() && !NeedParens)
8350 return;
8351
8352 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
8353
8354 // Generate the move bracket error message.
8355 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
8357
8358 if (NeedParens) {
8359 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
8360 << getLangOpts().CPlusPlus
8361 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
8362 << FixItHint::CreateInsertion(EndLoc, ")")
8364 EndLoc, CharSourceRange(BracketRange, true))
8365 << FixItHint::CreateRemoval(BracketRange);
8366 } else {
8367 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
8368 << getLangOpts().CPlusPlus
8370 EndLoc, CharSourceRange(BracketRange, true))
8371 << FixItHint::CreateRemoval(BracketRange);
8372 }
8373}
8374
8375/// [GNU] typeof-specifier:
8376/// typeof ( expressions )
8377/// typeof ( type-name )
8378/// [GNU/C++] typeof unary-expression
8379/// [C23] typeof-specifier:
8380/// typeof '(' typeof-specifier-argument ')'
8381/// typeof_unqual '(' typeof-specifier-argument ')'
8382///
8383/// typeof-specifier-argument:
8384/// expression
8385/// type-name
8386///
8387void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
8388 assert(Tok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual) &&
8389 "Not a typeof specifier");
8390
8391 bool IsUnqual = Tok.is(tok::kw_typeof_unqual);
8392 const IdentifierInfo *II = Tok.getIdentifierInfo();
8393 if (getLangOpts().C23 && !II->getName().starts_with("__"))
8394 Diag(Tok.getLocation(), diag::warn_c23_compat_keyword) << Tok.getName();
8395
8396 Token OpTok = Tok;
8397 SourceLocation StartLoc = ConsumeToken();
8398 bool HasParens = Tok.is(tok::l_paren);
8399
8403
8404 bool isCastExpr;
8405 ParsedType CastTy;
8406 SourceRange CastRange;
8408 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
8409 if (HasParens)
8410 DS.setTypeArgumentRange(CastRange);
8411
8412 if (CastRange.getEnd().isInvalid())
8413 // FIXME: Not accurate, the range gets one token more than it should.
8414 DS.SetRangeEnd(Tok.getLocation());
8415 else
8416 DS.SetRangeEnd(CastRange.getEnd());
8417
8418 if (isCastExpr) {
8419 if (!CastTy) {
8420 DS.SetTypeSpecError();
8421 return;
8422 }
8423
8424 const char *PrevSpec = nullptr;
8425 unsigned DiagID;
8426 // Check for duplicate type specifiers (e.g. "int typeof(int)").
8429 StartLoc, PrevSpec,
8430 DiagID, CastTy,
8431 Actions.getASTContext().getPrintingPolicy()))
8432 Diag(StartLoc, DiagID) << PrevSpec;
8433 return;
8434 }
8435
8436 // If we get here, the operand to the typeof was an expression.
8437 if (Operand.isInvalid()) {
8438 DS.SetTypeSpecError();
8439 return;
8440 }
8441
8442 // We might need to transform the operand if it is potentially evaluated.
8444 if (Operand.isInvalid()) {
8445 DS.SetTypeSpecError();
8446 return;
8447 }
8448
8449 const char *PrevSpec = nullptr;
8450 unsigned DiagID;
8451 // Check for duplicate type specifiers (e.g. "int typeof(int)").
8454 StartLoc, PrevSpec,
8455 DiagID, Operand.get(),
8456 Actions.getASTContext().getPrintingPolicy()))
8457 Diag(StartLoc, DiagID) << PrevSpec;
8458}
8459
8460/// [C11] atomic-specifier:
8461/// _Atomic ( type-name )
8462///
8463void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
8464 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
8465 "Not an atomic specifier");
8466
8467 SourceLocation StartLoc = ConsumeToken();
8468 BalancedDelimiterTracker T(*this, tok::l_paren);
8469 if (T.consumeOpen())
8470 return;
8471
8473 if (Result.isInvalid()) {
8474 SkipUntil(tok::r_paren, StopAtSemi);
8475 return;
8476 }
8477
8478 // Match the ')'
8479 T.consumeClose();
8480
8481 if (T.getCloseLocation().isInvalid())
8482 return;
8483
8484 DS.setTypeArgumentRange(T.getRange());
8485 DS.SetRangeEnd(T.getCloseLocation());
8486
8487 const char *PrevSpec = nullptr;
8488 unsigned DiagID;
8489 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
8490 DiagID, Result.get(),
8491 Actions.getASTContext().getPrintingPolicy()))
8492 Diag(StartLoc, DiagID) << PrevSpec;
8493}
8494
8495/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
8496/// from TryAltiVecVectorToken.
8497bool Parser::TryAltiVecVectorTokenOutOfLine() {
8498 Token Next = NextToken();
8499 switch (Next.getKind()) {
8500 default: return false;
8501 case tok::kw_short:
8502 case tok::kw_long:
8503 case tok::kw_signed:
8504 case tok::kw_unsigned:
8505 case tok::kw_void:
8506 case tok::kw_char:
8507 case tok::kw_int:
8508 case tok::kw_float:
8509 case tok::kw_double:
8510 case tok::kw_bool:
8511 case tok::kw__Bool:
8512 case tok::kw___bool:
8513 case tok::kw___pixel:
8514 Tok.setKind(tok::kw___vector);
8515 return true;
8516 case tok::identifier:
8517 if (Next.getIdentifierInfo() == Ident_pixel) {
8518 Tok.setKind(tok::kw___vector);
8519 return true;
8520 }
8521 if (Next.getIdentifierInfo() == Ident_bool ||
8522 Next.getIdentifierInfo() == Ident_Bool) {
8523 Tok.setKind(tok::kw___vector);
8524 return true;
8525 }
8526 return false;
8527 }
8528}
8529
8530bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
8531 const char *&PrevSpec, unsigned &DiagID,
8532 bool &isInvalid) {
8533 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
8534 if (Tok.getIdentifierInfo() == Ident_vector) {
8535 Token Next = NextToken();
8536 switch (Next.getKind()) {
8537 case tok::kw_short:
8538 case tok::kw_long:
8539 case tok::kw_signed:
8540 case tok::kw_unsigned:
8541 case tok::kw_void:
8542 case tok::kw_char:
8543 case tok::kw_int:
8544 case tok::kw_float:
8545 case tok::kw_double:
8546 case tok::kw_bool:
8547 case tok::kw__Bool:
8548 case tok::kw___bool:
8549 case tok::kw___pixel:
8550 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
8551 return true;
8552 case tok::identifier:
8553 if (Next.getIdentifierInfo() == Ident_pixel) {
8554 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
8555 return true;
8556 }
8557 if (Next.getIdentifierInfo() == Ident_bool ||
8558 Next.getIdentifierInfo() == Ident_Bool) {
8559 isInvalid =
8560 DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
8561 return true;
8562 }
8563 break;
8564 default:
8565 break;
8566 }
8567 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
8568 DS.isTypeAltiVecVector()) {
8569 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
8570 return true;
8571 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
8572 DS.isTypeAltiVecVector()) {
8573 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
8574 return true;
8575 }
8576 return false;
8577}
8578
8579TypeResult Parser::ParseTypeFromString(StringRef TypeStr, StringRef Context,
8580 SourceLocation IncludeLoc) {
8581 // Consume (unexpanded) tokens up to the end-of-directive.
8582 SmallVector<Token, 4> Tokens;
8583 {
8584 // Create a new buffer from which we will parse the type.
8585 auto &SourceMgr = PP.getSourceManager();
8586 FileID FID = SourceMgr.createFileID(
8587 llvm::MemoryBuffer::getMemBufferCopy(TypeStr, Context), SrcMgr::C_User,
8588 0, 0, IncludeLoc);
8589
8590 // Form a new lexer that references the buffer.
8591 Lexer L(FID, SourceMgr.getBufferOrFake(FID), PP);
8592 L.setParsingPreprocessorDirective(true);
8593
8594 // Lex the tokens from that buffer.
8595 Token Tok;
8596 do {
8597 L.Lex(Tok);
8598 Tokens.push_back(Tok);
8599 } while (Tok.isNot(tok::eod));
8600 }
8601
8602 // Replace the "eod" token with an "eof" token identifying the end of
8603 // the provided string.
8604 Token &EndToken = Tokens.back();
8605 EndToken.startToken();
8606 EndToken.setKind(tok::eof);
8607 EndToken.setLocation(Tok.getLocation());
8608 EndToken.setEofData(TypeStr.data());
8609
8610 // Add the current token back.
8611 Tokens.push_back(Tok);
8612
8613 // Enter the tokens into the token stream.
8614 PP.EnterTokenStream(Tokens, /*DisableMacroExpansion=*/false,
8615 /*IsReinject=*/false);
8616
8617 // Consume the current token so that we'll start parsing the tokens we
8618 // added to the stream.
8620
8621 // Enter a new scope.
8622 ParseScope LocalScope(this, 0);
8623
8624 // Parse the type.
8625 TypeResult Result = ParseTypeName(nullptr);
8626
8627 // Check if we parsed the whole thing.
8628 if (Result.isUsable() &&
8629 (Tok.isNot(tok::eof) || Tok.getEofData() != TypeStr.data())) {
8630 Diag(Tok.getLocation(), diag::err_type_unparsed);
8631 }
8632
8633 // There could be leftover tokens (e.g. because of an error).
8634 // Skip through until we reach the 'end of directive' token.
8635 while (Tok.isNot(tok::eof))
8637
8638 // Consume the end token.
8639 if (Tok.is(tok::eof) && Tok.getEofData() == TypeStr.data())
8641 return Result;
8642}
8643
8644void Parser::DiagnoseBitIntUse(const Token &Tok) {
8645 // If the token is for _ExtInt, diagnose it as being deprecated. Otherwise,
8646 // the token is about _BitInt and gets (potentially) diagnosed as use of an
8647 // extension.
8648 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
8649 "expected either an _ExtInt or _BitInt token!");
8650
8652 if (Tok.is(tok::kw__ExtInt)) {
8653 Diag(Loc, diag::warn_ext_int_deprecated)
8654 << FixItHint::CreateReplacement(Loc, "_BitInt");
8655 } else {
8656 // In C23 mode, diagnose that the use is not compatible with pre-C23 modes.
8657 // Otherwise, diagnose that the use is a Clang extension.
8658 if (getLangOpts().C23)
8659 Diag(Loc, diag::warn_c23_compat_keyword) << Tok.getName();
8660 else
8661 Diag(Loc, diag::ext_bit_int) << getLangOpts().CPlusPlus;
8662 }
8663}
Defines the clang::ASTContext interface.
StringRef P
Provides definitions for the various language-specific address spaces.
static StringRef normalizeAttrName(const IdentifierInfo *Name, StringRef NormalizedScopeName, AttributeCommonInfo::Syntax SyntaxUsed)
Definition: Attributes.cpp:101
#define SM(sm)
Definition: Cuda.cpp:84
const Decl * D
Expr * E
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1172
Defines the C++ template declaration subclasses.
#define X(type, name)
Definition: Value.h:144
llvm::MachO::RecordLoc RecordLoc
Definition: MachO.h:41
static bool IsAttributeLateParsedExperimentalExt(const IdentifierInfo &II)
returns true iff attribute is annotated with LateAttrParseExperimentalExt in Attr....
Definition: ParseDecl.cpp:98
static bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc, SourceLocation EndLoc)
Check if the a start and end source location expand to the same macro.
Definition: ParseDecl.cpp:117
static bool IsAttributeLateParsedStandard(const IdentifierInfo &II)
returns true iff attribute is annotated with LateAttrParseStandard in Attr.td.
Definition: ParseDecl.cpp:108
static ParsedAttributeArgumentsProperties attributeStringLiteralListArg(const llvm::Triple &T, const IdentifierInfo &II, ParsedAttr::Syntax Syntax, IdentifierInfo *ScopeName)
Determine whether the given attribute has string arguments.
Definition: ParseDecl.cpp:355
static bool attributeHasStrictIdentifierArgs(const IdentifierInfo &II, ParsedAttr::Syntax Syntax, IdentifierInfo *ScopeName)
Determine whether the given attribute takes a strict identifier argument.
Definition: ParseDecl.cpp:410
static bool attributeIsTypeArgAttr(const IdentifierInfo &II, ParsedAttr::Syntax Syntax, IdentifierInfo *ScopeName)
Determine whether the given attribute parses a type argument.
Definition: ParseDecl.cpp:399
static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II, ParsedAttr::Syntax Syntax, IdentifierInfo *ScopeName)
Determine whether the given attribute treats kw_this as an identifier.
Definition: ParseDecl.cpp:377
static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II, ParsedAttr::Syntax Syntax, IdentifierInfo *ScopeName)
Determine whether the given attribute requires parsing its arguments in an unevaluated context or not...
Definition: ParseDecl.cpp:422
static bool attributeHasIdentifierArg(const llvm::Triple &T, const IdentifierInfo &II, ParsedAttr::Syntax Syntax, IdentifierInfo *ScopeName)
Determine whether the given attribute has an identifier argument.
Definition: ParseDecl.cpp:342
static bool isValidAfterIdentifierInDeclarator(const Token &T)
isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the specified token is valid after t...
Definition: ParseDecl.cpp:3019
static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II, ParsedAttr::Syntax Syntax, IdentifierInfo *ScopeName)
Determine whether the given attribute has a variadic identifier argument.
Definition: ParseDecl.cpp:366
static bool isPipeDeclarator(const Declarator &D)
Definition: ParseDecl.cpp:6654
static SourceLocation getMissingDeclaratorIdLoc(Declarator &D, SourceLocation Loc)
Definition: ParseDecl.cpp:6880
static bool attributeAcceptsExprPack(const IdentifierInfo &II, ParsedAttr::Syntax Syntax, IdentifierInfo *ScopeName)
Determine if an attribute accepts parameter packs.
Definition: ParseDecl.cpp:388
static void DiagnoseCountAttributedTypeInUnnamedAnon(ParsingDeclSpec &DS, Parser &P)
Definition: ParseDecl.cpp:4891
static bool VersionNumberSeparator(const char Separator)
Definition: ParseDecl.cpp:1184
static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang, DeclaratorContext TheContext)
Definition: ParseDecl.cpp:6625
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static constexpr bool isOneOf()
This file declares semantic analysis for CUDA constructs.
This file declares facilities that support code completion.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines the clang::TokenKind enum and support functions.
@ Uninitialized
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2482
The result of parsing/analyzing an expression, statement etc.
Definition: Ownership.h:153
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Combines information about the source-code form of an attribute, including its syntax and spelling.
Syntax
The style used to specify an attribute.
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ....
SourceLocation getOpenLocation() const
SourceLocation getCloseLocation() const
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
SourceLocation getEndLoc() const
Definition: DeclSpec.h:85
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
void setTemplateParamLists(ArrayRef< TemplateParameterList * > L)
Definition: DeclSpec.h:87
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
Represents a character-granular source range.
SourceLocation getBegin() const
Callback handler that receives notifications when performing code completion within the preprocessor.
ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and restores it when destroyed.
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: Type.h:3306
bool isRecord() const
Definition: DeclBase.h:2169
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool isVirtualSpecified() const
Definition: DeclSpec.h:648
bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, ExplicitSpecifier ExplicitSpec, SourceLocation CloseParenLoc)
Definition: DeclSpec.cpp:1073
bool isTypeSpecPipe() const
Definition: DeclSpec.h:543
void ClearTypeSpecType()
Definition: DeclSpec.h:523
static const TSCS TSCS___thread
Definition: DeclSpec.h:266
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:309
void setTypeArgumentRange(SourceRange range)
Definition: DeclSpec.h:593
bool SetTypePipe(bool isPipe, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:912
SourceLocation getPipeLoc() const
Definition: DeclSpec.h:622
static const TST TST_typename
Definition: DeclSpec.h:306
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:576
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:691
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition: DeclSpec.cpp:645
static const TST TST_char8
Definition: DeclSpec.h:282
static const TST TST_BFloat16
Definition: DeclSpec.h:289
void ClearStorageClassSpecs()
Definition: DeclSpec.h:515
bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1132
static const TSCS TSCS__Thread_local
Definition: DeclSpec.h:268
bool SetTypeSpecWidth(TypeSpecifierWidth W, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec, but return true and ignore the request if ...
Definition: DeclSpec.cpp:721
bool isNoreturnSpecified() const
Definition: DeclSpec.h:661
TST getTypeSpecType() const
Definition: DeclSpec.h:537
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:510
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1120
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:860
bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:884
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:574
bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:707
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:709
bool SetBitIntType(SourceLocation KWLoc, Expr *BitWidth, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:971
static const TST TST_auto_type
Definition: DeclSpec.h:319
static const TST TST_interface
Definition: DeclSpec.h:304
static const TST TST_double
Definition: DeclSpec.h:291
static const TST TST_typeofExpr
Definition: DeclSpec.h:308
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:616
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:708
bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:929
bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1107
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:662
static const TST TST_union
Definition: DeclSpec.h:302
static const TST TST_char
Definition: DeclSpec.h:280
static const TST TST_bool
Definition: DeclSpec.h:297
static const TST TST_char16
Definition: DeclSpec.h:283
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:654
SourceLocation getFriendSpecLoc() const
Definition: DeclSpec.h:827
static const TST TST_int
Definition: DeclSpec.h:285
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:830
bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:738
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:788
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:502
bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1092
bool hasAttributes() const
Definition: DeclSpec.h:871
static const TST TST_accum
Definition: DeclSpec.h:293
static const TST TST_half
Definition: DeclSpec.h:288
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:873
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:617
static const TST TST_ibm128
Definition: DeclSpec.h:296
void addAttributes(const ParsedAttributesView &AL)
Concatenates two attribute lists.
Definition: DeclSpec.h:867
static const TST TST_enum
Definition: DeclSpec.h:301
bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:946
static const TST TST_float128
Definition: DeclSpec.h:295
void Finish(Sema &S, const PrintingPolicy &Policy)
Finish - This does final analysis of the declspec, issuing diagnostics for things like "_Complex" (la...
Definition: DeclSpec.cpp:1154
bool isInlineSpecified() const
Definition: DeclSpec.h:637
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:618
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:310
static const TST TST_class
Definition: DeclSpec.h:305
bool hasTagDefinition() const
Definition: DeclSpec.cpp:459
static const TST TST_decimal64
Definition: DeclSpec.h:299
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition: DeclSpec.cpp:468
void ClearFunctionSpecs()
Definition: DeclSpec.h:664
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:1017
static const TST TST_wchar
Definition: DeclSpec.h:281
static const TST TST_void
Definition: DeclSpec.h:279
bool isTypeAltiVecVector() const
Definition: DeclSpec.h:538
void ClearConstexprSpec()
Definition: DeclSpec.h:841
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:558
static const TST TST_float
Definition: DeclSpec.h:290
static const TST TST_atomic
Definition: DeclSpec.h:321
static const TST TST_fract
Definition: DeclSpec.h:294
bool SetTypeSpecError()
Definition: DeclSpec.cpp:963
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:511
Decl * getRepAsDecl() const
Definition: DeclSpec.h:551
static const TST TST_float16
Definition: DeclSpec.h:292
static const TST TST_unspecified
Definition: DeclSpec.h:278
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:620
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:649
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:836
CXXScopeSpec & getTypeSpecScope()
Definition: DeclSpec.h:571
bool isEmpty() const
isEmpty - Return true if this declaration specifier is completely empty: no tokens were parsed in the...
Definition: DeclSpec.h:704
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:267
bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1058
static const TST TST_decimal32
Definition: DeclSpec.h:298
bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:897
TypeSpecifierWidth getTypeSpecWidth() const
Definition: DeclSpec.h:530
static const TST TST_char32
Definition: DeclSpec.h:284
bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1032
static const TST TST_decimal128
Definition: DeclSpec.h:300
bool isTypeSpecOwned() const
Definition: DeclSpec.h:541
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:640
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:621
static const TST TST_int128
Definition: DeclSpec.h:286
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:619
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:821
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:651
bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1046
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:837
void takeAttributesFrom(ParsedAttributes &attrs)
Definition: DeclSpec.h:876
static const TST TST_typeofType
Definition: DeclSpec.h:307
bool SetTypeSpecSign(TypeSpecifierSign S, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:748
static const TST TST_auto
Definition: DeclSpec.h:318
@ PQ_FunctionSpecifier
Definition: DeclSpec.h:349
@ PQ_StorageClassSpecifier
Definition: DeclSpec.h:346
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:832
static const TST TST_struct
Definition: DeclSpec.h:303
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:438
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
Kind getKind() const
Definition: DeclBase.h:445
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:430
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
bool isInvalidType() const
Definition: DeclSpec.h:2717
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2085
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3847
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
This represents one expression.
Definition: Expr.h:110
ExtensionRAIIObject - This saves the state of extension warnings when constructed and disables them.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location.
Definition: Diagnostic.h:114
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:101
One of these records is kept for each identifier that is lexed.
bool isCPlusPlusKeyword(const LangOptions &LangOpts) const
Return true if this token is a C++ keyword in the specified language.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
const char * getNameStart() const
Return the beginning of the actual null-terminated string for this identifier.
bool isKeyword(const LangOptions &LangOpts) const
Return true if this token is a keyword in the specified language.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
StringRef getName() const
Return the actual identifier string.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:973
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:721
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
Definition: LangOptions.cpp:79
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens.
Definition: Lexer.h:78
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:1023
static bool isAtStartOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroBegin=nullptr)
Returns true if the given MacroID location points at the first token of the macro expansion.
Definition: Lexer.cpp:871
static bool isAtEndOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroEnd=nullptr)
Returns true if the given MacroID location points at the last token of the macro expansion.
Definition: Lexer.cpp:893
static bool getRawToken(SourceLocation Loc, Token &Result, const SourceManager &SM, const LangOptions &LangOpts, bool IgnoreWhiteSpace=false)
Relex the token at the specified location.
Definition: Lexer.cpp:509
static std::optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Finds the token that comes right after the given location.
Definition: Lexer.cpp:1324
Represents the results of name lookup.
Definition: Lookup.h:46
This represents a decl that may have a name.
Definition: Decl.h:253
PtrTy get() const
Definition: Ownership.h:80
bool isSupported(llvm::StringRef Ext, const LangOptions &LO) const
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing,...
Represents a parameter to a function.
Definition: Decl.h:1725
static constexpr unsigned getMaxFunctionScopeDepth()
Definition: Decl.h:1780
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
unsigned getMaxArgs() const
Definition: ParsedAttr.cpp:148
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:836
void addAtEnd(ParsedAttr *newAttr)
Definition: ParsedAttr.h:846
void addAll(iterator B, iterator E)
Definition: ParsedAttr.h:878
void remove(ParsedAttr *ToBeRemoved)
Definition: ParsedAttr.h:851
SizeType size() const
Definition: ParsedAttr.h:842
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:956
ParsedAttr * addNew(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, ArgsUnion *args, unsigned numArgs, ParsedAttr::Form form, SourceLocation ellipsisLoc=SourceLocation())
Add attribute with expression arguments.
Definition: ParsedAttr.h:989
void takeOneFrom(ParsedAttributes &Other, ParsedAttr *PA)
Definition: ParsedAttr.h:973
ParsedAttr * addNewPropertyAttr(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, IdentifierInfo *getterId, IdentifierInfo *setterId, ParsedAttr::Form formUsed)
Add microsoft __delspec(property) attribute.
Definition: ParsedAttr.h:1056
void takeAllFrom(ParsedAttributes &Other)
Definition: ParsedAttr.h:965
ParsedAttr * addNewTypeTagForDatatype(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, IdentifierLoc *argumentKind, ParsedType matchingCType, bool layoutCompatible, bool mustBeNull, ParsedAttr::Form form)
Add type_tag_for_datatype attribute.
Definition: ParsedAttr.h:1030
ParsedAttr * addNewTypeAttr(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, ParsedType typeArg, ParsedAttr::Form formUsed, SourceLocation ellipsisLoc=SourceLocation())
Add an attribute with a single type argument.
Definition: ParsedAttr.h:1043
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:58
TypeResult ParseTypeName(SourceRange *Range=nullptr, DeclaratorContext Context=DeclaratorContext::TypeName, AccessSpecifier AS=AS_none, Decl **OwnedType=nullptr, ParsedAttributes *Attrs=nullptr)
ParseTypeName type-name: [C99 6.7.6] specifier-qualifier-list abstract-declarator[opt].
Definition: ParseDecl.cpp:50
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:81
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition: Parser.h:548
DeclGroupPtrTy ParseOpenACCDirectiveDecl()
Placeholder for now, should just ignore the directives after emitting a diagnostic.
Sema & getActions() const
Definition: Parser.h:498
static TypeResult getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition: Parser.h:877
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
Definition: Parser.cpp:420
ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-or-expression.
Definition: ParseExpr.cpp:382
bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition: Parser.h:576
ExprResult ParseConstantExpression()
Definition: ParseExpr.cpp:235
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:556
Scope * getCurScope() const
Definition: Parser.h:502
SourceLocation getEndOfPreviousToken()
Definition: Parser.h:594
ExprResult ParseArrayBoundExpression()
Definition: ParseExpr.cpp:245
const TargetInfo & getTargetInfo() const
Definition: Parser.h:496
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
Definition: Parser.h:1294
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
Definition: ParseDecl.cpp:2239
friend class ObjCDeclContextSwitch
Definition: Parser.h:65
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast=NotTypeCast)
Parse an expr that doesn't include (top-level) commas.
Definition: ParseExpr.cpp:171
ExprResult ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:225
const LangOptions & getLangOpts() const
Definition: Parser.h:495
ExprResult ParseExpression(TypeCastState isTypeCast=NotTypeCast)
Simple precedence-based parser for binary/ternary operators.
Definition: ParseExpr.cpp:134
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition: Parser.h:1275
@ StopAtCodeCompletion
Stop at code completion.
Definition: Parser.h:1276
@ StopAtSemi
Stop skipping at semicolon.
Definition: Parser.h:1273
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition: Parser.cpp:1995
ExprResult ParseUnevaluatedStringLiteralExpression()
ObjCContainerDecl * getObjCDeclContext() const
Definition: Parser.h:507
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:872
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition: Parser.h:516
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
Definition: Parser.cpp:2246
RAII object used to inform the actions that we're currently parsing a declaration.
A class for parsing a DeclSpec.
A class for parsing a declarator.
A class for parsing a field declarator.
void enterVariableInit(SourceLocation Tok, Decl *D)
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:138
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
void EnterToken(const Token &Tok, bool IsReinject)
Enters a token in the token stream to be lexed next.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceManager & getSourceManager() const
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
const LangOptions & getLangOpts() const
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition: Type.h:929
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
The collection of all-type qualifiers we support.
Definition: Type.h:324
void addAddressSpace(LangAS space)
Definition: Type.h:590
void addConst()
Definition: Type.h:453
static Qualifiers fromCVRUMask(unsigned CVRU)
Definition: Type.h:434
Represents a struct/union/class.
Definition: Decl.h:4148
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition: Scope.h:412
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:263
@ FunctionPrototypeScope
This is a scope that corresponds to the parameters within a function prototype.
Definition: Scope.h:85
@ BlockScope
This is a scope that corresponds to a block/closure object.
Definition: Scope.h:75
@ FriendScope
This is a scope of friend declaration.
Definition: Scope.h:165
@ ControlScope
The controlling scope in a if/switch/while/for statement.
Definition: Scope.h:66
@ AtCatchScope
This is a scope that corresponds to the Objective-C @catch statement.
Definition: Scope.h:95
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:81
@ CompoundStmtScope
This is a compound statement scope.
Definition: Scope.h:134
@ ClassScope
The scope of a struct/union/class definition.
Definition: Scope.h:69
@ FunctionDeclarationScope
This is a scope that corresponds to the parameters within a function prototype for a function declara...
Definition: Scope.h:91
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
Definition: Scope.h:51
@ EnumScope
This scope corresponds to an enum.
Definition: Scope.h:122
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
@ CTCK_InitGlobalVar
Unknown context.
Definition: SemaCUDA.h:131
void CodeCompleteAttribute(AttributeCommonInfo::Syntax Syntax, AttributeCompletion Completion=AttributeCompletion::Attribute, const IdentifierInfo *Scope=nullptr)
ParserCompletionContext
Describes the context in which code completion occurs.
@ PCC_LocalDeclarationSpecifiers
Code completion occurs within a sequence of declaration specifiers within a function,...
@ PCC_MemberTemplate
Code completion occurs following one or more template headers within a class.
@ PCC_Class
Code completion occurs within a class, struct, or union.
@ PCC_ObjCImplementation
Code completion occurs within an Objective-C implementation or category implementation.
@ PCC_Namespace
Code completion occurs at top-level or namespace context.
@ PCC_Template
Code completion occurs following one or more template headers.
void CodeCompleteTypeQualifiers(DeclSpec &DS)
void CodeCompleteAfterFunctionEquals(Declarator &D)
QualType ProduceConstructorSignatureHelp(QualType Type, SourceLocation Loc, ArrayRef< Expr * > Args, SourceLocation OpenParLoc, bool Braced)
void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext)
void CodeCompleteInitializer(Scope *S, Decl *D)
void CodeCompleteBracketDeclarator(Scope *S)
void CodeCompleteTag(Scope *S, unsigned TagSpec)
void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers)
ParsedType ActOnObjCInstanceType(SourceLocation Loc)
The parser has parsed the context-sensitive type 'instancetype' in an Objective-C message declaration...
Definition: SemaObjC.cpp:745
void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, const IdentifierInfo *ClassName, SmallVectorImpl< Decl * > &Decls)
Called whenever @defs(ClassName) is encountered in the source.
void startOpenMPCXXRangeFor()
If the current region is a range loop-based region, mark the start of the loop construct.
NameClassificationKind getKind() const
Definition: Sema.h:3281
bool containsUnexpandedParameterPacks(Declarator &D)
Determine whether the given declarator contains any unexpanded parameter packs.
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8983
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
Definition: SemaDecl.cpp:5306
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E)
ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression found in an explicit(bool)...
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, Expr *DefaultArg)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
ActOnTemplateParameterList - Builds a TemplateParameterList, optionally constrained by RequiresClause...
SemaOpenMP & OpenMP()
Definition: Sema.h:1125
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:18207
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:15043
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, const IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
SemaCUDA & CUDA()
Definition: Sema.h:1070
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition: Sema.h:6440
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition: SemaDecl.cpp:641
void ActOnFinishFunctionDeclarationDeclarator(Declarator &D)
Called after parsing a function declarator belonging to a function declaration.
void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg)
ActOnParamDefaultArgument - Check whether the default argument provided for a function parameter is w...
ASTContext & Context
Definition: Sema.h:908
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14677
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
Definition: SemaDecl.cpp:20280
SemaObjC & ObjC()
Definition: Sema.h:1110
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:70
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
ASTContext & getASTContext() const
Definition: Sema.h:531
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
@ NC_Unknown
This name is not a type or template in this context, but might be something else.
Definition: Sema.h:3173
@ NC_VarTemplate
The name was classified as a variable template name.
Definition: Sema.h:3200
@ NC_NonType
The name was classified as a specific non-type, non-template declaration.
Definition: Sema.h:3183
@ NC_TypeTemplate
The name was classified as a template whose specializations are types.
Definition: Sema.h:3198
@ NC_Error
Classification failed; an error has been produced.
Definition: Sema.h:3175
@ NC_FunctionTemplate
The name was classified as a function template name.
Definition: Sema.h:3202
@ NC_DependentNonType
The name denotes a member of a dependent type that could not be resolved.
Definition: Sema.h:3191
@ NC_UndeclaredNonType
The name was classified as an ADL-only function name.
Definition: Sema.h:3187
@ NC_UndeclaredTemplate
The name was classified as an ADL-only function template name.
Definition: Sema.h:3204
@ NC_Keyword
The name has been typo-corrected to a keyword.
Definition: Sema.h:3177
@ NC_Type
The name was classified as a type.
Definition: Sema.h:3179
@ NC_OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
Definition: Sema.h:3196
@ NC_Concept
The name was classified as a concept name.
Definition: Sema.h:3206
void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth)
Called before parsing a function declarator belonging to a function declaration.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:7909
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:816
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:19730
const LangOptions & getLangOpts() const
Definition: Sema.h:524
SemaCodeCompletion & CodeCompletion()
Definition: Sema.h:1065
@ ReuseLambdaContextDecl
Definition: Sema.h:6524
bool isUnexpandedParameterPackPermitted()
Determine whether an unexpanded parameter pack might be permitted in this location.
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
Definition: SemaExpr.cpp:4711
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS)
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition: SemaDecl.cpp:860
bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D)
Determine if we're in a case where we need to (incorrectly) eagerly parse an exception specification ...
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:19756
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:14909
bool isDeclaratorFunctionLike(Declarator &D)
Determine whether.
Definition: Sema.cpp:2757
bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:18156
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1043
void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS)
Given an annotation pointer for a nested-name-specifier, restore the nested-name-specifier structure.
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:20011
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:18142
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:13903
TypeResult ActOnTypeName(Declarator &D)
Definition: SemaType.cpp:6413
TopLevelStmtDecl * ActOnStartTopLevelStmtDecl(Scope *S)
Definition: SemaDecl.cpp:20271
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc)
Invoked when parsing a template argument followed by an ellipsis, which creates a pack expansion.
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14834
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition: SemaDecl.cpp:592
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:286
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr)
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Definition: SemaDecl.cpp:17135
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, const ParsedAttributesView &DeclAttrs, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
Definition: SemaDecl.cpp:4785
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18992
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7910
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, CXXScopeSpec &SS, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration.
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:525
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:16402
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:13945
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13386
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:562
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
Definition: SemaDecl.cpp:18382
void ActOnCXXForRangeDecl(Decl *D)
Definition: SemaDecl.cpp:14230
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6049
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3672
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:681
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:17905
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
UIntTy getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:84
A RAII object used to temporarily suppress access-like checking.
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3564
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4743
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:187
SourceLocation getEndLoc() const
Definition: Token.h:159
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:132
const char * getName() const
Definition: Token.h:174
unsigned getLength() const
Definition: Token.h:135
void setKind(tok::TokenKind K)
Definition: Token.h:95
SourceLocation getAnnotationEndLoc() const
Definition: Token.h:146
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:99
void * getAnnotationValue() const
Definition: Token.h:234
tok::TokenKind getKind() const
Definition: Token.h:94
bool isRegularKeywordAttribute() const
Return true if the token is a keyword that is parsed in the same position as a standard attribute,...
Definition: Token.h:126
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:276
void setEofData(const void *D)
Definition: Token.h:204
SourceRange getAnnotationRange() const
SourceRange of the group of tokens that this annotation token represents.
Definition: Token.h:166
void setLocation(SourceLocation L)
Definition: Token.h:140
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:101
bool isNot(tok::TokenKind K) const
Definition: Token.h:100
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:121
const void * getEofData() const
Definition: Token.h:200
bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const
Return true if we have an ObjC keyword identifier.
Definition: Lexer.cpp:60
void startToken()
Reset all flags to cleared.
Definition: Token.h:177
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:196
A declaration that models statements at global scope.
Definition: Decl.h:4437
void setSemiMissing(bool Missing=true)
Definition: Decl.h:4458
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
The base class of the type hierarchy.
Definition: Type.h:1828
static constexpr int FunctionTypeNumParamsLimit
Definition: Type.h:1933
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Declaration of a variable template.
static const char * getSpecifierName(Specifier VS)
Definition: DeclSpec.cpp:1552
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
bool InitScope(InterpState &S, CodePtr OpPC, uint32_t I)
Definition: Interp.h:2172
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
bool isPragmaAnnotation(TokenKind K)
Return true if this is an annotation token representing a pragma.
Definition: TokenKinds.cpp:68
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
The JSON file list parser is used to communicate input to InstallAPI.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ TST_auto
Definition: Specifiers.h:92
@ TST_bool
Definition: Specifiers.h:75
@ TST_unknown_anytype
Definition: Specifiers.h:95
@ TST_decltype_auto
Definition: Specifiers.h:93
bool doesKeywordAttributeTakeArgs(tok::TokenKind Kind)
ImplicitTypenameContext
Definition: DeclSpec.h:1886
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus23
Definition: LangStandard.h:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus26
Definition: LangStandard.h:61
@ CPlusPlus17
Definition: LangStandard.h:58
llvm::PointerUnion< Expr *, IdentifierLoc * > ArgsUnion
A union of the various pointer types that can be passed to an ParsedAttr as an argument.
Definition: ParsedAttr.h:113
@ IK_TemplateId
A template-id, e.g., f<int>.
void takeAndConcatenateAttrs(ParsedAttributes &First, ParsedAttributes &Second, ParsedAttributes &Result)
Consumes the attributes from First and Second and concatenates them into Result.
Definition: ParsedAttr.cpp:312
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
DeclaratorContext
Definition: DeclSpec.h:1853
@ Result
The result type of a method or function.
TagUseKind
Definition: Sema.h:446
LLVM_READONLY bool isDigit(unsigned char c)
Return true if this character is an ASCII digit: [0-9].
Definition: CharInfo.h:114
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
int hasAttribute(AttributeCommonInfo::Syntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:34
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
@ TNK_Dependent_template_name
The name refers to a dependent template name:
Definition: TemplateKinds.h:46
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
Definition: TemplateKinds.h:50
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
const FunctionProtoType * T
@ Parens
New-expression has a C++98 paren-delimited initializer.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_None
no exception specification
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:123
@ AS_none
Definition: Specifiers.h:127
#define false
Definition: stdbool.h:26
Represents information about a change in availability for an entity, which is part of the encoding of...
Definition: ParsedAttr.h:48
VersionTuple Version
The version number at which the change occurred.
Definition: ParsedAttr.h:53
SourceLocation KeywordLoc
The location of the keyword indicating the kind of change.
Definition: ParsedAttr.h:50
SourceRange VersionRange
The source range covering the version number.
Definition: ParsedAttr.h:56
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1428
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1403
ParamInfo - An array of paraminfo objects is allocated whenever a function declarator is parsed.
Definition: DeclSpec.h:1333
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1251
static DeclaratorChunk getBlockPointer(unsigned TypeQuals, SourceLocation Loc)
Return a DeclaratorChunk for a block.
Definition: DeclSpec.h:1741
enum clang::DeclaratorChunk::@222 Kind
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:158
static DeclaratorChunk getPipe(unsigned TypeQuals, SourceLocation Loc)
Return a DeclaratorChunk for a block.
Definition: DeclSpec.h:1751
static DeclaratorChunk getArray(unsigned TypeQuals, bool isStatic, bool isStar, Expr *NumElts, SourceLocation LBLoc, SourceLocation RBLoc)
Return a DeclaratorChunk for an array.
Definition: DeclSpec.h:1698
SourceLocation Loc
Loc - The place where this type was defined.
Definition: DeclSpec.h:1259
static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS, unsigned TypeQuals, SourceLocation StarLoc, SourceLocation EndLoc)
Definition: DeclSpec.h:1760
static DeclaratorChunk getParen(SourceLocation LParenLoc, SourceLocation RParenLoc)
Return a DeclaratorChunk for a paren.
Definition: DeclSpec.h:1776
static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc, SourceLocation ConstQualLoc, SourceLocation VolatileQualLoc, SourceLocation RestrictQualLoc, SourceLocation AtomicQualLoc, SourceLocation UnalignedQualLoc)
Return a DeclaratorChunk for a pointer.
Definition: DeclSpec.h:1667
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1687
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:103
SourceLocation Loc
Definition: ParsedAttr.h:104
IdentifierInfo * Ident
Definition: ParsedAttr.h:105
static IdentifierLoc * create(ASTContext &Ctx, SourceLocation Loc, IdentifierInfo *Ident)
Definition: ParsedAttr.cpp:26
bool isStringLiteralArg(unsigned I) const
Definition: ParsedAttr.h:939
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:6366
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:6343
bool CheckSameAsPrevious
Definition: Sema.h:350
NamedDecl * New
Definition: Sema.h:352
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
TemplateNameKind Kind
The kind of template that Template refers to.