blob: 73b4f50fda46076a44fb5da2105b9b035371ee02 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Declaration portions of the Parser interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Parse/Parser.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000014#include "clang/Parse/RAIIObjectsForParser.h"
Erik Verbruggen888d52a2014-01-15 09:15:43 +000015#include "clang/AST/ASTContext.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000016#include "clang/AST/DeclTemplate.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000017#include "clang/AST/PrettyDeclStackTrace.h"
Benjamin Kramerd7d2b1f2012-12-01 16:35:25 +000018#include "clang/Basic/AddressSpaces.h"
Aaron Ballmanfdd783a2014-03-31 18:18:43 +000019#include "clang/Basic/Attributes.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000020#include "clang/Basic/CharInfo.h"
Aaron Ballmanfdd783a2014-03-31 18:18:43 +000021#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Parse/ParseDiagnostic.h"
Kaelyn Uhrain031643e2012-04-26 23:36:17 +000023#include "clang/Sema/Lookup.h"
John McCall8b0666c2010-08-20 18:27:03 +000024#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/Scope.h"
George Burgess IVa19ea342016-11-10 20:43:52 +000026#include "llvm/ADT/Optional.h"
Chris Lattnerad9ac942007-01-23 01:14:52 +000027#include "llvm/ADT/SmallSet.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000028#include "llvm/ADT/SmallString.h"
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +000029#include "llvm/ADT/StringSwitch.h"
Hans Wennborgdcfba332015-10-06 23:40:43 +000030
Chris Lattnerc0acd3d2006-07-31 05:13:43 +000031using namespace clang;
32
33//===----------------------------------------------------------------------===//
34// C99 6.7: Declarations.
35//===----------------------------------------------------------------------===//
36
Chris Lattnerf5fbd792006-08-10 23:56:11 +000037/// ParseTypeName
38/// type-name: [C99 6.7.6]
39/// specifier-qualifier-list abstract-declarator[opt]
Sebastian Redlbd150f42008-11-21 19:14:01 +000040///
41/// Called type-id in C++.
Douglas Gregor205d5e32011-01-31 16:09:46 +000042TypeResult Parser::ParseTypeName(SourceRange *Range,
Faisal Vali421b2d12017-12-29 05:41:00 +000043 DeclaratorContext Context,
Richard Smithcd1c0552011-07-01 19:46:12 +000044 AccessSpecifier AS,
Richard Smith54ecd982013-02-20 19:22:51 +000045 Decl **OwnedType,
46 ParsedAttributes *Attrs) {
Richard Smith62dad822012-03-15 01:02:11 +000047 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
Faisal Vali7db85c52017-12-31 00:06:40 +000048 if (DSC == DeclSpecContext::DSC_normal)
49 DSC = DeclSpecContext::DSC_type_specifier;
Richard Smithbfdb1082012-03-12 08:56:40 +000050
Chris Lattnerf5fbd792006-08-10 23:56:11 +000051 // Parse the common declaration-specifiers piece.
John McCall084e83d2011-03-24 11:26:52 +000052 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +000053 if (Attrs)
Erich Keanec480f302018-07-12 21:09:05 +000054 DS.addAttributes(*Attrs);
Richard Smithbfdb1082012-03-12 08:56:40 +000055 ParseSpecifierQualifierList(DS, AS, DSC);
Richard Smithcd1c0552011-07-01 19:46:12 +000056 if (OwnedType)
Craig Topper161e4db2014-05-21 06:02:52 +000057 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
Sebastian Redld6434562009-05-29 18:02:33 +000058
Chris Lattnerf5fbd792006-08-10 23:56:11 +000059 // Parse the abstract-declarator, if present.
Douglas Gregor205d5e32011-01-31 16:09:46 +000060 Declarator DeclaratorInfo(DS, Context);
Chris Lattnerf5fbd792006-08-10 23:56:11 +000061 ParseDeclarator(DeclaratorInfo);
Sebastian Redld6434562009-05-29 18:02:33 +000062 if (Range)
63 *Range = DeclaratorInfo.getSourceRange();
64
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000065 if (DeclaratorInfo.isInvalidType())
Douglas Gregor220cac52009-02-18 17:45:20 +000066 return true;
67
Douglas Gregor0be31a22010-07-02 17:43:08 +000068 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Chris Lattnerf5fbd792006-08-10 23:56:11 +000069}
70
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071/// Normalizes an attribute name by dropping prefixed and suffixed __.
George Burgess IV779af822017-06-30 22:33:24 +000072static StringRef normalizeAttrName(StringRef Name) {
73 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
74 return Name.drop_front(2).drop_back(2);
75 return Name;
76}
77
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000078/// isAttributeLateParsed - Return true if the attribute has arguments that
79/// require late parsing.
80static bool isAttributeLateParsed(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +000081#define CLANG_ATTR_LATE_PARSED_LIST
George Burgess IV779af822017-06-30 22:33:24 +000082 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +000083#include "clang/Parse/AttrParserStringSwitches.inc"
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000084 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +000085#undef CLANG_ATTR_LATE_PARSED_LIST
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000086}
87
Leonard Chanc72aaf62019-05-07 03:20:17 +000088/// Check if the a start and end source location expand to the same macro.
89bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc,
90 SourceLocation EndLoc) {
91 if (!StartLoc.isMacroID() || !EndLoc.isMacroID())
92 return false;
93
94 SourceManager &SM = PP.getSourceManager();
95 if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
96 return false;
97
98 bool AttrStartIsInMacro =
99 Lexer::isAtStartOfMacroExpansion(StartLoc, SM, PP.getLangOpts());
100 bool AttrEndIsInMacro =
101 Lexer::isAtEndOfMacroExpansion(EndLoc, SM, PP.getLangOpts());
102 return AttrStartIsInMacro && AttrEndIsInMacro;
103}
104
Alexis Hunt96d5c762009-11-21 08:43:09 +0000105/// ParseGNUAttributes - Parse a non-empty attributes list.
Chris Lattnerb8cd5c22006-08-15 04:10:46 +0000106///
107/// [GNU] attributes:
108/// attribute
109/// attributes attribute
110///
111/// [GNU] attribute:
112/// '__attribute__' '(' '(' attribute-list ')' ')'
113///
114/// [GNU] attribute-list:
115/// attrib
116/// attribute_list ',' attrib
117///
118/// [GNU] attrib:
119/// empty
Steve Naroff0f2fe172007-06-01 17:11:19 +0000120/// attrib-name
121/// attrib-name '(' identifier ')'
122/// attrib-name '(' identifier ',' nonempty-expr-list ')'
123/// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
Chris Lattnerb8cd5c22006-08-15 04:10:46 +0000124///
Steve Naroff0f2fe172007-06-01 17:11:19 +0000125/// [GNU] attrib-name:
126/// identifier
127/// typespec
128/// typequal
129/// storageclass
Mike Stump11289f42009-09-09 15:08:12 +0000130///
Richard Smithf7ca0c02013-09-03 18:57:36 +0000131/// Whether an attribute takes an 'identifier' is determined by the
132/// attrib-name. GCC's behavior here is not worth imitating:
Steve Naroff0f2fe172007-06-01 17:11:19 +0000133///
Richard Smithf7ca0c02013-09-03 18:57:36 +0000134/// * In C mode, if the attribute argument list starts with an identifier
135/// followed by a ',' or an ')', and the identifier doesn't resolve to
136/// a type, it is parsed as an identifier. If the attribute actually
137/// wanted an expression, it's out of luck (but it turns out that no
138/// attributes work that way, because C constant expressions are very
139/// limited).
140/// * In C++ mode, if the attribute argument list starts with an identifier,
141/// and the attribute *wants* an identifier, it is parsed as an identifier.
142/// At block scope, any additional tokens between the identifier and the
143/// ',' or ')' are ignored, otherwise they produce a parse error.
Richard Smithb12bf692011-10-17 21:20:17 +0000144///
Richard Smithf7ca0c02013-09-03 18:57:36 +0000145/// We follow the C++ model, but don't allow junk after the identifier.
John McCall53fa7142010-12-24 02:08:15 +0000146void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000147 SourceLocation *endLoc,
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000148 LateParsedAttrList *LateAttrs,
149 Declarator *D) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000150 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
Mike Stump11289f42009-09-09 15:08:12 +0000151
Chris Lattner76c72282007-10-09 17:33:22 +0000152 while (Tok.is(tok::kw___attribute)) {
Leonard Chanc72aaf62019-05-07 03:20:17 +0000153 SourceLocation AttrTokLoc = ConsumeToken();
154 unsigned OldNumAttrs = attrs.size();
155 unsigned OldNumLateAttrs = LateAttrs ? LateAttrs->size() : 0;
156
Steve Naroff0f2fe172007-06-01 17:11:19 +0000157 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
158 "attribute")) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000159 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
John McCall53fa7142010-12-24 02:08:15 +0000160 return;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000161 }
162 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000163 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
John McCall53fa7142010-12-24 02:08:15 +0000164 return;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000165 }
166 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
Aaron Ballman7a899092019-06-18 12:57:05 +0000167 do {
168 // Eat preceeding commas to allow __attribute__((,,,foo))
169 while (TryConsumeToken(tok::comma))
170 ;
Alp Toker094e5212014-01-05 03:27:11 +0000171
172 // Expect an identifier or declaration specifier (const, int, etc.)
David Majnemer22fe7712015-01-03 19:41:00 +0000173 if (Tok.isAnnotation())
174 break;
175 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
176 if (!AttrName)
Alp Toker094e5212014-01-05 03:27:11 +0000177 break;
178
Steve Naroff0f2fe172007-06-01 17:11:19 +0000179 SourceLocation AttrNameLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000180
Alp Toker094e5212014-01-05 03:27:11 +0000181 if (Tok.isNot(tok::l_paren)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000182 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000183 ParsedAttr::AS_GNU);
Alp Toker094e5212014-01-05 03:27:11 +0000184 continue;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000185 }
Alp Toker094e5212014-01-05 03:27:11 +0000186
187 // Handle "parameterized" attributes
188 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000189 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
Erich Keanee891aa92018-07-13 15:07:47 +0000190 SourceLocation(), ParsedAttr::AS_GNU, D);
Alp Toker094e5212014-01-05 03:27:11 +0000191 continue;
192 }
193
194 // Handle attributes with arguments that require late parsing.
195 LateParsedAttribute *LA =
196 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
197 LateAttrs->push_back(LA);
198
199 // Attributes in a class are parsed at the end of the class, along
200 // with other late-parsed declarations.
201 if (!ClassStack.empty() && !LateAttrs->parseSoon())
202 getCurrentClass().LateParsedDeclarations.push_back(LA);
203
George Burgess IVc8b95372017-01-04 22:43:01 +0000204 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
205 // recursively consumes balanced parens.
206 LA->Toks.push_back(Tok);
207 ConsumeParen();
208 // Consume everything up to and including the matching right parens.
209 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
Alp Toker094e5212014-01-05 03:27:11 +0000210
211 Token Eof;
212 Eof.startToken();
213 Eof.setLocation(Tok.getLocation());
214 LA->Toks.push_back(Eof);
Aaron Ballman7a899092019-06-18 12:57:05 +0000215 } while (Tok.is(tok::comma));
Alp Toker094e5212014-01-05 03:27:11 +0000216
Alp Toker383d2c42014-01-01 03:08:43 +0000217 if (ExpectAndConsume(tok::r_paren))
Alexey Bataevee6507d2013-11-18 08:17:37 +0000218 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000219 SourceLocation Loc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000220 if (ExpectAndConsume(tok::r_paren))
Alexey Bataevee6507d2013-11-18 08:17:37 +0000221 SkipUntil(tok::r_paren, StopAtSemi);
John McCall53fa7142010-12-24 02:08:15 +0000222 if (endLoc)
223 *endLoc = Loc;
Leonard Chanc72aaf62019-05-07 03:20:17 +0000224
225 // If this was declared in a macro, attach the macro IdentifierInfo to the
226 // parsed attribute.
Leonard Chan69aec052019-05-12 21:50:01 +0000227 auto &SM = PP.getSourceManager();
228 if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
229 FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
Leonard Chanc72aaf62019-05-07 03:20:17 +0000230 CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
231 StringRef FoundName =
232 Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
233 IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
234
235 for (unsigned i = OldNumAttrs; i < attrs.size(); ++i)
236 attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
237
238 if (LateAttrs) {
239 for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); ++i)
240 (*LateAttrs)[i]->MacroII = MacroII;
241 }
242 }
Steve Naroff0f2fe172007-06-01 17:11:19 +0000243 }
Steve Naroff0f2fe172007-06-01 17:11:19 +0000244}
Chris Lattnerf5fbd792006-08-10 23:56:11 +0000245
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000246/// Determine whether the given attribute has an identifier argument.
Aaron Ballman4768b312013-11-04 12:55:56 +0000247static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000248#define CLANG_ATTR_IDENTIFIER_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000249 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000250#include "clang/Parse/AttrParserStringSwitches.inc"
Douglas Gregord2472d42013-05-02 23:25:32 +0000251 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000252#undef CLANG_ATTR_IDENTIFIER_ARG_LIST
Douglas Gregord2472d42013-05-02 23:25:32 +0000253}
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000254
Erich Keane3efe0022018-07-20 14:13:28 +0000255/// Determine whether the given attribute has a variadic identifier argument.
256static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
257#define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
258 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
259#include "clang/Parse/AttrParserStringSwitches.inc"
260 .Default(false);
261#undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
262}
263
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000264/// Determine whether the given attribute treats kw_this as an identifier.
265static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II) {
266#define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
267 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
268#include "clang/Parse/AttrParserStringSwitches.inc"
269 .Default(false);
270#undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
271}
272
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000273/// Determine whether the given attribute parses a type argument.
Aaron Ballman4768b312013-11-04 12:55:56 +0000274static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000275#define CLANG_ATTR_TYPE_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000276 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000277#include "clang/Parse/AttrParserStringSwitches.inc"
Aaron Ballman4768b312013-11-04 12:55:56 +0000278 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000279#undef CLANG_ATTR_TYPE_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000280}
281
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000282/// Determine whether the given attribute requires parsing its arguments
Aaron Ballman15b27b92014-01-09 19:39:35 +0000283/// in an unevaluated context or not.
284static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000285#define CLANG_ATTR_ARG_CONTEXT_LIST
Aaron Ballman15b27b92014-01-09 19:39:35 +0000286 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000287#include "clang/Parse/AttrParserStringSwitches.inc"
Aaron Ballman15b27b92014-01-09 19:39:35 +0000288 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000289#undef CLANG_ATTR_ARG_CONTEXT_LIST
Aaron Ballman15b27b92014-01-09 19:39:35 +0000290}
291
Richard Smithfeefaf52013-09-03 18:01:40 +0000292IdentifierLoc *Parser::ParseIdentifierLoc() {
293 assert(Tok.is(tok::identifier) && "expected an identifier");
294 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
295 Tok.getLocation(),
296 Tok.getIdentifierInfo());
297 ConsumeToken();
298 return IL;
299}
300
Richard Smithb1f9a282013-10-31 01:56:18 +0000301void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
302 SourceLocation AttrNameLoc,
303 ParsedAttributes &Attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000304 SourceLocation *EndLoc,
305 IdentifierInfo *ScopeName,
306 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000307 ParsedAttr::Syntax Syntax) {
Richard Smithb1f9a282013-10-31 01:56:18 +0000308 BalancedDelimiterTracker Parens(*this, tok::l_paren);
309 Parens.consumeOpen();
310
311 TypeResult T;
312 if (Tok.isNot(tok::r_paren))
313 T = ParseTypeName();
314
315 if (Parens.consumeClose())
316 return;
317
318 if (T.isInvalid())
319 return;
320
321 if (T.isUsable())
322 Attrs.addNewTypeAttr(&AttrName,
Craig Topper161e4db2014-05-21 06:02:52 +0000323 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000324 ScopeName, ScopeLoc, T.get(), Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000325 else
326 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000327 ScopeName, ScopeLoc, nullptr, 0, Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000328}
329
Aaron Ballman35f94212014-04-14 16:03:22 +0000330unsigned Parser::ParseAttributeArgsCommon(
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000331 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
332 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +0000333 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000334 // Ignore the left paren location for now.
335 ConsumeParen();
336
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000337 bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
338
339 // Interpret "kw_this" as an identifier if the attributed requests it.
340 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
341 Tok.setKind(tok::identifier);
342
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000343 ArgsVector ArgExprs;
344 if (Tok.is(tok::identifier)) {
345 // If this attribute wants an 'identifier' argument, make it so.
Erich Keane3efe0022018-07-20 14:13:28 +0000346 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
347 attributeHasVariadicIdentifierArg(*AttrName);
Erich Keanee891aa92018-07-13 15:07:47 +0000348 ParsedAttr::Kind AttrKind =
349 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000350
351 // If we don't know how to parse this attribute, but this is the only
352 // token in this argument, assume it's meant to be an identifier.
Erich Keanee891aa92018-07-13 15:07:47 +0000353 if (AttrKind == ParsedAttr::UnknownAttribute ||
354 AttrKind == ParsedAttr::IgnoredAttribute) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000355 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000356 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000357 }
358
359 if (IsIdentifierArg)
360 ArgExprs.push_back(ParseIdentifierLoc());
361 }
362
363 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
364 // Eat the comma.
365 if (!ArgExprs.empty())
366 ConsumeToken();
367
368 // Parse the non-empty comma-separated list of expressions.
369 do {
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000370 // Interpret "kw_this" as an identifier if the attributed requests it.
371 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
372 Tok.setKind(tok::identifier);
373
Erich Keane3efe0022018-07-20 14:13:28 +0000374 ExprResult ArgExpr;
375 if (Tok.is(tok::identifier) &&
376 attributeHasVariadicIdentifierArg(*AttrName)) {
377 ArgExprs.push_back(ParseIdentifierLoc());
378 } else {
379 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
380 EnterExpressionEvaluationContext Unevaluated(
381 Actions,
382 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
383 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000384
Erich Keane3efe0022018-07-20 14:13:28 +0000385 ExprResult ArgExpr(
386 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
387 if (ArgExpr.isInvalid()) {
388 SkipUntil(tok::r_paren, StopAtSemi);
389 return 0;
390 }
391 ArgExprs.push_back(ArgExpr.get());
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000392 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000393 // Eat the comma, move to the next argument
394 } while (TryConsumeToken(tok::comma));
395 }
396
397 SourceLocation RParen = Tok.getLocation();
398 if (!ExpectAndConsume(tok::r_paren)) {
399 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
400 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
401 ArgExprs.data(), ArgExprs.size(), Syntax);
402 }
403
404 if (EndLoc)
405 *EndLoc = RParen;
Aaron Ballman35f94212014-04-14 16:03:22 +0000406
407 return static_cast<unsigned>(ArgExprs.size());
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000408}
409
Michael Han23214e52012-10-03 01:56:22 +0000410/// Parse the arguments to a parameterized GNU attribute or
411/// a C++11 attribute in "gnu" namespace.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000412void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
413 SourceLocation AttrNameLoc,
414 ParsedAttributes &Attrs,
Michael Han23214e52012-10-03 01:56:22 +0000415 SourceLocation *EndLoc,
416 IdentifierInfo *ScopeName,
417 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000418 ParsedAttr::Syntax Syntax,
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000419 Declarator *D) {
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000420
421 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
422
Erich Keanee891aa92018-07-13 15:07:47 +0000423 ParsedAttr::Kind AttrKind =
424 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Richard Smith66e71682013-10-24 01:07:54 +0000425
Erich Keanee891aa92018-07-13 15:07:47 +0000426 if (AttrKind == ParsedAttr::AT_Availability) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000427 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
428 ScopeLoc, Syntax);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000429 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000430 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000431 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
432 ScopeName, ScopeLoc, Syntax);
433 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000434 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000435 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
436 ScopeName, ScopeLoc, Syntax);
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +0000437 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000438 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000439 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
440 ScopeName, ScopeLoc, Syntax);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000441 return;
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000442 } else if (attributeIsTypeArgAttr(*AttrName)) {
443 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
444 ScopeLoc, Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000445 return;
446 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000447
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000448 // These may refer to the function arguments, but need to be parsed early to
449 // participate in determining whether it's a redeclaration.
George Burgess IVa19ea342016-11-10 20:43:52 +0000450 llvm::Optional<ParseScope> PrototypeScope;
Ulrich Weigandef5aa292015-07-13 14:13:01 +0000451 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
452 D && D->isFunctionDeclarator()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000453 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
George Burgess IVa19ea342016-11-10 20:43:52 +0000454 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
455 Scope::FunctionDeclarationScope |
456 Scope::DeclScope);
Alp Tokerc5350722014-02-26 22:27:52 +0000457 for (unsigned i = 0; i != FTI.NumParams; ++i) {
458 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000459 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
460 }
461 }
462
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000463 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
464 ScopeLoc, Syntax);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000465}
466
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000467unsigned Parser::ParseClangAttributeArgs(
468 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
469 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +0000470 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000471 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
472
Erich Keanee891aa92018-07-13 15:07:47 +0000473 ParsedAttr::Kind AttrKind =
474 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000475
Aaron Ballman38bbc162018-02-24 17:16:42 +0000476 switch (AttrKind) {
477 default:
478 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
479 ScopeName, ScopeLoc, Syntax);
Erich Keanee891aa92018-07-13 15:07:47 +0000480 case ParsedAttr::AT_ExternalSourceSymbol:
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000481 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
482 ScopeName, ScopeLoc, Syntax);
Aaron Ballman38bbc162018-02-24 17:16:42 +0000483 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000484 case ParsedAttr::AT_Availability:
Aaron Ballman38bbc162018-02-24 17:16:42 +0000485 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
486 ScopeLoc, Syntax);
487 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000488 case ParsedAttr::AT_ObjCBridgeRelated:
Aaron Ballmanc248b0f2018-02-24 17:37:37 +0000489 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
490 ScopeName, ScopeLoc, Syntax);
491 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000492 case ParsedAttr::AT_TypeTagForDatatype:
Aaron Ballmana26d8ee2018-02-25 14:01:04 +0000493 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
494 ScopeName, ScopeLoc, Syntax);
495 break;
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000496 }
Erich Keanec480f302018-07-12 21:09:05 +0000497 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000498}
499
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000500bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
501 SourceLocation AttrNameLoc,
502 ParsedAttributes &Attrs) {
503 // If the attribute isn't known, we will not attempt to parse any
504 // arguments.
505 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
Bob Wilson7c730832015-07-20 22:57:31 +0000506 getTargetInfo(), getLangOpts())) {
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000507 // Eat the left paren, then skip to the ending right paren.
508 ConsumeParen();
509 SkipUntil(tok::r_paren);
510 return false;
Aaron Ballman478faed2012-06-19 22:09:27 +0000511 }
Aaron Ballman478faed2012-06-19 22:09:27 +0000512
Aaron Ballman95d57032014-04-14 16:44:26 +0000513 SourceLocation OpenParenLoc = Tok.getLocation();
514
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000515 if (AttrName->getName() == "property") {
Aaron Ballman478faed2012-06-19 22:09:27 +0000516 // The property declspec is more complex in that it can take one or two
Chad Rosierc1183952012-06-26 22:30:43 +0000517 // assignment expressions as a parameter, but the lhs of the assignment
Aaron Ballman478faed2012-06-19 22:09:27 +0000518 // must be named get or put.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000519
John McCall5e77d762013-04-16 07:28:30 +0000520 BalancedDelimiterTracker T(*this, tok::l_paren);
521 T.expectAndConsume(diag::err_expected_lparen_after,
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000522 AttrName->getNameStart(), tok::r_paren);
John McCall5e77d762013-04-16 07:28:30 +0000523
524 enum AccessorKind {
525 AK_Invalid = -1,
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000526 AK_Put = 0,
527 AK_Get = 1 // indices into AccessorNames
John McCall5e77d762013-04-16 07:28:30 +0000528 };
Craig Topper161e4db2014-05-21 06:02:52 +0000529 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
John McCall5e77d762013-04-16 07:28:30 +0000530 bool HasInvalidAccessor = false;
531
532 // Parse the accessor specifications.
533 while (true) {
534 // Stop if this doesn't look like an accessor spec.
535 if (!Tok.is(tok::identifier)) {
536 // If the user wrote a completely empty list, use a special diagnostic.
537 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
Craig Topper161e4db2014-05-21 06:02:52 +0000538 AccessorNames[AK_Put] == nullptr &&
539 AccessorNames[AK_Get] == nullptr) {
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000540 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
John McCall5e77d762013-04-16 07:28:30 +0000541 break;
542 }
543
544 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
545 break;
546 }
547
548 AccessorKind Kind;
549 SourceLocation KindLoc = Tok.getLocation();
550 StringRef KindStr = Tok.getIdentifierInfo()->getName();
551 if (KindStr == "get") {
552 Kind = AK_Get;
553 } else if (KindStr == "put") {
554 Kind = AK_Put;
555
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000556 // Recover from the common mistake of using 'set' instead of 'put'.
John McCall5e77d762013-04-16 07:28:30 +0000557 } else if (KindStr == "set") {
558 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000559 << FixItHint::CreateReplacement(KindLoc, "put");
John McCall5e77d762013-04-16 07:28:30 +0000560 Kind = AK_Put;
561
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000562 // Handle the mistake of forgetting the accessor kind by skipping
563 // this accessor.
John McCall5e77d762013-04-16 07:28:30 +0000564 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
565 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
566 ConsumeToken();
567 HasInvalidAccessor = true;
568 goto next_property_accessor;
569
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000570 // Otherwise, complain about the unknown accessor kind.
John McCall5e77d762013-04-16 07:28:30 +0000571 } else {
572 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
573 HasInvalidAccessor = true;
574 Kind = AK_Invalid;
575
576 // Try to keep parsing unless it doesn't look like an accessor spec.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000577 if (!NextToken().is(tok::equal))
578 break;
John McCall5e77d762013-04-16 07:28:30 +0000579 }
580
581 // Consume the identifier.
582 ConsumeToken();
583
584 // Consume the '='.
Alp Toker8fbec672013-12-17 23:29:36 +0000585 if (!TryConsumeToken(tok::equal)) {
John McCall5e77d762013-04-16 07:28:30 +0000586 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000587 << KindStr;
John McCall5e77d762013-04-16 07:28:30 +0000588 break;
589 }
590
591 // Expect the method name.
592 if (!Tok.is(tok::identifier)) {
593 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
594 break;
595 }
596
597 if (Kind == AK_Invalid) {
598 // Just drop invalid accessors.
Craig Topper161e4db2014-05-21 06:02:52 +0000599 } else if (AccessorNames[Kind] != nullptr) {
John McCall5e77d762013-04-16 07:28:30 +0000600 // Complain about the repeated accessor, ignore it, and keep parsing.
601 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
602 } else {
603 AccessorNames[Kind] = Tok.getIdentifierInfo();
604 }
605 ConsumeToken();
606
607 next_property_accessor:
608 // Keep processing accessors until we run out.
Alp Toker094e5212014-01-05 03:27:11 +0000609 if (TryConsumeToken(tok::comma))
John McCall5e77d762013-04-16 07:28:30 +0000610 continue;
611
612 // If we run into the ')', stop without consuming it.
Alp Toker094e5212014-01-05 03:27:11 +0000613 if (Tok.is(tok::r_paren))
John McCall5e77d762013-04-16 07:28:30 +0000614 break;
Alp Toker094e5212014-01-05 03:27:11 +0000615
616 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
617 break;
John McCall5e77d762013-04-16 07:28:30 +0000618 }
619
620 // Only add the property attribute if it was well-formed.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000621 if (!HasInvalidAccessor)
Craig Topper161e4db2014-05-21 06:02:52 +0000622 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
John McCall5e77d762013-04-16 07:28:30 +0000623 AccessorNames[AK_Get], AccessorNames[AK_Put],
Erich Keanee891aa92018-07-13 15:07:47 +0000624 ParsedAttr::AS_Declspec);
Aaron Ballman478faed2012-06-19 22:09:27 +0000625 T.skipToEnd();
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000626 return !HasInvalidAccessor;
Aaron Ballman478faed2012-06-19 22:09:27 +0000627 }
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000628
Aaron Ballman95d57032014-04-14 16:44:26 +0000629 unsigned NumArgs =
630 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
Erich Keanee891aa92018-07-13 15:07:47 +0000631 SourceLocation(), ParsedAttr::AS_Declspec);
Aaron Ballman95d57032014-04-14 16:44:26 +0000632
633 // If this attribute's args were parsed, and it was expected to have
634 // arguments but none were provided, emit a diagnostic.
Erich Keanec480f302018-07-12 21:09:05 +0000635 if (!Attrs.empty() && Attrs.begin()->getMaxArgs() && !NumArgs) {
Aaron Ballmanef5d94c2014-04-15 00:36:39 +0000636 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Aaron Ballman95d57032014-04-14 16:44:26 +0000637 return false;
638 }
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000639 return true;
Aaron Ballman478faed2012-06-19 22:09:27 +0000640}
641
Eli Friedman06de2b52009-06-08 07:21:15 +0000642/// [MS] decl-specifier:
643/// __declspec ( extended-decl-modifier-seq )
644///
645/// [MS] extended-decl-modifier-seq:
646/// extended-decl-modifier[opt]
647/// extended-decl-modifier extended-decl-modifier-seq
Aaron Ballman068aa512015-05-20 20:58:33 +0000648void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
649 SourceLocation *End) {
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +0000650 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
Steve Naroff3a9b7e02008-12-24 20:59:21 +0000651 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
Eli Friedman06de2b52009-06-08 07:21:15 +0000652
Aaron Ballman068aa512015-05-20 20:58:33 +0000653 while (Tok.is(tok::kw___declspec)) {
654 ConsumeToken();
655 BalancedDelimiterTracker T(*this, tok::l_paren);
656 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
657 tok::r_paren))
Aaron Ballman478faed2012-06-19 22:09:27 +0000658 return;
Aaron Ballman478faed2012-06-19 22:09:27 +0000659
Aaron Ballman068aa512015-05-20 20:58:33 +0000660 // An empty declspec is perfectly legal and should not warn. Additionally,
661 // you can specify multiple attributes per declspec.
662 while (Tok.isNot(tok::r_paren)) {
663 // Attribute not present.
664 if (TryConsumeToken(tok::comma))
665 continue;
666
667 // We expect either a well-known identifier or a generic string. Anything
668 // else is a malformed declspec.
669 bool IsString = Tok.getKind() == tok::string_literal;
670 if (!IsString && Tok.getKind() != tok::identifier &&
671 Tok.getKind() != tok::kw_restrict) {
672 Diag(Tok, diag::err_ms_declspec_type);
Aaron Ballman478faed2012-06-19 22:09:27 +0000673 T.skipToEnd();
674 return;
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000675 }
Aaron Ballman068aa512015-05-20 20:58:33 +0000676
677 IdentifierInfo *AttrName;
678 SourceLocation AttrNameLoc;
679 if (IsString) {
680 SmallString<8> StrBuffer;
681 bool Invalid = false;
682 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
683 if (Invalid) {
684 T.skipToEnd();
685 return;
686 }
687 AttrName = PP.getIdentifierInfo(Str);
688 AttrNameLoc = ConsumeStringToken();
689 } else {
690 AttrName = Tok.getIdentifierInfo();
691 AttrNameLoc = ConsumeToken();
692 }
693
694 bool AttrHandled = false;
695
696 // Parse attribute arguments.
697 if (Tok.is(tok::l_paren))
698 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
699 else if (AttrName->getName() == "property")
700 // The property attribute must have an argument list.
701 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
702 << AttrName->getName();
703
704 if (!AttrHandled)
705 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000706 ParsedAttr::AS_Declspec);
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000707 }
Aaron Ballman068aa512015-05-20 20:58:33 +0000708 T.consumeClose();
709 if (End)
710 *End = T.getCloseLocation();
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000711 }
Eli Friedman53339e02009-06-08 23:27:34 +0000712}
713
John McCall53fa7142010-12-24 02:08:15 +0000714void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
Eli Friedman53339e02009-06-08 23:27:34 +0000715 // Treat these like attributes
Reid Klecknerd7857f02014-10-24 17:42:17 +0000716 while (true) {
717 switch (Tok.getKind()) {
718 case tok::kw___fastcall:
719 case tok::kw___stdcall:
720 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +0000721 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +0000722 case tok::kw___cdecl:
723 case tok::kw___vectorcall:
724 case tok::kw___ptr64:
725 case tok::kw___w64:
726 case tok::kw___ptr32:
Reid Klecknerd7857f02014-10-24 17:42:17 +0000727 case tok::kw___sptr:
728 case tok::kw___uptr: {
729 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
730 SourceLocation AttrNameLoc = ConsumeToken();
731 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000732 ParsedAttr::AS_Keyword);
Reid Klecknerd7857f02014-10-24 17:42:17 +0000733 break;
734 }
735 default:
736 return;
737 }
Eli Friedman53339e02009-06-08 23:27:34 +0000738 }
Steve Naroff3a9b7e02008-12-24 20:59:21 +0000739}
740
Nico Rieckeaaae272014-12-04 23:31:08 +0000741void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
742 SourceLocation StartLoc = Tok.getLocation();
743 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
744
745 if (EndLoc.isValid()) {
746 SourceRange Range(StartLoc, EndLoc);
747 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
748 }
749}
750
751SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
752 SourceLocation EndLoc;
753
754 while (true) {
755 switch (Tok.getKind()) {
756 case tok::kw_const:
757 case tok::kw_volatile:
758 case tok::kw___fastcall:
759 case tok::kw___stdcall:
760 case tok::kw___thiscall:
761 case tok::kw___cdecl:
762 case tok::kw___vectorcall:
763 case tok::kw___ptr32:
764 case tok::kw___ptr64:
765 case tok::kw___w64:
766 case tok::kw___unaligned:
767 case tok::kw___sptr:
768 case tok::kw___uptr:
769 EndLoc = ConsumeToken();
770 break;
771 default:
772 return EndLoc;
773 }
774 }
775}
776
John McCall53fa7142010-12-24 02:08:15 +0000777void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
Dawn Perchik335e16b2010-09-03 01:29:35 +0000778 // Treat these like attributes
779 while (Tok.is(tok::kw___pascal)) {
780 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
781 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000782 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000783 ParsedAttr::AS_Keyword);
Dawn Perchik335e16b2010-09-03 01:29:35 +0000784 }
John McCall53fa7142010-12-24 02:08:15 +0000785}
786
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +0000787void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000788 // Treat these like attributes
789 while (Tok.is(tok::kw___kernel)) {
Richard Smith0cdcc982013-01-29 01:24:26 +0000790 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000791 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000792 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000793 ParsedAttr::AS_Keyword);
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000794 }
795}
796
Aaron Ballman05d76ea2014-01-14 01:29:54 +0000797void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
798 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
799 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +0000800 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000801 ParsedAttr::AS_Keyword);
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000802}
803
Douglas Gregor261a89b2015-06-19 17:51:05 +0000804void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
805 // Treat these like attributes, even though they're type specifiers.
806 while (true) {
807 switch (Tok.getKind()) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +0000808 case tok::kw__Nonnull:
809 case tok::kw__Nullable:
810 case tok::kw__Null_unspecified: {
Douglas Gregor261a89b2015-06-19 17:51:05 +0000811 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
812 SourceLocation AttrNameLoc = ConsumeToken();
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000813 if (!getLangOpts().ObjC)
Douglas Gregor261a89b2015-06-19 17:51:05 +0000814 Diag(AttrNameLoc, diag::ext_nullability)
815 << AttrName;
Fangrui Song6907ce22018-07-30 19:24:48 +0000816 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000817 ParsedAttr::AS_Keyword);
Douglas Gregor261a89b2015-06-19 17:51:05 +0000818 break;
819 }
820 default:
821 return;
822 }
823 }
824}
825
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000826static bool VersionNumberSeparator(const char Separator) {
827 return (Separator == '.' || Separator == '_');
828}
829
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000830/// Parse a version number.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000831///
832/// version:
833/// simple-integer
Jan Korous23255692018-05-17 11:51:49 +0000834/// simple-integer '.' simple-integer
835/// simple-integer '_' simple-integer
836/// simple-integer '.' simple-integer '.' simple-integer
837/// simple-integer '_' simple-integer '_' simple-integer
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000838VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
Erik Pilkington29099de2016-07-16 00:35:23 +0000839 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000840
841 if (!Tok.is(tok::numeric_constant)) {
842 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000843 SkipUntil(tok::comma, tok::r_paren,
844 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000845 return VersionTuple();
846 }
847
848 // Parse the major (and possibly minor and subminor) versions, which
849 // are stored in the numeric constant. We utilize a quirk of the
850 // lexer, which is that it handles something like 1.2.3 as a single
851 // numeric constant, rather than two separate tokens.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000852 SmallString<512> Buffer;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000853 Buffer.resize(Tok.getLength()+1);
854 const char *ThisTokBegin = &Buffer[0];
855
856 // Get the spelling of the token, which eliminates trigraphs, etc.
857 bool Invalid = false;
858 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
859 if (Invalid)
860 return VersionTuple();
861
862 // Parse the major version.
863 unsigned AfterMajor = 0;
864 unsigned Major = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000865 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000866 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
867 ++AfterMajor;
868 }
869
870 if (AfterMajor == 0) {
871 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000872 SkipUntil(tok::comma, tok::r_paren,
873 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000874 return VersionTuple();
875 }
876
877 if (AfterMajor == ActualLength) {
878 ConsumeToken();
879
880 // We only had a single version component.
881 if (Major == 0) {
882 Diag(Tok, diag::err_zero_version);
883 return VersionTuple();
884 }
885
886 return VersionTuple(Major);
887 }
888
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000889 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
890 if (!VersionNumberSeparator(AfterMajorSeparator)
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000891 || (AfterMajor + 1 == ActualLength)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000892 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000893 SkipUntil(tok::comma, tok::r_paren,
894 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000895 return VersionTuple();
896 }
897
898 // Parse the minor version.
899 unsigned AfterMinor = AfterMajor + 1;
900 unsigned Minor = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000901 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000902 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
903 ++AfterMinor;
904 }
905
906 if (AfterMinor == ActualLength) {
907 ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +0000908
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000909 // We had major.minor.
910 if (Major == 0 && Minor == 0) {
911 Diag(Tok, diag::err_zero_version);
912 return VersionTuple();
913 }
914
Jan Korous23255692018-05-17 11:51:49 +0000915 return VersionTuple(Major, Minor);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000916 }
917
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000918 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000919 // If what follows is not a '.' or '_', we have a problem.
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000920 if (!VersionNumberSeparator(AfterMinorSeparator)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000921 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000922 SkipUntil(tok::comma, tok::r_paren,
923 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Chad Rosierc1183952012-06-26 22:30:43 +0000924 return VersionTuple();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000925 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000926
Fariborz Jahanianb6161612014-10-03 17:21:12 +0000927 // Warn if separators, be it '.' or '_', do not match.
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000928 if (AfterMajorSeparator != AfterMinorSeparator)
929 Diag(Tok, diag::warn_expected_consistent_version_separator);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000930
931 // Parse the subminor version.
932 unsigned AfterSubminor = AfterMinor + 1;
933 unsigned Subminor = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000934 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000935 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
936 ++AfterSubminor;
937 }
938
939 if (AfterSubminor != ActualLength) {
940 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000941 SkipUntil(tok::comma, tok::r_paren,
942 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000943 return VersionTuple();
944 }
945 ConsumeToken();
Jan Korous23255692018-05-17 11:51:49 +0000946 return VersionTuple(Major, Minor, Subminor);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000947}
948
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000949/// Parse the contents of the "availability" attribute.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000950///
951/// availability-attribute:
Manman Ren75bc6762016-03-21 17:30:55 +0000952/// 'availability' '(' platform ',' opt-strict version-arg-list,
953/// opt-replacement, opt-message')'
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000954///
955/// platform:
956/// identifier
957///
Manman Rend8039df2016-02-22 04:47:24 +0000958/// opt-strict:
959/// 'strict' ','
Manman Renb636b902016-02-17 22:05:48 +0000960///
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000961/// version-arg-list:
962/// version-arg
963/// version-arg ',' version-arg-list
964///
965/// version-arg:
966/// 'introduced' '=' version
967/// 'deprecated' '=' version
Douglas Gregorfdd417f2012-03-11 04:53:21 +0000968/// 'obsoleted' = version
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000969/// 'unavailable'
Manman Ren75bc6762016-03-21 17:30:55 +0000970/// opt-replacement:
971/// 'replacement' '=' <string>
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000972/// opt-message:
973/// 'message' '=' <string>
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000974void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
975 SourceLocation AvailabilityLoc,
976 ParsedAttributes &attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000977 SourceLocation *endLoc,
978 IdentifierInfo *ScopeName,
979 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000980 ParsedAttr::Syntax Syntax) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000981 enum { Introduced, Deprecated, Obsoleted, Unknown };
982 AvailabilityChange Changes[Unknown];
Manman Ren75bc6762016-03-21 17:30:55 +0000983 ExprResult MessageExpr, ReplacementExpr;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000984
985 // Opening '('.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000986 BalancedDelimiterTracker T(*this, tok::l_paren);
987 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000988 Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000989 return;
990 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000991
Manman Renb636b902016-02-17 22:05:48 +0000992 // Parse the platform name.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000993 if (Tok.isNot(tok::identifier)) {
994 Diag(Tok, diag::err_availability_expected_platform);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000995 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000996 return;
997 }
Richard Smithfeefaf52013-09-03 18:01:40 +0000998 IdentifierLoc *Platform = ParseIdentifierLoc();
Alex Lorenz0b1ce8b2017-08-15 14:42:01 +0000999 if (const IdentifierInfo *const Ident = Platform->Ident) {
1000 // Canonicalize platform name from "macosx" to "macos".
1001 if (Ident->getName() == "macosx")
1002 Platform->Ident = PP.getIdentifierInfo("macos");
1003 // Canonicalize platform name from "macosx_app_extension" to
1004 // "macos_app_extension".
1005 else if (Ident->getName() == "macosx_app_extension")
1006 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1007 else
1008 Platform->Ident = PP.getIdentifierInfo(
1009 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1010 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001011
1012 // Parse the ',' following the platform name.
Alp Toker383d2c42014-01-01 03:08:43 +00001013 if (ExpectAndConsume(tok::comma)) {
1014 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001015 return;
Alp Toker383d2c42014-01-01 03:08:43 +00001016 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001017
1018 // If we haven't grabbed the pointers for the identifiers
1019 // "introduced", "deprecated", and "obsoleted", do so now.
1020 if (!Ident_introduced) {
1021 Ident_introduced = PP.getIdentifierInfo("introduced");
1022 Ident_deprecated = PP.getIdentifierInfo("deprecated");
1023 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001024 Ident_unavailable = PP.getIdentifierInfo("unavailable");
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001025 Ident_message = PP.getIdentifierInfo("message");
Manman Rend8039df2016-02-22 04:47:24 +00001026 Ident_strict = PP.getIdentifierInfo("strict");
Manman Ren75bc6762016-03-21 17:30:55 +00001027 Ident_replacement = PP.getIdentifierInfo("replacement");
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001028 }
1029
Manman Ren75bc6762016-03-21 17:30:55 +00001030 // Parse the optional "strict", the optional "replacement" and the set of
Manman Renb636b902016-02-17 22:05:48 +00001031 // introductions/deprecations/removals.
Manman Rend8039df2016-02-22 04:47:24 +00001032 SourceLocation UnavailableLoc, StrictLoc;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001033 do {
1034 if (Tok.isNot(tok::identifier)) {
1035 Diag(Tok, diag::err_availability_expected_change);
Alexey Bataevee6507d2013-11-18 08:17:37 +00001036 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001037 return;
1038 }
1039 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1040 SourceLocation KeywordLoc = ConsumeToken();
1041
Manman Rend8039df2016-02-22 04:47:24 +00001042 if (Keyword == Ident_strict) {
1043 if (StrictLoc.isValid()) {
Manman Renb636b902016-02-17 22:05:48 +00001044 Diag(KeywordLoc, diag::err_availability_redundant)
Manman Rend8039df2016-02-22 04:47:24 +00001045 << Keyword << SourceRange(StrictLoc);
Manman Renb636b902016-02-17 22:05:48 +00001046 }
Manman Rend8039df2016-02-22 04:47:24 +00001047 StrictLoc = KeywordLoc;
Manman Renb636b902016-02-17 22:05:48 +00001048 continue;
1049 }
1050
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001051 if (Keyword == Ident_unavailable) {
1052 if (UnavailableLoc.isValid()) {
1053 Diag(KeywordLoc, diag::err_availability_redundant)
1054 << Keyword << SourceRange(UnavailableLoc);
Chad Rosierc1183952012-06-26 22:30:43 +00001055 }
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001056 UnavailableLoc = KeywordLoc;
Alp Toker97650562014-01-10 11:19:30 +00001057 continue;
Chad Rosierc1183952012-06-26 22:30:43 +00001058 }
1059
Michael Wu260e9622018-11-12 02:44:33 +00001060 if (Keyword == Ident_deprecated && Platform->Ident &&
1061 Platform->Ident->isStr("swift")) {
1062 // For swift, we deprecate for all versions.
1063 if (Changes[Deprecated].KeywordLoc.isValid()) {
1064 Diag(KeywordLoc, diag::err_availability_redundant)
1065 << Keyword
1066 << SourceRange(Changes[Deprecated].KeywordLoc);
1067 }
1068
1069 Changes[Deprecated].KeywordLoc = KeywordLoc;
1070 // Use a fake version here.
1071 Changes[Deprecated].Version = VersionTuple(1);
1072 continue;
1073 }
1074
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001075 if (Tok.isNot(tok::equal)) {
Alp Tokerec543272013-12-24 09:48:30 +00001076 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001077 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001078 return;
1079 }
1080 ConsumeToken();
Manman Ren75bc6762016-03-21 17:30:55 +00001081 if (Keyword == Ident_message || Keyword == Ident_replacement) {
David Majnemer2e498302014-07-18 05:43:12 +00001082 if (Tok.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001083 Diag(Tok, diag::err_expected_string_literal)
1084 << /*Source='availability attribute'*/2;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001085 SkipUntil(tok::r_paren, StopAtSemi);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001086 return;
1087 }
Manman Ren75bc6762016-03-21 17:30:55 +00001088 if (Keyword == Ident_message)
1089 MessageExpr = ParseStringLiteralExpression();
1090 else
1091 ReplacementExpr = ParseStringLiteralExpression();
David Majnemer2e498302014-07-18 05:43:12 +00001092 // Also reject wide string literals.
1093 if (StringLiteral *MessageStringLiteral =
1094 cast_or_null<StringLiteral>(MessageExpr.get())) {
1095 if (MessageStringLiteral->getCharByteWidth() != 1) {
1096 Diag(MessageStringLiteral->getSourceRange().getBegin(),
1097 diag::err_expected_string_literal)
1098 << /*Source='availability attribute'*/ 2;
1099 SkipUntil(tok::r_paren, StopAtSemi);
1100 return;
1101 }
1102 }
Manman Ren75bc6762016-03-21 17:30:55 +00001103 if (Keyword == Ident_message)
1104 break;
1105 else
1106 continue;
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001107 }
Chad Rosierc1183952012-06-26 22:30:43 +00001108
Fariborz Jahanian5a29e6a2014-11-05 23:58:55 +00001109 // Special handling of 'NA' only when applied to introduced or
1110 // deprecated.
1111 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1112 Tok.is(tok::identifier)) {
1113 IdentifierInfo *NA = Tok.getIdentifierInfo();
1114 if (NA->getName() == "NA") {
1115 ConsumeToken();
1116 if (Keyword == Ident_introduced)
1117 UnavailableLoc = KeywordLoc;
1118 continue;
1119 }
1120 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001121
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001122 SourceRange VersionRange;
1123 VersionTuple Version = ParseVersionTuple(VersionRange);
Chad Rosierc1183952012-06-26 22:30:43 +00001124
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001125 if (Version.empty()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001126 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001127 return;
1128 }
1129
1130 unsigned Index;
1131 if (Keyword == Ident_introduced)
1132 Index = Introduced;
1133 else if (Keyword == Ident_deprecated)
1134 Index = Deprecated;
1135 else if (Keyword == Ident_obsoleted)
1136 Index = Obsoleted;
Chad Rosierc1183952012-06-26 22:30:43 +00001137 else
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001138 Index = Unknown;
1139
1140 if (Index < Unknown) {
1141 if (!Changes[Index].KeywordLoc.isInvalid()) {
1142 Diag(KeywordLoc, diag::err_availability_redundant)
Chad Rosierc1183952012-06-26 22:30:43 +00001143 << Keyword
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001144 << SourceRange(Changes[Index].KeywordLoc,
1145 Changes[Index].VersionRange.getEnd());
1146 }
1147
1148 Changes[Index].KeywordLoc = KeywordLoc;
1149 Changes[Index].Version = Version;
1150 Changes[Index].VersionRange = VersionRange;
1151 } else {
1152 Diag(KeywordLoc, diag::err_availability_unknown_change)
1153 << Keyword << VersionRange;
1154 }
1155
Alp Toker97650562014-01-10 11:19:30 +00001156 } while (TryConsumeToken(tok::comma));
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001157
1158 // Closing ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001159 if (T.consumeClose())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001160 return;
1161
1162 if (endLoc)
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001163 *endLoc = T.getCloseLocation();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001164
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001165 // The 'unavailable' availability cannot be combined with any other
1166 // availability changes. Make sure that hasn't happened.
1167 if (UnavailableLoc.isValid()) {
1168 bool Complained = false;
1169 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1170 if (Changes[Index].KeywordLoc.isValid()) {
1171 if (!Complained) {
1172 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1173 << SourceRange(Changes[Index].KeywordLoc,
1174 Changes[Index].VersionRange.getEnd());
1175 Complained = true;
1176 }
1177
1178 // Clear out the availability.
1179 Changes[Index] = AvailabilityChange();
1180 }
1181 }
1182 }
1183
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001184 // Record this attribute
Chad Rosierc1183952012-06-26 22:30:43 +00001185 attrs.addNew(&Availability,
1186 SourceRange(AvailabilityLoc, T.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001187 ScopeName, ScopeLoc,
Aaron Ballman00e99962013-08-31 01:11:41 +00001188 Platform,
John McCall084e83d2011-03-24 11:26:52 +00001189 Changes[Introduced],
1190 Changes[Deprecated],
Chad Rosierc1183952012-06-26 22:30:43 +00001191 Changes[Obsoleted],
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001192 UnavailableLoc, MessageExpr.get(),
Manman Ren75bc6762016-03-21 17:30:55 +00001193 Syntax, StrictLoc, ReplacementExpr.get());
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001194}
1195
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001196/// Parse the contents of the "external_source_symbol" attribute.
Alex Lorenzd5d27e12017-03-01 18:06:25 +00001197///
1198/// external-source-symbol-attribute:
1199/// 'external_source_symbol' '(' keyword-arg-list ')'
1200///
1201/// keyword-arg-list:
1202/// keyword-arg
1203/// keyword-arg ',' keyword-arg-list
1204///
1205/// keyword-arg:
1206/// 'language' '=' <string>
1207/// 'defined_in' '=' <string>
1208/// 'generated_declaration'
1209void Parser::ParseExternalSourceSymbolAttribute(
1210 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1211 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +00001212 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00001213 // Opening '('.
1214 BalancedDelimiterTracker T(*this, tok::l_paren);
1215 if (T.expectAndConsume())
1216 return;
1217
1218 // Initialize the pointers for the keyword identifiers when required.
1219 if (!Ident_language) {
1220 Ident_language = PP.getIdentifierInfo("language");
1221 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1222 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1223 }
1224
1225 ExprResult Language;
1226 bool HasLanguage = false;
1227 ExprResult DefinedInExpr;
1228 bool HasDefinedIn = false;
1229 IdentifierLoc *GeneratedDeclaration = nullptr;
1230
1231 // Parse the language/defined_in/generated_declaration keywords
1232 do {
1233 if (Tok.isNot(tok::identifier)) {
1234 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1235 SkipUntil(tok::r_paren, StopAtSemi);
1236 return;
1237 }
1238
1239 SourceLocation KeywordLoc = Tok.getLocation();
1240 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1241 if (Keyword == Ident_generated_declaration) {
1242 if (GeneratedDeclaration) {
1243 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1244 SkipUntil(tok::r_paren, StopAtSemi);
1245 return;
1246 }
1247 GeneratedDeclaration = ParseIdentifierLoc();
1248 continue;
1249 }
1250
1251 if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1252 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1253 SkipUntil(tok::r_paren, StopAtSemi);
1254 return;
1255 }
1256
1257 ConsumeToken();
1258 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1259 Keyword->getName())) {
1260 SkipUntil(tok::r_paren, StopAtSemi);
1261 return;
1262 }
1263
1264 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1265 if (Keyword == Ident_language)
1266 HasLanguage = true;
1267 else
1268 HasDefinedIn = true;
1269
1270 if (Tok.isNot(tok::string_literal)) {
1271 Diag(Tok, diag::err_expected_string_literal)
1272 << /*Source='external_source_symbol attribute'*/ 3
1273 << /*language | source container*/ (Keyword != Ident_language);
1274 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1275 continue;
1276 }
1277 if (Keyword == Ident_language) {
1278 if (HadLanguage) {
1279 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1280 << Keyword;
1281 ParseStringLiteralExpression();
1282 continue;
1283 }
1284 Language = ParseStringLiteralExpression();
1285 } else {
1286 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1287 if (HadDefinedIn) {
1288 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1289 << Keyword;
1290 ParseStringLiteralExpression();
1291 continue;
1292 }
1293 DefinedInExpr = ParseStringLiteralExpression();
1294 }
1295 } while (TryConsumeToken(tok::comma));
1296
1297 // Closing ')'.
1298 if (T.consumeClose())
1299 return;
1300 if (EndLoc)
1301 *EndLoc = T.getCloseLocation();
1302
1303 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1304 GeneratedDeclaration};
1305 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1306 ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1307}
1308
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001309/// Parse the contents of the "objc_bridge_related" attribute.
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001310/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1311/// related_class:
1312/// Identifier
1313///
1314/// opt-class_method:
1315/// Identifier: | <empty>
1316///
1317/// opt-instance_method:
1318/// Identifier | <empty>
1319///
1320void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1321 SourceLocation ObjCBridgeRelatedLoc,
1322 ParsedAttributes &attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001323 SourceLocation *endLoc,
1324 IdentifierInfo *ScopeName,
1325 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001326 ParsedAttr::Syntax Syntax) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001327 // Opening '('.
1328 BalancedDelimiterTracker T(*this, tok::l_paren);
1329 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00001330 Diag(Tok, diag::err_expected) << tok::l_paren;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001331 return;
1332 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001333
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001334 // Parse the related class name.
1335 if (Tok.isNot(tok::identifier)) {
1336 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1337 SkipUntil(tok::r_paren, StopAtSemi);
1338 return;
1339 }
1340 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
Alp Toker97650562014-01-10 11:19:30 +00001341 if (ExpectAndConsume(tok::comma)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001342 SkipUntil(tok::r_paren, StopAtSemi);
1343 return;
1344 }
Alp Toker8fbec672013-12-17 23:29:36 +00001345
Aaron Ballman48a533d2018-02-27 23:49:28 +00001346 // Parse class method name. It's non-optional in the sense that a trailing
1347 // comma is required, but it can be the empty string, and then we record a
1348 // nullptr.
Craig Topper161e4db2014-05-21 06:02:52 +00001349 IdentifierLoc *ClassMethod = nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001350 if (Tok.is(tok::identifier)) {
1351 ClassMethod = ParseIdentifierLoc();
Alp Toker8fbec672013-12-17 23:29:36 +00001352 if (!TryConsumeToken(tok::colon)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001353 Diag(Tok, diag::err_objcbridge_related_selector_name);
1354 SkipUntil(tok::r_paren, StopAtSemi);
1355 return;
1356 }
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001357 }
Alp Toker8fbec672013-12-17 23:29:36 +00001358 if (!TryConsumeToken(tok::comma)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001359 if (Tok.is(tok::colon))
1360 Diag(Tok, diag::err_objcbridge_related_selector_name);
1361 else
Alp Tokerec543272013-12-24 09:48:30 +00001362 Diag(Tok, diag::err_expected) << tok::comma;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001363 SkipUntil(tok::r_paren, StopAtSemi);
1364 return;
1365 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001366
Aaron Ballman48a533d2018-02-27 23:49:28 +00001367 // Parse instance method name. Also non-optional but empty string is
1368 // permitted.
Craig Topper161e4db2014-05-21 06:02:52 +00001369 IdentifierLoc *InstanceMethod = nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001370 if (Tok.is(tok::identifier))
1371 InstanceMethod = ParseIdentifierLoc();
1372 else if (Tok.isNot(tok::r_paren)) {
Alp Tokerec543272013-12-24 09:48:30 +00001373 Diag(Tok, diag::err_expected) << tok::r_paren;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001374 SkipUntil(tok::r_paren, StopAtSemi);
1375 return;
1376 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001377
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001378 // Closing ')'.
1379 if (T.consumeClose())
1380 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001381
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001382 if (endLoc)
1383 *endLoc = T.getCloseLocation();
Fangrui Song6907ce22018-07-30 19:24:48 +00001384
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001385 // Record this attribute
1386 attrs.addNew(&ObjCBridgeRelated,
1387 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001388 ScopeName, ScopeLoc,
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001389 RelatedClass,
1390 ClassMethod,
1391 InstanceMethod,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001392 Syntax);
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001393}
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001394
Bill Wendling44426052012-12-20 19:22:21 +00001395// Late Parsed Attributes:
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001396// See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1397
1398void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1399
1400void Parser::LateParsedClass::ParseLexedAttributes() {
1401 Self->ParseLexedAttributes(*Class);
1402}
1403
1404void Parser::LateParsedAttribute::ParseLexedAttributes() {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001405 Self->ParseLexedAttribute(*this, true, false);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001406}
1407
1408/// Wrapper class which calls ParseLexedAttribute, after setting up the
1409/// scope appropriately.
1410void Parser::ParseLexedAttributes(ParsingClass &Class) {
1411 // Deal with templates
1412 // FIXME: Test cases to make sure this does the right thing for templates.
1413 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1414 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1415 HasTemplateScope);
1416 if (HasTemplateScope)
1417 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1418
Douglas Gregor3024f072012-04-16 07:05:22 +00001419 // Set or update the scope flags.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001420 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +00001421 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001422 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1423 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1424
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001425 // Enter the scope of nested classes
1426 if (!AlreadyHasClassScope)
1427 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1428 Class.TagOrTemplate);
Benjamin Kramer1d373c62012-05-17 12:01:52 +00001429 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001430 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1431 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1432 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001433 }
Chad Rosierc1183952012-06-26 22:30:43 +00001434
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001435 if (!AlreadyHasClassScope)
1436 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1437 Class.TagOrTemplate);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001438}
1439
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001440/// Parse all attributes in LAs, and attach them to Decl D.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001441void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1442 bool EnterScope, bool OnDefinition) {
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001443 assert(LAs.parseSoon() &&
1444 "Attribute list should be marked for immediate parsing.");
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001445 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
DeLesley Hutchins19c722d2012-08-15 22:41:04 +00001446 if (D)
1447 LAs[i]->addDecl(D);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001448 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
Benjamin Kramerbafc49a2012-04-14 12:44:47 +00001449 delete LAs[i];
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001450 }
1451 LAs.clear();
1452}
1453
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001454/// Finish parsing an attribute for which parsing was delayed.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001455/// This will be called at the end of parsing a class declaration
1456/// for each LateParsedAttribute. We consume the saved tokens and
Chad Rosierc1183952012-06-26 22:30:43 +00001457/// create an attribute with the arguments filled in. We add this
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001458/// to the Attribute list for the decl.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001459void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1460 bool EnterScope, bool OnDefinition) {
David Majnemerd5946f52015-01-13 08:35:24 +00001461 // Create a fake EOF so that attribute parsing won't go off the end of the
1462 // attribute.
1463 Token AttrEnd;
1464 AttrEnd.startToken();
1465 AttrEnd.setKind(tok::eof);
1466 AttrEnd.setLocation(Tok.getLocation());
1467 AttrEnd.setEofData(LA.Toks.data());
1468 LA.Toks.push_back(AttrEnd);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001469
1470 // Append the current token at the end of the new token stream so that it
1471 // doesn't get lost.
1472 LA.Toks.push_back(Tok);
Ilya Biryukov929af672019-05-17 09:32:05 +00001473 PP.EnterTokenStream(LA.Toks, true, /*IsReinject=*/true);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001474 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +00001475 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001476
1477 ParsedAttributes Attrs(AttrFactory);
1478 SourceLocation endLoc;
1479
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001480 if (LA.Decls.size() > 0) {
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001481 Decl *D = LA.Decls[0];
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001482 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1483 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001484
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001485 // Allow 'this' within late-parsed attributes.
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001486 Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
Richard Smithc3d2ebb2013-06-07 02:33:37 +00001487 ND && ND->isCXXInstanceMember());
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001488
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001489 if (LA.Decls.size() == 1) {
1490 // If the Decl is templatized, add template parameters to scope.
1491 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1492 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1493 if (HasTemplateScope)
1494 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001495
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001496 // If the Decl is on a function, add function parameters to the scope.
1497 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
Momchil Velikov57c681f2017-08-10 15:43:06 +00001498 ParseScope FnScope(
1499 this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
1500 HasFunScope);
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001501 if (HasFunScope)
1502 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001503
Michael Han23214e52012-10-03 01:56:22 +00001504 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001505 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
Craig Topper161e4db2014-05-21 06:02:52 +00001506 nullptr);
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001507
1508 if (HasFunScope) {
1509 Actions.ActOnExitFunctionContext();
1510 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1511 }
1512 if (HasTemplateScope) {
1513 TempScope.Exit();
1514 }
1515 } else {
1516 // If there are multiple decls, then the decl cannot be within the
1517 // function scope.
Michael Han23214e52012-10-03 01:56:22 +00001518 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001519 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
Craig Topper161e4db2014-05-21 06:02:52 +00001520 nullptr);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001521 }
DeLesley Hutchins71d61032012-03-02 22:29:50 +00001522 } else {
1523 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001524 }
1525
Erich Keanec480f302018-07-12 21:09:05 +00001526 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
1527 Attrs.begin()->isKnownToGCC())
Aaron Ballman9a99e0d2014-01-20 17:18:35 +00001528 Diag(Tok, diag::warn_attribute_on_function_definition)
1529 << &LA.AttrName;
1530
1531 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001532 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001533
David Majnemerd5946f52015-01-13 08:35:24 +00001534 // Due to a parsing error, we either went over the cached tokens or
1535 // there are still cached tokens left, so we skip the leftover tokens.
1536 while (Tok.isNot(tok::eof))
1537 ConsumeAnyToken();
1538
1539 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1540 ConsumeAnyToken();
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001541}
1542
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001543void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1544 SourceLocation AttrNameLoc,
1545 ParsedAttributes &Attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001546 SourceLocation *EndLoc,
1547 IdentifierInfo *ScopeName,
1548 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001549 ParsedAttr::Syntax Syntax) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001550 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1551
1552 BalancedDelimiterTracker T(*this, tok::l_paren);
1553 T.consumeOpen();
1554
1555 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001556 Diag(Tok, diag::err_expected) << tok::identifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001557 T.skipToEnd();
1558 return;
1559 }
Richard Smithfeefaf52013-09-03 18:01:40 +00001560 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001561
Alp Toker094e5212014-01-05 03:27:11 +00001562 if (ExpectAndConsume(tok::comma)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001563 T.skipToEnd();
1564 return;
1565 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001566
1567 SourceRange MatchingCTypeRange;
1568 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1569 if (MatchingCType.isInvalid()) {
1570 T.skipToEnd();
1571 return;
1572 }
1573
1574 bool LayoutCompatible = false;
1575 bool MustBeNull = false;
Alp Toker8fbec672013-12-17 23:29:36 +00001576 while (TryConsumeToken(tok::comma)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001577 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001578 Diag(Tok, diag::err_expected) << tok::identifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001579 T.skipToEnd();
1580 return;
1581 }
1582 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1583 if (Flag->isStr("layout_compatible"))
1584 LayoutCompatible = true;
1585 else if (Flag->isStr("must_be_null"))
1586 MustBeNull = true;
1587 else {
1588 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1589 T.skipToEnd();
1590 return;
1591 }
1592 ConsumeToken(); // consume flag
1593 }
1594
1595 if (!T.consumeClose()) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001596 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001597 ArgumentKind, MatchingCType.get(),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001598 LayoutCompatible, MustBeNull, Syntax);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001599 }
1600
1601 if (EndLoc)
1602 *EndLoc = T.getCloseLocation();
1603}
1604
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001605/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1606/// of a C++11 attribute-specifier in a location where an attribute is not
1607/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1608/// situation.
1609///
1610/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1611/// this doesn't appear to actually be an attribute-specifier, and the caller
1612/// should try to parse it.
1613bool Parser::DiagnoseProhibitedCXX11Attribute() {
1614 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1615
1616 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1617 case CAK_NotAttributeSpecifier:
1618 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1619 return false;
1620
1621 case CAK_InvalidAttributeSpecifier:
1622 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1623 return false;
1624
1625 case CAK_AttributeSpecifier:
1626 // Parse and discard the attributes.
1627 SourceLocation BeginLoc = ConsumeBracket();
1628 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001629 SkipUntil(tok::r_square);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001630 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1631 SourceLocation EndLoc = ConsumeBracket();
1632 Diag(BeginLoc, diag::err_attributes_not_allowed)
1633 << SourceRange(BeginLoc, EndLoc);
1634 return true;
1635 }
Chandler Carruthd8f7d382012-04-10 16:03:08 +00001636 llvm_unreachable("All cases handled above.");
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001637}
1638
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001639/// We have found the opening square brackets of a C++11
Richard Smith98155ad2013-02-20 01:17:14 +00001640/// attribute-specifier in a location where an attribute is not permitted, but
1641/// we know where the attributes ought to be written. Parse them anyway, and
1642/// provide a fixit moving them to the right place.
Richard Smith4c96e992013-02-19 23:47:15 +00001643void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1644 SourceLocation CorrectLocation) {
1645 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1646 Tok.is(tok::kw_alignas));
1647
1648 // Consume the attributes.
1649 SourceLocation Loc = Tok.getLocation();
1650 ParseCXX11Attributes(Attrs);
1651 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
Faisal Valic5089c02017-12-25 22:23:20 +00001652 // FIXME: use err_attributes_misplaced
Richard Smith4c96e992013-02-19 23:47:15 +00001653 Diag(Loc, diag::err_attributes_not_allowed)
1654 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1655 << FixItHint::CreateRemoval(AttrRange);
1656}
1657
Erich Keanec480f302018-07-12 21:09:05 +00001658void Parser::DiagnoseProhibitedAttributes(
1659 const SourceRange &Range, const SourceLocation CorrectLocation) {
Faisal Valic5089c02017-12-25 22:23:20 +00001660 if (CorrectLocation.isValid()) {
Erich Keanec480f302018-07-12 21:09:05 +00001661 CharSourceRange AttrRange(Range, true);
Faisal Valic5089c02017-12-25 22:23:20 +00001662 Diag(CorrectLocation, diag::err_attributes_misplaced)
1663 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1664 << FixItHint::CreateRemoval(AttrRange);
1665 } else
Erich Keanec480f302018-07-12 21:09:05 +00001666 Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
Dawn Perchik335e16b2010-09-03 01:29:35 +00001667}
1668
Richard Smith49cc1cc2016-08-18 21:59:42 +00001669void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1670 unsigned DiagID) {
Erich Keanee891aa92018-07-13 15:07:47 +00001671 for (const ParsedAttr &AL : Attrs) {
Erich Keanec480f302018-07-12 21:09:05 +00001672 if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
Richard Smith49cc1cc2016-08-18 21:59:42 +00001673 continue;
Erich Keanee891aa92018-07-13 15:07:47 +00001674 if (AL.getKind() == ParsedAttr::UnknownAttribute)
Erich Keanec480f302018-07-12 21:09:05 +00001675 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL.getName();
Richard Smith49cc1cc2016-08-18 21:59:42 +00001676 else {
Erich Keanec480f302018-07-12 21:09:05 +00001677 Diag(AL.getLoc(), DiagID) << AL.getName();
1678 AL.setInvalid();
Michael Han64536a62012-11-06 19:34:54 +00001679 }
Michael Han64536a62012-11-06 19:34:54 +00001680 }
1681}
1682
Nico Weber32a0fc72016-09-03 03:01:32 +00001683// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1684// applies to var, not the type Foo.
David Majnemer936b4112015-04-19 07:53:29 +00001685// As an exception to the rule, __declspec(align(...)) before the
1686// class-key affects the type instead of the variable.
Nico Weber32a0fc72016-09-03 03:01:32 +00001687// Also, Microsoft-style [attributes] seem to affect the type instead of the
1688// variable.
1689// This function moves attributes that should apply to the type off DS to Attrs.
1690void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1691 DeclSpec &DS,
1692 Sema::TagUseKind TUK) {
David Majnemer936b4112015-04-19 07:53:29 +00001693 if (TUK == Sema::TUK_Reference)
1694 return;
1695
Erich Keanee891aa92018-07-13 15:07:47 +00001696 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
David Majnemer936b4112015-04-19 07:53:29 +00001697
Erich Keanee891aa92018-07-13 15:07:47 +00001698 for (ParsedAttr &AL : DS.getAttributes()) {
1699 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
Erich Keanec480f302018-07-12 21:09:05 +00001700 AL.isDeclspecAttribute()) ||
1701 AL.isMicrosoftAttribute())
1702 ToBeMoved.push_back(&AL);
David Majnemer936b4112015-04-19 07:53:29 +00001703 }
Nico Weber88f5ed92016-09-13 18:55:26 +00001704
Erich Keanee891aa92018-07-13 15:07:47 +00001705 for (ParsedAttr *AL : ToBeMoved) {
Erich Keanec480f302018-07-12 21:09:05 +00001706 DS.getAttributes().remove(AL);
1707 Attrs.addAtEnd(AL);
1708 }
David Majnemer936b4112015-04-19 07:53:29 +00001709}
1710
Chris Lattner53361ac2006-08-10 05:19:57 +00001711/// ParseDeclaration - Parse a full 'declaration', which consists of
1712/// declaration-specifiers, some number of declarators, and a semicolon.
Faisal Vali421b2d12017-12-29 05:41:00 +00001713/// 'Context' should be a DeclaratorContext value. This returns the
Chris Lattner49836b42009-04-02 04:16:50 +00001714/// location of the semicolon in DeclEnd.
Chris Lattnera5235172007-08-25 06:57:03 +00001715///
1716/// declaration: [C99 6.7]
1717/// block-declaration ->
1718/// simple-declaration
1719/// others [FIXME]
Douglas Gregoreb31f392008-12-01 23:54:00 +00001720/// [C++] template-declaration
Chris Lattnera5235172007-08-25 06:57:03 +00001721/// [C++] namespace-definition
Douglas Gregord7c4d982008-12-30 03:27:21 +00001722/// [C++] using-directive
Douglas Gregor77b50e12009-06-22 23:06:13 +00001723/// [C++] using-declaration
Richard Smithc202b282012-04-14 00:33:13 +00001724/// [C++11/C11] static_assert-declaration
Chris Lattnera5235172007-08-25 06:57:03 +00001725/// others... [FIXME]
1726///
Faisal Vali421b2d12017-12-29 05:41:00 +00001727Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
Alexis Hunt96d5c762009-11-21 08:43:09 +00001728 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +00001729 ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +00001730 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Fariborz Jahanian59b75282011-08-30 17:10:52 +00001731 // Must temporarily exit the objective-c container scope for
1732 // parsing c none objective-c decls.
1733 ObjCDeclContextSwitch ObjCDC(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00001734
Craig Topper161e4db2014-05-21 06:02:52 +00001735 Decl *SingleDecl = nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +00001736 switch (Tok.getKind()) {
Douglas Gregoreb31f392008-12-01 23:54:00 +00001737 case tok::kw_template:
Douglas Gregor23996282009-05-12 21:31:51 +00001738 case tok::kw_export:
John McCall53fa7142010-12-24 02:08:15 +00001739 ProhibitAttributes(attrs);
Erich Keanec480f302018-07-12 21:09:05 +00001740 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001741 break;
Sebastian Redl67667942010-08-27 23:12:46 +00001742 case tok::kw_inline:
Sebastian Redl5a5f2c72010-08-31 00:36:45 +00001743 // Could be the start of an inline namespace. Allowed as an ext in C++03.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001744 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
John McCall53fa7142010-12-24 02:08:15 +00001745 ProhibitAttributes(attrs);
Sebastian Redl67667942010-08-27 23:12:46 +00001746 SourceLocation InlineLoc = ConsumeToken();
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00001747 return ParseNamespace(Context, DeclEnd, InlineLoc);
Sebastian Redl67667942010-08-27 23:12:46 +00001748 }
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001749 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
Fariborz Jahanian1db5c942010-09-28 20:42:35 +00001750 true);
Chris Lattnera5235172007-08-25 06:57:03 +00001751 case tok::kw_namespace:
John McCall53fa7142010-12-24 02:08:15 +00001752 ProhibitAttributes(attrs);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00001753 return ParseNamespace(Context, DeclEnd);
Douglas Gregord7c4d982008-12-30 03:27:21 +00001754 case tok::kw_using:
Richard Smith6f1daa42016-12-16 00:58:48 +00001755 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1756 DeclEnd, attrs);
Anders Carlssonf24fcff62009-03-11 16:27:10 +00001757 case tok::kw_static_assert:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00001758 case tok::kw__Static_assert:
John McCall53fa7142010-12-24 02:08:15 +00001759 ProhibitAttributes(attrs);
Chris Lattner49836b42009-04-02 04:16:50 +00001760 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001761 break;
Chris Lattnera5235172007-08-25 06:57:03 +00001762 default:
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001763 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
Chris Lattnera5235172007-08-25 06:57:03 +00001764 }
Chad Rosierc1183952012-06-26 22:30:43 +00001765
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001766 // This routine returns a DeclGroup, if the thing we parsed only contains a
Richard Smith6f1daa42016-12-16 00:58:48 +00001767 // single decl, convert it now.
1768 return Actions.ConvertDeclToDeclGroup(SingleDecl);
Chris Lattnera5235172007-08-25 06:57:03 +00001769}
1770
1771/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1772/// declaration-specifiers init-declarator-list[opt] ';'
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001773/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1774/// init-declarator-list ';'
Chris Lattnera5235172007-08-25 06:57:03 +00001775///[C90/C++]init-declarator-list ';' [TODO]
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001776/// [OMP] threadprivate-directive
1777/// [OMP] allocate-directive [TODO]
Chris Lattner32dc41c2009-03-29 17:27:48 +00001778///
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001779/// for-range-declaration: [C++11 6.5p1: stmt.ranged]
Richard Smith02e85f32011-04-14 22:09:26 +00001780/// attribute-specifier-seq[opt] type-specifier-seq declarator
1781///
Chris Lattner32dc41c2009-03-29 17:27:48 +00001782/// If RequireSemi is false, this does not check for a ';' at the end of the
Chris Lattner005fc1b2010-04-05 18:18:31 +00001783/// declaration. If it is true, it checks for and eats it.
Richard Smith02e85f32011-04-14 22:09:26 +00001784///
1785/// If FRI is non-null, we might be parsing a for-range-declaration instead
1786/// of a simple-declaration. If we find that we are, we also parse the
1787/// for-range-initializer, and place it here.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001788Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +00001789Parser::ParseSimpleDeclaration(DeclaratorContext Context,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001790 SourceLocation &DeclEnd,
Richard Smith2386c8b2013-02-22 09:06:26 +00001791 ParsedAttributesWithRange &Attrs,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001792 bool RequireSemi, ForRangeInit *FRI) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001793 // Parse the common declaration-specifiers piece.
John McCall28a6aea2009-11-04 02:18:39 +00001794 ParsingDeclSpec DS(*this);
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001795
Richard Smith404dfb42013-11-19 22:47:36 +00001796 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
Faisal Valia534f072018-04-26 00:42:40 +00001797 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
Richard Smith404dfb42013-11-19 22:47:36 +00001798
1799 // If we had a free-standing type definition with a missing semicolon, we
1800 // may get this far before the problem becomes obvious.
1801 if (DS.hasTagDefinition() &&
1802 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
David Blaikie0403cb12016-01-15 23:43:25 +00001803 return nullptr;
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001804
Chris Lattner0e894622006-08-13 19:58:17 +00001805 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1806 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner76c72282007-10-09 17:33:22 +00001807 if (Tok.is(tok::semi)) {
Richard Smith2386c8b2013-02-22 09:06:26 +00001808 ProhibitAttributes(Attrs);
Argyrios Kyrtzidisfbb2bb52012-05-16 23:49:15 +00001809 DeclEnd = Tok.getLocation();
Chris Lattner005fc1b2010-04-05 18:18:31 +00001810 if (RequireSemi) ConsumeToken();
Nico Weber7b837f52016-01-28 19:25:00 +00001811 RecordDecl *AnonRecord = nullptr;
John McCall48871652010-08-21 09:40:31 +00001812 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00001813 DS, AnonRecord);
John McCall28a6aea2009-11-04 02:18:39 +00001814 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00001815 if (AnonRecord) {
1816 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00001817 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00001818 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001819 return Actions.ConvertDeclToDeclGroup(TheDecl);
Chris Lattner0e894622006-08-13 19:58:17 +00001820 }
Chad Rosierc1183952012-06-26 22:30:43 +00001821
Richard Smith2386c8b2013-02-22 09:06:26 +00001822 DS.takeAttributesFrom(Attrs);
Reid Klecknerd61a3112014-12-15 23:16:32 +00001823 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
John McCalld5a36322009-11-03 19:26:08 +00001824}
Mike Stump11289f42009-09-09 15:08:12 +00001825
Richard Smith09f76ee2011-10-19 21:33:05 +00001826/// Returns true if this might be the start of a declarator, or a common typo
1827/// for a declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001828bool Parser::MightBeDeclarator(DeclaratorContext Context) {
Richard Smith09f76ee2011-10-19 21:33:05 +00001829 switch (Tok.getKind()) {
1830 case tok::annot_cxxscope:
1831 case tok::annot_template_id:
1832 case tok::caret:
1833 case tok::code_completion:
1834 case tok::coloncolon:
1835 case tok::ellipsis:
1836 case tok::kw___attribute:
1837 case tok::kw_operator:
1838 case tok::l_paren:
1839 case tok::star:
1840 return true;
1841
1842 case tok::amp:
1843 case tok::ampamp:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001844 return getLangOpts().CPlusPlus;
Richard Smith09f76ee2011-10-19 21:33:05 +00001845
Richard Smithc8a79032012-01-09 22:31:44 +00001846 case tok::l_square: // Might be an attribute on an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001847 return Context == DeclaratorContext::MemberContext &&
1848 getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
Richard Smithc8a79032012-01-09 22:31:44 +00001849
1850 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001851 return Context == DeclaratorContext::MemberContext ||
1852 getLangOpts().CPlusPlus;
Richard Smithc8a79032012-01-09 22:31:44 +00001853
Richard Smith09f76ee2011-10-19 21:33:05 +00001854 case tok::identifier:
1855 switch (NextToken().getKind()) {
1856 case tok::code_completion:
1857 case tok::coloncolon:
1858 case tok::comma:
1859 case tok::equal:
1860 case tok::equalequal: // Might be a typo for '='.
1861 case tok::kw_alignas:
1862 case tok::kw_asm:
1863 case tok::kw___attribute:
1864 case tok::l_brace:
1865 case tok::l_paren:
1866 case tok::l_square:
1867 case tok::less:
1868 case tok::r_brace:
1869 case tok::r_paren:
1870 case tok::r_square:
1871 case tok::semi:
1872 return true;
1873
1874 case tok::colon:
1875 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
Richard Smithc8a79032012-01-09 22:31:44 +00001876 // and in block scope it's probably a label. Inside a class definition,
1877 // this is a bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001878 return Context == DeclaratorContext::MemberContext ||
1879 (getLangOpts().CPlusPlus &&
1880 Context == DeclaratorContext::FileContext);
Richard Smithc8a79032012-01-09 22:31:44 +00001881
1882 case tok::identifier: // Possible virt-specifier.
Richard Smith89645bc2013-01-02 12:01:23 +00001883 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
Richard Smith09f76ee2011-10-19 21:33:05 +00001884
1885 default:
1886 return false;
1887 }
1888
1889 default:
1890 return false;
1891 }
1892}
1893
Richard Smithb8caac82012-04-11 20:59:20 +00001894/// Skip until we reach something which seems like a sensible place to pick
1895/// up parsing after a malformed declaration. This will sometimes stop sooner
1896/// than SkipUntil(tok::r_brace) would, but will never stop later.
1897void Parser::SkipMalformedDecl() {
1898 while (true) {
1899 switch (Tok.getKind()) {
1900 case tok::l_brace:
1901 // Skip until matching }, then stop. We've probably skipped over
1902 // a malformed class or function definition or similar.
1903 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001904 SkipUntil(tok::r_brace);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001905 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
Richard Smithb8caac82012-04-11 20:59:20 +00001906 // This declaration isn't over yet. Keep skipping.
1907 continue;
1908 }
Alp Toker8fbec672013-12-17 23:29:36 +00001909 TryConsumeToken(tok::semi);
Richard Smithb8caac82012-04-11 20:59:20 +00001910 return;
1911
1912 case tok::l_square:
1913 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001914 SkipUntil(tok::r_square);
Richard Smithb8caac82012-04-11 20:59:20 +00001915 continue;
1916
1917 case tok::l_paren:
1918 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001919 SkipUntil(tok::r_paren);
Richard Smithb8caac82012-04-11 20:59:20 +00001920 continue;
1921
1922 case tok::r_brace:
1923 return;
1924
1925 case tok::semi:
1926 ConsumeToken();
1927 return;
1928
1929 case tok::kw_inline:
1930 // 'inline namespace' at the start of a line is almost certainly
Jordan Rose12e730c2012-07-09 16:54:53 +00001931 // a good place to pick back up parsing, except in an Objective-C
1932 // @interface context.
1933 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1934 (!ParsingInObjCContainer || CurParsedObjCImpl))
Richard Smithb8caac82012-04-11 20:59:20 +00001935 return;
1936 break;
1937
1938 case tok::kw_namespace:
1939 // 'namespace' at the start of a line is almost certainly a good
Jordan Rose12e730c2012-07-09 16:54:53 +00001940 // place to pick back up parsing, except in an Objective-C
1941 // @interface context.
1942 if (Tok.isAtStartOfLine() &&
1943 (!ParsingInObjCContainer || CurParsedObjCImpl))
1944 return;
1945 break;
1946
1947 case tok::at:
1948 // @end is very much like } in Objective-C contexts.
1949 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1950 ParsingInObjCContainer)
1951 return;
1952 break;
1953
1954 case tok::minus:
1955 case tok::plus:
1956 // - and + probably start new method declarations in Objective-C contexts.
1957 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
Richard Smithb8caac82012-04-11 20:59:20 +00001958 return;
1959 break;
1960
1961 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001962 case tok::annot_module_begin:
1963 case tok::annot_module_end:
1964 case tok::annot_module_include:
Richard Smithb8caac82012-04-11 20:59:20 +00001965 return;
1966
1967 default:
1968 break;
1969 }
1970
1971 ConsumeAnyToken();
1972 }
1973}
1974
John McCalld5a36322009-11-03 19:26:08 +00001975/// ParseDeclGroup - Having concluded that this is either a function
1976/// definition or a group of object declarations, actually parse the
1977/// result.
John McCall28a6aea2009-11-04 02:18:39 +00001978Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
Faisal Vali421b2d12017-12-29 05:41:00 +00001979 DeclaratorContext Context,
Richard Smith02e85f32011-04-14 22:09:26 +00001980 SourceLocation *DeclEnd,
1981 ForRangeInit *FRI) {
John McCalld5a36322009-11-03 19:26:08 +00001982 // Parse the first declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001983 ParsingDeclarator D(*this, DS, Context);
John McCalld5a36322009-11-03 19:26:08 +00001984 ParseDeclarator(D);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001985
John McCalld5a36322009-11-03 19:26:08 +00001986 // Bail out if the first declarator didn't seem well-formed.
1987 if (!D.hasName() && !D.mayOmitIdentifier()) {
Richard Smithb8caac82012-04-11 20:59:20 +00001988 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00001989 return nullptr;
Chris Lattnerefb0f112009-03-29 17:18:04 +00001990 }
Mike Stump11289f42009-09-09 15:08:12 +00001991
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001992 // Save late-parsed attributes for now; they need to be parsed in the
1993 // appropriate function scope after the function Decl has been constructed.
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001994 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1995 LateParsedAttrList LateParsedAttrs(true);
Richard Smith99c464c2014-11-10 21:10:32 +00001996 if (D.isFunctionDeclarator()) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001997 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1998
Richard Smith99c464c2014-11-10 21:10:32 +00001999 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2000 // attribute. If we find the keyword here, tell the user to put it
2001 // at the start instead.
2002 if (Tok.is(tok::kw__Noreturn)) {
2003 SourceLocation Loc = ConsumeToken();
2004 const char *PrevSpec;
2005 unsigned DiagID;
2006
2007 // We can offer a fixit if it's valid to mark this function as _Noreturn
2008 // and we don't have any other declarators in this declaration.
2009 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2010 MaybeParseGNUAttributes(D, &LateParsedAttrs);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002011 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
Richard Smith99c464c2014-11-10 21:10:32 +00002012
2013 Diag(Loc, diag::err_c11_noreturn_misplaced)
2014 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002015 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
Richard Smith99c464c2014-11-10 21:10:32 +00002016 : FixItHint());
2017 }
2018 }
2019
Chris Lattnerdbb1e932010-07-11 22:24:20 +00002020 // Check to see if we have a function *definition* which must have a body.
Douglas Gregor012efe22013-04-16 16:01:32 +00002021 if (D.isFunctionDeclarator() &&
Chris Lattnerdbb1e932010-07-11 22:24:20 +00002022 // Look at the next token to make sure that this isn't a function
2023 // declaration. We have to check this because __attribute__ might be the
2024 // start of a function definition in GCC-extended K&R C.
Fariborz Jahanian712bb812012-08-10 15:54:40 +00002025 !isDeclarationAfterDeclarator()) {
Chad Rosierc1183952012-06-26 22:30:43 +00002026
Reid Klecknerd61a3112014-12-15 23:16:32 +00002027 // Function definitions are only allowed at file scope and in C++ classes.
2028 // The C++ inline method definition case is handled elsewhere, so we only
2029 // need to handle the file scope definition case.
Faisal Vali421b2d12017-12-29 05:41:00 +00002030 if (Context == DeclaratorContext::FileContext) {
Douglas Gregor012efe22013-04-16 16:01:32 +00002031 if (isStartOfFunctionDefinition(D)) {
2032 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2033 Diag(Tok, diag::err_function_declared_typedef);
John McCalld5a36322009-11-03 19:26:08 +00002034
Douglas Gregor012efe22013-04-16 16:01:32 +00002035 // Recover by treating the 'typedef' as spurious.
2036 DS.ClearStorageClassSpecs();
2037 }
2038
2039 Decl *TheDecl =
2040 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
2041 return Actions.ConvertDeclToDeclGroup(TheDecl);
John McCalld5a36322009-11-03 19:26:08 +00002042 }
2043
Douglas Gregor012efe22013-04-16 16:01:32 +00002044 if (isDeclarationSpecifier()) {
Nico Weber6b05f382015-02-18 04:53:03 +00002045 // If there is an invalid declaration specifier right after the
2046 // function prototype, then we must be in a missing semicolon case
2047 // where this isn't actually a body. Just fall through into the code
2048 // that handles it as a prototype, and let the top-level code handle
2049 // the erroneous declspec where it would otherwise expect a comma or
2050 // semicolon.
Douglas Gregor012efe22013-04-16 16:01:32 +00002051 } else {
2052 Diag(Tok, diag::err_expected_fn_body);
2053 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002054 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00002055 }
John McCalld5a36322009-11-03 19:26:08 +00002056 } else {
Douglas Gregor012efe22013-04-16 16:01:32 +00002057 if (Tok.is(tok::l_brace)) {
2058 Diag(Tok, diag::err_function_definition_not_allowed);
Serge Pavlov1de51512013-12-09 05:25:47 +00002059 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00002060 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00002061 }
John McCalld5a36322009-11-03 19:26:08 +00002062 }
2063 }
2064
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002065 if (ParseAsmAttributesAfterDeclarator(D))
David Blaikie0403cb12016-01-15 23:43:25 +00002066 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00002067
2068 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2069 // must parse and analyze the for-range-initializer before the declaration is
2070 // analyzed.
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002071 //
2072 // Handle the Objective-C for-in loop variable similarly, although we
2073 // don't need to parse the container in advance.
2074 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2075 bool IsForRangeLoop = false;
Alp Toker8fbec672013-12-17 23:29:36 +00002076 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002077 IsForRangeLoop = true;
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002078 if (Tok.is(tok::l_brace))
2079 FRI->RangeExpr = ParseBraceInitializer();
2080 else
2081 FRI->RangeExpr = ParseExpression();
2082 }
2083
Richard Smith02e85f32011-04-14 22:09:26 +00002084 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
George Karpenkovec38cf72018-03-29 00:56:24 +00002085 if (IsForRangeLoop) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002086 Actions.ActOnCXXForRangeDecl(ThisDecl);
George Karpenkovec38cf72018-03-29 00:56:24 +00002087 } else {
2088 // Obj-C for loop
2089 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2090 VD->setObjCForDecl(true);
2091 }
Richard Smith02e85f32011-04-14 22:09:26 +00002092 Actions.FinalizeDeclaration(ThisDecl);
John McCallcf6e0c82012-01-27 01:29:43 +00002093 D.complete(ThisDecl);
Rafael Espindolaab417692013-07-09 12:05:01 +00002094 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
Richard Smith02e85f32011-04-14 22:09:26 +00002095 }
2096
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002097 SmallVector<Decl *, 8> DeclsInGroup;
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002098 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2099 D, ParsedTemplateInfo(), FRI);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002100 if (LateParsedAttrs.size() > 0)
2101 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
John McCall28a6aea2009-11-04 02:18:39 +00002102 D.complete(FirstDecl);
John McCall48871652010-08-21 09:40:31 +00002103 if (FirstDecl)
John McCalld5a36322009-11-03 19:26:08 +00002104 DeclsInGroup.push_back(FirstDecl);
2105
Faisal Vali421b2d12017-12-29 05:41:00 +00002106 bool ExpectSemi = Context != DeclaratorContext::ForContext;
Fangrui Song6907ce22018-07-30 19:24:48 +00002107
John McCalld5a36322009-11-03 19:26:08 +00002108 // If we don't have a comma, it is either the end of the list (a ';') or an
2109 // error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00002110 SourceLocation CommaLoc;
2111 while (TryConsumeToken(tok::comma, CommaLoc)) {
Richard Smith09f76ee2011-10-19 21:33:05 +00002112 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2113 // This comma was followed by a line-break and something which can't be
2114 // the start of a declarator. The comma was probably a typo for a
2115 // semicolon.
2116 Diag(CommaLoc, diag::err_expected_semi_declaration)
2117 << FixItHint::CreateReplacement(CommaLoc, ";");
2118 ExpectSemi = false;
2119 break;
2120 }
John McCalld5a36322009-11-03 19:26:08 +00002121
2122 // Parse the next declarator.
2123 D.clear();
Richard Smith8d06f422012-01-12 23:53:29 +00002124 D.setCommaLoc(CommaLoc);
John McCalld5a36322009-11-03 19:26:08 +00002125
2126 // Accept attributes in an init-declarator. In the first declarator in a
2127 // declaration, these would be part of the declspec. In subsequent
2128 // declarators, they become part of the declarator itself, so that they
2129 // don't apply to declarators after *this* one. Examples:
2130 // short __attribute__((common)) var; -> declspec
2131 // short var __attribute__((common)); -> declarator
2132 // short x, __attribute__((common)) var; -> declarator
John McCall53fa7142010-12-24 02:08:15 +00002133 MaybeParseGNUAttributes(D);
John McCalld5a36322009-11-03 19:26:08 +00002134
Nico Rieckeaaae272014-12-04 23:31:08 +00002135 // MSVC parses but ignores qualifiers after the comma as an extension.
2136 if (getLangOpts().MicrosoftExt)
2137 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2138
John McCalld5a36322009-11-03 19:26:08 +00002139 ParseDeclarator(D);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002140 if (!D.isInvalidType()) {
2141 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2142 D.complete(ThisDecl);
2143 if (ThisDecl)
Chad Rosierc1183952012-06-26 22:30:43 +00002144 DeclsInGroup.push_back(ThisDecl);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002145 }
John McCalld5a36322009-11-03 19:26:08 +00002146 }
2147
2148 if (DeclEnd)
2149 *DeclEnd = Tok.getLocation();
2150
Richard Smith09f76ee2011-10-19 21:33:05 +00002151 if (ExpectSemi &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002152 ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
Chris Lattner02f1b612012-04-28 16:12:17 +00002153 ? diag::err_invalid_token_after_toplevel_declarator
2154 : diag::err_expected_semi_declaration)) {
Chris Lattner13901342010-07-11 22:42:07 +00002155 // Okay, there was no semicolon and one was expected. If we see a
2156 // declaration specifier, just assume it was missing and continue parsing.
2157 // Otherwise things are very confused and we skip to recover.
2158 if (!isDeclarationSpecifier()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002159 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Alp Toker8fbec672013-12-17 23:29:36 +00002160 TryConsumeToken(tok::semi);
Chris Lattner13901342010-07-11 22:42:07 +00002161 }
John McCalld5a36322009-11-03 19:26:08 +00002162 }
2163
Rafael Espindolaab417692013-07-09 12:05:01 +00002164 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner53361ac2006-08-10 05:19:57 +00002165}
2166
Richard Smith02e85f32011-04-14 22:09:26 +00002167/// Parse an optional simple-asm-expr and attributes, and attach them to a
2168/// declarator. Returns true on an error.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002169bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
Richard Smith02e85f32011-04-14 22:09:26 +00002170 // If a simple-asm-expr is present, parse it.
2171 if (Tok.is(tok::kw_asm)) {
2172 SourceLocation Loc;
2173 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2174 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002175 SkipUntil(tok::semi, StopBeforeMatch);
Richard Smith02e85f32011-04-14 22:09:26 +00002176 return true;
2177 }
2178
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002179 D.setAsmLabel(AsmLabel.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002180 D.SetRangeEnd(Loc);
2181 }
2182
2183 MaybeParseGNUAttributes(D);
2184 return false;
2185}
2186
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002187/// Parse 'declaration' after parsing 'declaration-specifiers
Douglas Gregor23996282009-05-12 21:31:51 +00002188/// declarator'. This method parses the remainder of the declaration
2189/// (including any attributes or initializer, among other things) and
2190/// finalizes the declaration.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002191///
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002192/// init-declarator: [C99 6.7]
2193/// declarator
2194/// declarator '=' initializer
Chris Lattner6d7e6342006-08-15 03:41:14 +00002195/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2196/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002197/// [C++] declarator initializer[opt]
2198///
2199/// [C++] initializer:
2200/// [C++] '=' initializer-clause
2201/// [C++] '(' expression-list ')'
Sebastian Redlf769df52009-03-24 22:27:57 +00002202/// [C++0x] '=' 'default' [TODO]
2203/// [C++0x] '=' 'delete'
Sebastian Redl3da34892011-06-05 12:23:16 +00002204/// [C++0x] braced-init-list
Sebastian Redlf769df52009-03-24 22:27:57 +00002205///
2206/// According to the standard grammar, =default and =delete are function
2207/// definitions, but that definitely doesn't fit with the parser here.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002208///
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002209Decl *Parser::ParseDeclarationAfterDeclarator(
2210 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002211 if (ParseAsmAttributesAfterDeclarator(D))
Craig Topper161e4db2014-05-21 06:02:52 +00002212 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002213
Richard Smith02e85f32011-04-14 22:09:26 +00002214 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2215}
Mike Stump11289f42009-09-09 15:08:12 +00002216
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002217Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2218 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
Richard Smithc95d2c52017-09-22 04:25:05 +00002219 // RAII type used to track whether we're inside an initializer.
2220 struct InitializerScopeRAII {
2221 Parser &P;
2222 Declarator &D;
2223 Decl *ThisDecl;
2224
2225 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2226 : P(P), D(D), ThisDecl(ThisDecl) {
2227 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2228 Scope *S = nullptr;
2229 if (D.getCXXScopeSpec().isSet()) {
2230 P.EnterScope(0);
2231 S = P.getCurScope();
2232 }
2233 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2234 }
2235 }
2236 ~InitializerScopeRAII() { pop(); }
2237 void pop() {
2238 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2239 Scope *S = nullptr;
2240 if (D.getCXXScopeSpec().isSet())
2241 S = P.getCurScope();
2242 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2243 if (S)
2244 P.ExitScope();
2245 }
2246 ThisDecl = nullptr;
2247 }
2248 };
2249
Douglas Gregor23996282009-05-12 21:31:51 +00002250 // Inform the current actions module that we just parsed this declarator.
Craig Topper161e4db2014-05-21 06:02:52 +00002251 Decl *ThisDecl = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00002252 switch (TemplateInfo.Kind) {
2253 case ParsedTemplateInfo::NonTemplate:
Douglas Gregor0be31a22010-07-02 17:43:08 +00002254 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
Douglas Gregor450f00842009-09-25 18:43:00 +00002255 break;
Chad Rosierc1183952012-06-26 22:30:43 +00002256
Douglas Gregor450f00842009-09-25 18:43:00 +00002257 case ParsedTemplateInfo::Template:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002258 case ParsedTemplateInfo::ExplicitSpecialization: {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002259 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002260 *TemplateInfo.TemplateParams,
Douglas Gregor450f00842009-09-25 18:43:00 +00002261 D);
Larisse Voufo833b05a2013-08-06 07:33:00 +00002262 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002263 // Re-direct this decl to refer to the templated decl so that we can
2264 // initialize it.
2265 ThisDecl = VT->getTemplatedDecl();
2266 break;
2267 }
2268 case ParsedTemplateInfo::ExplicitInstantiation: {
2269 if (Tok.is(tok::semi)) {
2270 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2271 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2272 if (ThisRes.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002273 SkipUntil(tok::semi, StopBeforeMatch);
Craig Topper161e4db2014-05-21 06:02:52 +00002274 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002275 }
2276 ThisDecl = ThisRes.get();
2277 } else {
2278 // FIXME: This check should be for a variable template instantiation only.
2279
2280 // Check that this is a valid instantiation
Faisal Vali2ab8c152017-12-30 04:15:27 +00002281 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002282 // If the declarator-id is not a template-id, issue a diagnostic and
2283 // recover by ignoring the 'template' keyword.
2284 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2285 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2286 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2287 } else {
2288 SourceLocation LAngleLoc =
2289 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2290 Diag(D.getIdentifierLoc(),
2291 diag::err_explicit_instantiation_with_definition)
2292 << SourceRange(TemplateInfo.TemplateLoc)
2293 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2294
2295 // Recover as if it were an explicit specialization.
2296 TemplateParameterLists FakedParamLists;
2297 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00002298 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00002299 LAngleLoc, nullptr));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002300
2301 ThisDecl =
2302 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2303 }
2304 }
Douglas Gregor450f00842009-09-25 18:43:00 +00002305 break;
2306 }
2307 }
Mike Stump11289f42009-09-09 15:08:12 +00002308
Douglas Gregor23996282009-05-12 21:31:51 +00002309 // Parse declarator '=' initializer.
Richard Trieuc64d3232012-01-18 22:54:52 +00002310 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Trieu4972a6d2012-01-19 22:01:51 +00002311 if (isTokenEqualOrEqualTypo()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002312 SourceLocation EqualLoc = ConsumeToken();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002313
Anders Carlsson991285e2010-09-24 21:25:25 +00002314 if (Tok.is(tok::kw_delete)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002315 if (D.isFunctionDeclarator())
2316 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2317 << 1 /* delete */;
2318 else
2319 Diag(ConsumeToken(), diag::err_deleted_non_function);
Alexis Hunt5dafebc2011-05-06 01:42:00 +00002320 } else if (Tok.is(tok::kw_default)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002321 if (D.isFunctionDeclarator())
Sebastian Redl46afb552012-02-11 23:51:21 +00002322 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2323 << 0 /* default */;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002324 else
2325 Diag(ConsumeToken(), diag::err_default_special_members);
Douglas Gregor23996282009-05-12 21:31:51 +00002326 } else {
Richard Smithc95d2c52017-09-22 04:25:05 +00002327 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002328
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002329 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002330 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
Peter Collingbourne6b4fdc22012-07-27 12:56:09 +00002331 Actions.FinalizeDeclaration(ThisDecl);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002332 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +00002333 return nullptr;
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002334 }
Chad Rosierc1183952012-06-26 22:30:43 +00002335
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00002336 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2337 ExprResult Init = ParseInitializer();
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002338
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002339 // If this is the only decl in (possibly) range based for statement,
2340 // our best guess is that the user meant ':' instead of '='.
2341 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2342 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2343 << FixItHint::CreateReplacement(EqualLoc, ":");
2344 // We are trying to stop parser from looking for ';' in this for
2345 // statement, therefore preventing spurious errors to be issued.
2346 FRI->ColonLoc = EqualLoc;
2347 Init = ExprError();
2348 FRI->RangeExpr = Init;
2349 }
2350
Richard Smithc95d2c52017-09-22 04:25:05 +00002351 InitScope.pop();
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002352
Douglas Gregor23996282009-05-12 21:31:51 +00002353 if (Init.isInvalid()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002354 SmallVector<tok::TokenKind, 2> StopTokens;
2355 StopTokens.push_back(tok::comma);
Faisal Vali421b2d12017-12-29 05:41:00 +00002356 if (D.getContext() == DeclaratorContext::ForContext ||
2357 D.getContext() == DeclaratorContext::InitStmtContext)
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002358 StopTokens.push_back(tok::r_paren);
2359 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
Douglas Gregor604c3022010-03-01 18:27:54 +00002360 Actions.ActOnInitializerError(ThisDecl);
2361 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002362 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002363 /*DirectInit=*/false);
Douglas Gregor23996282009-05-12 21:31:51 +00002364 }
2365 } else if (Tok.is(tok::l_paren)) {
2366 // Parse C++ direct initializer: '(' expression-list ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002367 BalancedDelimiterTracker T(*this, tok::l_paren);
2368 T.consumeOpen();
2369
Benjamin Kramerf0623432012-08-23 22:51:59 +00002370 ExprVector Exprs;
Douglas Gregor23996282009-05-12 21:31:51 +00002371 CommaLocsTy CommaLocs;
2372
Richard Smithc95d2c52017-09-22 04:25:05 +00002373 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Douglas Gregor613bf102009-12-22 17:47:17 +00002374
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002375 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002376 auto RunSignatureHelp = [&]() {
Ilya Biryukov832c4af2018-09-07 14:04:39 +00002377 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002378 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
Ilya Biryukov2fab2352018-08-30 13:08:03 +00002379 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002380 CalledSignatureHelp = true;
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002381 return PreferredType;
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002382 };
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002383 auto SetPreferredType = [&] {
2384 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2385 };
2386
2387 llvm::function_ref<void()> ExpressionStarts;
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002388 if (ThisVarDecl) {
2389 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2390 // VarDecl. This is an error and it is reported in a call to
2391 // Actions.ActOnInitializerError(). However, we call
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002392 // ProduceConstructorSignatureHelp only on VarDecls.
2393 ExpressionStarts = SetPreferredType;
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002394 }
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002395 if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002396 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2397 Actions.ProduceConstructorSignatureHelp(
2398 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2399 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2400 CalledSignatureHelp = true;
2401 }
David Blaikieeae04112012-10-10 23:15:05 +00002402 Actions.ActOnInitializerError(ThisDecl);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002403 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor23996282009-05-12 21:31:51 +00002404 } else {
2405 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002406 T.consumeClose();
Douglas Gregor23996282009-05-12 21:31:51 +00002407
2408 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2409 "Unexpected number of commas!");
Douglas Gregor613bf102009-12-22 17:47:17 +00002410
Richard Smithc95d2c52017-09-22 04:25:05 +00002411 InitScope.pop();
Douglas Gregor613bf102009-12-22 17:47:17 +00002412
Sebastian Redla9351792012-02-11 23:51:47 +00002413 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2414 T.getCloseLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002415 Exprs);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002416 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002417 /*DirectInit=*/true);
Douglas Gregor23996282009-05-12 21:31:51 +00002418 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002419 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
Fariborz Jahanian8be1ecd2012-07-03 23:22:13 +00002420 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
Sebastian Redl3da34892011-06-05 12:23:16 +00002421 // Parse C++0x braced-init-list.
Richard Smith5d164bc2011-10-15 05:09:34 +00002422 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2423
Richard Smithc95d2c52017-09-22 04:25:05 +00002424 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Sebastian Redl3da34892011-06-05 12:23:16 +00002425
2426 ExprResult Init(ParseBraceInitializer());
2427
Richard Smithc95d2c52017-09-22 04:25:05 +00002428 InitScope.pop();
Sebastian Redl3da34892011-06-05 12:23:16 +00002429
2430 if (Init.isInvalid()) {
2431 Actions.ActOnInitializerError(ThisDecl);
2432 } else
Richard Smith3beb7c62017-01-12 02:27:38 +00002433 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
Sebastian Redl3da34892011-06-05 12:23:16 +00002434
Douglas Gregor23996282009-05-12 21:31:51 +00002435 } else {
Richard Smith3beb7c62017-01-12 02:27:38 +00002436 Actions.ActOnUninitializedDecl(ThisDecl);
Douglas Gregor23996282009-05-12 21:31:51 +00002437 }
2438
Richard Smithb2bc2e62011-02-21 20:05:19 +00002439 Actions.FinalizeDeclaration(ThisDecl);
2440
Douglas Gregor23996282009-05-12 21:31:51 +00002441 return ThisDecl;
2442}
2443
Chris Lattner1890ac82006-08-13 01:16:23 +00002444/// ParseSpecifierQualifierList
2445/// specifier-qualifier-list:
2446/// type-specifier specifier-qualifier-list[opt]
2447/// type-qualifier specifier-qualifier-list[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002448/// [GNU] attributes specifier-qualifier-list[opt]
Chris Lattner1890ac82006-08-13 01:16:23 +00002449///
Richard Smithc5b05522012-03-12 07:56:15 +00002450void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2451 DeclSpecContext DSC) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002452 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2453 /// parse declaration-specifiers and complain about extra stuff.
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002454 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
Faisal Valia534f072018-04-26 00:42:40 +00002455 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
Mike Stump11289f42009-09-09 15:08:12 +00002456
Chris Lattner1890ac82006-08-13 01:16:23 +00002457 // Validate declspec for type-name.
2458 unsigned Specs = DS.getParsedSpecifiers();
Richard Smith649c7b062014-01-08 00:56:48 +00002459 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
Richard Smithc5b05522012-03-12 07:56:15 +00002460 Diag(Tok, diag::err_expected_type);
2461 DS.SetTypeSpecError();
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00002462 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002463 Diag(Tok, diag::err_typename_requires_specqual);
Richard Smithc5b05522012-03-12 07:56:15 +00002464 if (!DS.hasTypeSpecifier())
2465 DS.SetTypeSpecError();
2466 }
Mike Stump11289f42009-09-09 15:08:12 +00002467
Chris Lattner1b22eed2006-11-28 05:12:07 +00002468 // Issue diagnostic and remove storage class if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002469 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
Chris Lattner1b22eed2006-11-28 05:12:07 +00002470 if (DS.getStorageClassSpecLoc().isValid())
2471 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2472 else
Richard Smithb4a9e862013-04-12 22:46:28 +00002473 Diag(DS.getThreadStorageClassSpecLoc(),
2474 diag::err_typename_invalid_storageclass);
Chris Lattnera925dc62006-11-28 04:33:46 +00002475 DS.ClearStorageClassSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002476 }
Mike Stump11289f42009-09-09 15:08:12 +00002477
Craig Topper3f13d4d22015-11-14 18:15:55 +00002478 // Issue diagnostic and remove function specifier if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002479 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
Douglas Gregor61956c42008-10-31 09:07:45 +00002480 if (DS.isInlineSpecified())
2481 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2482 if (DS.isVirtualSpecified())
2483 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
Richard Smith76b90272019-05-09 03:59:21 +00002484 if (DS.hasExplicitSpecifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00002485 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
Chris Lattnera925dc62006-11-28 04:33:46 +00002486 DS.ClearFunctionSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002487 }
Richard Smithc5b05522012-03-12 07:56:15 +00002488
Richard Smith76b90272019-05-09 03:59:21 +00002489 // Issue diagnostic and remove constexpr specifier if present.
Gauthier Harnisch796ed032019-06-14 08:56:20 +00002490 if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2491 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2492 << (DS.getConstexprSpecifier() == CSK_consteval);
Richard Smithc5b05522012-03-12 07:56:15 +00002493 DS.ClearConstexprSpec();
2494 }
Chris Lattner1890ac82006-08-13 01:16:23 +00002495}
Chris Lattner53361ac2006-08-10 05:19:57 +00002496
Chris Lattner6cc055a2009-04-12 20:42:31 +00002497/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2498/// specified token is valid after the identifier in a declarator which
2499/// immediately follows the declspec. For example, these things are valid:
2500///
2501/// int x [ 4]; // direct-declarator
2502/// int x ( int y); // direct-declarator
2503/// int(int x ) // direct-declarator
2504/// int x ; // simple-declaration
2505/// int x = 17; // init-declarator-list
2506/// int x , y; // init-declarator-list
2507/// int x __asm__ ("foo"); // init-declarator-list
Chris Lattnera723ba92009-04-14 21:16:09 +00002508/// int x : 4; // struct-declarator
Chris Lattner2b988c12009-04-12 22:29:43 +00002509/// int x { 5}; // C++'0x unified initializers
Chris Lattner6cc055a2009-04-12 20:42:31 +00002510///
2511/// This is not, because 'x' does not immediately follow the declspec (though
2512/// ')' happens to be valid anyway).
2513/// int (x)
2514///
2515static bool isValidAfterIdentifierInDeclarator(const Token &T) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002516 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2517 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2518 tok::colon);
Chris Lattner6cc055a2009-04-12 20:42:31 +00002519}
2520
Chris Lattner20a0c612009-04-14 21:34:55 +00002521/// ParseImplicitInt - This method is called when we have an non-typename
2522/// identifier in a declspec (which normally terminates the decl spec) when
2523/// the declspec has no type specifier. In this case, the declspec is either
2524/// malformed or is "implicit int" (in K&R and C89).
2525///
2526/// This method handles diagnosing this prettily and returns false if the
2527/// declspec is done being processed. If it recovers and thinks there may be
2528/// other pieces of declspec after it, it returns true.
2529///
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002530bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002531 const ParsedTemplateInfo &TemplateInfo,
Richard Smitha0a5d502014-05-08 22:32:00 +00002532 AccessSpecifier AS, DeclSpecContext DSC,
Michael Han9407e502012-11-26 22:54:45 +00002533 ParsedAttributesWithRange &Attrs) {
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002534 assert(Tok.is(tok::identifier) && "should have identifier");
Mike Stump11289f42009-09-09 15:08:12 +00002535
Chris Lattner20a0c612009-04-14 21:34:55 +00002536 SourceLocation Loc = Tok.getLocation();
2537 // If we see an identifier that is not a type name, we normally would
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002538 // parse it as the identifier being declared. However, when a typename
Chris Lattner20a0c612009-04-14 21:34:55 +00002539 // is typo'd or the definition is not included, this will incorrectly
2540 // parse the typename as the identifier name and fall over misparsing
2541 // later parts of the diagnostic.
2542 //
2543 // As such, we try to do some look-ahead in cases where this would
2544 // otherwise be an "implicit-int" case to see if this is invalid. For
2545 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2546 // an identifier with implicit int, we'd get a parse error because the
2547 // next token is obviously invalid for a type. Parse these as a case
2548 // with an invalid type specifier.
2549 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
Mike Stump11289f42009-09-09 15:08:12 +00002550
Chris Lattner20a0c612009-04-14 21:34:55 +00002551 // Since we know that this either implicit int (which is rare) or an
Richard Smitha952ebb2012-05-15 21:01:51 +00002552 // error, do lookahead to try to do better recovery. This never applies
2553 // within a type specifier. Outside of C++, we allow this even if the
2554 // language doesn't "officially" support implicit int -- we support
Richard Smith3b870382013-04-30 22:43:51 +00002555 // implicit int as an extension in C99 and C11.
Richard Smith649c7b062014-01-08 00:56:48 +00002556 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
Richard Smithc5b05522012-03-12 07:56:15 +00002557 isValidAfterIdentifierInDeclarator(NextToken())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002558 // If this token is valid for implicit int, e.g. "static x = 4", then
2559 // we just avoid eating the identifier, so it will be parsed as the
2560 // identifier in the declarator.
2561 return false;
2562 }
Mike Stump11289f42009-09-09 15:08:12 +00002563
Sven van Haastregte518bb42019-05-22 13:12:20 +00002564 // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2565 // for incomplete declarations such as `pipe p`.
2566 if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2567 return false;
2568
Richard Smitha952ebb2012-05-15 21:01:51 +00002569 if (getLangOpts().CPlusPlus &&
2570 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2571 // Don't require a type specifier if we have the 'auto' storage class
2572 // specifier in C++98 -- we'll promote it to a type specifier.
Richard Smithfb8b7b92013-10-15 00:00:26 +00002573 if (SS)
2574 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
Richard Smitha952ebb2012-05-15 21:01:51 +00002575 return false;
2576 }
2577
Reid Kleckner9a96e422016-05-24 21:23:54 +00002578 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2579 getLangOpts().MSVCCompat) {
2580 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2581 // Give Sema a chance to recover if we are in a template with dependent base
2582 // classes.
2583 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2584 *Tok.getIdentifierInfo(), Tok.getLocation(),
Faisal Vali7db85c52017-12-31 00:06:40 +00002585 DSC == DeclSpecContext::DSC_template_type_arg)) {
Reid Kleckner9a96e422016-05-24 21:23:54 +00002586 const char *PrevSpec;
2587 unsigned DiagID;
2588 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2589 Actions.getASTContext().getPrintingPolicy());
2590 DS.SetRangeEnd(Tok.getLocation());
2591 ConsumeToken();
2592 return false;
2593 }
2594 }
2595
Chris Lattner20a0c612009-04-14 21:34:55 +00002596 // Otherwise, if we don't consume this token, we are going to emit an
2597 // error anyway. Try to recover from various common problems. Check
2598 // to see if this was a reference to a tag name without a tag specified.
2599 // This is a common problem in C (saying 'foo' instead of 'struct foo').
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002600 //
2601 // C++ doesn't need this, and isTagName doesn't take SS.
Craig Topper161e4db2014-05-21 06:02:52 +00002602 if (SS == nullptr) {
2603 const char *TagName = nullptr, *FixitTagName = nullptr;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002604 tok::TokenKind TagKind = tok::unknown;
Mike Stump11289f42009-09-09 15:08:12 +00002605
Douglas Gregor0be31a22010-07-02 17:43:08 +00002606 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002607 default: break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002608 case DeclSpec::TST_enum:
2609 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2610 case DeclSpec::TST_union:
2611 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2612 case DeclSpec::TST_struct:
2613 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
Joao Matosdc86f942012-08-31 18:45:21 +00002614 case DeclSpec::TST_interface:
2615 TagName="__interface"; FixitTagName = "__interface ";
2616 TagKind=tok::kw___interface;break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002617 case DeclSpec::TST_class:
2618 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
Chris Lattner20a0c612009-04-14 21:34:55 +00002619 }
Mike Stump11289f42009-09-09 15:08:12 +00002620
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002621 if (TagName) {
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002622 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2623 LookupResult R(Actions, TokenName, SourceLocation(),
2624 Sema::LookupOrdinaryName);
2625
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002626 Diag(Loc, diag::err_use_of_tag_name_without_tag)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002627 << TokenName << TagName << getLangOpts().CPlusPlus
2628 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2629
2630 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2631 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2632 I != IEnd; ++I)
Kaelyn Uhrain3fe3f852012-04-27 18:26:49 +00002633 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002634 << TokenName << TagName;
2635 }
Mike Stump11289f42009-09-09 15:08:12 +00002636
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002637 // Parse this as a tag as if the missing tag were present.
2638 if (TagKind == tok::kw_enum)
Faisal Vali7db85c52017-12-31 00:06:40 +00002639 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2640 DeclSpecContext::DSC_normal);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002641 else
Richard Smithc5b05522012-03-12 07:56:15 +00002642 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
Faisal Vali7db85c52017-12-31 00:06:40 +00002643 /*EnteringContext*/ false,
2644 DeclSpecContext::DSC_normal, Attrs);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002645 return true;
2646 }
Chris Lattner20a0c612009-04-14 21:34:55 +00002647 }
Mike Stump11289f42009-09-09 15:08:12 +00002648
Richard Smithfe904f02012-05-15 21:29:55 +00002649 // Determine whether this identifier could plausibly be the name of something
Richard Smithedd124e2012-05-15 21:42:17 +00002650 // being declared (with a missing type).
Faisal Vali7db85c52017-12-31 00:06:40 +00002651 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2652 DSC == DeclSpecContext::DSC_class)) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002653 // Look ahead to the next token to try to figure out what this declaration
2654 // was supposed to be.
2655 switch (NextToken().getKind()) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002656 case tok::l_paren: {
2657 // static x(4); // 'x' is not a type
2658 // x(int n); // 'x' is not a type
2659 // x (*p)[]; // 'x' is a type
2660 //
Richard Smitha0a5d502014-05-08 22:32:00 +00002661 // Since we're in an error case, we can afford to perform a tentative
2662 // parse to determine which case we're in.
Richard Smitha952ebb2012-05-15 21:01:51 +00002663 TentativeParsingAction PA(*this);
2664 ConsumeToken();
2665 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2666 PA.Revert();
Richard Smithfb8b7b92013-10-15 00:00:26 +00002667
Richard Smithee390432014-05-16 01:56:53 +00002668 if (TPR != TPResult::False) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002669 // The identifier is followed by a parenthesized declarator.
2670 // It's supposed to be a type.
2671 break;
2672 }
2673
2674 // If we're in a context where we could be declaring a constructor,
2675 // check whether this is a constructor declaration with a bogus name.
Faisal Vali7db85c52017-12-31 00:06:40 +00002676 if (DSC == DeclSpecContext::DSC_class ||
2677 (DSC == DeclSpecContext::DSC_top_level && SS)) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002678 IdentifierInfo *II = Tok.getIdentifierInfo();
2679 if (Actions.isCurrentClassNameTypo(II, SS)) {
2680 Diag(Loc, diag::err_constructor_bad_name)
2681 << Tok.getIdentifierInfo() << II
2682 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2683 Tok.setIdentifierInfo(II);
2684 }
2685 }
2686 // Fall through.
Galina Kistanova77674252017-06-01 21:15:34 +00002687 LLVM_FALLTHROUGH;
Richard Smitha952ebb2012-05-15 21:01:51 +00002688 }
Richard Smithfb8b7b92013-10-15 00:00:26 +00002689 case tok::comma:
2690 case tok::equal:
2691 case tok::kw_asm:
2692 case tok::l_brace:
2693 case tok::l_square:
2694 case tok::semi:
2695 // This looks like a variable or function declaration. The type is
2696 // probably missing. We're done parsing decl-specifiers.
Nicolas Lesseree057172019-05-05 12:15:17 +00002697 // But only if we are not in a function prototype scope.
2698 if (getCurScope()->isFunctionPrototypeScope())
2699 break;
Richard Smithfb8b7b92013-10-15 00:00:26 +00002700 if (SS)
2701 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2702 return false;
Richard Smitha952ebb2012-05-15 21:01:51 +00002703
2704 default:
2705 // This is probably supposed to be a type. This includes cases like:
2706 // int f(itn);
2707 // struct S { unsinged : 4; };
2708 break;
2709 }
2710 }
2711
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002712 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2713 // and attempt to recover.
John McCallba7bf592010-08-24 05:47:05 +00002714 ParsedType T;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +00002715 IdentifierInfo *II = Tok.getIdentifierInfo();
Richard Smith52f8d192017-05-10 21:32:16 +00002716 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002717 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
Richard Smith52f8d192017-05-10 21:32:16 +00002718 IsTemplateName);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002719 if (T) {
2720 // The action has suggested that the type T could be used. Set that as
2721 // the type in the declaration specifiers, consume the would-be type
2722 // name token, and we're done.
2723 const char *PrevSpec;
2724 unsigned DiagID;
2725 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2726 Actions.getASTContext().getPrintingPolicy());
2727 DS.SetRangeEnd(Tok.getLocation());
2728 ConsumeToken();
2729 // There may be other declaration specifiers after this.
2730 return true;
2731 } else if (II != Tok.getIdentifierInfo()) {
2732 // If no type was suggested, the correction is to a keyword
2733 Tok.setKind(II->getTokenID());
2734 // There may be other declaration specifiers after this.
2735 return true;
Douglas Gregor15e56022009-10-13 23:27:22 +00002736 }
Mike Stump11289f42009-09-09 15:08:12 +00002737
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002738 // Otherwise, the action had no suggestion for us. Mark this as an error.
Richard Smithc5b05522012-03-12 07:56:15 +00002739 DS.SetTypeSpecError();
Chris Lattner20a0c612009-04-14 21:34:55 +00002740 DS.SetRangeEnd(Tok.getLocation());
2741 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002742
Richard Smith52f8d192017-05-10 21:32:16 +00002743 // Eat any following template arguments.
2744 if (IsTemplateName) {
2745 SourceLocation LAngle, RAngle;
2746 TemplateArgList Args;
2747 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2748 }
2749
Chris Lattner20a0c612009-04-14 21:34:55 +00002750 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2751 // avoid rippling error messages on subsequent uses of the same type,
2752 // could be useful if #include was forgotten.
Richard Smithb3065792019-05-07 07:36:07 +00002753 return true;
Chris Lattner20a0c612009-04-14 21:34:55 +00002754}
2755
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002756/// Determine the declaration specifier context from the declarator
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002757/// context.
2758///
2759/// \param Context the declarator context, which is one of the
Faisal Vali421b2d12017-12-29 05:41:00 +00002760/// DeclaratorContext enumerator values.
Chad Rosierc1183952012-06-26 22:30:43 +00002761Parser::DeclSpecContext
Faisal Vali421b2d12017-12-29 05:41:00 +00002762Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2763 if (Context == DeclaratorContext::MemberContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002764 return DeclSpecContext::DSC_class;
Faisal Vali421b2d12017-12-29 05:41:00 +00002765 if (Context == DeclaratorContext::FileContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002766 return DeclSpecContext::DSC_top_level;
Faisal Vali421b2d12017-12-29 05:41:00 +00002767 if (Context == DeclaratorContext::TemplateParamContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002768 return DeclSpecContext::DSC_template_param;
Richard Smith77a9c602018-02-28 03:02:23 +00002769 if (Context == DeclaratorContext::TemplateArgContext ||
2770 Context == DeclaratorContext::TemplateTypeArgContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002771 return DeclSpecContext::DSC_template_type_arg;
Richard Smithe303e352018-02-02 22:24:54 +00002772 if (Context == DeclaratorContext::TrailingReturnContext ||
2773 Context == DeclaratorContext::TrailingReturnVarContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002774 return DeclSpecContext::DSC_trailing;
Faisal Vali421b2d12017-12-29 05:41:00 +00002775 if (Context == DeclaratorContext::AliasDeclContext ||
2776 Context == DeclaratorContext::AliasTemplateContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002777 return DeclSpecContext::DSC_alias_declaration;
2778 return DeclSpecContext::DSC_normal;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002779}
2780
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002781/// ParseAlignArgument - Parse the argument to an alignment-specifier.
2782///
2783/// FIXME: Simply returns an alignof() expression if the argument is a
2784/// type. Ideally, the type should be propagated directly into Sema.
2785///
Benjamin Kramere56f3932011-12-23 17:00:35 +00002786/// [C11] type-id
2787/// [C11] constant-expression
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002788/// [C++0x] type-id ...[opt]
2789/// [C++0x] assignment-expression ...[opt]
2790ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2791 SourceLocation &EllipsisLoc) {
2792 ExprResult ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002793 if (isTypeIdInParens()) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002794 SourceLocation TypeLoc = Tok.getLocation();
2795 ParsedType Ty = ParseTypeName().get();
2796 SourceRange TypeRange(Start, Tok.getLocation());
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002797 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2798 Ty.getAsOpaquePtr(), TypeRange);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002799 } else
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002800 ER = ParseConstantExpression();
2801
Alp Toker8fbec672013-12-17 23:29:36 +00002802 if (getLangOpts().CPlusPlus11)
2803 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002804
2805 return ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002806}
2807
2808/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2809/// attribute to Attrs.
2810///
2811/// alignment-specifier:
Benjamin Kramere56f3932011-12-23 17:00:35 +00002812/// [C11] '_Alignas' '(' type-id ')'
2813/// [C11] '_Alignas' '(' constant-expression ')'
Richard Smithd11c7a12013-01-29 01:48:07 +00002814/// [C++11] 'alignas' '(' type-id ...[opt] ')'
2815/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002816void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
Richard Smith44c247f2013-02-22 08:32:16 +00002817 SourceLocation *EndLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002818 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002819 "Not an alignment-specifier!");
2820
Richard Smithd11c7a12013-01-29 01:48:07 +00002821 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2822 SourceLocation KWLoc = ConsumeToken();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002823
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002824 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002825 if (T.expectAndConsume())
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002826 return;
2827
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002828 SourceLocation EllipsisLoc;
2829 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002830 if (ArgExpr.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002831 T.skipToEnd();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002832 return;
2833 }
2834
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002835 T.consumeClose();
Richard Smith44c247f2013-02-22 08:32:16 +00002836 if (EndLoc)
2837 *EndLoc = T.getCloseLocation();
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002838
Aaron Ballman00e99962013-08-31 01:11:41 +00002839 ArgsVector ArgExprs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002840 ArgExprs.push_back(ArgExpr.get());
Craig Topper161e4db2014-05-21 06:02:52 +00002841 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
Erich Keanee891aa92018-07-13 15:07:47 +00002842 ParsedAttr::AS_Keyword, EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002843}
2844
Richard Smith404dfb42013-11-19 22:47:36 +00002845/// Determine whether we're looking at something that might be a declarator
2846/// in a simple-declaration. If it can't possibly be a declarator, maybe
2847/// diagnose a missing semicolon after a prior tag definition in the decl
2848/// specifier.
2849///
2850/// \return \c true if an error occurred and this can't be any kind of
2851/// declaration.
2852bool
2853Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2854 DeclSpecContext DSContext,
2855 LateParsedAttrList *LateAttrs) {
2856 assert(DS.hasTagDefinition() && "shouldn't call this");
2857
Faisal Vali7db85c52017-12-31 00:06:40 +00002858 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2859 DSContext == DeclSpecContext::DSC_top_level);
Richard Smith404dfb42013-11-19 22:47:36 +00002860
2861 if (getLangOpts().CPlusPlus &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002862 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2863 tok::annot_template_id) &&
Richard Smith404dfb42013-11-19 22:47:36 +00002864 TryAnnotateCXXScopeToken(EnteringContext)) {
2865 SkipMalformedDecl();
2866 return true;
2867 }
2868
Richard Smith698875a2013-11-20 23:40:57 +00002869 bool HasScope = Tok.is(tok::annot_cxxscope);
2870 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2871 Token AfterScope = HasScope ? NextToken() : Tok;
2872
Richard Smith404dfb42013-11-19 22:47:36 +00002873 // Determine whether the following tokens could possibly be a
2874 // declarator.
Richard Smith698875a2013-11-20 23:40:57 +00002875 bool MightBeDeclarator = true;
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002876 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
Richard Smith698875a2013-11-20 23:40:57 +00002877 // A declarator-id can't start with 'typename'.
2878 MightBeDeclarator = false;
2879 } else if (AfterScope.is(tok::annot_template_id)) {
2880 // If we have a type expressed as a template-id, this cannot be a
2881 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2882 TemplateIdAnnotation *Annot =
2883 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2884 if (Annot->Kind == TNK_Type_template)
2885 MightBeDeclarator = false;
2886 } else if (AfterScope.is(tok::identifier)) {
2887 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2888
Richard Smith404dfb42013-11-19 22:47:36 +00002889 // These tokens cannot come after the declarator-id in a
2890 // simple-declaration, and are likely to come after a type-specifier.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002891 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2892 tok::annot_cxxscope, tok::coloncolon)) {
Richard Smith698875a2013-11-20 23:40:57 +00002893 // Missing a semicolon.
2894 MightBeDeclarator = false;
2895 } else if (HasScope) {
2896 // If the declarator-id has a scope specifier, it must redeclare a
2897 // previously-declared entity. If that's a type (and this is not a
2898 // typedef), that's an error.
2899 CXXScopeSpec SS;
2900 Actions.RestoreNestedNameSpecifierAnnotation(
2901 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2902 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2903 Sema::NameClassification Classification = Actions.ClassifyName(
2904 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
Bruno Ricci70ad3962019-03-25 17:08:51 +00002905 /*IsAddressOfOperand=*/false, /*CCC=*/nullptr);
Richard Smith698875a2013-11-20 23:40:57 +00002906 switch (Classification.getKind()) {
2907 case Sema::NC_Error:
2908 SkipMalformedDecl();
2909 return true;
Richard Smith404dfb42013-11-19 22:47:36 +00002910
Richard Smith698875a2013-11-20 23:40:57 +00002911 case Sema::NC_Keyword:
2912 case Sema::NC_NestedNameSpecifier:
2913 llvm_unreachable("typo correction and nested name specifiers not "
2914 "possible here");
Richard Smith404dfb42013-11-19 22:47:36 +00002915
Richard Smith698875a2013-11-20 23:40:57 +00002916 case Sema::NC_Type:
2917 case Sema::NC_TypeTemplate:
2918 // Not a previously-declared non-type entity.
2919 MightBeDeclarator = false;
2920 break;
Richard Smith404dfb42013-11-19 22:47:36 +00002921
Richard Smith698875a2013-11-20 23:40:57 +00002922 case Sema::NC_Unknown:
2923 case Sema::NC_Expression:
2924 case Sema::NC_VarTemplate:
2925 case Sema::NC_FunctionTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00002926 case Sema::NC_UndeclaredTemplate:
Richard Smith698875a2013-11-20 23:40:57 +00002927 // Might be a redeclaration of a prior entity.
2928 break;
2929 }
Richard Smith404dfb42013-11-19 22:47:36 +00002930 }
Richard Smith404dfb42013-11-19 22:47:36 +00002931 }
2932
Richard Smith698875a2013-11-20 23:40:57 +00002933 if (MightBeDeclarator)
Richard Smith404dfb42013-11-19 22:47:36 +00002934 return false;
2935
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002936 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002937 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
Alp Toker383d2c42014-01-01 03:08:43 +00002938 diag::err_expected_after)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002939 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
Richard Smith404dfb42013-11-19 22:47:36 +00002940
2941 // Try to recover from the typo, by dropping the tag definition and parsing
2942 // the problematic tokens as a type.
2943 //
2944 // FIXME: Split the DeclSpec into pieces for the standalone
2945 // declaration and pieces for the following declaration, instead
2946 // of assuming that all the other pieces attach to new declaration,
2947 // and call ParsedFreeStandingDeclSpec as appropriate.
2948 DS.ClearTypeSpecType();
2949 ParsedTemplateInfo NotATemplate;
Faisal Valia534f072018-04-26 00:42:40 +00002950 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
Richard Smith404dfb42013-11-19 22:47:36 +00002951 return false;
2952}
2953
Leonard Chanab80f3c2018-06-14 14:53:51 +00002954// Choose the apprpriate diagnostic error for why fixed point types are
2955// disabled, set the previous specifier, and mark as invalid.
2956static void SetupFixedPointError(const LangOptions &LangOpts,
2957 const char *&PrevSpec, unsigned &DiagID,
2958 bool &isInvalid) {
2959 assert(!LangOpts.FixedPoint);
2960 DiagID = diag::err_fixed_point_not_enabled;
2961 PrevSpec = ""; // Not used by diagnostic
2962 isInvalid = true;
2963}
2964
Faisal Valia534f072018-04-26 00:42:40 +00002965/// ParseDeclarationSpecifiers
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002966/// declaration-specifiers: [C99 6.7]
Chris Lattner3b561a32006-08-13 00:12:11 +00002967/// storage-class-specifier declaration-specifiers[opt]
2968/// type-specifier declaration-specifiers[opt]
Chris Lattner3b561a32006-08-13 00:12:11 +00002969/// [C99] function-specifier declaration-specifiers[opt]
Benjamin Kramere56f3932011-12-23 17:00:35 +00002970/// [C11] alignment-specifier declaration-specifiers[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002971/// [GNU] attributes declaration-specifiers[opt]
Douglas Gregor26701a42011-09-09 02:06:17 +00002972/// [Clang] '__module_private__' declaration-specifiers[opt]
Douglas Gregorab209d82015-07-07 03:58:42 +00002973/// [ObjC1] '__kindof' declaration-specifiers[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002974///
Chris Lattnerf63f89a2006-08-05 03:28:50 +00002975/// storage-class-specifier: [C99 6.7.1]
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002976/// 'typedef'
2977/// 'extern'
2978/// 'static'
2979/// 'auto'
2980/// 'register'
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002981/// [C++] 'mutable'
Richard Smithb4a9e862013-04-12 22:46:28 +00002982/// [C++11] 'thread_local'
2983/// [C11] '_Thread_local'
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002984/// [GNU] '__thread'
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002985/// function-specifier: [C99 6.7.4]
Chris Lattner3b561a32006-08-13 00:12:11 +00002986/// [C99] 'inline'
Douglas Gregor61956c42008-10-31 09:07:45 +00002987/// [C++] 'virtual'
2988/// [C++] 'explicit'
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00002989/// [OpenCL] '__kernel'
Anders Carlssoncd8db412009-05-06 04:46:28 +00002990/// 'friend': [C++ dcl.friend]
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00002991/// 'constexpr': [C++0x dcl.constexpr]
Faisal Valia534f072018-04-26 00:42:40 +00002992void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002993 const ParsedTemplateInfo &TemplateInfo,
John McCall07e91c02009-08-06 02:15:43 +00002994 AccessSpecifier AS,
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002995 DeclSpecContext DSContext,
2996 LateParsedAttrList *LateAttrs) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002997 if (DS.getSourceRange().isInvalid()) {
David Majnemer24b28302014-07-26 05:41:31 +00002998 // Start the range at the current token but make the end of the range
2999 // invalid. This will make the entire range invalid unless we successfully
3000 // consume a token.
Douglas Gregor0e7dde52011-04-24 05:37:28 +00003001 DS.SetRangeStart(Tok.getLocation());
David Majnemer24b28302014-07-26 05:41:31 +00003002 DS.SetRangeEnd(SourceLocation());
Douglas Gregor0e7dde52011-04-24 05:37:28 +00003003 }
Chad Rosierc1183952012-06-26 22:30:43 +00003004
Faisal Vali7db85c52017-12-31 00:06:40 +00003005 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3006 DSContext == DeclSpecContext::DSC_top_level);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003007 bool AttrsLastTime = false;
3008 ParsedAttributesWithRange attrs(AttrFactory);
Benjamin Kramere4812142015-03-12 14:28:38 +00003009 // We use Sema's policy to get bool macros right.
Richard Smith301bc212016-05-19 01:39:10 +00003010 PrintingPolicy Policy = Actions.getPrintingPolicy();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003011 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00003012 bool isInvalid = false;
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003013 bool isStorageClass = false;
Craig Topper161e4db2014-05-21 06:02:52 +00003014 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00003015 unsigned DiagID = 0;
3016
Richard Smithba24f352019-05-09 19:45:46 +00003017 // This value needs to be set to the location of the last token if the last
3018 // token of the specifier is already consumed.
3019 SourceLocation ConsumedEnd;
Richard Smith76b90272019-05-09 03:59:21 +00003020
David Majnemer51fd8a02015-07-22 23:46:18 +00003021 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3022 // implementation for VS2013 uses _Atomic as an identifier for one of the
3023 // classes in <atomic>.
3024 //
3025 // A typedef declaration containing _Atomic<...> is among the places where
3026 // the class is used. If we are currently parsing such a declaration, treat
3027 // the token as an identifier.
3028 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3029 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
3030 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3031 Tok.setKind(tok::identifier);
3032
Chris Lattner4d8f8732006-11-28 05:05:08 +00003033 SourceLocation Loc = Tok.getLocation();
Douglas Gregor450c75a2008-11-07 15:42:26 +00003034
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003035 switch (Tok.getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00003036 default:
Chris Lattner0974b232008-07-26 00:20:22 +00003037 DoneWithDeclSpec:
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003038 if (!AttrsLastTime)
3039 ProhibitAttributes(attrs);
Michael Han64536a62012-11-06 19:34:54 +00003040 else {
3041 // Reject C++11 attributes that appertain to decl specifiers as
3042 // we don't support any C++11 attributes that appertain to decl
3043 // specifiers. This also conforms to what g++ 4.8 is doing.
Richard Smith49cc1cc2016-08-18 21:59:42 +00003044 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
Michael Han64536a62012-11-06 19:34:54 +00003045
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003046 DS.takeAttributesFrom(attrs);
Michael Han64536a62012-11-06 19:34:54 +00003047 }
Peter Collingbourne70188b32011-09-29 18:03:57 +00003048
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003049 // If this is not a declaration specifier token, we're done reading decl
3050 // specifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00003051 DS.Finish(Actions, Policy);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003052 return;
Mike Stump11289f42009-09-09 15:08:12 +00003053
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003054 case tok::l_square:
3055 case tok::kw_alignas:
Aaron Ballman606093a2017-10-15 15:01:42 +00003056 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003057 goto DoneWithDeclSpec;
3058
3059 ProhibitAttributes(attrs);
3060 // FIXME: It would be good to recover by accepting the attributes,
3061 // but attempting to do that now would cause serious
3062 // madness in terms of diagnostics.
3063 attrs.clear();
3064 attrs.Range = SourceRange();
3065
3066 ParseCXX11Attributes(attrs);
3067 AttrsLastTime = true;
Chad Rosierc1183952012-06-26 22:30:43 +00003068 continue;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003069
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003070 case tok::code_completion: {
John McCallfaf5fb42010-08-26 23:41:50 +00003071 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003072 if (DS.hasTypeSpecifier()) {
3073 bool AllowNonIdentifiers
3074 = (getCurScope()->getFlags() & (Scope::ControlScope |
3075 Scope::BlockScope |
3076 Scope::TemplateParamScope |
3077 Scope::FunctionPrototypeScope |
3078 Scope::AtCatchScope)) == 0;
3079 bool AllowNestedNameSpecifiers
Faisal Vali7db85c52017-12-31 00:06:40 +00003080 = DSContext == DeclSpecContext::DSC_top_level ||
3081 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003082
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003083 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
Chad Rosierc1183952012-06-26 22:30:43 +00003084 AllowNonIdentifiers,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003085 AllowNestedNameSpecifiers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003086 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00003087 }
3088
Douglas Gregor80039242011-02-15 20:33:25 +00003089 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3090 CCC = Sema::PCC_LocalDeclarationSpecifiers;
3091 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
Faisal Vali7db85c52017-12-31 00:06:40 +00003092 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3093 : Sema::PCC_Template;
3094 else if (DSContext == DeclSpecContext::DSC_class)
John McCallfaf5fb42010-08-26 23:41:50 +00003095 CCC = Sema::PCC_Class;
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +00003096 else if (CurParsedObjCImpl)
John McCallfaf5fb42010-08-26 23:41:50 +00003097 CCC = Sema::PCC_ObjCImplementation;
Chad Rosierc1183952012-06-26 22:30:43 +00003098
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003099 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003100 return cutOffParsing();
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003101 }
3102
Chris Lattnerbd31aa32009-01-05 00:07:25 +00003103 case tok::coloncolon: // ::foo::bar
John McCall1f476a12010-02-26 08:45:28 +00003104 // C++ scope specifier. Annotate and loop, or bail out on error.
Eli Friedman2a1d9a92013-08-15 23:59:20 +00003105 if (TryAnnotateCXXScopeToken(EnteringContext)) {
John McCall1f476a12010-02-26 08:45:28 +00003106 if (!DS.hasTypeSpecifier())
3107 DS.SetTypeSpecError();
3108 goto DoneWithDeclSpec;
3109 }
John McCall8bc2a702010-03-01 18:20:46 +00003110 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3111 goto DoneWithDeclSpec;
John McCall1f476a12010-02-26 08:45:28 +00003112 continue;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003113
3114 case tok::annot_cxxscope: {
Richard Smith3092a3b2012-05-09 18:56:43 +00003115 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003116 goto DoneWithDeclSpec;
3117
John McCall9dab4e62009-12-12 11:40:51 +00003118 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00003119 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3120 Tok.getAnnotationRange(),
3121 SS);
John McCall9dab4e62009-12-12 11:40:51 +00003122
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003123 // We are looking for a qualified typename.
Douglas Gregor167fa622009-03-25 15:40:00 +00003124 Token Next = NextToken();
Mike Stump11289f42009-09-09 15:08:12 +00003125 if (Next.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003126 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
Douglas Gregorb67535d2009-03-31 00:43:58 +00003127 ->Kind == TNK_Type_template) {
Douglas Gregor167fa622009-03-25 15:40:00 +00003128 // We have a qualified template-id, e.g., N::A<int>
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003129
Richard Smith74f02342017-01-19 21:00:13 +00003130 // If this would be a valid constructor declaration with template
3131 // arguments, we will reject the attempt to form an invalid type-id
3132 // referring to the injected-class-name when we annotate the token,
3133 // per C++ [class.qual]p2.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003134 //
Richard Smith74f02342017-01-19 21:00:13 +00003135 // To improve diagnostics for this case, parse the declaration as a
3136 // constructor (and reject the extra template arguments later).
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003137 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
Faisal Vali7db85c52017-12-31 00:06:40 +00003138 if ((DSContext == DeclSpecContext::DSC_top_level ||
3139 DSContext == DeclSpecContext::DSC_class) &&
John McCall84821e72010-04-13 06:39:49 +00003140 TemplateId->Name &&
Richard Smith74f02342017-01-19 21:00:13 +00003141 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003142 isConstructorDeclarator(/*Unqualified*/ false)) {
Richard Smith74f02342017-01-19 21:00:13 +00003143 // The user meant this to be an out-of-line constructor
3144 // definition, but template arguments are not allowed
3145 // there. Just allow this as a constructor; we'll
3146 // complain about it later.
3147 goto DoneWithDeclSpec;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003148 }
3149
John McCall9dab4e62009-12-12 11:40:51 +00003150 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003151 ConsumeAnnotationToken(); // The C++ scope.
Mike Stump11289f42009-09-09 15:08:12 +00003152 assert(Tok.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003153 "ParseOptionalCXXScopeSpecifier not working");
Douglas Gregore7c20652011-03-02 00:47:37 +00003154 AnnotateTemplateIdTokenAsType();
Douglas Gregor167fa622009-03-25 15:40:00 +00003155 continue;
3156 }
3157
Douglas Gregorc5790df2009-09-28 07:26:33 +00003158 if (Next.is(tok::annot_typename)) {
John McCall9dab4e62009-12-12 11:40:51 +00003159 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003160 ConsumeAnnotationToken(); // The C++ scope.
John McCallba7bf592010-08-24 05:47:05 +00003161 if (Tok.getAnnotationValue()) {
3162 ParsedType T = getTypeAnnotation(Tok);
Nico Weber77430342010-11-22 10:30:56 +00003163 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
Chad Rosierc1183952012-06-26 22:30:43 +00003164 Tok.getAnnotationEndLoc(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003165 PrevSpec, DiagID, T, Policy);
Richard Smithda837032012-09-14 18:27:01 +00003166 if (isInvalid)
3167 break;
John McCallba7bf592010-08-24 05:47:05 +00003168 }
Douglas Gregorc5790df2009-09-28 07:26:33 +00003169 else
3170 DS.SetTypeSpecError();
3171 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003172 ConsumeAnnotationToken(); // The typename
Douglas Gregorc5790df2009-09-28 07:26:33 +00003173 }
3174
Douglas Gregor167fa622009-03-25 15:40:00 +00003175 if (Next.isNot(tok::identifier))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003176 goto DoneWithDeclSpec;
3177
Richard Smith74f02342017-01-19 21:00:13 +00003178 // Check whether this is a constructor declaration. If we're in a
3179 // context where the identifier could be a class name, and it has the
3180 // shape of a constructor declaration, process it as one.
Faisal Vali7db85c52017-12-31 00:06:40 +00003181 if ((DSContext == DeclSpecContext::DSC_top_level ||
3182 DSContext == DeclSpecContext::DSC_class) &&
Chad Rosierc1183952012-06-26 22:30:43 +00003183 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
Richard Smith74f02342017-01-19 21:00:13 +00003184 &SS) &&
3185 isConstructorDeclarator(/*Unqualified*/ false))
3186 goto DoneWithDeclSpec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003187
David Blaikieefdccaa2016-01-15 23:43:34 +00003188 ParsedType TypeRep =
3189 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3190 getCurScope(), &SS, false, false, nullptr,
3191 /*IsCtorOrDtorName=*/false,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003192 /*WantNontrivialTypeSourceInfo=*/true,
Richard Smith600b5262017-01-26 20:40:47 +00003193 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003194
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003195 // If the referenced identifier is not a type, then this declspec is
3196 // erroneous: We already checked about that it has no type specifier, and
3197 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
Mike Stump11289f42009-09-09 15:08:12 +00003198 // typename.
David Blaikie7d170102013-05-15 07:37:26 +00003199 if (!TypeRep) {
Richard Smithaf3b3252017-05-18 19:21:48 +00003200 // Eat the scope spec so the identifier is current.
3201 ConsumeAnnotationToken();
Michael Han9407e502012-11-26 22:54:45 +00003202 ParsedAttributesWithRange Attrs(AttrFactory);
3203 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3204 if (!Attrs.empty()) {
3205 AttrsLastTime = true;
3206 attrs.takeAllFrom(Attrs);
3207 }
3208 continue;
3209 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003210 goto DoneWithDeclSpec;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003211 }
Mike Stump11289f42009-09-09 15:08:12 +00003212
John McCall9dab4e62009-12-12 11:40:51 +00003213 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003214 ConsumeAnnotationToken(); // The C++ scope.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003215
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003216 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003217 DiagID, TypeRep, Policy);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003218 if (isInvalid)
3219 break;
Mike Stump11289f42009-09-09 15:08:12 +00003220
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003221 DS.SetRangeEnd(Tok.getLocation());
3222 ConsumeToken(); // The typename.
3223
3224 continue;
3225 }
Mike Stump11289f42009-09-09 15:08:12 +00003226
Chris Lattnere387d9e2009-01-21 19:48:37 +00003227 case tok::annot_typename: {
Richard Smith404dfb42013-11-19 22:47:36 +00003228 // If we've previously seen a tag definition, we were almost surely
3229 // missing a semicolon after it.
3230 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3231 goto DoneWithDeclSpec;
3232
John McCallba7bf592010-08-24 05:47:05 +00003233 if (Tok.getAnnotationValue()) {
3234 ParsedType T = getTypeAnnotation(Tok);
Nico Weber7f8bb362010-11-22 12:50:03 +00003235 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003236 DiagID, T, Policy);
John McCallba7bf592010-08-24 05:47:05 +00003237 } else
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003238 DS.SetTypeSpecError();
Chad Rosierc1183952012-06-26 22:30:43 +00003239
Chris Lattner005fc1b2010-04-05 18:18:31 +00003240 if (isInvalid)
3241 break;
3242
Chris Lattnere387d9e2009-01-21 19:48:37 +00003243 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003244 ConsumeAnnotationToken(); // The typename
Mike Stump11289f42009-09-09 15:08:12 +00003245
Chris Lattnere387d9e2009-01-21 19:48:37 +00003246 continue;
3247 }
Mike Stump11289f42009-09-09 15:08:12 +00003248
Douglas Gregor06873092011-04-28 15:48:45 +00003249 case tok::kw___is_signed:
3250 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3251 // typically treats it as a trait. If we see __is_signed as it appears
3252 // in libstdc++, e.g.,
3253 //
3254 // static const bool __is_signed;
3255 //
3256 // then treat __is_signed as an identifier rather than as a keyword.
Faisal Vali090da2d2018-01-01 18:23:28 +00003257 if (DS.getTypeSpecType() == TST_bool &&
Douglas Gregor06873092011-04-28 15:48:45 +00003258 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
Alp Toker47642d22013-12-03 06:13:01 +00003259 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3260 TryKeywordIdentFallback(true);
Douglas Gregor06873092011-04-28 15:48:45 +00003261
3262 // We're done with the declaration-specifiers.
3263 goto DoneWithDeclSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00003264
Chris Lattner16fac4f2008-07-26 01:18:38 +00003265 // typedef-name
Nikola Smiljanic67860242014-09-26 00:28:20 +00003266 case tok::kw___super:
David Blaikie15a430a2011-12-04 05:04:18 +00003267 case tok::kw_decltype:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003268 case tok::identifier: {
Reid Klecknerc582f012014-07-14 18:19:58 +00003269 // This identifier can only be a typedef name if we haven't already seen
3270 // a type-specifier. Without this check we misparse:
3271 // typedef int X; struct Y { short X; }; as 'short int'.
3272 if (DS.hasTypeSpecifier())
3273 goto DoneWithDeclSpec;
3274
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003275 // If the token is an identifier named "__declspec" and Microsoft
3276 // extensions are not enabled, it is likely that there will be cascading
3277 // parse errors if this really is a __declspec attribute. Attempt to
3278 // recognize that scenario and recover gracefully.
3279 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3280 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3281 Diag(Loc, diag::err_ms_attributes_not_enabled);
3282
3283 // The next token should be an open paren. If it is, eat the entire
3284 // attribute declaration and continue.
3285 if (NextToken().is(tok::l_paren)) {
3286 // Consume the __declspec identifier.
Richard Trieuba057372017-02-14 23:56:55 +00003287 ConsumeToken();
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003288
3289 // Eat the parens and everything between them.
3290 BalancedDelimiterTracker T(*this, tok::l_paren);
3291 if (T.consumeOpen()) {
3292 assert(false && "Not a left paren?");
3293 return;
3294 }
3295 T.skipToEnd();
3296 continue;
3297 }
3298 }
3299
Serge Pavlov458ea762014-07-16 05:16:52 +00003300 // In C++, check to see if this is a scope specifier like foo::bar::, if
3301 // so handle it as such. This is important for ctor parsing.
3302 if (getLangOpts().CPlusPlus) {
3303 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3304 DS.SetTypeSpecError();
3305 goto DoneWithDeclSpec;
3306 }
3307 if (!Tok.is(tok::identifier))
3308 continue;
3309 }
3310
John Thompson22334602010-02-05 00:12:22 +00003311 // Check for need to substitute AltiVec keyword tokens.
3312 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3313 break;
3314
Richard Smith3092a3b2012-05-09 18:56:43 +00003315 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3316 // allow the use of a typedef name as a type specifier.
3317 if (DS.isTypeAltiVecVector())
3318 goto DoneWithDeclSpec;
3319
Faisal Vali7db85c52017-12-31 00:06:40 +00003320 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3321 isObjCInstancetype()) {
Douglas Gregor5c0870a2015-06-19 23:18:00 +00003322 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3323 assert(TypeRep);
3324 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3325 DiagID, TypeRep, Policy);
3326 if (isInvalid)
3327 break;
3328
3329 DS.SetRangeEnd(Loc);
3330 ConsumeToken();
3331 continue;
3332 }
3333
Richard Smith715ee072018-06-20 21:58:20 +00003334 // If we're in a context where the identifier could be a class name,
3335 // check whether this is a constructor declaration.
3336 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3337 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3338 isConstructorDeclarator(/*Unqualified*/true))
3339 goto DoneWithDeclSpec;
3340
Richard Smith600b5262017-01-26 20:40:47 +00003341 ParsedType TypeRep = Actions.getTypeName(
3342 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3343 false, false, nullptr, false, false,
3344 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003345
Chris Lattner6cc055a2009-04-12 20:42:31 +00003346 // If this is not a typedef name, don't parse it as part of the declspec,
3347 // it must be an implicit int or an error.
John McCallba7bf592010-08-24 05:47:05 +00003348 if (!TypeRep) {
Michael Han9407e502012-11-26 22:54:45 +00003349 ParsedAttributesWithRange Attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +00003350 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
Michael Han9407e502012-11-26 22:54:45 +00003351 if (!Attrs.empty()) {
3352 AttrsLastTime = true;
3353 attrs.takeAllFrom(Attrs);
3354 }
3355 continue;
3356 }
Chris Lattner16fac4f2008-07-26 01:18:38 +00003357 goto DoneWithDeclSpec;
Chris Lattner6cc055a2009-04-12 20:42:31 +00003358 }
Douglas Gregor8bf42052009-02-09 18:46:07 +00003359
Richard Smith35845152017-02-07 01:37:30 +00003360 // Likewise, if this is a context where the identifier could be a template
3361 // name, check whether this is a deduction guide declaration.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003362 if (getLangOpts().CPlusPlus17 &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003363 (DSContext == DeclSpecContext::DSC_class ||
3364 DSContext == DeclSpecContext::DSC_top_level) &&
Richard Smith35845152017-02-07 01:37:30 +00003365 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3366 Tok.getLocation()) &&
3367 isConstructorDeclarator(/*Unqualified*/ true,
3368 /*DeductionGuide*/ true))
3369 goto DoneWithDeclSpec;
3370
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003371 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003372 DiagID, TypeRep, Policy);
Chris Lattner16fac4f2008-07-26 01:18:38 +00003373 if (isInvalid)
3374 break;
Mike Stump11289f42009-09-09 15:08:12 +00003375
Chris Lattner16fac4f2008-07-26 01:18:38 +00003376 DS.SetRangeEnd(Tok.getLocation());
3377 ConsumeToken(); // The identifier
3378
Douglas Gregore9d95f12015-07-07 03:57:35 +00003379 // Objective-C supports type arguments and protocol references
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003380 // following an Objective-C object or object pointer
3381 // type. Handle either one of them.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003382 if (Tok.is(tok::less) && getLangOpts().ObjC) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003383 SourceLocation NewEndLoc;
3384 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3385 Loc, TypeRep, /*consumeLastToken=*/true,
3386 NewEndLoc);
3387 if (NewTypeRep.isUsable()) {
3388 DS.UpdateTypeRep(NewTypeRep.get());
3389 DS.SetRangeEnd(NewEndLoc);
3390 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00003391 }
Chad Rosierc1183952012-06-26 22:30:43 +00003392
Steve Naroffcd5e7822008-09-22 10:28:57 +00003393 // Need to support trailing type qualifiers (e.g. "id<p> const").
3394 // If a type specifier follows, it will be diagnosed elsewhere.
3395 continue;
Chris Lattner16fac4f2008-07-26 01:18:38 +00003396 }
Douglas Gregor7f741122009-02-25 19:37:18 +00003397
3398 // type-name
3399 case tok::annot_template_id: {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003400 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithb23c5e82019-05-09 03:31:27 +00003401 if (TemplateId->Kind != TNK_Type_template &&
3402 TemplateId->Kind != TNK_Undeclared_template) {
Douglas Gregor7f741122009-02-25 19:37:18 +00003403 // This template-id does not refer to a type name, so we're
3404 // done with the type-specifiers.
3405 goto DoneWithDeclSpec;
3406 }
3407
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003408 // If we're in a context where the template-id could be a
3409 // constructor name or specialization, check whether this is a
3410 // constructor declaration.
Faisal Vali7db85c52017-12-31 00:06:40 +00003411 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00003412 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
Richard Smith446161b2014-03-03 21:12:53 +00003413 isConstructorDeclarator(TemplateId->SS.isEmpty()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003414 goto DoneWithDeclSpec;
3415
Douglas Gregor7f741122009-02-25 19:37:18 +00003416 // Turn the template-id annotation token into a type annotation
3417 // token, then try again to parse it as a type-specifier.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003418 AnnotateTemplateIdTokenAsType();
Douglas Gregor7f741122009-02-25 19:37:18 +00003419 continue;
3420 }
3421
Chris Lattnere37e2332006-08-15 04:50:22 +00003422 // GNU attributes support.
3423 case tok::kw___attribute:
Craig Topper161e4db2014-05-21 06:02:52 +00003424 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
Chris Lattnerb95cca02006-10-17 03:01:08 +00003425 continue;
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003426
3427 // Microsoft declspec support.
3428 case tok::kw___declspec:
Aaron Ballman068aa512015-05-20 20:58:33 +00003429 ParseMicrosoftDeclSpecs(DS.getAttributes());
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003430 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003431
Steve Naroff44ac7772008-12-25 14:16:32 +00003432 // Microsoft single token adornments.
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003433 case tok::kw___forceinline: {
Serge Pavlov750db652013-11-13 06:57:53 +00003434 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003435 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Richard Smithda837032012-09-14 18:27:01 +00003436 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00003437 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00003438 nullptr, 0, ParsedAttr::AS_Keyword);
Richard Smithda837032012-09-14 18:27:01 +00003439 break;
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003440 }
Eli Friedman53339e02009-06-08 23:27:34 +00003441
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003442 case tok::kw___unaligned:
3443 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3444 getLangOpts());
3445 break;
3446
Aaron Ballman317a77f2013-05-22 23:25:32 +00003447 case tok::kw___sptr:
3448 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00003449 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00003450 case tok::kw___ptr32:
Steve Narofff9c29d42008-12-25 14:41:26 +00003451 case tok::kw___w64:
Steve Naroff44ac7772008-12-25 14:16:32 +00003452 case tok::kw___cdecl:
3453 case tok::kw___stdcall:
3454 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00003455 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00003456 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00003457 case tok::kw___vectorcall:
John McCall53fa7142010-12-24 02:08:15 +00003458 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00003459 continue;
3460
Dawn Perchik335e16b2010-09-03 01:29:35 +00003461 // Borland single token adornments.
3462 case tok::kw___pascal:
John McCall53fa7142010-12-24 02:08:15 +00003463 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00003464 continue;
3465
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003466 // OpenCL single token adornments.
3467 case tok::kw___kernel:
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +00003468 ParseOpenCLKernelAttributes(DS.getAttributes());
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003469 continue;
3470
Douglas Gregor261a89b2015-06-19 17:51:05 +00003471 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00003472 case tok::kw__Nonnull:
3473 case tok::kw__Nullable:
3474 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00003475 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3476 continue;
3477
Douglas Gregorab209d82015-07-07 03:58:42 +00003478 // Objective-C 'kindof' types.
3479 case tok::kw___kindof:
3480 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00003481 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00003482 (void)ConsumeToken();
3483 continue;
3484
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003485 // storage-class-specifier
3486 case tok::kw_typedef:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003487 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003488 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003489 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003490 break;
3491 case tok::kw_extern:
Richard Smithb4a9e862013-04-12 22:46:28 +00003492 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003493 Diag(Tok, diag::ext_thread_before) << "extern";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003494 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003495 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003496 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003497 break;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003498 case tok::kw___private_extern__:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003499 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003500 Loc, PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003501 isStorageClass = true;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003502 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003503 case tok::kw_static:
Richard Smithb4a9e862013-04-12 22:46:28 +00003504 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003505 Diag(Tok, diag::ext_thread_before) << "static";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003506 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003507 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003508 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003509 break;
3510 case tok::kw_auto:
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003511 if (getLangOpts().CPlusPlus11) {
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003512 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003513 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003514 PrevSpec, DiagID, Policy);
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003515 if (!isInvalid)
Richard Smith58c74332011-09-04 19:54:14 +00003516 Diag(Tok, diag::ext_auto_storage_class)
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003517 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith58c74332011-09-04 19:54:14 +00003518 } else
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003519 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003520 DiagID, Policy);
Richard Smith58c74332011-09-04 19:54:14 +00003521 } else
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003522 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003523 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003524 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003525 break;
Richard Smithe301ba22015-11-11 02:02:15 +00003526 case tok::kw___auto_type:
3527 Diag(Tok, diag::ext_auto_type);
3528 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3529 DiagID, Policy);
3530 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003531 case tok::kw_register:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003532 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003533 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003534 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003535 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003536 case tok::kw_mutable:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003537 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003538 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003539 isStorageClass = true;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003540 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003541 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00003542 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3543 PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003544 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003545 break;
3546 case tok::kw_thread_local:
3547 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3548 PrevSpec, DiagID);
Sven van Haastregtc4100832018-04-24 14:47:29 +00003549 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003550 break;
3551 case tok::kw__Thread_local:
3552 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3553 Loc, PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003554 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003555 break;
Mike Stump11289f42009-09-09 15:08:12 +00003556
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003557 // function-specifier
3558 case tok::kw_inline:
Serge Pavlov750db652013-11-13 06:57:53 +00003559 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003560 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003561 case tok::kw_virtual:
Anastasia Stulova46b55fa2019-07-18 10:02:35 +00003562 // C++ for OpenCL does not allow virtual function qualifier, to avoid
3563 // function pointers restricted in OpenCL v2.0 s6.9.a.
Sven van Haastregt49ffffb2018-04-23 11:23:47 +00003564 if (getLangOpts().OpenCLCPlusPlus) {
3565 DiagID = diag::err_openclcxx_virtual_function;
3566 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3567 isInvalid = true;
3568 }
3569 else {
3570 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3571 }
Douglas Gregor61956c42008-10-31 09:07:45 +00003572 break;
Richard Smith76b90272019-05-09 03:59:21 +00003573 case tok::kw_explicit: {
3574 SourceLocation ExplicitLoc = Loc;
3575 SourceLocation CloseParenLoc;
3576 ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
Richard Smithba24f352019-05-09 19:45:46 +00003577 ConsumedEnd = ExplicitLoc;
Richard Smith76b90272019-05-09 03:59:21 +00003578 ConsumeToken(); // kw_explicit
3579 if (Tok.is(tok::l_paren)) {
3580 if (getLangOpts().CPlusPlus2a) {
3581 ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3582 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3583 Tracker.consumeOpen();
3584 ExplicitExpr = ParseConstantExpression();
Richard Smithba24f352019-05-09 19:45:46 +00003585 ConsumedEnd = Tok.getLocation();
Richard Smith76b90272019-05-09 03:59:21 +00003586 if (ExplicitExpr.isUsable()) {
3587 CloseParenLoc = Tok.getLocation();
3588 Tracker.consumeClose();
3589 ExplicitSpec =
3590 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3591 } else
3592 Tracker.skipToEnd();
3593 } else
3594 Diag(Tok.getLocation(), diag::warn_cxx2a_compat_explicit_bool);
3595 }
3596 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3597 ExplicitSpec, CloseParenLoc);
Douglas Gregor61956c42008-10-31 09:07:45 +00003598 break;
Richard Smith76b90272019-05-09 03:59:21 +00003599 }
Richard Smith0015f092013-01-17 22:16:11 +00003600 case tok::kw__Noreturn:
3601 if (!getLangOpts().C11)
3602 Diag(Loc, diag::ext_c11_noreturn);
Serge Pavlov750db652013-11-13 06:57:53 +00003603 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
Richard Smith0015f092013-01-17 22:16:11 +00003604 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003605
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003606 // alignment-specifier
3607 case tok::kw__Alignas:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003608 if (!getLangOpts().C11)
Jordan Rose58d54722012-06-30 21:33:57 +00003609 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003610 ParseAlignmentSpecifier(DS.getAttributes());
3611 continue;
3612
Anders Carlssoncd8db412009-05-06 04:46:28 +00003613 // friend
3614 case tok::kw_friend:
Faisal Vali7db85c52017-12-31 00:06:40 +00003615 if (DSContext == DeclSpecContext::DSC_class)
John McCall07e91c02009-08-06 02:15:43 +00003616 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3617 else {
3618 PrevSpec = ""; // not actually used by the diagnostic
3619 DiagID = diag::err_friend_invalid_in_context;
3620 isInvalid = true;
3621 }
Anders Carlssoncd8db412009-05-06 04:46:28 +00003622 break;
Mike Stump11289f42009-09-09 15:08:12 +00003623
Douglas Gregor26701a42011-09-09 02:06:17 +00003624 // Modules
3625 case tok::kw___module_private__:
3626 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3627 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003628
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00003629 // constexpr
3630 case tok::kw_constexpr:
Gauthier Harnisch796ed032019-06-14 08:56:20 +00003631 isInvalid = DS.SetConstexprSpec(CSK_constexpr, Loc, PrevSpec, DiagID);
3632 break;
3633
3634 // consteval
3635 case tok::kw_consteval:
3636 isInvalid = DS.SetConstexprSpec(CSK_consteval, Loc, PrevSpec, DiagID);
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00003637 break;
3638
Chris Lattnere387d9e2009-01-21 19:48:37 +00003639 // type-specifier
3640 case tok::kw_short:
John McCall49bfce42009-08-03 20:12:06 +00003641 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003642 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003643 break;
3644 case tok::kw_long:
3645 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
John McCall49bfce42009-08-03 20:12:06 +00003646 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003647 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003648 else
John McCall49bfce42009-08-03 20:12:06 +00003649 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003650 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003651 break;
Francois Pichet84133e42011-04-28 01:59:37 +00003652 case tok::kw___int64:
3653 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003654 DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00003655 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003656 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00003657 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3658 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003659 break;
3660 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00003661 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3662 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003663 break;
3664 case tok::kw__Complex:
John McCall49bfce42009-08-03 20:12:06 +00003665 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3666 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003667 break;
3668 case tok::kw__Imaginary:
John McCall49bfce42009-08-03 20:12:06 +00003669 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3670 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003671 break;
3672 case tok::kw_void:
John McCall49bfce42009-08-03 20:12:06 +00003673 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003674 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003675 break;
3676 case tok::kw_char:
John McCall49bfce42009-08-03 20:12:06 +00003677 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003678 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003679 break;
3680 case tok::kw_int:
John McCall49bfce42009-08-03 20:12:06 +00003681 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003682 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003683 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00003684 case tok::kw___int128:
3685 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003686 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003687 break;
3688 case tok::kw_half:
3689 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003690 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003691 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003692 case tok::kw_float:
John McCall49bfce42009-08-03 20:12:06 +00003693 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003694 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003695 break;
3696 case tok::kw_double:
John McCall49bfce42009-08-03 20:12:06 +00003697 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003698 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003699 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00003700 case tok::kw__Float16:
3701 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3702 DiagID, Policy);
3703 break;
Leonard Chanf921d852018-06-04 16:07:52 +00003704 case tok::kw__Accum:
3705 if (!getLangOpts().FixedPoint) {
Leonard Chanab80f3c2018-06-14 14:53:51 +00003706 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
Leonard Chanf921d852018-06-04 16:07:52 +00003707 } else {
3708 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3709 DiagID, Policy);
3710 }
3711 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00003712 case tok::kw__Fract:
3713 if (!getLangOpts().FixedPoint) {
3714 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3715 } else {
3716 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3717 DiagID, Policy);
3718 }
3719 break;
3720 case tok::kw__Sat:
3721 if (!getLangOpts().FixedPoint) {
3722 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3723 } else {
3724 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3725 }
3726 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003727 case tok::kw___float128:
3728 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3729 DiagID, Policy);
3730 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003731 case tok::kw_wchar_t:
John McCall49bfce42009-08-03 20:12:06 +00003732 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003733 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003734 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00003735 case tok::kw_char8_t:
3736 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3737 DiagID, Policy);
3738 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003739 case tok::kw_char16_t:
John McCall49bfce42009-08-03 20:12:06 +00003740 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003741 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003742 break;
3743 case tok::kw_char32_t:
John McCall49bfce42009-08-03 20:12:06 +00003744 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003745 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003746 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003747 case tok::kw_bool:
3748 case tok::kw__Bool:
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003749 if (Tok.is(tok::kw_bool) &&
3750 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3751 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3752 PrevSpec = ""; // Not used by the diagnostic.
3753 DiagID = diag::err_bool_redeclaration;
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003754 // For better error recovery.
3755 Tok.setKind(tok::identifier);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003756 isInvalid = true;
3757 } else {
3758 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003759 DiagID, Policy);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003760 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003761 break;
3762 case tok::kw__Decimal32:
John McCall49bfce42009-08-03 20:12:06 +00003763 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003764 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003765 break;
3766 case tok::kw__Decimal64:
John McCall49bfce42009-08-03 20:12:06 +00003767 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003768 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003769 break;
3770 case tok::kw__Decimal128:
John McCall49bfce42009-08-03 20:12:06 +00003771 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003772 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003773 break;
John Thompson22334602010-02-05 00:12:22 +00003774 case tok::kw___vector:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003775 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003776 break;
3777 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003778 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003779 break;
Bill Seurercf2c96b2015-01-12 19:35:51 +00003780 case tok::kw___bool:
3781 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3782 break;
Xiuli Pan9c14e282016-01-09 12:53:17 +00003783 case tok::kw_pipe:
Sven van Haastregte518bb42019-05-22 13:12:20 +00003784 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200 &&
3785 !getLangOpts().OpenCLCPlusPlus)) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003786 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3787 // support the "pipe" word as identifier.
3788 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3789 goto DoneWithDeclSpec;
3790 }
3791 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3792 break;
Alexey Bader954ba212016-04-08 13:40:33 +00003793#define GENERIC_IMAGE_TYPE(ImgType, Id) \
3794 case tok::kw_##ImgType##_t: \
3795 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3796 DiagID, Policy); \
3797 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00003798#include "clang/Basic/OpenCLImageTypes.def"
John McCall39439732011-04-09 22:50:59 +00003799 case tok::kw___unknown_anytype:
Faisal Vali090da2d2018-01-01 18:23:28 +00003800 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003801 PrevSpec, DiagID, Policy);
John McCall39439732011-04-09 22:50:59 +00003802 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003803
3804 // class-specifier:
3805 case tok::kw_class:
3806 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00003807 case tok::kw___interface:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003808 case tok::kw_union: {
3809 tok::TokenKind Kind = Tok.getKind();
3810 ConsumeToken();
Michael Han9407e502012-11-26 22:54:45 +00003811
3812 // These are attributes following class specifiers.
3813 // To produce better diagnostic, we parse them when
3814 // parsing class specifier.
Bill Wendling44426052012-12-20 19:22:21 +00003815 ParsedAttributesWithRange Attributes(AttrFactory);
Richard Smithc5b05522012-03-12 07:56:15 +00003816 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
Bill Wendling44426052012-12-20 19:22:21 +00003817 EnteringContext, DSContext, Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003818
3819 // If there are attributes following class specifier,
3820 // take them over and handle them here.
Bill Wendling44426052012-12-20 19:22:21 +00003821 if (!Attributes.empty()) {
Michael Han9407e502012-11-26 22:54:45 +00003822 AttrsLastTime = true;
Bill Wendling44426052012-12-20 19:22:21 +00003823 attrs.takeAllFrom(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003824 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003825 continue;
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003826 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003827
3828 // enum-specifier:
3829 case tok::kw_enum:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003830 ConsumeToken();
Richard Smithc5b05522012-03-12 07:56:15 +00003831 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003832 continue;
Faisal Valia534f072018-04-26 00:42:40 +00003833
Chris Lattnere387d9e2009-01-21 19:48:37 +00003834 // cv-qualifier:
3835 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00003836 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003837 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003838 break;
3839 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00003840 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003841 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003842 break;
3843 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00003844 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003845 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003846 break;
3847
Douglas Gregor333489b2009-03-27 23:10:48 +00003848 // C++ typename-specifier:
3849 case tok::kw_typename:
John McCall1f476a12010-02-26 08:45:28 +00003850 if (TryAnnotateTypeOrScopeToken()) {
3851 DS.SetTypeSpecError();
3852 goto DoneWithDeclSpec;
3853 }
3854 if (!Tok.is(tok::kw_typename))
Douglas Gregor333489b2009-03-27 23:10:48 +00003855 continue;
3856 break;
3857
Chris Lattnere387d9e2009-01-21 19:48:37 +00003858 // GNU typeof support.
3859 case tok::kw_typeof:
3860 ParseTypeofSpecifier(DS);
3861 continue;
3862
David Blaikie15a430a2011-12-04 05:04:18 +00003863 case tok::annot_decltype:
Anders Carlsson74948d02009-06-24 17:47:40 +00003864 ParseDecltypeSpecifier(DS);
3865 continue;
3866
David Majnemer15b311c2016-06-14 03:20:28 +00003867 case tok::annot_pragma_pack:
3868 HandlePragmaPack();
3869 continue;
3870
3871 case tok::annot_pragma_ms_pragma:
3872 HandlePragmaMSPragma();
3873 continue;
3874
3875 case tok::annot_pragma_ms_vtordisp:
3876 HandlePragmaMSVtorDisp();
3877 continue;
3878
3879 case tok::annot_pragma_ms_pointers_to_members:
3880 HandlePragmaMSPointersToMembers();
3881 continue;
3882
Alexis Hunt4a257072011-05-19 05:37:45 +00003883 case tok::kw___underlying_type:
3884 ParseUnderlyingTypeSpecifier(DS);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003885 continue;
3886
3887 case tok::kw__Atomic:
Richard Smith8e1ac332013-03-28 01:55:44 +00003888 // C11 6.7.2.4/4:
3889 // If the _Atomic keyword is immediately followed by a left parenthesis,
3890 // it is interpreted as a type specifier (with a type name), not as a
3891 // type qualifier.
3892 if (NextToken().is(tok::l_paren)) {
3893 ParseAtomicSpecifier(DS);
3894 continue;
3895 }
3896 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3897 getLangOpts());
3898 break;
Alexis Hunt4a257072011-05-19 05:37:45 +00003899
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003900 // OpenCL address space qualifiers:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003901 case tok::kw___generic:
3902 // generic address space is introduced only in OpenCL v2.0
3903 // see OpenCL C Spec v2.0 s6.5.5
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003904 if (Actions.getLangOpts().OpenCLVersion < 200 &&
3905 !Actions.getLangOpts().OpenCLCPlusPlus) {
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003906 DiagID = diag::err_opencl_unknown_type_specifier;
3907 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3908 isInvalid = true;
3909 break;
3910 };
Galina Kistanova77674252017-06-01 21:15:34 +00003911 LLVM_FALLTHROUGH;
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003912 case tok::kw_private:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003913 case tok::kw___private:
3914 case tok::kw___global:
3915 case tok::kw___local:
3916 case tok::kw___constant:
Anastasia Stulova2c4730d2019-02-15 12:07:57 +00003917 // OpenCL access qualifiers:
3918 case tok::kw___read_only:
3919 case tok::kw___write_only:
3920 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00003921 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003922 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003923
Steve Naroffcfdf6162008-06-05 00:02:44 +00003924 case tok::less:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003925 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
Chris Lattner0974b232008-07-26 00:20:22 +00003926 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3927 // but we support it.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003928 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
Chris Lattner0974b232008-07-26 00:20:22 +00003929 goto DoneWithDeclSpec;
Mike Stump11289f42009-09-09 15:08:12 +00003930
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003931 SourceLocation StartLoc = Tok.getLocation();
3932 SourceLocation EndLoc;
3933 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3934 if (Type.isUsable()) {
3935 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3936 PrevSpec, DiagID, Type.get(),
3937 Actions.getASTContext().getPrintingPolicy()))
3938 Diag(StartLoc, DiagID) << PrevSpec;
Fangrui Song6907ce22018-07-30 19:24:48 +00003939
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003940 DS.SetRangeEnd(EndLoc);
3941 } else {
3942 DS.SetTypeSpecError();
3943 }
Chad Rosierc1183952012-06-26 22:30:43 +00003944
Douglas Gregor06e41ae2010-10-21 23:17:00 +00003945 // Need to support trailing type qualifiers (e.g. "id<p> const").
3946 // If a type specifier follows, it will be diagnosed elsewhere.
3947 continue;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003948 }
Richard Smith76b90272019-05-09 03:59:21 +00003949
Richard Smithba24f352019-05-09 19:45:46 +00003950 DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
Richard Smith76b90272019-05-09 03:59:21 +00003951
John McCall49bfce42009-08-03 20:12:06 +00003952 // If the specifier wasn't legal, issue a diagnostic.
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003953 if (isInvalid) {
3954 assert(PrevSpec && "Method did not return previous specifier!");
John McCall49bfce42009-08-03 20:12:06 +00003955 assert(DiagID);
Chad Rosierc1183952012-06-26 22:30:43 +00003956
Nick Desaulniers150ca532018-10-03 23:09:29 +00003957 if (DiagID == diag::ext_duplicate_declspec ||
Richard Smith76b90272019-05-09 03:59:21 +00003958 DiagID == diag::ext_warn_duplicate_declspec ||
3959 DiagID == diag::err_duplicate_declspec)
3960 Diag(Loc, DiagID) << PrevSpec
3961 << FixItHint::CreateRemoval(
3962 SourceRange(Loc, DS.getEndLoc()));
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003963 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
Richard Smith76b90272019-05-09 03:59:21 +00003964 Diag(Loc, DiagID) << getLangOpts().OpenCLCPlusPlus
3965 << getLangOpts().getOpenCLVersionTuple().getAsString()
3966 << PrevSpec << isStorageClass;
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003967 } else
Richard Smith76b90272019-05-09 03:59:21 +00003968 Diag(Loc, DiagID) << PrevSpec;
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003969 }
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003970
Richard Smithba24f352019-05-09 19:45:46 +00003971 if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
Volodymyr Sapsai9f7b5cc2018-04-10 18:29:47 +00003972 // After an error the next token can be an annotation token.
3973 ConsumeAnyToken();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003974
3975 AttrsLastTime = false;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003976 }
3977}
Douglas Gregoreb31f392008-12-01 23:54:00 +00003978
Chris Lattner70ae4912007-10-29 04:42:53 +00003979/// ParseStructDeclaration - Parse a struct declaration without the terminating
3980/// semicolon.
3981///
Nico Weber98dd0852019-03-14 14:18:56 +00003982/// Note that a struct declaration refers to a declaration in a struct,
3983/// not to the declaration of a struct.
3984///
Chris Lattner90a26b02007-01-23 04:38:16 +00003985/// struct-declaration:
Aaron Ballman606093a2017-10-15 15:01:42 +00003986/// [C2x] attributes-specifier-seq[opt]
3987/// specifier-qualifier-list struct-declarator-list
Chris Lattner736ed5d2007-06-09 05:59:07 +00003988/// [GNU] __extension__ struct-declaration
Chris Lattner70ae4912007-10-29 04:42:53 +00003989/// [GNU] specifier-qualifier-list
Chris Lattner90a26b02007-01-23 04:38:16 +00003990/// struct-declarator-list:
3991/// struct-declarator
3992/// struct-declarator-list ',' struct-declarator
3993/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3994/// struct-declarator:
3995/// declarator
3996/// [GNU] declarator attributes[opt]
3997/// declarator[opt] ':' constant-expression
3998/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3999///
Benjamin Kramera39beb92014-09-03 11:06:10 +00004000void Parser::ParseStructDeclaration(
4001 ParsingDeclSpec &DS,
4002 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
Chad Rosierc1183952012-06-26 22:30:43 +00004003
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00004004 if (Tok.is(tok::kw___extension__)) {
4005 // __extension__ silences extension warnings in the subexpression.
4006 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Steve Naroff97170802007-08-20 22:28:22 +00004007 ConsumeToken();
Benjamin Kramera39beb92014-09-03 11:06:10 +00004008 return ParseStructDeclaration(DS, FieldsCallback);
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00004009 }
Mike Stump11289f42009-09-09 15:08:12 +00004010
Aaron Ballman606093a2017-10-15 15:01:42 +00004011 // Parse leading attributes.
4012 ParsedAttributesWithRange Attrs(AttrFactory);
4013 MaybeParseCXX11Attributes(Attrs);
4014 DS.takeAttributesFrom(Attrs);
4015
Steve Naroff97170802007-08-20 22:28:22 +00004016 // Parse the common specifier-qualifiers-list piece.
Steve Naroff97170802007-08-20 22:28:22 +00004017 ParseSpecifierQualifierList(DS);
Mike Stump11289f42009-09-09 15:08:12 +00004018
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00004019 // If there are no declarators, this is a free-standing declaration
4020 // specifier. Let the actions module cope with it.
Chris Lattner76c72282007-10-09 17:33:22 +00004021 if (Tok.is(tok::semi)) {
Nico Weber7b837f52016-01-28 19:25:00 +00004022 RecordDecl *AnonRecord = nullptr;
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004023 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00004024 DS, AnonRecord);
4025 assert(!AnonRecord && "Did not expect anonymous struct or union here");
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004026 DS.complete(TheDecl);
Steve Naroff97170802007-08-20 22:28:22 +00004027 return;
4028 }
4029
4030 // Read struct-declarators until we find the semicolon.
John McCallcfefb6d2009-11-03 02:38:08 +00004031 bool FirstDeclarator = true;
Richard Smith8d06f422012-01-12 23:53:29 +00004032 SourceLocation CommaLoc;
Steve Naroff97170802007-08-20 22:28:22 +00004033 while (1) {
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004034 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
Richard Smith8d06f422012-01-12 23:53:29 +00004035 DeclaratorInfo.D.setCommaLoc(CommaLoc);
John McCallcfefb6d2009-11-03 02:38:08 +00004036
Bill Wendling44426052012-12-20 19:22:21 +00004037 // Attributes are only allowed here on successive declarators.
John McCall53fa7142010-12-24 02:08:15 +00004038 if (!FirstDeclarator)
4039 MaybeParseGNUAttributes(DeclaratorInfo.D);
Mike Stump11289f42009-09-09 15:08:12 +00004040
Steve Naroff97170802007-08-20 22:28:22 +00004041 /// struct-declarator: declarator
4042 /// struct-declarator: declarator[opt] ':' constant-expression
Chris Lattner17c3b1f2009-12-10 01:59:24 +00004043 if (Tok.isNot(tok::colon)) {
4044 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4045 ColonProtectionRAIIObject X(*this);
Chris Lattnera12405b2008-04-10 06:46:29 +00004046 ParseDeclarator(DeclaratorInfo.D);
Richard Smith3d1a94c2014-08-12 00:22:39 +00004047 } else
4048 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004049
Alp Toker8fbec672013-12-17 23:29:36 +00004050 if (TryConsumeToken(tok::colon)) {
John McCalldadc5752010-08-24 06:29:42 +00004051 ExprResult Res(ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004052 if (Res.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00004053 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner32295d32008-04-10 06:15:14 +00004054 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004055 DeclaratorInfo.BitfieldSize = Res.get();
Steve Naroff97170802007-08-20 22:28:22 +00004056 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004057
Steve Naroff97170802007-08-20 22:28:22 +00004058 // If attributes exist after the declarator, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004059 MaybeParseGNUAttributes(DeclaratorInfo.D);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004060
John McCallcfefb6d2009-11-03 02:38:08 +00004061 // We're done with this declarator; invoke the callback.
Benjamin Kramera39beb92014-09-03 11:06:10 +00004062 FieldsCallback(DeclaratorInfo);
John McCallcfefb6d2009-11-03 02:38:08 +00004063
Steve Naroff97170802007-08-20 22:28:22 +00004064 // If we don't have a comma, it is either the end of the list (a ';')
4065 // or an error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00004066 if (!TryConsumeToken(tok::comma, CommaLoc))
Chris Lattner70ae4912007-10-29 04:42:53 +00004067 return;
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004068
John McCallcfefb6d2009-11-03 02:38:08 +00004069 FirstDeclarator = false;
Steve Naroff97170802007-08-20 22:28:22 +00004070 }
Steve Naroff97170802007-08-20 22:28:22 +00004071}
4072
4073/// ParseStructUnionBody
4074/// struct-contents:
4075/// struct-declaration-list
4076/// [EXT] empty
4077/// [GNU] "struct-declaration-list" without terminatoring ';'
4078/// struct-declaration-list:
4079/// struct-declaration
4080/// struct-declaration-list struct-declaration
Chris Lattner535b8302008-06-21 19:39:06 +00004081/// [OBC] '@' 'defs' '(' class-name ')'
Steve Naroff97170802007-08-20 22:28:22 +00004082///
Chris Lattner1300fb92007-01-23 23:42:53 +00004083void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00004084 unsigned TagType, Decl *TagDecl) {
Jordan Rose1e879d82018-03-23 00:07:18 +00004085 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00004086 "parsing struct/union body");
Andy Gibbs22e140b2013-04-03 09:31:19 +00004087 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
Mike Stump11289f42009-09-09 15:08:12 +00004088
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004089 BalancedDelimiterTracker T(*this, tok::l_brace);
4090 if (T.consumeOpen())
4091 return;
Mike Stump11289f42009-09-09 15:08:12 +00004092
Douglas Gregor658b9552009-01-09 22:42:13 +00004093 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004094 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004095
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004096 SmallVector<Decl *, 32> FieldDecls;
Chris Lattnera12405b2008-04-10 06:46:29 +00004097
Chris Lattner7b9ace62007-01-23 20:11:08 +00004098 // While we still have something to read, read the declarations in the struct.
Richard Smith752ada82015-11-17 23:32:01 +00004099 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4100 Tok.isNot(tok::eof)) {
Chris Lattner90a26b02007-01-23 04:38:16 +00004101 // Each iteration of this loop reads one struct-declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004102
Chris Lattner736ed5d2007-06-09 05:59:07 +00004103 // Check for extraneous top-level semicolon.
Chris Lattner76c72282007-10-09 17:33:22 +00004104 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004105 ConsumeExtraSemi(InsideStruct, TagType);
Chris Lattner36e46a22007-06-09 05:49:55 +00004106 continue;
4107 }
Chris Lattnera12405b2008-04-10 06:46:29 +00004108
Andy Gibbsc804e082013-04-03 09:46:04 +00004109 // Parse _Static_assert declaration.
4110 if (Tok.is(tok::kw__Static_assert)) {
4111 SourceLocation DeclEnd;
4112 ParseStaticAssertDeclaration(DeclEnd);
4113 continue;
4114 }
4115
Argyrios Kyrtzidis71c12fb2013-04-18 01:42:35 +00004116 if (Tok.is(tok::annot_pragma_pack)) {
4117 HandlePragmaPack();
4118 continue;
4119 }
4120
4121 if (Tok.is(tok::annot_pragma_align)) {
4122 HandlePragmaAlign();
4123 continue;
4124 }
4125
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004126 if (Tok.is(tok::annot_pragma_openmp)) {
Alexey Bataev587e1de2016-03-30 10:43:55 +00004127 // Result can be ignored, because it must be always empty.
4128 AccessSpecifier AS = AS_none;
4129 ParsedAttributesWithRange Attrs(AttrFactory);
4130 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004131 continue;
4132 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004133
John McCallcfefb6d2009-11-03 02:38:08 +00004134 if (!Tok.is(tok::at)) {
Benjamin Kramera39beb92014-09-03 11:06:10 +00004135 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4136 // Install the declarator into the current TagDecl.
4137 Decl *Field =
4138 Actions.ActOnField(getCurScope(), TagDecl,
4139 FD.D.getDeclSpec().getSourceRange().getBegin(),
4140 FD.D, FD.BitfieldSize);
4141 FieldDecls.push_back(Field);
4142 FD.complete(Field);
4143 };
John McCallcfefb6d2009-11-03 02:38:08 +00004144
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004145 // Parse all the comma separated declarators.
4146 ParsingDeclSpec DS(*this);
Benjamin Kramera39beb92014-09-03 11:06:10 +00004147 ParseStructDeclaration(DS, CFieldCallback);
Chris Lattner535b8302008-06-21 19:39:06 +00004148 } else { // Handle @defs
4149 ConsumeToken();
4150 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4151 Diag(Tok, diag::err_unexpected_at);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004152 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004153 continue;
4154 }
4155 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004156 ExpectAndConsume(tok::l_paren);
Chris Lattner535b8302008-06-21 19:39:06 +00004157 if (!Tok.is(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004158 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004159 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004160 continue;
4161 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004162 SmallVector<Decl *, 16> Fields;
Douglas Gregor0be31a22010-07-02 17:43:08 +00004163 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004164 Tok.getIdentifierInfo(), Fields);
Chris Lattner535b8302008-06-21 19:39:06 +00004165 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4166 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004167 ExpectAndConsume(tok::r_paren);
Mike Stump11289f42009-09-09 15:08:12 +00004168 }
Chris Lattner736ed5d2007-06-09 05:59:07 +00004169
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004170 if (TryConsumeToken(tok::semi))
4171 continue;
4172
4173 if (Tok.is(tok::r_brace)) {
Chris Lattner245c5332010-02-02 00:37:27 +00004174 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
Chris Lattner0c7e82d2007-06-09 05:54:40 +00004175 break;
Chris Lattner90a26b02007-01-23 04:38:16 +00004176 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004177
4178 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4179 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4180 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4181 // If we stopped at a ';', eat it.
4182 TryConsumeToken(tok::semi);
Chris Lattner90a26b02007-01-23 04:38:16 +00004183 }
Mike Stump11289f42009-09-09 15:08:12 +00004184
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004185 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +00004186
John McCall084e83d2011-03-24 11:26:52 +00004187 ParsedAttributes attrs(AttrFactory);
Chris Lattner90a26b02007-01-23 04:38:16 +00004188 // If attributes exist after struct contents, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004189 MaybeParseGNUAttributes(attrs);
Daniel Dunbar15619c72008-10-03 02:03:53 +00004190
Erich Keanec480f302018-07-12 21:09:05 +00004191 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4192 T.getOpenLocation(), T.getCloseLocation(), attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004193 StructScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004194 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
Chris Lattner90a26b02007-01-23 04:38:16 +00004195}
4196
Chris Lattner3b561a32006-08-13 00:12:11 +00004197/// ParseEnumSpecifier
Chris Lattner1890ac82006-08-13 01:16:23 +00004198/// enum-specifier: [C99 6.7.2.2]
Chris Lattner3b561a32006-08-13 00:12:11 +00004199/// 'enum' identifier[opt] '{' enumerator-list '}'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004200///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
Chris Lattnere37e2332006-08-15 04:50:22 +00004201/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4202/// '}' attributes[opt]
Aaron Ballman9ecff022012-03-01 04:09:28 +00004203/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4204/// '}'
Chris Lattner3b561a32006-08-13 00:12:11 +00004205/// 'enum' identifier
Chris Lattnere37e2332006-08-15 04:50:22 +00004206/// [GNU] 'enum' attributes[opt] identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004207///
Richard Smith7d137e32012-03-23 03:33:32 +00004208/// [C++11] enum-head '{' enumerator-list[opt] '}'
4209/// [C++11] enum-head '{' enumerator-list ',' '}'
Douglas Gregor0bf31402010-10-08 23:50:27 +00004210///
Richard Smith7d137e32012-03-23 03:33:32 +00004211/// enum-head: [C++11]
4212/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4213/// enum-key attribute-specifier-seq[opt] nested-name-specifier
4214/// identifier enum-base[opt]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004215///
Richard Smith7d137e32012-03-23 03:33:32 +00004216/// enum-key: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004217/// 'enum'
4218/// 'enum' 'class'
4219/// 'enum' 'struct'
4220///
Richard Smith7d137e32012-03-23 03:33:32 +00004221/// enum-base: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004222/// ':' type-specifier-seq
4223///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004224/// [C++] elaborated-type-specifier:
4225/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4226///
Chris Lattnerffaa0e62009-04-12 21:49:30 +00004227void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregordc70c3a2010-03-02 17:53:14 +00004228 const ParsedTemplateInfo &TemplateInfo,
Richard Smithc5b05522012-03-12 07:56:15 +00004229 AccessSpecifier AS, DeclSpecContext DSC) {
Chris Lattnerffbc2712007-01-25 06:05:38 +00004230 // Parse the tag portion of this.
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004231 if (Tok.is(tok::code_completion)) {
4232 // Code completion for an enum name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004233 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00004234 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004235 }
John McCallcb432fa2011-07-06 05:58:41 +00004236
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004237 // If attributes exist after tag, parse them.
4238 ParsedAttributesWithRange attrs(AttrFactory);
4239 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004240 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004241 MaybeParseMicrosoftDeclSpecs(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004242
Richard Smith0f8ee222012-01-10 01:33:14 +00004243 SourceLocation ScopedEnumKWLoc;
John McCallcb432fa2011-07-06 05:58:41 +00004244 bool IsScopedUsingClassTag = false;
4245
John McCallbeae29a2012-06-23 22:30:04 +00004246 // In C++11, recognize 'enum class' and 'enum struct'.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004247 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
Richard Trieud0d87b52013-04-23 02:47:36 +00004248 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4249 : diag::ext_scoped_enum);
John McCallcb432fa2011-07-06 05:58:41 +00004250 IsScopedUsingClassTag = Tok.is(tok::kw_class);
Richard Smith0f8ee222012-01-10 01:33:14 +00004251 ScopedEnumKWLoc = ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004252
Bill Wendling44426052012-12-20 19:22:21 +00004253 // Attributes are not allowed between these keywords. Diagnose,
John McCallbeae29a2012-06-23 22:30:04 +00004254 // but then just treat them like they appeared in the right place.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004255 ProhibitAttributes(attrs);
John McCallbeae29a2012-06-23 22:30:04 +00004256
4257 // They are allowed afterwards, though.
4258 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004259 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004260 MaybeParseMicrosoftDeclSpecs(attrs);
John McCallcb432fa2011-07-06 05:58:41 +00004261 }
Richard Smith7d137e32012-03-23 03:33:32 +00004262
John McCall6347b682012-05-07 06:16:58 +00004263 // C++11 [temp.explicit]p12:
4264 // The usual access controls do not apply to names used to specify
4265 // explicit instantiations.
4266 // We extend this to also cover explicit specializations. Note that
4267 // we don't suppress if this turns out to be an elaborated type
4268 // specifier.
4269 bool shouldDelayDiagsInTag =
4270 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4271 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4272 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Richard Smith7d137e32012-03-23 03:33:32 +00004273
Richard Smithbfdb1082012-03-12 08:56:40 +00004274 // Enum definitions should not be parsed in a trailing-return-type.
Faisal Vali7db85c52017-12-31 00:06:40 +00004275 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
Richard Smithbfdb1082012-03-12 08:56:40 +00004276
Abramo Bagnarad7548482010-05-19 21:37:53 +00004277 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004278 if (getLangOpts().CPlusPlus) {
John McCallcb432fa2011-07-06 05:58:41 +00004279 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4280 // if a fixed underlying type is allowed.
Erik Pilkington6f11db12018-09-28 20:24:58 +00004281 ColonProtectionRAIIObject X(*this, AllowDeclaration);
Chad Rosierc1183952012-06-26 22:30:43 +00004282
Nico Webercfaa4cd2015-02-15 07:26:13 +00004283 CXXScopeSpec Spec;
David Blaikieefdccaa2016-01-15 23:43:34 +00004284 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
Richard Smith1d4b2e12013-04-01 21:43:41 +00004285 /*EnteringContext=*/true))
John McCall1f476a12010-02-26 08:45:28 +00004286 return;
4287
Nico Webercfaa4cd2015-02-15 07:26:13 +00004288 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004289 Diag(Tok, diag::err_expected) << tok::identifier;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004290 if (Tok.isNot(tok::l_brace)) {
4291 // Has no name and is not a definition.
4292 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004293 SkipUntil(tok::comma, StopAtSemi);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004294 return;
4295 }
4296 }
Nico Webercfaa4cd2015-02-15 07:26:13 +00004297
4298 SS = Spec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004299 }
Mike Stump11289f42009-09-09 15:08:12 +00004300
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004301 // Must have either 'enum name' or 'enum {...}'.
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004302 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
Erik Pilkington6f11db12018-09-28 20:24:58 +00004303 !(AllowDeclaration && Tok.is(tok::colon))) {
Alp Tokerec543272013-12-24 09:48:30 +00004304 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
Mike Stump11289f42009-09-09 15:08:12 +00004305
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004306 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004307 SkipUntil(tok::comma, StopAtSemi);
Chris Lattner3b561a32006-08-13 00:12:11 +00004308 return;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004309 }
Mike Stump11289f42009-09-09 15:08:12 +00004310
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004311 // If an identifier is present, consume and remember it.
Craig Topper161e4db2014-05-21 06:02:52 +00004312 IdentifierInfo *Name = nullptr;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004313 SourceLocation NameLoc;
4314 if (Tok.is(tok::identifier)) {
4315 Name = Tok.getIdentifierInfo();
4316 NameLoc = ConsumeToken();
4317 }
Mike Stump11289f42009-09-09 15:08:12 +00004318
Richard Smith0f8ee222012-01-10 01:33:14 +00004319 if (!Name && ScopedEnumKWLoc.isValid()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00004320 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4321 // declaration of a scoped enumeration.
4322 Diag(Tok, diag::err_scoped_enum_missing_identifier);
Richard Smith0f8ee222012-01-10 01:33:14 +00004323 ScopedEnumKWLoc = SourceLocation();
Abramo Bagnara0e05e242010-12-03 18:54:17 +00004324 IsScopedUsingClassTag = false;
Douglas Gregor0bf31402010-10-08 23:50:27 +00004325 }
4326
John McCall6347b682012-05-07 06:16:58 +00004327 // Okay, end the suppression area. We'll decide whether to emit the
4328 // diagnostics in a second.
4329 if (shouldDelayDiagsInTag)
4330 diagsFromTag.done();
Richard Smith7d137e32012-03-23 03:33:32 +00004331
Douglas Gregor0bf31402010-10-08 23:50:27 +00004332 TypeResult BaseType;
4333
Douglas Gregord1f69f62010-12-01 17:42:47 +00004334 // Parse the fixed underlying type.
Richard Smith200f47c2012-07-02 19:14:01 +00004335 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
Erik Pilkington6f11db12018-09-28 20:24:58 +00004336 if (AllowDeclaration && Tok.is(tok::colon)) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004337 bool PossibleBitfield = false;
Richard Smith200f47c2012-07-02 19:14:01 +00004338 if (CanBeBitfield) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004339 // If we're in class scope, this can either be an enum declaration with
4340 // an underlying type, or a declaration of a bitfield member. We try to
4341 // use a simple disambiguation scheme first to catch the common cases
Chad Rosierc1183952012-06-26 22:30:43 +00004342 // (integer literal, sizeof); if it's still ambiguous, we then consider
4343 // anything that's a simple-type-specifier followed by '(' as an
4344 // expression. This suffices because function types are not valid
Douglas Gregord1f69f62010-12-01 17:42:47 +00004345 // underlying types anyway.
Faisal Valid143a0c2017-04-01 21:30:49 +00004346 EnterExpressionEvaluationContext Unevaluated(
4347 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregord1f69f62010-12-01 17:42:47 +00004348 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
Chad Rosierc1183952012-06-26 22:30:43 +00004349 // If the next token starts an expression, we know we're parsing a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004350 // bit-field. This is the common case.
Richard Smithee390432014-05-16 01:56:53 +00004351 if (TPR == TPResult::True)
Douglas Gregord1f69f62010-12-01 17:42:47 +00004352 PossibleBitfield = true;
4353 // If the next token starts a type-specifier-seq, it may be either a
4354 // a fixed underlying type or the start of a function-style cast in C++;
Chad Rosierc1183952012-06-26 22:30:43 +00004355 // lookahead one more token to see if it's obvious that we have a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004356 // fixed underlying type.
Richard Smithee390432014-05-16 01:56:53 +00004357 else if (TPR == TPResult::False &&
Douglas Gregord1f69f62010-12-01 17:42:47 +00004358 GetLookAheadToken(2).getKind() == tok::semi) {
4359 // Consume the ':'.
4360 ConsumeToken();
4361 } else {
4362 // We have the start of a type-specifier-seq, so we have to perform
4363 // tentative parsing to determine whether we have an expression or a
4364 // type.
4365 TentativeParsingAction TPA(*this);
4366
4367 // Consume the ':'.
4368 ConsumeToken();
Richard Smith1e3b0f02012-02-23 01:36:12 +00004369
4370 // If we see a type specifier followed by an open-brace, we have an
4371 // ambiguity between an underlying type and a C++11 braced
4372 // function-style cast. Resolve this by always treating it as an
4373 // underlying type.
4374 // FIXME: The standard is not entirely clear on how to disambiguate in
4375 // this case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004376 if ((getLangOpts().CPlusPlus &&
Richard Smithee390432014-05-16 01:56:53 +00004377 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00004378 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004379 // We'll parse this as a bitfield later.
4380 PossibleBitfield = true;
4381 TPA.Revert();
4382 } else {
4383 // We have a type-specifier-seq.
4384 TPA.Commit();
4385 }
4386 }
4387 } else {
4388 // Consume the ':'.
4389 ConsumeToken();
4390 }
4391
4392 if (!PossibleBitfield) {
4393 SourceRange Range;
4394 BaseType = ParseTypeName(&Range);
Chad Rosierc1183952012-06-26 22:30:43 +00004395
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004396 if (!getLangOpts().ObjC) {
Erik Pilkington6f11db12018-09-28 20:24:58 +00004397 if (getLangOpts().CPlusPlus11)
4398 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4399 else if (getLangOpts().CPlusPlus)
4400 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4401 else if (getLangOpts().MicrosoftExt)
4402 Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004403 else
Erik Pilkington6f11db12018-09-28 20:24:58 +00004404 Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004405 }
Douglas Gregord1f69f62010-12-01 17:42:47 +00004406 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004407 }
4408
Richard Smith0f8ee222012-01-10 01:33:14 +00004409 // There are four options here. If we have 'friend enum foo;' then this is a
4410 // friend declaration, and cannot have an accompanying definition. If we have
4411 // 'enum foo;', then this is a forward declaration. If we have
4412 // 'enum foo {...' then this is a definition. Otherwise we have something
4413 // like 'enum foo xyz', a reference.
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004414 //
4415 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4416 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4417 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4418 //
John McCallfaf5fb42010-08-26 23:41:50 +00004419 Sema::TagUseKind TUK;
John McCall6347b682012-05-07 06:16:58 +00004420 if (!AllowDeclaration) {
Richard Smithbfdb1082012-03-12 08:56:40 +00004421 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004422 } else if (Tok.is(tok::l_brace)) {
4423 if (DS.isFriendSpecified()) {
4424 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4425 << SourceRange(DS.getFriendSpecLoc());
4426 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004427 SkipUntil(tok::r_brace, StopAtSemi);
John McCall6347b682012-05-07 06:16:58 +00004428 TUK = Sema::TUK_Friend;
4429 } else {
4430 TUK = Sema::TUK_Definition;
4431 }
Richard Smith649c7b062014-01-08 00:56:48 +00004432 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00004433 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00004434 (Tok.isAtStartOfLine() &&
4435 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
Richard Smith369b9f92012-06-25 21:37:02 +00004436 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4437 if (Tok.isNot(tok::semi)) {
4438 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00004439 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Ilya Biryukov929af672019-05-17 09:32:05 +00004440 PP.EnterToken(Tok, /*IsReinject=*/true);
Richard Smith369b9f92012-06-25 21:37:02 +00004441 Tok.setKind(tok::semi);
4442 }
John McCall6347b682012-05-07 06:16:58 +00004443 } else {
John McCallfaf5fb42010-08-26 23:41:50 +00004444 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004445 }
4446
4447 // If this is an elaborated type specifier, and we delayed
4448 // diagnostics before, just merge them into the current pool.
4449 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4450 diagsFromTag.redelay();
4451 }
Richard Smith7d137e32012-03-23 03:33:32 +00004452
4453 MultiTemplateParamsArg TParams;
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004454 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
John McCallfaf5fb42010-08-26 23:41:50 +00004455 TUK != Sema::TUK_Reference) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004456 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
Richard Smith7d137e32012-03-23 03:33:32 +00004457 // Skip the rest of this declarator, up until the comma or semicolon.
4458 Diag(Tok, diag::err_enum_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004459 SkipUntil(tok::comma, StopAtSemi);
Richard Smith7d137e32012-03-23 03:33:32 +00004460 return;
4461 }
4462
4463 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4464 // Enumerations can't be explicitly instantiated.
4465 DS.SetTypeSpecError();
4466 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4467 return;
4468 }
4469
4470 assert(TemplateInfo.TemplateParams && "no template parameters");
4471 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4472 TemplateInfo.TemplateParams->size());
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004473 }
Chad Rosierc1183952012-06-26 22:30:43 +00004474
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004475 if (TUK == Sema::TUK_Reference)
4476 ProhibitAttributes(attrs);
Richard Smith7d137e32012-03-23 03:33:32 +00004477
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004478 if (!Name && TUK != Sema::TUK_Definition) {
4479 Diag(Tok, diag::err_enumerator_unnamed_no_def);
Richard Smith7d137e32012-03-23 03:33:32 +00004480
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004481 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004482 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004483 return;
4484 }
Richard Smith7d137e32012-03-23 03:33:32 +00004485
Nico Weber32a0fc72016-09-03 03:01:32 +00004486 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00004487
Richard Smithd9ba2242015-05-07 03:54:19 +00004488 Sema::SkipBodyInfo SkipBody;
4489 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4490 NextToken().is(tok::identifier))
4491 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4492 NextToken().getIdentifierInfo(),
4493 NextToken().getLocation());
4494
Douglas Gregord6ab8742009-05-28 23:31:59 +00004495 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004496 bool IsDependent = false;
Craig Topper161e4db2014-05-21 06:02:52 +00004497 const char *PrevSpec = nullptr;
Douglas Gregorba41d012010-04-24 16:38:41 +00004498 unsigned DiagID;
Faisal Vali7db85c52017-12-31 00:06:40 +00004499 Decl *TagDecl = Actions.ActOnTag(
4500 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
Erich Keanec480f302018-07-12 21:09:05 +00004501 attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4502 ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
Faisal Vali7db85c52017-12-31 00:06:40 +00004503 DSC == DeclSpecContext::DSC_type_specifier,
4504 DSC == DeclSpecContext::DSC_template_param ||
4505 DSC == DeclSpecContext::DSC_template_type_arg,
4506 &SkipBody);
Richard Smithd9ba2242015-05-07 03:54:19 +00004507
4508 if (SkipBody.ShouldSkip) {
4509 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4510
4511 BalancedDelimiterTracker T(*this, tok::l_brace);
4512 T.consumeOpen();
4513 T.skipToEnd();
4514
4515 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4516 NameLoc.isValid() ? NameLoc : StartLoc,
4517 PrevSpec, DiagID, TagDecl, Owned,
4518 Actions.getASTContext().getPrintingPolicy()))
4519 Diag(StartLoc, DiagID) << PrevSpec;
4520 return;
4521 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004522
Douglas Gregorba41d012010-04-24 16:38:41 +00004523 if (IsDependent) {
Chad Rosierc1183952012-06-26 22:30:43 +00004524 // This enum has a dependent nested-name-specifier. Handle it as a
Douglas Gregorba41d012010-04-24 16:38:41 +00004525 // dependent tag.
4526 if (!Name) {
4527 DS.SetTypeSpecError();
4528 Diag(Tok, diag::err_expected_type_name_after_typename);
4529 return;
4530 }
Chad Rosierc1183952012-06-26 22:30:43 +00004531
Nico Weber83ea0122014-05-03 21:57:40 +00004532 TypeResult Type = Actions.ActOnDependentTag(
4533 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
Douglas Gregorba41d012010-04-24 16:38:41 +00004534 if (Type.isInvalid()) {
4535 DS.SetTypeSpecError();
4536 return;
4537 }
Chad Rosierc1183952012-06-26 22:30:43 +00004538
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004539 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4540 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004541 PrevSpec, DiagID, Type.get(),
4542 Actions.getASTContext().getPrintingPolicy()))
Douglas Gregorba41d012010-04-24 16:38:41 +00004543 Diag(StartLoc, DiagID) << PrevSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00004544
Douglas Gregorba41d012010-04-24 16:38:41 +00004545 return;
4546 }
Mike Stump11289f42009-09-09 15:08:12 +00004547
John McCall48871652010-08-21 09:40:31 +00004548 if (!TagDecl) {
Chad Rosierc1183952012-06-26 22:30:43 +00004549 // The action failed to produce an enumeration tag. If this is a
Douglas Gregorba41d012010-04-24 16:38:41 +00004550 // definition, consume the entire definition.
Richard Smithbfdb1082012-03-12 08:56:40 +00004551 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
Douglas Gregorba41d012010-04-24 16:38:41 +00004552 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004553 SkipUntil(tok::r_brace, StopAtSemi);
Douglas Gregorba41d012010-04-24 16:38:41 +00004554 }
Chad Rosierc1183952012-06-26 22:30:43 +00004555
Douglas Gregorba41d012010-04-24 16:38:41 +00004556 DS.SetTypeSpecError();
4557 return;
4558 }
Richard Smith0f8ee222012-01-10 01:33:14 +00004559
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004560 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4561 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4562 ParseEnumBody(StartLoc, D);
4563 if (SkipBody.CheckSameAsPrevious &&
4564 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4565 DS.SetTypeSpecError();
4566 return;
4567 }
4568 }
Mike Stump11289f42009-09-09 15:08:12 +00004569
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004570 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4571 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004572 PrevSpec, DiagID, TagDecl, Owned,
4573 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00004574 Diag(StartLoc, DiagID) << PrevSpec;
Chris Lattner3b561a32006-08-13 00:12:11 +00004575}
4576
Chris Lattnerc1915e22007-01-25 07:29:02 +00004577/// ParseEnumBody - Parse a {} enclosed enumerator-list.
4578/// enumerator-list:
4579/// enumerator
4580/// enumerator-list ',' enumerator
4581/// enumerator:
Aaron Ballman730476b2014-11-08 15:33:35 +00004582/// enumeration-constant attributes[opt]
4583/// enumeration-constant attributes[opt] '=' constant-expression
Chris Lattnerc1915e22007-01-25 07:29:02 +00004584/// enumeration-constant:
4585/// identifier
4586///
John McCall48871652010-08-21 09:40:31 +00004587void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004588 // Enter the scope of the enum body and start the definition.
Hans Wennborgfe781452014-06-17 00:00:18 +00004589 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004590 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
Douglas Gregor07665a62009-01-05 19:45:36 +00004591
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004592 BalancedDelimiterTracker T(*this, tok::l_brace);
4593 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00004594
Chris Lattner37256fb2007-08-27 17:24:30 +00004595 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
David Blaikiebbafb8a2012-03-11 07:00:24 +00004596 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
Richard Smithf8812672016-12-02 22:38:31 +00004597 Diag(Tok, diag::err_empty_enum);
Mike Stump11289f42009-09-09 15:08:12 +00004598
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004599 SmallVector<Decl *, 32> EnumConstantDecls;
Jordan Rose60ac3162015-04-30 17:20:30 +00004600 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
Chris Lattnerc1915e22007-01-25 07:29:02 +00004601
Craig Topper161e4db2014-05-21 06:02:52 +00004602 Decl *LastEnumConstDecl = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004603
Chris Lattnerc1915e22007-01-25 07:29:02 +00004604 // Parse the enumerator-list.
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004605 while (Tok.isNot(tok::r_brace)) {
4606 // Parse enumerator. If failed, try skipping till the start of the next
4607 // enumerator definition.
4608 if (Tok.isNot(tok::identifier)) {
4609 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4610 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4611 TryConsumeToken(tok::comma))
4612 continue;
4613 break;
4614 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004615 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4616 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00004617
John McCall811a0f52010-10-22 23:36:17 +00004618 // If attributes exist after the enumerator, parse them.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004619 ParsedAttributesWithRange attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004620 MaybeParseGNUAttributes(attrs);
Aaron Ballman730476b2014-11-08 15:33:35 +00004621 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
Aaron Ballman606093a2017-10-15 15:01:42 +00004622 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4623 if (getLangOpts().CPlusPlus)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004624 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Aaron Ballman606093a2017-10-15 15:01:42 +00004625 ? diag::warn_cxx14_compat_ns_enum_attribute
4626 : diag::ext_ns_enum_attribute)
4627 << 1 /*enumerator*/;
Aaron Ballman730476b2014-11-08 15:33:35 +00004628 ParseCXX11Attributes(attrs);
4629 }
John McCall811a0f52010-10-22 23:36:17 +00004630
Chris Lattnerc1915e22007-01-25 07:29:02 +00004631 SourceLocation EqualLoc;
John McCalldadc5752010-08-24 06:29:42 +00004632 ExprResult AssignedVal;
Jordan Rose60ac3162015-04-30 17:20:30 +00004633 EnumAvailabilityDiags.emplace_back(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00004634
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004635 if (TryConsumeToken(tok::equal, EqualLoc)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004636 AssignedVal = ParseConstantExpression();
4637 if (AssignedVal.isInvalid())
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004638 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
Chris Lattnerc1915e22007-01-25 07:29:02 +00004639 }
Mike Stump11289f42009-09-09 15:08:12 +00004640
Chris Lattnerc1915e22007-01-25 07:29:02 +00004641 // Install the enumerator constant into EnumDecl.
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004642 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
Erich Keanec480f302018-07-12 21:09:05 +00004643 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4644 EqualLoc, AssignedVal.get());
Jordan Rose60ac3162015-04-30 17:20:30 +00004645 EnumAvailabilityDiags.back().done();
Chad Rosierc1183952012-06-26 22:30:43 +00004646
Chris Lattner4ef40012007-06-11 01:28:17 +00004647 EnumConstantDecls.push_back(EnumConstDecl);
4648 LastEnumConstDecl = EnumConstDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004649
Douglas Gregorce66d022010-09-07 14:51:08 +00004650 if (Tok.is(tok::identifier)) {
4651 // We're missing a comma between enumerators.
Richard Smithbdb84f32016-07-22 23:36:59 +00004652 SourceLocation Loc = getEndOfPreviousToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004653 Diag(Loc, diag::err_enumerator_list_missing_comma)
Douglas Gregorce66d022010-09-07 14:51:08 +00004654 << FixItHint::CreateInsertion(Loc, ", ");
4655 continue;
4656 }
Chad Rosierc1183952012-06-26 22:30:43 +00004657
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004658 // Emumerator definition must be finished, only comma or r_brace are
4659 // allowed here.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004660 SourceLocation CommaLoc;
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004661 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4662 if (EqualLoc.isValid())
4663 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4664 << tok::comma;
4665 else
4666 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4667 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4668 if (TryConsumeToken(tok::comma, CommaLoc))
4669 continue;
4670 } else {
4671 break;
4672 }
4673 }
Mike Stump11289f42009-09-09 15:08:12 +00004674
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004675 // If comma is followed by r_brace, emit appropriate warning.
4676 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004677 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
Richard Smith87f5dc52012-07-23 05:45:25 +00004678 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4679 diag::ext_enumerator_list_comma_cxx :
4680 diag::ext_enumerator_list_comma_c)
Richard Smith5d164bc2011-10-15 05:09:34 +00004681 << FixItHint::CreateRemoval(CommaLoc);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004682 else if (getLangOpts().CPlusPlus11)
Richard Smith5d164bc2011-10-15 05:09:34 +00004683 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4684 << FixItHint::CreateRemoval(CommaLoc);
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004685 break;
Richard Smith5d164bc2011-10-15 05:09:34 +00004686 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004687 }
Mike Stump11289f42009-09-09 15:08:12 +00004688
Chris Lattnerc1915e22007-01-25 07:29:02 +00004689 // Eat the }.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004690 T.consumeClose();
Chris Lattnerc1915e22007-01-25 07:29:02 +00004691
Chris Lattnerc1915e22007-01-25 07:29:02 +00004692 // If attributes exist after the identifier list, parse them.
John McCall084e83d2011-03-24 11:26:52 +00004693 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004694 MaybeParseGNUAttributes(attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004695
Erich Keanec480f302018-07-12 21:09:05 +00004696 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4697 getCurScope(), attrs);
Mike Stump11289f42009-09-09 15:08:12 +00004698
Jordan Rose60ac3162015-04-30 17:20:30 +00004699 // Now handle enum constant availability diagnostics.
4700 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4701 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4702 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4703 EnumAvailabilityDiags[i].redelay();
4704 PD.complete(EnumConstantDecls[i]);
4705 }
4706
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004707 EnumScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004708 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
Richard Smith369b9f92012-06-25 21:37:02 +00004709
4710 // The next token must be valid after an enum definition. If not, a ';'
4711 // was probably forgotten.
Richard Smith200f47c2012-07-02 19:14:01 +00004712 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4713 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
Alp Toker383d2c42014-01-01 03:08:43 +00004714 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004715 // Push this token back into the preprocessor and change our current token
4716 // to ';' so that the rest of the code recovers as though there were an
4717 // ';' after the definition.
Ilya Biryukov929af672019-05-17 09:32:05 +00004718 PP.EnterToken(Tok, /*IsReinject=*/true);
Richard Smith369b9f92012-06-25 21:37:02 +00004719 Tok.setKind(tok::semi);
4720 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004721}
Chris Lattner3b561a32006-08-13 00:12:11 +00004722
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004723/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4724/// is definitely a type-specifier. Return false if it isn't part of a type
4725/// specifier or if we're not sure.
4726bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4727 switch (Tok.getKind()) {
4728 default: return false;
4729 // type-specifiers
4730 case tok::kw_short:
4731 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004732 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004733 case tok::kw___int128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004734 case tok::kw_signed:
4735 case tok::kw_unsigned:
4736 case tok::kw__Complex:
4737 case tok::kw__Imaginary:
4738 case tok::kw_void:
4739 case tok::kw_char:
4740 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004741 case tok::kw_char8_t:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004742 case tok::kw_char16_t:
4743 case tok::kw_char32_t:
4744 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004745 case tok::kw_half:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004746 case tok::kw_float:
4747 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004748 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004749 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004750 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004751 case tok::kw___float128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004752 case tok::kw_bool:
4753 case tok::kw__Bool:
4754 case tok::kw__Decimal32:
4755 case tok::kw__Decimal64:
4756 case tok::kw__Decimal128:
4757 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004758#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004759#include "clang/Basic/OpenCLImageTypes.def"
Chad Rosierc1183952012-06-26 22:30:43 +00004760
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004761 // struct-or-union-specifier (C99) or class-specifier (C++)
4762 case tok::kw_class:
4763 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004764 case tok::kw___interface:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004765 case tok::kw_union:
4766 // enum-specifier
4767 case tok::kw_enum:
Chad Rosierc1183952012-06-26 22:30:43 +00004768
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004769 // typedef-name
4770 case tok::annot_typename:
4771 return true;
4772 }
4773}
4774
Steve Naroff69e8f9e2008-02-11 23:15:56 +00004775/// isTypeSpecifierQualifier - Return true if the current token could be the
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004776/// start of a specifier-qualifier-list.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004777bool Parser::isTypeSpecifierQualifier() {
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004778 switch (Tok.getKind()) {
4779 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004780
Chris Lattner020bab92009-01-04 23:41:41 +00004781 case tok::identifier: // foo::bar
John Thompson22334602010-02-05 00:12:22 +00004782 if (TryAltiVecVectorToken())
4783 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004784 LLVM_FALLTHROUGH;
Douglas Gregor333489b2009-03-27 23:10:48 +00004785 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004786 // Annotate typenames and C++ scope specifiers. If we get one, just
4787 // recurse to handle whatever we get.
4788 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004789 return true;
4790 if (Tok.is(tok::identifier))
4791 return false;
4792 return isTypeSpecifierQualifier();
Douglas Gregor333489b2009-03-27 23:10:48 +00004793
Chris Lattner020bab92009-01-04 23:41:41 +00004794 case tok::coloncolon: // ::foo::bar
4795 if (NextToken().is(tok::kw_new) || // ::new
4796 NextToken().is(tok::kw_delete)) // ::delete
4797 return false;
4798
Chris Lattner020bab92009-01-04 23:41:41 +00004799 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004800 return true;
4801 return isTypeSpecifierQualifier();
Mike Stump11289f42009-09-09 15:08:12 +00004802
Chris Lattnere37e2332006-08-15 04:50:22 +00004803 // GNU attributes support.
4804 case tok::kw___attribute:
Steve Naroffad373bd2007-07-31 12:34:36 +00004805 // GNU typeof support.
4806 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004807
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004808 // type-specifiers
4809 case tok::kw_short:
4810 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004811 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004812 case tok::kw___int128:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004813 case tok::kw_signed:
4814 case tok::kw_unsigned:
4815 case tok::kw__Complex:
4816 case tok::kw__Imaginary:
4817 case tok::kw_void:
4818 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004819 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004820 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004821 case tok::kw_char16_t:
4822 case tok::kw_char32_t:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004823 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004824 case tok::kw_half:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004825 case tok::kw_float:
4826 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004827 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004828 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004829 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004830 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004831 case tok::kw_bool:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004832 case tok::kw__Bool:
4833 case tok::kw__Decimal32:
4834 case tok::kw__Decimal64:
4835 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004836 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004837#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004838#include "clang/Basic/OpenCLImageTypes.def"
Mike Stump11289f42009-09-09 15:08:12 +00004839
Chris Lattner861a2262008-04-13 18:59:07 +00004840 // struct-or-union-specifier (C99) or class-specifier (C++)
4841 case tok::kw_class:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004842 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004843 case tok::kw___interface:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004844 case tok::kw_union:
4845 // enum-specifier
4846 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004847
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004848 // type-qualifier
4849 case tok::kw_const:
4850 case tok::kw_volatile:
4851 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004852 case tok::kw__Sat:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004853
John McCallea0a39e2012-11-14 00:49:39 +00004854 // Debugger support.
4855 case tok::kw___unknown_anytype:
4856
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004857 // typedef-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00004858 case tok::annot_typename:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004859 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004860
Chris Lattner409bf7d2008-10-20 00:25:30 +00004861 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4862 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004863 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00004864
Steve Naroff44ac7772008-12-25 14:16:32 +00004865 case tok::kw___cdecl:
4866 case tok::kw___stdcall:
4867 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004868 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004869 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004870 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004871 case tok::kw___w64:
4872 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004873 case tok::kw___ptr32:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004874 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004875 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004876
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004877 case tok::kw__Nonnull:
4878 case tok::kw__Nullable:
4879 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004880
Douglas Gregorab209d82015-07-07 03:58:42 +00004881 case tok::kw___kindof:
4882
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004883 case tok::kw___private:
4884 case tok::kw___local:
4885 case tok::kw___global:
4886 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004887 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004888 case tok::kw___read_only:
4889 case tok::kw___read_write:
4890 case tok::kw___write_only:
Eli Friedman53339e02009-06-08 23:27:34 +00004891 return true;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004892
Anastasia Stulova314fab62019-03-28 11:47:14 +00004893 case tok::kw_private:
4894 return getLangOpts().OpenCL;
4895
Richard Smith8e1ac332013-03-28 01:55:44 +00004896 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004897 case tok::kw__Atomic:
4898 return true;
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004899 }
4900}
4901
Chris Lattneracd58a32006-08-06 17:24:14 +00004902/// isDeclarationSpecifier() - Return true if the current token is part of a
4903/// declaration specifier.
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004904///
4905/// \param DisambiguatingWithExpression True to indicate that the purpose of
4906/// this check is to disambiguate between an expression and a declaration.
4907bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
Chris Lattneracd58a32006-08-06 17:24:14 +00004908 switch (Tok.getKind()) {
4909 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004910
Xiuli Pan9c14e282016-01-09 12:53:17 +00004911 case tok::kw_pipe:
Sven van Haastregte518bb42019-05-22 13:12:20 +00004912 return (getLangOpts().OpenCL && getLangOpts().OpenCLVersion >= 200) ||
4913 getLangOpts().OpenCLCPlusPlus;
Xiuli Pan9c14e282016-01-09 12:53:17 +00004914
Chris Lattner020bab92009-01-04 23:41:41 +00004915 case tok::identifier: // foo::bar
Steve Naroff9527bbf2009-03-09 21:12:44 +00004916 // Unfortunate hack to support "Class.factoryMethod" notation.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004917 if (getLangOpts().ObjC && NextToken().is(tok::period))
Steve Naroff9527bbf2009-03-09 21:12:44 +00004918 return false;
John Thompson22334602010-02-05 00:12:22 +00004919 if (TryAltiVecVectorToken())
4920 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004921 LLVM_FALLTHROUGH;
David Blaikie15a430a2011-12-04 05:04:18 +00004922 case tok::kw_decltype: // decltype(T())::type
Douglas Gregor333489b2009-03-27 23:10:48 +00004923 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004924 // Annotate typenames and C++ scope specifiers. If we get one, just
4925 // recurse to handle whatever we get.
4926 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004927 return true;
4928 if (Tok.is(tok::identifier))
4929 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004930
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004931 // If we're in Objective-C and we have an Objective-C class type followed
Chad Rosierc1183952012-06-26 22:30:43 +00004932 // by an identifier and then either ':' or ']', in a place where an
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004933 // expression is permitted, then this is probably a class message send
4934 // missing the initial '['. In this case, we won't consider this to be
4935 // the start of a declaration.
Chad Rosierc1183952012-06-26 22:30:43 +00004936 if (DisambiguatingWithExpression &&
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004937 isStartOfObjCClassMessageMissingOpenBracket())
4938 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004939
John McCall1f476a12010-02-26 08:45:28 +00004940 return isDeclarationSpecifier();
4941
Chris Lattner020bab92009-01-04 23:41:41 +00004942 case tok::coloncolon: // ::foo::bar
4943 if (NextToken().is(tok::kw_new) || // ::new
4944 NextToken().is(tok::kw_delete)) // ::delete
4945 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004946
Chris Lattner020bab92009-01-04 23:41:41 +00004947 // Annotate typenames and C++ scope specifiers. If we get one, just
4948 // recurse to handle whatever we get.
4949 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004950 return true;
4951 return isDeclarationSpecifier();
Mike Stump11289f42009-09-09 15:08:12 +00004952
Chris Lattneracd58a32006-08-06 17:24:14 +00004953 // storage-class-specifier
4954 case tok::kw_typedef:
4955 case tok::kw_extern:
Steve Naroff2050b0d2007-12-18 00:16:02 +00004956 case tok::kw___private_extern__:
Chris Lattneracd58a32006-08-06 17:24:14 +00004957 case tok::kw_static:
4958 case tok::kw_auto:
Richard Smithe301ba22015-11-11 02:02:15 +00004959 case tok::kw___auto_type:
Chris Lattneracd58a32006-08-06 17:24:14 +00004960 case tok::kw_register:
4961 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00004962 case tok::kw_thread_local:
4963 case tok::kw__Thread_local:
Mike Stump11289f42009-09-09 15:08:12 +00004964
Douglas Gregor26701a42011-09-09 02:06:17 +00004965 // Modules
4966 case tok::kw___module_private__:
Chad Rosierc1183952012-06-26 22:30:43 +00004967
John McCallea0a39e2012-11-14 00:49:39 +00004968 // Debugger support
4969 case tok::kw___unknown_anytype:
4970
Chris Lattneracd58a32006-08-06 17:24:14 +00004971 // type-specifiers
4972 case tok::kw_short:
4973 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004974 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004975 case tok::kw___int128:
Chris Lattneracd58a32006-08-06 17:24:14 +00004976 case tok::kw_signed:
4977 case tok::kw_unsigned:
4978 case tok::kw__Complex:
4979 case tok::kw__Imaginary:
4980 case tok::kw_void:
4981 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004982 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004983 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004984 case tok::kw_char16_t:
4985 case tok::kw_char32_t:
4986
Chris Lattneracd58a32006-08-06 17:24:14 +00004987 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004988 case tok::kw_half:
Chris Lattneracd58a32006-08-06 17:24:14 +00004989 case tok::kw_float:
4990 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004991 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004992 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004993 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004994 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004995 case tok::kw_bool:
Chris Lattneracd58a32006-08-06 17:24:14 +00004996 case tok::kw__Bool:
4997 case tok::kw__Decimal32:
4998 case tok::kw__Decimal64:
4999 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00005000 case tok::kw___vector:
Mike Stump11289f42009-09-09 15:08:12 +00005001
Chris Lattner861a2262008-04-13 18:59:07 +00005002 // struct-or-union-specifier (C99) or class-specifier (C++)
5003 case tok::kw_class:
Chris Lattneracd58a32006-08-06 17:24:14 +00005004 case tok::kw_struct:
5005 case tok::kw_union:
Joao Matosdc86f942012-08-31 18:45:21 +00005006 case tok::kw___interface:
Chris Lattneracd58a32006-08-06 17:24:14 +00005007 // enum-specifier
5008 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00005009
Chris Lattneracd58a32006-08-06 17:24:14 +00005010 // type-qualifier
5011 case tok::kw_const:
5012 case tok::kw_volatile:
5013 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00005014 case tok::kw__Sat:
Steve Naroffad373bd2007-07-31 12:34:36 +00005015
Chris Lattneracd58a32006-08-06 17:24:14 +00005016 // function-specifier
5017 case tok::kw_inline:
Douglas Gregor61956c42008-10-31 09:07:45 +00005018 case tok::kw_virtual:
5019 case tok::kw_explicit:
Richard Smith0015f092013-01-17 22:16:11 +00005020 case tok::kw__Noreturn:
Chris Lattner7b20dc72007-08-09 16:40:21 +00005021
Richard Smith1dba27c2013-01-29 09:02:09 +00005022 // alignment-specifier
5023 case tok::kw__Alignas:
5024
Richard Smithd16fe122012-10-25 00:00:53 +00005025 // friend keyword.
5026 case tok::kw_friend:
5027
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00005028 // static_assert-declaration
5029 case tok::kw__Static_assert:
5030
Chris Lattner599e47e2007-08-09 17:01:07 +00005031 // GNU typeof support.
5032 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00005033
Chris Lattner599e47e2007-08-09 17:01:07 +00005034 // GNU attributes.
Chris Lattner7b20dc72007-08-09 16:40:21 +00005035 case tok::kw___attribute:
Mike Stump11289f42009-09-09 15:08:12 +00005036
Richard Smithd16fe122012-10-25 00:00:53 +00005037 // C++11 decltype and constexpr.
David Blaikie15a430a2011-12-04 05:04:18 +00005038 case tok::annot_decltype:
Richard Smithd16fe122012-10-25 00:00:53 +00005039 case tok::kw_constexpr:
Francois Pichete878cb62011-06-19 08:02:06 +00005040
Gauthier Harnisch796ed032019-06-14 08:56:20 +00005041 // C++20 consteval.
5042 case tok::kw_consteval:
5043
Richard Smith8e1ac332013-03-28 01:55:44 +00005044 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00005045 case tok::kw__Atomic:
5046 return true;
5047
Chris Lattner8b2ec162008-07-26 03:38:44 +00005048 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5049 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005050 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00005051
Douglas Gregor19b7acf2011-04-27 05:41:15 +00005052 // typedef-name
5053 case tok::annot_typename:
5054 return !DisambiguatingWithExpression ||
5055 !isStartOfObjCClassMessageMissingOpenBracket();
Chad Rosierc1183952012-06-26 22:30:43 +00005056
Steve Narofff192fab2009-01-06 19:34:12 +00005057 case tok::kw___declspec:
Steve Naroff44ac7772008-12-25 14:16:32 +00005058 case tok::kw___cdecl:
5059 case tok::kw___stdcall:
5060 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005061 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005062 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005063 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00005064 case tok::kw___w64:
Aaron Ballman317a77f2013-05-22 23:25:32 +00005065 case tok::kw___sptr:
5066 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005067 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005068 case tok::kw___ptr32:
Eli Friedman53339e02009-06-08 23:27:34 +00005069 case tok::kw___forceinline:
Dawn Perchik335e16b2010-09-03 01:29:35 +00005070 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00005071 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005072
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005073 case tok::kw__Nonnull:
5074 case tok::kw__Nullable:
5075 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005076
Douglas Gregorab209d82015-07-07 03:58:42 +00005077 case tok::kw___kindof:
5078
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005079 case tok::kw___private:
5080 case tok::kw___local:
5081 case tok::kw___global:
5082 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005083 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005084 case tok::kw___read_only:
5085 case tok::kw___read_write:
5086 case tok::kw___write_only:
Alexey Bader954ba212016-04-08 13:40:33 +00005087#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00005088#include "clang/Basic/OpenCLImageTypes.def"
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005089
Eli Friedman53339e02009-06-08 23:27:34 +00005090 return true;
Anastasia Stulova314fab62019-03-28 11:47:14 +00005091
5092 case tok::kw_private:
5093 return getLangOpts().OpenCL;
Chris Lattneracd58a32006-08-06 17:24:14 +00005094 }
5095}
5096
Richard Smith35845152017-02-07 01:37:30 +00005097bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005098 TentativeParsingAction TPA(*this);
5099
5100 // Parse the C++ scope specifier.
5101 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005102 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005103 /*EnteringContext=*/true)) {
John McCall1f476a12010-02-26 08:45:28 +00005104 TPA.Revert();
5105 return false;
5106 }
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005107
5108 // Parse the constructor name.
Richard Smithaf3b3252017-05-18 19:21:48 +00005109 if (Tok.is(tok::identifier)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005110 // We already know that we have a constructor name; just consume
5111 // the token.
5112 ConsumeToken();
Richard Smithaf3b3252017-05-18 19:21:48 +00005113 } else if (Tok.is(tok::annot_template_id)) {
5114 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005115 } else {
5116 TPA.Revert();
5117 return false;
5118 }
5119
Richard Smith8f8697f2017-02-08 01:16:55 +00005120 // There may be attributes here, appertaining to the constructor name or type
5121 // we just stepped past.
5122 SkipCXX11Attributes();
5123
Richard Smith43f340f2012-03-27 23:05:05 +00005124 // Current class name must be followed by a left parenthesis.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005125 if (Tok.isNot(tok::l_paren)) {
5126 TPA.Revert();
5127 return false;
5128 }
5129 ConsumeParen();
5130
Richard Smith43f340f2012-03-27 23:05:05 +00005131 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5132 // that we have a constructor.
5133 if (Tok.is(tok::r_paren) ||
5134 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005135 TPA.Revert();
5136 return true;
5137 }
5138
Richard Smithf2163662013-09-06 00:12:20 +00005139 // A C++11 attribute here signals that we have a constructor, and is an
5140 // attribute on the first constructor parameter.
5141 if (getLangOpts().CPlusPlus11 &&
5142 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5143 /*OuterMightBeMessageSend*/ true)) {
5144 TPA.Revert();
5145 return true;
5146 }
5147
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005148 // If we need to, enter the specified scope.
5149 DeclaratorScopeObj DeclScopeObj(*this, SS);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005150 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005151 DeclScopeObj.EnterDeclaratorScope();
5152
Francois Pichet79f3a872011-01-31 04:54:32 +00005153 // Optionally skip Microsoft attributes.
John McCall084e83d2011-03-24 11:26:52 +00005154 ParsedAttributes Attrs(AttrFactory);
Francois Pichet79f3a872011-01-31 04:54:32 +00005155 MaybeParseMicrosoftAttributes(Attrs);
5156
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005157 // Check whether the next token(s) are part of a declaration
5158 // specifier, in which case we have the start of a parameter and,
5159 // therefore, we know that this is a constructor.
Richard Smithefd009d2012-03-27 00:56:56 +00005160 bool IsConstructor = false;
5161 if (isDeclarationSpecifier())
5162 IsConstructor = true;
5163 else if (Tok.is(tok::identifier) ||
5164 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5165 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5166 // This might be a parenthesized member name, but is more likely to
5167 // be a constructor declaration with an invalid argument type. Keep
5168 // looking.
5169 if (Tok.is(tok::annot_cxxscope))
Richard Smithaf3b3252017-05-18 19:21:48 +00005170 ConsumeAnnotationToken();
Richard Smithefd009d2012-03-27 00:56:56 +00005171 ConsumeToken();
5172
5173 // If this is not a constructor, we must be parsing a declarator,
Richard Smith1453e312012-03-27 01:42:32 +00005174 // which must have one of the following syntactic forms (see the
5175 // grammar extract at the start of ParseDirectDeclarator):
Richard Smithefd009d2012-03-27 00:56:56 +00005176 switch (Tok.getKind()) {
5177 case tok::l_paren:
5178 // C(X ( int));
5179 case tok::l_square:
5180 // C(X [ 5]);
5181 // C(X [ [attribute]]);
5182 case tok::coloncolon:
5183 // C(X :: Y);
5184 // C(X :: *p);
Richard Smithefd009d2012-03-27 00:56:56 +00005185 // Assume this isn't a constructor, rather than assuming it's a
5186 // constructor with an unnamed parameter of an ill-formed type.
5187 break;
5188
Richard Smith446161b2014-03-03 21:12:53 +00005189 case tok::r_paren:
5190 // C(X )
Richard Smith8f8697f2017-02-08 01:16:55 +00005191
5192 // Skip past the right-paren and any following attributes to get to
5193 // the function body or trailing-return-type.
5194 ConsumeParen();
5195 SkipCXX11Attributes();
5196
Richard Smith35845152017-02-07 01:37:30 +00005197 if (DeductionGuide) {
5198 // C(X) -> ... is a deduction guide.
Richard Smith8f8697f2017-02-08 01:16:55 +00005199 IsConstructor = Tok.is(tok::arrow);
Richard Smith35845152017-02-07 01:37:30 +00005200 break;
5201 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005202 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
Richard Smith446161b2014-03-03 21:12:53 +00005203 // Assume these were meant to be constructors:
5204 // C(X) : (the name of a bit-field cannot be parenthesized).
5205 // C(X) try (this is otherwise ill-formed).
5206 IsConstructor = true;
5207 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005208 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
Richard Smith446161b2014-03-03 21:12:53 +00005209 // If we have a constructor name within the class definition,
5210 // assume these were meant to be constructors:
5211 // C(X) {
5212 // C(X) ;
5213 // ... because otherwise we would be declaring a non-static data
5214 // member that is ill-formed because it's of the same type as its
5215 // surrounding class.
5216 //
5217 // FIXME: We can actually do this whether or not the name is qualified,
5218 // because if it is qualified in this context it must be being used as
Richard Smith35845152017-02-07 01:37:30 +00005219 // a constructor name.
Richard Smith446161b2014-03-03 21:12:53 +00005220 // currently, so we're somewhat conservative here.
5221 IsConstructor = IsUnqualified;
5222 }
5223 break;
5224
Richard Smithefd009d2012-03-27 00:56:56 +00005225 default:
5226 IsConstructor = true;
5227 break;
5228 }
5229 }
5230
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005231 TPA.Revert();
5232 return IsConstructor;
5233}
Chris Lattnerb9093cd2006-08-04 04:39:53 +00005234
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005235/// ParseTypeQualifierListOpt
Dawn Perchik335e16b2010-09-03 01:29:35 +00005236/// type-qualifier-list: [C99 6.7.5]
5237/// type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005238/// [vendor] attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005239/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005240/// type-qualifier-list type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005241/// [vendor] type-qualifier-list attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005242/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005243/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
Aaron Ballman08b06592014-07-22 12:44:22 +00005244/// [ only if AttReqs & AR_CXX11AttributesParsed ]
5245/// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5246/// AttrRequirements bitmask values.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005247void Parser::ParseTypeQualifierListOpt(
5248 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5249 bool IdentifierRequired,
5250 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
Aaron Ballman606093a2017-10-15 15:01:42 +00005251 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005252 isCXX11AttributeSpecifier()) {
John McCall084e83d2011-03-24 11:26:52 +00005253 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith3dff2512012-04-10 03:25:07 +00005254 ParseCXX11Attributes(attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005255 DS.takeAttributesFrom(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005256 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005257
5258 SourceLocation EndLoc;
5259
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005260 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00005261 bool isInvalid = false;
Craig Topper161e4db2014-05-21 06:02:52 +00005262 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00005263 unsigned DiagID = 0;
Chris Lattner60809f52006-11-28 05:18:46 +00005264 SourceLocation Loc = Tok.getLocation();
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005265
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005266 switch (Tok.getKind()) {
Douglas Gregor28c78432010-08-27 17:35:51 +00005267 case tok::code_completion:
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005268 if (CodeCompletionHandler)
5269 (*CodeCompletionHandler)();
5270 else
5271 Actions.CodeCompleteTypeQualifiers(DS);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00005272 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00005273
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005274 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00005275 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005276 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005277 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005278 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00005279 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005280 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005281 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005282 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00005283 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005284 getLangOpts());
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005285 break;
Richard Smith8e1ac332013-03-28 01:55:44 +00005286 case tok::kw__Atomic:
5287 if (!AtomicAllowed)
5288 goto DoneWithTypeQuals;
5289 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5290 getLangOpts());
5291 break;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005292
5293 // OpenCL qualifiers:
Anastasia Stulova948e37c2019-03-25 11:54:02 +00005294 case tok::kw_private:
Anastasia Stulova314fab62019-03-28 11:47:14 +00005295 if (!getLangOpts().OpenCL)
5296 goto DoneWithTypeQuals;
5297 LLVM_FALLTHROUGH;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005298 case tok::kw___private:
5299 case tok::kw___global:
5300 case tok::kw___local:
5301 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005302 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005303 case tok::kw___read_only:
5304 case tok::kw___write_only:
5305 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00005306 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005307 break;
5308
Andrey Bokhanko45d41322016-05-11 18:38:21 +00005309 case tok::kw___unaligned:
5310 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5311 getLangOpts());
5312 break;
Aaron Ballman317a77f2013-05-22 23:25:32 +00005313 case tok::kw___uptr:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005314 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
Alp Toker62c5b572013-11-26 01:30:10 +00005315 // with the MS modifier keyword.
Aaron Ballman08b06592014-07-22 12:44:22 +00005316 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
Alp Toker47642d22013-12-03 06:13:01 +00005317 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5318 if (TryKeywordIdentFallback(false))
5319 continue;
Alp Toker62c5b572013-11-26 01:30:10 +00005320 }
Galina Kistanova77674252017-06-01 21:15:34 +00005321 LLVM_FALLTHROUGH;
Alp Toker62c5b572013-11-26 01:30:10 +00005322 case tok::kw___sptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005323 case tok::kw___w64:
Steve Narofff9c29d42008-12-25 14:41:26 +00005324 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005325 case tok::kw___ptr32:
Steve Naroff44ac7772008-12-25 14:16:32 +00005326 case tok::kw___cdecl:
5327 case tok::kw___stdcall:
5328 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005329 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005330 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005331 case tok::kw___vectorcall:
Aaron Ballman08b06592014-07-22 12:44:22 +00005332 if (AttrReqs & AR_DeclspecAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005333 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00005334 continue;
5335 }
5336 goto DoneWithTypeQuals;
Dawn Perchik335e16b2010-09-03 01:29:35 +00005337 case tok::kw___pascal:
Aaron Ballman08b06592014-07-22 12:44:22 +00005338 if (AttrReqs & AR_VendorAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005339 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00005340 continue;
5341 }
5342 goto DoneWithTypeQuals;
Douglas Gregor261a89b2015-06-19 17:51:05 +00005343
5344 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005345 case tok::kw__Nonnull:
5346 case tok::kw__Nullable:
5347 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005348 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5349 continue;
5350
Douglas Gregorab209d82015-07-07 03:58:42 +00005351 // Objective-C 'kindof' types.
5352 case tok::kw___kindof:
5353 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00005354 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00005355 (void)ConsumeToken();
5356 continue;
5357
Chris Lattnere37e2332006-08-15 04:50:22 +00005358 case tok::kw___attribute:
Aaron Ballman08b06592014-07-22 12:44:22 +00005359 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5360 // When GNU attributes are expressly forbidden, diagnose their usage.
5361 Diag(Tok, diag::err_attributes_not_allowed);
5362
5363 // Parse the attributes even if they are rejected to ensure that error
5364 // recovery is graceful.
5365 if (AttrReqs & AR_GNUAttributesParsed ||
5366 AttrReqs & AR_GNUAttributesParsedAndRejected) {
John McCall53fa7142010-12-24 02:08:15 +00005367 ParseGNUAttributes(DS.getAttributes());
Chris Lattnercf0bab22008-12-18 07:02:59 +00005368 continue; // do *not* consume the next token!
5369 }
5370 // otherwise, FALL THROUGH!
Galina Kistanova77674252017-06-01 21:15:34 +00005371 LLVM_FALLTHROUGH;
Chris Lattnercf0bab22008-12-18 07:02:59 +00005372 default:
Steve Naroff44ac7772008-12-25 14:16:32 +00005373 DoneWithTypeQuals:
Chris Lattnercf0bab22008-12-18 07:02:59 +00005374 // If this is not a type-qualifier token, we're done reading type
5375 // qualifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00005376 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005377 if (EndLoc.isValid())
5378 DS.SetRangeEnd(EndLoc);
Chris Lattnercf0bab22008-12-18 07:02:59 +00005379 return;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005380 }
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00005381
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005382 // If the specifier combination wasn't legal, issue a diagnostic.
5383 if (isInvalid) {
5384 assert(PrevSpec && "Method did not return previous specifier!");
Chris Lattner6d29c102008-11-18 07:48:38 +00005385 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005386 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005387 EndLoc = ConsumeToken();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005388 }
5389}
5390
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005391/// ParseDeclarator - Parse and verify a newly-initialized declarator.
5392///
5393void Parser::ParseDeclarator(Declarator &D) {
5394 /// This implements the 'declarator' production in the C grammar, then checks
5395 /// for well-formedness and issues diagnostics.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005396 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005397}
5398
Richard Smith0b350b92014-10-28 16:55:02 +00005399static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
Faisal Vali421b2d12017-12-29 05:41:00 +00005400 DeclaratorContext TheContext) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005401 if (Kind == tok::star || Kind == tok::caret)
5402 return true;
5403
Sven van Haastregte518bb42019-05-22 13:12:20 +00005404 if (Kind == tok::kw_pipe &&
5405 ((Lang.OpenCL && Lang.OpenCLVersion >= 200) || Lang.OpenCLCPlusPlus))
Xiuli Pan9c14e282016-01-09 12:53:17 +00005406 return true;
5407
Richard Smith0efa75c2012-03-29 01:16:42 +00005408 if (!Lang.CPlusPlus)
5409 return false;
5410
Richard Smith0b350b92014-10-28 16:55:02 +00005411 if (Kind == tok::amp)
5412 return true;
5413
5414 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5415 // But we must not parse them in conversion-type-ids and new-type-ids, since
5416 // those can be legitimately followed by a && operator.
5417 // (The same thing can in theory happen after a trailing-return-type, but
5418 // since those are a C++11 feature, there is no rejects-valid issue there.)
5419 if (Kind == tok::ampamp)
Faisal Vali421b2d12017-12-29 05:41:00 +00005420 return Lang.CPlusPlus11 ||
5421 (TheContext != DeclaratorContext::ConversionIdContext &&
5422 TheContext != DeclaratorContext::CXXNewContext);
Richard Smith0b350b92014-10-28 16:55:02 +00005423
5424 return false;
Richard Smith0efa75c2012-03-29 01:16:42 +00005425}
5426
Xiuli Pan9c14e282016-01-09 12:53:17 +00005427// Indicates whether the given declarator is a pipe declarator.
5428static bool isPipeDeclerator(const Declarator &D) {
5429 const unsigned NumTypes = D.getNumTypeObjects();
5430
5431 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5432 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5433 return true;
5434
5435 return false;
5436}
5437
Sebastian Redlbd150f42008-11-21 19:14:01 +00005438/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5439/// is parsed by the function passed to it. Pass null, and the direct-declarator
5440/// isn't parsed at all, making this function effectively parse the C++
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005441/// ptr-operator production.
5442///
Richard Smith09f76ee2011-10-19 21:33:05 +00005443/// If the grammar of this construct is extended, matching changes must also be
Richard Smith1453e312012-03-27 01:42:32 +00005444/// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5445/// isConstructorDeclarator.
Richard Smith09f76ee2011-10-19 21:33:05 +00005446///
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005447/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5448/// [C] pointer[opt] direct-declarator
5449/// [C++] direct-declarator
5450/// [C++] ptr-operator declarator
Chris Lattner6c7416c2006-08-07 00:19:33 +00005451///
5452/// pointer: [C99 6.7.5]
5453/// '*' type-qualifier-list[opt]
5454/// '*' type-qualifier-list[opt] pointer
5455///
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005456/// ptr-operator:
5457/// '*' cv-qualifier-seq[opt]
5458/// '&'
Sebastian Redled0f3b02009-03-15 22:02:01 +00005459/// [C++0x] '&&'
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005460/// [GNU] '&' restrict[opt] attributes[opt]
Sebastian Redled0f3b02009-03-15 22:02:01 +00005461/// [GNU?] '&&' restrict[opt] attributes[opt]
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005462/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
Sebastian Redlbd150f42008-11-21 19:14:01 +00005463void Parser::ParseDeclaratorInternal(Declarator &D,
5464 DirectDeclParseFunction DirectDeclParser) {
Douglas Gregor66a985d2009-08-26 14:27:30 +00005465 if (Diags.hasAllExtensionsSilenced())
5466 D.setExtension();
Chad Rosierc1183952012-06-26 22:30:43 +00005467
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005468 // C++ member pointers start with a '::' or a nested-name.
5469 // Member pointers get special handling, since there's no place for the
5470 // scope spec in the generic path below.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005471 if (getLangOpts().CPlusPlus &&
Richard Smith83c2ecf2016-02-02 23:34:49 +00005472 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
Serge Pavlov458ea762014-07-16 05:16:52 +00005473 (Tok.is(tok::identifier) &&
5474 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
Chris Lattner803802d2009-03-24 17:04:48 +00005475 Tok.is(tok::annot_cxxscope))) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005476 bool EnteringContext =
5477 D.getContext() == DeclaratorContext::FileContext ||
5478 D.getContext() == DeclaratorContext::MemberContext;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005479 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005480 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005481
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +00005482 if (SS.isNotEmpty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005483 if (Tok.isNot(tok::star)) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005484 // The scope spec really belongs to the direct-declarator.
Richard Smith5f044ad2013-01-08 22:43:49 +00005485 if (D.mayHaveIdentifier())
5486 D.getCXXScopeSpec() = SS;
5487 else
5488 AnnotateScopeToken(SS, true);
5489
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005490 if (DirectDeclParser)
5491 (this->*DirectDeclParser)(D);
5492 return;
5493 }
5494
5495 SourceLocation Loc = ConsumeToken();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005496 D.SetRangeEnd(Loc);
John McCall084e83d2011-03-24 11:26:52 +00005497 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005498 ParseTypeQualifierListOpt(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005499 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005500
5501 // Recurse to parse whatever is left.
5502 ParseDeclaratorInternal(D, DirectDeclParser);
5503
5504 // Sema will have to catch (syntactically invalid) pointers into global
5505 // scope. It has to catch pointers into namespace scope anyway.
Erich Keanec480f302018-07-12 21:09:05 +00005506 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005507 SS, DS.getTypeQualifiers(), DS.getEndLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005508 std::move(DS.getAttributes()),
5509 /* Don't replace range end. */ SourceLocation());
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005510 return;
5511 }
5512 }
5513
5514 tok::TokenKind Kind = Tok.getKind();
Xiuli Pan9c14e282016-01-09 12:53:17 +00005515
5516 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
Xiuli Pan11e13f62016-02-26 03:13:03 +00005517 DeclSpec DS(AttrFactory);
5518 ParseTypeQualifierListOpt(DS);
Xiuli Pan9c14e282016-01-09 12:53:17 +00005519
5520 D.AddTypeInfo(
5521 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005522 std::move(DS.getAttributes()), SourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00005523 }
5524
Steve Naroffec33ed92008-08-27 16:04:49 +00005525 // Not a pointer, C++ reference, or block.
Richard Smith0b350b92014-10-28 16:55:02 +00005526 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00005527 if (DirectDeclParser)
5528 (this->*DirectDeclParser)(D);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005529 return;
5530 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005531
Sebastian Redled0f3b02009-03-15 22:02:01 +00005532 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5533 // '&&' -> rvalue reference
Sebastian Redl3b27be62009-03-23 00:00:23 +00005534 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005535 D.SetRangeEnd(Loc);
Bill Wendling3708c182007-05-27 10:15:43 +00005536
Chris Lattner9eac9312009-03-27 04:18:06 +00005537 if (Kind == tok::star || Kind == tok::caret) {
Chris Lattner788404f2008-02-21 01:32:26 +00005538 // Is a pointer.
John McCall084e83d2011-03-24 11:26:52 +00005539 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005540
Aaron Ballman08b06592014-07-22 12:44:22 +00005541 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5542 // C++11 attributes are allowed.
5543 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
Faisal Vali421b2d12017-12-29 05:41:00 +00005544 ((D.getContext() != DeclaratorContext::CXXNewContext)
5545 ? AR_GNUAttributesParsed
5546 : AR_GNUAttributesParsedAndRejected);
Aaron Ballman08b06592014-07-22 12:44:22 +00005547 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005548 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005549
Bill Wendling3708c182007-05-27 10:15:43 +00005550 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005551 ParseDeclaratorInternal(D, DirectDeclParser);
Steve Naroffec33ed92008-08-27 16:04:49 +00005552 if (Kind == tok::star)
5553 // Remember that we parsed a pointer type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005554 D.AddTypeInfo(DeclaratorChunk::getPointer(
5555 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5556 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5557 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5558 std::move(DS.getAttributes()), SourceLocation());
Steve Naroffec33ed92008-08-27 16:04:49 +00005559 else
5560 // Remember that we parsed a Block type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005561 D.AddTypeInfo(
5562 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5563 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005564 } else {
5565 // Is a reference
John McCall084e83d2011-03-24 11:26:52 +00005566 DeclSpec DS(AttrFactory);
Bill Wendling93efb222007-06-02 23:28:54 +00005567
Sebastian Redl3b27be62009-03-23 00:00:23 +00005568 // Complain about rvalue references in C++03, but then go on and build
5569 // the declarator.
Richard Smith5d164bc2011-10-15 05:09:34 +00005570 if (Kind == tok::ampamp)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005571 Diag(Loc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00005572 diag::warn_cxx98_compat_rvalue_reference :
5573 diag::ext_rvalue_reference);
Sebastian Redl3b27be62009-03-23 00:00:23 +00005574
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005575 // GNU-style and C++11 attributes are allowed here, as is restrict.
5576 ParseTypeQualifierListOpt(DS);
5577 D.ExtendWithDeclSpec(DS);
5578
Bill Wendling93efb222007-06-02 23:28:54 +00005579 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5580 // cv-qualifiers are introduced through the use of a typedef or of a
5581 // template type argument, in which case the cv-qualifiers are ignored.
Bill Wendling93efb222007-06-02 23:28:54 +00005582 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5583 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5584 Diag(DS.getConstSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005585 diag::err_invalid_reference_qualifier_application) << "const";
Bill Wendling93efb222007-06-02 23:28:54 +00005586 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5587 Diag(DS.getVolatileSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005588 diag::err_invalid_reference_qualifier_application) << "volatile";
Richard Smith8e1ac332013-03-28 01:55:44 +00005589 // 'restrict' is permitted as an extension.
5590 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5591 Diag(DS.getAtomicSpecLoc(),
5592 diag::err_invalid_reference_qualifier_application) << "_Atomic";
Bill Wendling93efb222007-06-02 23:28:54 +00005593 }
Bill Wendling3708c182007-05-27 10:15:43 +00005594
5595 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005596 ParseDeclaratorInternal(D, DirectDeclParser);
Bill Wendling3708c182007-05-27 10:15:43 +00005597
Douglas Gregor66583c52008-11-03 15:51:28 +00005598 if (D.getNumTypeObjects() > 0) {
5599 // C++ [dcl.ref]p4: There shall be no references to references.
5600 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5601 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
Chris Lattnerebad6a22008-11-19 07:37:42 +00005602 if (const IdentifierInfo *II = D.getIdentifier())
5603 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5604 << II;
5605 else
5606 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5607 << "type name";
Douglas Gregor66583c52008-11-03 15:51:28 +00005608
Sebastian Redlbd150f42008-11-21 19:14:01 +00005609 // Once we've complained about the reference-to-reference, we
Douglas Gregor66583c52008-11-03 15:51:28 +00005610 // can go ahead and build the (technically ill-formed)
5611 // declarator: reference collapsing will take care of it.
5612 }
5613 }
5614
Richard Smith8e1ac332013-03-28 01:55:44 +00005615 // Remember that we parsed a reference type.
Chris Lattner788404f2008-02-21 01:32:26 +00005616 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
Sebastian Redled0f3b02009-03-15 22:02:01 +00005617 Kind == tok::amp),
Erich Keanec480f302018-07-12 21:09:05 +00005618 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005619 }
Chris Lattner6c7416c2006-08-07 00:19:33 +00005620}
5621
Richard Trieuf4b81d02014-06-24 23:14:24 +00005622// When correcting from misplaced brackets before the identifier, the location
5623// is saved inside the declarator so that other diagnostic messages can use
5624// them. This extracts and returns that location, or returns the provided
5625// location if a stored location does not exist.
5626static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5627 SourceLocation Loc) {
5628 if (D.getName().StartLocation.isInvalid() &&
5629 D.getName().EndLocation.isValid())
5630 return D.getName().EndLocation;
5631
5632 return Loc;
5633}
5634
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005635/// ParseDirectDeclarator
5636/// direct-declarator: [C99 6.7.5]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005637/// [C99] identifier
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005638/// '(' declarator ')'
5639/// [GNU] '(' attributes declarator ')'
Chris Lattnere8074e62006-08-06 18:30:15 +00005640/// [C90] direct-declarator '[' constant-expression[opt] ']'
5641/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5642/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5643/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5644/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005645/// [C++11] direct-declarator '[' constant-expression[opt] ']'
5646/// attribute-specifier-seq[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005647/// direct-declarator '(' parameter-type-list ')'
5648/// direct-declarator '(' identifier-list[opt] ')'
5649/// [GNU] direct-declarator '(' parameter-forward-declarations
5650/// parameter-type-list[opt] ')'
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00005651/// [C++] direct-declarator '(' parameter-declaration-clause ')'
5652/// cv-qualifier-seq[opt] exception-specification[opt]
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005653/// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5654/// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5655/// ref-qualifier[opt] exception-specification[opt]
Douglas Gregor61956c42008-10-31 09:07:45 +00005656/// [C++] declarator-id
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005657/// [C++11] declarator-id attribute-specifier-seq[opt]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005658///
5659/// declarator-id: [C++ 8]
Douglas Gregor27b4c162010-12-23 22:44:42 +00005660/// '...'[opt] id-expression
Douglas Gregor831c93f2008-11-05 20:51:48 +00005661/// '::'[opt] nested-name-specifier[opt] type-name
5662///
5663/// id-expression: [C++ 5.1]
5664/// unqualified-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005665/// qualified-id
Douglas Gregor831c93f2008-11-05 20:51:48 +00005666///
5667/// unqualified-id: [C++ 5.1]
Mike Stump11289f42009-09-09 15:08:12 +00005668/// identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005669/// operator-function-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005670/// conversion-function-id
Mike Stump11289f42009-09-09 15:08:12 +00005671/// '~' class-name
Douglas Gregor7f741122009-02-25 19:37:18 +00005672/// template-id
Argyrios Kyrtzidise4426352008-11-07 22:02:30 +00005673///
Richard Smithbdb84f32016-07-22 23:36:59 +00005674/// C++17 adds the following, which we also handle here:
5675///
5676/// simple-declaration:
5677/// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5678///
Richard Smith1453e312012-03-27 01:42:32 +00005679/// Note, any additional constructs added here may need corresponding changes
5680/// in isConstructorDeclarator.
Chris Lattneracd58a32006-08-06 17:24:14 +00005681void Parser::ParseDirectDeclarator(Declarator &D) {
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005682 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005683
David Blaikiebbafb8a2012-03-11 07:00:24 +00005684 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
Richard Smithbdb84f32016-07-22 23:36:59 +00005685 // This might be a C++17 structured binding.
5686 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5687 D.getCXXScopeSpec().isEmpty())
5688 return ParseDecompositionDeclarator(D);
5689
Serge Pavlov458ea762014-07-16 05:16:52 +00005690 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5691 // this context it is a bitfield. Also in range-based for statement colon
5692 // may delimit for-range-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00005693 ColonProtectionRAIIObject X(
5694 *this, D.getContext() == DeclaratorContext::MemberContext ||
5695 (D.getContext() == DeclaratorContext::ForContext &&
5696 getLangOpts().CPlusPlus11));
Serge Pavlov458ea762014-07-16 05:16:52 +00005697
Douglas Gregor7861a802009-11-03 01:35:08 +00005698 // ParseDeclaratorInternal might already have parsed the scope.
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005699 if (D.getCXXScopeSpec().isEmpty()) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005700 bool EnteringContext =
5701 D.getContext() == DeclaratorContext::FileContext ||
5702 D.getContext() == DeclaratorContext::MemberContext;
David Blaikieefdccaa2016-01-15 23:43:34 +00005703 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005704 EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005705 }
5706
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005707 if (D.getCXXScopeSpec().isValid()) {
Richard Smith64e033f2015-01-15 00:48:52 +00005708 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5709 D.getCXXScopeSpec()))
John McCall2b058ef2009-12-11 20:04:54 +00005710 // Change the declaration context for name lookup, until this function
5711 // is exited (and the declarator has been parsed).
5712 DeclScopeObj.EnterDeclaratorScope();
Alex Lorenze151f0102016-12-07 10:24:44 +00005713 else if (getObjCDeclContext()) {
5714 // Ensure that we don't interpret the next token as an identifier when
5715 // dealing with declarations in an Objective-C container.
5716 D.SetIdentifier(nullptr, Tok.getLocation());
5717 D.setInvalidType(true);
5718 ConsumeToken();
5719 goto PastIdentifier;
5720 }
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005721 }
5722
Douglas Gregor27b4c162010-12-23 22:44:42 +00005723 // C++0x [dcl.fct]p14:
Faisal Vali8435a692014-12-04 12:40:21 +00005724 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5725 // parameter-declaration-clause without a preceding comma. In this case,
5726 // the ellipsis is parsed as part of the abstract-declarator if the type
5727 // of the parameter either names a template parameter pack that has not
5728 // been expanded or contains auto; otherwise, it is parsed as part of the
5729 // parameter-declaration-clause.
Richard Smith0efa75c2012-03-29 01:16:42 +00005730 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00005731 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5732 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5733 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
Douglas Gregor27b4c162010-12-23 22:44:42 +00005734 NextToken().is(tok::r_paren) &&
Richard Smithb19337f2013-02-20 20:19:27 +00005735 !D.hasGroupingParens() &&
Faisal Vali8435a692014-12-04 12:40:21 +00005736 !Actions.containsUnexpandedParameterPacks(D) &&
Faisal Vali090da2d2018-01-01 18:23:28 +00005737 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005738 SourceLocation EllipsisLoc = ConsumeToken();
Richard Smith0b350b92014-10-28 16:55:02 +00005739 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005740 // The ellipsis was put in the wrong place. Recover, and explain to
5741 // the user what they should have done.
5742 ParseDeclarator(D);
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00005743 if (EllipsisLoc.isValid())
5744 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00005745 return;
5746 } else
5747 D.setEllipsisLoc(EllipsisLoc);
5748
5749 // The ellipsis can't be followed by a parenthesized declarator. We
5750 // check for that in ParseParenDeclarator, after we have disambiguated
5751 // the l_paren token.
5752 }
5753
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005754 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5755 tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00005756 // We found something that indicates the start of an unqualified-id.
5757 // Parse that unqualified-id.
John McCall84821e72010-04-13 06:39:49 +00005758 bool AllowConstructorName;
Richard Smith35845152017-02-07 01:37:30 +00005759 bool AllowDeductionGuide;
5760 if (D.getDeclSpec().hasTypeSpecifier()) {
John McCall84821e72010-04-13 06:39:49 +00005761 AllowConstructorName = false;
Richard Smith35845152017-02-07 01:37:30 +00005762 AllowDeductionGuide = false;
5763 } else if (D.getCXXScopeSpec().isSet()) {
John McCall84821e72010-04-13 06:39:49 +00005764 AllowConstructorName =
Faisal Vali421b2d12017-12-29 05:41:00 +00005765 (D.getContext() == DeclaratorContext::FileContext ||
5766 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005767 AllowDeductionGuide = false;
5768 } else {
Faisal Vali421b2d12017-12-29 05:41:00 +00005769 AllowConstructorName =
5770 (D.getContext() == DeclaratorContext::MemberContext);
Fangrui Song6907ce22018-07-30 19:24:48 +00005771 AllowDeductionGuide =
Faisal Vali421b2d12017-12-29 05:41:00 +00005772 (D.getContext() == DeclaratorContext::FileContext ||
5773 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005774 }
John McCall84821e72010-04-13 06:39:49 +00005775
Richard Smith64e033f2015-01-15 00:48:52 +00005776 bool HadScope = D.getCXXScopeSpec().isValid();
Chad Rosierc1183952012-06-26 22:30:43 +00005777 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5778 /*EnteringContext=*/true,
David Blaikieefdccaa2016-01-15 23:43:34 +00005779 /*AllowDestructorName=*/true, AllowConstructorName,
Richard Smithc08b6932018-04-27 02:00:13 +00005780 AllowDeductionGuide, nullptr, nullptr,
Richard Smith35845152017-02-07 01:37:30 +00005781 D.getName()) ||
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005782 // Once we're past the identifier, if the scope was bad, mark the
5783 // whole declarator bad.
5784 D.getCXXScopeSpec().isInvalid()) {
Craig Topper161e4db2014-05-21 06:02:52 +00005785 D.SetIdentifier(nullptr, Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005786 D.setInvalidType(true);
Douglas Gregor7861a802009-11-03 01:35:08 +00005787 } else {
Richard Smith64e033f2015-01-15 00:48:52 +00005788 // ParseUnqualifiedId might have parsed a scope specifier during error
5789 // recovery. If it did so, enter that scope.
5790 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5791 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5792 D.getCXXScopeSpec()))
5793 DeclScopeObj.EnterDeclaratorScope();
5794
Douglas Gregor7861a802009-11-03 01:35:08 +00005795 // Parsed the unqualified-id; update range information and move along.
5796 if (D.getSourceRange().getBegin().isInvalid())
5797 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5798 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005799 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005800 goto PastIdentifier;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005801 }
Richard Smithd63db6e2015-12-19 02:40:19 +00005802
5803 if (D.getCXXScopeSpec().isNotEmpty()) {
5804 // We have a scope specifier but no following unqualified-id.
5805 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5806 diag::err_expected_unqualified_id)
5807 << /*C++*/1;
5808 D.SetIdentifier(nullptr, Tok.getLocation());
5809 goto PastIdentifier;
5810 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005811 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005812 assert(!getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005813 "There's a C++-specific check for tok::identifier above");
5814 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5815 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Richard Trieu2664dc12014-05-05 22:06:50 +00005816 D.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005817 ConsumeToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00005818 goto PastIdentifier;
Richard Smith74639b12017-05-19 01:54:59 +00005819 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5820 // We're not allowed an identifier here, but we got one. Try to figure out
5821 // if the user was trying to attach a name to the type, or whether the name
5822 // is some unrelated trailing syntax.
5823 bool DiagnoseIdentifier = false;
5824 if (D.hasGroupingParens())
5825 // An identifier within parens is unlikely to be intended to be anything
5826 // other than a name being "declared".
5827 DiagnoseIdentifier = true;
Richard Smith77a9c602018-02-28 03:02:23 +00005828 else if (D.getContext() == DeclaratorContext::TemplateArgContext)
Richard Smith74639b12017-05-19 01:54:59 +00005829 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5830 DiagnoseIdentifier =
5831 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali421b2d12017-12-29 05:41:00 +00005832 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5833 D.getContext() == DeclaratorContext::AliasTemplateContext)
Richard Smith74639b12017-05-19 01:54:59 +00005834 // The most likely error is that the ';' was forgotten.
5835 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
Richard Smithe303e352018-02-02 22:24:54 +00005836 else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5837 D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
Richard Smith74639b12017-05-19 01:54:59 +00005838 !isCXX11VirtSpecifier(Tok))
5839 DiagnoseIdentifier = NextToken().isOneOf(
5840 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5841 if (DiagnoseIdentifier) {
Richard Smithf39720b2013-10-13 22:12:28 +00005842 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5843 << FixItHint::CreateRemoval(Tok.getLocation());
Craig Topper161e4db2014-05-21 06:02:52 +00005844 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithf39720b2013-10-13 22:12:28 +00005845 ConsumeToken();
5846 goto PastIdentifier;
5847 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005848 }
Richard Smith0efa75c2012-03-29 01:16:42 +00005849
Douglas Gregor7861a802009-11-03 01:35:08 +00005850 if (Tok.is(tok::l_paren)) {
Richard Smithe303e352018-02-02 22:24:54 +00005851 // If this might be an abstract-declarator followed by a direct-initializer,
5852 // check whether this is a valid declarator chunk. If it can't be, assume
5853 // that it's an initializer instead.
5854 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5855 RevertingTentativeParsingAction PA(*this);
5856 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5857 TPResult::False) {
5858 D.SetIdentifier(nullptr, Tok.getLocation());
5859 goto PastIdentifier;
5860 }
5861 }
5862
Chris Lattneracd58a32006-08-06 17:24:14 +00005863 // direct-declarator: '(' declarator ')'
Chris Lattnere37e2332006-08-15 04:50:22 +00005864 // direct-declarator: '(' attributes declarator ')'
Chris Lattneracd58a32006-08-06 17:24:14 +00005865 // Example: 'char (*X)' or 'int (*XX)(void)'
5866 ParseParenDeclarator(D);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005867
5868 // If the declarator was parenthesized, we entered the declarator
5869 // scope when parsing the parenthesized declarator, then exited
5870 // the scope already. Re-enter the scope, if we need to.
5871 if (D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005872 // If there was an error parsing parenthesized declarator, declarator
Richard Smith0efa75c2012-03-29 01:16:42 +00005873 // scope may have been entered before. Don't do it again.
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005874 if (!D.isInvalidType() &&
Nico Weber6b05f382015-02-18 04:53:03 +00005875 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5876 D.getCXXScopeSpec()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005877 // Change the declaration context for name lookup, until this function
5878 // is exited (and the declarator has been parsed).
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005879 DeclScopeObj.EnterDeclaratorScope();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005880 }
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005881 } else if (D.mayOmitIdentifier()) {
Chris Lattneracd58a32006-08-06 17:24:14 +00005882 // This could be something simple like "int" (in which case the declarator
5883 // portion is empty), if an abstract-declarator is allowed.
Craig Topper161e4db2014-05-21 06:02:52 +00005884 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithb19337f2013-02-20 20:19:27 +00005885
5886 // The grammar for abstract-pack-declarator does not allow grouping parens.
5887 // FIXME: Revisit this once core issue 1488 is resolved.
5888 if (D.hasEllipsis() && D.hasGroupingParens())
5889 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5890 diag::ext_abstract_pack_declarator_parens);
Chris Lattneracd58a32006-08-06 17:24:14 +00005891 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00005892 if (Tok.getKind() == tok::annot_pragma_parser_crash)
David Blaikie5bd4c2a2012-08-21 18:56:49 +00005893 LLVM_BUILTIN_TRAP;
Richard Trieuf4b81d02014-06-24 23:14:24 +00005894 if (Tok.is(tok::l_square))
5895 return ParseMisplacedBracketDeclarator(D);
Faisal Vali421b2d12017-12-29 05:41:00 +00005896 if (D.getContext() == DeclaratorContext::MemberContext) {
Alex Lorenzf1278212017-04-11 15:01:53 +00005897 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5898 // treating these keyword as valid member names.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005899 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
Alex Lorenzf1278212017-04-11 15:01:53 +00005900 Tok.getIdentifierInfo() &&
5901 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5902 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5903 diag::err_expected_member_name_or_semi_objcxx_keyword)
5904 << Tok.getIdentifierInfo()
5905 << (D.getDeclSpec().isEmpty() ? SourceRange()
5906 : D.getDeclSpec().getSourceRange());
5907 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5908 D.SetRangeEnd(Tok.getLocation());
5909 ConsumeToken();
5910 goto PastIdentifier;
5911 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005912 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5913 diag::err_expected_member_name_or_semi)
Richard Trieua1342402014-05-02 23:40:32 +00005914 << (D.getDeclSpec().isEmpty() ? SourceRange()
5915 : D.getDeclSpec().getSourceRange());
Richard Trieuf4b81d02014-06-24 23:14:24 +00005916 } else if (getLangOpts().CPlusPlus) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005917 if (Tok.isOneOf(tok::period, tok::arrow))
Richard Trieu9c672672013-01-26 02:31:38 +00005918 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
Richard Trieu2f586962013-09-05 02:31:33 +00005919 else {
5920 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5921 if (Tok.isAtStartOfLine() && Loc.isValid())
5922 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5923 << getLangOpts().CPlusPlus;
5924 else
Richard Trieuf4b81d02014-06-24 23:14:24 +00005925 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5926 diag::err_expected_unqualified_id)
Richard Trieu2f586962013-09-05 02:31:33 +00005927 << getLangOpts().CPlusPlus;
5928 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005929 } else {
5930 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5931 diag::err_expected_either)
5932 << tok::identifier << tok::l_paren;
5933 }
Craig Topper161e4db2014-05-21 06:02:52 +00005934 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattner8c5dd732008-11-11 06:13:16 +00005935 D.setInvalidType(true);
Chris Lattneracd58a32006-08-06 17:24:14 +00005936 }
Mike Stump11289f42009-09-09 15:08:12 +00005937
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005938 PastIdentifier:
Chris Lattneracd58a32006-08-06 17:24:14 +00005939 assert(D.isPastIdentifier() &&
5940 "Haven't past the location of the identifier yet?");
Mike Stump11289f42009-09-09 15:08:12 +00005941
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005942 // Don't parse attributes unless we have parsed an unparenthesized name.
5943 if (D.hasName() && !D.getNumTypeObjects())
Richard Smith89645bc2013-01-02 12:01:23 +00005944 MaybeParseCXX11Attributes(D);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005945
Chris Lattneracd58a32006-08-06 17:24:14 +00005946 while (1) {
Chris Lattner76c72282007-10-09 17:33:22 +00005947 if (Tok.is(tok::l_paren)) {
David Blaikie15a430a2011-12-04 05:04:18 +00005948 // Enter function-declaration scope, limiting any declarators to the
5949 // function prototype scope, including parameter declarators.
5950 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00005951 Scope::FunctionPrototypeScope|Scope::DeclScope|
5952 (D.isFunctionDeclaratorAFunctionDeclaration()
5953 ? Scope::FunctionDeclarationScope : 0));
5954
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005955 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5956 // In such a case, check if we actually have a function declarator; if it
5957 // is not, the declarator has been fully parsed.
Richard Smith943c4402012-07-30 21:30:52 +00005958 bool IsAmbiguous = false;
Richard Smith4f605af2012-08-18 00:55:03 +00005959 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5960 // The name of the declarator, if any, is tentatively declared within
5961 // a possible direct initializer.
5962 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5963 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5964 TentativelyDeclaredIdentifiers.pop_back();
5965 if (!IsFunctionDecl)
5966 break;
5967 }
John McCall084e83d2011-03-24 11:26:52 +00005968 ParsedAttributes attrs(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005969 BalancedDelimiterTracker T(*this, tok::l_paren);
5970 T.consumeOpen();
Richard Smith943c4402012-07-30 21:30:52 +00005971 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
David Blaikie15a430a2011-12-04 05:04:18 +00005972 PrototypeScope.Exit();
Chris Lattner76c72282007-10-09 17:33:22 +00005973 } else if (Tok.is(tok::l_square)) {
Chris Lattnere8074e62006-08-06 18:30:15 +00005974 ParseBracketDeclarator(D);
Chris Lattneracd58a32006-08-06 17:24:14 +00005975 } else {
5976 break;
5977 }
5978 }
Chad Rosierc1183952012-06-26 22:30:43 +00005979}
Chris Lattneracd58a32006-08-06 17:24:14 +00005980
Richard Smithbdb84f32016-07-22 23:36:59 +00005981void Parser::ParseDecompositionDeclarator(Declarator &D) {
5982 assert(Tok.is(tok::l_square));
5983
5984 // If this doesn't look like a structured binding, maybe it's a misplaced
5985 // array declarator.
5986 // FIXME: Consume the l_square first so we don't need extra lookahead for
5987 // this.
5988 if (!(NextToken().is(tok::identifier) &&
5989 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5990 !(NextToken().is(tok::r_square) &&
5991 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5992 return ParseMisplacedBracketDeclarator(D);
5993
5994 BalancedDelimiterTracker T(*this, tok::l_square);
5995 T.consumeOpen();
5996
5997 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5998 while (Tok.isNot(tok::r_square)) {
5999 if (!Bindings.empty()) {
6000 if (Tok.is(tok::comma))
6001 ConsumeToken();
6002 else {
6003 if (Tok.is(tok::identifier)) {
6004 SourceLocation EndLoc = getEndOfPreviousToken();
6005 Diag(EndLoc, diag::err_expected)
6006 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
6007 } else {
6008 Diag(Tok, diag::err_expected_comma_or_rsquare);
6009 }
6010
6011 SkipUntil(tok::r_square, tok::comma, tok::identifier,
6012 StopAtSemi | StopBeforeMatch);
6013 if (Tok.is(tok::comma))
6014 ConsumeToken();
6015 else if (Tok.isNot(tok::identifier))
6016 break;
6017 }
6018 }
6019
6020 if (Tok.isNot(tok::identifier)) {
6021 Diag(Tok, diag::err_expected) << tok::identifier;
6022 break;
6023 }
6024
6025 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
6026 ConsumeToken();
6027 }
6028
6029 if (Tok.isNot(tok::r_square))
6030 // We've already diagnosed a problem here.
6031 T.skipToEnd();
6032 else {
6033 // C++17 does not allow the identifier-list in a structured binding
6034 // to be empty.
6035 if (Bindings.empty())
6036 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
6037
6038 T.consumeClose();
6039 }
6040
6041 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
6042 T.getCloseLocation());
6043}
6044
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006045/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
6046/// only called before the identifier, so these are most likely just grouping
Mike Stump11289f42009-09-09 15:08:12 +00006047/// parens for precedence. If we find that these are actually function
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006048/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
6049///
6050/// direct-declarator:
6051/// '(' declarator ')'
6052/// [GNU] '(' attributes declarator ')'
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006053/// direct-declarator '(' parameter-type-list ')'
6054/// direct-declarator '(' identifier-list[opt] ')'
6055/// [GNU] direct-declarator '(' parameter-forward-declarations
6056/// parameter-type-list[opt] ')'
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006057///
6058void Parser::ParseParenDeclarator(Declarator &D) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006059 BalancedDelimiterTracker T(*this, tok::l_paren);
6060 T.consumeOpen();
6061
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006062 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
Mike Stump11289f42009-09-09 15:08:12 +00006063
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006064 // Eat any attributes before we look at whether this is a grouping or function
6065 // declarator paren. If this is a grouping paren, the attribute applies to
6066 // the type being built up, for example:
6067 // int (__attribute__(()) *x)(long y)
6068 // If this ends up not being a grouping paren, the attribute applies to the
6069 // first argument, for example:
6070 // int (__attribute__(()) int x)
6071 // In either case, we need to eat any attributes to be able to determine what
6072 // sort of paren this is.
6073 //
John McCall084e83d2011-03-24 11:26:52 +00006074 ParsedAttributes attrs(AttrFactory);
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006075 bool RequiresArg = false;
6076 if (Tok.is(tok::kw___attribute)) {
John McCall53fa7142010-12-24 02:08:15 +00006077 ParseGNUAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006078
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006079 // We require that the argument list (if this is a non-grouping paren) be
6080 // present even if the attribute list was empty.
6081 RequiresArg = true;
6082 }
Chad Rosiereea9ca72012-12-21 21:22:20 +00006083
Steve Naroff44ac7772008-12-25 14:16:32 +00006084 // Eat any Microsoft extensions.
Chad Rosiereea9ca72012-12-21 21:22:20 +00006085 ParseMicrosoftTypeAttributes(attrs);
6086
Dawn Perchik335e16b2010-09-03 01:29:35 +00006087 // Eat any Borland extensions.
Ted Kremenek5eec2b02010-11-10 05:59:39 +00006088 if (Tok.is(tok::kw___pascal))
John McCall53fa7142010-12-24 02:08:15 +00006089 ParseBorlandTypeAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006090
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006091 // If we haven't past the identifier yet (or where the identifier would be
6092 // stored, if this is an abstract declarator), then this is probably just
6093 // grouping parens. However, if this could be an abstract-declarator, then
6094 // this could also be the start of function arguments (consider 'void()').
6095 bool isGrouping;
Mike Stump11289f42009-09-09 15:08:12 +00006096
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006097 if (!D.mayOmitIdentifier()) {
6098 // If this can't be an abstract-declarator, this *must* be a grouping
6099 // paren, because we haven't seen the identifier yet.
6100 isGrouping = true;
6101 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
Richard Smith43f340f2012-03-27 23:05:05 +00006102 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6103 NextToken().is(tok::r_paren)) || // C++ int(...)
Richard Smith2620cd92012-04-11 04:01:28 +00006104 isDeclarationSpecifier() || // 'int(int)' is a function.
6105 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006106 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6107 // considered to be a type, not a K&R identifier-list.
6108 isGrouping = false;
6109 } else {
6110 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6111 isGrouping = true;
6112 }
Mike Stump11289f42009-09-09 15:08:12 +00006113
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006114 // If this is a grouping paren, handle:
6115 // direct-declarator: '(' declarator ')'
6116 // direct-declarator: '(' attributes declarator ')'
6117 if (isGrouping) {
Richard Smith0efa75c2012-03-29 01:16:42 +00006118 SourceLocation EllipsisLoc = D.getEllipsisLoc();
6119 D.setEllipsisLoc(SourceLocation());
6120
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006121 bool hadGroupingParens = D.hasGroupingParens();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006122 D.setGroupingParens(true);
Sebastian Redlbd150f42008-11-21 19:14:01 +00006123 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006124 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006125 T.consumeClose();
Erich Keanec480f302018-07-12 21:09:05 +00006126 D.AddTypeInfo(
6127 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6128 std::move(attrs), T.getCloseLocation());
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006129
6130 D.setGroupingParens(hadGroupingParens);
Richard Smith0efa75c2012-03-29 01:16:42 +00006131
6132 // An ellipsis cannot be placed outside parentheses.
6133 if (EllipsisLoc.isValid())
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00006134 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00006135
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006136 return;
6137 }
Mike Stump11289f42009-09-09 15:08:12 +00006138
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006139 // Okay, if this wasn't a grouping paren, it must be the start of a function
6140 // argument list. Recognize that this declarator will never have an
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006141 // identifier (and remember where it would have been), then call into
6142 // ParseFunctionDeclarator to handle of argument list.
Craig Topper161e4db2014-05-21 06:02:52 +00006143 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006144
David Blaikie15a430a2011-12-04 05:04:18 +00006145 // Enter function-declaration scope, limiting any declarators to the
6146 // function prototype scope, including parameter declarators.
6147 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00006148 Scope::FunctionPrototypeScope | Scope::DeclScope |
6149 (D.isFunctionDeclaratorAFunctionDeclaration()
6150 ? Scope::FunctionDeclarationScope : 0));
Richard Smith943c4402012-07-30 21:30:52 +00006151 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
David Blaikie15a430a2011-12-04 05:04:18 +00006152 PrototypeScope.Exit();
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006153}
6154
6155/// ParseFunctionDeclarator - We are after the identifier and have parsed the
6156/// declarator D up to a paren, which indicates that we are parsing function
6157/// arguments.
Chris Lattneracd58a32006-08-06 17:24:14 +00006158///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006159/// If FirstArgAttrs is non-null, then the caller parsed those arguments
6160/// immediately after the open paren - they should be considered to be the
6161/// first argument of a parameter.
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006162///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006163/// If RequiresArg is true, then the first argument of the function is required
6164/// to be present and required to not be an identifier list.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006165///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006166/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6167/// (C++11) ref-qualifier[opt], exception-specification[opt],
6168/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
6169///
6170/// [C++11] exception-specification:
Douglas Gregor9e66af42011-07-05 16:44:18 +00006171/// dynamic-exception-specification
6172/// noexcept-specification
6173///
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006174void Parser::ParseFunctionDeclarator(Declarator &D,
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006175 ParsedAttributes &FirstArgAttrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006176 BalancedDelimiterTracker &Tracker,
Richard Smith943c4402012-07-30 21:30:52 +00006177 bool IsAmbiguous,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006178 bool RequiresArg) {
Chad Rosierc1183952012-06-26 22:30:43 +00006179 assert(getCurScope()->isFunctionPrototypeScope() &&
David Blaikie15a430a2011-12-04 05:04:18 +00006180 "Should call from a Function scope");
Douglas Gregor9e66af42011-07-05 16:44:18 +00006181 // lparen is already consumed!
6182 assert(D.isPastIdentifier() && "Should not call before identifier!");
6183
6184 // This should be true when the function has typed arguments.
6185 // Otherwise, it is treated as a K&R-style function.
6186 bool HasProto = false;
6187 // Build up an array of information about the parsed arguments.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006188 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006189 // Remember where we see an ellipsis, if any.
6190 SourceLocation EllipsisLoc;
6191
6192 DeclSpec DS(AttrFactory);
6193 bool RefQualifierIsLValueRef = true;
6194 SourceLocation RefQualifierLoc;
6195 ExceptionSpecificationType ESpecType = EST_None;
6196 SourceRange ESpecRange;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006197 SmallVector<ParsedType, 2> DynamicExceptions;
6198 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006199 ExprResult NoexceptExpr;
Hans Wennborgdcfba332015-10-06 23:40:43 +00006200 CachedTokens *ExceptionSpecTokens = nullptr;
Aaron Ballman606093a2017-10-15 15:01:42 +00006201 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith700537c2012-06-12 01:51:59 +00006202 TypeResult TrailingReturnType;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006203
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006204 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6205 EndLoc is the end location for the function declarator.
6206 They differ for trailing return types. */
6207 SourceLocation StartLoc, LocalEndLoc, EndLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006208 SourceLocation LParenLoc, RParenLoc;
6209 LParenLoc = Tracker.getOpenLocation();
6210 StartLoc = LParenLoc;
6211
Douglas Gregor9e66af42011-07-05 16:44:18 +00006212 if (isFunctionDeclaratorIdentifierList()) {
6213 if (RequiresArg)
6214 Diag(Tok, diag::err_argument_required_after_attribute);
6215
6216 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6217
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006218 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006219 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006220 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006221 EndLoc = RParenLoc;
Aaron Ballman606093a2017-10-15 15:01:42 +00006222
Fangrui Song6907ce22018-07-30 19:24:48 +00006223 // If there are attributes following the identifier list, parse them and
Aaron Ballman606093a2017-10-15 15:01:42 +00006224 // prohibit them.
6225 MaybeParseCXX11Attributes(FnAttrs);
6226 ProhibitAttributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006227 } else {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006228 if (Tok.isNot(tok::r_paren))
Fangrui Song6907ce22018-07-30 19:24:48 +00006229 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
Faisal Vali2b391ab2013-09-26 19:54:12 +00006230 EllipsisLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006231 else if (RequiresArg)
6232 Diag(Tok, diag::err_argument_required_after_attribute);
6233
Alexey Bader1f277942017-10-11 11:16:31 +00006234 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6235 || getLangOpts().OpenCL;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006236
6237 // If we have the closing ')', eat it.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006238 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006239 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006240 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006241 EndLoc = RParenLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006242
David Blaikiebbafb8a2012-03-11 07:00:24 +00006243 if (getLangOpts().CPlusPlus) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006244 // FIXME: Accept these components in any order, and produce fixits to
6245 // correct the order if the user gets it wrong. Ideally we should deal
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00006246 // with the pure-specifier in the same way.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006247
6248 // Parse cv-qualifier-seq[opt].
Aaron Ballman08b06592014-07-22 12:44:22 +00006249 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
Alex Lorenz8f4d3992017-02-13 23:19:40 +00006250 /*AtomicAllowed*/ false,
6251 /*IdentifierRequired=*/false,
6252 llvm::function_ref<void()>([&]() {
6253 Actions.CodeCompleteFunctionQualifiers(DS, D);
6254 }));
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006255 if (!DS.getSourceRange().getEnd().isInvalid()) {
6256 EndLoc = DS.getSourceRange().getEnd();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006257 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006258
6259 // Parse ref-qualifier[opt].
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006260 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
Douglas Gregor9e66af42011-07-05 16:44:18 +00006261 EndLoc = RefQualifierLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006262
Douglas Gregor3024f072012-04-16 07:05:22 +00006263 // C++11 [expr.prim.general]p3:
Chad Rosierc1183952012-06-26 22:30:43 +00006264 // If a declaration declares a member function or member function
6265 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00006266 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Chad Rosierc1183952012-06-26 22:30:43 +00006267 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00006268 // declarator.
Richard Smithad1bbb92013-03-15 00:41:52 +00006269 // FIXME: currently, "static" case isn't handled correctly.
Chad Rosierc1183952012-06-26 22:30:43 +00006270 bool IsCXX11MemberFunction =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006271 getLangOpts().CPlusPlus11 &&
Richard Smith990a6922014-01-17 21:01:18 +00006272 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
Faisal Vali421b2d12017-12-29 05:41:00 +00006273 (D.getContext() == DeclaratorContext::MemberContext
Richard Smithad1bbb92013-03-15 00:41:52 +00006274 ? !D.getDeclSpec().isFriendSpecified()
Faisal Vali421b2d12017-12-29 05:41:00 +00006275 : D.getContext() == DeclaratorContext::FileContext &&
Richard Smithad1bbb92013-03-15 00:41:52 +00006276 D.getCXXScopeSpec().isValid() &&
6277 Actions.CurContext->isRecord());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006278
6279 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
Gauthier Harnisch796ed032019-06-14 08:56:20 +00006280 if (D.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14)
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006281 Q.addConst();
Anastasia Stulova5cffa452019-01-21 16:01:38 +00006282 // FIXME: Collect C++ address spaces.
6283 // If there are multiple different address spaces, the source is invalid.
6284 // Carry on using the first addr space for the qualifiers of 'this'.
6285 // The diagnostic will be given later while creating the function
6286 // prototype for the method.
6287 if (getLangOpts().OpenCLCPlusPlus) {
6288 for (ParsedAttr &attr : DS.getAttributes()) {
6289 LangAS ASIdx = attr.asOpenCLLangAS();
6290 if (ASIdx != LangAS::Default) {
6291 Q.addAddressSpace(ASIdx);
6292 break;
6293 }
6294 }
6295 }
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006296
6297 Sema::CXXThisScopeRAII ThisScope(
6298 Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6299 IsCXX11MemberFunction);
Richard Smith2331bbf2012-05-02 22:22:32 +00006300
Douglas Gregor9e66af42011-07-05 16:44:18 +00006301 // Parse exception-specification[opt].
Richard Smith0b3a4622014-11-13 20:01:57 +00006302 bool Delayed = D.isFirstDeclarationOfMember() &&
Richard Smith3ef3e892014-11-20 22:32:11 +00006303 D.isFunctionDeclaratorAFunctionDeclaration();
6304 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6305 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6306 GetLookAheadToken(1).is(tok::l_paren) &&
6307 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6308 GetLookAheadToken(3).is(tok::l_paren) &&
6309 GetLookAheadToken(4).is(tok::identifier) &&
6310 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6311 // HACK: We've got an exception-specification
6312 // noexcept(noexcept(swap(...)))
6313 // or
6314 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6315 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6316 // for 'swap' will only find the function we're currently declaring,
6317 // whereas it expects to find a non-member swap through ADL. Turn off
6318 // delayed parsing to give it a chance to find what it expects.
6319 Delayed = false;
6320 }
Richard Smith0b3a4622014-11-13 20:01:57 +00006321 ESpecType = tryParseExceptionSpecification(Delayed,
6322 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00006323 DynamicExceptions,
6324 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00006325 NoexceptExpr,
6326 ExceptionSpecTokens);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006327 if (ESpecType != EST_None)
6328 EndLoc = ESpecRange.getEnd();
6329
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006330 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6331 // after the exception-specification.
Richard Smith89645bc2013-01-02 12:01:23 +00006332 MaybeParseCXX11Attributes(FnAttrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006333
Douglas Gregor9e66af42011-07-05 16:44:18 +00006334 // Parse trailing-return-type[opt].
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006335 LocalEndLoc = EndLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006336 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00006337 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
Faisal Vali090da2d2018-01-01 18:23:28 +00006338 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006339 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006340 LocalEndLoc = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00006341 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00006342 TrailingReturnType =
6343 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006344 EndLoc = Range.getEnd();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006345 }
Aaron Ballman606093a2017-10-15 15:01:42 +00006346 } else if (standardAttributesAllowed()) {
6347 MaybeParseCXX11Attributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006348 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006349 }
6350
Reid Kleckner078aea92016-12-09 17:14:05 +00006351 // Collect non-parameter declarations from the prototype if this is a function
6352 // declaration. They will be moved into the scope of the function. Only do
6353 // this in C and not C++, where the decls will continue to live in the
6354 // surrounding context.
6355 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6356 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6357 !getLangOpts().CPlusPlus) {
6358 for (Decl *D : getCurScope()->decls()) {
6359 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6360 if (!ND || isa<ParmVarDecl>(ND))
6361 continue;
6362 DeclsInPrototype.push_back(ND);
6363 }
6364 }
6365
Douglas Gregor9e66af42011-07-05 16:44:18 +00006366 // Remember that we parsed a function type, and remember the attributes.
Erich Keanec480f302018-07-12 21:09:05 +00006367 D.AddTypeInfo(DeclaratorChunk::getFunction(
6368 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6369 ParamInfo.size(), EllipsisLoc, RParenLoc,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00006370 RefQualifierIsLValueRef, RefQualifierLoc,
6371 /*MutableLoc=*/SourceLocation(),
6372 ESpecType, ESpecRange, DynamicExceptions.data(),
6373 DynamicExceptionRanges.data(), DynamicExceptions.size(),
Erich Keanec480f302018-07-12 21:09:05 +00006374 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6375 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00006376 LocalEndLoc, D, TrailingReturnType, &DS),
Erich Keanec480f302018-07-12 21:09:05 +00006377 std::move(FnAttrs), EndLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006378}
6379
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006380/// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6381/// true if a ref-qualifier is found.
6382bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6383 SourceLocation &RefQualifierLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00006384 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006385 Diag(Tok, getLangOpts().CPlusPlus11 ?
6386 diag::warn_cxx98_compat_ref_qualifier :
6387 diag::ext_ref_qualifier);
6388
6389 RefQualifierIsLValueRef = Tok.is(tok::amp);
6390 RefQualifierLoc = ConsumeToken();
6391 return true;
6392 }
6393 return false;
6394}
6395
Douglas Gregor9e66af42011-07-05 16:44:18 +00006396/// isFunctionDeclaratorIdentifierList - This parameter list may have an
6397/// identifier list form for a K&R-style function: void foo(a,b,c)
6398///
6399/// Note that identifier-lists are only allowed for normal declarators, not for
6400/// abstract-declarators.
6401bool Parser::isFunctionDeclaratorIdentifierList() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006402 return !getLangOpts().CPlusPlus
Douglas Gregor9e66af42011-07-05 16:44:18 +00006403 && Tok.is(tok::identifier)
6404 && !TryAltiVecVectorToken()
6405 // K&R identifier lists can't have typedefs as identifiers, per C99
6406 // 6.7.5.3p11.
6407 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6408 // Identifier lists follow a really simple grammar: the identifiers can
6409 // be followed *only* by a ", identifier" or ")". However, K&R
6410 // identifier lists are really rare in the brave new modern world, and
6411 // it is very common for someone to typo a type in a non-K&R style
6412 // list. If we are presented with something like: "void foo(intptr x,
6413 // float y)", we don't want to start parsing the function declarator as
6414 // though it is a K&R style declarator just because intptr is an
6415 // invalid type.
6416 //
6417 // To handle this, we check to see if the token after the first
6418 // identifier is a "," or ")". Only then do we parse it as an
6419 // identifier list.
Bruno Cardoso Lopes218c8742016-09-13 20:04:35 +00006420 && (!Tok.is(tok::eof) &&
6421 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006422}
6423
6424/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6425/// we found a K&R-style identifier list instead of a typed parameter list.
6426///
6427/// After returning, ParamInfo will hold the parsed parameters.
6428///
6429/// identifier-list: [C99 6.7.5]
6430/// identifier
6431/// identifier-list ',' identifier
6432///
6433void Parser::ParseFunctionDeclaratorIdentifierList(
6434 Declarator &D,
Craig Topper5603df42013-07-05 19:34:19 +00006435 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006436 // If there was no identifier specified for the declarator, either we are in
6437 // an abstract-declarator, or we are in a parameter declarator which was found
6438 // to be abstract. In abstract-declarators, identifier lists are not valid:
6439 // diagnose this.
6440 if (!D.getIdentifier())
6441 Diag(Tok, diag::ext_ident_list_in_param);
6442
6443 // Maintain an efficient lookup of params we have seen so far.
6444 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6445
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006446 do {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006447 // If this isn't an identifier, report the error and skip until ')'.
6448 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00006449 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00006450 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006451 // Forget we parsed anything.
6452 ParamInfo.clear();
6453 return;
6454 }
6455
6456 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6457
6458 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6459 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6460 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6461
6462 // Verify that the argument identifier has not already been mentioned.
David Blaikie82e95a32014-11-19 07:49:47 +00006463 if (!ParamsSoFar.insert(ParmII).second) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006464 Diag(Tok, diag::err_param_redefinition) << ParmII;
6465 } else {
6466 // Remember this identifier in ParamInfo.
6467 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6468 Tok.getLocation(),
Craig Topper161e4db2014-05-21 06:02:52 +00006469 nullptr));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006470 }
6471
6472 // Eat the identifier.
6473 ConsumeToken();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006474 // The list continues if we see a comma.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006475 } while (TryConsumeToken(tok::comma));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006476}
6477
6478/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6479/// after the opening parenthesis. This function will not parse a K&R-style
6480/// identifier list.
6481///
Richard Smith2620cd92012-04-11 04:01:28 +00006482/// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6483/// caller parsed those arguments immediately after the open paren - they should
6484/// be considered to be part of the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006485///
6486/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6487/// be the location of the ellipsis, if any was parsed.
6488///
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006489/// parameter-type-list: [C99 6.7.5]
6490/// parameter-list
6491/// parameter-list ',' '...'
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006492/// [C++] parameter-list '...'
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006493///
6494/// parameter-list: [C99 6.7.5]
6495/// parameter-declaration
6496/// parameter-list ',' parameter-declaration
6497///
6498/// parameter-declaration: [C99 6.7.5]
6499/// declaration-specifiers declarator
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006500/// [C++] declaration-specifiers declarator '=' assignment-expression
Sebastian Redldb63af22012-03-14 15:54:00 +00006501/// [C++11] initializer-clause
Chris Lattnere37e2332006-08-15 04:50:22 +00006502/// [GNU] declaration-specifiers declarator attributes
Sebastian Redlf769df52009-03-24 22:27:57 +00006503/// declaration-specifiers abstract-declarator[opt]
6504/// [C++] declaration-specifiers abstract-declarator[opt]
Chris Lattner58258242008-04-10 02:22:51 +00006505/// '=' assignment-expression
Chris Lattnere37e2332006-08-15 04:50:22 +00006506/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
Richard Smith2620cd92012-04-11 04:01:28 +00006507/// [C++11] attribute-specifier-seq parameter-declaration
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006508///
Douglas Gregor9e66af42011-07-05 16:44:18 +00006509void Parser::ParseParameterDeclarationClause(
6510 Declarator &D,
Richard Smith2620cd92012-04-11 04:01:28 +00006511 ParsedAttributes &FirstArgAttrs,
Craig Topper5603df42013-07-05 19:34:19 +00006512 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006513 SourceLocation &EllipsisLoc) {
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006514 do {
6515 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6516 // before deciding this was a parameter-declaration-clause.
6517 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Chris Lattner371ed4e2008-04-06 06:57:35 +00006518 break;
Mike Stump11289f42009-09-09 15:08:12 +00006519
Chris Lattner371ed4e2008-04-06 06:57:35 +00006520 // Parse the declaration-specifiers.
John McCall28a6aea2009-11-04 02:18:39 +00006521 // Just use the ParsingDeclaration "scope" of the declarator.
John McCall084e83d2011-03-24 11:26:52 +00006522 DeclSpec DS(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006523
Richard Smith2620cd92012-04-11 04:01:28 +00006524 // Parse any C++11 attributes.
Richard Smith89645bc2013-01-02 12:01:23 +00006525 MaybeParseCXX11Attributes(DS.getAttributes());
Richard Smith2620cd92012-04-11 04:01:28 +00006526
John McCall53fa7142010-12-24 02:08:15 +00006527 // Skip any Microsoft attributes before a param.
Chad Rosierf8a2e702012-12-20 20:37:53 +00006528 MaybeParseMicrosoftAttributes(DS.getAttributes());
John McCall53fa7142010-12-24 02:08:15 +00006529
6530 SourceLocation DSStart = Tok.getLocation();
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006531
6532 // If the caller parsed attributes for the first argument, add them now.
John McCall53fa7142010-12-24 02:08:15 +00006533 // Take them so that we only apply the attributes to the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006534 // FIXME: If we can leave the attributes in the token stream somehow, we can
Richard Smith2620cd92012-04-11 04:01:28 +00006535 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6536 // too much hassle.
6537 DS.takeAttributesFrom(FirstArgAttrs);
John McCall53fa7142010-12-24 02:08:15 +00006538
Faisal Valia534f072018-04-26 00:42:40 +00006539 ParseDeclarationSpecifiers(DS);
Mike Stump11289f42009-09-09 15:08:12 +00006540
Faisal Vali2b391ab2013-09-26 19:54:12 +00006541
Fangrui Song6907ce22018-07-30 19:24:48 +00006542 // Parse the declarator. This is "PrototypeContext" or
6543 // "LambdaExprParameterContext", because we must accept either
Faisal Vali2b391ab2013-09-26 19:54:12 +00006544 // 'declarator' or 'abstract-declarator' here.
Faisal Vali421b2d12017-12-29 05:41:00 +00006545 Declarator ParmDeclarator(
6546 DS, D.getContext() == DeclaratorContext::LambdaExprContext
6547 ? DeclaratorContext::LambdaExprParameterContext
6548 : DeclaratorContext::PrototypeContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00006549 ParseDeclarator(ParmDeclarator);
Chris Lattner371ed4e2008-04-06 06:57:35 +00006550
6551 // Parse GNU attributes, if present.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006552 MaybeParseGNUAttributes(ParmDeclarator);
Mike Stump11289f42009-09-09 15:08:12 +00006553
Chris Lattner371ed4e2008-04-06 06:57:35 +00006554 // Remember this parsed parameter in ParamInfo.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006555 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
Mike Stump11289f42009-09-09 15:08:12 +00006556
Douglas Gregor4d87df52008-12-16 21:30:33 +00006557 // DefArgToks is used when the parsing of default arguments needs
6558 // to be delayed.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006559 std::unique_ptr<CachedTokens> DefArgToks;
Douglas Gregor4d87df52008-12-16 21:30:33 +00006560
Chris Lattner371ed4e2008-04-06 06:57:35 +00006561 // If no parameter was specified, verify that *something* was specified,
6562 // otherwise we have a missing type and identifier.
Craig Topper161e4db2014-05-21 06:02:52 +00006563 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
Faisal Vali2b391ab2013-09-26 19:54:12 +00006564 ParmDeclarator.getNumTypeObjects() == 0) {
Chris Lattner371ed4e2008-04-06 06:57:35 +00006565 // Completely missing, emit error.
6566 Diag(DSStart, diag::err_missing_param);
6567 } else {
6568 // Otherwise, we have something. Add it and let semantic analysis try
6569 // to grok it and add the result to the ParamInfo we are building.
Mike Stump11289f42009-09-09 15:08:12 +00006570
Richard Smith36ee9fb2014-08-11 23:30:23 +00006571 // Last chance to recover from a misplaced ellipsis in an attempted
6572 // parameter pack declaration.
6573 if (Tok.is(tok::ellipsis) &&
6574 (NextToken().isNot(tok::r_paren) ||
6575 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6576 !Actions.isUnexpandedParameterPackPermitted())) &&
6577 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6578 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6579
Chris Lattner371ed4e2008-04-06 06:57:35 +00006580 // Inform the actions module about the parameter declarator, so it gets
6581 // added to the current scope.
Richard Smith95e1fb02014-08-27 03:23:12 +00006582 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006583 // Parse the default argument, if any. We parse the default
6584 // arguments in all dialects; the semantic analysis in
6585 // ActOnParamDefaultArgument will reject the default argument in
6586 // C.
6587 if (Tok.is(tok::equal)) {
Douglas Gregor58354032008-12-24 00:01:03 +00006588 SourceLocation EqualLoc = Tok.getLocation();
6589
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006590 // Parse the default argument
Faisal Vali421b2d12017-12-29 05:41:00 +00006591 if (D.getContext() == DeclaratorContext::MemberContext) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006592 // If we're inside a class definition, cache the tokens
6593 // corresponding to the default argument. We'll actually parse
6594 // them when we see the end of the class definition.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006595 DefArgToks.reset(new CachedTokens);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006596
David Majnemer906ed272015-01-13 05:28:24 +00006597 SourceLocation ArgStartLoc = NextToken().getLocation();
Richard Smith1fff95c2013-09-12 23:28:08 +00006598 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006599 DefArgToks.reset();
Serge Pavlovb4b35782014-07-22 01:54:49 +00006600 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006601 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006602 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
David Majnemer906ed272015-01-13 05:28:24 +00006603 ArgStartLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006604 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006605 } else {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006606 // Consume the '='.
Douglas Gregor58354032008-12-24 00:01:03 +00006607 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00006608
Chad Rosierc1183952012-06-26 22:30:43 +00006609 // The argument isn't actually potentially evaluated unless it is
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006610 // used.
Faisal Valid143a0c2017-04-01 21:30:49 +00006611 EnterExpressionEvaluationContext Eval(
6612 Actions,
6613 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6614 Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006615
Sebastian Redldb63af22012-03-14 15:54:00 +00006616 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006617 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006618 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +00006619 DefArgResult = ParseBraceInitializer();
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006620 } else
Sebastian Redldb63af22012-03-14 15:54:00 +00006621 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +00006622 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006623 if (DefArgResult.isInvalid()) {
Serge Pavlovb4b35782014-07-22 01:54:49 +00006624 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Alexey Bataevee6507d2013-11-18 08:17:37 +00006625 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006626 } else {
6627 // Inform the actions module about the default argument
6628 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006629 DefArgResult.get());
Douglas Gregor4d87df52008-12-16 21:30:33 +00006630 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006631 }
6632 }
Mike Stump11289f42009-09-09 15:08:12 +00006633
6634 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
Fangrui Song6907ce22018-07-30 19:24:48 +00006635 ParmDeclarator.getIdentifierLoc(),
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006636 Param, std::move(DefArgToks)));
Chris Lattner371ed4e2008-04-06 06:57:35 +00006637 }
6638
Richard Smith36ee9fb2014-08-11 23:30:23 +00006639 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6640 if (!getLangOpts().CPlusPlus) {
6641 // We have ellipsis without a preceding ',', which is ill-formed
6642 // in C. Complain and provide the fix.
6643 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6644 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6645 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6646 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6647 // It looks like this was supposed to be a parameter pack. Warn and
6648 // point out where the ellipsis should have gone.
6649 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6650 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6651 << ParmEllipsis.isValid() << ParmEllipsis;
6652 if (ParmEllipsis.isValid()) {
6653 Diag(ParmEllipsis,
6654 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6655 } else {
6656 Diag(ParmDeclarator.getIdentifierLoc(),
6657 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6658 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6659 "...")
6660 << !ParmDeclarator.hasName();
6661 }
6662 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006663 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
Richard Smith36ee9fb2014-08-11 23:30:23 +00006664 }
6665
6666 // We can't have any more parameters after an ellipsis.
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006667 break;
6668 }
Mike Stump11289f42009-09-09 15:08:12 +00006669
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006670 // If the next token is a comma, consume it and keep reading arguments.
6671 } while (TryConsumeToken(tok::comma));
Chris Lattner6c940e62008-04-06 06:34:08 +00006672}
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006673
Chris Lattnere8074e62006-08-06 18:30:15 +00006674/// [C90] direct-declarator '[' constant-expression[opt] ']'
6675/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6676/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6677/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6678/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006679/// [C++11] direct-declarator '[' constant-expression[opt] ']'
6680/// attribute-specifier-seq[opt]
Chris Lattnere8074e62006-08-06 18:30:15 +00006681void Parser::ParseBracketDeclarator(Declarator &D) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006682 if (CheckProhibitedCXX11Attribute())
6683 return;
6684
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006685 BalancedDelimiterTracker T(*this, tok::l_square);
6686 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00006687
Chris Lattner84a11622008-12-18 07:27:21 +00006688 // C array syntax has many features, but by-far the most common is [] and [4].
6689 // This code does a fast path to handle some of the most obvious cases.
6690 if (Tok.getKind() == tok::r_square) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006691 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006692 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006693 MaybeParseCXX11Attributes(attrs);
Chad Rosierc1183952012-06-26 22:30:43 +00006694
Chris Lattner84a11622008-12-18 07:27:21 +00006695 // Remember that we parsed the empty array type.
Craig Topper161e4db2014-05-21 06:02:52 +00006696 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006697 T.getOpenLocation(),
6698 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006699 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006700 return;
6701 } else if (Tok.getKind() == tok::numeric_constant &&
6702 GetLookAheadToken(1).is(tok::r_square)) {
6703 // [4] is very common. Parse the numeric constant expression.
Richard Smithbcc22fc2012-03-09 08:00:36 +00006704 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
Chris Lattner84a11622008-12-18 07:27:21 +00006705 ConsumeToken();
6706
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006707 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006708 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006709 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006710
Chris Lattner84a11622008-12-18 07:27:21 +00006711 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006712 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006713 T.getOpenLocation(),
6714 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006715 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006716 return;
Benjamin Kramer72dae622016-02-18 15:30:24 +00006717 } else if (Tok.getKind() == tok::code_completion) {
6718 Actions.CodeCompleteBracketDeclarator(getCurScope());
6719 return cutOffParsing();
Chris Lattner84a11622008-12-18 07:27:21 +00006720 }
Mike Stump11289f42009-09-09 15:08:12 +00006721
Chris Lattnere8074e62006-08-06 18:30:15 +00006722 // If valid, this location is the position where we read the 'static' keyword.
6723 SourceLocation StaticLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006724 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006725
Chris Lattnere8074e62006-08-06 18:30:15 +00006726 // If there is a type-qualifier-list, read it now.
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006727 // Type qualifiers in an array subscript are a C99 feature.
John McCall084e83d2011-03-24 11:26:52 +00006728 DeclSpec DS(AttrFactory);
Aaron Ballman08b06592014-07-22 12:44:22 +00006729 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
Mike Stump11289f42009-09-09 15:08:12 +00006730
Chris Lattnere8074e62006-08-06 18:30:15 +00006731 // If we haven't already read 'static', check to see if there is one after the
6732 // type-qualifier-list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006733 if (!StaticLoc.isValid())
6734 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006735
Chris Lattnere8074e62006-08-06 18:30:15 +00006736 // Handle "direct-declarator [ type-qual-list[opt] * ]".
Chris Lattnere8074e62006-08-06 18:30:15 +00006737 bool isStar = false;
John McCalldadc5752010-08-24 06:29:42 +00006738 ExprResult NumElements;
Mike Stump11289f42009-09-09 15:08:12 +00006739
Chris Lattner521ff2b2008-04-06 05:26:30 +00006740 // Handle the case where we have '[*]' as the array size. However, a leading
6741 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
Sylvestre Ledru830885c2012-07-23 08:59:39 +00006742 // the token after the star is a ']'. Since stars in arrays are
Chris Lattner521ff2b2008-04-06 05:26:30 +00006743 // infrequent, use of lookahead is not costly here.
6744 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
Chris Lattnerc439f0d2008-04-06 05:27:21 +00006745 ConsumeToken(); // Eat the '*'.
Chris Lattner1906f802006-08-06 19:14:46 +00006746
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006747 if (StaticLoc.isValid()) {
Chris Lattner521ff2b2008-04-06 05:26:30 +00006748 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006749 StaticLoc = SourceLocation(); // Drop the static.
6750 }
Chris Lattner521ff2b2008-04-06 05:26:30 +00006751 isStar = true;
Chris Lattner76c72282007-10-09 17:33:22 +00006752 } else if (Tok.isNot(tok::r_square)) {
Chris Lattner84a11622008-12-18 07:27:21 +00006753 // Note, in C89, this production uses the constant-expr production instead
6754 // of assignment-expr. The only difference is that assignment-expr allows
6755 // things like '=' and '*='. Sema rejects these in C89 mode because they
6756 // are not i-c-e's, so we don't need to distinguish between the two here.
Mike Stump11289f42009-09-09 15:08:12 +00006757
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006758 // Parse the constant-expression or assignment-expression now (depending
6759 // on dialect).
David Blaikiebbafb8a2012-03-11 07:00:24 +00006760 if (getLangOpts().CPlusPlus) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006761 NumElements = ParseConstantExpression();
Eli Friedmane0afc982012-01-21 01:01:51 +00006762 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00006763 EnterExpressionEvaluationContext Unevaluated(
6764 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Kaelyn Takata15867822014-11-21 18:48:04 +00006765 NumElements =
6766 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Eli Friedmane0afc982012-01-21 01:01:51 +00006767 }
David Majnemerf9834d52014-08-08 07:21:18 +00006768 } else {
6769 if (StaticLoc.isValid()) {
6770 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6771 StaticLoc = SourceLocation(); // Drop the static.
6772 }
Chris Lattner62591722006-08-12 18:40:58 +00006773 }
Mike Stump11289f42009-09-09 15:08:12 +00006774
Chris Lattner62591722006-08-12 18:40:58 +00006775 // If there was an error parsing the assignment-expression, recover.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00006776 if (NumElements.isInvalid()) {
Chris Lattnercd2a8c52009-04-24 22:30:50 +00006777 D.setInvalidType(true);
Chris Lattner62591722006-08-12 18:40:58 +00006778 // If the expression was invalid, skip it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00006779 SkipUntil(tok::r_square, StopAtSemi);
Chris Lattner62591722006-08-12 18:40:58 +00006780 return;
Chris Lattnere8074e62006-08-06 18:30:15 +00006781 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006782
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006783 T.consumeClose();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006784
Jordan Rose303e2f12016-11-10 23:28:17 +00006785 MaybeParseCXX11Attributes(DS.getAttributes());
Alexis Hunt96d5c762009-11-21 08:43:09 +00006786
Chris Lattner84a11622008-12-18 07:27:21 +00006787 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006788 D.AddTypeInfo(
6789 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6790 isStar, NumElements.get(), T.getOpenLocation(),
6791 T.getCloseLocation()),
6792 std::move(DS.getAttributes()), T.getCloseLocation());
Chris Lattnere8074e62006-08-06 18:30:15 +00006793}
6794
Richard Trieuf4b81d02014-06-24 23:14:24 +00006795/// Diagnose brackets before an identifier.
6796void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6797 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6798 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6799
6800 SourceLocation StartBracketLoc = Tok.getLocation();
6801 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6802
6803 while (Tok.is(tok::l_square)) {
6804 ParseBracketDeclarator(TempDeclarator);
6805 }
6806
6807 // Stuff the location of the start of the brackets into the Declarator.
6808 // The diagnostics from ParseDirectDeclarator will make more sense if
6809 // they use this location instead.
6810 if (Tok.is(tok::semi))
6811 D.getName().EndLocation = StartBracketLoc;
6812
6813 SourceLocation SuggestParenLoc = Tok.getLocation();
6814
6815 // Now that the brackets are removed, try parsing the declarator again.
6816 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6817
6818 // Something went wrong parsing the brackets, in which case,
6819 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6820 // one here.
6821 if (TempDeclarator.getNumTypeObjects() == 0)
6822 return;
6823
6824 // Determine if parens will need to be suggested in the diagnostic.
6825 bool NeedParens = false;
6826 if (D.getNumTypeObjects() != 0) {
6827 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6828 case DeclaratorChunk::Pointer:
6829 case DeclaratorChunk::Reference:
6830 case DeclaratorChunk::BlockPointer:
6831 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00006832 case DeclaratorChunk::Pipe:
Richard Trieuf4b81d02014-06-24 23:14:24 +00006833 NeedParens = true;
6834 break;
6835 case DeclaratorChunk::Array:
6836 case DeclaratorChunk::Function:
6837 case DeclaratorChunk::Paren:
6838 break;
6839 }
6840 }
6841
6842 if (NeedParens) {
6843 // Create a DeclaratorChunk for the inserted parens.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006844 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Erich Keanec480f302018-07-12 21:09:05 +00006845 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
Richard Trieuf4b81d02014-06-24 23:14:24 +00006846 SourceLocation());
6847 }
6848
6849 // Adding back the bracket info to the end of the Declarator.
6850 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6851 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
Erich Keanec480f302018-07-12 21:09:05 +00006852 D.AddTypeInfo(Chunk, SourceLocation());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006853 }
6854
6855 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6856 // If parentheses are required, always suggest them.
6857 if (!D.getIdentifier() && !NeedParens)
6858 return;
6859
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006860 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
Richard Trieuf4b81d02014-06-24 23:14:24 +00006861
6862 // Generate the move bracket error message.
6863 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006864 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006865
6866 if (NeedParens) {
6867 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6868 << getLangOpts().CPlusPlus
6869 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6870 << FixItHint::CreateInsertion(EndLoc, ")")
6871 << FixItHint::CreateInsertionFromRange(
6872 EndLoc, CharSourceRange(BracketRange, true))
6873 << FixItHint::CreateRemoval(BracketRange);
6874 } else {
6875 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6876 << getLangOpts().CPlusPlus
6877 << FixItHint::CreateInsertionFromRange(
6878 EndLoc, CharSourceRange(BracketRange, true))
6879 << FixItHint::CreateRemoval(BracketRange);
6880 }
6881}
6882
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006883/// [GNU] typeof-specifier:
6884/// typeof ( expressions )
6885/// typeof ( type-name )
6886/// [GNU/C++] typeof unary-expression
Steve Naroffad373bd2007-07-31 12:34:36 +00006887///
6888void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
Chris Lattner76c72282007-10-09 17:33:22 +00006889 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006890 Token OpTok = Tok;
Steve Naroffad373bd2007-07-31 12:34:36 +00006891 SourceLocation StartLoc = ConsumeToken();
6892
John McCalle8595032010-01-13 20:03:27 +00006893 const bool hasParens = Tok.is(tok::l_paren);
6894
Faisal Valid143a0c2017-04-01 21:30:49 +00006895 EnterExpressionEvaluationContext Unevaluated(
6896 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6897 Sema::ReuseLambdaContextDecl);
Eli Friedmane0afc982012-01-21 01:01:51 +00006898
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006899 bool isCastExpr;
John McCallba7bf592010-08-24 05:47:05 +00006900 ParsedType CastTy;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006901 SourceRange CastRange;
Kaelyn Takata911260742014-12-19 01:28:40 +00006902 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6903 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
John McCalle8595032010-01-13 20:03:27 +00006904 if (hasParens)
6905 DS.setTypeofParensRange(CastRange);
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006906
6907 if (CastRange.getEnd().isInvalid())
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006908 // FIXME: Not accurate, the range gets one token more than it should.
6909 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006910 else
6911 DS.SetRangeEnd(CastRange.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +00006912
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006913 if (isCastExpr) {
6914 if (!CastTy) {
6915 DS.SetTypeSpecError();
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006916 return;
Douglas Gregor220cac52009-02-18 17:45:20 +00006917 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006918
Craig Topper161e4db2014-05-21 06:02:52 +00006919 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006920 unsigned DiagID;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006921 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6922 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006923 DiagID, CastTy,
6924 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006925 Diag(StartLoc, DiagID) << PrevSpec;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006926 return;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006927 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006928
Hiroshi Inoue533777f2017-07-02 06:12:49 +00006929 // If we get here, the operand to the typeof was an expression.
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006930 if (Operand.isInvalid()) {
6931 DS.SetTypeSpecError();
Steve Naroff4bd2f712007-08-02 02:53:48 +00006932 return;
Steve Naroffad373bd2007-07-31 12:34:36 +00006933 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006934
Eli Friedmane0afc982012-01-21 01:01:51 +00006935 // We might need to transform the operand if it is potentially evaluated.
6936 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6937 if (Operand.isInvalid()) {
6938 DS.SetTypeSpecError();
6939 return;
6940 }
6941
Craig Topper161e4db2014-05-21 06:02:52 +00006942 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006943 unsigned DiagID;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006944 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6945 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006946 DiagID, Operand.get(),
6947 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006948 Diag(StartLoc, DiagID) << PrevSpec;
Steve Naroffad373bd2007-07-31 12:34:36 +00006949}
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006950
Benjamin Kramere56f3932011-12-23 17:00:35 +00006951/// [C11] atomic-specifier:
Eli Friedman0dfb8892011-10-06 23:00:33 +00006952/// _Atomic ( type-name )
6953///
6954void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
Richard Smith8e1ac332013-03-28 01:55:44 +00006955 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6956 "Not an atomic specifier");
Eli Friedman0dfb8892011-10-06 23:00:33 +00006957
6958 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006959 BalancedDelimiterTracker T(*this, tok::l_paren);
Richard Smith8e1ac332013-03-28 01:55:44 +00006960 if (T.consumeOpen())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006961 return;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006962
6963 TypeResult Result = ParseTypeName();
6964 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00006965 SkipUntil(tok::r_paren, StopAtSemi);
Eli Friedman0dfb8892011-10-06 23:00:33 +00006966 return;
6967 }
6968
6969 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006970 T.consumeClose();
Eli Friedman0dfb8892011-10-06 23:00:33 +00006971
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006972 if (T.getCloseLocation().isInvalid())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006973 return;
6974
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006975 DS.setTypeofParensRange(T.getRange());
6976 DS.SetRangeEnd(T.getCloseLocation());
Eli Friedman0dfb8892011-10-06 23:00:33 +00006977
Craig Topper161e4db2014-05-21 06:02:52 +00006978 const char *PrevSpec = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006979 unsigned DiagID;
6980 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006981 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006982 Actions.getASTContext().getPrintingPolicy()))
Eli Friedman0dfb8892011-10-06 23:00:33 +00006983 Diag(StartLoc, DiagID) << PrevSpec;
6984}
6985
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006986/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6987/// from TryAltiVecVectorToken.
6988bool Parser::TryAltiVecVectorTokenOutOfLine() {
6989 Token Next = NextToken();
6990 switch (Next.getKind()) {
6991 default: return false;
6992 case tok::kw_short:
6993 case tok::kw_long:
6994 case tok::kw_signed:
6995 case tok::kw_unsigned:
6996 case tok::kw_void:
6997 case tok::kw_char:
6998 case tok::kw_int:
6999 case tok::kw_float:
7000 case tok::kw_double:
7001 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00007002 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007003 case tok::kw___pixel:
7004 Tok.setKind(tok::kw___vector);
7005 return true;
7006 case tok::identifier:
7007 if (Next.getIdentifierInfo() == Ident_pixel) {
7008 Tok.setKind(tok::kw___vector);
7009 return true;
7010 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00007011 if (Next.getIdentifierInfo() == Ident_bool) {
7012 Tok.setKind(tok::kw___vector);
7013 return true;
7014 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007015 return false;
7016 }
7017}
7018
7019bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
7020 const char *&PrevSpec, unsigned &DiagID,
7021 bool &isInvalid) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007022 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007023 if (Tok.getIdentifierInfo() == Ident_vector) {
7024 Token Next = NextToken();
7025 switch (Next.getKind()) {
7026 case tok::kw_short:
7027 case tok::kw_long:
7028 case tok::kw_signed:
7029 case tok::kw_unsigned:
7030 case tok::kw_void:
7031 case tok::kw_char:
7032 case tok::kw_int:
7033 case tok::kw_float:
7034 case tok::kw_double:
7035 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00007036 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007037 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007038 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007039 return true;
7040 case tok::identifier:
7041 if (Next.getIdentifierInfo() == Ident_pixel) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007042 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007043 return true;
7044 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00007045 if (Next.getIdentifierInfo() == Ident_bool) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007046 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00007047 return true;
7048 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007049 break;
7050 default:
7051 break;
7052 }
Douglas Gregor9938e3b2010-06-16 15:28:57 +00007053 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007054 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007055 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007056 return true;
Bill Schmidt99a084b2013-07-03 20:54:09 +00007057 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
7058 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007059 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00007060 return true;
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007061 }
7062 return false;
7063}