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