blob: fe597ed2dfb36131c4a71c3888b114f8f2a04010 [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") ))
Alp Toker094e5212014-01-05 03:27:11 +0000167 while (true) {
168 // Allow empty/non-empty attributes. ((__vector_size__(16),,,,))
169 if (TryConsumeToken(tok::comma))
Steve Naroff0f2fe172007-06-01 17:11:19 +0000170 continue;
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);
Steve Naroff0f2fe172007-06-01 17:11:19 +0000215 }
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);
David Blaikie2eabcc92016-02-09 18:52:09 +00001473 PP.EnterTokenStream(LA.Toks, 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.
Faisal Vali7db85c52017-12-31 00:06:40 +00002490 if (DS.isConstexprSpecified() && DSC != DeclSpecContext::DSC_condition) {
Richard Smithc5b05522012-03-12 07:56:15 +00002491 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2492 DS.ClearConstexprSpec();
2493 }
Chris Lattner1890ac82006-08-13 01:16:23 +00002494}
Chris Lattner53361ac2006-08-10 05:19:57 +00002495
Chris Lattner6cc055a2009-04-12 20:42:31 +00002496/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2497/// specified token is valid after the identifier in a declarator which
2498/// immediately follows the declspec. For example, these things are valid:
2499///
2500/// int x [ 4]; // direct-declarator
2501/// int x ( int y); // direct-declarator
2502/// int(int x ) // direct-declarator
2503/// int x ; // simple-declaration
2504/// int x = 17; // init-declarator-list
2505/// int x , y; // init-declarator-list
2506/// int x __asm__ ("foo"); // init-declarator-list
Chris Lattnera723ba92009-04-14 21:16:09 +00002507/// int x : 4; // struct-declarator
Chris Lattner2b988c12009-04-12 22:29:43 +00002508/// int x { 5}; // C++'0x unified initializers
Chris Lattner6cc055a2009-04-12 20:42:31 +00002509///
2510/// This is not, because 'x' does not immediately follow the declspec (though
2511/// ')' happens to be valid anyway).
2512/// int (x)
2513///
2514static bool isValidAfterIdentifierInDeclarator(const Token &T) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002515 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2516 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2517 tok::colon);
Chris Lattner6cc055a2009-04-12 20:42:31 +00002518}
2519
Chris Lattner20a0c612009-04-14 21:34:55 +00002520/// ParseImplicitInt - This method is called when we have an non-typename
2521/// identifier in a declspec (which normally terminates the decl spec) when
2522/// the declspec has no type specifier. In this case, the declspec is either
2523/// malformed or is "implicit int" (in K&R and C89).
2524///
2525/// This method handles diagnosing this prettily and returns false if the
2526/// declspec is done being processed. If it recovers and thinks there may be
2527/// other pieces of declspec after it, it returns true.
2528///
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002529bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002530 const ParsedTemplateInfo &TemplateInfo,
Richard Smitha0a5d502014-05-08 22:32:00 +00002531 AccessSpecifier AS, DeclSpecContext DSC,
Michael Han9407e502012-11-26 22:54:45 +00002532 ParsedAttributesWithRange &Attrs) {
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002533 assert(Tok.is(tok::identifier) && "should have identifier");
Mike Stump11289f42009-09-09 15:08:12 +00002534
Chris Lattner20a0c612009-04-14 21:34:55 +00002535 SourceLocation Loc = Tok.getLocation();
2536 // If we see an identifier that is not a type name, we normally would
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002537 // parse it as the identifier being declared. However, when a typename
Chris Lattner20a0c612009-04-14 21:34:55 +00002538 // is typo'd or the definition is not included, this will incorrectly
2539 // parse the typename as the identifier name and fall over misparsing
2540 // later parts of the diagnostic.
2541 //
2542 // As such, we try to do some look-ahead in cases where this would
2543 // otherwise be an "implicit-int" case to see if this is invalid. For
2544 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2545 // an identifier with implicit int, we'd get a parse error because the
2546 // next token is obviously invalid for a type. Parse these as a case
2547 // with an invalid type specifier.
2548 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
Mike Stump11289f42009-09-09 15:08:12 +00002549
Chris Lattner20a0c612009-04-14 21:34:55 +00002550 // Since we know that this either implicit int (which is rare) or an
Richard Smitha952ebb2012-05-15 21:01:51 +00002551 // error, do lookahead to try to do better recovery. This never applies
2552 // within a type specifier. Outside of C++, we allow this even if the
2553 // language doesn't "officially" support implicit int -- we support
Richard Smith3b870382013-04-30 22:43:51 +00002554 // implicit int as an extension in C99 and C11.
Richard Smith649c7b062014-01-08 00:56:48 +00002555 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
Richard Smithc5b05522012-03-12 07:56:15 +00002556 isValidAfterIdentifierInDeclarator(NextToken())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002557 // If this token is valid for implicit int, e.g. "static x = 4", then
2558 // we just avoid eating the identifier, so it will be parsed as the
2559 // identifier in the declarator.
2560 return false;
2561 }
Mike Stump11289f42009-09-09 15:08:12 +00002562
Richard Smitha952ebb2012-05-15 21:01:51 +00002563 if (getLangOpts().CPlusPlus &&
2564 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2565 // Don't require a type specifier if we have the 'auto' storage class
2566 // specifier in C++98 -- we'll promote it to a type specifier.
Richard Smithfb8b7b92013-10-15 00:00:26 +00002567 if (SS)
2568 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
Richard Smitha952ebb2012-05-15 21:01:51 +00002569 return false;
2570 }
2571
Reid Kleckner9a96e422016-05-24 21:23:54 +00002572 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2573 getLangOpts().MSVCCompat) {
2574 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2575 // Give Sema a chance to recover if we are in a template with dependent base
2576 // classes.
2577 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2578 *Tok.getIdentifierInfo(), Tok.getLocation(),
Faisal Vali7db85c52017-12-31 00:06:40 +00002579 DSC == DeclSpecContext::DSC_template_type_arg)) {
Reid Kleckner9a96e422016-05-24 21:23:54 +00002580 const char *PrevSpec;
2581 unsigned DiagID;
2582 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2583 Actions.getASTContext().getPrintingPolicy());
2584 DS.SetRangeEnd(Tok.getLocation());
2585 ConsumeToken();
2586 return false;
2587 }
2588 }
2589
Chris Lattner20a0c612009-04-14 21:34:55 +00002590 // Otherwise, if we don't consume this token, we are going to emit an
2591 // error anyway. Try to recover from various common problems. Check
2592 // to see if this was a reference to a tag name without a tag specified.
2593 // This is a common problem in C (saying 'foo' instead of 'struct foo').
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002594 //
2595 // C++ doesn't need this, and isTagName doesn't take SS.
Craig Topper161e4db2014-05-21 06:02:52 +00002596 if (SS == nullptr) {
2597 const char *TagName = nullptr, *FixitTagName = nullptr;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002598 tok::TokenKind TagKind = tok::unknown;
Mike Stump11289f42009-09-09 15:08:12 +00002599
Douglas Gregor0be31a22010-07-02 17:43:08 +00002600 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002601 default: break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002602 case DeclSpec::TST_enum:
2603 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2604 case DeclSpec::TST_union:
2605 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2606 case DeclSpec::TST_struct:
2607 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
Joao Matosdc86f942012-08-31 18:45:21 +00002608 case DeclSpec::TST_interface:
2609 TagName="__interface"; FixitTagName = "__interface ";
2610 TagKind=tok::kw___interface;break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002611 case DeclSpec::TST_class:
2612 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
Chris Lattner20a0c612009-04-14 21:34:55 +00002613 }
Mike Stump11289f42009-09-09 15:08:12 +00002614
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002615 if (TagName) {
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002616 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2617 LookupResult R(Actions, TokenName, SourceLocation(),
2618 Sema::LookupOrdinaryName);
2619
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002620 Diag(Loc, diag::err_use_of_tag_name_without_tag)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002621 << TokenName << TagName << getLangOpts().CPlusPlus
2622 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2623
2624 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2625 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2626 I != IEnd; ++I)
Kaelyn Uhrain3fe3f852012-04-27 18:26:49 +00002627 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002628 << TokenName << TagName;
2629 }
Mike Stump11289f42009-09-09 15:08:12 +00002630
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002631 // Parse this as a tag as if the missing tag were present.
2632 if (TagKind == tok::kw_enum)
Faisal Vali7db85c52017-12-31 00:06:40 +00002633 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2634 DeclSpecContext::DSC_normal);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002635 else
Richard Smithc5b05522012-03-12 07:56:15 +00002636 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
Faisal Vali7db85c52017-12-31 00:06:40 +00002637 /*EnteringContext*/ false,
2638 DeclSpecContext::DSC_normal, Attrs);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002639 return true;
2640 }
Chris Lattner20a0c612009-04-14 21:34:55 +00002641 }
Mike Stump11289f42009-09-09 15:08:12 +00002642
Richard Smithfe904f02012-05-15 21:29:55 +00002643 // Determine whether this identifier could plausibly be the name of something
Richard Smithedd124e2012-05-15 21:42:17 +00002644 // being declared (with a missing type).
Faisal Vali7db85c52017-12-31 00:06:40 +00002645 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2646 DSC == DeclSpecContext::DSC_class)) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002647 // Look ahead to the next token to try to figure out what this declaration
2648 // was supposed to be.
2649 switch (NextToken().getKind()) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002650 case tok::l_paren: {
2651 // static x(4); // 'x' is not a type
2652 // x(int n); // 'x' is not a type
2653 // x (*p)[]; // 'x' is a type
2654 //
Richard Smitha0a5d502014-05-08 22:32:00 +00002655 // Since we're in an error case, we can afford to perform a tentative
2656 // parse to determine which case we're in.
Richard Smitha952ebb2012-05-15 21:01:51 +00002657 TentativeParsingAction PA(*this);
2658 ConsumeToken();
2659 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2660 PA.Revert();
Richard Smithfb8b7b92013-10-15 00:00:26 +00002661
Richard Smithee390432014-05-16 01:56:53 +00002662 if (TPR != TPResult::False) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002663 // The identifier is followed by a parenthesized declarator.
2664 // It's supposed to be a type.
2665 break;
2666 }
2667
2668 // If we're in a context where we could be declaring a constructor,
2669 // check whether this is a constructor declaration with a bogus name.
Faisal Vali7db85c52017-12-31 00:06:40 +00002670 if (DSC == DeclSpecContext::DSC_class ||
2671 (DSC == DeclSpecContext::DSC_top_level && SS)) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002672 IdentifierInfo *II = Tok.getIdentifierInfo();
2673 if (Actions.isCurrentClassNameTypo(II, SS)) {
2674 Diag(Loc, diag::err_constructor_bad_name)
2675 << Tok.getIdentifierInfo() << II
2676 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2677 Tok.setIdentifierInfo(II);
2678 }
2679 }
2680 // Fall through.
Galina Kistanova77674252017-06-01 21:15:34 +00002681 LLVM_FALLTHROUGH;
Richard Smitha952ebb2012-05-15 21:01:51 +00002682 }
Richard Smithfb8b7b92013-10-15 00:00:26 +00002683 case tok::comma:
2684 case tok::equal:
2685 case tok::kw_asm:
2686 case tok::l_brace:
2687 case tok::l_square:
2688 case tok::semi:
2689 // This looks like a variable or function declaration. The type is
2690 // probably missing. We're done parsing decl-specifiers.
Nicolas Lesseree057172019-05-05 12:15:17 +00002691 // But only if we are not in a function prototype scope.
2692 if (getCurScope()->isFunctionPrototypeScope())
2693 break;
Richard Smithfb8b7b92013-10-15 00:00:26 +00002694 if (SS)
2695 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2696 return false;
Richard Smitha952ebb2012-05-15 21:01:51 +00002697
2698 default:
2699 // This is probably supposed to be a type. This includes cases like:
2700 // int f(itn);
2701 // struct S { unsinged : 4; };
2702 break;
2703 }
2704 }
2705
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002706 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2707 // and attempt to recover.
John McCallba7bf592010-08-24 05:47:05 +00002708 ParsedType T;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +00002709 IdentifierInfo *II = Tok.getIdentifierInfo();
Richard Smith52f8d192017-05-10 21:32:16 +00002710 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002711 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
Richard Smith52f8d192017-05-10 21:32:16 +00002712 IsTemplateName);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002713 if (T) {
2714 // The action has suggested that the type T could be used. Set that as
2715 // the type in the declaration specifiers, consume the would-be type
2716 // name token, and we're done.
2717 const char *PrevSpec;
2718 unsigned DiagID;
2719 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2720 Actions.getASTContext().getPrintingPolicy());
2721 DS.SetRangeEnd(Tok.getLocation());
2722 ConsumeToken();
2723 // There may be other declaration specifiers after this.
2724 return true;
2725 } else if (II != Tok.getIdentifierInfo()) {
2726 // If no type was suggested, the correction is to a keyword
2727 Tok.setKind(II->getTokenID());
2728 // There may be other declaration specifiers after this.
2729 return true;
Douglas Gregor15e56022009-10-13 23:27:22 +00002730 }
Mike Stump11289f42009-09-09 15:08:12 +00002731
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002732 // Otherwise, the action had no suggestion for us. Mark this as an error.
Richard Smithc5b05522012-03-12 07:56:15 +00002733 DS.SetTypeSpecError();
Chris Lattner20a0c612009-04-14 21:34:55 +00002734 DS.SetRangeEnd(Tok.getLocation());
2735 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002736
Richard Smith52f8d192017-05-10 21:32:16 +00002737 // Eat any following template arguments.
2738 if (IsTemplateName) {
2739 SourceLocation LAngle, RAngle;
2740 TemplateArgList Args;
2741 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2742 }
2743
Chris Lattner20a0c612009-04-14 21:34:55 +00002744 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2745 // avoid rippling error messages on subsequent uses of the same type,
2746 // could be useful if #include was forgotten.
Richard Smithb3065792019-05-07 07:36:07 +00002747 return true;
Chris Lattner20a0c612009-04-14 21:34:55 +00002748}
2749
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002750/// Determine the declaration specifier context from the declarator
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002751/// context.
2752///
2753/// \param Context the declarator context, which is one of the
Faisal Vali421b2d12017-12-29 05:41:00 +00002754/// DeclaratorContext enumerator values.
Chad Rosierc1183952012-06-26 22:30:43 +00002755Parser::DeclSpecContext
Faisal Vali421b2d12017-12-29 05:41:00 +00002756Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2757 if (Context == DeclaratorContext::MemberContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002758 return DeclSpecContext::DSC_class;
Faisal Vali421b2d12017-12-29 05:41:00 +00002759 if (Context == DeclaratorContext::FileContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002760 return DeclSpecContext::DSC_top_level;
Faisal Vali421b2d12017-12-29 05:41:00 +00002761 if (Context == DeclaratorContext::TemplateParamContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002762 return DeclSpecContext::DSC_template_param;
Richard Smith77a9c602018-02-28 03:02:23 +00002763 if (Context == DeclaratorContext::TemplateArgContext ||
2764 Context == DeclaratorContext::TemplateTypeArgContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002765 return DeclSpecContext::DSC_template_type_arg;
Richard Smithe303e352018-02-02 22:24:54 +00002766 if (Context == DeclaratorContext::TrailingReturnContext ||
2767 Context == DeclaratorContext::TrailingReturnVarContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002768 return DeclSpecContext::DSC_trailing;
Faisal Vali421b2d12017-12-29 05:41:00 +00002769 if (Context == DeclaratorContext::AliasDeclContext ||
2770 Context == DeclaratorContext::AliasTemplateContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002771 return DeclSpecContext::DSC_alias_declaration;
2772 return DeclSpecContext::DSC_normal;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002773}
2774
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002775/// ParseAlignArgument - Parse the argument to an alignment-specifier.
2776///
2777/// FIXME: Simply returns an alignof() expression if the argument is a
2778/// type. Ideally, the type should be propagated directly into Sema.
2779///
Benjamin Kramere56f3932011-12-23 17:00:35 +00002780/// [C11] type-id
2781/// [C11] constant-expression
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002782/// [C++0x] type-id ...[opt]
2783/// [C++0x] assignment-expression ...[opt]
2784ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2785 SourceLocation &EllipsisLoc) {
2786 ExprResult ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002787 if (isTypeIdInParens()) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002788 SourceLocation TypeLoc = Tok.getLocation();
2789 ParsedType Ty = ParseTypeName().get();
2790 SourceRange TypeRange(Start, Tok.getLocation());
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002791 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2792 Ty.getAsOpaquePtr(), TypeRange);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002793 } else
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002794 ER = ParseConstantExpression();
2795
Alp Toker8fbec672013-12-17 23:29:36 +00002796 if (getLangOpts().CPlusPlus11)
2797 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002798
2799 return ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002800}
2801
2802/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2803/// attribute to Attrs.
2804///
2805/// alignment-specifier:
Benjamin Kramere56f3932011-12-23 17:00:35 +00002806/// [C11] '_Alignas' '(' type-id ')'
2807/// [C11] '_Alignas' '(' constant-expression ')'
Richard Smithd11c7a12013-01-29 01:48:07 +00002808/// [C++11] 'alignas' '(' type-id ...[opt] ')'
2809/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002810void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
Richard Smith44c247f2013-02-22 08:32:16 +00002811 SourceLocation *EndLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002812 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002813 "Not an alignment-specifier!");
2814
Richard Smithd11c7a12013-01-29 01:48:07 +00002815 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2816 SourceLocation KWLoc = ConsumeToken();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002817
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002818 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002819 if (T.expectAndConsume())
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002820 return;
2821
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002822 SourceLocation EllipsisLoc;
2823 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002824 if (ArgExpr.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002825 T.skipToEnd();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002826 return;
2827 }
2828
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002829 T.consumeClose();
Richard Smith44c247f2013-02-22 08:32:16 +00002830 if (EndLoc)
2831 *EndLoc = T.getCloseLocation();
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002832
Aaron Ballman00e99962013-08-31 01:11:41 +00002833 ArgsVector ArgExprs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002834 ArgExprs.push_back(ArgExpr.get());
Craig Topper161e4db2014-05-21 06:02:52 +00002835 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
Erich Keanee891aa92018-07-13 15:07:47 +00002836 ParsedAttr::AS_Keyword, EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002837}
2838
Richard Smith404dfb42013-11-19 22:47:36 +00002839/// Determine whether we're looking at something that might be a declarator
2840/// in a simple-declaration. If it can't possibly be a declarator, maybe
2841/// diagnose a missing semicolon after a prior tag definition in the decl
2842/// specifier.
2843///
2844/// \return \c true if an error occurred and this can't be any kind of
2845/// declaration.
2846bool
2847Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2848 DeclSpecContext DSContext,
2849 LateParsedAttrList *LateAttrs) {
2850 assert(DS.hasTagDefinition() && "shouldn't call this");
2851
Faisal Vali7db85c52017-12-31 00:06:40 +00002852 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2853 DSContext == DeclSpecContext::DSC_top_level);
Richard Smith404dfb42013-11-19 22:47:36 +00002854
2855 if (getLangOpts().CPlusPlus &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002856 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2857 tok::annot_template_id) &&
Richard Smith404dfb42013-11-19 22:47:36 +00002858 TryAnnotateCXXScopeToken(EnteringContext)) {
2859 SkipMalformedDecl();
2860 return true;
2861 }
2862
Richard Smith698875a2013-11-20 23:40:57 +00002863 bool HasScope = Tok.is(tok::annot_cxxscope);
2864 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2865 Token AfterScope = HasScope ? NextToken() : Tok;
2866
Richard Smith404dfb42013-11-19 22:47:36 +00002867 // Determine whether the following tokens could possibly be a
2868 // declarator.
Richard Smith698875a2013-11-20 23:40:57 +00002869 bool MightBeDeclarator = true;
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002870 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
Richard Smith698875a2013-11-20 23:40:57 +00002871 // A declarator-id can't start with 'typename'.
2872 MightBeDeclarator = false;
2873 } else if (AfterScope.is(tok::annot_template_id)) {
2874 // If we have a type expressed as a template-id, this cannot be a
2875 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2876 TemplateIdAnnotation *Annot =
2877 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2878 if (Annot->Kind == TNK_Type_template)
2879 MightBeDeclarator = false;
2880 } else if (AfterScope.is(tok::identifier)) {
2881 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2882
Richard Smith404dfb42013-11-19 22:47:36 +00002883 // These tokens cannot come after the declarator-id in a
2884 // simple-declaration, and are likely to come after a type-specifier.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002885 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2886 tok::annot_cxxscope, tok::coloncolon)) {
Richard Smith698875a2013-11-20 23:40:57 +00002887 // Missing a semicolon.
2888 MightBeDeclarator = false;
2889 } else if (HasScope) {
2890 // If the declarator-id has a scope specifier, it must redeclare a
2891 // previously-declared entity. If that's a type (and this is not a
2892 // typedef), that's an error.
2893 CXXScopeSpec SS;
2894 Actions.RestoreNestedNameSpecifierAnnotation(
2895 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2896 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2897 Sema::NameClassification Classification = Actions.ClassifyName(
2898 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
Bruno Ricci70ad3962019-03-25 17:08:51 +00002899 /*IsAddressOfOperand=*/false, /*CCC=*/nullptr);
Richard Smith698875a2013-11-20 23:40:57 +00002900 switch (Classification.getKind()) {
2901 case Sema::NC_Error:
2902 SkipMalformedDecl();
2903 return true;
Richard Smith404dfb42013-11-19 22:47:36 +00002904
Richard Smith698875a2013-11-20 23:40:57 +00002905 case Sema::NC_Keyword:
2906 case Sema::NC_NestedNameSpecifier:
2907 llvm_unreachable("typo correction and nested name specifiers not "
2908 "possible here");
Richard Smith404dfb42013-11-19 22:47:36 +00002909
Richard Smith698875a2013-11-20 23:40:57 +00002910 case Sema::NC_Type:
2911 case Sema::NC_TypeTemplate:
2912 // Not a previously-declared non-type entity.
2913 MightBeDeclarator = false;
2914 break;
Richard Smith404dfb42013-11-19 22:47:36 +00002915
Richard Smith698875a2013-11-20 23:40:57 +00002916 case Sema::NC_Unknown:
2917 case Sema::NC_Expression:
2918 case Sema::NC_VarTemplate:
2919 case Sema::NC_FunctionTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00002920 case Sema::NC_UndeclaredTemplate:
Richard Smith698875a2013-11-20 23:40:57 +00002921 // Might be a redeclaration of a prior entity.
2922 break;
2923 }
Richard Smith404dfb42013-11-19 22:47:36 +00002924 }
Richard Smith404dfb42013-11-19 22:47:36 +00002925 }
2926
Richard Smith698875a2013-11-20 23:40:57 +00002927 if (MightBeDeclarator)
Richard Smith404dfb42013-11-19 22:47:36 +00002928 return false;
2929
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002930 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002931 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
Alp Toker383d2c42014-01-01 03:08:43 +00002932 diag::err_expected_after)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002933 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
Richard Smith404dfb42013-11-19 22:47:36 +00002934
2935 // Try to recover from the typo, by dropping the tag definition and parsing
2936 // the problematic tokens as a type.
2937 //
2938 // FIXME: Split the DeclSpec into pieces for the standalone
2939 // declaration and pieces for the following declaration, instead
2940 // of assuming that all the other pieces attach to new declaration,
2941 // and call ParsedFreeStandingDeclSpec as appropriate.
2942 DS.ClearTypeSpecType();
2943 ParsedTemplateInfo NotATemplate;
Faisal Valia534f072018-04-26 00:42:40 +00002944 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
Richard Smith404dfb42013-11-19 22:47:36 +00002945 return false;
2946}
2947
Leonard Chanab80f3c2018-06-14 14:53:51 +00002948// Choose the apprpriate diagnostic error for why fixed point types are
2949// disabled, set the previous specifier, and mark as invalid.
2950static void SetupFixedPointError(const LangOptions &LangOpts,
2951 const char *&PrevSpec, unsigned &DiagID,
2952 bool &isInvalid) {
2953 assert(!LangOpts.FixedPoint);
2954 DiagID = diag::err_fixed_point_not_enabled;
2955 PrevSpec = ""; // Not used by diagnostic
2956 isInvalid = true;
2957}
2958
Faisal Valia534f072018-04-26 00:42:40 +00002959/// ParseDeclarationSpecifiers
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002960/// declaration-specifiers: [C99 6.7]
Chris Lattner3b561a32006-08-13 00:12:11 +00002961/// storage-class-specifier declaration-specifiers[opt]
2962/// type-specifier declaration-specifiers[opt]
Chris Lattner3b561a32006-08-13 00:12:11 +00002963/// [C99] function-specifier declaration-specifiers[opt]
Benjamin Kramere56f3932011-12-23 17:00:35 +00002964/// [C11] alignment-specifier declaration-specifiers[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002965/// [GNU] attributes declaration-specifiers[opt]
Douglas Gregor26701a42011-09-09 02:06:17 +00002966/// [Clang] '__module_private__' declaration-specifiers[opt]
Douglas Gregorab209d82015-07-07 03:58:42 +00002967/// [ObjC1] '__kindof' declaration-specifiers[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002968///
Chris Lattnerf63f89a2006-08-05 03:28:50 +00002969/// storage-class-specifier: [C99 6.7.1]
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002970/// 'typedef'
2971/// 'extern'
2972/// 'static'
2973/// 'auto'
2974/// 'register'
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002975/// [C++] 'mutable'
Richard Smithb4a9e862013-04-12 22:46:28 +00002976/// [C++11] 'thread_local'
2977/// [C11] '_Thread_local'
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002978/// [GNU] '__thread'
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002979/// function-specifier: [C99 6.7.4]
Chris Lattner3b561a32006-08-13 00:12:11 +00002980/// [C99] 'inline'
Douglas Gregor61956c42008-10-31 09:07:45 +00002981/// [C++] 'virtual'
2982/// [C++] 'explicit'
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00002983/// [OpenCL] '__kernel'
Anders Carlssoncd8db412009-05-06 04:46:28 +00002984/// 'friend': [C++ dcl.friend]
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00002985/// 'constexpr': [C++0x dcl.constexpr]
Faisal Valia534f072018-04-26 00:42:40 +00002986void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002987 const ParsedTemplateInfo &TemplateInfo,
John McCall07e91c02009-08-06 02:15:43 +00002988 AccessSpecifier AS,
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002989 DeclSpecContext DSContext,
2990 LateParsedAttrList *LateAttrs) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002991 if (DS.getSourceRange().isInvalid()) {
David Majnemer24b28302014-07-26 05:41:31 +00002992 // Start the range at the current token but make the end of the range
2993 // invalid. This will make the entire range invalid unless we successfully
2994 // consume a token.
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002995 DS.SetRangeStart(Tok.getLocation());
David Majnemer24b28302014-07-26 05:41:31 +00002996 DS.SetRangeEnd(SourceLocation());
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002997 }
Chad Rosierc1183952012-06-26 22:30:43 +00002998
Faisal Vali7db85c52017-12-31 00:06:40 +00002999 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3000 DSContext == DeclSpecContext::DSC_top_level);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003001 bool AttrsLastTime = false;
3002 ParsedAttributesWithRange attrs(AttrFactory);
Benjamin Kramere4812142015-03-12 14:28:38 +00003003 // We use Sema's policy to get bool macros right.
Richard Smith301bc212016-05-19 01:39:10 +00003004 PrintingPolicy Policy = Actions.getPrintingPolicy();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003005 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00003006 bool isInvalid = false;
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003007 bool isStorageClass = false;
Craig Topper161e4db2014-05-21 06:02:52 +00003008 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00003009 unsigned DiagID = 0;
3010
Richard Smithba24f352019-05-09 19:45:46 +00003011 // This value needs to be set to the location of the last token if the last
3012 // token of the specifier is already consumed.
3013 SourceLocation ConsumedEnd;
Richard Smith76b90272019-05-09 03:59:21 +00003014
David Majnemer51fd8a02015-07-22 23:46:18 +00003015 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3016 // implementation for VS2013 uses _Atomic as an identifier for one of the
3017 // classes in <atomic>.
3018 //
3019 // A typedef declaration containing _Atomic<...> is among the places where
3020 // the class is used. If we are currently parsing such a declaration, treat
3021 // the token as an identifier.
3022 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3023 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
3024 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3025 Tok.setKind(tok::identifier);
3026
Chris Lattner4d8f8732006-11-28 05:05:08 +00003027 SourceLocation Loc = Tok.getLocation();
Douglas Gregor450c75a2008-11-07 15:42:26 +00003028
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003029 switch (Tok.getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00003030 default:
Chris Lattner0974b232008-07-26 00:20:22 +00003031 DoneWithDeclSpec:
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003032 if (!AttrsLastTime)
3033 ProhibitAttributes(attrs);
Michael Han64536a62012-11-06 19:34:54 +00003034 else {
3035 // Reject C++11 attributes that appertain to decl specifiers as
3036 // we don't support any C++11 attributes that appertain to decl
3037 // specifiers. This also conforms to what g++ 4.8 is doing.
Richard Smith49cc1cc2016-08-18 21:59:42 +00003038 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
Michael Han64536a62012-11-06 19:34:54 +00003039
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003040 DS.takeAttributesFrom(attrs);
Michael Han64536a62012-11-06 19:34:54 +00003041 }
Peter Collingbourne70188b32011-09-29 18:03:57 +00003042
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003043 // If this is not a declaration specifier token, we're done reading decl
3044 // specifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00003045 DS.Finish(Actions, Policy);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003046 return;
Mike Stump11289f42009-09-09 15:08:12 +00003047
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003048 case tok::l_square:
3049 case tok::kw_alignas:
Aaron Ballman606093a2017-10-15 15:01:42 +00003050 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003051 goto DoneWithDeclSpec;
3052
3053 ProhibitAttributes(attrs);
3054 // FIXME: It would be good to recover by accepting the attributes,
3055 // but attempting to do that now would cause serious
3056 // madness in terms of diagnostics.
3057 attrs.clear();
3058 attrs.Range = SourceRange();
3059
3060 ParseCXX11Attributes(attrs);
3061 AttrsLastTime = true;
Chad Rosierc1183952012-06-26 22:30:43 +00003062 continue;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003063
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003064 case tok::code_completion: {
John McCallfaf5fb42010-08-26 23:41:50 +00003065 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003066 if (DS.hasTypeSpecifier()) {
3067 bool AllowNonIdentifiers
3068 = (getCurScope()->getFlags() & (Scope::ControlScope |
3069 Scope::BlockScope |
3070 Scope::TemplateParamScope |
3071 Scope::FunctionPrototypeScope |
3072 Scope::AtCatchScope)) == 0;
3073 bool AllowNestedNameSpecifiers
Faisal Vali7db85c52017-12-31 00:06:40 +00003074 = DSContext == DeclSpecContext::DSC_top_level ||
3075 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003076
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003077 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
Chad Rosierc1183952012-06-26 22:30:43 +00003078 AllowNonIdentifiers,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003079 AllowNestedNameSpecifiers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003080 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00003081 }
3082
Douglas Gregor80039242011-02-15 20:33:25 +00003083 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3084 CCC = Sema::PCC_LocalDeclarationSpecifiers;
3085 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
Faisal Vali7db85c52017-12-31 00:06:40 +00003086 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3087 : Sema::PCC_Template;
3088 else if (DSContext == DeclSpecContext::DSC_class)
John McCallfaf5fb42010-08-26 23:41:50 +00003089 CCC = Sema::PCC_Class;
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +00003090 else if (CurParsedObjCImpl)
John McCallfaf5fb42010-08-26 23:41:50 +00003091 CCC = Sema::PCC_ObjCImplementation;
Chad Rosierc1183952012-06-26 22:30:43 +00003092
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003093 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003094 return cutOffParsing();
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003095 }
3096
Chris Lattnerbd31aa32009-01-05 00:07:25 +00003097 case tok::coloncolon: // ::foo::bar
John McCall1f476a12010-02-26 08:45:28 +00003098 // C++ scope specifier. Annotate and loop, or bail out on error.
Eli Friedman2a1d9a92013-08-15 23:59:20 +00003099 if (TryAnnotateCXXScopeToken(EnteringContext)) {
John McCall1f476a12010-02-26 08:45:28 +00003100 if (!DS.hasTypeSpecifier())
3101 DS.SetTypeSpecError();
3102 goto DoneWithDeclSpec;
3103 }
John McCall8bc2a702010-03-01 18:20:46 +00003104 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3105 goto DoneWithDeclSpec;
John McCall1f476a12010-02-26 08:45:28 +00003106 continue;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003107
3108 case tok::annot_cxxscope: {
Richard Smith3092a3b2012-05-09 18:56:43 +00003109 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003110 goto DoneWithDeclSpec;
3111
John McCall9dab4e62009-12-12 11:40:51 +00003112 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00003113 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3114 Tok.getAnnotationRange(),
3115 SS);
John McCall9dab4e62009-12-12 11:40:51 +00003116
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003117 // We are looking for a qualified typename.
Douglas Gregor167fa622009-03-25 15:40:00 +00003118 Token Next = NextToken();
Mike Stump11289f42009-09-09 15:08:12 +00003119 if (Next.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003120 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
Douglas Gregorb67535d2009-03-31 00:43:58 +00003121 ->Kind == TNK_Type_template) {
Douglas Gregor167fa622009-03-25 15:40:00 +00003122 // We have a qualified template-id, e.g., N::A<int>
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003123
Richard Smith74f02342017-01-19 21:00:13 +00003124 // If this would be a valid constructor declaration with template
3125 // arguments, we will reject the attempt to form an invalid type-id
3126 // referring to the injected-class-name when we annotate the token,
3127 // per C++ [class.qual]p2.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003128 //
Richard Smith74f02342017-01-19 21:00:13 +00003129 // To improve diagnostics for this case, parse the declaration as a
3130 // constructor (and reject the extra template arguments later).
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003131 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
Faisal Vali7db85c52017-12-31 00:06:40 +00003132 if ((DSContext == DeclSpecContext::DSC_top_level ||
3133 DSContext == DeclSpecContext::DSC_class) &&
John McCall84821e72010-04-13 06:39:49 +00003134 TemplateId->Name &&
Richard Smith74f02342017-01-19 21:00:13 +00003135 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003136 isConstructorDeclarator(/*Unqualified*/ false)) {
Richard Smith74f02342017-01-19 21:00:13 +00003137 // The user meant this to be an out-of-line constructor
3138 // definition, but template arguments are not allowed
3139 // there. Just allow this as a constructor; we'll
3140 // complain about it later.
3141 goto DoneWithDeclSpec;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003142 }
3143
John McCall9dab4e62009-12-12 11:40:51 +00003144 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003145 ConsumeAnnotationToken(); // The C++ scope.
Mike Stump11289f42009-09-09 15:08:12 +00003146 assert(Tok.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003147 "ParseOptionalCXXScopeSpecifier not working");
Douglas Gregore7c20652011-03-02 00:47:37 +00003148 AnnotateTemplateIdTokenAsType();
Douglas Gregor167fa622009-03-25 15:40:00 +00003149 continue;
3150 }
3151
Douglas Gregorc5790df2009-09-28 07:26:33 +00003152 if (Next.is(tok::annot_typename)) {
John McCall9dab4e62009-12-12 11:40:51 +00003153 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003154 ConsumeAnnotationToken(); // The C++ scope.
John McCallba7bf592010-08-24 05:47:05 +00003155 if (Tok.getAnnotationValue()) {
3156 ParsedType T = getTypeAnnotation(Tok);
Nico Weber77430342010-11-22 10:30:56 +00003157 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
Chad Rosierc1183952012-06-26 22:30:43 +00003158 Tok.getAnnotationEndLoc(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003159 PrevSpec, DiagID, T, Policy);
Richard Smithda837032012-09-14 18:27:01 +00003160 if (isInvalid)
3161 break;
John McCallba7bf592010-08-24 05:47:05 +00003162 }
Douglas Gregorc5790df2009-09-28 07:26:33 +00003163 else
3164 DS.SetTypeSpecError();
3165 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003166 ConsumeAnnotationToken(); // The typename
Douglas Gregorc5790df2009-09-28 07:26:33 +00003167 }
3168
Douglas Gregor167fa622009-03-25 15:40:00 +00003169 if (Next.isNot(tok::identifier))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003170 goto DoneWithDeclSpec;
3171
Richard Smith74f02342017-01-19 21:00:13 +00003172 // Check whether this is a constructor declaration. If we're in a
3173 // context where the identifier could be a class name, and it has the
3174 // shape of a constructor declaration, process it as one.
Faisal Vali7db85c52017-12-31 00:06:40 +00003175 if ((DSContext == DeclSpecContext::DSC_top_level ||
3176 DSContext == DeclSpecContext::DSC_class) &&
Chad Rosierc1183952012-06-26 22:30:43 +00003177 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
Richard Smith74f02342017-01-19 21:00:13 +00003178 &SS) &&
3179 isConstructorDeclarator(/*Unqualified*/ false))
3180 goto DoneWithDeclSpec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003181
David Blaikieefdccaa2016-01-15 23:43:34 +00003182 ParsedType TypeRep =
3183 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3184 getCurScope(), &SS, false, false, nullptr,
3185 /*IsCtorOrDtorName=*/false,
Richard Smith600b5262017-01-26 20:40:47 +00003186 /*WantNonTrivialSourceInfo=*/true,
3187 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003188
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003189 // If the referenced identifier is not a type, then this declspec is
3190 // erroneous: We already checked about that it has no type specifier, and
3191 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
Mike Stump11289f42009-09-09 15:08:12 +00003192 // typename.
David Blaikie7d170102013-05-15 07:37:26 +00003193 if (!TypeRep) {
Richard Smithaf3b3252017-05-18 19:21:48 +00003194 // Eat the scope spec so the identifier is current.
3195 ConsumeAnnotationToken();
Michael Han9407e502012-11-26 22:54:45 +00003196 ParsedAttributesWithRange Attrs(AttrFactory);
3197 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3198 if (!Attrs.empty()) {
3199 AttrsLastTime = true;
3200 attrs.takeAllFrom(Attrs);
3201 }
3202 continue;
3203 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003204 goto DoneWithDeclSpec;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003205 }
Mike Stump11289f42009-09-09 15:08:12 +00003206
John McCall9dab4e62009-12-12 11:40:51 +00003207 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003208 ConsumeAnnotationToken(); // The C++ scope.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003209
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003210 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003211 DiagID, TypeRep, Policy);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003212 if (isInvalid)
3213 break;
Mike Stump11289f42009-09-09 15:08:12 +00003214
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003215 DS.SetRangeEnd(Tok.getLocation());
3216 ConsumeToken(); // The typename.
3217
3218 continue;
3219 }
Mike Stump11289f42009-09-09 15:08:12 +00003220
Chris Lattnere387d9e2009-01-21 19:48:37 +00003221 case tok::annot_typename: {
Richard Smith404dfb42013-11-19 22:47:36 +00003222 // If we've previously seen a tag definition, we were almost surely
3223 // missing a semicolon after it.
3224 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3225 goto DoneWithDeclSpec;
3226
John McCallba7bf592010-08-24 05:47:05 +00003227 if (Tok.getAnnotationValue()) {
3228 ParsedType T = getTypeAnnotation(Tok);
Nico Weber7f8bb362010-11-22 12:50:03 +00003229 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003230 DiagID, T, Policy);
John McCallba7bf592010-08-24 05:47:05 +00003231 } else
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003232 DS.SetTypeSpecError();
Chad Rosierc1183952012-06-26 22:30:43 +00003233
Chris Lattner005fc1b2010-04-05 18:18:31 +00003234 if (isInvalid)
3235 break;
3236
Chris Lattnere387d9e2009-01-21 19:48:37 +00003237 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003238 ConsumeAnnotationToken(); // The typename
Mike Stump11289f42009-09-09 15:08:12 +00003239
Chris Lattnere387d9e2009-01-21 19:48:37 +00003240 continue;
3241 }
Mike Stump11289f42009-09-09 15:08:12 +00003242
Douglas Gregor06873092011-04-28 15:48:45 +00003243 case tok::kw___is_signed:
3244 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3245 // typically treats it as a trait. If we see __is_signed as it appears
3246 // in libstdc++, e.g.,
3247 //
3248 // static const bool __is_signed;
3249 //
3250 // then treat __is_signed as an identifier rather than as a keyword.
Faisal Vali090da2d2018-01-01 18:23:28 +00003251 if (DS.getTypeSpecType() == TST_bool &&
Douglas Gregor06873092011-04-28 15:48:45 +00003252 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
Alp Toker47642d22013-12-03 06:13:01 +00003253 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3254 TryKeywordIdentFallback(true);
Douglas Gregor06873092011-04-28 15:48:45 +00003255
3256 // We're done with the declaration-specifiers.
3257 goto DoneWithDeclSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00003258
Chris Lattner16fac4f2008-07-26 01:18:38 +00003259 // typedef-name
Nikola Smiljanic67860242014-09-26 00:28:20 +00003260 case tok::kw___super:
David Blaikie15a430a2011-12-04 05:04:18 +00003261 case tok::kw_decltype:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003262 case tok::identifier: {
Reid Klecknerc582f012014-07-14 18:19:58 +00003263 // This identifier can only be a typedef name if we haven't already seen
3264 // a type-specifier. Without this check we misparse:
3265 // typedef int X; struct Y { short X; }; as 'short int'.
3266 if (DS.hasTypeSpecifier())
3267 goto DoneWithDeclSpec;
3268
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003269 // If the token is an identifier named "__declspec" and Microsoft
3270 // extensions are not enabled, it is likely that there will be cascading
3271 // parse errors if this really is a __declspec attribute. Attempt to
3272 // recognize that scenario and recover gracefully.
3273 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3274 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3275 Diag(Loc, diag::err_ms_attributes_not_enabled);
3276
3277 // The next token should be an open paren. If it is, eat the entire
3278 // attribute declaration and continue.
3279 if (NextToken().is(tok::l_paren)) {
3280 // Consume the __declspec identifier.
Richard Trieuba057372017-02-14 23:56:55 +00003281 ConsumeToken();
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003282
3283 // Eat the parens and everything between them.
3284 BalancedDelimiterTracker T(*this, tok::l_paren);
3285 if (T.consumeOpen()) {
3286 assert(false && "Not a left paren?");
3287 return;
3288 }
3289 T.skipToEnd();
3290 continue;
3291 }
3292 }
3293
Serge Pavlov458ea762014-07-16 05:16:52 +00003294 // In C++, check to see if this is a scope specifier like foo::bar::, if
3295 // so handle it as such. This is important for ctor parsing.
3296 if (getLangOpts().CPlusPlus) {
3297 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3298 DS.SetTypeSpecError();
3299 goto DoneWithDeclSpec;
3300 }
3301 if (!Tok.is(tok::identifier))
3302 continue;
3303 }
3304
John Thompson22334602010-02-05 00:12:22 +00003305 // Check for need to substitute AltiVec keyword tokens.
3306 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3307 break;
3308
Richard Smith3092a3b2012-05-09 18:56:43 +00003309 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3310 // allow the use of a typedef name as a type specifier.
3311 if (DS.isTypeAltiVecVector())
3312 goto DoneWithDeclSpec;
3313
Faisal Vali7db85c52017-12-31 00:06:40 +00003314 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3315 isObjCInstancetype()) {
Douglas Gregor5c0870a2015-06-19 23:18:00 +00003316 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3317 assert(TypeRep);
3318 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3319 DiagID, TypeRep, Policy);
3320 if (isInvalid)
3321 break;
3322
3323 DS.SetRangeEnd(Loc);
3324 ConsumeToken();
3325 continue;
3326 }
3327
Richard Smith715ee072018-06-20 21:58:20 +00003328 // If we're in a context where the identifier could be a class name,
3329 // check whether this is a constructor declaration.
3330 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3331 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3332 isConstructorDeclarator(/*Unqualified*/true))
3333 goto DoneWithDeclSpec;
3334
Richard Smith600b5262017-01-26 20:40:47 +00003335 ParsedType TypeRep = Actions.getTypeName(
3336 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3337 false, false, nullptr, false, false,
3338 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003339
Chris Lattner6cc055a2009-04-12 20:42:31 +00003340 // If this is not a typedef name, don't parse it as part of the declspec,
3341 // it must be an implicit int or an error.
John McCallba7bf592010-08-24 05:47:05 +00003342 if (!TypeRep) {
Michael Han9407e502012-11-26 22:54:45 +00003343 ParsedAttributesWithRange Attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +00003344 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
Michael Han9407e502012-11-26 22:54:45 +00003345 if (!Attrs.empty()) {
3346 AttrsLastTime = true;
3347 attrs.takeAllFrom(Attrs);
3348 }
3349 continue;
3350 }
Chris Lattner16fac4f2008-07-26 01:18:38 +00003351 goto DoneWithDeclSpec;
Chris Lattner6cc055a2009-04-12 20:42:31 +00003352 }
Douglas Gregor8bf42052009-02-09 18:46:07 +00003353
Richard Smith35845152017-02-07 01:37:30 +00003354 // Likewise, if this is a context where the identifier could be a template
3355 // name, check whether this is a deduction guide declaration.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003356 if (getLangOpts().CPlusPlus17 &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003357 (DSContext == DeclSpecContext::DSC_class ||
3358 DSContext == DeclSpecContext::DSC_top_level) &&
Richard Smith35845152017-02-07 01:37:30 +00003359 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3360 Tok.getLocation()) &&
3361 isConstructorDeclarator(/*Unqualified*/ true,
3362 /*DeductionGuide*/ true))
3363 goto DoneWithDeclSpec;
3364
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003365 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003366 DiagID, TypeRep, Policy);
Chris Lattner16fac4f2008-07-26 01:18:38 +00003367 if (isInvalid)
3368 break;
Mike Stump11289f42009-09-09 15:08:12 +00003369
Chris Lattner16fac4f2008-07-26 01:18:38 +00003370 DS.SetRangeEnd(Tok.getLocation());
3371 ConsumeToken(); // The identifier
3372
Douglas Gregore9d95f12015-07-07 03:57:35 +00003373 // Objective-C supports type arguments and protocol references
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003374 // following an Objective-C object or object pointer
3375 // type. Handle either one of them.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003376 if (Tok.is(tok::less) && getLangOpts().ObjC) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003377 SourceLocation NewEndLoc;
3378 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3379 Loc, TypeRep, /*consumeLastToken=*/true,
3380 NewEndLoc);
3381 if (NewTypeRep.isUsable()) {
3382 DS.UpdateTypeRep(NewTypeRep.get());
3383 DS.SetRangeEnd(NewEndLoc);
3384 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00003385 }
Chad Rosierc1183952012-06-26 22:30:43 +00003386
Steve Naroffcd5e7822008-09-22 10:28:57 +00003387 // Need to support trailing type qualifiers (e.g. "id<p> const").
3388 // If a type specifier follows, it will be diagnosed elsewhere.
3389 continue;
Chris Lattner16fac4f2008-07-26 01:18:38 +00003390 }
Douglas Gregor7f741122009-02-25 19:37:18 +00003391
3392 // type-name
3393 case tok::annot_template_id: {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003394 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithb23c5e82019-05-09 03:31:27 +00003395 if (TemplateId->Kind != TNK_Type_template &&
3396 TemplateId->Kind != TNK_Undeclared_template) {
Douglas Gregor7f741122009-02-25 19:37:18 +00003397 // This template-id does not refer to a type name, so we're
3398 // done with the type-specifiers.
3399 goto DoneWithDeclSpec;
3400 }
3401
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003402 // If we're in a context where the template-id could be a
3403 // constructor name or specialization, check whether this is a
3404 // constructor declaration.
Faisal Vali7db85c52017-12-31 00:06:40 +00003405 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00003406 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
Richard Smith446161b2014-03-03 21:12:53 +00003407 isConstructorDeclarator(TemplateId->SS.isEmpty()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003408 goto DoneWithDeclSpec;
3409
Douglas Gregor7f741122009-02-25 19:37:18 +00003410 // Turn the template-id annotation token into a type annotation
3411 // token, then try again to parse it as a type-specifier.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003412 AnnotateTemplateIdTokenAsType();
Douglas Gregor7f741122009-02-25 19:37:18 +00003413 continue;
3414 }
3415
Chris Lattnere37e2332006-08-15 04:50:22 +00003416 // GNU attributes support.
3417 case tok::kw___attribute:
Craig Topper161e4db2014-05-21 06:02:52 +00003418 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
Chris Lattnerb95cca02006-10-17 03:01:08 +00003419 continue;
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003420
3421 // Microsoft declspec support.
3422 case tok::kw___declspec:
Aaron Ballman068aa512015-05-20 20:58:33 +00003423 ParseMicrosoftDeclSpecs(DS.getAttributes());
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003424 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003425
Steve Naroff44ac7772008-12-25 14:16:32 +00003426 // Microsoft single token adornments.
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003427 case tok::kw___forceinline: {
Serge Pavlov750db652013-11-13 06:57:53 +00003428 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003429 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Richard Smithda837032012-09-14 18:27:01 +00003430 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00003431 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00003432 nullptr, 0, ParsedAttr::AS_Keyword);
Richard Smithda837032012-09-14 18:27:01 +00003433 break;
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003434 }
Eli Friedman53339e02009-06-08 23:27:34 +00003435
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003436 case tok::kw___unaligned:
3437 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3438 getLangOpts());
3439 break;
3440
Aaron Ballman317a77f2013-05-22 23:25:32 +00003441 case tok::kw___sptr:
3442 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00003443 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00003444 case tok::kw___ptr32:
Steve Narofff9c29d42008-12-25 14:41:26 +00003445 case tok::kw___w64:
Steve Naroff44ac7772008-12-25 14:16:32 +00003446 case tok::kw___cdecl:
3447 case tok::kw___stdcall:
3448 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00003449 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00003450 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00003451 case tok::kw___vectorcall:
John McCall53fa7142010-12-24 02:08:15 +00003452 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00003453 continue;
3454
Dawn Perchik335e16b2010-09-03 01:29:35 +00003455 // Borland single token adornments.
3456 case tok::kw___pascal:
John McCall53fa7142010-12-24 02:08:15 +00003457 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00003458 continue;
3459
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003460 // OpenCL single token adornments.
3461 case tok::kw___kernel:
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +00003462 ParseOpenCLKernelAttributes(DS.getAttributes());
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003463 continue;
3464
Douglas Gregor261a89b2015-06-19 17:51:05 +00003465 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00003466 case tok::kw__Nonnull:
3467 case tok::kw__Nullable:
3468 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00003469 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3470 continue;
3471
Douglas Gregorab209d82015-07-07 03:58:42 +00003472 // Objective-C 'kindof' types.
3473 case tok::kw___kindof:
3474 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00003475 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00003476 (void)ConsumeToken();
3477 continue;
3478
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003479 // storage-class-specifier
3480 case tok::kw_typedef:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003481 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003482 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003483 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003484 break;
3485 case tok::kw_extern:
Richard Smithb4a9e862013-04-12 22:46:28 +00003486 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003487 Diag(Tok, diag::ext_thread_before) << "extern";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003488 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003489 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003490 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003491 break;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003492 case tok::kw___private_extern__:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003493 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003494 Loc, PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003495 isStorageClass = true;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003496 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003497 case tok::kw_static:
Richard Smithb4a9e862013-04-12 22:46:28 +00003498 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003499 Diag(Tok, diag::ext_thread_before) << "static";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003500 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003501 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003502 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003503 break;
3504 case tok::kw_auto:
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003505 if (getLangOpts().CPlusPlus11) {
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003506 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003507 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003508 PrevSpec, DiagID, Policy);
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003509 if (!isInvalid)
Richard Smith58c74332011-09-04 19:54:14 +00003510 Diag(Tok, diag::ext_auto_storage_class)
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003511 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith58c74332011-09-04 19:54:14 +00003512 } else
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003513 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003514 DiagID, Policy);
Richard Smith58c74332011-09-04 19:54:14 +00003515 } else
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003516 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003517 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003518 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003519 break;
Richard Smithe301ba22015-11-11 02:02:15 +00003520 case tok::kw___auto_type:
3521 Diag(Tok, diag::ext_auto_type);
3522 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3523 DiagID, Policy);
3524 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003525 case tok::kw_register:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003526 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003527 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003528 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003529 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003530 case tok::kw_mutable:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003531 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003532 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003533 isStorageClass = true;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003534 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003535 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00003536 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3537 PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003538 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003539 break;
3540 case tok::kw_thread_local:
3541 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3542 PrevSpec, DiagID);
Sven van Haastregtc4100832018-04-24 14:47:29 +00003543 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003544 break;
3545 case tok::kw__Thread_local:
3546 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3547 Loc, PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003548 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003549 break;
Mike Stump11289f42009-09-09 15:08:12 +00003550
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003551 // function-specifier
3552 case tok::kw_inline:
Serge Pavlov750db652013-11-13 06:57:53 +00003553 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003554 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003555 case tok::kw_virtual:
Sven van Haastregt49ffffb2018-04-23 11:23:47 +00003556 // OpenCL C++ v1.0 s2.9: the virtual function qualifier is not supported.
3557 if (getLangOpts().OpenCLCPlusPlus) {
3558 DiagID = diag::err_openclcxx_virtual_function;
3559 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3560 isInvalid = true;
3561 }
3562 else {
3563 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3564 }
Douglas Gregor61956c42008-10-31 09:07:45 +00003565 break;
Richard Smith76b90272019-05-09 03:59:21 +00003566 case tok::kw_explicit: {
3567 SourceLocation ExplicitLoc = Loc;
3568 SourceLocation CloseParenLoc;
3569 ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
Richard Smithba24f352019-05-09 19:45:46 +00003570 ConsumedEnd = ExplicitLoc;
Richard Smith76b90272019-05-09 03:59:21 +00003571 ConsumeToken(); // kw_explicit
3572 if (Tok.is(tok::l_paren)) {
3573 if (getLangOpts().CPlusPlus2a) {
3574 ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3575 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3576 Tracker.consumeOpen();
3577 ExplicitExpr = ParseConstantExpression();
Richard Smithba24f352019-05-09 19:45:46 +00003578 ConsumedEnd = Tok.getLocation();
Richard Smith76b90272019-05-09 03:59:21 +00003579 if (ExplicitExpr.isUsable()) {
3580 CloseParenLoc = Tok.getLocation();
3581 Tracker.consumeClose();
3582 ExplicitSpec =
3583 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3584 } else
3585 Tracker.skipToEnd();
3586 } else
3587 Diag(Tok.getLocation(), diag::warn_cxx2a_compat_explicit_bool);
3588 }
3589 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3590 ExplicitSpec, CloseParenLoc);
Douglas Gregor61956c42008-10-31 09:07:45 +00003591 break;
Richard Smith76b90272019-05-09 03:59:21 +00003592 }
Richard Smith0015f092013-01-17 22:16:11 +00003593 case tok::kw__Noreturn:
3594 if (!getLangOpts().C11)
3595 Diag(Loc, diag::ext_c11_noreturn);
Serge Pavlov750db652013-11-13 06:57:53 +00003596 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
Richard Smith0015f092013-01-17 22:16:11 +00003597 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003598
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003599 // alignment-specifier
3600 case tok::kw__Alignas:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003601 if (!getLangOpts().C11)
Jordan Rose58d54722012-06-30 21:33:57 +00003602 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003603 ParseAlignmentSpecifier(DS.getAttributes());
3604 continue;
3605
Anders Carlssoncd8db412009-05-06 04:46:28 +00003606 // friend
3607 case tok::kw_friend:
Faisal Vali7db85c52017-12-31 00:06:40 +00003608 if (DSContext == DeclSpecContext::DSC_class)
John McCall07e91c02009-08-06 02:15:43 +00003609 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3610 else {
3611 PrevSpec = ""; // not actually used by the diagnostic
3612 DiagID = diag::err_friend_invalid_in_context;
3613 isInvalid = true;
3614 }
Anders Carlssoncd8db412009-05-06 04:46:28 +00003615 break;
Mike Stump11289f42009-09-09 15:08:12 +00003616
Douglas Gregor26701a42011-09-09 02:06:17 +00003617 // Modules
3618 case tok::kw___module_private__:
3619 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3620 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003621
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00003622 // constexpr
3623 case tok::kw_constexpr:
3624 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3625 break;
3626
Chris Lattnere387d9e2009-01-21 19:48:37 +00003627 // type-specifier
3628 case tok::kw_short:
John McCall49bfce42009-08-03 20:12:06 +00003629 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003630 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003631 break;
3632 case tok::kw_long:
3633 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
John McCall49bfce42009-08-03 20:12:06 +00003634 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003635 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003636 else
John McCall49bfce42009-08-03 20:12:06 +00003637 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003638 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003639 break;
Francois Pichet84133e42011-04-28 01:59:37 +00003640 case tok::kw___int64:
3641 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003642 DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00003643 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003644 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00003645 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3646 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003647 break;
3648 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00003649 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3650 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003651 break;
3652 case tok::kw__Complex:
John McCall49bfce42009-08-03 20:12:06 +00003653 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3654 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003655 break;
3656 case tok::kw__Imaginary:
John McCall49bfce42009-08-03 20:12:06 +00003657 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3658 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003659 break;
3660 case tok::kw_void:
John McCall49bfce42009-08-03 20:12:06 +00003661 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003662 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003663 break;
3664 case tok::kw_char:
John McCall49bfce42009-08-03 20:12:06 +00003665 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003666 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003667 break;
3668 case tok::kw_int:
John McCall49bfce42009-08-03 20:12:06 +00003669 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003670 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003671 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00003672 case tok::kw___int128:
3673 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003674 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003675 break;
3676 case tok::kw_half:
3677 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003678 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003679 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003680 case tok::kw_float:
John McCall49bfce42009-08-03 20:12:06 +00003681 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003682 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003683 break;
3684 case tok::kw_double:
John McCall49bfce42009-08-03 20:12:06 +00003685 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003686 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003687 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00003688 case tok::kw__Float16:
3689 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3690 DiagID, Policy);
3691 break;
Leonard Chanf921d852018-06-04 16:07:52 +00003692 case tok::kw__Accum:
3693 if (!getLangOpts().FixedPoint) {
Leonard Chanab80f3c2018-06-14 14:53:51 +00003694 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
Leonard Chanf921d852018-06-04 16:07:52 +00003695 } else {
3696 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3697 DiagID, Policy);
3698 }
3699 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00003700 case tok::kw__Fract:
3701 if (!getLangOpts().FixedPoint) {
3702 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3703 } else {
3704 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3705 DiagID, Policy);
3706 }
3707 break;
3708 case tok::kw__Sat:
3709 if (!getLangOpts().FixedPoint) {
3710 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3711 } else {
3712 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3713 }
3714 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003715 case tok::kw___float128:
3716 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3717 DiagID, Policy);
3718 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003719 case tok::kw_wchar_t:
John McCall49bfce42009-08-03 20:12:06 +00003720 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003721 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003722 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00003723 case tok::kw_char8_t:
3724 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3725 DiagID, Policy);
3726 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003727 case tok::kw_char16_t:
John McCall49bfce42009-08-03 20:12:06 +00003728 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003729 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003730 break;
3731 case tok::kw_char32_t:
John McCall49bfce42009-08-03 20:12:06 +00003732 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003733 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003734 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003735 case tok::kw_bool:
3736 case tok::kw__Bool:
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003737 if (Tok.is(tok::kw_bool) &&
3738 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3739 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3740 PrevSpec = ""; // Not used by the diagnostic.
3741 DiagID = diag::err_bool_redeclaration;
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003742 // For better error recovery.
3743 Tok.setKind(tok::identifier);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003744 isInvalid = true;
3745 } else {
3746 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003747 DiagID, Policy);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003748 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003749 break;
3750 case tok::kw__Decimal32:
John McCall49bfce42009-08-03 20:12:06 +00003751 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003752 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003753 break;
3754 case tok::kw__Decimal64:
John McCall49bfce42009-08-03 20:12:06 +00003755 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003756 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003757 break;
3758 case tok::kw__Decimal128:
John McCall49bfce42009-08-03 20:12:06 +00003759 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003760 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003761 break;
John Thompson22334602010-02-05 00:12:22 +00003762 case tok::kw___vector:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003763 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003764 break;
3765 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003766 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003767 break;
Bill Seurercf2c96b2015-01-12 19:35:51 +00003768 case tok::kw___bool:
3769 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3770 break;
Xiuli Pan9c14e282016-01-09 12:53:17 +00003771 case tok::kw_pipe:
3772 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3773 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3774 // support the "pipe" word as identifier.
3775 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3776 goto DoneWithDeclSpec;
3777 }
3778 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3779 break;
Alexey Bader954ba212016-04-08 13:40:33 +00003780#define GENERIC_IMAGE_TYPE(ImgType, Id) \
3781 case tok::kw_##ImgType##_t: \
3782 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3783 DiagID, Policy); \
3784 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00003785#include "clang/Basic/OpenCLImageTypes.def"
John McCall39439732011-04-09 22:50:59 +00003786 case tok::kw___unknown_anytype:
Faisal Vali090da2d2018-01-01 18:23:28 +00003787 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003788 PrevSpec, DiagID, Policy);
John McCall39439732011-04-09 22:50:59 +00003789 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003790
3791 // class-specifier:
3792 case tok::kw_class:
3793 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00003794 case tok::kw___interface:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003795 case tok::kw_union: {
3796 tok::TokenKind Kind = Tok.getKind();
3797 ConsumeToken();
Michael Han9407e502012-11-26 22:54:45 +00003798
3799 // These are attributes following class specifiers.
3800 // To produce better diagnostic, we parse them when
3801 // parsing class specifier.
Bill Wendling44426052012-12-20 19:22:21 +00003802 ParsedAttributesWithRange Attributes(AttrFactory);
Richard Smithc5b05522012-03-12 07:56:15 +00003803 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
Bill Wendling44426052012-12-20 19:22:21 +00003804 EnteringContext, DSContext, Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003805
3806 // If there are attributes following class specifier,
3807 // take them over and handle them here.
Bill Wendling44426052012-12-20 19:22:21 +00003808 if (!Attributes.empty()) {
Michael Han9407e502012-11-26 22:54:45 +00003809 AttrsLastTime = true;
Bill Wendling44426052012-12-20 19:22:21 +00003810 attrs.takeAllFrom(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003811 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003812 continue;
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003813 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003814
3815 // enum-specifier:
3816 case tok::kw_enum:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003817 ConsumeToken();
Richard Smithc5b05522012-03-12 07:56:15 +00003818 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003819 continue;
Faisal Valia534f072018-04-26 00:42:40 +00003820
Chris Lattnere387d9e2009-01-21 19:48:37 +00003821 // cv-qualifier:
3822 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00003823 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003824 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003825 break;
3826 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00003827 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003828 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003829 break;
3830 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00003831 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003832 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003833 break;
3834
Douglas Gregor333489b2009-03-27 23:10:48 +00003835 // C++ typename-specifier:
3836 case tok::kw_typename:
John McCall1f476a12010-02-26 08:45:28 +00003837 if (TryAnnotateTypeOrScopeToken()) {
3838 DS.SetTypeSpecError();
3839 goto DoneWithDeclSpec;
3840 }
3841 if (!Tok.is(tok::kw_typename))
Douglas Gregor333489b2009-03-27 23:10:48 +00003842 continue;
3843 break;
3844
Chris Lattnere387d9e2009-01-21 19:48:37 +00003845 // GNU typeof support.
3846 case tok::kw_typeof:
3847 ParseTypeofSpecifier(DS);
3848 continue;
3849
David Blaikie15a430a2011-12-04 05:04:18 +00003850 case tok::annot_decltype:
Anders Carlsson74948d02009-06-24 17:47:40 +00003851 ParseDecltypeSpecifier(DS);
3852 continue;
3853
David Majnemer15b311c2016-06-14 03:20:28 +00003854 case tok::annot_pragma_pack:
3855 HandlePragmaPack();
3856 continue;
3857
3858 case tok::annot_pragma_ms_pragma:
3859 HandlePragmaMSPragma();
3860 continue;
3861
3862 case tok::annot_pragma_ms_vtordisp:
3863 HandlePragmaMSVtorDisp();
3864 continue;
3865
3866 case tok::annot_pragma_ms_pointers_to_members:
3867 HandlePragmaMSPointersToMembers();
3868 continue;
3869
Alexis Hunt4a257072011-05-19 05:37:45 +00003870 case tok::kw___underlying_type:
3871 ParseUnderlyingTypeSpecifier(DS);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003872 continue;
3873
3874 case tok::kw__Atomic:
Richard Smith8e1ac332013-03-28 01:55:44 +00003875 // C11 6.7.2.4/4:
3876 // If the _Atomic keyword is immediately followed by a left parenthesis,
3877 // it is interpreted as a type specifier (with a type name), not as a
3878 // type qualifier.
3879 if (NextToken().is(tok::l_paren)) {
3880 ParseAtomicSpecifier(DS);
3881 continue;
3882 }
3883 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3884 getLangOpts());
3885 break;
Alexis Hunt4a257072011-05-19 05:37:45 +00003886
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003887 // OpenCL address space qualifiers:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003888 case tok::kw___generic:
3889 // generic address space is introduced only in OpenCL v2.0
3890 // see OpenCL C Spec v2.0 s6.5.5
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003891 if (Actions.getLangOpts().OpenCLVersion < 200 &&
3892 !Actions.getLangOpts().OpenCLCPlusPlus) {
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003893 DiagID = diag::err_opencl_unknown_type_specifier;
3894 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3895 isInvalid = true;
3896 break;
3897 };
Galina Kistanova77674252017-06-01 21:15:34 +00003898 LLVM_FALLTHROUGH;
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003899 case tok::kw_private:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003900 case tok::kw___private:
3901 case tok::kw___global:
3902 case tok::kw___local:
3903 case tok::kw___constant:
Anastasia Stulova2c4730d2019-02-15 12:07:57 +00003904 // OpenCL access qualifiers:
3905 case tok::kw___read_only:
3906 case tok::kw___write_only:
3907 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00003908 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003909 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003910
Steve Naroffcfdf6162008-06-05 00:02:44 +00003911 case tok::less:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003912 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
Chris Lattner0974b232008-07-26 00:20:22 +00003913 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3914 // but we support it.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003915 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
Chris Lattner0974b232008-07-26 00:20:22 +00003916 goto DoneWithDeclSpec;
Mike Stump11289f42009-09-09 15:08:12 +00003917
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003918 SourceLocation StartLoc = Tok.getLocation();
3919 SourceLocation EndLoc;
3920 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3921 if (Type.isUsable()) {
3922 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3923 PrevSpec, DiagID, Type.get(),
3924 Actions.getASTContext().getPrintingPolicy()))
3925 Diag(StartLoc, DiagID) << PrevSpec;
Fangrui Song6907ce22018-07-30 19:24:48 +00003926
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003927 DS.SetRangeEnd(EndLoc);
3928 } else {
3929 DS.SetTypeSpecError();
3930 }
Chad Rosierc1183952012-06-26 22:30:43 +00003931
Douglas Gregor06e41ae2010-10-21 23:17:00 +00003932 // Need to support trailing type qualifiers (e.g. "id<p> const").
3933 // If a type specifier follows, it will be diagnosed elsewhere.
3934 continue;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003935 }
Richard Smith76b90272019-05-09 03:59:21 +00003936
Richard Smithba24f352019-05-09 19:45:46 +00003937 DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
Richard Smith76b90272019-05-09 03:59:21 +00003938
John McCall49bfce42009-08-03 20:12:06 +00003939 // If the specifier wasn't legal, issue a diagnostic.
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003940 if (isInvalid) {
3941 assert(PrevSpec && "Method did not return previous specifier!");
John McCall49bfce42009-08-03 20:12:06 +00003942 assert(DiagID);
Chad Rosierc1183952012-06-26 22:30:43 +00003943
Nick Desaulniers150ca532018-10-03 23:09:29 +00003944 if (DiagID == diag::ext_duplicate_declspec ||
Richard Smith76b90272019-05-09 03:59:21 +00003945 DiagID == diag::ext_warn_duplicate_declspec ||
3946 DiagID == diag::err_duplicate_declspec)
3947 Diag(Loc, DiagID) << PrevSpec
3948 << FixItHint::CreateRemoval(
3949 SourceRange(Loc, DS.getEndLoc()));
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003950 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
Richard Smith76b90272019-05-09 03:59:21 +00003951 Diag(Loc, DiagID) << getLangOpts().OpenCLCPlusPlus
3952 << getLangOpts().getOpenCLVersionTuple().getAsString()
3953 << PrevSpec << isStorageClass;
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003954 } else
Richard Smith76b90272019-05-09 03:59:21 +00003955 Diag(Loc, DiagID) << PrevSpec;
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003956 }
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003957
Richard Smithba24f352019-05-09 19:45:46 +00003958 if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
Volodymyr Sapsai9f7b5cc2018-04-10 18:29:47 +00003959 // After an error the next token can be an annotation token.
3960 ConsumeAnyToken();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003961
3962 AttrsLastTime = false;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003963 }
3964}
Douglas Gregoreb31f392008-12-01 23:54:00 +00003965
Chris Lattner70ae4912007-10-29 04:42:53 +00003966/// ParseStructDeclaration - Parse a struct declaration without the terminating
3967/// semicolon.
3968///
Nico Weber98dd0852019-03-14 14:18:56 +00003969/// Note that a struct declaration refers to a declaration in a struct,
3970/// not to the declaration of a struct.
3971///
Chris Lattner90a26b02007-01-23 04:38:16 +00003972/// struct-declaration:
Aaron Ballman606093a2017-10-15 15:01:42 +00003973/// [C2x] attributes-specifier-seq[opt]
3974/// specifier-qualifier-list struct-declarator-list
Chris Lattner736ed5d2007-06-09 05:59:07 +00003975/// [GNU] __extension__ struct-declaration
Chris Lattner70ae4912007-10-29 04:42:53 +00003976/// [GNU] specifier-qualifier-list
Chris Lattner90a26b02007-01-23 04:38:16 +00003977/// struct-declarator-list:
3978/// struct-declarator
3979/// struct-declarator-list ',' struct-declarator
3980/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3981/// struct-declarator:
3982/// declarator
3983/// [GNU] declarator attributes[opt]
3984/// declarator[opt] ':' constant-expression
3985/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3986///
Benjamin Kramera39beb92014-09-03 11:06:10 +00003987void Parser::ParseStructDeclaration(
3988 ParsingDeclSpec &DS,
3989 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
Chad Rosierc1183952012-06-26 22:30:43 +00003990
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003991 if (Tok.is(tok::kw___extension__)) {
3992 // __extension__ silences extension warnings in the subexpression.
3993 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Steve Naroff97170802007-08-20 22:28:22 +00003994 ConsumeToken();
Benjamin Kramera39beb92014-09-03 11:06:10 +00003995 return ParseStructDeclaration(DS, FieldsCallback);
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003996 }
Mike Stump11289f42009-09-09 15:08:12 +00003997
Aaron Ballman606093a2017-10-15 15:01:42 +00003998 // Parse leading attributes.
3999 ParsedAttributesWithRange Attrs(AttrFactory);
4000 MaybeParseCXX11Attributes(Attrs);
4001 DS.takeAttributesFrom(Attrs);
4002
Steve Naroff97170802007-08-20 22:28:22 +00004003 // Parse the common specifier-qualifiers-list piece.
Steve Naroff97170802007-08-20 22:28:22 +00004004 ParseSpecifierQualifierList(DS);
Mike Stump11289f42009-09-09 15:08:12 +00004005
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00004006 // If there are no declarators, this is a free-standing declaration
4007 // specifier. Let the actions module cope with it.
Chris Lattner76c72282007-10-09 17:33:22 +00004008 if (Tok.is(tok::semi)) {
Nico Weber7b837f52016-01-28 19:25:00 +00004009 RecordDecl *AnonRecord = nullptr;
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004010 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00004011 DS, AnonRecord);
4012 assert(!AnonRecord && "Did not expect anonymous struct or union here");
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004013 DS.complete(TheDecl);
Steve Naroff97170802007-08-20 22:28:22 +00004014 return;
4015 }
4016
4017 // Read struct-declarators until we find the semicolon.
John McCallcfefb6d2009-11-03 02:38:08 +00004018 bool FirstDeclarator = true;
Richard Smith8d06f422012-01-12 23:53:29 +00004019 SourceLocation CommaLoc;
Steve Naroff97170802007-08-20 22:28:22 +00004020 while (1) {
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004021 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
Richard Smith8d06f422012-01-12 23:53:29 +00004022 DeclaratorInfo.D.setCommaLoc(CommaLoc);
John McCallcfefb6d2009-11-03 02:38:08 +00004023
Bill Wendling44426052012-12-20 19:22:21 +00004024 // Attributes are only allowed here on successive declarators.
John McCall53fa7142010-12-24 02:08:15 +00004025 if (!FirstDeclarator)
4026 MaybeParseGNUAttributes(DeclaratorInfo.D);
Mike Stump11289f42009-09-09 15:08:12 +00004027
Steve Naroff97170802007-08-20 22:28:22 +00004028 /// struct-declarator: declarator
4029 /// struct-declarator: declarator[opt] ':' constant-expression
Chris Lattner17c3b1f2009-12-10 01:59:24 +00004030 if (Tok.isNot(tok::colon)) {
4031 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4032 ColonProtectionRAIIObject X(*this);
Chris Lattnera12405b2008-04-10 06:46:29 +00004033 ParseDeclarator(DeclaratorInfo.D);
Richard Smith3d1a94c2014-08-12 00:22:39 +00004034 } else
4035 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004036
Alp Toker8fbec672013-12-17 23:29:36 +00004037 if (TryConsumeToken(tok::colon)) {
John McCalldadc5752010-08-24 06:29:42 +00004038 ExprResult Res(ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004039 if (Res.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00004040 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner32295d32008-04-10 06:15:14 +00004041 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004042 DeclaratorInfo.BitfieldSize = Res.get();
Steve Naroff97170802007-08-20 22:28:22 +00004043 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004044
Steve Naroff97170802007-08-20 22:28:22 +00004045 // If attributes exist after the declarator, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004046 MaybeParseGNUAttributes(DeclaratorInfo.D);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004047
John McCallcfefb6d2009-11-03 02:38:08 +00004048 // We're done with this declarator; invoke the callback.
Benjamin Kramera39beb92014-09-03 11:06:10 +00004049 FieldsCallback(DeclaratorInfo);
John McCallcfefb6d2009-11-03 02:38:08 +00004050
Steve Naroff97170802007-08-20 22:28:22 +00004051 // If we don't have a comma, it is either the end of the list (a ';')
4052 // or an error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00004053 if (!TryConsumeToken(tok::comma, CommaLoc))
Chris Lattner70ae4912007-10-29 04:42:53 +00004054 return;
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004055
John McCallcfefb6d2009-11-03 02:38:08 +00004056 FirstDeclarator = false;
Steve Naroff97170802007-08-20 22:28:22 +00004057 }
Steve Naroff97170802007-08-20 22:28:22 +00004058}
4059
4060/// ParseStructUnionBody
4061/// struct-contents:
4062/// struct-declaration-list
4063/// [EXT] empty
4064/// [GNU] "struct-declaration-list" without terminatoring ';'
4065/// struct-declaration-list:
4066/// struct-declaration
4067/// struct-declaration-list struct-declaration
Chris Lattner535b8302008-06-21 19:39:06 +00004068/// [OBC] '@' 'defs' '(' class-name ')'
Steve Naroff97170802007-08-20 22:28:22 +00004069///
Chris Lattner1300fb92007-01-23 23:42:53 +00004070void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00004071 unsigned TagType, Decl *TagDecl) {
Jordan Rose1e879d82018-03-23 00:07:18 +00004072 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00004073 "parsing struct/union body");
Andy Gibbs22e140b2013-04-03 09:31:19 +00004074 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
Mike Stump11289f42009-09-09 15:08:12 +00004075
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004076 BalancedDelimiterTracker T(*this, tok::l_brace);
4077 if (T.consumeOpen())
4078 return;
Mike Stump11289f42009-09-09 15:08:12 +00004079
Douglas Gregor658b9552009-01-09 22:42:13 +00004080 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004081 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004082
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004083 SmallVector<Decl *, 32> FieldDecls;
Chris Lattnera12405b2008-04-10 06:46:29 +00004084
Chris Lattner7b9ace62007-01-23 20:11:08 +00004085 // While we still have something to read, read the declarations in the struct.
Richard Smith752ada82015-11-17 23:32:01 +00004086 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4087 Tok.isNot(tok::eof)) {
Chris Lattner90a26b02007-01-23 04:38:16 +00004088 // Each iteration of this loop reads one struct-declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004089
Chris Lattner736ed5d2007-06-09 05:59:07 +00004090 // Check for extraneous top-level semicolon.
Chris Lattner76c72282007-10-09 17:33:22 +00004091 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004092 ConsumeExtraSemi(InsideStruct, TagType);
Chris Lattner36e46a22007-06-09 05:49:55 +00004093 continue;
4094 }
Chris Lattnera12405b2008-04-10 06:46:29 +00004095
Andy Gibbsc804e082013-04-03 09:46:04 +00004096 // Parse _Static_assert declaration.
4097 if (Tok.is(tok::kw__Static_assert)) {
4098 SourceLocation DeclEnd;
4099 ParseStaticAssertDeclaration(DeclEnd);
4100 continue;
4101 }
4102
Argyrios Kyrtzidis71c12fb2013-04-18 01:42:35 +00004103 if (Tok.is(tok::annot_pragma_pack)) {
4104 HandlePragmaPack();
4105 continue;
4106 }
4107
4108 if (Tok.is(tok::annot_pragma_align)) {
4109 HandlePragmaAlign();
4110 continue;
4111 }
4112
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004113 if (Tok.is(tok::annot_pragma_openmp)) {
Alexey Bataev587e1de2016-03-30 10:43:55 +00004114 // Result can be ignored, because it must be always empty.
4115 AccessSpecifier AS = AS_none;
4116 ParsedAttributesWithRange Attrs(AttrFactory);
4117 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004118 continue;
4119 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004120
John McCallcfefb6d2009-11-03 02:38:08 +00004121 if (!Tok.is(tok::at)) {
Benjamin Kramera39beb92014-09-03 11:06:10 +00004122 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4123 // Install the declarator into the current TagDecl.
4124 Decl *Field =
4125 Actions.ActOnField(getCurScope(), TagDecl,
4126 FD.D.getDeclSpec().getSourceRange().getBegin(),
4127 FD.D, FD.BitfieldSize);
4128 FieldDecls.push_back(Field);
4129 FD.complete(Field);
4130 };
John McCallcfefb6d2009-11-03 02:38:08 +00004131
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004132 // Parse all the comma separated declarators.
4133 ParsingDeclSpec DS(*this);
Benjamin Kramera39beb92014-09-03 11:06:10 +00004134 ParseStructDeclaration(DS, CFieldCallback);
Chris Lattner535b8302008-06-21 19:39:06 +00004135 } else { // Handle @defs
4136 ConsumeToken();
4137 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4138 Diag(Tok, diag::err_unexpected_at);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004139 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004140 continue;
4141 }
4142 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004143 ExpectAndConsume(tok::l_paren);
Chris Lattner535b8302008-06-21 19:39:06 +00004144 if (!Tok.is(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004145 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004146 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004147 continue;
4148 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004149 SmallVector<Decl *, 16> Fields;
Douglas Gregor0be31a22010-07-02 17:43:08 +00004150 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004151 Tok.getIdentifierInfo(), Fields);
Chris Lattner535b8302008-06-21 19:39:06 +00004152 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4153 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004154 ExpectAndConsume(tok::r_paren);
Mike Stump11289f42009-09-09 15:08:12 +00004155 }
Chris Lattner736ed5d2007-06-09 05:59:07 +00004156
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004157 if (TryConsumeToken(tok::semi))
4158 continue;
4159
4160 if (Tok.is(tok::r_brace)) {
Chris Lattner245c5332010-02-02 00:37:27 +00004161 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
Chris Lattner0c7e82d2007-06-09 05:54:40 +00004162 break;
Chris Lattner90a26b02007-01-23 04:38:16 +00004163 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004164
4165 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4166 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4167 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4168 // If we stopped at a ';', eat it.
4169 TryConsumeToken(tok::semi);
Chris Lattner90a26b02007-01-23 04:38:16 +00004170 }
Mike Stump11289f42009-09-09 15:08:12 +00004171
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004172 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +00004173
John McCall084e83d2011-03-24 11:26:52 +00004174 ParsedAttributes attrs(AttrFactory);
Chris Lattner90a26b02007-01-23 04:38:16 +00004175 // If attributes exist after struct contents, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004176 MaybeParseGNUAttributes(attrs);
Daniel Dunbar15619c72008-10-03 02:03:53 +00004177
Erich Keanec480f302018-07-12 21:09:05 +00004178 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4179 T.getOpenLocation(), T.getCloseLocation(), attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004180 StructScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004181 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
Chris Lattner90a26b02007-01-23 04:38:16 +00004182}
4183
Chris Lattner3b561a32006-08-13 00:12:11 +00004184/// ParseEnumSpecifier
Chris Lattner1890ac82006-08-13 01:16:23 +00004185/// enum-specifier: [C99 6.7.2.2]
Chris Lattner3b561a32006-08-13 00:12:11 +00004186/// 'enum' identifier[opt] '{' enumerator-list '}'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004187///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
Chris Lattnere37e2332006-08-15 04:50:22 +00004188/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4189/// '}' attributes[opt]
Aaron Ballman9ecff022012-03-01 04:09:28 +00004190/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4191/// '}'
Chris Lattner3b561a32006-08-13 00:12:11 +00004192/// 'enum' identifier
Chris Lattnere37e2332006-08-15 04:50:22 +00004193/// [GNU] 'enum' attributes[opt] identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004194///
Richard Smith7d137e32012-03-23 03:33:32 +00004195/// [C++11] enum-head '{' enumerator-list[opt] '}'
4196/// [C++11] enum-head '{' enumerator-list ',' '}'
Douglas Gregor0bf31402010-10-08 23:50:27 +00004197///
Richard Smith7d137e32012-03-23 03:33:32 +00004198/// enum-head: [C++11]
4199/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4200/// enum-key attribute-specifier-seq[opt] nested-name-specifier
4201/// identifier enum-base[opt]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004202///
Richard Smith7d137e32012-03-23 03:33:32 +00004203/// enum-key: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004204/// 'enum'
4205/// 'enum' 'class'
4206/// 'enum' 'struct'
4207///
Richard Smith7d137e32012-03-23 03:33:32 +00004208/// enum-base: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004209/// ':' type-specifier-seq
4210///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004211/// [C++] elaborated-type-specifier:
4212/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4213///
Chris Lattnerffaa0e62009-04-12 21:49:30 +00004214void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregordc70c3a2010-03-02 17:53:14 +00004215 const ParsedTemplateInfo &TemplateInfo,
Richard Smithc5b05522012-03-12 07:56:15 +00004216 AccessSpecifier AS, DeclSpecContext DSC) {
Chris Lattnerffbc2712007-01-25 06:05:38 +00004217 // Parse the tag portion of this.
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004218 if (Tok.is(tok::code_completion)) {
4219 // Code completion for an enum name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004220 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00004221 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004222 }
John McCallcb432fa2011-07-06 05:58:41 +00004223
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004224 // If attributes exist after tag, parse them.
4225 ParsedAttributesWithRange attrs(AttrFactory);
4226 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004227 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004228 MaybeParseMicrosoftDeclSpecs(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004229
Richard Smith0f8ee222012-01-10 01:33:14 +00004230 SourceLocation ScopedEnumKWLoc;
John McCallcb432fa2011-07-06 05:58:41 +00004231 bool IsScopedUsingClassTag = false;
4232
John McCallbeae29a2012-06-23 22:30:04 +00004233 // In C++11, recognize 'enum class' and 'enum struct'.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004234 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
Richard Trieud0d87b52013-04-23 02:47:36 +00004235 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4236 : diag::ext_scoped_enum);
John McCallcb432fa2011-07-06 05:58:41 +00004237 IsScopedUsingClassTag = Tok.is(tok::kw_class);
Richard Smith0f8ee222012-01-10 01:33:14 +00004238 ScopedEnumKWLoc = ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004239
Bill Wendling44426052012-12-20 19:22:21 +00004240 // Attributes are not allowed between these keywords. Diagnose,
John McCallbeae29a2012-06-23 22:30:04 +00004241 // but then just treat them like they appeared in the right place.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004242 ProhibitAttributes(attrs);
John McCallbeae29a2012-06-23 22:30:04 +00004243
4244 // They are allowed afterwards, though.
4245 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004246 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004247 MaybeParseMicrosoftDeclSpecs(attrs);
John McCallcb432fa2011-07-06 05:58:41 +00004248 }
Richard Smith7d137e32012-03-23 03:33:32 +00004249
John McCall6347b682012-05-07 06:16:58 +00004250 // C++11 [temp.explicit]p12:
4251 // The usual access controls do not apply to names used to specify
4252 // explicit instantiations.
4253 // We extend this to also cover explicit specializations. Note that
4254 // we don't suppress if this turns out to be an elaborated type
4255 // specifier.
4256 bool shouldDelayDiagsInTag =
4257 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4258 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4259 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Richard Smith7d137e32012-03-23 03:33:32 +00004260
Richard Smithbfdb1082012-03-12 08:56:40 +00004261 // Enum definitions should not be parsed in a trailing-return-type.
Faisal Vali7db85c52017-12-31 00:06:40 +00004262 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
Richard Smithbfdb1082012-03-12 08:56:40 +00004263
Abramo Bagnarad7548482010-05-19 21:37:53 +00004264 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004265 if (getLangOpts().CPlusPlus) {
John McCallcb432fa2011-07-06 05:58:41 +00004266 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4267 // if a fixed underlying type is allowed.
Erik Pilkington6f11db12018-09-28 20:24:58 +00004268 ColonProtectionRAIIObject X(*this, AllowDeclaration);
Chad Rosierc1183952012-06-26 22:30:43 +00004269
Nico Webercfaa4cd2015-02-15 07:26:13 +00004270 CXXScopeSpec Spec;
David Blaikieefdccaa2016-01-15 23:43:34 +00004271 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
Richard Smith1d4b2e12013-04-01 21:43:41 +00004272 /*EnteringContext=*/true))
John McCall1f476a12010-02-26 08:45:28 +00004273 return;
4274
Nico Webercfaa4cd2015-02-15 07:26:13 +00004275 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004276 Diag(Tok, diag::err_expected) << tok::identifier;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004277 if (Tok.isNot(tok::l_brace)) {
4278 // Has no name and is not a definition.
4279 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004280 SkipUntil(tok::comma, StopAtSemi);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004281 return;
4282 }
4283 }
Nico Webercfaa4cd2015-02-15 07:26:13 +00004284
4285 SS = Spec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004286 }
Mike Stump11289f42009-09-09 15:08:12 +00004287
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004288 // Must have either 'enum name' or 'enum {...}'.
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004289 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
Erik Pilkington6f11db12018-09-28 20:24:58 +00004290 !(AllowDeclaration && Tok.is(tok::colon))) {
Alp Tokerec543272013-12-24 09:48:30 +00004291 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
Mike Stump11289f42009-09-09 15:08:12 +00004292
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004293 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004294 SkipUntil(tok::comma, StopAtSemi);
Chris Lattner3b561a32006-08-13 00:12:11 +00004295 return;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004296 }
Mike Stump11289f42009-09-09 15:08:12 +00004297
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004298 // If an identifier is present, consume and remember it.
Craig Topper161e4db2014-05-21 06:02:52 +00004299 IdentifierInfo *Name = nullptr;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004300 SourceLocation NameLoc;
4301 if (Tok.is(tok::identifier)) {
4302 Name = Tok.getIdentifierInfo();
4303 NameLoc = ConsumeToken();
4304 }
Mike Stump11289f42009-09-09 15:08:12 +00004305
Richard Smith0f8ee222012-01-10 01:33:14 +00004306 if (!Name && ScopedEnumKWLoc.isValid()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00004307 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4308 // declaration of a scoped enumeration.
4309 Diag(Tok, diag::err_scoped_enum_missing_identifier);
Richard Smith0f8ee222012-01-10 01:33:14 +00004310 ScopedEnumKWLoc = SourceLocation();
Abramo Bagnara0e05e242010-12-03 18:54:17 +00004311 IsScopedUsingClassTag = false;
Douglas Gregor0bf31402010-10-08 23:50:27 +00004312 }
4313
John McCall6347b682012-05-07 06:16:58 +00004314 // Okay, end the suppression area. We'll decide whether to emit the
4315 // diagnostics in a second.
4316 if (shouldDelayDiagsInTag)
4317 diagsFromTag.done();
Richard Smith7d137e32012-03-23 03:33:32 +00004318
Douglas Gregor0bf31402010-10-08 23:50:27 +00004319 TypeResult BaseType;
4320
Douglas Gregord1f69f62010-12-01 17:42:47 +00004321 // Parse the fixed underlying type.
Richard Smith200f47c2012-07-02 19:14:01 +00004322 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
Erik Pilkington6f11db12018-09-28 20:24:58 +00004323 if (AllowDeclaration && Tok.is(tok::colon)) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004324 bool PossibleBitfield = false;
Richard Smith200f47c2012-07-02 19:14:01 +00004325 if (CanBeBitfield) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004326 // If we're in class scope, this can either be an enum declaration with
4327 // an underlying type, or a declaration of a bitfield member. We try to
4328 // use a simple disambiguation scheme first to catch the common cases
Chad Rosierc1183952012-06-26 22:30:43 +00004329 // (integer literal, sizeof); if it's still ambiguous, we then consider
4330 // anything that's a simple-type-specifier followed by '(' as an
4331 // expression. This suffices because function types are not valid
Douglas Gregord1f69f62010-12-01 17:42:47 +00004332 // underlying types anyway.
Faisal Valid143a0c2017-04-01 21:30:49 +00004333 EnterExpressionEvaluationContext Unevaluated(
4334 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregord1f69f62010-12-01 17:42:47 +00004335 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
Chad Rosierc1183952012-06-26 22:30:43 +00004336 // If the next token starts an expression, we know we're parsing a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004337 // bit-field. This is the common case.
Richard Smithee390432014-05-16 01:56:53 +00004338 if (TPR == TPResult::True)
Douglas Gregord1f69f62010-12-01 17:42:47 +00004339 PossibleBitfield = true;
4340 // If the next token starts a type-specifier-seq, it may be either a
4341 // a fixed underlying type or the start of a function-style cast in C++;
Chad Rosierc1183952012-06-26 22:30:43 +00004342 // lookahead one more token to see if it's obvious that we have a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004343 // fixed underlying type.
Richard Smithee390432014-05-16 01:56:53 +00004344 else if (TPR == TPResult::False &&
Douglas Gregord1f69f62010-12-01 17:42:47 +00004345 GetLookAheadToken(2).getKind() == tok::semi) {
4346 // Consume the ':'.
4347 ConsumeToken();
4348 } else {
4349 // We have the start of a type-specifier-seq, so we have to perform
4350 // tentative parsing to determine whether we have an expression or a
4351 // type.
4352 TentativeParsingAction TPA(*this);
4353
4354 // Consume the ':'.
4355 ConsumeToken();
Richard Smith1e3b0f02012-02-23 01:36:12 +00004356
4357 // If we see a type specifier followed by an open-brace, we have an
4358 // ambiguity between an underlying type and a C++11 braced
4359 // function-style cast. Resolve this by always treating it as an
4360 // underlying type.
4361 // FIXME: The standard is not entirely clear on how to disambiguate in
4362 // this case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004363 if ((getLangOpts().CPlusPlus &&
Richard Smithee390432014-05-16 01:56:53 +00004364 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00004365 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004366 // We'll parse this as a bitfield later.
4367 PossibleBitfield = true;
4368 TPA.Revert();
4369 } else {
4370 // We have a type-specifier-seq.
4371 TPA.Commit();
4372 }
4373 }
4374 } else {
4375 // Consume the ':'.
4376 ConsumeToken();
4377 }
4378
4379 if (!PossibleBitfield) {
4380 SourceRange Range;
4381 BaseType = ParseTypeName(&Range);
Chad Rosierc1183952012-06-26 22:30:43 +00004382
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004383 if (!getLangOpts().ObjC) {
Erik Pilkington6f11db12018-09-28 20:24:58 +00004384 if (getLangOpts().CPlusPlus11)
4385 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4386 else if (getLangOpts().CPlusPlus)
4387 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4388 else if (getLangOpts().MicrosoftExt)
4389 Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004390 else
Erik Pilkington6f11db12018-09-28 20:24:58 +00004391 Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004392 }
Douglas Gregord1f69f62010-12-01 17:42:47 +00004393 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004394 }
4395
Richard Smith0f8ee222012-01-10 01:33:14 +00004396 // There are four options here. If we have 'friend enum foo;' then this is a
4397 // friend declaration, and cannot have an accompanying definition. If we have
4398 // 'enum foo;', then this is a forward declaration. If we have
4399 // 'enum foo {...' then this is a definition. Otherwise we have something
4400 // like 'enum foo xyz', a reference.
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004401 //
4402 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4403 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4404 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4405 //
John McCallfaf5fb42010-08-26 23:41:50 +00004406 Sema::TagUseKind TUK;
John McCall6347b682012-05-07 06:16:58 +00004407 if (!AllowDeclaration) {
Richard Smithbfdb1082012-03-12 08:56:40 +00004408 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004409 } else if (Tok.is(tok::l_brace)) {
4410 if (DS.isFriendSpecified()) {
4411 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4412 << SourceRange(DS.getFriendSpecLoc());
4413 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004414 SkipUntil(tok::r_brace, StopAtSemi);
John McCall6347b682012-05-07 06:16:58 +00004415 TUK = Sema::TUK_Friend;
4416 } else {
4417 TUK = Sema::TUK_Definition;
4418 }
Richard Smith649c7b062014-01-08 00:56:48 +00004419 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00004420 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00004421 (Tok.isAtStartOfLine() &&
4422 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
Richard Smith369b9f92012-06-25 21:37:02 +00004423 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4424 if (Tok.isNot(tok::semi)) {
4425 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00004426 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004427 PP.EnterToken(Tok);
4428 Tok.setKind(tok::semi);
4429 }
John McCall6347b682012-05-07 06:16:58 +00004430 } else {
John McCallfaf5fb42010-08-26 23:41:50 +00004431 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004432 }
4433
4434 // If this is an elaborated type specifier, and we delayed
4435 // diagnostics before, just merge them into the current pool.
4436 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4437 diagsFromTag.redelay();
4438 }
Richard Smith7d137e32012-03-23 03:33:32 +00004439
4440 MultiTemplateParamsArg TParams;
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004441 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
John McCallfaf5fb42010-08-26 23:41:50 +00004442 TUK != Sema::TUK_Reference) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004443 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
Richard Smith7d137e32012-03-23 03:33:32 +00004444 // Skip the rest of this declarator, up until the comma or semicolon.
4445 Diag(Tok, diag::err_enum_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004446 SkipUntil(tok::comma, StopAtSemi);
Richard Smith7d137e32012-03-23 03:33:32 +00004447 return;
4448 }
4449
4450 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4451 // Enumerations can't be explicitly instantiated.
4452 DS.SetTypeSpecError();
4453 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4454 return;
4455 }
4456
4457 assert(TemplateInfo.TemplateParams && "no template parameters");
4458 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4459 TemplateInfo.TemplateParams->size());
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004460 }
Chad Rosierc1183952012-06-26 22:30:43 +00004461
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004462 if (TUK == Sema::TUK_Reference)
4463 ProhibitAttributes(attrs);
Richard Smith7d137e32012-03-23 03:33:32 +00004464
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004465 if (!Name && TUK != Sema::TUK_Definition) {
4466 Diag(Tok, diag::err_enumerator_unnamed_no_def);
Richard Smith7d137e32012-03-23 03:33:32 +00004467
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004468 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004469 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004470 return;
4471 }
Richard Smith7d137e32012-03-23 03:33:32 +00004472
Nico Weber32a0fc72016-09-03 03:01:32 +00004473 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00004474
Richard Smithd9ba2242015-05-07 03:54:19 +00004475 Sema::SkipBodyInfo SkipBody;
4476 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4477 NextToken().is(tok::identifier))
4478 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4479 NextToken().getIdentifierInfo(),
4480 NextToken().getLocation());
4481
Douglas Gregord6ab8742009-05-28 23:31:59 +00004482 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004483 bool IsDependent = false;
Craig Topper161e4db2014-05-21 06:02:52 +00004484 const char *PrevSpec = nullptr;
Douglas Gregorba41d012010-04-24 16:38:41 +00004485 unsigned DiagID;
Faisal Vali7db85c52017-12-31 00:06:40 +00004486 Decl *TagDecl = Actions.ActOnTag(
4487 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
Erich Keanec480f302018-07-12 21:09:05 +00004488 attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4489 ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
Faisal Vali7db85c52017-12-31 00:06:40 +00004490 DSC == DeclSpecContext::DSC_type_specifier,
4491 DSC == DeclSpecContext::DSC_template_param ||
4492 DSC == DeclSpecContext::DSC_template_type_arg,
4493 &SkipBody);
Richard Smithd9ba2242015-05-07 03:54:19 +00004494
4495 if (SkipBody.ShouldSkip) {
4496 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4497
4498 BalancedDelimiterTracker T(*this, tok::l_brace);
4499 T.consumeOpen();
4500 T.skipToEnd();
4501
4502 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4503 NameLoc.isValid() ? NameLoc : StartLoc,
4504 PrevSpec, DiagID, TagDecl, Owned,
4505 Actions.getASTContext().getPrintingPolicy()))
4506 Diag(StartLoc, DiagID) << PrevSpec;
4507 return;
4508 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004509
Douglas Gregorba41d012010-04-24 16:38:41 +00004510 if (IsDependent) {
Chad Rosierc1183952012-06-26 22:30:43 +00004511 // This enum has a dependent nested-name-specifier. Handle it as a
Douglas Gregorba41d012010-04-24 16:38:41 +00004512 // dependent tag.
4513 if (!Name) {
4514 DS.SetTypeSpecError();
4515 Diag(Tok, diag::err_expected_type_name_after_typename);
4516 return;
4517 }
Chad Rosierc1183952012-06-26 22:30:43 +00004518
Nico Weber83ea0122014-05-03 21:57:40 +00004519 TypeResult Type = Actions.ActOnDependentTag(
4520 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
Douglas Gregorba41d012010-04-24 16:38:41 +00004521 if (Type.isInvalid()) {
4522 DS.SetTypeSpecError();
4523 return;
4524 }
Chad Rosierc1183952012-06-26 22:30:43 +00004525
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004526 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4527 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004528 PrevSpec, DiagID, Type.get(),
4529 Actions.getASTContext().getPrintingPolicy()))
Douglas Gregorba41d012010-04-24 16:38:41 +00004530 Diag(StartLoc, DiagID) << PrevSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00004531
Douglas Gregorba41d012010-04-24 16:38:41 +00004532 return;
4533 }
Mike Stump11289f42009-09-09 15:08:12 +00004534
John McCall48871652010-08-21 09:40:31 +00004535 if (!TagDecl) {
Chad Rosierc1183952012-06-26 22:30:43 +00004536 // The action failed to produce an enumeration tag. If this is a
Douglas Gregorba41d012010-04-24 16:38:41 +00004537 // definition, consume the entire definition.
Richard Smithbfdb1082012-03-12 08:56:40 +00004538 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
Douglas Gregorba41d012010-04-24 16:38:41 +00004539 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004540 SkipUntil(tok::r_brace, StopAtSemi);
Douglas Gregorba41d012010-04-24 16:38:41 +00004541 }
Chad Rosierc1183952012-06-26 22:30:43 +00004542
Douglas Gregorba41d012010-04-24 16:38:41 +00004543 DS.SetTypeSpecError();
4544 return;
4545 }
Richard Smith0f8ee222012-01-10 01:33:14 +00004546
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004547 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4548 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4549 ParseEnumBody(StartLoc, D);
4550 if (SkipBody.CheckSameAsPrevious &&
4551 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4552 DS.SetTypeSpecError();
4553 return;
4554 }
4555 }
Mike Stump11289f42009-09-09 15:08:12 +00004556
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004557 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4558 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004559 PrevSpec, DiagID, TagDecl, Owned,
4560 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00004561 Diag(StartLoc, DiagID) << PrevSpec;
Chris Lattner3b561a32006-08-13 00:12:11 +00004562}
4563
Chris Lattnerc1915e22007-01-25 07:29:02 +00004564/// ParseEnumBody - Parse a {} enclosed enumerator-list.
4565/// enumerator-list:
4566/// enumerator
4567/// enumerator-list ',' enumerator
4568/// enumerator:
Aaron Ballman730476b2014-11-08 15:33:35 +00004569/// enumeration-constant attributes[opt]
4570/// enumeration-constant attributes[opt] '=' constant-expression
Chris Lattnerc1915e22007-01-25 07:29:02 +00004571/// enumeration-constant:
4572/// identifier
4573///
John McCall48871652010-08-21 09:40:31 +00004574void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004575 // Enter the scope of the enum body and start the definition.
Hans Wennborgfe781452014-06-17 00:00:18 +00004576 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004577 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
Douglas Gregor07665a62009-01-05 19:45:36 +00004578
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004579 BalancedDelimiterTracker T(*this, tok::l_brace);
4580 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00004581
Chris Lattner37256fb2007-08-27 17:24:30 +00004582 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
David Blaikiebbafb8a2012-03-11 07:00:24 +00004583 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
Richard Smithf8812672016-12-02 22:38:31 +00004584 Diag(Tok, diag::err_empty_enum);
Mike Stump11289f42009-09-09 15:08:12 +00004585
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004586 SmallVector<Decl *, 32> EnumConstantDecls;
Jordan Rose60ac3162015-04-30 17:20:30 +00004587 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
Chris Lattnerc1915e22007-01-25 07:29:02 +00004588
Craig Topper161e4db2014-05-21 06:02:52 +00004589 Decl *LastEnumConstDecl = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004590
Chris Lattnerc1915e22007-01-25 07:29:02 +00004591 // Parse the enumerator-list.
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004592 while (Tok.isNot(tok::r_brace)) {
4593 // Parse enumerator. If failed, try skipping till the start of the next
4594 // enumerator definition.
4595 if (Tok.isNot(tok::identifier)) {
4596 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4597 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4598 TryConsumeToken(tok::comma))
4599 continue;
4600 break;
4601 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004602 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4603 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00004604
John McCall811a0f52010-10-22 23:36:17 +00004605 // If attributes exist after the enumerator, parse them.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004606 ParsedAttributesWithRange attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004607 MaybeParseGNUAttributes(attrs);
Aaron Ballman730476b2014-11-08 15:33:35 +00004608 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
Aaron Ballman606093a2017-10-15 15:01:42 +00004609 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4610 if (getLangOpts().CPlusPlus)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004611 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Aaron Ballman606093a2017-10-15 15:01:42 +00004612 ? diag::warn_cxx14_compat_ns_enum_attribute
4613 : diag::ext_ns_enum_attribute)
4614 << 1 /*enumerator*/;
Aaron Ballman730476b2014-11-08 15:33:35 +00004615 ParseCXX11Attributes(attrs);
4616 }
John McCall811a0f52010-10-22 23:36:17 +00004617
Chris Lattnerc1915e22007-01-25 07:29:02 +00004618 SourceLocation EqualLoc;
John McCalldadc5752010-08-24 06:29:42 +00004619 ExprResult AssignedVal;
Jordan Rose60ac3162015-04-30 17:20:30 +00004620 EnumAvailabilityDiags.emplace_back(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00004621
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004622 if (TryConsumeToken(tok::equal, EqualLoc)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004623 AssignedVal = ParseConstantExpression();
4624 if (AssignedVal.isInvalid())
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004625 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
Chris Lattnerc1915e22007-01-25 07:29:02 +00004626 }
Mike Stump11289f42009-09-09 15:08:12 +00004627
Chris Lattnerc1915e22007-01-25 07:29:02 +00004628 // Install the enumerator constant into EnumDecl.
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004629 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
Erich Keanec480f302018-07-12 21:09:05 +00004630 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4631 EqualLoc, AssignedVal.get());
Jordan Rose60ac3162015-04-30 17:20:30 +00004632 EnumAvailabilityDiags.back().done();
Chad Rosierc1183952012-06-26 22:30:43 +00004633
Chris Lattner4ef40012007-06-11 01:28:17 +00004634 EnumConstantDecls.push_back(EnumConstDecl);
4635 LastEnumConstDecl = EnumConstDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004636
Douglas Gregorce66d022010-09-07 14:51:08 +00004637 if (Tok.is(tok::identifier)) {
4638 // We're missing a comma between enumerators.
Richard Smithbdb84f32016-07-22 23:36:59 +00004639 SourceLocation Loc = getEndOfPreviousToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004640 Diag(Loc, diag::err_enumerator_list_missing_comma)
Douglas Gregorce66d022010-09-07 14:51:08 +00004641 << FixItHint::CreateInsertion(Loc, ", ");
4642 continue;
4643 }
Chad Rosierc1183952012-06-26 22:30:43 +00004644
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004645 // Emumerator definition must be finished, only comma or r_brace are
4646 // allowed here.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004647 SourceLocation CommaLoc;
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004648 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4649 if (EqualLoc.isValid())
4650 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4651 << tok::comma;
4652 else
4653 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4654 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4655 if (TryConsumeToken(tok::comma, CommaLoc))
4656 continue;
4657 } else {
4658 break;
4659 }
4660 }
Mike Stump11289f42009-09-09 15:08:12 +00004661
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004662 // If comma is followed by r_brace, emit appropriate warning.
4663 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004664 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
Richard Smith87f5dc52012-07-23 05:45:25 +00004665 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4666 diag::ext_enumerator_list_comma_cxx :
4667 diag::ext_enumerator_list_comma_c)
Richard Smith5d164bc2011-10-15 05:09:34 +00004668 << FixItHint::CreateRemoval(CommaLoc);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004669 else if (getLangOpts().CPlusPlus11)
Richard Smith5d164bc2011-10-15 05:09:34 +00004670 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4671 << FixItHint::CreateRemoval(CommaLoc);
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004672 break;
Richard Smith5d164bc2011-10-15 05:09:34 +00004673 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004674 }
Mike Stump11289f42009-09-09 15:08:12 +00004675
Chris Lattnerc1915e22007-01-25 07:29:02 +00004676 // Eat the }.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004677 T.consumeClose();
Chris Lattnerc1915e22007-01-25 07:29:02 +00004678
Chris Lattnerc1915e22007-01-25 07:29:02 +00004679 // If attributes exist after the identifier list, parse them.
John McCall084e83d2011-03-24 11:26:52 +00004680 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004681 MaybeParseGNUAttributes(attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004682
Erich Keanec480f302018-07-12 21:09:05 +00004683 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4684 getCurScope(), attrs);
Mike Stump11289f42009-09-09 15:08:12 +00004685
Jordan Rose60ac3162015-04-30 17:20:30 +00004686 // Now handle enum constant availability diagnostics.
4687 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4688 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4689 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4690 EnumAvailabilityDiags[i].redelay();
4691 PD.complete(EnumConstantDecls[i]);
4692 }
4693
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004694 EnumScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004695 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
Richard Smith369b9f92012-06-25 21:37:02 +00004696
4697 // The next token must be valid after an enum definition. If not, a ';'
4698 // was probably forgotten.
Richard Smith200f47c2012-07-02 19:14:01 +00004699 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4700 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
Alp Toker383d2c42014-01-01 03:08:43 +00004701 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004702 // Push this token back into the preprocessor and change our current token
4703 // to ';' so that the rest of the code recovers as though there were an
4704 // ';' after the definition.
4705 PP.EnterToken(Tok);
4706 Tok.setKind(tok::semi);
4707 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004708}
Chris Lattner3b561a32006-08-13 00:12:11 +00004709
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004710/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4711/// is definitely a type-specifier. Return false if it isn't part of a type
4712/// specifier or if we're not sure.
4713bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4714 switch (Tok.getKind()) {
4715 default: return false;
4716 // type-specifiers
4717 case tok::kw_short:
4718 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004719 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004720 case tok::kw___int128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004721 case tok::kw_signed:
4722 case tok::kw_unsigned:
4723 case tok::kw__Complex:
4724 case tok::kw__Imaginary:
4725 case tok::kw_void:
4726 case tok::kw_char:
4727 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004728 case tok::kw_char8_t:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004729 case tok::kw_char16_t:
4730 case tok::kw_char32_t:
4731 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004732 case tok::kw_half:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004733 case tok::kw_float:
4734 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004735 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004736 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004737 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004738 case tok::kw___float128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004739 case tok::kw_bool:
4740 case tok::kw__Bool:
4741 case tok::kw__Decimal32:
4742 case tok::kw__Decimal64:
4743 case tok::kw__Decimal128:
4744 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004745#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004746#include "clang/Basic/OpenCLImageTypes.def"
Chad Rosierc1183952012-06-26 22:30:43 +00004747
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004748 // struct-or-union-specifier (C99) or class-specifier (C++)
4749 case tok::kw_class:
4750 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004751 case tok::kw___interface:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004752 case tok::kw_union:
4753 // enum-specifier
4754 case tok::kw_enum:
Chad Rosierc1183952012-06-26 22:30:43 +00004755
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004756 // typedef-name
4757 case tok::annot_typename:
4758 return true;
4759 }
4760}
4761
Steve Naroff69e8f9e2008-02-11 23:15:56 +00004762/// isTypeSpecifierQualifier - Return true if the current token could be the
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004763/// start of a specifier-qualifier-list.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004764bool Parser::isTypeSpecifierQualifier() {
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004765 switch (Tok.getKind()) {
4766 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004767
Chris Lattner020bab92009-01-04 23:41:41 +00004768 case tok::identifier: // foo::bar
John Thompson22334602010-02-05 00:12:22 +00004769 if (TryAltiVecVectorToken())
4770 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004771 LLVM_FALLTHROUGH;
Douglas Gregor333489b2009-03-27 23:10:48 +00004772 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004773 // Annotate typenames and C++ scope specifiers. If we get one, just
4774 // recurse to handle whatever we get.
4775 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004776 return true;
4777 if (Tok.is(tok::identifier))
4778 return false;
4779 return isTypeSpecifierQualifier();
Douglas Gregor333489b2009-03-27 23:10:48 +00004780
Chris Lattner020bab92009-01-04 23:41:41 +00004781 case tok::coloncolon: // ::foo::bar
4782 if (NextToken().is(tok::kw_new) || // ::new
4783 NextToken().is(tok::kw_delete)) // ::delete
4784 return false;
4785
Chris Lattner020bab92009-01-04 23:41:41 +00004786 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004787 return true;
4788 return isTypeSpecifierQualifier();
Mike Stump11289f42009-09-09 15:08:12 +00004789
Chris Lattnere37e2332006-08-15 04:50:22 +00004790 // GNU attributes support.
4791 case tok::kw___attribute:
Steve Naroffad373bd2007-07-31 12:34:36 +00004792 // GNU typeof support.
4793 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004794
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004795 // type-specifiers
4796 case tok::kw_short:
4797 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004798 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004799 case tok::kw___int128:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004800 case tok::kw_signed:
4801 case tok::kw_unsigned:
4802 case tok::kw__Complex:
4803 case tok::kw__Imaginary:
4804 case tok::kw_void:
4805 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004806 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004807 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004808 case tok::kw_char16_t:
4809 case tok::kw_char32_t:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004810 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004811 case tok::kw_half:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004812 case tok::kw_float:
4813 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004814 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004815 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004816 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004817 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004818 case tok::kw_bool:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004819 case tok::kw__Bool:
4820 case tok::kw__Decimal32:
4821 case tok::kw__Decimal64:
4822 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004823 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004824#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004825#include "clang/Basic/OpenCLImageTypes.def"
Mike Stump11289f42009-09-09 15:08:12 +00004826
Chris Lattner861a2262008-04-13 18:59:07 +00004827 // struct-or-union-specifier (C99) or class-specifier (C++)
4828 case tok::kw_class:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004829 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004830 case tok::kw___interface:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004831 case tok::kw_union:
4832 // enum-specifier
4833 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004834
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004835 // type-qualifier
4836 case tok::kw_const:
4837 case tok::kw_volatile:
4838 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004839 case tok::kw__Sat:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004840
John McCallea0a39e2012-11-14 00:49:39 +00004841 // Debugger support.
4842 case tok::kw___unknown_anytype:
4843
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004844 // typedef-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00004845 case tok::annot_typename:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004846 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004847
Chris Lattner409bf7d2008-10-20 00:25:30 +00004848 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4849 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004850 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00004851
Steve Naroff44ac7772008-12-25 14:16:32 +00004852 case tok::kw___cdecl:
4853 case tok::kw___stdcall:
4854 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004855 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004856 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004857 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004858 case tok::kw___w64:
4859 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004860 case tok::kw___ptr32:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004861 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004862 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004863
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004864 case tok::kw__Nonnull:
4865 case tok::kw__Nullable:
4866 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004867
Douglas Gregorab209d82015-07-07 03:58:42 +00004868 case tok::kw___kindof:
4869
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004870 case tok::kw___private:
4871 case tok::kw___local:
4872 case tok::kw___global:
4873 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004874 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004875 case tok::kw___read_only:
4876 case tok::kw___read_write:
4877 case tok::kw___write_only:
Eli Friedman53339e02009-06-08 23:27:34 +00004878 return true;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004879
Anastasia Stulova314fab62019-03-28 11:47:14 +00004880 case tok::kw_private:
4881 return getLangOpts().OpenCL;
4882
Richard Smith8e1ac332013-03-28 01:55:44 +00004883 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004884 case tok::kw__Atomic:
4885 return true;
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004886 }
4887}
4888
Chris Lattneracd58a32006-08-06 17:24:14 +00004889/// isDeclarationSpecifier() - Return true if the current token is part of a
4890/// declaration specifier.
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004891///
4892/// \param DisambiguatingWithExpression True to indicate that the purpose of
4893/// this check is to disambiguate between an expression and a declaration.
4894bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
Chris Lattneracd58a32006-08-06 17:24:14 +00004895 switch (Tok.getKind()) {
4896 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004897
Xiuli Pan9c14e282016-01-09 12:53:17 +00004898 case tok::kw_pipe:
4899 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4900
Chris Lattner020bab92009-01-04 23:41:41 +00004901 case tok::identifier: // foo::bar
Steve Naroff9527bbf2009-03-09 21:12:44 +00004902 // Unfortunate hack to support "Class.factoryMethod" notation.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004903 if (getLangOpts().ObjC && NextToken().is(tok::period))
Steve Naroff9527bbf2009-03-09 21:12:44 +00004904 return false;
John Thompson22334602010-02-05 00:12:22 +00004905 if (TryAltiVecVectorToken())
4906 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004907 LLVM_FALLTHROUGH;
David Blaikie15a430a2011-12-04 05:04:18 +00004908 case tok::kw_decltype: // decltype(T())::type
Douglas Gregor333489b2009-03-27 23:10:48 +00004909 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004910 // Annotate typenames and C++ scope specifiers. If we get one, just
4911 // recurse to handle whatever we get.
4912 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004913 return true;
4914 if (Tok.is(tok::identifier))
4915 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004916
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004917 // If we're in Objective-C and we have an Objective-C class type followed
Chad Rosierc1183952012-06-26 22:30:43 +00004918 // by an identifier and then either ':' or ']', in a place where an
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004919 // expression is permitted, then this is probably a class message send
4920 // missing the initial '['. In this case, we won't consider this to be
4921 // the start of a declaration.
Chad Rosierc1183952012-06-26 22:30:43 +00004922 if (DisambiguatingWithExpression &&
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004923 isStartOfObjCClassMessageMissingOpenBracket())
4924 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004925
John McCall1f476a12010-02-26 08:45:28 +00004926 return isDeclarationSpecifier();
4927
Chris Lattner020bab92009-01-04 23:41:41 +00004928 case tok::coloncolon: // ::foo::bar
4929 if (NextToken().is(tok::kw_new) || // ::new
4930 NextToken().is(tok::kw_delete)) // ::delete
4931 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004932
Chris Lattner020bab92009-01-04 23:41:41 +00004933 // Annotate typenames and C++ scope specifiers. If we get one, just
4934 // recurse to handle whatever we get.
4935 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004936 return true;
4937 return isDeclarationSpecifier();
Mike Stump11289f42009-09-09 15:08:12 +00004938
Chris Lattneracd58a32006-08-06 17:24:14 +00004939 // storage-class-specifier
4940 case tok::kw_typedef:
4941 case tok::kw_extern:
Steve Naroff2050b0d2007-12-18 00:16:02 +00004942 case tok::kw___private_extern__:
Chris Lattneracd58a32006-08-06 17:24:14 +00004943 case tok::kw_static:
4944 case tok::kw_auto:
Richard Smithe301ba22015-11-11 02:02:15 +00004945 case tok::kw___auto_type:
Chris Lattneracd58a32006-08-06 17:24:14 +00004946 case tok::kw_register:
4947 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00004948 case tok::kw_thread_local:
4949 case tok::kw__Thread_local:
Mike Stump11289f42009-09-09 15:08:12 +00004950
Douglas Gregor26701a42011-09-09 02:06:17 +00004951 // Modules
4952 case tok::kw___module_private__:
Chad Rosierc1183952012-06-26 22:30:43 +00004953
John McCallea0a39e2012-11-14 00:49:39 +00004954 // Debugger support
4955 case tok::kw___unknown_anytype:
4956
Chris Lattneracd58a32006-08-06 17:24:14 +00004957 // type-specifiers
4958 case tok::kw_short:
4959 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004960 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004961 case tok::kw___int128:
Chris Lattneracd58a32006-08-06 17:24:14 +00004962 case tok::kw_signed:
4963 case tok::kw_unsigned:
4964 case tok::kw__Complex:
4965 case tok::kw__Imaginary:
4966 case tok::kw_void:
4967 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004968 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004969 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004970 case tok::kw_char16_t:
4971 case tok::kw_char32_t:
4972
Chris Lattneracd58a32006-08-06 17:24:14 +00004973 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004974 case tok::kw_half:
Chris Lattneracd58a32006-08-06 17:24:14 +00004975 case tok::kw_float:
4976 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004977 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004978 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004979 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004980 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004981 case tok::kw_bool:
Chris Lattneracd58a32006-08-06 17:24:14 +00004982 case tok::kw__Bool:
4983 case tok::kw__Decimal32:
4984 case tok::kw__Decimal64:
4985 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004986 case tok::kw___vector:
Mike Stump11289f42009-09-09 15:08:12 +00004987
Chris Lattner861a2262008-04-13 18:59:07 +00004988 // struct-or-union-specifier (C99) or class-specifier (C++)
4989 case tok::kw_class:
Chris Lattneracd58a32006-08-06 17:24:14 +00004990 case tok::kw_struct:
4991 case tok::kw_union:
Joao Matosdc86f942012-08-31 18:45:21 +00004992 case tok::kw___interface:
Chris Lattneracd58a32006-08-06 17:24:14 +00004993 // enum-specifier
4994 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004995
Chris Lattneracd58a32006-08-06 17:24:14 +00004996 // type-qualifier
4997 case tok::kw_const:
4998 case tok::kw_volatile:
4999 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00005000 case tok::kw__Sat:
Steve Naroffad373bd2007-07-31 12:34:36 +00005001
Chris Lattneracd58a32006-08-06 17:24:14 +00005002 // function-specifier
5003 case tok::kw_inline:
Douglas Gregor61956c42008-10-31 09:07:45 +00005004 case tok::kw_virtual:
5005 case tok::kw_explicit:
Richard Smith0015f092013-01-17 22:16:11 +00005006 case tok::kw__Noreturn:
Chris Lattner7b20dc72007-08-09 16:40:21 +00005007
Richard Smith1dba27c2013-01-29 09:02:09 +00005008 // alignment-specifier
5009 case tok::kw__Alignas:
5010
Richard Smithd16fe122012-10-25 00:00:53 +00005011 // friend keyword.
5012 case tok::kw_friend:
5013
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00005014 // static_assert-declaration
5015 case tok::kw__Static_assert:
5016
Chris Lattner599e47e2007-08-09 17:01:07 +00005017 // GNU typeof support.
5018 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00005019
Chris Lattner599e47e2007-08-09 17:01:07 +00005020 // GNU attributes.
Chris Lattner7b20dc72007-08-09 16:40:21 +00005021 case tok::kw___attribute:
Mike Stump11289f42009-09-09 15:08:12 +00005022
Richard Smithd16fe122012-10-25 00:00:53 +00005023 // C++11 decltype and constexpr.
David Blaikie15a430a2011-12-04 05:04:18 +00005024 case tok::annot_decltype:
Richard Smithd16fe122012-10-25 00:00:53 +00005025 case tok::kw_constexpr:
Francois Pichete878cb62011-06-19 08:02:06 +00005026
Richard Smith8e1ac332013-03-28 01:55:44 +00005027 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00005028 case tok::kw__Atomic:
5029 return true;
5030
Chris Lattner8b2ec162008-07-26 03:38:44 +00005031 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5032 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005033 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00005034
Douglas Gregor19b7acf2011-04-27 05:41:15 +00005035 // typedef-name
5036 case tok::annot_typename:
5037 return !DisambiguatingWithExpression ||
5038 !isStartOfObjCClassMessageMissingOpenBracket();
Chad Rosierc1183952012-06-26 22:30:43 +00005039
Steve Narofff192fab2009-01-06 19:34:12 +00005040 case tok::kw___declspec:
Steve Naroff44ac7772008-12-25 14:16:32 +00005041 case tok::kw___cdecl:
5042 case tok::kw___stdcall:
5043 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005044 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005045 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005046 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00005047 case tok::kw___w64:
Aaron Ballman317a77f2013-05-22 23:25:32 +00005048 case tok::kw___sptr:
5049 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005050 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005051 case tok::kw___ptr32:
Eli Friedman53339e02009-06-08 23:27:34 +00005052 case tok::kw___forceinline:
Dawn Perchik335e16b2010-09-03 01:29:35 +00005053 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00005054 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005055
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005056 case tok::kw__Nonnull:
5057 case tok::kw__Nullable:
5058 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005059
Douglas Gregorab209d82015-07-07 03:58:42 +00005060 case tok::kw___kindof:
5061
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005062 case tok::kw___private:
5063 case tok::kw___local:
5064 case tok::kw___global:
5065 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005066 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005067 case tok::kw___read_only:
5068 case tok::kw___read_write:
5069 case tok::kw___write_only:
Alexey Bader954ba212016-04-08 13:40:33 +00005070#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00005071#include "clang/Basic/OpenCLImageTypes.def"
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005072
Eli Friedman53339e02009-06-08 23:27:34 +00005073 return true;
Anastasia Stulova314fab62019-03-28 11:47:14 +00005074
5075 case tok::kw_private:
5076 return getLangOpts().OpenCL;
Chris Lattneracd58a32006-08-06 17:24:14 +00005077 }
5078}
5079
Richard Smith35845152017-02-07 01:37:30 +00005080bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005081 TentativeParsingAction TPA(*this);
5082
5083 // Parse the C++ scope specifier.
5084 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005085 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005086 /*EnteringContext=*/true)) {
John McCall1f476a12010-02-26 08:45:28 +00005087 TPA.Revert();
5088 return false;
5089 }
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005090
5091 // Parse the constructor name.
Richard Smithaf3b3252017-05-18 19:21:48 +00005092 if (Tok.is(tok::identifier)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005093 // We already know that we have a constructor name; just consume
5094 // the token.
5095 ConsumeToken();
Richard Smithaf3b3252017-05-18 19:21:48 +00005096 } else if (Tok.is(tok::annot_template_id)) {
5097 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005098 } else {
5099 TPA.Revert();
5100 return false;
5101 }
5102
Richard Smith8f8697f2017-02-08 01:16:55 +00005103 // There may be attributes here, appertaining to the constructor name or type
5104 // we just stepped past.
5105 SkipCXX11Attributes();
5106
Richard Smith43f340f2012-03-27 23:05:05 +00005107 // Current class name must be followed by a left parenthesis.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005108 if (Tok.isNot(tok::l_paren)) {
5109 TPA.Revert();
5110 return false;
5111 }
5112 ConsumeParen();
5113
Richard Smith43f340f2012-03-27 23:05:05 +00005114 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5115 // that we have a constructor.
5116 if (Tok.is(tok::r_paren) ||
5117 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005118 TPA.Revert();
5119 return true;
5120 }
5121
Richard Smithf2163662013-09-06 00:12:20 +00005122 // A C++11 attribute here signals that we have a constructor, and is an
5123 // attribute on the first constructor parameter.
5124 if (getLangOpts().CPlusPlus11 &&
5125 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5126 /*OuterMightBeMessageSend*/ true)) {
5127 TPA.Revert();
5128 return true;
5129 }
5130
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005131 // If we need to, enter the specified scope.
5132 DeclaratorScopeObj DeclScopeObj(*this, SS);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005133 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005134 DeclScopeObj.EnterDeclaratorScope();
5135
Francois Pichet79f3a872011-01-31 04:54:32 +00005136 // Optionally skip Microsoft attributes.
John McCall084e83d2011-03-24 11:26:52 +00005137 ParsedAttributes Attrs(AttrFactory);
Francois Pichet79f3a872011-01-31 04:54:32 +00005138 MaybeParseMicrosoftAttributes(Attrs);
5139
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005140 // Check whether the next token(s) are part of a declaration
5141 // specifier, in which case we have the start of a parameter and,
5142 // therefore, we know that this is a constructor.
Richard Smithefd009d2012-03-27 00:56:56 +00005143 bool IsConstructor = false;
5144 if (isDeclarationSpecifier())
5145 IsConstructor = true;
5146 else if (Tok.is(tok::identifier) ||
5147 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5148 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5149 // This might be a parenthesized member name, but is more likely to
5150 // be a constructor declaration with an invalid argument type. Keep
5151 // looking.
5152 if (Tok.is(tok::annot_cxxscope))
Richard Smithaf3b3252017-05-18 19:21:48 +00005153 ConsumeAnnotationToken();
Richard Smithefd009d2012-03-27 00:56:56 +00005154 ConsumeToken();
5155
5156 // If this is not a constructor, we must be parsing a declarator,
Richard Smith1453e312012-03-27 01:42:32 +00005157 // which must have one of the following syntactic forms (see the
5158 // grammar extract at the start of ParseDirectDeclarator):
Richard Smithefd009d2012-03-27 00:56:56 +00005159 switch (Tok.getKind()) {
5160 case tok::l_paren:
5161 // C(X ( int));
5162 case tok::l_square:
5163 // C(X [ 5]);
5164 // C(X [ [attribute]]);
5165 case tok::coloncolon:
5166 // C(X :: Y);
5167 // C(X :: *p);
Richard Smithefd009d2012-03-27 00:56:56 +00005168 // Assume this isn't a constructor, rather than assuming it's a
5169 // constructor with an unnamed parameter of an ill-formed type.
5170 break;
5171
Richard Smith446161b2014-03-03 21:12:53 +00005172 case tok::r_paren:
5173 // C(X )
Richard Smith8f8697f2017-02-08 01:16:55 +00005174
5175 // Skip past the right-paren and any following attributes to get to
5176 // the function body or trailing-return-type.
5177 ConsumeParen();
5178 SkipCXX11Attributes();
5179
Richard Smith35845152017-02-07 01:37:30 +00005180 if (DeductionGuide) {
5181 // C(X) -> ... is a deduction guide.
Richard Smith8f8697f2017-02-08 01:16:55 +00005182 IsConstructor = Tok.is(tok::arrow);
Richard Smith35845152017-02-07 01:37:30 +00005183 break;
5184 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005185 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
Richard Smith446161b2014-03-03 21:12:53 +00005186 // Assume these were meant to be constructors:
5187 // C(X) : (the name of a bit-field cannot be parenthesized).
5188 // C(X) try (this is otherwise ill-formed).
5189 IsConstructor = true;
5190 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005191 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
Richard Smith446161b2014-03-03 21:12:53 +00005192 // If we have a constructor name within the class definition,
5193 // assume these were meant to be constructors:
5194 // C(X) {
5195 // C(X) ;
5196 // ... because otherwise we would be declaring a non-static data
5197 // member that is ill-formed because it's of the same type as its
5198 // surrounding class.
5199 //
5200 // FIXME: We can actually do this whether or not the name is qualified,
5201 // because if it is qualified in this context it must be being used as
Richard Smith35845152017-02-07 01:37:30 +00005202 // a constructor name.
Richard Smith446161b2014-03-03 21:12:53 +00005203 // currently, so we're somewhat conservative here.
5204 IsConstructor = IsUnqualified;
5205 }
5206 break;
5207
Richard Smithefd009d2012-03-27 00:56:56 +00005208 default:
5209 IsConstructor = true;
5210 break;
5211 }
5212 }
5213
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005214 TPA.Revert();
5215 return IsConstructor;
5216}
Chris Lattnerb9093cd2006-08-04 04:39:53 +00005217
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005218/// ParseTypeQualifierListOpt
Dawn Perchik335e16b2010-09-03 01:29:35 +00005219/// type-qualifier-list: [C99 6.7.5]
5220/// type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005221/// [vendor] attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005222/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005223/// type-qualifier-list type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005224/// [vendor] type-qualifier-list attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005225/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005226/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
Aaron Ballman08b06592014-07-22 12:44:22 +00005227/// [ only if AttReqs & AR_CXX11AttributesParsed ]
5228/// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5229/// AttrRequirements bitmask values.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005230void Parser::ParseTypeQualifierListOpt(
5231 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5232 bool IdentifierRequired,
5233 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
Aaron Ballman606093a2017-10-15 15:01:42 +00005234 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005235 isCXX11AttributeSpecifier()) {
John McCall084e83d2011-03-24 11:26:52 +00005236 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith3dff2512012-04-10 03:25:07 +00005237 ParseCXX11Attributes(attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005238 DS.takeAttributesFrom(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005239 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005240
5241 SourceLocation EndLoc;
5242
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005243 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00005244 bool isInvalid = false;
Craig Topper161e4db2014-05-21 06:02:52 +00005245 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00005246 unsigned DiagID = 0;
Chris Lattner60809f52006-11-28 05:18:46 +00005247 SourceLocation Loc = Tok.getLocation();
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005248
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005249 switch (Tok.getKind()) {
Douglas Gregor28c78432010-08-27 17:35:51 +00005250 case tok::code_completion:
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005251 if (CodeCompletionHandler)
5252 (*CodeCompletionHandler)();
5253 else
5254 Actions.CodeCompleteTypeQualifiers(DS);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00005255 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00005256
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005257 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00005258 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005259 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005260 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005261 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00005262 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005263 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005264 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005265 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00005266 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005267 getLangOpts());
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005268 break;
Richard Smith8e1ac332013-03-28 01:55:44 +00005269 case tok::kw__Atomic:
5270 if (!AtomicAllowed)
5271 goto DoneWithTypeQuals;
5272 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5273 getLangOpts());
5274 break;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005275
5276 // OpenCL qualifiers:
Anastasia Stulova948e37c2019-03-25 11:54:02 +00005277 case tok::kw_private:
Anastasia Stulova314fab62019-03-28 11:47:14 +00005278 if (!getLangOpts().OpenCL)
5279 goto DoneWithTypeQuals;
5280 LLVM_FALLTHROUGH;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005281 case tok::kw___private:
5282 case tok::kw___global:
5283 case tok::kw___local:
5284 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005285 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005286 case tok::kw___read_only:
5287 case tok::kw___write_only:
5288 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00005289 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005290 break;
5291
Andrey Bokhanko45d41322016-05-11 18:38:21 +00005292 case tok::kw___unaligned:
5293 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5294 getLangOpts());
5295 break;
Aaron Ballman317a77f2013-05-22 23:25:32 +00005296 case tok::kw___uptr:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005297 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
Alp Toker62c5b572013-11-26 01:30:10 +00005298 // with the MS modifier keyword.
Aaron Ballman08b06592014-07-22 12:44:22 +00005299 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
Alp Toker47642d22013-12-03 06:13:01 +00005300 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5301 if (TryKeywordIdentFallback(false))
5302 continue;
Alp Toker62c5b572013-11-26 01:30:10 +00005303 }
Galina Kistanova77674252017-06-01 21:15:34 +00005304 LLVM_FALLTHROUGH;
Alp Toker62c5b572013-11-26 01:30:10 +00005305 case tok::kw___sptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005306 case tok::kw___w64:
Steve Narofff9c29d42008-12-25 14:41:26 +00005307 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005308 case tok::kw___ptr32:
Steve Naroff44ac7772008-12-25 14:16:32 +00005309 case tok::kw___cdecl:
5310 case tok::kw___stdcall:
5311 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005312 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005313 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005314 case tok::kw___vectorcall:
Aaron Ballman08b06592014-07-22 12:44:22 +00005315 if (AttrReqs & AR_DeclspecAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005316 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00005317 continue;
5318 }
5319 goto DoneWithTypeQuals;
Dawn Perchik335e16b2010-09-03 01:29:35 +00005320 case tok::kw___pascal:
Aaron Ballman08b06592014-07-22 12:44:22 +00005321 if (AttrReqs & AR_VendorAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005322 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00005323 continue;
5324 }
5325 goto DoneWithTypeQuals;
Douglas Gregor261a89b2015-06-19 17:51:05 +00005326
5327 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005328 case tok::kw__Nonnull:
5329 case tok::kw__Nullable:
5330 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005331 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5332 continue;
5333
Douglas Gregorab209d82015-07-07 03:58:42 +00005334 // Objective-C 'kindof' types.
5335 case tok::kw___kindof:
5336 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00005337 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00005338 (void)ConsumeToken();
5339 continue;
5340
Chris Lattnere37e2332006-08-15 04:50:22 +00005341 case tok::kw___attribute:
Aaron Ballman08b06592014-07-22 12:44:22 +00005342 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5343 // When GNU attributes are expressly forbidden, diagnose their usage.
5344 Diag(Tok, diag::err_attributes_not_allowed);
5345
5346 // Parse the attributes even if they are rejected to ensure that error
5347 // recovery is graceful.
5348 if (AttrReqs & AR_GNUAttributesParsed ||
5349 AttrReqs & AR_GNUAttributesParsedAndRejected) {
John McCall53fa7142010-12-24 02:08:15 +00005350 ParseGNUAttributes(DS.getAttributes());
Chris Lattnercf0bab22008-12-18 07:02:59 +00005351 continue; // do *not* consume the next token!
5352 }
5353 // otherwise, FALL THROUGH!
Galina Kistanova77674252017-06-01 21:15:34 +00005354 LLVM_FALLTHROUGH;
Chris Lattnercf0bab22008-12-18 07:02:59 +00005355 default:
Steve Naroff44ac7772008-12-25 14:16:32 +00005356 DoneWithTypeQuals:
Chris Lattnercf0bab22008-12-18 07:02:59 +00005357 // If this is not a type-qualifier token, we're done reading type
5358 // qualifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00005359 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005360 if (EndLoc.isValid())
5361 DS.SetRangeEnd(EndLoc);
Chris Lattnercf0bab22008-12-18 07:02:59 +00005362 return;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005363 }
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00005364
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005365 // If the specifier combination wasn't legal, issue a diagnostic.
5366 if (isInvalid) {
5367 assert(PrevSpec && "Method did not return previous specifier!");
Chris Lattner6d29c102008-11-18 07:48:38 +00005368 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005369 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005370 EndLoc = ConsumeToken();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005371 }
5372}
5373
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005374/// ParseDeclarator - Parse and verify a newly-initialized declarator.
5375///
5376void Parser::ParseDeclarator(Declarator &D) {
5377 /// This implements the 'declarator' production in the C grammar, then checks
5378 /// for well-formedness and issues diagnostics.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005379 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005380}
5381
Richard Smith0b350b92014-10-28 16:55:02 +00005382static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
Faisal Vali421b2d12017-12-29 05:41:00 +00005383 DeclaratorContext TheContext) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005384 if (Kind == tok::star || Kind == tok::caret)
5385 return true;
5386
Xiuli Pan9c14e282016-01-09 12:53:17 +00005387 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5388 return true;
5389
Richard Smith0efa75c2012-03-29 01:16:42 +00005390 if (!Lang.CPlusPlus)
5391 return false;
5392
Richard Smith0b350b92014-10-28 16:55:02 +00005393 if (Kind == tok::amp)
5394 return true;
5395
5396 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5397 // But we must not parse them in conversion-type-ids and new-type-ids, since
5398 // those can be legitimately followed by a && operator.
5399 // (The same thing can in theory happen after a trailing-return-type, but
5400 // since those are a C++11 feature, there is no rejects-valid issue there.)
5401 if (Kind == tok::ampamp)
Faisal Vali421b2d12017-12-29 05:41:00 +00005402 return Lang.CPlusPlus11 ||
5403 (TheContext != DeclaratorContext::ConversionIdContext &&
5404 TheContext != DeclaratorContext::CXXNewContext);
Richard Smith0b350b92014-10-28 16:55:02 +00005405
5406 return false;
Richard Smith0efa75c2012-03-29 01:16:42 +00005407}
5408
Xiuli Pan9c14e282016-01-09 12:53:17 +00005409// Indicates whether the given declarator is a pipe declarator.
5410static bool isPipeDeclerator(const Declarator &D) {
5411 const unsigned NumTypes = D.getNumTypeObjects();
5412
5413 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5414 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5415 return true;
5416
5417 return false;
5418}
5419
Sebastian Redlbd150f42008-11-21 19:14:01 +00005420/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5421/// is parsed by the function passed to it. Pass null, and the direct-declarator
5422/// isn't parsed at all, making this function effectively parse the C++
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005423/// ptr-operator production.
5424///
Richard Smith09f76ee2011-10-19 21:33:05 +00005425/// If the grammar of this construct is extended, matching changes must also be
Richard Smith1453e312012-03-27 01:42:32 +00005426/// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5427/// isConstructorDeclarator.
Richard Smith09f76ee2011-10-19 21:33:05 +00005428///
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005429/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5430/// [C] pointer[opt] direct-declarator
5431/// [C++] direct-declarator
5432/// [C++] ptr-operator declarator
Chris Lattner6c7416c2006-08-07 00:19:33 +00005433///
5434/// pointer: [C99 6.7.5]
5435/// '*' type-qualifier-list[opt]
5436/// '*' type-qualifier-list[opt] pointer
5437///
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005438/// ptr-operator:
5439/// '*' cv-qualifier-seq[opt]
5440/// '&'
Sebastian Redled0f3b02009-03-15 22:02:01 +00005441/// [C++0x] '&&'
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005442/// [GNU] '&' restrict[opt] attributes[opt]
Sebastian Redled0f3b02009-03-15 22:02:01 +00005443/// [GNU?] '&&' restrict[opt] attributes[opt]
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005444/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
Sebastian Redlbd150f42008-11-21 19:14:01 +00005445void Parser::ParseDeclaratorInternal(Declarator &D,
5446 DirectDeclParseFunction DirectDeclParser) {
Douglas Gregor66a985d2009-08-26 14:27:30 +00005447 if (Diags.hasAllExtensionsSilenced())
5448 D.setExtension();
Chad Rosierc1183952012-06-26 22:30:43 +00005449
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005450 // C++ member pointers start with a '::' or a nested-name.
5451 // Member pointers get special handling, since there's no place for the
5452 // scope spec in the generic path below.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005453 if (getLangOpts().CPlusPlus &&
Richard Smith83c2ecf2016-02-02 23:34:49 +00005454 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
Serge Pavlov458ea762014-07-16 05:16:52 +00005455 (Tok.is(tok::identifier) &&
5456 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
Chris Lattner803802d2009-03-24 17:04:48 +00005457 Tok.is(tok::annot_cxxscope))) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005458 bool EnteringContext =
5459 D.getContext() == DeclaratorContext::FileContext ||
5460 D.getContext() == DeclaratorContext::MemberContext;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005461 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005462 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005463
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +00005464 if (SS.isNotEmpty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005465 if (Tok.isNot(tok::star)) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005466 // The scope spec really belongs to the direct-declarator.
Richard Smith5f044ad2013-01-08 22:43:49 +00005467 if (D.mayHaveIdentifier())
5468 D.getCXXScopeSpec() = SS;
5469 else
5470 AnnotateScopeToken(SS, true);
5471
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005472 if (DirectDeclParser)
5473 (this->*DirectDeclParser)(D);
5474 return;
5475 }
5476
5477 SourceLocation Loc = ConsumeToken();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005478 D.SetRangeEnd(Loc);
John McCall084e83d2011-03-24 11:26:52 +00005479 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005480 ParseTypeQualifierListOpt(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005481 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005482
5483 // Recurse to parse whatever is left.
5484 ParseDeclaratorInternal(D, DirectDeclParser);
5485
5486 // Sema will have to catch (syntactically invalid) pointers into global
5487 // scope. It has to catch pointers into namespace scope anyway.
Erich Keanec480f302018-07-12 21:09:05 +00005488 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005489 SS, DS.getTypeQualifiers(), DS.getEndLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005490 std::move(DS.getAttributes()),
5491 /* Don't replace range end. */ SourceLocation());
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005492 return;
5493 }
5494 }
5495
5496 tok::TokenKind Kind = Tok.getKind();
Xiuli Pan9c14e282016-01-09 12:53:17 +00005497
5498 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
Xiuli Pan11e13f62016-02-26 03:13:03 +00005499 DeclSpec DS(AttrFactory);
5500 ParseTypeQualifierListOpt(DS);
Xiuli Pan9c14e282016-01-09 12:53:17 +00005501
5502 D.AddTypeInfo(
5503 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005504 std::move(DS.getAttributes()), SourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00005505 }
5506
Steve Naroffec33ed92008-08-27 16:04:49 +00005507 // Not a pointer, C++ reference, or block.
Richard Smith0b350b92014-10-28 16:55:02 +00005508 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00005509 if (DirectDeclParser)
5510 (this->*DirectDeclParser)(D);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005511 return;
5512 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005513
Sebastian Redled0f3b02009-03-15 22:02:01 +00005514 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5515 // '&&' -> rvalue reference
Sebastian Redl3b27be62009-03-23 00:00:23 +00005516 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005517 D.SetRangeEnd(Loc);
Bill Wendling3708c182007-05-27 10:15:43 +00005518
Chris Lattner9eac9312009-03-27 04:18:06 +00005519 if (Kind == tok::star || Kind == tok::caret) {
Chris Lattner788404f2008-02-21 01:32:26 +00005520 // Is a pointer.
John McCall084e83d2011-03-24 11:26:52 +00005521 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005522
Aaron Ballman08b06592014-07-22 12:44:22 +00005523 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5524 // C++11 attributes are allowed.
5525 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
Faisal Vali421b2d12017-12-29 05:41:00 +00005526 ((D.getContext() != DeclaratorContext::CXXNewContext)
5527 ? AR_GNUAttributesParsed
5528 : AR_GNUAttributesParsedAndRejected);
Aaron Ballman08b06592014-07-22 12:44:22 +00005529 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005530 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005531
Bill Wendling3708c182007-05-27 10:15:43 +00005532 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005533 ParseDeclaratorInternal(D, DirectDeclParser);
Steve Naroffec33ed92008-08-27 16:04:49 +00005534 if (Kind == tok::star)
5535 // Remember that we parsed a pointer type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005536 D.AddTypeInfo(DeclaratorChunk::getPointer(
5537 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5538 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5539 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5540 std::move(DS.getAttributes()), SourceLocation());
Steve Naroffec33ed92008-08-27 16:04:49 +00005541 else
5542 // Remember that we parsed a Block type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005543 D.AddTypeInfo(
5544 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5545 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005546 } else {
5547 // Is a reference
John McCall084e83d2011-03-24 11:26:52 +00005548 DeclSpec DS(AttrFactory);
Bill Wendling93efb222007-06-02 23:28:54 +00005549
Sebastian Redl3b27be62009-03-23 00:00:23 +00005550 // Complain about rvalue references in C++03, but then go on and build
5551 // the declarator.
Richard Smith5d164bc2011-10-15 05:09:34 +00005552 if (Kind == tok::ampamp)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005553 Diag(Loc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00005554 diag::warn_cxx98_compat_rvalue_reference :
5555 diag::ext_rvalue_reference);
Sebastian Redl3b27be62009-03-23 00:00:23 +00005556
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005557 // GNU-style and C++11 attributes are allowed here, as is restrict.
5558 ParseTypeQualifierListOpt(DS);
5559 D.ExtendWithDeclSpec(DS);
5560
Bill Wendling93efb222007-06-02 23:28:54 +00005561 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5562 // cv-qualifiers are introduced through the use of a typedef or of a
5563 // template type argument, in which case the cv-qualifiers are ignored.
Bill Wendling93efb222007-06-02 23:28:54 +00005564 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5565 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5566 Diag(DS.getConstSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005567 diag::err_invalid_reference_qualifier_application) << "const";
Bill Wendling93efb222007-06-02 23:28:54 +00005568 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5569 Diag(DS.getVolatileSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005570 diag::err_invalid_reference_qualifier_application) << "volatile";
Richard Smith8e1ac332013-03-28 01:55:44 +00005571 // 'restrict' is permitted as an extension.
5572 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5573 Diag(DS.getAtomicSpecLoc(),
5574 diag::err_invalid_reference_qualifier_application) << "_Atomic";
Bill Wendling93efb222007-06-02 23:28:54 +00005575 }
Bill Wendling3708c182007-05-27 10:15:43 +00005576
5577 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005578 ParseDeclaratorInternal(D, DirectDeclParser);
Bill Wendling3708c182007-05-27 10:15:43 +00005579
Douglas Gregor66583c52008-11-03 15:51:28 +00005580 if (D.getNumTypeObjects() > 0) {
5581 // C++ [dcl.ref]p4: There shall be no references to references.
5582 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5583 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
Chris Lattnerebad6a22008-11-19 07:37:42 +00005584 if (const IdentifierInfo *II = D.getIdentifier())
5585 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5586 << II;
5587 else
5588 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5589 << "type name";
Douglas Gregor66583c52008-11-03 15:51:28 +00005590
Sebastian Redlbd150f42008-11-21 19:14:01 +00005591 // Once we've complained about the reference-to-reference, we
Douglas Gregor66583c52008-11-03 15:51:28 +00005592 // can go ahead and build the (technically ill-formed)
5593 // declarator: reference collapsing will take care of it.
5594 }
5595 }
5596
Richard Smith8e1ac332013-03-28 01:55:44 +00005597 // Remember that we parsed a reference type.
Chris Lattner788404f2008-02-21 01:32:26 +00005598 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
Sebastian Redled0f3b02009-03-15 22:02:01 +00005599 Kind == tok::amp),
Erich Keanec480f302018-07-12 21:09:05 +00005600 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005601 }
Chris Lattner6c7416c2006-08-07 00:19:33 +00005602}
5603
Richard Trieuf4b81d02014-06-24 23:14:24 +00005604// When correcting from misplaced brackets before the identifier, the location
5605// is saved inside the declarator so that other diagnostic messages can use
5606// them. This extracts and returns that location, or returns the provided
5607// location if a stored location does not exist.
5608static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5609 SourceLocation Loc) {
5610 if (D.getName().StartLocation.isInvalid() &&
5611 D.getName().EndLocation.isValid())
5612 return D.getName().EndLocation;
5613
5614 return Loc;
5615}
5616
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005617/// ParseDirectDeclarator
5618/// direct-declarator: [C99 6.7.5]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005619/// [C99] identifier
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005620/// '(' declarator ')'
5621/// [GNU] '(' attributes declarator ')'
Chris Lattnere8074e62006-08-06 18:30:15 +00005622/// [C90] direct-declarator '[' constant-expression[opt] ']'
5623/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5624/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5625/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5626/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005627/// [C++11] direct-declarator '[' constant-expression[opt] ']'
5628/// attribute-specifier-seq[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005629/// direct-declarator '(' parameter-type-list ')'
5630/// direct-declarator '(' identifier-list[opt] ')'
5631/// [GNU] direct-declarator '(' parameter-forward-declarations
5632/// parameter-type-list[opt] ')'
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00005633/// [C++] direct-declarator '(' parameter-declaration-clause ')'
5634/// cv-qualifier-seq[opt] exception-specification[opt]
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005635/// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5636/// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5637/// ref-qualifier[opt] exception-specification[opt]
Douglas Gregor61956c42008-10-31 09:07:45 +00005638/// [C++] declarator-id
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005639/// [C++11] declarator-id attribute-specifier-seq[opt]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005640///
5641/// declarator-id: [C++ 8]
Douglas Gregor27b4c162010-12-23 22:44:42 +00005642/// '...'[opt] id-expression
Douglas Gregor831c93f2008-11-05 20:51:48 +00005643/// '::'[opt] nested-name-specifier[opt] type-name
5644///
5645/// id-expression: [C++ 5.1]
5646/// unqualified-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005647/// qualified-id
Douglas Gregor831c93f2008-11-05 20:51:48 +00005648///
5649/// unqualified-id: [C++ 5.1]
Mike Stump11289f42009-09-09 15:08:12 +00005650/// identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005651/// operator-function-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005652/// conversion-function-id
Mike Stump11289f42009-09-09 15:08:12 +00005653/// '~' class-name
Douglas Gregor7f741122009-02-25 19:37:18 +00005654/// template-id
Argyrios Kyrtzidise4426352008-11-07 22:02:30 +00005655///
Richard Smithbdb84f32016-07-22 23:36:59 +00005656/// C++17 adds the following, which we also handle here:
5657///
5658/// simple-declaration:
5659/// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5660///
Richard Smith1453e312012-03-27 01:42:32 +00005661/// Note, any additional constructs added here may need corresponding changes
5662/// in isConstructorDeclarator.
Chris Lattneracd58a32006-08-06 17:24:14 +00005663void Parser::ParseDirectDeclarator(Declarator &D) {
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005664 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005665
David Blaikiebbafb8a2012-03-11 07:00:24 +00005666 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
Richard Smithbdb84f32016-07-22 23:36:59 +00005667 // This might be a C++17 structured binding.
5668 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5669 D.getCXXScopeSpec().isEmpty())
5670 return ParseDecompositionDeclarator(D);
5671
Serge Pavlov458ea762014-07-16 05:16:52 +00005672 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5673 // this context it is a bitfield. Also in range-based for statement colon
5674 // may delimit for-range-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00005675 ColonProtectionRAIIObject X(
5676 *this, D.getContext() == DeclaratorContext::MemberContext ||
5677 (D.getContext() == DeclaratorContext::ForContext &&
5678 getLangOpts().CPlusPlus11));
Serge Pavlov458ea762014-07-16 05:16:52 +00005679
Douglas Gregor7861a802009-11-03 01:35:08 +00005680 // ParseDeclaratorInternal might already have parsed the scope.
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005681 if (D.getCXXScopeSpec().isEmpty()) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005682 bool EnteringContext =
5683 D.getContext() == DeclaratorContext::FileContext ||
5684 D.getContext() == DeclaratorContext::MemberContext;
David Blaikieefdccaa2016-01-15 23:43:34 +00005685 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005686 EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005687 }
5688
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005689 if (D.getCXXScopeSpec().isValid()) {
Richard Smith64e033f2015-01-15 00:48:52 +00005690 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5691 D.getCXXScopeSpec()))
John McCall2b058ef2009-12-11 20:04:54 +00005692 // Change the declaration context for name lookup, until this function
5693 // is exited (and the declarator has been parsed).
5694 DeclScopeObj.EnterDeclaratorScope();
Alex Lorenze151f0102016-12-07 10:24:44 +00005695 else if (getObjCDeclContext()) {
5696 // Ensure that we don't interpret the next token as an identifier when
5697 // dealing with declarations in an Objective-C container.
5698 D.SetIdentifier(nullptr, Tok.getLocation());
5699 D.setInvalidType(true);
5700 ConsumeToken();
5701 goto PastIdentifier;
5702 }
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005703 }
5704
Douglas Gregor27b4c162010-12-23 22:44:42 +00005705 // C++0x [dcl.fct]p14:
Faisal Vali8435a692014-12-04 12:40:21 +00005706 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5707 // parameter-declaration-clause without a preceding comma. In this case,
5708 // the ellipsis is parsed as part of the abstract-declarator if the type
5709 // of the parameter either names a template parameter pack that has not
5710 // been expanded or contains auto; otherwise, it is parsed as part of the
5711 // parameter-declaration-clause.
Richard Smith0efa75c2012-03-29 01:16:42 +00005712 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00005713 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5714 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5715 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
Douglas Gregor27b4c162010-12-23 22:44:42 +00005716 NextToken().is(tok::r_paren) &&
Richard Smithb19337f2013-02-20 20:19:27 +00005717 !D.hasGroupingParens() &&
Faisal Vali8435a692014-12-04 12:40:21 +00005718 !Actions.containsUnexpandedParameterPacks(D) &&
Faisal Vali090da2d2018-01-01 18:23:28 +00005719 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005720 SourceLocation EllipsisLoc = ConsumeToken();
Richard Smith0b350b92014-10-28 16:55:02 +00005721 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005722 // The ellipsis was put in the wrong place. Recover, and explain to
5723 // the user what they should have done.
5724 ParseDeclarator(D);
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00005725 if (EllipsisLoc.isValid())
5726 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00005727 return;
5728 } else
5729 D.setEllipsisLoc(EllipsisLoc);
5730
5731 // The ellipsis can't be followed by a parenthesized declarator. We
5732 // check for that in ParseParenDeclarator, after we have disambiguated
5733 // the l_paren token.
5734 }
5735
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005736 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5737 tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00005738 // We found something that indicates the start of an unqualified-id.
5739 // Parse that unqualified-id.
John McCall84821e72010-04-13 06:39:49 +00005740 bool AllowConstructorName;
Richard Smith35845152017-02-07 01:37:30 +00005741 bool AllowDeductionGuide;
5742 if (D.getDeclSpec().hasTypeSpecifier()) {
John McCall84821e72010-04-13 06:39:49 +00005743 AllowConstructorName = false;
Richard Smith35845152017-02-07 01:37:30 +00005744 AllowDeductionGuide = false;
5745 } else if (D.getCXXScopeSpec().isSet()) {
John McCall84821e72010-04-13 06:39:49 +00005746 AllowConstructorName =
Faisal Vali421b2d12017-12-29 05:41:00 +00005747 (D.getContext() == DeclaratorContext::FileContext ||
5748 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005749 AllowDeductionGuide = false;
5750 } else {
Faisal Vali421b2d12017-12-29 05:41:00 +00005751 AllowConstructorName =
5752 (D.getContext() == DeclaratorContext::MemberContext);
Fangrui Song6907ce22018-07-30 19:24:48 +00005753 AllowDeductionGuide =
Faisal Vali421b2d12017-12-29 05:41:00 +00005754 (D.getContext() == DeclaratorContext::FileContext ||
5755 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005756 }
John McCall84821e72010-04-13 06:39:49 +00005757
Richard Smith64e033f2015-01-15 00:48:52 +00005758 bool HadScope = D.getCXXScopeSpec().isValid();
Chad Rosierc1183952012-06-26 22:30:43 +00005759 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5760 /*EnteringContext=*/true,
David Blaikieefdccaa2016-01-15 23:43:34 +00005761 /*AllowDestructorName=*/true, AllowConstructorName,
Richard Smithc08b6932018-04-27 02:00:13 +00005762 AllowDeductionGuide, nullptr, nullptr,
Richard Smith35845152017-02-07 01:37:30 +00005763 D.getName()) ||
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005764 // Once we're past the identifier, if the scope was bad, mark the
5765 // whole declarator bad.
5766 D.getCXXScopeSpec().isInvalid()) {
Craig Topper161e4db2014-05-21 06:02:52 +00005767 D.SetIdentifier(nullptr, Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005768 D.setInvalidType(true);
Douglas Gregor7861a802009-11-03 01:35:08 +00005769 } else {
Richard Smith64e033f2015-01-15 00:48:52 +00005770 // ParseUnqualifiedId might have parsed a scope specifier during error
5771 // recovery. If it did so, enter that scope.
5772 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5773 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5774 D.getCXXScopeSpec()))
5775 DeclScopeObj.EnterDeclaratorScope();
5776
Douglas Gregor7861a802009-11-03 01:35:08 +00005777 // Parsed the unqualified-id; update range information and move along.
5778 if (D.getSourceRange().getBegin().isInvalid())
5779 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5780 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005781 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005782 goto PastIdentifier;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005783 }
Richard Smithd63db6e2015-12-19 02:40:19 +00005784
5785 if (D.getCXXScopeSpec().isNotEmpty()) {
5786 // We have a scope specifier but no following unqualified-id.
5787 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5788 diag::err_expected_unqualified_id)
5789 << /*C++*/1;
5790 D.SetIdentifier(nullptr, Tok.getLocation());
5791 goto PastIdentifier;
5792 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005793 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005794 assert(!getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005795 "There's a C++-specific check for tok::identifier above");
5796 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5797 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Richard Trieu2664dc12014-05-05 22:06:50 +00005798 D.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005799 ConsumeToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00005800 goto PastIdentifier;
Richard Smith74639b12017-05-19 01:54:59 +00005801 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5802 // We're not allowed an identifier here, but we got one. Try to figure out
5803 // if the user was trying to attach a name to the type, or whether the name
5804 // is some unrelated trailing syntax.
5805 bool DiagnoseIdentifier = false;
5806 if (D.hasGroupingParens())
5807 // An identifier within parens is unlikely to be intended to be anything
5808 // other than a name being "declared".
5809 DiagnoseIdentifier = true;
Richard Smith77a9c602018-02-28 03:02:23 +00005810 else if (D.getContext() == DeclaratorContext::TemplateArgContext)
Richard Smith74639b12017-05-19 01:54:59 +00005811 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5812 DiagnoseIdentifier =
5813 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali421b2d12017-12-29 05:41:00 +00005814 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5815 D.getContext() == DeclaratorContext::AliasTemplateContext)
Richard Smith74639b12017-05-19 01:54:59 +00005816 // The most likely error is that the ';' was forgotten.
5817 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
Richard Smithe303e352018-02-02 22:24:54 +00005818 else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5819 D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
Richard Smith74639b12017-05-19 01:54:59 +00005820 !isCXX11VirtSpecifier(Tok))
5821 DiagnoseIdentifier = NextToken().isOneOf(
5822 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5823 if (DiagnoseIdentifier) {
Richard Smithf39720b2013-10-13 22:12:28 +00005824 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5825 << FixItHint::CreateRemoval(Tok.getLocation());
Craig Topper161e4db2014-05-21 06:02:52 +00005826 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithf39720b2013-10-13 22:12:28 +00005827 ConsumeToken();
5828 goto PastIdentifier;
5829 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005830 }
Richard Smith0efa75c2012-03-29 01:16:42 +00005831
Douglas Gregor7861a802009-11-03 01:35:08 +00005832 if (Tok.is(tok::l_paren)) {
Richard Smithe303e352018-02-02 22:24:54 +00005833 // If this might be an abstract-declarator followed by a direct-initializer,
5834 // check whether this is a valid declarator chunk. If it can't be, assume
5835 // that it's an initializer instead.
5836 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5837 RevertingTentativeParsingAction PA(*this);
5838 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5839 TPResult::False) {
5840 D.SetIdentifier(nullptr, Tok.getLocation());
5841 goto PastIdentifier;
5842 }
5843 }
5844
Chris Lattneracd58a32006-08-06 17:24:14 +00005845 // direct-declarator: '(' declarator ')'
Chris Lattnere37e2332006-08-15 04:50:22 +00005846 // direct-declarator: '(' attributes declarator ')'
Chris Lattneracd58a32006-08-06 17:24:14 +00005847 // Example: 'char (*X)' or 'int (*XX)(void)'
5848 ParseParenDeclarator(D);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005849
5850 // If the declarator was parenthesized, we entered the declarator
5851 // scope when parsing the parenthesized declarator, then exited
5852 // the scope already. Re-enter the scope, if we need to.
5853 if (D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005854 // If there was an error parsing parenthesized declarator, declarator
Richard Smith0efa75c2012-03-29 01:16:42 +00005855 // scope may have been entered before. Don't do it again.
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005856 if (!D.isInvalidType() &&
Nico Weber6b05f382015-02-18 04:53:03 +00005857 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5858 D.getCXXScopeSpec()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005859 // Change the declaration context for name lookup, until this function
5860 // is exited (and the declarator has been parsed).
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005861 DeclScopeObj.EnterDeclaratorScope();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005862 }
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005863 } else if (D.mayOmitIdentifier()) {
Chris Lattneracd58a32006-08-06 17:24:14 +00005864 // This could be something simple like "int" (in which case the declarator
5865 // portion is empty), if an abstract-declarator is allowed.
Craig Topper161e4db2014-05-21 06:02:52 +00005866 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithb19337f2013-02-20 20:19:27 +00005867
5868 // The grammar for abstract-pack-declarator does not allow grouping parens.
5869 // FIXME: Revisit this once core issue 1488 is resolved.
5870 if (D.hasEllipsis() && D.hasGroupingParens())
5871 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5872 diag::ext_abstract_pack_declarator_parens);
Chris Lattneracd58a32006-08-06 17:24:14 +00005873 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00005874 if (Tok.getKind() == tok::annot_pragma_parser_crash)
David Blaikie5bd4c2a2012-08-21 18:56:49 +00005875 LLVM_BUILTIN_TRAP;
Richard Trieuf4b81d02014-06-24 23:14:24 +00005876 if (Tok.is(tok::l_square))
5877 return ParseMisplacedBracketDeclarator(D);
Faisal Vali421b2d12017-12-29 05:41:00 +00005878 if (D.getContext() == DeclaratorContext::MemberContext) {
Alex Lorenzf1278212017-04-11 15:01:53 +00005879 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5880 // treating these keyword as valid member names.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005881 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
Alex Lorenzf1278212017-04-11 15:01:53 +00005882 Tok.getIdentifierInfo() &&
5883 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5884 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5885 diag::err_expected_member_name_or_semi_objcxx_keyword)
5886 << Tok.getIdentifierInfo()
5887 << (D.getDeclSpec().isEmpty() ? SourceRange()
5888 : D.getDeclSpec().getSourceRange());
5889 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5890 D.SetRangeEnd(Tok.getLocation());
5891 ConsumeToken();
5892 goto PastIdentifier;
5893 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005894 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5895 diag::err_expected_member_name_or_semi)
Richard Trieua1342402014-05-02 23:40:32 +00005896 << (D.getDeclSpec().isEmpty() ? SourceRange()
5897 : D.getDeclSpec().getSourceRange());
Richard Trieuf4b81d02014-06-24 23:14:24 +00005898 } else if (getLangOpts().CPlusPlus) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005899 if (Tok.isOneOf(tok::period, tok::arrow))
Richard Trieu9c672672013-01-26 02:31:38 +00005900 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
Richard Trieu2f586962013-09-05 02:31:33 +00005901 else {
5902 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5903 if (Tok.isAtStartOfLine() && Loc.isValid())
5904 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5905 << getLangOpts().CPlusPlus;
5906 else
Richard Trieuf4b81d02014-06-24 23:14:24 +00005907 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5908 diag::err_expected_unqualified_id)
Richard Trieu2f586962013-09-05 02:31:33 +00005909 << getLangOpts().CPlusPlus;
5910 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005911 } else {
5912 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5913 diag::err_expected_either)
5914 << tok::identifier << tok::l_paren;
5915 }
Craig Topper161e4db2014-05-21 06:02:52 +00005916 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattner8c5dd732008-11-11 06:13:16 +00005917 D.setInvalidType(true);
Chris Lattneracd58a32006-08-06 17:24:14 +00005918 }
Mike Stump11289f42009-09-09 15:08:12 +00005919
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005920 PastIdentifier:
Chris Lattneracd58a32006-08-06 17:24:14 +00005921 assert(D.isPastIdentifier() &&
5922 "Haven't past the location of the identifier yet?");
Mike Stump11289f42009-09-09 15:08:12 +00005923
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005924 // Don't parse attributes unless we have parsed an unparenthesized name.
5925 if (D.hasName() && !D.getNumTypeObjects())
Richard Smith89645bc2013-01-02 12:01:23 +00005926 MaybeParseCXX11Attributes(D);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005927
Chris Lattneracd58a32006-08-06 17:24:14 +00005928 while (1) {
Chris Lattner76c72282007-10-09 17:33:22 +00005929 if (Tok.is(tok::l_paren)) {
David Blaikie15a430a2011-12-04 05:04:18 +00005930 // Enter function-declaration scope, limiting any declarators to the
5931 // function prototype scope, including parameter declarators.
5932 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00005933 Scope::FunctionPrototypeScope|Scope::DeclScope|
5934 (D.isFunctionDeclaratorAFunctionDeclaration()
5935 ? Scope::FunctionDeclarationScope : 0));
5936
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005937 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5938 // In such a case, check if we actually have a function declarator; if it
5939 // is not, the declarator has been fully parsed.
Richard Smith943c4402012-07-30 21:30:52 +00005940 bool IsAmbiguous = false;
Richard Smith4f605af2012-08-18 00:55:03 +00005941 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5942 // The name of the declarator, if any, is tentatively declared within
5943 // a possible direct initializer.
5944 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5945 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5946 TentativelyDeclaredIdentifiers.pop_back();
5947 if (!IsFunctionDecl)
5948 break;
5949 }
John McCall084e83d2011-03-24 11:26:52 +00005950 ParsedAttributes attrs(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005951 BalancedDelimiterTracker T(*this, tok::l_paren);
5952 T.consumeOpen();
Richard Smith943c4402012-07-30 21:30:52 +00005953 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
David Blaikie15a430a2011-12-04 05:04:18 +00005954 PrototypeScope.Exit();
Chris Lattner76c72282007-10-09 17:33:22 +00005955 } else if (Tok.is(tok::l_square)) {
Chris Lattnere8074e62006-08-06 18:30:15 +00005956 ParseBracketDeclarator(D);
Chris Lattneracd58a32006-08-06 17:24:14 +00005957 } else {
5958 break;
5959 }
5960 }
Chad Rosierc1183952012-06-26 22:30:43 +00005961}
Chris Lattneracd58a32006-08-06 17:24:14 +00005962
Richard Smithbdb84f32016-07-22 23:36:59 +00005963void Parser::ParseDecompositionDeclarator(Declarator &D) {
5964 assert(Tok.is(tok::l_square));
5965
5966 // If this doesn't look like a structured binding, maybe it's a misplaced
5967 // array declarator.
5968 // FIXME: Consume the l_square first so we don't need extra lookahead for
5969 // this.
5970 if (!(NextToken().is(tok::identifier) &&
5971 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5972 !(NextToken().is(tok::r_square) &&
5973 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5974 return ParseMisplacedBracketDeclarator(D);
5975
5976 BalancedDelimiterTracker T(*this, tok::l_square);
5977 T.consumeOpen();
5978
5979 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5980 while (Tok.isNot(tok::r_square)) {
5981 if (!Bindings.empty()) {
5982 if (Tok.is(tok::comma))
5983 ConsumeToken();
5984 else {
5985 if (Tok.is(tok::identifier)) {
5986 SourceLocation EndLoc = getEndOfPreviousToken();
5987 Diag(EndLoc, diag::err_expected)
5988 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5989 } else {
5990 Diag(Tok, diag::err_expected_comma_or_rsquare);
5991 }
5992
5993 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5994 StopAtSemi | StopBeforeMatch);
5995 if (Tok.is(tok::comma))
5996 ConsumeToken();
5997 else if (Tok.isNot(tok::identifier))
5998 break;
5999 }
6000 }
6001
6002 if (Tok.isNot(tok::identifier)) {
6003 Diag(Tok, diag::err_expected) << tok::identifier;
6004 break;
6005 }
6006
6007 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
6008 ConsumeToken();
6009 }
6010
6011 if (Tok.isNot(tok::r_square))
6012 // We've already diagnosed a problem here.
6013 T.skipToEnd();
6014 else {
6015 // C++17 does not allow the identifier-list in a structured binding
6016 // to be empty.
6017 if (Bindings.empty())
6018 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
6019
6020 T.consumeClose();
6021 }
6022
6023 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
6024 T.getCloseLocation());
6025}
6026
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006027/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
6028/// only called before the identifier, so these are most likely just grouping
Mike Stump11289f42009-09-09 15:08:12 +00006029/// parens for precedence. If we find that these are actually function
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006030/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
6031///
6032/// direct-declarator:
6033/// '(' declarator ')'
6034/// [GNU] '(' attributes declarator ')'
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006035/// direct-declarator '(' parameter-type-list ')'
6036/// direct-declarator '(' identifier-list[opt] ')'
6037/// [GNU] direct-declarator '(' parameter-forward-declarations
6038/// parameter-type-list[opt] ')'
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006039///
6040void Parser::ParseParenDeclarator(Declarator &D) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006041 BalancedDelimiterTracker T(*this, tok::l_paren);
6042 T.consumeOpen();
6043
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006044 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
Mike Stump11289f42009-09-09 15:08:12 +00006045
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006046 // Eat any attributes before we look at whether this is a grouping or function
6047 // declarator paren. If this is a grouping paren, the attribute applies to
6048 // the type being built up, for example:
6049 // int (__attribute__(()) *x)(long y)
6050 // If this ends up not being a grouping paren, the attribute applies to the
6051 // first argument, for example:
6052 // int (__attribute__(()) int x)
6053 // In either case, we need to eat any attributes to be able to determine what
6054 // sort of paren this is.
6055 //
John McCall084e83d2011-03-24 11:26:52 +00006056 ParsedAttributes attrs(AttrFactory);
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006057 bool RequiresArg = false;
6058 if (Tok.is(tok::kw___attribute)) {
John McCall53fa7142010-12-24 02:08:15 +00006059 ParseGNUAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006060
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006061 // We require that the argument list (if this is a non-grouping paren) be
6062 // present even if the attribute list was empty.
6063 RequiresArg = true;
6064 }
Chad Rosiereea9ca72012-12-21 21:22:20 +00006065
Steve Naroff44ac7772008-12-25 14:16:32 +00006066 // Eat any Microsoft extensions.
Chad Rosiereea9ca72012-12-21 21:22:20 +00006067 ParseMicrosoftTypeAttributes(attrs);
6068
Dawn Perchik335e16b2010-09-03 01:29:35 +00006069 // Eat any Borland extensions.
Ted Kremenek5eec2b02010-11-10 05:59:39 +00006070 if (Tok.is(tok::kw___pascal))
John McCall53fa7142010-12-24 02:08:15 +00006071 ParseBorlandTypeAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006072
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006073 // If we haven't past the identifier yet (or where the identifier would be
6074 // stored, if this is an abstract declarator), then this is probably just
6075 // grouping parens. However, if this could be an abstract-declarator, then
6076 // this could also be the start of function arguments (consider 'void()').
6077 bool isGrouping;
Mike Stump11289f42009-09-09 15:08:12 +00006078
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006079 if (!D.mayOmitIdentifier()) {
6080 // If this can't be an abstract-declarator, this *must* be a grouping
6081 // paren, because we haven't seen the identifier yet.
6082 isGrouping = true;
6083 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
Richard Smith43f340f2012-03-27 23:05:05 +00006084 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6085 NextToken().is(tok::r_paren)) || // C++ int(...)
Richard Smith2620cd92012-04-11 04:01:28 +00006086 isDeclarationSpecifier() || // 'int(int)' is a function.
6087 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006088 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6089 // considered to be a type, not a K&R identifier-list.
6090 isGrouping = false;
6091 } else {
6092 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6093 isGrouping = true;
6094 }
Mike Stump11289f42009-09-09 15:08:12 +00006095
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006096 // If this is a grouping paren, handle:
6097 // direct-declarator: '(' declarator ')'
6098 // direct-declarator: '(' attributes declarator ')'
6099 if (isGrouping) {
Richard Smith0efa75c2012-03-29 01:16:42 +00006100 SourceLocation EllipsisLoc = D.getEllipsisLoc();
6101 D.setEllipsisLoc(SourceLocation());
6102
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006103 bool hadGroupingParens = D.hasGroupingParens();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006104 D.setGroupingParens(true);
Sebastian Redlbd150f42008-11-21 19:14:01 +00006105 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006106 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006107 T.consumeClose();
Erich Keanec480f302018-07-12 21:09:05 +00006108 D.AddTypeInfo(
6109 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6110 std::move(attrs), T.getCloseLocation());
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006111
6112 D.setGroupingParens(hadGroupingParens);
Richard Smith0efa75c2012-03-29 01:16:42 +00006113
6114 // An ellipsis cannot be placed outside parentheses.
6115 if (EllipsisLoc.isValid())
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00006116 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00006117
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006118 return;
6119 }
Mike Stump11289f42009-09-09 15:08:12 +00006120
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006121 // Okay, if this wasn't a grouping paren, it must be the start of a function
6122 // argument list. Recognize that this declarator will never have an
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006123 // identifier (and remember where it would have been), then call into
6124 // ParseFunctionDeclarator to handle of argument list.
Craig Topper161e4db2014-05-21 06:02:52 +00006125 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006126
David Blaikie15a430a2011-12-04 05:04:18 +00006127 // Enter function-declaration scope, limiting any declarators to the
6128 // function prototype scope, including parameter declarators.
6129 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00006130 Scope::FunctionPrototypeScope | Scope::DeclScope |
6131 (D.isFunctionDeclaratorAFunctionDeclaration()
6132 ? Scope::FunctionDeclarationScope : 0));
Richard Smith943c4402012-07-30 21:30:52 +00006133 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
David Blaikie15a430a2011-12-04 05:04:18 +00006134 PrototypeScope.Exit();
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006135}
6136
6137/// ParseFunctionDeclarator - We are after the identifier and have parsed the
6138/// declarator D up to a paren, which indicates that we are parsing function
6139/// arguments.
Chris Lattneracd58a32006-08-06 17:24:14 +00006140///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006141/// If FirstArgAttrs is non-null, then the caller parsed those arguments
6142/// immediately after the open paren - they should be considered to be the
6143/// first argument of a parameter.
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006144///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006145/// If RequiresArg is true, then the first argument of the function is required
6146/// to be present and required to not be an identifier list.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006147///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006148/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6149/// (C++11) ref-qualifier[opt], exception-specification[opt],
6150/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
6151///
6152/// [C++11] exception-specification:
Douglas Gregor9e66af42011-07-05 16:44:18 +00006153/// dynamic-exception-specification
6154/// noexcept-specification
6155///
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006156void Parser::ParseFunctionDeclarator(Declarator &D,
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006157 ParsedAttributes &FirstArgAttrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006158 BalancedDelimiterTracker &Tracker,
Richard Smith943c4402012-07-30 21:30:52 +00006159 bool IsAmbiguous,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006160 bool RequiresArg) {
Chad Rosierc1183952012-06-26 22:30:43 +00006161 assert(getCurScope()->isFunctionPrototypeScope() &&
David Blaikie15a430a2011-12-04 05:04:18 +00006162 "Should call from a Function scope");
Douglas Gregor9e66af42011-07-05 16:44:18 +00006163 // lparen is already consumed!
6164 assert(D.isPastIdentifier() && "Should not call before identifier!");
6165
6166 // This should be true when the function has typed arguments.
6167 // Otherwise, it is treated as a K&R-style function.
6168 bool HasProto = false;
6169 // Build up an array of information about the parsed arguments.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006170 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006171 // Remember where we see an ellipsis, if any.
6172 SourceLocation EllipsisLoc;
6173
6174 DeclSpec DS(AttrFactory);
6175 bool RefQualifierIsLValueRef = true;
6176 SourceLocation RefQualifierLoc;
6177 ExceptionSpecificationType ESpecType = EST_None;
6178 SourceRange ESpecRange;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006179 SmallVector<ParsedType, 2> DynamicExceptions;
6180 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006181 ExprResult NoexceptExpr;
Hans Wennborgdcfba332015-10-06 23:40:43 +00006182 CachedTokens *ExceptionSpecTokens = nullptr;
Aaron Ballman606093a2017-10-15 15:01:42 +00006183 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith700537c2012-06-12 01:51:59 +00006184 TypeResult TrailingReturnType;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006185
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006186 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6187 EndLoc is the end location for the function declarator.
6188 They differ for trailing return types. */
6189 SourceLocation StartLoc, LocalEndLoc, EndLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006190 SourceLocation LParenLoc, RParenLoc;
6191 LParenLoc = Tracker.getOpenLocation();
6192 StartLoc = LParenLoc;
6193
Douglas Gregor9e66af42011-07-05 16:44:18 +00006194 if (isFunctionDeclaratorIdentifierList()) {
6195 if (RequiresArg)
6196 Diag(Tok, diag::err_argument_required_after_attribute);
6197
6198 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6199
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006200 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006201 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006202 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006203 EndLoc = RParenLoc;
Aaron Ballman606093a2017-10-15 15:01:42 +00006204
Fangrui Song6907ce22018-07-30 19:24:48 +00006205 // If there are attributes following the identifier list, parse them and
Aaron Ballman606093a2017-10-15 15:01:42 +00006206 // prohibit them.
6207 MaybeParseCXX11Attributes(FnAttrs);
6208 ProhibitAttributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006209 } else {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006210 if (Tok.isNot(tok::r_paren))
Fangrui Song6907ce22018-07-30 19:24:48 +00006211 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
Faisal Vali2b391ab2013-09-26 19:54:12 +00006212 EllipsisLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006213 else if (RequiresArg)
6214 Diag(Tok, diag::err_argument_required_after_attribute);
6215
Alexey Bader1f277942017-10-11 11:16:31 +00006216 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6217 || getLangOpts().OpenCL;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006218
6219 // If we have the closing ')', eat it.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006220 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006221 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006222 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006223 EndLoc = RParenLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006224
David Blaikiebbafb8a2012-03-11 07:00:24 +00006225 if (getLangOpts().CPlusPlus) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006226 // FIXME: Accept these components in any order, and produce fixits to
6227 // correct the order if the user gets it wrong. Ideally we should deal
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00006228 // with the pure-specifier in the same way.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006229
6230 // Parse cv-qualifier-seq[opt].
Aaron Ballman08b06592014-07-22 12:44:22 +00006231 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
Alex Lorenz8f4d3992017-02-13 23:19:40 +00006232 /*AtomicAllowed*/ false,
6233 /*IdentifierRequired=*/false,
6234 llvm::function_ref<void()>([&]() {
6235 Actions.CodeCompleteFunctionQualifiers(DS, D);
6236 }));
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006237 if (!DS.getSourceRange().getEnd().isInvalid()) {
6238 EndLoc = DS.getSourceRange().getEnd();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006239 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006240
6241 // Parse ref-qualifier[opt].
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006242 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
Douglas Gregor9e66af42011-07-05 16:44:18 +00006243 EndLoc = RefQualifierLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006244
Douglas Gregor3024f072012-04-16 07:05:22 +00006245 // C++11 [expr.prim.general]p3:
Chad Rosierc1183952012-06-26 22:30:43 +00006246 // If a declaration declares a member function or member function
6247 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00006248 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Chad Rosierc1183952012-06-26 22:30:43 +00006249 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00006250 // declarator.
Richard Smithad1bbb92013-03-15 00:41:52 +00006251 // FIXME: currently, "static" case isn't handled correctly.
Chad Rosierc1183952012-06-26 22:30:43 +00006252 bool IsCXX11MemberFunction =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006253 getLangOpts().CPlusPlus11 &&
Richard Smith990a6922014-01-17 21:01:18 +00006254 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
Faisal Vali421b2d12017-12-29 05:41:00 +00006255 (D.getContext() == DeclaratorContext::MemberContext
Richard Smithad1bbb92013-03-15 00:41:52 +00006256 ? !D.getDeclSpec().isFriendSpecified()
Faisal Vali421b2d12017-12-29 05:41:00 +00006257 : D.getContext() == DeclaratorContext::FileContext &&
Richard Smithad1bbb92013-03-15 00:41:52 +00006258 D.getCXXScopeSpec().isValid() &&
6259 Actions.CurContext->isRecord());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006260
6261 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6262 if (D.getDeclSpec().isConstexprSpecified() && !getLangOpts().CPlusPlus14)
6263 Q.addConst();
Anastasia Stulova5cffa452019-01-21 16:01:38 +00006264 // FIXME: Collect C++ address spaces.
6265 // If there are multiple different address spaces, the source is invalid.
6266 // Carry on using the first addr space for the qualifiers of 'this'.
6267 // The diagnostic will be given later while creating the function
6268 // prototype for the method.
6269 if (getLangOpts().OpenCLCPlusPlus) {
6270 for (ParsedAttr &attr : DS.getAttributes()) {
6271 LangAS ASIdx = attr.asOpenCLLangAS();
6272 if (ASIdx != LangAS::Default) {
6273 Q.addAddressSpace(ASIdx);
6274 break;
6275 }
6276 }
6277 }
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006278
6279 Sema::CXXThisScopeRAII ThisScope(
6280 Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6281 IsCXX11MemberFunction);
Richard Smith2331bbf2012-05-02 22:22:32 +00006282
Douglas Gregor9e66af42011-07-05 16:44:18 +00006283 // Parse exception-specification[opt].
Richard Smith0b3a4622014-11-13 20:01:57 +00006284 bool Delayed = D.isFirstDeclarationOfMember() &&
Richard Smith3ef3e892014-11-20 22:32:11 +00006285 D.isFunctionDeclaratorAFunctionDeclaration();
6286 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6287 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6288 GetLookAheadToken(1).is(tok::l_paren) &&
6289 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6290 GetLookAheadToken(3).is(tok::l_paren) &&
6291 GetLookAheadToken(4).is(tok::identifier) &&
6292 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6293 // HACK: We've got an exception-specification
6294 // noexcept(noexcept(swap(...)))
6295 // or
6296 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6297 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6298 // for 'swap' will only find the function we're currently declaring,
6299 // whereas it expects to find a non-member swap through ADL. Turn off
6300 // delayed parsing to give it a chance to find what it expects.
6301 Delayed = false;
6302 }
Richard Smith0b3a4622014-11-13 20:01:57 +00006303 ESpecType = tryParseExceptionSpecification(Delayed,
6304 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00006305 DynamicExceptions,
6306 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00006307 NoexceptExpr,
6308 ExceptionSpecTokens);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006309 if (ESpecType != EST_None)
6310 EndLoc = ESpecRange.getEnd();
6311
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006312 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6313 // after the exception-specification.
Richard Smith89645bc2013-01-02 12:01:23 +00006314 MaybeParseCXX11Attributes(FnAttrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006315
Douglas Gregor9e66af42011-07-05 16:44:18 +00006316 // Parse trailing-return-type[opt].
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006317 LocalEndLoc = EndLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006318 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00006319 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
Faisal Vali090da2d2018-01-01 18:23:28 +00006320 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006321 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006322 LocalEndLoc = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00006323 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00006324 TrailingReturnType =
6325 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006326 EndLoc = Range.getEnd();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006327 }
Aaron Ballman606093a2017-10-15 15:01:42 +00006328 } else if (standardAttributesAllowed()) {
6329 MaybeParseCXX11Attributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006330 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006331 }
6332
Reid Kleckner078aea92016-12-09 17:14:05 +00006333 // Collect non-parameter declarations from the prototype if this is a function
6334 // declaration. They will be moved into the scope of the function. Only do
6335 // this in C and not C++, where the decls will continue to live in the
6336 // surrounding context.
6337 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6338 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6339 !getLangOpts().CPlusPlus) {
6340 for (Decl *D : getCurScope()->decls()) {
6341 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6342 if (!ND || isa<ParmVarDecl>(ND))
6343 continue;
6344 DeclsInPrototype.push_back(ND);
6345 }
6346 }
6347
Douglas Gregor9e66af42011-07-05 16:44:18 +00006348 // Remember that we parsed a function type, and remember the attributes.
Erich Keanec480f302018-07-12 21:09:05 +00006349 D.AddTypeInfo(DeclaratorChunk::getFunction(
6350 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6351 ParamInfo.size(), EllipsisLoc, RParenLoc,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00006352 RefQualifierIsLValueRef, RefQualifierLoc,
6353 /*MutableLoc=*/SourceLocation(),
6354 ESpecType, ESpecRange, DynamicExceptions.data(),
6355 DynamicExceptionRanges.data(), DynamicExceptions.size(),
Erich Keanec480f302018-07-12 21:09:05 +00006356 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6357 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00006358 LocalEndLoc, D, TrailingReturnType, &DS),
Erich Keanec480f302018-07-12 21:09:05 +00006359 std::move(FnAttrs), EndLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006360}
6361
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006362/// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6363/// true if a ref-qualifier is found.
6364bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6365 SourceLocation &RefQualifierLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00006366 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006367 Diag(Tok, getLangOpts().CPlusPlus11 ?
6368 diag::warn_cxx98_compat_ref_qualifier :
6369 diag::ext_ref_qualifier);
6370
6371 RefQualifierIsLValueRef = Tok.is(tok::amp);
6372 RefQualifierLoc = ConsumeToken();
6373 return true;
6374 }
6375 return false;
6376}
6377
Douglas Gregor9e66af42011-07-05 16:44:18 +00006378/// isFunctionDeclaratorIdentifierList - This parameter list may have an
6379/// identifier list form for a K&R-style function: void foo(a,b,c)
6380///
6381/// Note that identifier-lists are only allowed for normal declarators, not for
6382/// abstract-declarators.
6383bool Parser::isFunctionDeclaratorIdentifierList() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006384 return !getLangOpts().CPlusPlus
Douglas Gregor9e66af42011-07-05 16:44:18 +00006385 && Tok.is(tok::identifier)
6386 && !TryAltiVecVectorToken()
6387 // K&R identifier lists can't have typedefs as identifiers, per C99
6388 // 6.7.5.3p11.
6389 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6390 // Identifier lists follow a really simple grammar: the identifiers can
6391 // be followed *only* by a ", identifier" or ")". However, K&R
6392 // identifier lists are really rare in the brave new modern world, and
6393 // it is very common for someone to typo a type in a non-K&R style
6394 // list. If we are presented with something like: "void foo(intptr x,
6395 // float y)", we don't want to start parsing the function declarator as
6396 // though it is a K&R style declarator just because intptr is an
6397 // invalid type.
6398 //
6399 // To handle this, we check to see if the token after the first
6400 // identifier is a "," or ")". Only then do we parse it as an
6401 // identifier list.
Bruno Cardoso Lopes218c8742016-09-13 20:04:35 +00006402 && (!Tok.is(tok::eof) &&
6403 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006404}
6405
6406/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6407/// we found a K&R-style identifier list instead of a typed parameter list.
6408///
6409/// After returning, ParamInfo will hold the parsed parameters.
6410///
6411/// identifier-list: [C99 6.7.5]
6412/// identifier
6413/// identifier-list ',' identifier
6414///
6415void Parser::ParseFunctionDeclaratorIdentifierList(
6416 Declarator &D,
Craig Topper5603df42013-07-05 19:34:19 +00006417 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006418 // If there was no identifier specified for the declarator, either we are in
6419 // an abstract-declarator, or we are in a parameter declarator which was found
6420 // to be abstract. In abstract-declarators, identifier lists are not valid:
6421 // diagnose this.
6422 if (!D.getIdentifier())
6423 Diag(Tok, diag::ext_ident_list_in_param);
6424
6425 // Maintain an efficient lookup of params we have seen so far.
6426 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6427
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006428 do {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006429 // If this isn't an identifier, report the error and skip until ')'.
6430 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00006431 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00006432 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006433 // Forget we parsed anything.
6434 ParamInfo.clear();
6435 return;
6436 }
6437
6438 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6439
6440 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6441 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6442 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6443
6444 // Verify that the argument identifier has not already been mentioned.
David Blaikie82e95a32014-11-19 07:49:47 +00006445 if (!ParamsSoFar.insert(ParmII).second) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006446 Diag(Tok, diag::err_param_redefinition) << ParmII;
6447 } else {
6448 // Remember this identifier in ParamInfo.
6449 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6450 Tok.getLocation(),
Craig Topper161e4db2014-05-21 06:02:52 +00006451 nullptr));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006452 }
6453
6454 // Eat the identifier.
6455 ConsumeToken();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006456 // The list continues if we see a comma.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006457 } while (TryConsumeToken(tok::comma));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006458}
6459
6460/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6461/// after the opening parenthesis. This function will not parse a K&R-style
6462/// identifier list.
6463///
Richard Smith2620cd92012-04-11 04:01:28 +00006464/// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6465/// caller parsed those arguments immediately after the open paren - they should
6466/// be considered to be part of the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006467///
6468/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6469/// be the location of the ellipsis, if any was parsed.
6470///
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006471/// parameter-type-list: [C99 6.7.5]
6472/// parameter-list
6473/// parameter-list ',' '...'
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006474/// [C++] parameter-list '...'
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006475///
6476/// parameter-list: [C99 6.7.5]
6477/// parameter-declaration
6478/// parameter-list ',' parameter-declaration
6479///
6480/// parameter-declaration: [C99 6.7.5]
6481/// declaration-specifiers declarator
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006482/// [C++] declaration-specifiers declarator '=' assignment-expression
Sebastian Redldb63af22012-03-14 15:54:00 +00006483/// [C++11] initializer-clause
Chris Lattnere37e2332006-08-15 04:50:22 +00006484/// [GNU] declaration-specifiers declarator attributes
Sebastian Redlf769df52009-03-24 22:27:57 +00006485/// declaration-specifiers abstract-declarator[opt]
6486/// [C++] declaration-specifiers abstract-declarator[opt]
Chris Lattner58258242008-04-10 02:22:51 +00006487/// '=' assignment-expression
Chris Lattnere37e2332006-08-15 04:50:22 +00006488/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
Richard Smith2620cd92012-04-11 04:01:28 +00006489/// [C++11] attribute-specifier-seq parameter-declaration
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006490///
Douglas Gregor9e66af42011-07-05 16:44:18 +00006491void Parser::ParseParameterDeclarationClause(
6492 Declarator &D,
Richard Smith2620cd92012-04-11 04:01:28 +00006493 ParsedAttributes &FirstArgAttrs,
Craig Topper5603df42013-07-05 19:34:19 +00006494 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006495 SourceLocation &EllipsisLoc) {
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006496 do {
6497 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6498 // before deciding this was a parameter-declaration-clause.
6499 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Chris Lattner371ed4e2008-04-06 06:57:35 +00006500 break;
Mike Stump11289f42009-09-09 15:08:12 +00006501
Chris Lattner371ed4e2008-04-06 06:57:35 +00006502 // Parse the declaration-specifiers.
John McCall28a6aea2009-11-04 02:18:39 +00006503 // Just use the ParsingDeclaration "scope" of the declarator.
John McCall084e83d2011-03-24 11:26:52 +00006504 DeclSpec DS(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006505
Richard Smith2620cd92012-04-11 04:01:28 +00006506 // Parse any C++11 attributes.
Richard Smith89645bc2013-01-02 12:01:23 +00006507 MaybeParseCXX11Attributes(DS.getAttributes());
Richard Smith2620cd92012-04-11 04:01:28 +00006508
John McCall53fa7142010-12-24 02:08:15 +00006509 // Skip any Microsoft attributes before a param.
Chad Rosierf8a2e702012-12-20 20:37:53 +00006510 MaybeParseMicrosoftAttributes(DS.getAttributes());
John McCall53fa7142010-12-24 02:08:15 +00006511
6512 SourceLocation DSStart = Tok.getLocation();
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006513
6514 // If the caller parsed attributes for the first argument, add them now.
John McCall53fa7142010-12-24 02:08:15 +00006515 // Take them so that we only apply the attributes to the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006516 // FIXME: If we can leave the attributes in the token stream somehow, we can
Richard Smith2620cd92012-04-11 04:01:28 +00006517 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6518 // too much hassle.
6519 DS.takeAttributesFrom(FirstArgAttrs);
John McCall53fa7142010-12-24 02:08:15 +00006520
Faisal Valia534f072018-04-26 00:42:40 +00006521 ParseDeclarationSpecifiers(DS);
Mike Stump11289f42009-09-09 15:08:12 +00006522
Faisal Vali2b391ab2013-09-26 19:54:12 +00006523
Fangrui Song6907ce22018-07-30 19:24:48 +00006524 // Parse the declarator. This is "PrototypeContext" or
6525 // "LambdaExprParameterContext", because we must accept either
Faisal Vali2b391ab2013-09-26 19:54:12 +00006526 // 'declarator' or 'abstract-declarator' here.
Faisal Vali421b2d12017-12-29 05:41:00 +00006527 Declarator ParmDeclarator(
6528 DS, D.getContext() == DeclaratorContext::LambdaExprContext
6529 ? DeclaratorContext::LambdaExprParameterContext
6530 : DeclaratorContext::PrototypeContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00006531 ParseDeclarator(ParmDeclarator);
Chris Lattner371ed4e2008-04-06 06:57:35 +00006532
6533 // Parse GNU attributes, if present.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006534 MaybeParseGNUAttributes(ParmDeclarator);
Mike Stump11289f42009-09-09 15:08:12 +00006535
Chris Lattner371ed4e2008-04-06 06:57:35 +00006536 // Remember this parsed parameter in ParamInfo.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006537 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
Mike Stump11289f42009-09-09 15:08:12 +00006538
Douglas Gregor4d87df52008-12-16 21:30:33 +00006539 // DefArgToks is used when the parsing of default arguments needs
6540 // to be delayed.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006541 std::unique_ptr<CachedTokens> DefArgToks;
Douglas Gregor4d87df52008-12-16 21:30:33 +00006542
Chris Lattner371ed4e2008-04-06 06:57:35 +00006543 // If no parameter was specified, verify that *something* was specified,
6544 // otherwise we have a missing type and identifier.
Craig Topper161e4db2014-05-21 06:02:52 +00006545 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
Faisal Vali2b391ab2013-09-26 19:54:12 +00006546 ParmDeclarator.getNumTypeObjects() == 0) {
Chris Lattner371ed4e2008-04-06 06:57:35 +00006547 // Completely missing, emit error.
6548 Diag(DSStart, diag::err_missing_param);
6549 } else {
6550 // Otherwise, we have something. Add it and let semantic analysis try
6551 // to grok it and add the result to the ParamInfo we are building.
Mike Stump11289f42009-09-09 15:08:12 +00006552
Richard Smith36ee9fb2014-08-11 23:30:23 +00006553 // Last chance to recover from a misplaced ellipsis in an attempted
6554 // parameter pack declaration.
6555 if (Tok.is(tok::ellipsis) &&
6556 (NextToken().isNot(tok::r_paren) ||
6557 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6558 !Actions.isUnexpandedParameterPackPermitted())) &&
6559 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6560 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6561
Chris Lattner371ed4e2008-04-06 06:57:35 +00006562 // Inform the actions module about the parameter declarator, so it gets
6563 // added to the current scope.
Richard Smith95e1fb02014-08-27 03:23:12 +00006564 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006565 // Parse the default argument, if any. We parse the default
6566 // arguments in all dialects; the semantic analysis in
6567 // ActOnParamDefaultArgument will reject the default argument in
6568 // C.
6569 if (Tok.is(tok::equal)) {
Douglas Gregor58354032008-12-24 00:01:03 +00006570 SourceLocation EqualLoc = Tok.getLocation();
6571
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006572 // Parse the default argument
Faisal Vali421b2d12017-12-29 05:41:00 +00006573 if (D.getContext() == DeclaratorContext::MemberContext) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006574 // If we're inside a class definition, cache the tokens
6575 // corresponding to the default argument. We'll actually parse
6576 // them when we see the end of the class definition.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006577 DefArgToks.reset(new CachedTokens);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006578
David Majnemer906ed272015-01-13 05:28:24 +00006579 SourceLocation ArgStartLoc = NextToken().getLocation();
Richard Smith1fff95c2013-09-12 23:28:08 +00006580 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006581 DefArgToks.reset();
Serge Pavlovb4b35782014-07-22 01:54:49 +00006582 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006583 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006584 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
David Majnemer906ed272015-01-13 05:28:24 +00006585 ArgStartLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006586 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006587 } else {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006588 // Consume the '='.
Douglas Gregor58354032008-12-24 00:01:03 +00006589 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00006590
Chad Rosierc1183952012-06-26 22:30:43 +00006591 // The argument isn't actually potentially evaluated unless it is
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006592 // used.
Faisal Valid143a0c2017-04-01 21:30:49 +00006593 EnterExpressionEvaluationContext Eval(
6594 Actions,
6595 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6596 Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006597
Sebastian Redldb63af22012-03-14 15:54:00 +00006598 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006599 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006600 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +00006601 DefArgResult = ParseBraceInitializer();
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006602 } else
Sebastian Redldb63af22012-03-14 15:54:00 +00006603 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +00006604 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006605 if (DefArgResult.isInvalid()) {
Serge Pavlovb4b35782014-07-22 01:54:49 +00006606 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Alexey Bataevee6507d2013-11-18 08:17:37 +00006607 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006608 } else {
6609 // Inform the actions module about the default argument
6610 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006611 DefArgResult.get());
Douglas Gregor4d87df52008-12-16 21:30:33 +00006612 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006613 }
6614 }
Mike Stump11289f42009-09-09 15:08:12 +00006615
6616 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
Fangrui Song6907ce22018-07-30 19:24:48 +00006617 ParmDeclarator.getIdentifierLoc(),
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006618 Param, std::move(DefArgToks)));
Chris Lattner371ed4e2008-04-06 06:57:35 +00006619 }
6620
Richard Smith36ee9fb2014-08-11 23:30:23 +00006621 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6622 if (!getLangOpts().CPlusPlus) {
6623 // We have ellipsis without a preceding ',', which is ill-formed
6624 // in C. Complain and provide the fix.
6625 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6626 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6627 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6628 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6629 // It looks like this was supposed to be a parameter pack. Warn and
6630 // point out where the ellipsis should have gone.
6631 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6632 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6633 << ParmEllipsis.isValid() << ParmEllipsis;
6634 if (ParmEllipsis.isValid()) {
6635 Diag(ParmEllipsis,
6636 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6637 } else {
6638 Diag(ParmDeclarator.getIdentifierLoc(),
6639 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6640 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6641 "...")
6642 << !ParmDeclarator.hasName();
6643 }
6644 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006645 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
Richard Smith36ee9fb2014-08-11 23:30:23 +00006646 }
6647
6648 // We can't have any more parameters after an ellipsis.
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006649 break;
6650 }
Mike Stump11289f42009-09-09 15:08:12 +00006651
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006652 // If the next token is a comma, consume it and keep reading arguments.
6653 } while (TryConsumeToken(tok::comma));
Chris Lattner6c940e62008-04-06 06:34:08 +00006654}
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006655
Chris Lattnere8074e62006-08-06 18:30:15 +00006656/// [C90] direct-declarator '[' constant-expression[opt] ']'
6657/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6658/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6659/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6660/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006661/// [C++11] direct-declarator '[' constant-expression[opt] ']'
6662/// attribute-specifier-seq[opt]
Chris Lattnere8074e62006-08-06 18:30:15 +00006663void Parser::ParseBracketDeclarator(Declarator &D) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006664 if (CheckProhibitedCXX11Attribute())
6665 return;
6666
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006667 BalancedDelimiterTracker T(*this, tok::l_square);
6668 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00006669
Chris Lattner84a11622008-12-18 07:27:21 +00006670 // C array syntax has many features, but by-far the most common is [] and [4].
6671 // This code does a fast path to handle some of the most obvious cases.
6672 if (Tok.getKind() == tok::r_square) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006673 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006674 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006675 MaybeParseCXX11Attributes(attrs);
Chad Rosierc1183952012-06-26 22:30:43 +00006676
Chris Lattner84a11622008-12-18 07:27:21 +00006677 // Remember that we parsed the empty array type.
Craig Topper161e4db2014-05-21 06:02:52 +00006678 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006679 T.getOpenLocation(),
6680 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006681 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006682 return;
6683 } else if (Tok.getKind() == tok::numeric_constant &&
6684 GetLookAheadToken(1).is(tok::r_square)) {
6685 // [4] is very common. Parse the numeric constant expression.
Richard Smithbcc22fc2012-03-09 08:00:36 +00006686 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
Chris Lattner84a11622008-12-18 07:27:21 +00006687 ConsumeToken();
6688
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006689 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006690 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006691 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006692
Chris Lattner84a11622008-12-18 07:27:21 +00006693 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006694 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006695 T.getOpenLocation(),
6696 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006697 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006698 return;
Benjamin Kramer72dae622016-02-18 15:30:24 +00006699 } else if (Tok.getKind() == tok::code_completion) {
6700 Actions.CodeCompleteBracketDeclarator(getCurScope());
6701 return cutOffParsing();
Chris Lattner84a11622008-12-18 07:27:21 +00006702 }
Mike Stump11289f42009-09-09 15:08:12 +00006703
Chris Lattnere8074e62006-08-06 18:30:15 +00006704 // If valid, this location is the position where we read the 'static' keyword.
6705 SourceLocation StaticLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006706 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006707
Chris Lattnere8074e62006-08-06 18:30:15 +00006708 // If there is a type-qualifier-list, read it now.
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006709 // Type qualifiers in an array subscript are a C99 feature.
John McCall084e83d2011-03-24 11:26:52 +00006710 DeclSpec DS(AttrFactory);
Aaron Ballman08b06592014-07-22 12:44:22 +00006711 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
Mike Stump11289f42009-09-09 15:08:12 +00006712
Chris Lattnere8074e62006-08-06 18:30:15 +00006713 // If we haven't already read 'static', check to see if there is one after the
6714 // type-qualifier-list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006715 if (!StaticLoc.isValid())
6716 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006717
Chris Lattnere8074e62006-08-06 18:30:15 +00006718 // Handle "direct-declarator [ type-qual-list[opt] * ]".
Chris Lattnere8074e62006-08-06 18:30:15 +00006719 bool isStar = false;
John McCalldadc5752010-08-24 06:29:42 +00006720 ExprResult NumElements;
Mike Stump11289f42009-09-09 15:08:12 +00006721
Chris Lattner521ff2b2008-04-06 05:26:30 +00006722 // Handle the case where we have '[*]' as the array size. However, a leading
6723 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
Sylvestre Ledru830885c2012-07-23 08:59:39 +00006724 // the token after the star is a ']'. Since stars in arrays are
Chris Lattner521ff2b2008-04-06 05:26:30 +00006725 // infrequent, use of lookahead is not costly here.
6726 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
Chris Lattnerc439f0d2008-04-06 05:27:21 +00006727 ConsumeToken(); // Eat the '*'.
Chris Lattner1906f802006-08-06 19:14:46 +00006728
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006729 if (StaticLoc.isValid()) {
Chris Lattner521ff2b2008-04-06 05:26:30 +00006730 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006731 StaticLoc = SourceLocation(); // Drop the static.
6732 }
Chris Lattner521ff2b2008-04-06 05:26:30 +00006733 isStar = true;
Chris Lattner76c72282007-10-09 17:33:22 +00006734 } else if (Tok.isNot(tok::r_square)) {
Chris Lattner84a11622008-12-18 07:27:21 +00006735 // Note, in C89, this production uses the constant-expr production instead
6736 // of assignment-expr. The only difference is that assignment-expr allows
6737 // things like '=' and '*='. Sema rejects these in C89 mode because they
6738 // are not i-c-e's, so we don't need to distinguish between the two here.
Mike Stump11289f42009-09-09 15:08:12 +00006739
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006740 // Parse the constant-expression or assignment-expression now (depending
6741 // on dialect).
David Blaikiebbafb8a2012-03-11 07:00:24 +00006742 if (getLangOpts().CPlusPlus) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006743 NumElements = ParseConstantExpression();
Eli Friedmane0afc982012-01-21 01:01:51 +00006744 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00006745 EnterExpressionEvaluationContext Unevaluated(
6746 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Kaelyn Takata15867822014-11-21 18:48:04 +00006747 NumElements =
6748 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Eli Friedmane0afc982012-01-21 01:01:51 +00006749 }
David Majnemerf9834d52014-08-08 07:21:18 +00006750 } else {
6751 if (StaticLoc.isValid()) {
6752 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6753 StaticLoc = SourceLocation(); // Drop the static.
6754 }
Chris Lattner62591722006-08-12 18:40:58 +00006755 }
Mike Stump11289f42009-09-09 15:08:12 +00006756
Chris Lattner62591722006-08-12 18:40:58 +00006757 // If there was an error parsing the assignment-expression, recover.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00006758 if (NumElements.isInvalid()) {
Chris Lattnercd2a8c52009-04-24 22:30:50 +00006759 D.setInvalidType(true);
Chris Lattner62591722006-08-12 18:40:58 +00006760 // If the expression was invalid, skip it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00006761 SkipUntil(tok::r_square, StopAtSemi);
Chris Lattner62591722006-08-12 18:40:58 +00006762 return;
Chris Lattnere8074e62006-08-06 18:30:15 +00006763 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006764
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006765 T.consumeClose();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006766
Jordan Rose303e2f12016-11-10 23:28:17 +00006767 MaybeParseCXX11Attributes(DS.getAttributes());
Alexis Hunt96d5c762009-11-21 08:43:09 +00006768
Chris Lattner84a11622008-12-18 07:27:21 +00006769 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006770 D.AddTypeInfo(
6771 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6772 isStar, NumElements.get(), T.getOpenLocation(),
6773 T.getCloseLocation()),
6774 std::move(DS.getAttributes()), T.getCloseLocation());
Chris Lattnere8074e62006-08-06 18:30:15 +00006775}
6776
Richard Trieuf4b81d02014-06-24 23:14:24 +00006777/// Diagnose brackets before an identifier.
6778void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6779 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6780 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6781
6782 SourceLocation StartBracketLoc = Tok.getLocation();
6783 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6784
6785 while (Tok.is(tok::l_square)) {
6786 ParseBracketDeclarator(TempDeclarator);
6787 }
6788
6789 // Stuff the location of the start of the brackets into the Declarator.
6790 // The diagnostics from ParseDirectDeclarator will make more sense if
6791 // they use this location instead.
6792 if (Tok.is(tok::semi))
6793 D.getName().EndLocation = StartBracketLoc;
6794
6795 SourceLocation SuggestParenLoc = Tok.getLocation();
6796
6797 // Now that the brackets are removed, try parsing the declarator again.
6798 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6799
6800 // Something went wrong parsing the brackets, in which case,
6801 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6802 // one here.
6803 if (TempDeclarator.getNumTypeObjects() == 0)
6804 return;
6805
6806 // Determine if parens will need to be suggested in the diagnostic.
6807 bool NeedParens = false;
6808 if (D.getNumTypeObjects() != 0) {
6809 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6810 case DeclaratorChunk::Pointer:
6811 case DeclaratorChunk::Reference:
6812 case DeclaratorChunk::BlockPointer:
6813 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00006814 case DeclaratorChunk::Pipe:
Richard Trieuf4b81d02014-06-24 23:14:24 +00006815 NeedParens = true;
6816 break;
6817 case DeclaratorChunk::Array:
6818 case DeclaratorChunk::Function:
6819 case DeclaratorChunk::Paren:
6820 break;
6821 }
6822 }
6823
6824 if (NeedParens) {
6825 // Create a DeclaratorChunk for the inserted parens.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006826 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Erich Keanec480f302018-07-12 21:09:05 +00006827 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
Richard Trieuf4b81d02014-06-24 23:14:24 +00006828 SourceLocation());
6829 }
6830
6831 // Adding back the bracket info to the end of the Declarator.
6832 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6833 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
Erich Keanec480f302018-07-12 21:09:05 +00006834 D.AddTypeInfo(Chunk, SourceLocation());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006835 }
6836
6837 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6838 // If parentheses are required, always suggest them.
6839 if (!D.getIdentifier() && !NeedParens)
6840 return;
6841
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006842 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
Richard Trieuf4b81d02014-06-24 23:14:24 +00006843
6844 // Generate the move bracket error message.
6845 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006846 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006847
6848 if (NeedParens) {
6849 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6850 << getLangOpts().CPlusPlus
6851 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6852 << FixItHint::CreateInsertion(EndLoc, ")")
6853 << FixItHint::CreateInsertionFromRange(
6854 EndLoc, CharSourceRange(BracketRange, true))
6855 << FixItHint::CreateRemoval(BracketRange);
6856 } else {
6857 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6858 << getLangOpts().CPlusPlus
6859 << FixItHint::CreateInsertionFromRange(
6860 EndLoc, CharSourceRange(BracketRange, true))
6861 << FixItHint::CreateRemoval(BracketRange);
6862 }
6863}
6864
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006865/// [GNU] typeof-specifier:
6866/// typeof ( expressions )
6867/// typeof ( type-name )
6868/// [GNU/C++] typeof unary-expression
Steve Naroffad373bd2007-07-31 12:34:36 +00006869///
6870void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
Chris Lattner76c72282007-10-09 17:33:22 +00006871 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006872 Token OpTok = Tok;
Steve Naroffad373bd2007-07-31 12:34:36 +00006873 SourceLocation StartLoc = ConsumeToken();
6874
John McCalle8595032010-01-13 20:03:27 +00006875 const bool hasParens = Tok.is(tok::l_paren);
6876
Faisal Valid143a0c2017-04-01 21:30:49 +00006877 EnterExpressionEvaluationContext Unevaluated(
6878 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6879 Sema::ReuseLambdaContextDecl);
Eli Friedmane0afc982012-01-21 01:01:51 +00006880
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006881 bool isCastExpr;
John McCallba7bf592010-08-24 05:47:05 +00006882 ParsedType CastTy;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006883 SourceRange CastRange;
Kaelyn Takata911260742014-12-19 01:28:40 +00006884 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6885 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
John McCalle8595032010-01-13 20:03:27 +00006886 if (hasParens)
6887 DS.setTypeofParensRange(CastRange);
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006888
6889 if (CastRange.getEnd().isInvalid())
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006890 // FIXME: Not accurate, the range gets one token more than it should.
6891 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006892 else
6893 DS.SetRangeEnd(CastRange.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +00006894
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006895 if (isCastExpr) {
6896 if (!CastTy) {
6897 DS.SetTypeSpecError();
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006898 return;
Douglas Gregor220cac52009-02-18 17:45:20 +00006899 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006900
Craig Topper161e4db2014-05-21 06:02:52 +00006901 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006902 unsigned DiagID;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006903 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6904 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006905 DiagID, CastTy,
6906 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006907 Diag(StartLoc, DiagID) << PrevSpec;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006908 return;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006909 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006910
Hiroshi Inoue533777f2017-07-02 06:12:49 +00006911 // If we get here, the operand to the typeof was an expression.
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006912 if (Operand.isInvalid()) {
6913 DS.SetTypeSpecError();
Steve Naroff4bd2f712007-08-02 02:53:48 +00006914 return;
Steve Naroffad373bd2007-07-31 12:34:36 +00006915 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006916
Eli Friedmane0afc982012-01-21 01:01:51 +00006917 // We might need to transform the operand if it is potentially evaluated.
6918 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6919 if (Operand.isInvalid()) {
6920 DS.SetTypeSpecError();
6921 return;
6922 }
6923
Craig Topper161e4db2014-05-21 06:02:52 +00006924 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006925 unsigned DiagID;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006926 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6927 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006928 DiagID, Operand.get(),
6929 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006930 Diag(StartLoc, DiagID) << PrevSpec;
Steve Naroffad373bd2007-07-31 12:34:36 +00006931}
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006932
Benjamin Kramere56f3932011-12-23 17:00:35 +00006933/// [C11] atomic-specifier:
Eli Friedman0dfb8892011-10-06 23:00:33 +00006934/// _Atomic ( type-name )
6935///
6936void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
Richard Smith8e1ac332013-03-28 01:55:44 +00006937 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6938 "Not an atomic specifier");
Eli Friedman0dfb8892011-10-06 23:00:33 +00006939
6940 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006941 BalancedDelimiterTracker T(*this, tok::l_paren);
Richard Smith8e1ac332013-03-28 01:55:44 +00006942 if (T.consumeOpen())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006943 return;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006944
6945 TypeResult Result = ParseTypeName();
6946 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00006947 SkipUntil(tok::r_paren, StopAtSemi);
Eli Friedman0dfb8892011-10-06 23:00:33 +00006948 return;
6949 }
6950
6951 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006952 T.consumeClose();
Eli Friedman0dfb8892011-10-06 23:00:33 +00006953
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006954 if (T.getCloseLocation().isInvalid())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006955 return;
6956
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006957 DS.setTypeofParensRange(T.getRange());
6958 DS.SetRangeEnd(T.getCloseLocation());
Eli Friedman0dfb8892011-10-06 23:00:33 +00006959
Craig Topper161e4db2014-05-21 06:02:52 +00006960 const char *PrevSpec = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006961 unsigned DiagID;
6962 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006963 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006964 Actions.getASTContext().getPrintingPolicy()))
Eli Friedman0dfb8892011-10-06 23:00:33 +00006965 Diag(StartLoc, DiagID) << PrevSpec;
6966}
6967
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006968/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6969/// from TryAltiVecVectorToken.
6970bool Parser::TryAltiVecVectorTokenOutOfLine() {
6971 Token Next = NextToken();
6972 switch (Next.getKind()) {
6973 default: return false;
6974 case tok::kw_short:
6975 case tok::kw_long:
6976 case tok::kw_signed:
6977 case tok::kw_unsigned:
6978 case tok::kw_void:
6979 case tok::kw_char:
6980 case tok::kw_int:
6981 case tok::kw_float:
6982 case tok::kw_double:
6983 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006984 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006985 case tok::kw___pixel:
6986 Tok.setKind(tok::kw___vector);
6987 return true;
6988 case tok::identifier:
6989 if (Next.getIdentifierInfo() == Ident_pixel) {
6990 Tok.setKind(tok::kw___vector);
6991 return true;
6992 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006993 if (Next.getIdentifierInfo() == Ident_bool) {
6994 Tok.setKind(tok::kw___vector);
6995 return true;
6996 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006997 return false;
6998 }
6999}
7000
7001bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
7002 const char *&PrevSpec, unsigned &DiagID,
7003 bool &isInvalid) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007004 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007005 if (Tok.getIdentifierInfo() == Ident_vector) {
7006 Token Next = NextToken();
7007 switch (Next.getKind()) {
7008 case tok::kw_short:
7009 case tok::kw_long:
7010 case tok::kw_signed:
7011 case tok::kw_unsigned:
7012 case tok::kw_void:
7013 case tok::kw_char:
7014 case tok::kw_int:
7015 case tok::kw_float:
7016 case tok::kw_double:
7017 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00007018 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007019 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007020 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007021 return true;
7022 case tok::identifier:
7023 if (Next.getIdentifierInfo() == Ident_pixel) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007024 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007025 return true;
7026 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00007027 if (Next.getIdentifierInfo() == Ident_bool) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007028 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00007029 return true;
7030 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007031 break;
7032 default:
7033 break;
7034 }
Douglas Gregor9938e3b2010-06-16 15:28:57 +00007035 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007036 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007037 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007038 return true;
Bill Schmidt99a084b2013-07-03 20:54:09 +00007039 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
7040 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007041 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00007042 return true;
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007043 }
7044 return false;
7045}