blob: 9c9a9f4679820767542ffcd0ef5e189cedc569d2 [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.
227 if (FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
228 auto &SM = PP.getSourceManager();
229 CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
230 StringRef FoundName =
231 Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
232 IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
233
234 for (unsigned i = OldNumAttrs; i < attrs.size(); ++i)
235 attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
236
237 if (LateAttrs) {
238 for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); ++i)
239 (*LateAttrs)[i]->MacroII = MacroII;
240 }
241 }
Steve Naroff0f2fe172007-06-01 17:11:19 +0000242 }
Steve Naroff0f2fe172007-06-01 17:11:19 +0000243}
Chris Lattnerf5fbd792006-08-10 23:56:11 +0000244
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000245/// Determine whether the given attribute has an identifier argument.
Aaron Ballman4768b312013-11-04 12:55:56 +0000246static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000247#define CLANG_ATTR_IDENTIFIER_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000248 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000249#include "clang/Parse/AttrParserStringSwitches.inc"
Douglas Gregord2472d42013-05-02 23:25:32 +0000250 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000251#undef CLANG_ATTR_IDENTIFIER_ARG_LIST
Douglas Gregord2472d42013-05-02 23:25:32 +0000252}
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000253
Erich Keane3efe0022018-07-20 14:13:28 +0000254/// Determine whether the given attribute has a variadic identifier argument.
255static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
256#define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
257 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
258#include "clang/Parse/AttrParserStringSwitches.inc"
259 .Default(false);
260#undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
261}
262
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000263/// Determine whether the given attribute treats kw_this as an identifier.
264static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II) {
265#define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
266 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
267#include "clang/Parse/AttrParserStringSwitches.inc"
268 .Default(false);
269#undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
270}
271
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000272/// Determine whether the given attribute parses a type argument.
Aaron Ballman4768b312013-11-04 12:55:56 +0000273static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000274#define CLANG_ATTR_TYPE_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000275 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000276#include "clang/Parse/AttrParserStringSwitches.inc"
Aaron Ballman4768b312013-11-04 12:55:56 +0000277 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000278#undef CLANG_ATTR_TYPE_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000279}
280
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000281/// Determine whether the given attribute requires parsing its arguments
Aaron Ballman15b27b92014-01-09 19:39:35 +0000282/// in an unevaluated context or not.
283static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000284#define CLANG_ATTR_ARG_CONTEXT_LIST
Aaron Ballman15b27b92014-01-09 19:39:35 +0000285 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000286#include "clang/Parse/AttrParserStringSwitches.inc"
Aaron Ballman15b27b92014-01-09 19:39:35 +0000287 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000288#undef CLANG_ATTR_ARG_CONTEXT_LIST
Aaron Ballman15b27b92014-01-09 19:39:35 +0000289}
290
Richard Smithfeefaf52013-09-03 18:01:40 +0000291IdentifierLoc *Parser::ParseIdentifierLoc() {
292 assert(Tok.is(tok::identifier) && "expected an identifier");
293 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
294 Tok.getLocation(),
295 Tok.getIdentifierInfo());
296 ConsumeToken();
297 return IL;
298}
299
Richard Smithb1f9a282013-10-31 01:56:18 +0000300void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
301 SourceLocation AttrNameLoc,
302 ParsedAttributes &Attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000303 SourceLocation *EndLoc,
304 IdentifierInfo *ScopeName,
305 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000306 ParsedAttr::Syntax Syntax) {
Richard Smithb1f9a282013-10-31 01:56:18 +0000307 BalancedDelimiterTracker Parens(*this, tok::l_paren);
308 Parens.consumeOpen();
309
310 TypeResult T;
311 if (Tok.isNot(tok::r_paren))
312 T = ParseTypeName();
313
314 if (Parens.consumeClose())
315 return;
316
317 if (T.isInvalid())
318 return;
319
320 if (T.isUsable())
321 Attrs.addNewTypeAttr(&AttrName,
Craig Topper161e4db2014-05-21 06:02:52 +0000322 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000323 ScopeName, ScopeLoc, T.get(), Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000324 else
325 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000326 ScopeName, ScopeLoc, nullptr, 0, Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000327}
328
Aaron Ballman35f94212014-04-14 16:03:22 +0000329unsigned Parser::ParseAttributeArgsCommon(
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000330 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
331 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +0000332 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000333 // Ignore the left paren location for now.
334 ConsumeParen();
335
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000336 bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
337
338 // Interpret "kw_this" as an identifier if the attributed requests it.
339 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
340 Tok.setKind(tok::identifier);
341
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000342 ArgsVector ArgExprs;
343 if (Tok.is(tok::identifier)) {
344 // If this attribute wants an 'identifier' argument, make it so.
Erich Keane3efe0022018-07-20 14:13:28 +0000345 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
346 attributeHasVariadicIdentifierArg(*AttrName);
Erich Keanee891aa92018-07-13 15:07:47 +0000347 ParsedAttr::Kind AttrKind =
348 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000349
350 // If we don't know how to parse this attribute, but this is the only
351 // token in this argument, assume it's meant to be an identifier.
Erich Keanee891aa92018-07-13 15:07:47 +0000352 if (AttrKind == ParsedAttr::UnknownAttribute ||
353 AttrKind == ParsedAttr::IgnoredAttribute) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000354 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000355 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000356 }
357
358 if (IsIdentifierArg)
359 ArgExprs.push_back(ParseIdentifierLoc());
360 }
361
362 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
363 // Eat the comma.
364 if (!ArgExprs.empty())
365 ConsumeToken();
366
367 // Parse the non-empty comma-separated list of expressions.
368 do {
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000369 // Interpret "kw_this" as an identifier if the attributed requests it.
370 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
371 Tok.setKind(tok::identifier);
372
Erich Keane3efe0022018-07-20 14:13:28 +0000373 ExprResult ArgExpr;
374 if (Tok.is(tok::identifier) &&
375 attributeHasVariadicIdentifierArg(*AttrName)) {
376 ArgExprs.push_back(ParseIdentifierLoc());
377 } else {
378 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
379 EnterExpressionEvaluationContext Unevaluated(
380 Actions,
381 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
382 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000383
Erich Keane3efe0022018-07-20 14:13:28 +0000384 ExprResult ArgExpr(
385 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
386 if (ArgExpr.isInvalid()) {
387 SkipUntil(tok::r_paren, StopAtSemi);
388 return 0;
389 }
390 ArgExprs.push_back(ArgExpr.get());
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000391 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000392 // Eat the comma, move to the next argument
393 } while (TryConsumeToken(tok::comma));
394 }
395
396 SourceLocation RParen = Tok.getLocation();
397 if (!ExpectAndConsume(tok::r_paren)) {
398 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
399 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
400 ArgExprs.data(), ArgExprs.size(), Syntax);
401 }
402
403 if (EndLoc)
404 *EndLoc = RParen;
Aaron Ballman35f94212014-04-14 16:03:22 +0000405
406 return static_cast<unsigned>(ArgExprs.size());
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000407}
408
Michael Han23214e52012-10-03 01:56:22 +0000409/// Parse the arguments to a parameterized GNU attribute or
410/// a C++11 attribute in "gnu" namespace.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000411void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
412 SourceLocation AttrNameLoc,
413 ParsedAttributes &Attrs,
Michael Han23214e52012-10-03 01:56:22 +0000414 SourceLocation *EndLoc,
415 IdentifierInfo *ScopeName,
416 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000417 ParsedAttr::Syntax Syntax,
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000418 Declarator *D) {
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000419
420 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
421
Erich Keanee891aa92018-07-13 15:07:47 +0000422 ParsedAttr::Kind AttrKind =
423 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Richard Smith66e71682013-10-24 01:07:54 +0000424
Erich Keanee891aa92018-07-13 15:07:47 +0000425 if (AttrKind == ParsedAttr::AT_Availability) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000426 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
427 ScopeLoc, Syntax);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000428 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000429 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000430 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
431 ScopeName, ScopeLoc, Syntax);
432 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000433 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000434 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
435 ScopeName, ScopeLoc, Syntax);
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +0000436 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000437 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000438 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
439 ScopeName, ScopeLoc, Syntax);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000440 return;
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000441 } else if (attributeIsTypeArgAttr(*AttrName)) {
442 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
443 ScopeLoc, Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000444 return;
445 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000446
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000447 // These may refer to the function arguments, but need to be parsed early to
448 // participate in determining whether it's a redeclaration.
George Burgess IVa19ea342016-11-10 20:43:52 +0000449 llvm::Optional<ParseScope> PrototypeScope;
Ulrich Weigandef5aa292015-07-13 14:13:01 +0000450 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
451 D && D->isFunctionDeclarator()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000452 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
George Burgess IVa19ea342016-11-10 20:43:52 +0000453 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
454 Scope::FunctionDeclarationScope |
455 Scope::DeclScope);
Alp Tokerc5350722014-02-26 22:27:52 +0000456 for (unsigned i = 0; i != FTI.NumParams; ++i) {
457 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000458 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
459 }
460 }
461
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000462 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
463 ScopeLoc, Syntax);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000464}
465
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000466unsigned Parser::ParseClangAttributeArgs(
467 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
468 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +0000469 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000470 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
471
Erich Keanee891aa92018-07-13 15:07:47 +0000472 ParsedAttr::Kind AttrKind =
473 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000474
Aaron Ballman38bbc162018-02-24 17:16:42 +0000475 switch (AttrKind) {
476 default:
477 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
478 ScopeName, ScopeLoc, Syntax);
Erich Keanee891aa92018-07-13 15:07:47 +0000479 case ParsedAttr::AT_ExternalSourceSymbol:
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000480 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
481 ScopeName, ScopeLoc, Syntax);
Aaron Ballman38bbc162018-02-24 17:16:42 +0000482 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000483 case ParsedAttr::AT_Availability:
Aaron Ballman38bbc162018-02-24 17:16:42 +0000484 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
485 ScopeLoc, Syntax);
486 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000487 case ParsedAttr::AT_ObjCBridgeRelated:
Aaron Ballmanc248b0f2018-02-24 17:37:37 +0000488 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
489 ScopeName, ScopeLoc, Syntax);
490 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000491 case ParsedAttr::AT_TypeTagForDatatype:
Aaron Ballmana26d8ee2018-02-25 14:01:04 +0000492 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
493 ScopeName, ScopeLoc, Syntax);
494 break;
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000495 }
Erich Keanec480f302018-07-12 21:09:05 +0000496 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000497}
498
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000499bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
500 SourceLocation AttrNameLoc,
501 ParsedAttributes &Attrs) {
502 // If the attribute isn't known, we will not attempt to parse any
503 // arguments.
504 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
Bob Wilson7c730832015-07-20 22:57:31 +0000505 getTargetInfo(), getLangOpts())) {
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000506 // Eat the left paren, then skip to the ending right paren.
507 ConsumeParen();
508 SkipUntil(tok::r_paren);
509 return false;
Aaron Ballman478faed2012-06-19 22:09:27 +0000510 }
Aaron Ballman478faed2012-06-19 22:09:27 +0000511
Aaron Ballman95d57032014-04-14 16:44:26 +0000512 SourceLocation OpenParenLoc = Tok.getLocation();
513
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000514 if (AttrName->getName() == "property") {
Aaron Ballman478faed2012-06-19 22:09:27 +0000515 // The property declspec is more complex in that it can take one or two
Chad Rosierc1183952012-06-26 22:30:43 +0000516 // assignment expressions as a parameter, but the lhs of the assignment
Aaron Ballman478faed2012-06-19 22:09:27 +0000517 // must be named get or put.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000518
John McCall5e77d762013-04-16 07:28:30 +0000519 BalancedDelimiterTracker T(*this, tok::l_paren);
520 T.expectAndConsume(diag::err_expected_lparen_after,
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000521 AttrName->getNameStart(), tok::r_paren);
John McCall5e77d762013-04-16 07:28:30 +0000522
523 enum AccessorKind {
524 AK_Invalid = -1,
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000525 AK_Put = 0,
526 AK_Get = 1 // indices into AccessorNames
John McCall5e77d762013-04-16 07:28:30 +0000527 };
Craig Topper161e4db2014-05-21 06:02:52 +0000528 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
John McCall5e77d762013-04-16 07:28:30 +0000529 bool HasInvalidAccessor = false;
530
531 // Parse the accessor specifications.
532 while (true) {
533 // Stop if this doesn't look like an accessor spec.
534 if (!Tok.is(tok::identifier)) {
535 // If the user wrote a completely empty list, use a special diagnostic.
536 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
Craig Topper161e4db2014-05-21 06:02:52 +0000537 AccessorNames[AK_Put] == nullptr &&
538 AccessorNames[AK_Get] == nullptr) {
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000539 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
John McCall5e77d762013-04-16 07:28:30 +0000540 break;
541 }
542
543 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
544 break;
545 }
546
547 AccessorKind Kind;
548 SourceLocation KindLoc = Tok.getLocation();
549 StringRef KindStr = Tok.getIdentifierInfo()->getName();
550 if (KindStr == "get") {
551 Kind = AK_Get;
552 } else if (KindStr == "put") {
553 Kind = AK_Put;
554
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000555 // Recover from the common mistake of using 'set' instead of 'put'.
John McCall5e77d762013-04-16 07:28:30 +0000556 } else if (KindStr == "set") {
557 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000558 << FixItHint::CreateReplacement(KindLoc, "put");
John McCall5e77d762013-04-16 07:28:30 +0000559 Kind = AK_Put;
560
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000561 // Handle the mistake of forgetting the accessor kind by skipping
562 // this accessor.
John McCall5e77d762013-04-16 07:28:30 +0000563 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
564 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
565 ConsumeToken();
566 HasInvalidAccessor = true;
567 goto next_property_accessor;
568
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000569 // Otherwise, complain about the unknown accessor kind.
John McCall5e77d762013-04-16 07:28:30 +0000570 } else {
571 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
572 HasInvalidAccessor = true;
573 Kind = AK_Invalid;
574
575 // Try to keep parsing unless it doesn't look like an accessor spec.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000576 if (!NextToken().is(tok::equal))
577 break;
John McCall5e77d762013-04-16 07:28:30 +0000578 }
579
580 // Consume the identifier.
581 ConsumeToken();
582
583 // Consume the '='.
Alp Toker8fbec672013-12-17 23:29:36 +0000584 if (!TryConsumeToken(tok::equal)) {
John McCall5e77d762013-04-16 07:28:30 +0000585 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000586 << KindStr;
John McCall5e77d762013-04-16 07:28:30 +0000587 break;
588 }
589
590 // Expect the method name.
591 if (!Tok.is(tok::identifier)) {
592 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
593 break;
594 }
595
596 if (Kind == AK_Invalid) {
597 // Just drop invalid accessors.
Craig Topper161e4db2014-05-21 06:02:52 +0000598 } else if (AccessorNames[Kind] != nullptr) {
John McCall5e77d762013-04-16 07:28:30 +0000599 // Complain about the repeated accessor, ignore it, and keep parsing.
600 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
601 } else {
602 AccessorNames[Kind] = Tok.getIdentifierInfo();
603 }
604 ConsumeToken();
605
606 next_property_accessor:
607 // Keep processing accessors until we run out.
Alp Toker094e5212014-01-05 03:27:11 +0000608 if (TryConsumeToken(tok::comma))
John McCall5e77d762013-04-16 07:28:30 +0000609 continue;
610
611 // If we run into the ')', stop without consuming it.
Alp Toker094e5212014-01-05 03:27:11 +0000612 if (Tok.is(tok::r_paren))
John McCall5e77d762013-04-16 07:28:30 +0000613 break;
Alp Toker094e5212014-01-05 03:27:11 +0000614
615 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
616 break;
John McCall5e77d762013-04-16 07:28:30 +0000617 }
618
619 // Only add the property attribute if it was well-formed.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000620 if (!HasInvalidAccessor)
Craig Topper161e4db2014-05-21 06:02:52 +0000621 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
John McCall5e77d762013-04-16 07:28:30 +0000622 AccessorNames[AK_Get], AccessorNames[AK_Put],
Erich Keanee891aa92018-07-13 15:07:47 +0000623 ParsedAttr::AS_Declspec);
Aaron Ballman478faed2012-06-19 22:09:27 +0000624 T.skipToEnd();
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000625 return !HasInvalidAccessor;
Aaron Ballman478faed2012-06-19 22:09:27 +0000626 }
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000627
Aaron Ballman95d57032014-04-14 16:44:26 +0000628 unsigned NumArgs =
629 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
Erich Keanee891aa92018-07-13 15:07:47 +0000630 SourceLocation(), ParsedAttr::AS_Declspec);
Aaron Ballman95d57032014-04-14 16:44:26 +0000631
632 // If this attribute's args were parsed, and it was expected to have
633 // arguments but none were provided, emit a diagnostic.
Erich Keanec480f302018-07-12 21:09:05 +0000634 if (!Attrs.empty() && Attrs.begin()->getMaxArgs() && !NumArgs) {
Aaron Ballmanef5d94c2014-04-15 00:36:39 +0000635 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Aaron Ballman95d57032014-04-14 16:44:26 +0000636 return false;
637 }
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000638 return true;
Aaron Ballman478faed2012-06-19 22:09:27 +0000639}
640
Eli Friedman06de2b52009-06-08 07:21:15 +0000641/// [MS] decl-specifier:
642/// __declspec ( extended-decl-modifier-seq )
643///
644/// [MS] extended-decl-modifier-seq:
645/// extended-decl-modifier[opt]
646/// extended-decl-modifier extended-decl-modifier-seq
Aaron Ballman068aa512015-05-20 20:58:33 +0000647void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
648 SourceLocation *End) {
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +0000649 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
Steve Naroff3a9b7e02008-12-24 20:59:21 +0000650 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
Eli Friedman06de2b52009-06-08 07:21:15 +0000651
Aaron Ballman068aa512015-05-20 20:58:33 +0000652 while (Tok.is(tok::kw___declspec)) {
653 ConsumeToken();
654 BalancedDelimiterTracker T(*this, tok::l_paren);
655 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
656 tok::r_paren))
Aaron Ballman478faed2012-06-19 22:09:27 +0000657 return;
Aaron Ballman478faed2012-06-19 22:09:27 +0000658
Aaron Ballman068aa512015-05-20 20:58:33 +0000659 // An empty declspec is perfectly legal and should not warn. Additionally,
660 // you can specify multiple attributes per declspec.
661 while (Tok.isNot(tok::r_paren)) {
662 // Attribute not present.
663 if (TryConsumeToken(tok::comma))
664 continue;
665
666 // We expect either a well-known identifier or a generic string. Anything
667 // else is a malformed declspec.
668 bool IsString = Tok.getKind() == tok::string_literal;
669 if (!IsString && Tok.getKind() != tok::identifier &&
670 Tok.getKind() != tok::kw_restrict) {
671 Diag(Tok, diag::err_ms_declspec_type);
Aaron Ballman478faed2012-06-19 22:09:27 +0000672 T.skipToEnd();
673 return;
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000674 }
Aaron Ballman068aa512015-05-20 20:58:33 +0000675
676 IdentifierInfo *AttrName;
677 SourceLocation AttrNameLoc;
678 if (IsString) {
679 SmallString<8> StrBuffer;
680 bool Invalid = false;
681 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
682 if (Invalid) {
683 T.skipToEnd();
684 return;
685 }
686 AttrName = PP.getIdentifierInfo(Str);
687 AttrNameLoc = ConsumeStringToken();
688 } else {
689 AttrName = Tok.getIdentifierInfo();
690 AttrNameLoc = ConsumeToken();
691 }
692
693 bool AttrHandled = false;
694
695 // Parse attribute arguments.
696 if (Tok.is(tok::l_paren))
697 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
698 else if (AttrName->getName() == "property")
699 // The property attribute must have an argument list.
700 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
701 << AttrName->getName();
702
703 if (!AttrHandled)
704 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000705 ParsedAttr::AS_Declspec);
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000706 }
Aaron Ballman068aa512015-05-20 20:58:33 +0000707 T.consumeClose();
708 if (End)
709 *End = T.getCloseLocation();
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000710 }
Eli Friedman53339e02009-06-08 23:27:34 +0000711}
712
John McCall53fa7142010-12-24 02:08:15 +0000713void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
Eli Friedman53339e02009-06-08 23:27:34 +0000714 // Treat these like attributes
Reid Klecknerd7857f02014-10-24 17:42:17 +0000715 while (true) {
716 switch (Tok.getKind()) {
717 case tok::kw___fastcall:
718 case tok::kw___stdcall:
719 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +0000720 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +0000721 case tok::kw___cdecl:
722 case tok::kw___vectorcall:
723 case tok::kw___ptr64:
724 case tok::kw___w64:
725 case tok::kw___ptr32:
Reid Klecknerd7857f02014-10-24 17:42:17 +0000726 case tok::kw___sptr:
727 case tok::kw___uptr: {
728 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
729 SourceLocation AttrNameLoc = ConsumeToken();
730 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000731 ParsedAttr::AS_Keyword);
Reid Klecknerd7857f02014-10-24 17:42:17 +0000732 break;
733 }
734 default:
735 return;
736 }
Eli Friedman53339e02009-06-08 23:27:34 +0000737 }
Steve Naroff3a9b7e02008-12-24 20:59:21 +0000738}
739
Nico Rieckeaaae272014-12-04 23:31:08 +0000740void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
741 SourceLocation StartLoc = Tok.getLocation();
742 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
743
744 if (EndLoc.isValid()) {
745 SourceRange Range(StartLoc, EndLoc);
746 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
747 }
748}
749
750SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
751 SourceLocation EndLoc;
752
753 while (true) {
754 switch (Tok.getKind()) {
755 case tok::kw_const:
756 case tok::kw_volatile:
757 case tok::kw___fastcall:
758 case tok::kw___stdcall:
759 case tok::kw___thiscall:
760 case tok::kw___cdecl:
761 case tok::kw___vectorcall:
762 case tok::kw___ptr32:
763 case tok::kw___ptr64:
764 case tok::kw___w64:
765 case tok::kw___unaligned:
766 case tok::kw___sptr:
767 case tok::kw___uptr:
768 EndLoc = ConsumeToken();
769 break;
770 default:
771 return EndLoc;
772 }
773 }
774}
775
John McCall53fa7142010-12-24 02:08:15 +0000776void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
Dawn Perchik335e16b2010-09-03 01:29:35 +0000777 // Treat these like attributes
778 while (Tok.is(tok::kw___pascal)) {
779 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
780 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000781 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000782 ParsedAttr::AS_Keyword);
Dawn Perchik335e16b2010-09-03 01:29:35 +0000783 }
John McCall53fa7142010-12-24 02:08:15 +0000784}
785
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +0000786void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000787 // Treat these like attributes
788 while (Tok.is(tok::kw___kernel)) {
Richard Smith0cdcc982013-01-29 01:24:26 +0000789 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000790 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000791 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000792 ParsedAttr::AS_Keyword);
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000793 }
794}
795
Aaron Ballman05d76ea2014-01-14 01:29:54 +0000796void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
797 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
798 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +0000799 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000800 ParsedAttr::AS_Keyword);
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000801}
802
Douglas Gregor261a89b2015-06-19 17:51:05 +0000803void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
804 // Treat these like attributes, even though they're type specifiers.
805 while (true) {
806 switch (Tok.getKind()) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +0000807 case tok::kw__Nonnull:
808 case tok::kw__Nullable:
809 case tok::kw__Null_unspecified: {
Douglas Gregor261a89b2015-06-19 17:51:05 +0000810 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
811 SourceLocation AttrNameLoc = ConsumeToken();
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000812 if (!getLangOpts().ObjC)
Douglas Gregor261a89b2015-06-19 17:51:05 +0000813 Diag(AttrNameLoc, diag::ext_nullability)
814 << AttrName;
Fangrui Song6907ce22018-07-30 19:24:48 +0000815 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000816 ParsedAttr::AS_Keyword);
Douglas Gregor261a89b2015-06-19 17:51:05 +0000817 break;
818 }
819 default:
820 return;
821 }
822 }
823}
824
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000825static bool VersionNumberSeparator(const char Separator) {
826 return (Separator == '.' || Separator == '_');
827}
828
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000829/// Parse a version number.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000830///
831/// version:
832/// simple-integer
Jan Korous23255692018-05-17 11:51:49 +0000833/// simple-integer '.' simple-integer
834/// simple-integer '_' simple-integer
835/// simple-integer '.' simple-integer '.' simple-integer
836/// simple-integer '_' simple-integer '_' simple-integer
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000837VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
Erik Pilkington29099de2016-07-16 00:35:23 +0000838 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000839
840 if (!Tok.is(tok::numeric_constant)) {
841 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000842 SkipUntil(tok::comma, tok::r_paren,
843 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000844 return VersionTuple();
845 }
846
847 // Parse the major (and possibly minor and subminor) versions, which
848 // are stored in the numeric constant. We utilize a quirk of the
849 // lexer, which is that it handles something like 1.2.3 as a single
850 // numeric constant, rather than two separate tokens.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000851 SmallString<512> Buffer;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000852 Buffer.resize(Tok.getLength()+1);
853 const char *ThisTokBegin = &Buffer[0];
854
855 // Get the spelling of the token, which eliminates trigraphs, etc.
856 bool Invalid = false;
857 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
858 if (Invalid)
859 return VersionTuple();
860
861 // Parse the major version.
862 unsigned AfterMajor = 0;
863 unsigned Major = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000864 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000865 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
866 ++AfterMajor;
867 }
868
869 if (AfterMajor == 0) {
870 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000871 SkipUntil(tok::comma, tok::r_paren,
872 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000873 return VersionTuple();
874 }
875
876 if (AfterMajor == ActualLength) {
877 ConsumeToken();
878
879 // We only had a single version component.
880 if (Major == 0) {
881 Diag(Tok, diag::err_zero_version);
882 return VersionTuple();
883 }
884
885 return VersionTuple(Major);
886 }
887
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000888 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
889 if (!VersionNumberSeparator(AfterMajorSeparator)
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000890 || (AfterMajor + 1 == ActualLength)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000891 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000892 SkipUntil(tok::comma, tok::r_paren,
893 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000894 return VersionTuple();
895 }
896
897 // Parse the minor version.
898 unsigned AfterMinor = AfterMajor + 1;
899 unsigned Minor = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000900 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000901 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
902 ++AfterMinor;
903 }
904
905 if (AfterMinor == ActualLength) {
906 ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +0000907
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000908 // We had major.minor.
909 if (Major == 0 && Minor == 0) {
910 Diag(Tok, diag::err_zero_version);
911 return VersionTuple();
912 }
913
Jan Korous23255692018-05-17 11:51:49 +0000914 return VersionTuple(Major, Minor);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000915 }
916
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000917 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000918 // If what follows is not a '.' or '_', we have a problem.
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000919 if (!VersionNumberSeparator(AfterMinorSeparator)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000920 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000921 SkipUntil(tok::comma, tok::r_paren,
922 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Chad Rosierc1183952012-06-26 22:30:43 +0000923 return VersionTuple();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000924 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000925
Fariborz Jahanianb6161612014-10-03 17:21:12 +0000926 // Warn if separators, be it '.' or '_', do not match.
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000927 if (AfterMajorSeparator != AfterMinorSeparator)
928 Diag(Tok, diag::warn_expected_consistent_version_separator);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000929
930 // Parse the subminor version.
931 unsigned AfterSubminor = AfterMinor + 1;
932 unsigned Subminor = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000933 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000934 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
935 ++AfterSubminor;
936 }
937
938 if (AfterSubminor != ActualLength) {
939 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000940 SkipUntil(tok::comma, tok::r_paren,
941 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000942 return VersionTuple();
943 }
944 ConsumeToken();
Jan Korous23255692018-05-17 11:51:49 +0000945 return VersionTuple(Major, Minor, Subminor);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000946}
947
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000948/// Parse the contents of the "availability" attribute.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000949///
950/// availability-attribute:
Manman Ren75bc6762016-03-21 17:30:55 +0000951/// 'availability' '(' platform ',' opt-strict version-arg-list,
952/// opt-replacement, opt-message')'
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000953///
954/// platform:
955/// identifier
956///
Manman Rend8039df2016-02-22 04:47:24 +0000957/// opt-strict:
958/// 'strict' ','
Manman Renb636b902016-02-17 22:05:48 +0000959///
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000960/// version-arg-list:
961/// version-arg
962/// version-arg ',' version-arg-list
963///
964/// version-arg:
965/// 'introduced' '=' version
966/// 'deprecated' '=' version
Douglas Gregorfdd417f2012-03-11 04:53:21 +0000967/// 'obsoleted' = version
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000968/// 'unavailable'
Manman Ren75bc6762016-03-21 17:30:55 +0000969/// opt-replacement:
970/// 'replacement' '=' <string>
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000971/// opt-message:
972/// 'message' '=' <string>
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000973void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
974 SourceLocation AvailabilityLoc,
975 ParsedAttributes &attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000976 SourceLocation *endLoc,
977 IdentifierInfo *ScopeName,
978 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000979 ParsedAttr::Syntax Syntax) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000980 enum { Introduced, Deprecated, Obsoleted, Unknown };
981 AvailabilityChange Changes[Unknown];
Manman Ren75bc6762016-03-21 17:30:55 +0000982 ExprResult MessageExpr, ReplacementExpr;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000983
984 // Opening '('.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000985 BalancedDelimiterTracker T(*this, tok::l_paren);
986 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000987 Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000988 return;
989 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000990
Manman Renb636b902016-02-17 22:05:48 +0000991 // Parse the platform name.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000992 if (Tok.isNot(tok::identifier)) {
993 Diag(Tok, diag::err_availability_expected_platform);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000994 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000995 return;
996 }
Richard Smithfeefaf52013-09-03 18:01:40 +0000997 IdentifierLoc *Platform = ParseIdentifierLoc();
Alex Lorenz0b1ce8b2017-08-15 14:42:01 +0000998 if (const IdentifierInfo *const Ident = Platform->Ident) {
999 // Canonicalize platform name from "macosx" to "macos".
1000 if (Ident->getName() == "macosx")
1001 Platform->Ident = PP.getIdentifierInfo("macos");
1002 // Canonicalize platform name from "macosx_app_extension" to
1003 // "macos_app_extension".
1004 else if (Ident->getName() == "macosx_app_extension")
1005 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1006 else
1007 Platform->Ident = PP.getIdentifierInfo(
1008 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1009 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001010
1011 // Parse the ',' following the platform name.
Alp Toker383d2c42014-01-01 03:08:43 +00001012 if (ExpectAndConsume(tok::comma)) {
1013 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001014 return;
Alp Toker383d2c42014-01-01 03:08:43 +00001015 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001016
1017 // If we haven't grabbed the pointers for the identifiers
1018 // "introduced", "deprecated", and "obsoleted", do so now.
1019 if (!Ident_introduced) {
1020 Ident_introduced = PP.getIdentifierInfo("introduced");
1021 Ident_deprecated = PP.getIdentifierInfo("deprecated");
1022 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001023 Ident_unavailable = PP.getIdentifierInfo("unavailable");
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001024 Ident_message = PP.getIdentifierInfo("message");
Manman Rend8039df2016-02-22 04:47:24 +00001025 Ident_strict = PP.getIdentifierInfo("strict");
Manman Ren75bc6762016-03-21 17:30:55 +00001026 Ident_replacement = PP.getIdentifierInfo("replacement");
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001027 }
1028
Manman Ren75bc6762016-03-21 17:30:55 +00001029 // Parse the optional "strict", the optional "replacement" and the set of
Manman Renb636b902016-02-17 22:05:48 +00001030 // introductions/deprecations/removals.
Manman Rend8039df2016-02-22 04:47:24 +00001031 SourceLocation UnavailableLoc, StrictLoc;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001032 do {
1033 if (Tok.isNot(tok::identifier)) {
1034 Diag(Tok, diag::err_availability_expected_change);
Alexey Bataevee6507d2013-11-18 08:17:37 +00001035 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001036 return;
1037 }
1038 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1039 SourceLocation KeywordLoc = ConsumeToken();
1040
Manman Rend8039df2016-02-22 04:47:24 +00001041 if (Keyword == Ident_strict) {
1042 if (StrictLoc.isValid()) {
Manman Renb636b902016-02-17 22:05:48 +00001043 Diag(KeywordLoc, diag::err_availability_redundant)
Manman Rend8039df2016-02-22 04:47:24 +00001044 << Keyword << SourceRange(StrictLoc);
Manman Renb636b902016-02-17 22:05:48 +00001045 }
Manman Rend8039df2016-02-22 04:47:24 +00001046 StrictLoc = KeywordLoc;
Manman Renb636b902016-02-17 22:05:48 +00001047 continue;
1048 }
1049
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001050 if (Keyword == Ident_unavailable) {
1051 if (UnavailableLoc.isValid()) {
1052 Diag(KeywordLoc, diag::err_availability_redundant)
1053 << Keyword << SourceRange(UnavailableLoc);
Chad Rosierc1183952012-06-26 22:30:43 +00001054 }
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001055 UnavailableLoc = KeywordLoc;
Alp Toker97650562014-01-10 11:19:30 +00001056 continue;
Chad Rosierc1183952012-06-26 22:30:43 +00001057 }
1058
Michael Wu260e9622018-11-12 02:44:33 +00001059 if (Keyword == Ident_deprecated && Platform->Ident &&
1060 Platform->Ident->isStr("swift")) {
1061 // For swift, we deprecate for all versions.
1062 if (Changes[Deprecated].KeywordLoc.isValid()) {
1063 Diag(KeywordLoc, diag::err_availability_redundant)
1064 << Keyword
1065 << SourceRange(Changes[Deprecated].KeywordLoc);
1066 }
1067
1068 Changes[Deprecated].KeywordLoc = KeywordLoc;
1069 // Use a fake version here.
1070 Changes[Deprecated].Version = VersionTuple(1);
1071 continue;
1072 }
1073
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001074 if (Tok.isNot(tok::equal)) {
Alp Tokerec543272013-12-24 09:48:30 +00001075 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001076 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001077 return;
1078 }
1079 ConsumeToken();
Manman Ren75bc6762016-03-21 17:30:55 +00001080 if (Keyword == Ident_message || Keyword == Ident_replacement) {
David Majnemer2e498302014-07-18 05:43:12 +00001081 if (Tok.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001082 Diag(Tok, diag::err_expected_string_literal)
1083 << /*Source='availability attribute'*/2;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001084 SkipUntil(tok::r_paren, StopAtSemi);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001085 return;
1086 }
Manman Ren75bc6762016-03-21 17:30:55 +00001087 if (Keyword == Ident_message)
1088 MessageExpr = ParseStringLiteralExpression();
1089 else
1090 ReplacementExpr = ParseStringLiteralExpression();
David Majnemer2e498302014-07-18 05:43:12 +00001091 // Also reject wide string literals.
1092 if (StringLiteral *MessageStringLiteral =
1093 cast_or_null<StringLiteral>(MessageExpr.get())) {
1094 if (MessageStringLiteral->getCharByteWidth() != 1) {
1095 Diag(MessageStringLiteral->getSourceRange().getBegin(),
1096 diag::err_expected_string_literal)
1097 << /*Source='availability attribute'*/ 2;
1098 SkipUntil(tok::r_paren, StopAtSemi);
1099 return;
1100 }
1101 }
Manman Ren75bc6762016-03-21 17:30:55 +00001102 if (Keyword == Ident_message)
1103 break;
1104 else
1105 continue;
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001106 }
Chad Rosierc1183952012-06-26 22:30:43 +00001107
Fariborz Jahanian5a29e6a2014-11-05 23:58:55 +00001108 // Special handling of 'NA' only when applied to introduced or
1109 // deprecated.
1110 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1111 Tok.is(tok::identifier)) {
1112 IdentifierInfo *NA = Tok.getIdentifierInfo();
1113 if (NA->getName() == "NA") {
1114 ConsumeToken();
1115 if (Keyword == Ident_introduced)
1116 UnavailableLoc = KeywordLoc;
1117 continue;
1118 }
1119 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001120
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001121 SourceRange VersionRange;
1122 VersionTuple Version = ParseVersionTuple(VersionRange);
Chad Rosierc1183952012-06-26 22:30:43 +00001123
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001124 if (Version.empty()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001125 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001126 return;
1127 }
1128
1129 unsigned Index;
1130 if (Keyword == Ident_introduced)
1131 Index = Introduced;
1132 else if (Keyword == Ident_deprecated)
1133 Index = Deprecated;
1134 else if (Keyword == Ident_obsoleted)
1135 Index = Obsoleted;
Chad Rosierc1183952012-06-26 22:30:43 +00001136 else
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001137 Index = Unknown;
1138
1139 if (Index < Unknown) {
1140 if (!Changes[Index].KeywordLoc.isInvalid()) {
1141 Diag(KeywordLoc, diag::err_availability_redundant)
Chad Rosierc1183952012-06-26 22:30:43 +00001142 << Keyword
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001143 << SourceRange(Changes[Index].KeywordLoc,
1144 Changes[Index].VersionRange.getEnd());
1145 }
1146
1147 Changes[Index].KeywordLoc = KeywordLoc;
1148 Changes[Index].Version = Version;
1149 Changes[Index].VersionRange = VersionRange;
1150 } else {
1151 Diag(KeywordLoc, diag::err_availability_unknown_change)
1152 << Keyword << VersionRange;
1153 }
1154
Alp Toker97650562014-01-10 11:19:30 +00001155 } while (TryConsumeToken(tok::comma));
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001156
1157 // Closing ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001158 if (T.consumeClose())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001159 return;
1160
1161 if (endLoc)
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001162 *endLoc = T.getCloseLocation();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001163
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001164 // The 'unavailable' availability cannot be combined with any other
1165 // availability changes. Make sure that hasn't happened.
1166 if (UnavailableLoc.isValid()) {
1167 bool Complained = false;
1168 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1169 if (Changes[Index].KeywordLoc.isValid()) {
1170 if (!Complained) {
1171 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1172 << SourceRange(Changes[Index].KeywordLoc,
1173 Changes[Index].VersionRange.getEnd());
1174 Complained = true;
1175 }
1176
1177 // Clear out the availability.
1178 Changes[Index] = AvailabilityChange();
1179 }
1180 }
1181 }
1182
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001183 // Record this attribute
Chad Rosierc1183952012-06-26 22:30:43 +00001184 attrs.addNew(&Availability,
1185 SourceRange(AvailabilityLoc, T.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001186 ScopeName, ScopeLoc,
Aaron Ballman00e99962013-08-31 01:11:41 +00001187 Platform,
John McCall084e83d2011-03-24 11:26:52 +00001188 Changes[Introduced],
1189 Changes[Deprecated],
Chad Rosierc1183952012-06-26 22:30:43 +00001190 Changes[Obsoleted],
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001191 UnavailableLoc, MessageExpr.get(),
Manman Ren75bc6762016-03-21 17:30:55 +00001192 Syntax, StrictLoc, ReplacementExpr.get());
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001193}
1194
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001195/// Parse the contents of the "external_source_symbol" attribute.
Alex Lorenzd5d27e12017-03-01 18:06:25 +00001196///
1197/// external-source-symbol-attribute:
1198/// 'external_source_symbol' '(' keyword-arg-list ')'
1199///
1200/// keyword-arg-list:
1201/// keyword-arg
1202/// keyword-arg ',' keyword-arg-list
1203///
1204/// keyword-arg:
1205/// 'language' '=' <string>
1206/// 'defined_in' '=' <string>
1207/// 'generated_declaration'
1208void Parser::ParseExternalSourceSymbolAttribute(
1209 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1210 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +00001211 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00001212 // Opening '('.
1213 BalancedDelimiterTracker T(*this, tok::l_paren);
1214 if (T.expectAndConsume())
1215 return;
1216
1217 // Initialize the pointers for the keyword identifiers when required.
1218 if (!Ident_language) {
1219 Ident_language = PP.getIdentifierInfo("language");
1220 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1221 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1222 }
1223
1224 ExprResult Language;
1225 bool HasLanguage = false;
1226 ExprResult DefinedInExpr;
1227 bool HasDefinedIn = false;
1228 IdentifierLoc *GeneratedDeclaration = nullptr;
1229
1230 // Parse the language/defined_in/generated_declaration keywords
1231 do {
1232 if (Tok.isNot(tok::identifier)) {
1233 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1234 SkipUntil(tok::r_paren, StopAtSemi);
1235 return;
1236 }
1237
1238 SourceLocation KeywordLoc = Tok.getLocation();
1239 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1240 if (Keyword == Ident_generated_declaration) {
1241 if (GeneratedDeclaration) {
1242 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1243 SkipUntil(tok::r_paren, StopAtSemi);
1244 return;
1245 }
1246 GeneratedDeclaration = ParseIdentifierLoc();
1247 continue;
1248 }
1249
1250 if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1251 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1252 SkipUntil(tok::r_paren, StopAtSemi);
1253 return;
1254 }
1255
1256 ConsumeToken();
1257 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1258 Keyword->getName())) {
1259 SkipUntil(tok::r_paren, StopAtSemi);
1260 return;
1261 }
1262
1263 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1264 if (Keyword == Ident_language)
1265 HasLanguage = true;
1266 else
1267 HasDefinedIn = true;
1268
1269 if (Tok.isNot(tok::string_literal)) {
1270 Diag(Tok, diag::err_expected_string_literal)
1271 << /*Source='external_source_symbol attribute'*/ 3
1272 << /*language | source container*/ (Keyword != Ident_language);
1273 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1274 continue;
1275 }
1276 if (Keyword == Ident_language) {
1277 if (HadLanguage) {
1278 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1279 << Keyword;
1280 ParseStringLiteralExpression();
1281 continue;
1282 }
1283 Language = ParseStringLiteralExpression();
1284 } else {
1285 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1286 if (HadDefinedIn) {
1287 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1288 << Keyword;
1289 ParseStringLiteralExpression();
1290 continue;
1291 }
1292 DefinedInExpr = ParseStringLiteralExpression();
1293 }
1294 } while (TryConsumeToken(tok::comma));
1295
1296 // Closing ')'.
1297 if (T.consumeClose())
1298 return;
1299 if (EndLoc)
1300 *EndLoc = T.getCloseLocation();
1301
1302 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1303 GeneratedDeclaration};
1304 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1305 ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1306}
1307
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001308/// Parse the contents of the "objc_bridge_related" attribute.
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001309/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1310/// related_class:
1311/// Identifier
1312///
1313/// opt-class_method:
1314/// Identifier: | <empty>
1315///
1316/// opt-instance_method:
1317/// Identifier | <empty>
1318///
1319void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1320 SourceLocation ObjCBridgeRelatedLoc,
1321 ParsedAttributes &attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001322 SourceLocation *endLoc,
1323 IdentifierInfo *ScopeName,
1324 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001325 ParsedAttr::Syntax Syntax) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001326 // Opening '('.
1327 BalancedDelimiterTracker T(*this, tok::l_paren);
1328 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00001329 Diag(Tok, diag::err_expected) << tok::l_paren;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001330 return;
1331 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001332
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001333 // Parse the related class name.
1334 if (Tok.isNot(tok::identifier)) {
1335 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1336 SkipUntil(tok::r_paren, StopAtSemi);
1337 return;
1338 }
1339 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
Alp Toker97650562014-01-10 11:19:30 +00001340 if (ExpectAndConsume(tok::comma)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001341 SkipUntil(tok::r_paren, StopAtSemi);
1342 return;
1343 }
Alp Toker8fbec672013-12-17 23:29:36 +00001344
Aaron Ballman48a533d2018-02-27 23:49:28 +00001345 // Parse class method name. It's non-optional in the sense that a trailing
1346 // comma is required, but it can be the empty string, and then we record a
1347 // nullptr.
Craig Topper161e4db2014-05-21 06:02:52 +00001348 IdentifierLoc *ClassMethod = nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001349 if (Tok.is(tok::identifier)) {
1350 ClassMethod = ParseIdentifierLoc();
Alp Toker8fbec672013-12-17 23:29:36 +00001351 if (!TryConsumeToken(tok::colon)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001352 Diag(Tok, diag::err_objcbridge_related_selector_name);
1353 SkipUntil(tok::r_paren, StopAtSemi);
1354 return;
1355 }
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001356 }
Alp Toker8fbec672013-12-17 23:29:36 +00001357 if (!TryConsumeToken(tok::comma)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001358 if (Tok.is(tok::colon))
1359 Diag(Tok, diag::err_objcbridge_related_selector_name);
1360 else
Alp Tokerec543272013-12-24 09:48:30 +00001361 Diag(Tok, diag::err_expected) << tok::comma;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001362 SkipUntil(tok::r_paren, StopAtSemi);
1363 return;
1364 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001365
Aaron Ballman48a533d2018-02-27 23:49:28 +00001366 // Parse instance method name. Also non-optional but empty string is
1367 // permitted.
Craig Topper161e4db2014-05-21 06:02:52 +00001368 IdentifierLoc *InstanceMethod = nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001369 if (Tok.is(tok::identifier))
1370 InstanceMethod = ParseIdentifierLoc();
1371 else if (Tok.isNot(tok::r_paren)) {
Alp Tokerec543272013-12-24 09:48:30 +00001372 Diag(Tok, diag::err_expected) << tok::r_paren;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001373 SkipUntil(tok::r_paren, StopAtSemi);
1374 return;
1375 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001376
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001377 // Closing ')'.
1378 if (T.consumeClose())
1379 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001380
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001381 if (endLoc)
1382 *endLoc = T.getCloseLocation();
Fangrui Song6907ce22018-07-30 19:24:48 +00001383
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001384 // Record this attribute
1385 attrs.addNew(&ObjCBridgeRelated,
1386 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001387 ScopeName, ScopeLoc,
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001388 RelatedClass,
1389 ClassMethod,
1390 InstanceMethod,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001391 Syntax);
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001392}
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001393
Bill Wendling44426052012-12-20 19:22:21 +00001394// Late Parsed Attributes:
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001395// See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1396
1397void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1398
1399void Parser::LateParsedClass::ParseLexedAttributes() {
1400 Self->ParseLexedAttributes(*Class);
1401}
1402
1403void Parser::LateParsedAttribute::ParseLexedAttributes() {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001404 Self->ParseLexedAttribute(*this, true, false);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001405}
1406
1407/// Wrapper class which calls ParseLexedAttribute, after setting up the
1408/// scope appropriately.
1409void Parser::ParseLexedAttributes(ParsingClass &Class) {
1410 // Deal with templates
1411 // FIXME: Test cases to make sure this does the right thing for templates.
1412 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1413 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1414 HasTemplateScope);
1415 if (HasTemplateScope)
1416 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1417
Douglas Gregor3024f072012-04-16 07:05:22 +00001418 // Set or update the scope flags.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001419 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +00001420 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001421 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1422 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1423
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001424 // Enter the scope of nested classes
1425 if (!AlreadyHasClassScope)
1426 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1427 Class.TagOrTemplate);
Benjamin Kramer1d373c62012-05-17 12:01:52 +00001428 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001429 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1430 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1431 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001432 }
Chad Rosierc1183952012-06-26 22:30:43 +00001433
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001434 if (!AlreadyHasClassScope)
1435 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1436 Class.TagOrTemplate);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001437}
1438
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001439/// Parse all attributes in LAs, and attach them to Decl D.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001440void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1441 bool EnterScope, bool OnDefinition) {
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001442 assert(LAs.parseSoon() &&
1443 "Attribute list should be marked for immediate parsing.");
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001444 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
DeLesley Hutchins19c722d2012-08-15 22:41:04 +00001445 if (D)
1446 LAs[i]->addDecl(D);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001447 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
Benjamin Kramerbafc49a2012-04-14 12:44:47 +00001448 delete LAs[i];
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001449 }
1450 LAs.clear();
1451}
1452
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001453/// Finish parsing an attribute for which parsing was delayed.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001454/// This will be called at the end of parsing a class declaration
1455/// for each LateParsedAttribute. We consume the saved tokens and
Chad Rosierc1183952012-06-26 22:30:43 +00001456/// create an attribute with the arguments filled in. We add this
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001457/// to the Attribute list for the decl.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001458void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1459 bool EnterScope, bool OnDefinition) {
David Majnemerd5946f52015-01-13 08:35:24 +00001460 // Create a fake EOF so that attribute parsing won't go off the end of the
1461 // attribute.
1462 Token AttrEnd;
1463 AttrEnd.startToken();
1464 AttrEnd.setKind(tok::eof);
1465 AttrEnd.setLocation(Tok.getLocation());
1466 AttrEnd.setEofData(LA.Toks.data());
1467 LA.Toks.push_back(AttrEnd);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001468
1469 // Append the current token at the end of the new token stream so that it
1470 // doesn't get lost.
1471 LA.Toks.push_back(Tok);
David Blaikie2eabcc92016-02-09 18:52:09 +00001472 PP.EnterTokenStream(LA.Toks, true);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001473 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +00001474 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001475
1476 ParsedAttributes Attrs(AttrFactory);
1477 SourceLocation endLoc;
1478
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001479 if (LA.Decls.size() > 0) {
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001480 Decl *D = LA.Decls[0];
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001481 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1482 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001483
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001484 // Allow 'this' within late-parsed attributes.
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001485 Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
Richard Smithc3d2ebb2013-06-07 02:33:37 +00001486 ND && ND->isCXXInstanceMember());
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001487
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001488 if (LA.Decls.size() == 1) {
1489 // If the Decl is templatized, add template parameters to scope.
1490 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1491 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1492 if (HasTemplateScope)
1493 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001494
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001495 // If the Decl is on a function, add function parameters to the scope.
1496 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
Momchil Velikov57c681f2017-08-10 15:43:06 +00001497 ParseScope FnScope(
1498 this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
1499 HasFunScope);
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001500 if (HasFunScope)
1501 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001502
Michael Han23214e52012-10-03 01:56:22 +00001503 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001504 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
Craig Topper161e4db2014-05-21 06:02:52 +00001505 nullptr);
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001506
1507 if (HasFunScope) {
1508 Actions.ActOnExitFunctionContext();
1509 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1510 }
1511 if (HasTemplateScope) {
1512 TempScope.Exit();
1513 }
1514 } else {
1515 // If there are multiple decls, then the decl cannot be within the
1516 // function scope.
Michael Han23214e52012-10-03 01:56:22 +00001517 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001518 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
Craig Topper161e4db2014-05-21 06:02:52 +00001519 nullptr);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001520 }
DeLesley Hutchins71d61032012-03-02 22:29:50 +00001521 } else {
1522 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001523 }
1524
Erich Keanec480f302018-07-12 21:09:05 +00001525 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
1526 Attrs.begin()->isKnownToGCC())
Aaron Ballman9a99e0d2014-01-20 17:18:35 +00001527 Diag(Tok, diag::warn_attribute_on_function_definition)
1528 << &LA.AttrName;
1529
1530 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001531 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001532
David Majnemerd5946f52015-01-13 08:35:24 +00001533 // Due to a parsing error, we either went over the cached tokens or
1534 // there are still cached tokens left, so we skip the leftover tokens.
1535 while (Tok.isNot(tok::eof))
1536 ConsumeAnyToken();
1537
1538 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1539 ConsumeAnyToken();
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001540}
1541
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001542void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1543 SourceLocation AttrNameLoc,
1544 ParsedAttributes &Attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001545 SourceLocation *EndLoc,
1546 IdentifierInfo *ScopeName,
1547 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001548 ParsedAttr::Syntax Syntax) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001549 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1550
1551 BalancedDelimiterTracker T(*this, tok::l_paren);
1552 T.consumeOpen();
1553
1554 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001555 Diag(Tok, diag::err_expected) << tok::identifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001556 T.skipToEnd();
1557 return;
1558 }
Richard Smithfeefaf52013-09-03 18:01:40 +00001559 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001560
Alp Toker094e5212014-01-05 03:27:11 +00001561 if (ExpectAndConsume(tok::comma)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001562 T.skipToEnd();
1563 return;
1564 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001565
1566 SourceRange MatchingCTypeRange;
1567 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1568 if (MatchingCType.isInvalid()) {
1569 T.skipToEnd();
1570 return;
1571 }
1572
1573 bool LayoutCompatible = false;
1574 bool MustBeNull = false;
Alp Toker8fbec672013-12-17 23:29:36 +00001575 while (TryConsumeToken(tok::comma)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001576 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001577 Diag(Tok, diag::err_expected) << tok::identifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001578 T.skipToEnd();
1579 return;
1580 }
1581 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1582 if (Flag->isStr("layout_compatible"))
1583 LayoutCompatible = true;
1584 else if (Flag->isStr("must_be_null"))
1585 MustBeNull = true;
1586 else {
1587 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1588 T.skipToEnd();
1589 return;
1590 }
1591 ConsumeToken(); // consume flag
1592 }
1593
1594 if (!T.consumeClose()) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001595 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001596 ArgumentKind, MatchingCType.get(),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001597 LayoutCompatible, MustBeNull, Syntax);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001598 }
1599
1600 if (EndLoc)
1601 *EndLoc = T.getCloseLocation();
1602}
1603
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001604/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1605/// of a C++11 attribute-specifier in a location where an attribute is not
1606/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1607/// situation.
1608///
1609/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1610/// this doesn't appear to actually be an attribute-specifier, and the caller
1611/// should try to parse it.
1612bool Parser::DiagnoseProhibitedCXX11Attribute() {
1613 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1614
1615 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1616 case CAK_NotAttributeSpecifier:
1617 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1618 return false;
1619
1620 case CAK_InvalidAttributeSpecifier:
1621 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1622 return false;
1623
1624 case CAK_AttributeSpecifier:
1625 // Parse and discard the attributes.
1626 SourceLocation BeginLoc = ConsumeBracket();
1627 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001628 SkipUntil(tok::r_square);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001629 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1630 SourceLocation EndLoc = ConsumeBracket();
1631 Diag(BeginLoc, diag::err_attributes_not_allowed)
1632 << SourceRange(BeginLoc, EndLoc);
1633 return true;
1634 }
Chandler Carruthd8f7d382012-04-10 16:03:08 +00001635 llvm_unreachable("All cases handled above.");
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001636}
1637
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001638/// We have found the opening square brackets of a C++11
Richard Smith98155ad2013-02-20 01:17:14 +00001639/// attribute-specifier in a location where an attribute is not permitted, but
1640/// we know where the attributes ought to be written. Parse them anyway, and
1641/// provide a fixit moving them to the right place.
Richard Smith4c96e992013-02-19 23:47:15 +00001642void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1643 SourceLocation CorrectLocation) {
1644 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1645 Tok.is(tok::kw_alignas));
1646
1647 // Consume the attributes.
1648 SourceLocation Loc = Tok.getLocation();
1649 ParseCXX11Attributes(Attrs);
1650 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
Faisal Valic5089c02017-12-25 22:23:20 +00001651 // FIXME: use err_attributes_misplaced
Richard Smith4c96e992013-02-19 23:47:15 +00001652 Diag(Loc, diag::err_attributes_not_allowed)
1653 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1654 << FixItHint::CreateRemoval(AttrRange);
1655}
1656
Erich Keanec480f302018-07-12 21:09:05 +00001657void Parser::DiagnoseProhibitedAttributes(
1658 const SourceRange &Range, const SourceLocation CorrectLocation) {
Faisal Valic5089c02017-12-25 22:23:20 +00001659 if (CorrectLocation.isValid()) {
Erich Keanec480f302018-07-12 21:09:05 +00001660 CharSourceRange AttrRange(Range, true);
Faisal Valic5089c02017-12-25 22:23:20 +00001661 Diag(CorrectLocation, diag::err_attributes_misplaced)
1662 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1663 << FixItHint::CreateRemoval(AttrRange);
1664 } else
Erich Keanec480f302018-07-12 21:09:05 +00001665 Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
Dawn Perchik335e16b2010-09-03 01:29:35 +00001666}
1667
Richard Smith49cc1cc2016-08-18 21:59:42 +00001668void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1669 unsigned DiagID) {
Erich Keanee891aa92018-07-13 15:07:47 +00001670 for (const ParsedAttr &AL : Attrs) {
Erich Keanec480f302018-07-12 21:09:05 +00001671 if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
Richard Smith49cc1cc2016-08-18 21:59:42 +00001672 continue;
Erich Keanee891aa92018-07-13 15:07:47 +00001673 if (AL.getKind() == ParsedAttr::UnknownAttribute)
Erich Keanec480f302018-07-12 21:09:05 +00001674 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL.getName();
Richard Smith49cc1cc2016-08-18 21:59:42 +00001675 else {
Erich Keanec480f302018-07-12 21:09:05 +00001676 Diag(AL.getLoc(), DiagID) << AL.getName();
1677 AL.setInvalid();
Michael Han64536a62012-11-06 19:34:54 +00001678 }
Michael Han64536a62012-11-06 19:34:54 +00001679 }
1680}
1681
Nico Weber32a0fc72016-09-03 03:01:32 +00001682// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1683// applies to var, not the type Foo.
David Majnemer936b4112015-04-19 07:53:29 +00001684// As an exception to the rule, __declspec(align(...)) before the
1685// class-key affects the type instead of the variable.
Nico Weber32a0fc72016-09-03 03:01:32 +00001686// Also, Microsoft-style [attributes] seem to affect the type instead of the
1687// variable.
1688// This function moves attributes that should apply to the type off DS to Attrs.
1689void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1690 DeclSpec &DS,
1691 Sema::TagUseKind TUK) {
David Majnemer936b4112015-04-19 07:53:29 +00001692 if (TUK == Sema::TUK_Reference)
1693 return;
1694
Erich Keanee891aa92018-07-13 15:07:47 +00001695 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
David Majnemer936b4112015-04-19 07:53:29 +00001696
Erich Keanee891aa92018-07-13 15:07:47 +00001697 for (ParsedAttr &AL : DS.getAttributes()) {
1698 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
Erich Keanec480f302018-07-12 21:09:05 +00001699 AL.isDeclspecAttribute()) ||
1700 AL.isMicrosoftAttribute())
1701 ToBeMoved.push_back(&AL);
David Majnemer936b4112015-04-19 07:53:29 +00001702 }
Nico Weber88f5ed92016-09-13 18:55:26 +00001703
Erich Keanee891aa92018-07-13 15:07:47 +00001704 for (ParsedAttr *AL : ToBeMoved) {
Erich Keanec480f302018-07-12 21:09:05 +00001705 DS.getAttributes().remove(AL);
1706 Attrs.addAtEnd(AL);
1707 }
David Majnemer936b4112015-04-19 07:53:29 +00001708}
1709
Chris Lattner53361ac2006-08-10 05:19:57 +00001710/// ParseDeclaration - Parse a full 'declaration', which consists of
1711/// declaration-specifiers, some number of declarators, and a semicolon.
Faisal Vali421b2d12017-12-29 05:41:00 +00001712/// 'Context' should be a DeclaratorContext value. This returns the
Chris Lattner49836b42009-04-02 04:16:50 +00001713/// location of the semicolon in DeclEnd.
Chris Lattnera5235172007-08-25 06:57:03 +00001714///
1715/// declaration: [C99 6.7]
1716/// block-declaration ->
1717/// simple-declaration
1718/// others [FIXME]
Douglas Gregoreb31f392008-12-01 23:54:00 +00001719/// [C++] template-declaration
Chris Lattnera5235172007-08-25 06:57:03 +00001720/// [C++] namespace-definition
Douglas Gregord7c4d982008-12-30 03:27:21 +00001721/// [C++] using-directive
Douglas Gregor77b50e12009-06-22 23:06:13 +00001722/// [C++] using-declaration
Richard Smithc202b282012-04-14 00:33:13 +00001723/// [C++11/C11] static_assert-declaration
Chris Lattnera5235172007-08-25 06:57:03 +00001724/// others... [FIXME]
1725///
Faisal Vali421b2d12017-12-29 05:41:00 +00001726Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
Alexis Hunt96d5c762009-11-21 08:43:09 +00001727 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +00001728 ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +00001729 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Fariborz Jahanian59b75282011-08-30 17:10:52 +00001730 // Must temporarily exit the objective-c container scope for
1731 // parsing c none objective-c decls.
1732 ObjCDeclContextSwitch ObjCDC(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00001733
Craig Topper161e4db2014-05-21 06:02:52 +00001734 Decl *SingleDecl = nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +00001735 switch (Tok.getKind()) {
Douglas Gregoreb31f392008-12-01 23:54:00 +00001736 case tok::kw_template:
Douglas Gregor23996282009-05-12 21:31:51 +00001737 case tok::kw_export:
John McCall53fa7142010-12-24 02:08:15 +00001738 ProhibitAttributes(attrs);
Erich Keanec480f302018-07-12 21:09:05 +00001739 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001740 break;
Sebastian Redl67667942010-08-27 23:12:46 +00001741 case tok::kw_inline:
Sebastian Redl5a5f2c72010-08-31 00:36:45 +00001742 // Could be the start of an inline namespace. Allowed as an ext in C++03.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001743 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
John McCall53fa7142010-12-24 02:08:15 +00001744 ProhibitAttributes(attrs);
Sebastian Redl67667942010-08-27 23:12:46 +00001745 SourceLocation InlineLoc = ConsumeToken();
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00001746 return ParseNamespace(Context, DeclEnd, InlineLoc);
Sebastian Redl67667942010-08-27 23:12:46 +00001747 }
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001748 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
Fariborz Jahanian1db5c942010-09-28 20:42:35 +00001749 true);
Chris Lattnera5235172007-08-25 06:57:03 +00001750 case tok::kw_namespace:
John McCall53fa7142010-12-24 02:08:15 +00001751 ProhibitAttributes(attrs);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00001752 return ParseNamespace(Context, DeclEnd);
Douglas Gregord7c4d982008-12-30 03:27:21 +00001753 case tok::kw_using:
Richard Smith6f1daa42016-12-16 00:58:48 +00001754 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1755 DeclEnd, attrs);
Anders Carlssonf24fcff62009-03-11 16:27:10 +00001756 case tok::kw_static_assert:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00001757 case tok::kw__Static_assert:
John McCall53fa7142010-12-24 02:08:15 +00001758 ProhibitAttributes(attrs);
Chris Lattner49836b42009-04-02 04:16:50 +00001759 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001760 break;
Chris Lattnera5235172007-08-25 06:57:03 +00001761 default:
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001762 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
Chris Lattnera5235172007-08-25 06:57:03 +00001763 }
Chad Rosierc1183952012-06-26 22:30:43 +00001764
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001765 // This routine returns a DeclGroup, if the thing we parsed only contains a
Richard Smith6f1daa42016-12-16 00:58:48 +00001766 // single decl, convert it now.
1767 return Actions.ConvertDeclToDeclGroup(SingleDecl);
Chris Lattnera5235172007-08-25 06:57:03 +00001768}
1769
1770/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1771/// declaration-specifiers init-declarator-list[opt] ';'
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001772/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1773/// init-declarator-list ';'
Chris Lattnera5235172007-08-25 06:57:03 +00001774///[C90/C++]init-declarator-list ';' [TODO]
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001775/// [OMP] threadprivate-directive
1776/// [OMP] allocate-directive [TODO]
Chris Lattner32dc41c2009-03-29 17:27:48 +00001777///
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001778/// for-range-declaration: [C++11 6.5p1: stmt.ranged]
Richard Smith02e85f32011-04-14 22:09:26 +00001779/// attribute-specifier-seq[opt] type-specifier-seq declarator
1780///
Chris Lattner32dc41c2009-03-29 17:27:48 +00001781/// If RequireSemi is false, this does not check for a ';' at the end of the
Chris Lattner005fc1b2010-04-05 18:18:31 +00001782/// declaration. If it is true, it checks for and eats it.
Richard Smith02e85f32011-04-14 22:09:26 +00001783///
1784/// If FRI is non-null, we might be parsing a for-range-declaration instead
1785/// of a simple-declaration. If we find that we are, we also parse the
1786/// for-range-initializer, and place it here.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001787Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +00001788Parser::ParseSimpleDeclaration(DeclaratorContext Context,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001789 SourceLocation &DeclEnd,
Richard Smith2386c8b2013-02-22 09:06:26 +00001790 ParsedAttributesWithRange &Attrs,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001791 bool RequireSemi, ForRangeInit *FRI) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001792 // Parse the common declaration-specifiers piece.
John McCall28a6aea2009-11-04 02:18:39 +00001793 ParsingDeclSpec DS(*this);
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001794
Richard Smith404dfb42013-11-19 22:47:36 +00001795 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
Faisal Valia534f072018-04-26 00:42:40 +00001796 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
Richard Smith404dfb42013-11-19 22:47:36 +00001797
1798 // If we had a free-standing type definition with a missing semicolon, we
1799 // may get this far before the problem becomes obvious.
1800 if (DS.hasTagDefinition() &&
1801 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
David Blaikie0403cb12016-01-15 23:43:25 +00001802 return nullptr;
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001803
Chris Lattner0e894622006-08-13 19:58:17 +00001804 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1805 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner76c72282007-10-09 17:33:22 +00001806 if (Tok.is(tok::semi)) {
Richard Smith2386c8b2013-02-22 09:06:26 +00001807 ProhibitAttributes(Attrs);
Argyrios Kyrtzidisfbb2bb52012-05-16 23:49:15 +00001808 DeclEnd = Tok.getLocation();
Chris Lattner005fc1b2010-04-05 18:18:31 +00001809 if (RequireSemi) ConsumeToken();
Nico Weber7b837f52016-01-28 19:25:00 +00001810 RecordDecl *AnonRecord = nullptr;
John McCall48871652010-08-21 09:40:31 +00001811 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00001812 DS, AnonRecord);
John McCall28a6aea2009-11-04 02:18:39 +00001813 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00001814 if (AnonRecord) {
1815 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00001816 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00001817 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001818 return Actions.ConvertDeclToDeclGroup(TheDecl);
Chris Lattner0e894622006-08-13 19:58:17 +00001819 }
Chad Rosierc1183952012-06-26 22:30:43 +00001820
Richard Smith2386c8b2013-02-22 09:06:26 +00001821 DS.takeAttributesFrom(Attrs);
Reid Klecknerd61a3112014-12-15 23:16:32 +00001822 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
John McCalld5a36322009-11-03 19:26:08 +00001823}
Mike Stump11289f42009-09-09 15:08:12 +00001824
Richard Smith09f76ee2011-10-19 21:33:05 +00001825/// Returns true if this might be the start of a declarator, or a common typo
1826/// for a declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001827bool Parser::MightBeDeclarator(DeclaratorContext Context) {
Richard Smith09f76ee2011-10-19 21:33:05 +00001828 switch (Tok.getKind()) {
1829 case tok::annot_cxxscope:
1830 case tok::annot_template_id:
1831 case tok::caret:
1832 case tok::code_completion:
1833 case tok::coloncolon:
1834 case tok::ellipsis:
1835 case tok::kw___attribute:
1836 case tok::kw_operator:
1837 case tok::l_paren:
1838 case tok::star:
1839 return true;
1840
1841 case tok::amp:
1842 case tok::ampamp:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001843 return getLangOpts().CPlusPlus;
Richard Smith09f76ee2011-10-19 21:33:05 +00001844
Richard Smithc8a79032012-01-09 22:31:44 +00001845 case tok::l_square: // Might be an attribute on an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001846 return Context == DeclaratorContext::MemberContext &&
1847 getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
Richard Smithc8a79032012-01-09 22:31:44 +00001848
1849 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001850 return Context == DeclaratorContext::MemberContext ||
1851 getLangOpts().CPlusPlus;
Richard Smithc8a79032012-01-09 22:31:44 +00001852
Richard Smith09f76ee2011-10-19 21:33:05 +00001853 case tok::identifier:
1854 switch (NextToken().getKind()) {
1855 case tok::code_completion:
1856 case tok::coloncolon:
1857 case tok::comma:
1858 case tok::equal:
1859 case tok::equalequal: // Might be a typo for '='.
1860 case tok::kw_alignas:
1861 case tok::kw_asm:
1862 case tok::kw___attribute:
1863 case tok::l_brace:
1864 case tok::l_paren:
1865 case tok::l_square:
1866 case tok::less:
1867 case tok::r_brace:
1868 case tok::r_paren:
1869 case tok::r_square:
1870 case tok::semi:
1871 return true;
1872
1873 case tok::colon:
1874 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
Richard Smithc8a79032012-01-09 22:31:44 +00001875 // and in block scope it's probably a label. Inside a class definition,
1876 // this is a bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001877 return Context == DeclaratorContext::MemberContext ||
1878 (getLangOpts().CPlusPlus &&
1879 Context == DeclaratorContext::FileContext);
Richard Smithc8a79032012-01-09 22:31:44 +00001880
1881 case tok::identifier: // Possible virt-specifier.
Richard Smith89645bc2013-01-02 12:01:23 +00001882 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
Richard Smith09f76ee2011-10-19 21:33:05 +00001883
1884 default:
1885 return false;
1886 }
1887
1888 default:
1889 return false;
1890 }
1891}
1892
Richard Smithb8caac82012-04-11 20:59:20 +00001893/// Skip until we reach something which seems like a sensible place to pick
1894/// up parsing after a malformed declaration. This will sometimes stop sooner
1895/// than SkipUntil(tok::r_brace) would, but will never stop later.
1896void Parser::SkipMalformedDecl() {
1897 while (true) {
1898 switch (Tok.getKind()) {
1899 case tok::l_brace:
1900 // Skip until matching }, then stop. We've probably skipped over
1901 // a malformed class or function definition or similar.
1902 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001903 SkipUntil(tok::r_brace);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001904 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
Richard Smithb8caac82012-04-11 20:59:20 +00001905 // This declaration isn't over yet. Keep skipping.
1906 continue;
1907 }
Alp Toker8fbec672013-12-17 23:29:36 +00001908 TryConsumeToken(tok::semi);
Richard Smithb8caac82012-04-11 20:59:20 +00001909 return;
1910
1911 case tok::l_square:
1912 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001913 SkipUntil(tok::r_square);
Richard Smithb8caac82012-04-11 20:59:20 +00001914 continue;
1915
1916 case tok::l_paren:
1917 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001918 SkipUntil(tok::r_paren);
Richard Smithb8caac82012-04-11 20:59:20 +00001919 continue;
1920
1921 case tok::r_brace:
1922 return;
1923
1924 case tok::semi:
1925 ConsumeToken();
1926 return;
1927
1928 case tok::kw_inline:
1929 // 'inline namespace' at the start of a line is almost certainly
Jordan Rose12e730c2012-07-09 16:54:53 +00001930 // a good place to pick back up parsing, except in an Objective-C
1931 // @interface context.
1932 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1933 (!ParsingInObjCContainer || CurParsedObjCImpl))
Richard Smithb8caac82012-04-11 20:59:20 +00001934 return;
1935 break;
1936
1937 case tok::kw_namespace:
1938 // 'namespace' at the start of a line is almost certainly a good
Jordan Rose12e730c2012-07-09 16:54:53 +00001939 // place to pick back up parsing, except in an Objective-C
1940 // @interface context.
1941 if (Tok.isAtStartOfLine() &&
1942 (!ParsingInObjCContainer || CurParsedObjCImpl))
1943 return;
1944 break;
1945
1946 case tok::at:
1947 // @end is very much like } in Objective-C contexts.
1948 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1949 ParsingInObjCContainer)
1950 return;
1951 break;
1952
1953 case tok::minus:
1954 case tok::plus:
1955 // - and + probably start new method declarations in Objective-C contexts.
1956 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
Richard Smithb8caac82012-04-11 20:59:20 +00001957 return;
1958 break;
1959
1960 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001961 case tok::annot_module_begin:
1962 case tok::annot_module_end:
1963 case tok::annot_module_include:
Richard Smithb8caac82012-04-11 20:59:20 +00001964 return;
1965
1966 default:
1967 break;
1968 }
1969
1970 ConsumeAnyToken();
1971 }
1972}
1973
John McCalld5a36322009-11-03 19:26:08 +00001974/// ParseDeclGroup - Having concluded that this is either a function
1975/// definition or a group of object declarations, actually parse the
1976/// result.
John McCall28a6aea2009-11-04 02:18:39 +00001977Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
Faisal Vali421b2d12017-12-29 05:41:00 +00001978 DeclaratorContext Context,
Richard Smith02e85f32011-04-14 22:09:26 +00001979 SourceLocation *DeclEnd,
1980 ForRangeInit *FRI) {
John McCalld5a36322009-11-03 19:26:08 +00001981 // Parse the first declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001982 ParsingDeclarator D(*this, DS, Context);
John McCalld5a36322009-11-03 19:26:08 +00001983 ParseDeclarator(D);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001984
John McCalld5a36322009-11-03 19:26:08 +00001985 // Bail out if the first declarator didn't seem well-formed.
1986 if (!D.hasName() && !D.mayOmitIdentifier()) {
Richard Smithb8caac82012-04-11 20:59:20 +00001987 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00001988 return nullptr;
Chris Lattnerefb0f112009-03-29 17:18:04 +00001989 }
Mike Stump11289f42009-09-09 15:08:12 +00001990
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001991 // Save late-parsed attributes for now; they need to be parsed in the
1992 // appropriate function scope after the function Decl has been constructed.
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001993 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1994 LateParsedAttrList LateParsedAttrs(true);
Richard Smith99c464c2014-11-10 21:10:32 +00001995 if (D.isFunctionDeclarator()) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001996 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1997
Richard Smith99c464c2014-11-10 21:10:32 +00001998 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1999 // attribute. If we find the keyword here, tell the user to put it
2000 // at the start instead.
2001 if (Tok.is(tok::kw__Noreturn)) {
2002 SourceLocation Loc = ConsumeToken();
2003 const char *PrevSpec;
2004 unsigned DiagID;
2005
2006 // We can offer a fixit if it's valid to mark this function as _Noreturn
2007 // and we don't have any other declarators in this declaration.
2008 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2009 MaybeParseGNUAttributes(D, &LateParsedAttrs);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002010 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
Richard Smith99c464c2014-11-10 21:10:32 +00002011
2012 Diag(Loc, diag::err_c11_noreturn_misplaced)
2013 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002014 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
Richard Smith99c464c2014-11-10 21:10:32 +00002015 : FixItHint());
2016 }
2017 }
2018
Chris Lattnerdbb1e932010-07-11 22:24:20 +00002019 // Check to see if we have a function *definition* which must have a body.
Douglas Gregor012efe22013-04-16 16:01:32 +00002020 if (D.isFunctionDeclarator() &&
Chris Lattnerdbb1e932010-07-11 22:24:20 +00002021 // Look at the next token to make sure that this isn't a function
2022 // declaration. We have to check this because __attribute__ might be the
2023 // start of a function definition in GCC-extended K&R C.
Fariborz Jahanian712bb812012-08-10 15:54:40 +00002024 !isDeclarationAfterDeclarator()) {
Chad Rosierc1183952012-06-26 22:30:43 +00002025
Reid Klecknerd61a3112014-12-15 23:16:32 +00002026 // Function definitions are only allowed at file scope and in C++ classes.
2027 // The C++ inline method definition case is handled elsewhere, so we only
2028 // need to handle the file scope definition case.
Faisal Vali421b2d12017-12-29 05:41:00 +00002029 if (Context == DeclaratorContext::FileContext) {
Douglas Gregor012efe22013-04-16 16:01:32 +00002030 if (isStartOfFunctionDefinition(D)) {
2031 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2032 Diag(Tok, diag::err_function_declared_typedef);
John McCalld5a36322009-11-03 19:26:08 +00002033
Douglas Gregor012efe22013-04-16 16:01:32 +00002034 // Recover by treating the 'typedef' as spurious.
2035 DS.ClearStorageClassSpecs();
2036 }
2037
2038 Decl *TheDecl =
2039 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
2040 return Actions.ConvertDeclToDeclGroup(TheDecl);
John McCalld5a36322009-11-03 19:26:08 +00002041 }
2042
Douglas Gregor012efe22013-04-16 16:01:32 +00002043 if (isDeclarationSpecifier()) {
Nico Weber6b05f382015-02-18 04:53:03 +00002044 // If there is an invalid declaration specifier right after the
2045 // function prototype, then we must be in a missing semicolon case
2046 // where this isn't actually a body. Just fall through into the code
2047 // that handles it as a prototype, and let the top-level code handle
2048 // the erroneous declspec where it would otherwise expect a comma or
2049 // semicolon.
Douglas Gregor012efe22013-04-16 16:01:32 +00002050 } else {
2051 Diag(Tok, diag::err_expected_fn_body);
2052 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002053 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00002054 }
John McCalld5a36322009-11-03 19:26:08 +00002055 } else {
Douglas Gregor012efe22013-04-16 16:01:32 +00002056 if (Tok.is(tok::l_brace)) {
2057 Diag(Tok, diag::err_function_definition_not_allowed);
Serge Pavlov1de51512013-12-09 05:25:47 +00002058 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00002059 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00002060 }
John McCalld5a36322009-11-03 19:26:08 +00002061 }
2062 }
2063
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002064 if (ParseAsmAttributesAfterDeclarator(D))
David Blaikie0403cb12016-01-15 23:43:25 +00002065 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00002066
2067 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2068 // must parse and analyze the for-range-initializer before the declaration is
2069 // analyzed.
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002070 //
2071 // Handle the Objective-C for-in loop variable similarly, although we
2072 // don't need to parse the container in advance.
2073 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2074 bool IsForRangeLoop = false;
Alp Toker8fbec672013-12-17 23:29:36 +00002075 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002076 IsForRangeLoop = true;
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002077 if (Tok.is(tok::l_brace))
2078 FRI->RangeExpr = ParseBraceInitializer();
2079 else
2080 FRI->RangeExpr = ParseExpression();
2081 }
2082
Richard Smith02e85f32011-04-14 22:09:26 +00002083 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
George Karpenkovec38cf72018-03-29 00:56:24 +00002084 if (IsForRangeLoop) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002085 Actions.ActOnCXXForRangeDecl(ThisDecl);
George Karpenkovec38cf72018-03-29 00:56:24 +00002086 } else {
2087 // Obj-C for loop
2088 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2089 VD->setObjCForDecl(true);
2090 }
Richard Smith02e85f32011-04-14 22:09:26 +00002091 Actions.FinalizeDeclaration(ThisDecl);
John McCallcf6e0c82012-01-27 01:29:43 +00002092 D.complete(ThisDecl);
Rafael Espindolaab417692013-07-09 12:05:01 +00002093 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
Richard Smith02e85f32011-04-14 22:09:26 +00002094 }
2095
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002096 SmallVector<Decl *, 8> DeclsInGroup;
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002097 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2098 D, ParsedTemplateInfo(), FRI);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002099 if (LateParsedAttrs.size() > 0)
2100 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
John McCall28a6aea2009-11-04 02:18:39 +00002101 D.complete(FirstDecl);
John McCall48871652010-08-21 09:40:31 +00002102 if (FirstDecl)
John McCalld5a36322009-11-03 19:26:08 +00002103 DeclsInGroup.push_back(FirstDecl);
2104
Faisal Vali421b2d12017-12-29 05:41:00 +00002105 bool ExpectSemi = Context != DeclaratorContext::ForContext;
Fangrui Song6907ce22018-07-30 19:24:48 +00002106
John McCalld5a36322009-11-03 19:26:08 +00002107 // If we don't have a comma, it is either the end of the list (a ';') or an
2108 // error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00002109 SourceLocation CommaLoc;
2110 while (TryConsumeToken(tok::comma, CommaLoc)) {
Richard Smith09f76ee2011-10-19 21:33:05 +00002111 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2112 // This comma was followed by a line-break and something which can't be
2113 // the start of a declarator. The comma was probably a typo for a
2114 // semicolon.
2115 Diag(CommaLoc, diag::err_expected_semi_declaration)
2116 << FixItHint::CreateReplacement(CommaLoc, ";");
2117 ExpectSemi = false;
2118 break;
2119 }
John McCalld5a36322009-11-03 19:26:08 +00002120
2121 // Parse the next declarator.
2122 D.clear();
Richard Smith8d06f422012-01-12 23:53:29 +00002123 D.setCommaLoc(CommaLoc);
John McCalld5a36322009-11-03 19:26:08 +00002124
2125 // Accept attributes in an init-declarator. In the first declarator in a
2126 // declaration, these would be part of the declspec. In subsequent
2127 // declarators, they become part of the declarator itself, so that they
2128 // don't apply to declarators after *this* one. Examples:
2129 // short __attribute__((common)) var; -> declspec
2130 // short var __attribute__((common)); -> declarator
2131 // short x, __attribute__((common)) var; -> declarator
John McCall53fa7142010-12-24 02:08:15 +00002132 MaybeParseGNUAttributes(D);
John McCalld5a36322009-11-03 19:26:08 +00002133
Nico Rieckeaaae272014-12-04 23:31:08 +00002134 // MSVC parses but ignores qualifiers after the comma as an extension.
2135 if (getLangOpts().MicrosoftExt)
2136 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2137
John McCalld5a36322009-11-03 19:26:08 +00002138 ParseDeclarator(D);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002139 if (!D.isInvalidType()) {
2140 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2141 D.complete(ThisDecl);
2142 if (ThisDecl)
Chad Rosierc1183952012-06-26 22:30:43 +00002143 DeclsInGroup.push_back(ThisDecl);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002144 }
John McCalld5a36322009-11-03 19:26:08 +00002145 }
2146
2147 if (DeclEnd)
2148 *DeclEnd = Tok.getLocation();
2149
Richard Smith09f76ee2011-10-19 21:33:05 +00002150 if (ExpectSemi &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002151 ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
Chris Lattner02f1b612012-04-28 16:12:17 +00002152 ? diag::err_invalid_token_after_toplevel_declarator
2153 : diag::err_expected_semi_declaration)) {
Chris Lattner13901342010-07-11 22:42:07 +00002154 // Okay, there was no semicolon and one was expected. If we see a
2155 // declaration specifier, just assume it was missing and continue parsing.
2156 // Otherwise things are very confused and we skip to recover.
2157 if (!isDeclarationSpecifier()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002158 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Alp Toker8fbec672013-12-17 23:29:36 +00002159 TryConsumeToken(tok::semi);
Chris Lattner13901342010-07-11 22:42:07 +00002160 }
John McCalld5a36322009-11-03 19:26:08 +00002161 }
2162
Rafael Espindolaab417692013-07-09 12:05:01 +00002163 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner53361ac2006-08-10 05:19:57 +00002164}
2165
Richard Smith02e85f32011-04-14 22:09:26 +00002166/// Parse an optional simple-asm-expr and attributes, and attach them to a
2167/// declarator. Returns true on an error.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002168bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
Richard Smith02e85f32011-04-14 22:09:26 +00002169 // If a simple-asm-expr is present, parse it.
2170 if (Tok.is(tok::kw_asm)) {
2171 SourceLocation Loc;
2172 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2173 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002174 SkipUntil(tok::semi, StopBeforeMatch);
Richard Smith02e85f32011-04-14 22:09:26 +00002175 return true;
2176 }
2177
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002178 D.setAsmLabel(AsmLabel.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002179 D.SetRangeEnd(Loc);
2180 }
2181
2182 MaybeParseGNUAttributes(D);
2183 return false;
2184}
2185
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002186/// Parse 'declaration' after parsing 'declaration-specifiers
Douglas Gregor23996282009-05-12 21:31:51 +00002187/// declarator'. This method parses the remainder of the declaration
2188/// (including any attributes or initializer, among other things) and
2189/// finalizes the declaration.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002190///
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002191/// init-declarator: [C99 6.7]
2192/// declarator
2193/// declarator '=' initializer
Chris Lattner6d7e6342006-08-15 03:41:14 +00002194/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2195/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002196/// [C++] declarator initializer[opt]
2197///
2198/// [C++] initializer:
2199/// [C++] '=' initializer-clause
2200/// [C++] '(' expression-list ')'
Sebastian Redlf769df52009-03-24 22:27:57 +00002201/// [C++0x] '=' 'default' [TODO]
2202/// [C++0x] '=' 'delete'
Sebastian Redl3da34892011-06-05 12:23:16 +00002203/// [C++0x] braced-init-list
Sebastian Redlf769df52009-03-24 22:27:57 +00002204///
2205/// According to the standard grammar, =default and =delete are function
2206/// definitions, but that definitely doesn't fit with the parser here.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002207///
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002208Decl *Parser::ParseDeclarationAfterDeclarator(
2209 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002210 if (ParseAsmAttributesAfterDeclarator(D))
Craig Topper161e4db2014-05-21 06:02:52 +00002211 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002212
Richard Smith02e85f32011-04-14 22:09:26 +00002213 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2214}
Mike Stump11289f42009-09-09 15:08:12 +00002215
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002216Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2217 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
Richard Smithc95d2c52017-09-22 04:25:05 +00002218 // RAII type used to track whether we're inside an initializer.
2219 struct InitializerScopeRAII {
2220 Parser &P;
2221 Declarator &D;
2222 Decl *ThisDecl;
2223
2224 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2225 : P(P), D(D), ThisDecl(ThisDecl) {
2226 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2227 Scope *S = nullptr;
2228 if (D.getCXXScopeSpec().isSet()) {
2229 P.EnterScope(0);
2230 S = P.getCurScope();
2231 }
2232 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2233 }
2234 }
2235 ~InitializerScopeRAII() { pop(); }
2236 void pop() {
2237 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2238 Scope *S = nullptr;
2239 if (D.getCXXScopeSpec().isSet())
2240 S = P.getCurScope();
2241 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2242 if (S)
2243 P.ExitScope();
2244 }
2245 ThisDecl = nullptr;
2246 }
2247 };
2248
Douglas Gregor23996282009-05-12 21:31:51 +00002249 // Inform the current actions module that we just parsed this declarator.
Craig Topper161e4db2014-05-21 06:02:52 +00002250 Decl *ThisDecl = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00002251 switch (TemplateInfo.Kind) {
2252 case ParsedTemplateInfo::NonTemplate:
Douglas Gregor0be31a22010-07-02 17:43:08 +00002253 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
Douglas Gregor450f00842009-09-25 18:43:00 +00002254 break;
Chad Rosierc1183952012-06-26 22:30:43 +00002255
Douglas Gregor450f00842009-09-25 18:43:00 +00002256 case ParsedTemplateInfo::Template:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002257 case ParsedTemplateInfo::ExplicitSpecialization: {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002258 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002259 *TemplateInfo.TemplateParams,
Douglas Gregor450f00842009-09-25 18:43:00 +00002260 D);
Larisse Voufo833b05a2013-08-06 07:33:00 +00002261 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002262 // Re-direct this decl to refer to the templated decl so that we can
2263 // initialize it.
2264 ThisDecl = VT->getTemplatedDecl();
2265 break;
2266 }
2267 case ParsedTemplateInfo::ExplicitInstantiation: {
2268 if (Tok.is(tok::semi)) {
2269 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2270 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2271 if (ThisRes.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002272 SkipUntil(tok::semi, StopBeforeMatch);
Craig Topper161e4db2014-05-21 06:02:52 +00002273 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002274 }
2275 ThisDecl = ThisRes.get();
2276 } else {
2277 // FIXME: This check should be for a variable template instantiation only.
2278
2279 // Check that this is a valid instantiation
Faisal Vali2ab8c152017-12-30 04:15:27 +00002280 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002281 // If the declarator-id is not a template-id, issue a diagnostic and
2282 // recover by ignoring the 'template' keyword.
2283 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2284 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2285 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2286 } else {
2287 SourceLocation LAngleLoc =
2288 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2289 Diag(D.getIdentifierLoc(),
2290 diag::err_explicit_instantiation_with_definition)
2291 << SourceRange(TemplateInfo.TemplateLoc)
2292 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2293
2294 // Recover as if it were an explicit specialization.
2295 TemplateParameterLists FakedParamLists;
2296 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00002297 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00002298 LAngleLoc, nullptr));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002299
2300 ThisDecl =
2301 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2302 }
2303 }
Douglas Gregor450f00842009-09-25 18:43:00 +00002304 break;
2305 }
2306 }
Mike Stump11289f42009-09-09 15:08:12 +00002307
Douglas Gregor23996282009-05-12 21:31:51 +00002308 // Parse declarator '=' initializer.
Richard Trieuc64d3232012-01-18 22:54:52 +00002309 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Trieu4972a6d2012-01-19 22:01:51 +00002310 if (isTokenEqualOrEqualTypo()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002311 SourceLocation EqualLoc = ConsumeToken();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002312
Anders Carlsson991285e2010-09-24 21:25:25 +00002313 if (Tok.is(tok::kw_delete)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002314 if (D.isFunctionDeclarator())
2315 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2316 << 1 /* delete */;
2317 else
2318 Diag(ConsumeToken(), diag::err_deleted_non_function);
Alexis Hunt5dafebc2011-05-06 01:42:00 +00002319 } else if (Tok.is(tok::kw_default)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002320 if (D.isFunctionDeclarator())
Sebastian Redl46afb552012-02-11 23:51:21 +00002321 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2322 << 0 /* default */;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002323 else
2324 Diag(ConsumeToken(), diag::err_default_special_members);
Douglas Gregor23996282009-05-12 21:31:51 +00002325 } else {
Richard Smithc95d2c52017-09-22 04:25:05 +00002326 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002327
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002328 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002329 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
Peter Collingbourne6b4fdc22012-07-27 12:56:09 +00002330 Actions.FinalizeDeclaration(ThisDecl);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002331 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +00002332 return nullptr;
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002333 }
Chad Rosierc1183952012-06-26 22:30:43 +00002334
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00002335 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2336 ExprResult Init = ParseInitializer();
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002337
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002338 // If this is the only decl in (possibly) range based for statement,
2339 // our best guess is that the user meant ':' instead of '='.
2340 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2341 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2342 << FixItHint::CreateReplacement(EqualLoc, ":");
2343 // We are trying to stop parser from looking for ';' in this for
2344 // statement, therefore preventing spurious errors to be issued.
2345 FRI->ColonLoc = EqualLoc;
2346 Init = ExprError();
2347 FRI->RangeExpr = Init;
2348 }
2349
Richard Smithc95d2c52017-09-22 04:25:05 +00002350 InitScope.pop();
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002351
Douglas Gregor23996282009-05-12 21:31:51 +00002352 if (Init.isInvalid()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002353 SmallVector<tok::TokenKind, 2> StopTokens;
2354 StopTokens.push_back(tok::comma);
Faisal Vali421b2d12017-12-29 05:41:00 +00002355 if (D.getContext() == DeclaratorContext::ForContext ||
2356 D.getContext() == DeclaratorContext::InitStmtContext)
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002357 StopTokens.push_back(tok::r_paren);
2358 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
Douglas Gregor604c3022010-03-01 18:27:54 +00002359 Actions.ActOnInitializerError(ThisDecl);
2360 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002361 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002362 /*DirectInit=*/false);
Douglas Gregor23996282009-05-12 21:31:51 +00002363 }
2364 } else if (Tok.is(tok::l_paren)) {
2365 // Parse C++ direct initializer: '(' expression-list ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002366 BalancedDelimiterTracker T(*this, tok::l_paren);
2367 T.consumeOpen();
2368
Benjamin Kramerf0623432012-08-23 22:51:59 +00002369 ExprVector Exprs;
Douglas Gregor23996282009-05-12 21:31:51 +00002370 CommaLocsTy CommaLocs;
2371
Richard Smithc95d2c52017-09-22 04:25:05 +00002372 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Douglas Gregor613bf102009-12-22 17:47:17 +00002373
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002374 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002375 auto RunSignatureHelp = [&]() {
Ilya Biryukov832c4af2018-09-07 14:04:39 +00002376 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002377 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
Ilya Biryukov2fab2352018-08-30 13:08:03 +00002378 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002379 CalledSignatureHelp = true;
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002380 return PreferredType;
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002381 };
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002382 auto SetPreferredType = [&] {
2383 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2384 };
2385
2386 llvm::function_ref<void()> ExpressionStarts;
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002387 if (ThisVarDecl) {
2388 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2389 // VarDecl. This is an error and it is reported in a call to
2390 // Actions.ActOnInitializerError(). However, we call
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002391 // ProduceConstructorSignatureHelp only on VarDecls.
2392 ExpressionStarts = SetPreferredType;
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002393 }
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002394 if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002395 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2396 Actions.ProduceConstructorSignatureHelp(
2397 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2398 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2399 CalledSignatureHelp = true;
2400 }
David Blaikieeae04112012-10-10 23:15:05 +00002401 Actions.ActOnInitializerError(ThisDecl);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002402 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor23996282009-05-12 21:31:51 +00002403 } else {
2404 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002405 T.consumeClose();
Douglas Gregor23996282009-05-12 21:31:51 +00002406
2407 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2408 "Unexpected number of commas!");
Douglas Gregor613bf102009-12-22 17:47:17 +00002409
Richard Smithc95d2c52017-09-22 04:25:05 +00002410 InitScope.pop();
Douglas Gregor613bf102009-12-22 17:47:17 +00002411
Sebastian Redla9351792012-02-11 23:51:47 +00002412 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2413 T.getCloseLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002414 Exprs);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002415 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002416 /*DirectInit=*/true);
Douglas Gregor23996282009-05-12 21:31:51 +00002417 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002418 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
Fariborz Jahanian8be1ecd2012-07-03 23:22:13 +00002419 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
Sebastian Redl3da34892011-06-05 12:23:16 +00002420 // Parse C++0x braced-init-list.
Richard Smith5d164bc2011-10-15 05:09:34 +00002421 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2422
Richard Smithc95d2c52017-09-22 04:25:05 +00002423 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Sebastian Redl3da34892011-06-05 12:23:16 +00002424
2425 ExprResult Init(ParseBraceInitializer());
2426
Richard Smithc95d2c52017-09-22 04:25:05 +00002427 InitScope.pop();
Sebastian Redl3da34892011-06-05 12:23:16 +00002428
2429 if (Init.isInvalid()) {
2430 Actions.ActOnInitializerError(ThisDecl);
2431 } else
Richard Smith3beb7c62017-01-12 02:27:38 +00002432 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
Sebastian Redl3da34892011-06-05 12:23:16 +00002433
Douglas Gregor23996282009-05-12 21:31:51 +00002434 } else {
Richard Smith3beb7c62017-01-12 02:27:38 +00002435 Actions.ActOnUninitializedDecl(ThisDecl);
Douglas Gregor23996282009-05-12 21:31:51 +00002436 }
2437
Richard Smithb2bc2e62011-02-21 20:05:19 +00002438 Actions.FinalizeDeclaration(ThisDecl);
2439
Douglas Gregor23996282009-05-12 21:31:51 +00002440 return ThisDecl;
2441}
2442
Chris Lattner1890ac82006-08-13 01:16:23 +00002443/// ParseSpecifierQualifierList
2444/// specifier-qualifier-list:
2445/// type-specifier specifier-qualifier-list[opt]
2446/// type-qualifier specifier-qualifier-list[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002447/// [GNU] attributes specifier-qualifier-list[opt]
Chris Lattner1890ac82006-08-13 01:16:23 +00002448///
Richard Smithc5b05522012-03-12 07:56:15 +00002449void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2450 DeclSpecContext DSC) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002451 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2452 /// parse declaration-specifiers and complain about extra stuff.
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002453 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
Faisal Valia534f072018-04-26 00:42:40 +00002454 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
Mike Stump11289f42009-09-09 15:08:12 +00002455
Chris Lattner1890ac82006-08-13 01:16:23 +00002456 // Validate declspec for type-name.
2457 unsigned Specs = DS.getParsedSpecifiers();
Richard Smith649c7b062014-01-08 00:56:48 +00002458 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
Richard Smithc5b05522012-03-12 07:56:15 +00002459 Diag(Tok, diag::err_expected_type);
2460 DS.SetTypeSpecError();
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00002461 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002462 Diag(Tok, diag::err_typename_requires_specqual);
Richard Smithc5b05522012-03-12 07:56:15 +00002463 if (!DS.hasTypeSpecifier())
2464 DS.SetTypeSpecError();
2465 }
Mike Stump11289f42009-09-09 15:08:12 +00002466
Chris Lattner1b22eed2006-11-28 05:12:07 +00002467 // Issue diagnostic and remove storage class if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002468 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
Chris Lattner1b22eed2006-11-28 05:12:07 +00002469 if (DS.getStorageClassSpecLoc().isValid())
2470 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2471 else
Richard Smithb4a9e862013-04-12 22:46:28 +00002472 Diag(DS.getThreadStorageClassSpecLoc(),
2473 diag::err_typename_invalid_storageclass);
Chris Lattnera925dc62006-11-28 04:33:46 +00002474 DS.ClearStorageClassSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002475 }
Mike Stump11289f42009-09-09 15:08:12 +00002476
Craig Topper3f13d4d22015-11-14 18:15:55 +00002477 // Issue diagnostic and remove function specifier if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002478 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
Douglas Gregor61956c42008-10-31 09:07:45 +00002479 if (DS.isInlineSpecified())
2480 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2481 if (DS.isVirtualSpecified())
2482 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00002483 if (DS.isExplicitSpecified())
Douglas Gregor61956c42008-10-31 09:07:45 +00002484 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
Chris Lattnera925dc62006-11-28 04:33:46 +00002485 DS.ClearFunctionSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002486 }
Richard Smithc5b05522012-03-12 07:56:15 +00002487
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00002488 // Issue diagnostic and remove constexpr specfier if present.
Faisal Vali7db85c52017-12-31 00:06:40 +00002489 if (DS.isConstexprSpecified() && DSC != DeclSpecContext::DSC_condition) {
Richard Smithc5b05522012-03-12 07:56:15 +00002490 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2491 DS.ClearConstexprSpec();
2492 }
Chris Lattner1890ac82006-08-13 01:16:23 +00002493}
Chris Lattner53361ac2006-08-10 05:19:57 +00002494
Chris Lattner6cc055a2009-04-12 20:42:31 +00002495/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2496/// specified token is valid after the identifier in a declarator which
2497/// immediately follows the declspec. For example, these things are valid:
2498///
2499/// int x [ 4]; // direct-declarator
2500/// int x ( int y); // direct-declarator
2501/// int(int x ) // direct-declarator
2502/// int x ; // simple-declaration
2503/// int x = 17; // init-declarator-list
2504/// int x , y; // init-declarator-list
2505/// int x __asm__ ("foo"); // init-declarator-list
Chris Lattnera723ba92009-04-14 21:16:09 +00002506/// int x : 4; // struct-declarator
Chris Lattner2b988c12009-04-12 22:29:43 +00002507/// int x { 5}; // C++'0x unified initializers
Chris Lattner6cc055a2009-04-12 20:42:31 +00002508///
2509/// This is not, because 'x' does not immediately follow the declspec (though
2510/// ')' happens to be valid anyway).
2511/// int (x)
2512///
2513static bool isValidAfterIdentifierInDeclarator(const Token &T) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002514 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2515 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2516 tok::colon);
Chris Lattner6cc055a2009-04-12 20:42:31 +00002517}
2518
Chris Lattner20a0c612009-04-14 21:34:55 +00002519/// ParseImplicitInt - This method is called when we have an non-typename
2520/// identifier in a declspec (which normally terminates the decl spec) when
2521/// the declspec has no type specifier. In this case, the declspec is either
2522/// malformed or is "implicit int" (in K&R and C89).
2523///
2524/// This method handles diagnosing this prettily and returns false if the
2525/// declspec is done being processed. If it recovers and thinks there may be
2526/// other pieces of declspec after it, it returns true.
2527///
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002528bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002529 const ParsedTemplateInfo &TemplateInfo,
Richard Smitha0a5d502014-05-08 22:32:00 +00002530 AccessSpecifier AS, DeclSpecContext DSC,
Michael Han9407e502012-11-26 22:54:45 +00002531 ParsedAttributesWithRange &Attrs) {
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002532 assert(Tok.is(tok::identifier) && "should have identifier");
Mike Stump11289f42009-09-09 15:08:12 +00002533
Chris Lattner20a0c612009-04-14 21:34:55 +00002534 SourceLocation Loc = Tok.getLocation();
2535 // If we see an identifier that is not a type name, we normally would
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002536 // parse it as the identifier being declared. However, when a typename
Chris Lattner20a0c612009-04-14 21:34:55 +00002537 // is typo'd or the definition is not included, this will incorrectly
2538 // parse the typename as the identifier name and fall over misparsing
2539 // later parts of the diagnostic.
2540 //
2541 // As such, we try to do some look-ahead in cases where this would
2542 // otherwise be an "implicit-int" case to see if this is invalid. For
2543 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2544 // an identifier with implicit int, we'd get a parse error because the
2545 // next token is obviously invalid for a type. Parse these as a case
2546 // with an invalid type specifier.
2547 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
Mike Stump11289f42009-09-09 15:08:12 +00002548
Chris Lattner20a0c612009-04-14 21:34:55 +00002549 // Since we know that this either implicit int (which is rare) or an
Richard Smitha952ebb2012-05-15 21:01:51 +00002550 // error, do lookahead to try to do better recovery. This never applies
2551 // within a type specifier. Outside of C++, we allow this even if the
2552 // language doesn't "officially" support implicit int -- we support
Richard Smith3b870382013-04-30 22:43:51 +00002553 // implicit int as an extension in C99 and C11.
Richard Smith649c7b062014-01-08 00:56:48 +00002554 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
Richard Smithc5b05522012-03-12 07:56:15 +00002555 isValidAfterIdentifierInDeclarator(NextToken())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002556 // If this token is valid for implicit int, e.g. "static x = 4", then
2557 // we just avoid eating the identifier, so it will be parsed as the
2558 // identifier in the declarator.
2559 return false;
2560 }
Mike Stump11289f42009-09-09 15:08:12 +00002561
Richard Smitha952ebb2012-05-15 21:01:51 +00002562 if (getLangOpts().CPlusPlus &&
2563 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2564 // Don't require a type specifier if we have the 'auto' storage class
2565 // specifier in C++98 -- we'll promote it to a type specifier.
Richard Smithfb8b7b92013-10-15 00:00:26 +00002566 if (SS)
2567 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
Richard Smitha952ebb2012-05-15 21:01:51 +00002568 return false;
2569 }
2570
Reid Kleckner9a96e422016-05-24 21:23:54 +00002571 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2572 getLangOpts().MSVCCompat) {
2573 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2574 // Give Sema a chance to recover if we are in a template with dependent base
2575 // classes.
2576 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2577 *Tok.getIdentifierInfo(), Tok.getLocation(),
Faisal Vali7db85c52017-12-31 00:06:40 +00002578 DSC == DeclSpecContext::DSC_template_type_arg)) {
Reid Kleckner9a96e422016-05-24 21:23:54 +00002579 const char *PrevSpec;
2580 unsigned DiagID;
2581 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2582 Actions.getASTContext().getPrintingPolicy());
2583 DS.SetRangeEnd(Tok.getLocation());
2584 ConsumeToken();
2585 return false;
2586 }
2587 }
2588
Chris Lattner20a0c612009-04-14 21:34:55 +00002589 // Otherwise, if we don't consume this token, we are going to emit an
2590 // error anyway. Try to recover from various common problems. Check
2591 // to see if this was a reference to a tag name without a tag specified.
2592 // This is a common problem in C (saying 'foo' instead of 'struct foo').
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002593 //
2594 // C++ doesn't need this, and isTagName doesn't take SS.
Craig Topper161e4db2014-05-21 06:02:52 +00002595 if (SS == nullptr) {
2596 const char *TagName = nullptr, *FixitTagName = nullptr;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002597 tok::TokenKind TagKind = tok::unknown;
Mike Stump11289f42009-09-09 15:08:12 +00002598
Douglas Gregor0be31a22010-07-02 17:43:08 +00002599 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002600 default: break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002601 case DeclSpec::TST_enum:
2602 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2603 case DeclSpec::TST_union:
2604 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2605 case DeclSpec::TST_struct:
2606 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
Joao Matosdc86f942012-08-31 18:45:21 +00002607 case DeclSpec::TST_interface:
2608 TagName="__interface"; FixitTagName = "__interface ";
2609 TagKind=tok::kw___interface;break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002610 case DeclSpec::TST_class:
2611 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
Chris Lattner20a0c612009-04-14 21:34:55 +00002612 }
Mike Stump11289f42009-09-09 15:08:12 +00002613
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002614 if (TagName) {
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002615 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2616 LookupResult R(Actions, TokenName, SourceLocation(),
2617 Sema::LookupOrdinaryName);
2618
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002619 Diag(Loc, diag::err_use_of_tag_name_without_tag)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002620 << TokenName << TagName << getLangOpts().CPlusPlus
2621 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2622
2623 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2624 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2625 I != IEnd; ++I)
Kaelyn Uhrain3fe3f852012-04-27 18:26:49 +00002626 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002627 << TokenName << TagName;
2628 }
Mike Stump11289f42009-09-09 15:08:12 +00002629
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002630 // Parse this as a tag as if the missing tag were present.
2631 if (TagKind == tok::kw_enum)
Faisal Vali7db85c52017-12-31 00:06:40 +00002632 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2633 DeclSpecContext::DSC_normal);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002634 else
Richard Smithc5b05522012-03-12 07:56:15 +00002635 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
Faisal Vali7db85c52017-12-31 00:06:40 +00002636 /*EnteringContext*/ false,
2637 DeclSpecContext::DSC_normal, Attrs);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002638 return true;
2639 }
Chris Lattner20a0c612009-04-14 21:34:55 +00002640 }
Mike Stump11289f42009-09-09 15:08:12 +00002641
Richard Smithfe904f02012-05-15 21:29:55 +00002642 // Determine whether this identifier could plausibly be the name of something
Richard Smithedd124e2012-05-15 21:42:17 +00002643 // being declared (with a missing type).
Faisal Vali7db85c52017-12-31 00:06:40 +00002644 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2645 DSC == DeclSpecContext::DSC_class)) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002646 // Look ahead to the next token to try to figure out what this declaration
2647 // was supposed to be.
2648 switch (NextToken().getKind()) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002649 case tok::l_paren: {
2650 // static x(4); // 'x' is not a type
2651 // x(int n); // 'x' is not a type
2652 // x (*p)[]; // 'x' is a type
2653 //
Richard Smitha0a5d502014-05-08 22:32:00 +00002654 // Since we're in an error case, we can afford to perform a tentative
2655 // parse to determine which case we're in.
Richard Smitha952ebb2012-05-15 21:01:51 +00002656 TentativeParsingAction PA(*this);
2657 ConsumeToken();
2658 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2659 PA.Revert();
Richard Smithfb8b7b92013-10-15 00:00:26 +00002660
Richard Smithee390432014-05-16 01:56:53 +00002661 if (TPR != TPResult::False) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002662 // The identifier is followed by a parenthesized declarator.
2663 // It's supposed to be a type.
2664 break;
2665 }
2666
2667 // If we're in a context where we could be declaring a constructor,
2668 // check whether this is a constructor declaration with a bogus name.
Faisal Vali7db85c52017-12-31 00:06:40 +00002669 if (DSC == DeclSpecContext::DSC_class ||
2670 (DSC == DeclSpecContext::DSC_top_level && SS)) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002671 IdentifierInfo *II = Tok.getIdentifierInfo();
2672 if (Actions.isCurrentClassNameTypo(II, SS)) {
2673 Diag(Loc, diag::err_constructor_bad_name)
2674 << Tok.getIdentifierInfo() << II
2675 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2676 Tok.setIdentifierInfo(II);
2677 }
2678 }
2679 // Fall through.
Galina Kistanova77674252017-06-01 21:15:34 +00002680 LLVM_FALLTHROUGH;
Richard Smitha952ebb2012-05-15 21:01:51 +00002681 }
Richard Smithfb8b7b92013-10-15 00:00:26 +00002682 case tok::comma:
2683 case tok::equal:
2684 case tok::kw_asm:
2685 case tok::l_brace:
2686 case tok::l_square:
2687 case tok::semi:
2688 // This looks like a variable or function declaration. The type is
2689 // probably missing. We're done parsing decl-specifiers.
Nicolas Lesseree057172019-05-05 12:15:17 +00002690 // But only if we are not in a function prototype scope.
2691 if (getCurScope()->isFunctionPrototypeScope())
2692 break;
Richard Smithfb8b7b92013-10-15 00:00:26 +00002693 if (SS)
2694 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2695 return false;
Richard Smitha952ebb2012-05-15 21:01:51 +00002696
2697 default:
2698 // This is probably supposed to be a type. This includes cases like:
2699 // int f(itn);
2700 // struct S { unsinged : 4; };
2701 break;
2702 }
2703 }
2704
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002705 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2706 // and attempt to recover.
John McCallba7bf592010-08-24 05:47:05 +00002707 ParsedType T;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +00002708 IdentifierInfo *II = Tok.getIdentifierInfo();
Richard Smith52f8d192017-05-10 21:32:16 +00002709 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002710 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
Richard Smith52f8d192017-05-10 21:32:16 +00002711 IsTemplateName);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002712 if (T) {
2713 // The action has suggested that the type T could be used. Set that as
2714 // the type in the declaration specifiers, consume the would-be type
2715 // name token, and we're done.
2716 const char *PrevSpec;
2717 unsigned DiagID;
2718 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2719 Actions.getASTContext().getPrintingPolicy());
2720 DS.SetRangeEnd(Tok.getLocation());
2721 ConsumeToken();
2722 // There may be other declaration specifiers after this.
2723 return true;
2724 } else if (II != Tok.getIdentifierInfo()) {
2725 // If no type was suggested, the correction is to a keyword
2726 Tok.setKind(II->getTokenID());
2727 // There may be other declaration specifiers after this.
2728 return true;
Douglas Gregor15e56022009-10-13 23:27:22 +00002729 }
Mike Stump11289f42009-09-09 15:08:12 +00002730
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002731 // Otherwise, the action had no suggestion for us. Mark this as an error.
Richard Smithc5b05522012-03-12 07:56:15 +00002732 DS.SetTypeSpecError();
Chris Lattner20a0c612009-04-14 21:34:55 +00002733 DS.SetRangeEnd(Tok.getLocation());
2734 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002735
Richard Smith52f8d192017-05-10 21:32:16 +00002736 // Eat any following template arguments.
2737 if (IsTemplateName) {
2738 SourceLocation LAngle, RAngle;
2739 TemplateArgList Args;
2740 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2741 }
2742
Chris Lattner20a0c612009-04-14 21:34:55 +00002743 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2744 // avoid rippling error messages on subsequent uses of the same type,
2745 // could be useful if #include was forgotten.
Richard Smithb3065792019-05-07 07:36:07 +00002746 return true;
Chris Lattner20a0c612009-04-14 21:34:55 +00002747}
2748
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002749/// Determine the declaration specifier context from the declarator
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002750/// context.
2751///
2752/// \param Context the declarator context, which is one of the
Faisal Vali421b2d12017-12-29 05:41:00 +00002753/// DeclaratorContext enumerator values.
Chad Rosierc1183952012-06-26 22:30:43 +00002754Parser::DeclSpecContext
Faisal Vali421b2d12017-12-29 05:41:00 +00002755Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2756 if (Context == DeclaratorContext::MemberContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002757 return DeclSpecContext::DSC_class;
Faisal Vali421b2d12017-12-29 05:41:00 +00002758 if (Context == DeclaratorContext::FileContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002759 return DeclSpecContext::DSC_top_level;
Faisal Vali421b2d12017-12-29 05:41:00 +00002760 if (Context == DeclaratorContext::TemplateParamContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002761 return DeclSpecContext::DSC_template_param;
Richard Smith77a9c602018-02-28 03:02:23 +00002762 if (Context == DeclaratorContext::TemplateArgContext ||
2763 Context == DeclaratorContext::TemplateTypeArgContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002764 return DeclSpecContext::DSC_template_type_arg;
Richard Smithe303e352018-02-02 22:24:54 +00002765 if (Context == DeclaratorContext::TrailingReturnContext ||
2766 Context == DeclaratorContext::TrailingReturnVarContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002767 return DeclSpecContext::DSC_trailing;
Faisal Vali421b2d12017-12-29 05:41:00 +00002768 if (Context == DeclaratorContext::AliasDeclContext ||
2769 Context == DeclaratorContext::AliasTemplateContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002770 return DeclSpecContext::DSC_alias_declaration;
2771 return DeclSpecContext::DSC_normal;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002772}
2773
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002774/// ParseAlignArgument - Parse the argument to an alignment-specifier.
2775///
2776/// FIXME: Simply returns an alignof() expression if the argument is a
2777/// type. Ideally, the type should be propagated directly into Sema.
2778///
Benjamin Kramere56f3932011-12-23 17:00:35 +00002779/// [C11] type-id
2780/// [C11] constant-expression
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002781/// [C++0x] type-id ...[opt]
2782/// [C++0x] assignment-expression ...[opt]
2783ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2784 SourceLocation &EllipsisLoc) {
2785 ExprResult ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002786 if (isTypeIdInParens()) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002787 SourceLocation TypeLoc = Tok.getLocation();
2788 ParsedType Ty = ParseTypeName().get();
2789 SourceRange TypeRange(Start, Tok.getLocation());
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002790 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2791 Ty.getAsOpaquePtr(), TypeRange);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002792 } else
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002793 ER = ParseConstantExpression();
2794
Alp Toker8fbec672013-12-17 23:29:36 +00002795 if (getLangOpts().CPlusPlus11)
2796 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002797
2798 return ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002799}
2800
2801/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2802/// attribute to Attrs.
2803///
2804/// alignment-specifier:
Benjamin Kramere56f3932011-12-23 17:00:35 +00002805/// [C11] '_Alignas' '(' type-id ')'
2806/// [C11] '_Alignas' '(' constant-expression ')'
Richard Smithd11c7a12013-01-29 01:48:07 +00002807/// [C++11] 'alignas' '(' type-id ...[opt] ')'
2808/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002809void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
Richard Smith44c247f2013-02-22 08:32:16 +00002810 SourceLocation *EndLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002811 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002812 "Not an alignment-specifier!");
2813
Richard Smithd11c7a12013-01-29 01:48:07 +00002814 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2815 SourceLocation KWLoc = ConsumeToken();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002816
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002817 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002818 if (T.expectAndConsume())
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002819 return;
2820
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002821 SourceLocation EllipsisLoc;
2822 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002823 if (ArgExpr.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002824 T.skipToEnd();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002825 return;
2826 }
2827
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002828 T.consumeClose();
Richard Smith44c247f2013-02-22 08:32:16 +00002829 if (EndLoc)
2830 *EndLoc = T.getCloseLocation();
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002831
Aaron Ballman00e99962013-08-31 01:11:41 +00002832 ArgsVector ArgExprs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002833 ArgExprs.push_back(ArgExpr.get());
Craig Topper161e4db2014-05-21 06:02:52 +00002834 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
Erich Keanee891aa92018-07-13 15:07:47 +00002835 ParsedAttr::AS_Keyword, EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002836}
2837
Richard Smith404dfb42013-11-19 22:47:36 +00002838/// Determine whether we're looking at something that might be a declarator
2839/// in a simple-declaration. If it can't possibly be a declarator, maybe
2840/// diagnose a missing semicolon after a prior tag definition in the decl
2841/// specifier.
2842///
2843/// \return \c true if an error occurred and this can't be any kind of
2844/// declaration.
2845bool
2846Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2847 DeclSpecContext DSContext,
2848 LateParsedAttrList *LateAttrs) {
2849 assert(DS.hasTagDefinition() && "shouldn't call this");
2850
Faisal Vali7db85c52017-12-31 00:06:40 +00002851 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2852 DSContext == DeclSpecContext::DSC_top_level);
Richard Smith404dfb42013-11-19 22:47:36 +00002853
2854 if (getLangOpts().CPlusPlus &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002855 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2856 tok::annot_template_id) &&
Richard Smith404dfb42013-11-19 22:47:36 +00002857 TryAnnotateCXXScopeToken(EnteringContext)) {
2858 SkipMalformedDecl();
2859 return true;
2860 }
2861
Richard Smith698875a2013-11-20 23:40:57 +00002862 bool HasScope = Tok.is(tok::annot_cxxscope);
2863 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2864 Token AfterScope = HasScope ? NextToken() : Tok;
2865
Richard Smith404dfb42013-11-19 22:47:36 +00002866 // Determine whether the following tokens could possibly be a
2867 // declarator.
Richard Smith698875a2013-11-20 23:40:57 +00002868 bool MightBeDeclarator = true;
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002869 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
Richard Smith698875a2013-11-20 23:40:57 +00002870 // A declarator-id can't start with 'typename'.
2871 MightBeDeclarator = false;
2872 } else if (AfterScope.is(tok::annot_template_id)) {
2873 // If we have a type expressed as a template-id, this cannot be a
2874 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2875 TemplateIdAnnotation *Annot =
2876 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2877 if (Annot->Kind == TNK_Type_template)
2878 MightBeDeclarator = false;
2879 } else if (AfterScope.is(tok::identifier)) {
2880 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2881
Richard Smith404dfb42013-11-19 22:47:36 +00002882 // These tokens cannot come after the declarator-id in a
2883 // simple-declaration, and are likely to come after a type-specifier.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002884 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2885 tok::annot_cxxscope, tok::coloncolon)) {
Richard Smith698875a2013-11-20 23:40:57 +00002886 // Missing a semicolon.
2887 MightBeDeclarator = false;
2888 } else if (HasScope) {
2889 // If the declarator-id has a scope specifier, it must redeclare a
2890 // previously-declared entity. If that's a type (and this is not a
2891 // typedef), that's an error.
2892 CXXScopeSpec SS;
2893 Actions.RestoreNestedNameSpecifierAnnotation(
2894 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2895 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2896 Sema::NameClassification Classification = Actions.ClassifyName(
2897 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
Bruno Ricci70ad3962019-03-25 17:08:51 +00002898 /*IsAddressOfOperand=*/false, /*CCC=*/nullptr);
Richard Smith698875a2013-11-20 23:40:57 +00002899 switch (Classification.getKind()) {
2900 case Sema::NC_Error:
2901 SkipMalformedDecl();
2902 return true;
Richard Smith404dfb42013-11-19 22:47:36 +00002903
Richard Smith698875a2013-11-20 23:40:57 +00002904 case Sema::NC_Keyword:
2905 case Sema::NC_NestedNameSpecifier:
2906 llvm_unreachable("typo correction and nested name specifiers not "
2907 "possible here");
Richard Smith404dfb42013-11-19 22:47:36 +00002908
Richard Smith698875a2013-11-20 23:40:57 +00002909 case Sema::NC_Type:
2910 case Sema::NC_TypeTemplate:
2911 // Not a previously-declared non-type entity.
2912 MightBeDeclarator = false;
2913 break;
Richard Smith404dfb42013-11-19 22:47:36 +00002914
Richard Smith698875a2013-11-20 23:40:57 +00002915 case Sema::NC_Unknown:
2916 case Sema::NC_Expression:
2917 case Sema::NC_VarTemplate:
2918 case Sema::NC_FunctionTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00002919 case Sema::NC_UndeclaredTemplate:
Richard Smith698875a2013-11-20 23:40:57 +00002920 // Might be a redeclaration of a prior entity.
2921 break;
2922 }
Richard Smith404dfb42013-11-19 22:47:36 +00002923 }
Richard Smith404dfb42013-11-19 22:47:36 +00002924 }
2925
Richard Smith698875a2013-11-20 23:40:57 +00002926 if (MightBeDeclarator)
Richard Smith404dfb42013-11-19 22:47:36 +00002927 return false;
2928
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002929 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002930 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
Alp Toker383d2c42014-01-01 03:08:43 +00002931 diag::err_expected_after)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002932 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
Richard Smith404dfb42013-11-19 22:47:36 +00002933
2934 // Try to recover from the typo, by dropping the tag definition and parsing
2935 // the problematic tokens as a type.
2936 //
2937 // FIXME: Split the DeclSpec into pieces for the standalone
2938 // declaration and pieces for the following declaration, instead
2939 // of assuming that all the other pieces attach to new declaration,
2940 // and call ParsedFreeStandingDeclSpec as appropriate.
2941 DS.ClearTypeSpecType();
2942 ParsedTemplateInfo NotATemplate;
Faisal Valia534f072018-04-26 00:42:40 +00002943 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
Richard Smith404dfb42013-11-19 22:47:36 +00002944 return false;
2945}
2946
Leonard Chanab80f3c2018-06-14 14:53:51 +00002947// Choose the apprpriate diagnostic error for why fixed point types are
2948// disabled, set the previous specifier, and mark as invalid.
2949static void SetupFixedPointError(const LangOptions &LangOpts,
2950 const char *&PrevSpec, unsigned &DiagID,
2951 bool &isInvalid) {
2952 assert(!LangOpts.FixedPoint);
2953 DiagID = diag::err_fixed_point_not_enabled;
2954 PrevSpec = ""; // Not used by diagnostic
2955 isInvalid = true;
2956}
2957
Faisal Valia534f072018-04-26 00:42:40 +00002958/// ParseDeclarationSpecifiers
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002959/// declaration-specifiers: [C99 6.7]
Chris Lattner3b561a32006-08-13 00:12:11 +00002960/// storage-class-specifier declaration-specifiers[opt]
2961/// type-specifier declaration-specifiers[opt]
Chris Lattner3b561a32006-08-13 00:12:11 +00002962/// [C99] function-specifier declaration-specifiers[opt]
Benjamin Kramere56f3932011-12-23 17:00:35 +00002963/// [C11] alignment-specifier declaration-specifiers[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002964/// [GNU] attributes declaration-specifiers[opt]
Douglas Gregor26701a42011-09-09 02:06:17 +00002965/// [Clang] '__module_private__' declaration-specifiers[opt]
Douglas Gregorab209d82015-07-07 03:58:42 +00002966/// [ObjC1] '__kindof' declaration-specifiers[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002967///
Chris Lattnerf63f89a2006-08-05 03:28:50 +00002968/// storage-class-specifier: [C99 6.7.1]
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002969/// 'typedef'
2970/// 'extern'
2971/// 'static'
2972/// 'auto'
2973/// 'register'
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002974/// [C++] 'mutable'
Richard Smithb4a9e862013-04-12 22:46:28 +00002975/// [C++11] 'thread_local'
2976/// [C11] '_Thread_local'
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002977/// [GNU] '__thread'
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002978/// function-specifier: [C99 6.7.4]
Chris Lattner3b561a32006-08-13 00:12:11 +00002979/// [C99] 'inline'
Douglas Gregor61956c42008-10-31 09:07:45 +00002980/// [C++] 'virtual'
2981/// [C++] 'explicit'
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00002982/// [OpenCL] '__kernel'
Anders Carlssoncd8db412009-05-06 04:46:28 +00002983/// 'friend': [C++ dcl.friend]
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00002984/// 'constexpr': [C++0x dcl.constexpr]
Faisal Valia534f072018-04-26 00:42:40 +00002985void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002986 const ParsedTemplateInfo &TemplateInfo,
John McCall07e91c02009-08-06 02:15:43 +00002987 AccessSpecifier AS,
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002988 DeclSpecContext DSContext,
2989 LateParsedAttrList *LateAttrs) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002990 if (DS.getSourceRange().isInvalid()) {
David Majnemer24b28302014-07-26 05:41:31 +00002991 // Start the range at the current token but make the end of the range
2992 // invalid. This will make the entire range invalid unless we successfully
2993 // consume a token.
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002994 DS.SetRangeStart(Tok.getLocation());
David Majnemer24b28302014-07-26 05:41:31 +00002995 DS.SetRangeEnd(SourceLocation());
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002996 }
Chad Rosierc1183952012-06-26 22:30:43 +00002997
Faisal Vali7db85c52017-12-31 00:06:40 +00002998 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2999 DSContext == DeclSpecContext::DSC_top_level);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003000 bool AttrsLastTime = false;
3001 ParsedAttributesWithRange attrs(AttrFactory);
Benjamin Kramere4812142015-03-12 14:28:38 +00003002 // We use Sema's policy to get bool macros right.
Richard Smith301bc212016-05-19 01:39:10 +00003003 PrintingPolicy Policy = Actions.getPrintingPolicy();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003004 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00003005 bool isInvalid = false;
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003006 bool isStorageClass = false;
Craig Topper161e4db2014-05-21 06:02:52 +00003007 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00003008 unsigned DiagID = 0;
3009
David Majnemer51fd8a02015-07-22 23:46:18 +00003010 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3011 // implementation for VS2013 uses _Atomic as an identifier for one of the
3012 // classes in <atomic>.
3013 //
3014 // A typedef declaration containing _Atomic<...> is among the places where
3015 // the class is used. If we are currently parsing such a declaration, treat
3016 // the token as an identifier.
3017 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3018 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
3019 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3020 Tok.setKind(tok::identifier);
3021
Chris Lattner4d8f8732006-11-28 05:05:08 +00003022 SourceLocation Loc = Tok.getLocation();
Douglas Gregor450c75a2008-11-07 15:42:26 +00003023
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003024 switch (Tok.getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00003025 default:
Chris Lattner0974b232008-07-26 00:20:22 +00003026 DoneWithDeclSpec:
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003027 if (!AttrsLastTime)
3028 ProhibitAttributes(attrs);
Michael Han64536a62012-11-06 19:34:54 +00003029 else {
3030 // Reject C++11 attributes that appertain to decl specifiers as
3031 // we don't support any C++11 attributes that appertain to decl
3032 // specifiers. This also conforms to what g++ 4.8 is doing.
Richard Smith49cc1cc2016-08-18 21:59:42 +00003033 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
Michael Han64536a62012-11-06 19:34:54 +00003034
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003035 DS.takeAttributesFrom(attrs);
Michael Han64536a62012-11-06 19:34:54 +00003036 }
Peter Collingbourne70188b32011-09-29 18:03:57 +00003037
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003038 // If this is not a declaration specifier token, we're done reading decl
3039 // specifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00003040 DS.Finish(Actions, Policy);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003041 return;
Mike Stump11289f42009-09-09 15:08:12 +00003042
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003043 case tok::l_square:
3044 case tok::kw_alignas:
Aaron Ballman606093a2017-10-15 15:01:42 +00003045 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003046 goto DoneWithDeclSpec;
3047
3048 ProhibitAttributes(attrs);
3049 // FIXME: It would be good to recover by accepting the attributes,
3050 // but attempting to do that now would cause serious
3051 // madness in terms of diagnostics.
3052 attrs.clear();
3053 attrs.Range = SourceRange();
3054
3055 ParseCXX11Attributes(attrs);
3056 AttrsLastTime = true;
Chad Rosierc1183952012-06-26 22:30:43 +00003057 continue;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003058
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003059 case tok::code_completion: {
John McCallfaf5fb42010-08-26 23:41:50 +00003060 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003061 if (DS.hasTypeSpecifier()) {
3062 bool AllowNonIdentifiers
3063 = (getCurScope()->getFlags() & (Scope::ControlScope |
3064 Scope::BlockScope |
3065 Scope::TemplateParamScope |
3066 Scope::FunctionPrototypeScope |
3067 Scope::AtCatchScope)) == 0;
3068 bool AllowNestedNameSpecifiers
Faisal Vali7db85c52017-12-31 00:06:40 +00003069 = DSContext == DeclSpecContext::DSC_top_level ||
3070 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003071
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003072 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
Chad Rosierc1183952012-06-26 22:30:43 +00003073 AllowNonIdentifiers,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003074 AllowNestedNameSpecifiers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003075 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00003076 }
3077
Douglas Gregor80039242011-02-15 20:33:25 +00003078 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3079 CCC = Sema::PCC_LocalDeclarationSpecifiers;
3080 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
Faisal Vali7db85c52017-12-31 00:06:40 +00003081 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3082 : Sema::PCC_Template;
3083 else if (DSContext == DeclSpecContext::DSC_class)
John McCallfaf5fb42010-08-26 23:41:50 +00003084 CCC = Sema::PCC_Class;
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +00003085 else if (CurParsedObjCImpl)
John McCallfaf5fb42010-08-26 23:41:50 +00003086 CCC = Sema::PCC_ObjCImplementation;
Chad Rosierc1183952012-06-26 22:30:43 +00003087
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003088 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003089 return cutOffParsing();
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003090 }
3091
Chris Lattnerbd31aa32009-01-05 00:07:25 +00003092 case tok::coloncolon: // ::foo::bar
John McCall1f476a12010-02-26 08:45:28 +00003093 // C++ scope specifier. Annotate and loop, or bail out on error.
Eli Friedman2a1d9a92013-08-15 23:59:20 +00003094 if (TryAnnotateCXXScopeToken(EnteringContext)) {
John McCall1f476a12010-02-26 08:45:28 +00003095 if (!DS.hasTypeSpecifier())
3096 DS.SetTypeSpecError();
3097 goto DoneWithDeclSpec;
3098 }
John McCall8bc2a702010-03-01 18:20:46 +00003099 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3100 goto DoneWithDeclSpec;
John McCall1f476a12010-02-26 08:45:28 +00003101 continue;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003102
3103 case tok::annot_cxxscope: {
Richard Smith3092a3b2012-05-09 18:56:43 +00003104 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003105 goto DoneWithDeclSpec;
3106
John McCall9dab4e62009-12-12 11:40:51 +00003107 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00003108 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3109 Tok.getAnnotationRange(),
3110 SS);
John McCall9dab4e62009-12-12 11:40:51 +00003111
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003112 // We are looking for a qualified typename.
Douglas Gregor167fa622009-03-25 15:40:00 +00003113 Token Next = NextToken();
Mike Stump11289f42009-09-09 15:08:12 +00003114 if (Next.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003115 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
Douglas Gregorb67535d2009-03-31 00:43:58 +00003116 ->Kind == TNK_Type_template) {
Douglas Gregor167fa622009-03-25 15:40:00 +00003117 // We have a qualified template-id, e.g., N::A<int>
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003118
Richard Smith74f02342017-01-19 21:00:13 +00003119 // If this would be a valid constructor declaration with template
3120 // arguments, we will reject the attempt to form an invalid type-id
3121 // referring to the injected-class-name when we annotate the token,
3122 // per C++ [class.qual]p2.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003123 //
Richard Smith74f02342017-01-19 21:00:13 +00003124 // To improve diagnostics for this case, parse the declaration as a
3125 // constructor (and reject the extra template arguments later).
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003126 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
Faisal Vali7db85c52017-12-31 00:06:40 +00003127 if ((DSContext == DeclSpecContext::DSC_top_level ||
3128 DSContext == DeclSpecContext::DSC_class) &&
John McCall84821e72010-04-13 06:39:49 +00003129 TemplateId->Name &&
Richard Smith74f02342017-01-19 21:00:13 +00003130 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003131 isConstructorDeclarator(/*Unqualified*/ false)) {
Richard Smith74f02342017-01-19 21:00:13 +00003132 // The user meant this to be an out-of-line constructor
3133 // definition, but template arguments are not allowed
3134 // there. Just allow this as a constructor; we'll
3135 // complain about it later.
3136 goto DoneWithDeclSpec;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003137 }
3138
John McCall9dab4e62009-12-12 11:40:51 +00003139 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003140 ConsumeAnnotationToken(); // The C++ scope.
Mike Stump11289f42009-09-09 15:08:12 +00003141 assert(Tok.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003142 "ParseOptionalCXXScopeSpecifier not working");
Douglas Gregore7c20652011-03-02 00:47:37 +00003143 AnnotateTemplateIdTokenAsType();
Douglas Gregor167fa622009-03-25 15:40:00 +00003144 continue;
3145 }
3146
Douglas Gregorc5790df2009-09-28 07:26:33 +00003147 if (Next.is(tok::annot_typename)) {
John McCall9dab4e62009-12-12 11:40:51 +00003148 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003149 ConsumeAnnotationToken(); // The C++ scope.
John McCallba7bf592010-08-24 05:47:05 +00003150 if (Tok.getAnnotationValue()) {
3151 ParsedType T = getTypeAnnotation(Tok);
Nico Weber77430342010-11-22 10:30:56 +00003152 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
Chad Rosierc1183952012-06-26 22:30:43 +00003153 Tok.getAnnotationEndLoc(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003154 PrevSpec, DiagID, T, Policy);
Richard Smithda837032012-09-14 18:27:01 +00003155 if (isInvalid)
3156 break;
John McCallba7bf592010-08-24 05:47:05 +00003157 }
Douglas Gregorc5790df2009-09-28 07:26:33 +00003158 else
3159 DS.SetTypeSpecError();
3160 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003161 ConsumeAnnotationToken(); // The typename
Douglas Gregorc5790df2009-09-28 07:26:33 +00003162 }
3163
Douglas Gregor167fa622009-03-25 15:40:00 +00003164 if (Next.isNot(tok::identifier))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003165 goto DoneWithDeclSpec;
3166
Richard Smith74f02342017-01-19 21:00:13 +00003167 // Check whether this is a constructor declaration. If we're in a
3168 // context where the identifier could be a class name, and it has the
3169 // shape of a constructor declaration, process it as one.
Faisal Vali7db85c52017-12-31 00:06:40 +00003170 if ((DSContext == DeclSpecContext::DSC_top_level ||
3171 DSContext == DeclSpecContext::DSC_class) &&
Chad Rosierc1183952012-06-26 22:30:43 +00003172 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
Richard Smith74f02342017-01-19 21:00:13 +00003173 &SS) &&
3174 isConstructorDeclarator(/*Unqualified*/ false))
3175 goto DoneWithDeclSpec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003176
David Blaikieefdccaa2016-01-15 23:43:34 +00003177 ParsedType TypeRep =
3178 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3179 getCurScope(), &SS, false, false, nullptr,
3180 /*IsCtorOrDtorName=*/false,
Richard Smith600b5262017-01-26 20:40:47 +00003181 /*WantNonTrivialSourceInfo=*/true,
3182 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003183
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003184 // If the referenced identifier is not a type, then this declspec is
3185 // erroneous: We already checked about that it has no type specifier, and
3186 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
Mike Stump11289f42009-09-09 15:08:12 +00003187 // typename.
David Blaikie7d170102013-05-15 07:37:26 +00003188 if (!TypeRep) {
Richard Smithaf3b3252017-05-18 19:21:48 +00003189 // Eat the scope spec so the identifier is current.
3190 ConsumeAnnotationToken();
Michael Han9407e502012-11-26 22:54:45 +00003191 ParsedAttributesWithRange Attrs(AttrFactory);
3192 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3193 if (!Attrs.empty()) {
3194 AttrsLastTime = true;
3195 attrs.takeAllFrom(Attrs);
3196 }
3197 continue;
3198 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003199 goto DoneWithDeclSpec;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003200 }
Mike Stump11289f42009-09-09 15:08:12 +00003201
John McCall9dab4e62009-12-12 11:40:51 +00003202 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003203 ConsumeAnnotationToken(); // The C++ scope.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003204
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003205 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003206 DiagID, TypeRep, Policy);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003207 if (isInvalid)
3208 break;
Mike Stump11289f42009-09-09 15:08:12 +00003209
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003210 DS.SetRangeEnd(Tok.getLocation());
3211 ConsumeToken(); // The typename.
3212
3213 continue;
3214 }
Mike Stump11289f42009-09-09 15:08:12 +00003215
Chris Lattnere387d9e2009-01-21 19:48:37 +00003216 case tok::annot_typename: {
Richard Smith404dfb42013-11-19 22:47:36 +00003217 // If we've previously seen a tag definition, we were almost surely
3218 // missing a semicolon after it.
3219 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3220 goto DoneWithDeclSpec;
3221
John McCallba7bf592010-08-24 05:47:05 +00003222 if (Tok.getAnnotationValue()) {
3223 ParsedType T = getTypeAnnotation(Tok);
Nico Weber7f8bb362010-11-22 12:50:03 +00003224 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003225 DiagID, T, Policy);
John McCallba7bf592010-08-24 05:47:05 +00003226 } else
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003227 DS.SetTypeSpecError();
Chad Rosierc1183952012-06-26 22:30:43 +00003228
Chris Lattner005fc1b2010-04-05 18:18:31 +00003229 if (isInvalid)
3230 break;
3231
Chris Lattnere387d9e2009-01-21 19:48:37 +00003232 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003233 ConsumeAnnotationToken(); // The typename
Mike Stump11289f42009-09-09 15:08:12 +00003234
Chris Lattnere387d9e2009-01-21 19:48:37 +00003235 continue;
3236 }
Mike Stump11289f42009-09-09 15:08:12 +00003237
Douglas Gregor06873092011-04-28 15:48:45 +00003238 case tok::kw___is_signed:
3239 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3240 // typically treats it as a trait. If we see __is_signed as it appears
3241 // in libstdc++, e.g.,
3242 //
3243 // static const bool __is_signed;
3244 //
3245 // then treat __is_signed as an identifier rather than as a keyword.
Faisal Vali090da2d2018-01-01 18:23:28 +00003246 if (DS.getTypeSpecType() == TST_bool &&
Douglas Gregor06873092011-04-28 15:48:45 +00003247 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
Alp Toker47642d22013-12-03 06:13:01 +00003248 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3249 TryKeywordIdentFallback(true);
Douglas Gregor06873092011-04-28 15:48:45 +00003250
3251 // We're done with the declaration-specifiers.
3252 goto DoneWithDeclSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00003253
Chris Lattner16fac4f2008-07-26 01:18:38 +00003254 // typedef-name
Nikola Smiljanic67860242014-09-26 00:28:20 +00003255 case tok::kw___super:
David Blaikie15a430a2011-12-04 05:04:18 +00003256 case tok::kw_decltype:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003257 case tok::identifier: {
Reid Klecknerc582f012014-07-14 18:19:58 +00003258 // This identifier can only be a typedef name if we haven't already seen
3259 // a type-specifier. Without this check we misparse:
3260 // typedef int X; struct Y { short X; }; as 'short int'.
3261 if (DS.hasTypeSpecifier())
3262 goto DoneWithDeclSpec;
3263
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003264 // If the token is an identifier named "__declspec" and Microsoft
3265 // extensions are not enabled, it is likely that there will be cascading
3266 // parse errors if this really is a __declspec attribute. Attempt to
3267 // recognize that scenario and recover gracefully.
3268 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3269 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3270 Diag(Loc, diag::err_ms_attributes_not_enabled);
3271
3272 // The next token should be an open paren. If it is, eat the entire
3273 // attribute declaration and continue.
3274 if (NextToken().is(tok::l_paren)) {
3275 // Consume the __declspec identifier.
Richard Trieuba057372017-02-14 23:56:55 +00003276 ConsumeToken();
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003277
3278 // Eat the parens and everything between them.
3279 BalancedDelimiterTracker T(*this, tok::l_paren);
3280 if (T.consumeOpen()) {
3281 assert(false && "Not a left paren?");
3282 return;
3283 }
3284 T.skipToEnd();
3285 continue;
3286 }
3287 }
3288
Serge Pavlov458ea762014-07-16 05:16:52 +00003289 // In C++, check to see if this is a scope specifier like foo::bar::, if
3290 // so handle it as such. This is important for ctor parsing.
3291 if (getLangOpts().CPlusPlus) {
3292 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3293 DS.SetTypeSpecError();
3294 goto DoneWithDeclSpec;
3295 }
3296 if (!Tok.is(tok::identifier))
3297 continue;
3298 }
3299
John Thompson22334602010-02-05 00:12:22 +00003300 // Check for need to substitute AltiVec keyword tokens.
3301 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3302 break;
3303
Richard Smith3092a3b2012-05-09 18:56:43 +00003304 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3305 // allow the use of a typedef name as a type specifier.
3306 if (DS.isTypeAltiVecVector())
3307 goto DoneWithDeclSpec;
3308
Faisal Vali7db85c52017-12-31 00:06:40 +00003309 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3310 isObjCInstancetype()) {
Douglas Gregor5c0870a2015-06-19 23:18:00 +00003311 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3312 assert(TypeRep);
3313 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3314 DiagID, TypeRep, Policy);
3315 if (isInvalid)
3316 break;
3317
3318 DS.SetRangeEnd(Loc);
3319 ConsumeToken();
3320 continue;
3321 }
3322
Richard Smith715ee072018-06-20 21:58:20 +00003323 // If we're in a context where the identifier could be a class name,
3324 // check whether this is a constructor declaration.
3325 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3326 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3327 isConstructorDeclarator(/*Unqualified*/true))
3328 goto DoneWithDeclSpec;
3329
Richard Smith600b5262017-01-26 20:40:47 +00003330 ParsedType TypeRep = Actions.getTypeName(
3331 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3332 false, false, nullptr, false, false,
3333 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003334
Chris Lattner6cc055a2009-04-12 20:42:31 +00003335 // If this is not a typedef name, don't parse it as part of the declspec,
3336 // it must be an implicit int or an error.
John McCallba7bf592010-08-24 05:47:05 +00003337 if (!TypeRep) {
Michael Han9407e502012-11-26 22:54:45 +00003338 ParsedAttributesWithRange Attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +00003339 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
Michael Han9407e502012-11-26 22:54:45 +00003340 if (!Attrs.empty()) {
3341 AttrsLastTime = true;
3342 attrs.takeAllFrom(Attrs);
3343 }
3344 continue;
3345 }
Chris Lattner16fac4f2008-07-26 01:18:38 +00003346 goto DoneWithDeclSpec;
Chris Lattner6cc055a2009-04-12 20:42:31 +00003347 }
Douglas Gregor8bf42052009-02-09 18:46:07 +00003348
Richard Smith35845152017-02-07 01:37:30 +00003349 // Likewise, if this is a context where the identifier could be a template
3350 // name, check whether this is a deduction guide declaration.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003351 if (getLangOpts().CPlusPlus17 &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003352 (DSContext == DeclSpecContext::DSC_class ||
3353 DSContext == DeclSpecContext::DSC_top_level) &&
Richard Smith35845152017-02-07 01:37:30 +00003354 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3355 Tok.getLocation()) &&
3356 isConstructorDeclarator(/*Unqualified*/ true,
3357 /*DeductionGuide*/ true))
3358 goto DoneWithDeclSpec;
3359
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003360 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003361 DiagID, TypeRep, Policy);
Chris Lattner16fac4f2008-07-26 01:18:38 +00003362 if (isInvalid)
3363 break;
Mike Stump11289f42009-09-09 15:08:12 +00003364
Chris Lattner16fac4f2008-07-26 01:18:38 +00003365 DS.SetRangeEnd(Tok.getLocation());
3366 ConsumeToken(); // The identifier
3367
Douglas Gregore9d95f12015-07-07 03:57:35 +00003368 // Objective-C supports type arguments and protocol references
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003369 // following an Objective-C object or object pointer
3370 // type. Handle either one of them.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003371 if (Tok.is(tok::less) && getLangOpts().ObjC) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003372 SourceLocation NewEndLoc;
3373 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3374 Loc, TypeRep, /*consumeLastToken=*/true,
3375 NewEndLoc);
3376 if (NewTypeRep.isUsable()) {
3377 DS.UpdateTypeRep(NewTypeRep.get());
3378 DS.SetRangeEnd(NewEndLoc);
3379 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00003380 }
Chad Rosierc1183952012-06-26 22:30:43 +00003381
Steve Naroffcd5e7822008-09-22 10:28:57 +00003382 // Need to support trailing type qualifiers (e.g. "id<p> const").
3383 // If a type specifier follows, it will be diagnosed elsewhere.
3384 continue;
Chris Lattner16fac4f2008-07-26 01:18:38 +00003385 }
Douglas Gregor7f741122009-02-25 19:37:18 +00003386
3387 // type-name
3388 case tok::annot_template_id: {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003389 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithb23c5e82019-05-09 03:31:27 +00003390 if (TemplateId->Kind != TNK_Type_template &&
3391 TemplateId->Kind != TNK_Undeclared_template) {
Douglas Gregor7f741122009-02-25 19:37:18 +00003392 // This template-id does not refer to a type name, so we're
3393 // done with the type-specifiers.
3394 goto DoneWithDeclSpec;
3395 }
3396
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003397 // If we're in a context where the template-id could be a
3398 // constructor name or specialization, check whether this is a
3399 // constructor declaration.
Faisal Vali7db85c52017-12-31 00:06:40 +00003400 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00003401 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
Richard Smith446161b2014-03-03 21:12:53 +00003402 isConstructorDeclarator(TemplateId->SS.isEmpty()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003403 goto DoneWithDeclSpec;
3404
Douglas Gregor7f741122009-02-25 19:37:18 +00003405 // Turn the template-id annotation token into a type annotation
3406 // token, then try again to parse it as a type-specifier.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003407 AnnotateTemplateIdTokenAsType();
Douglas Gregor7f741122009-02-25 19:37:18 +00003408 continue;
3409 }
3410
Chris Lattnere37e2332006-08-15 04:50:22 +00003411 // GNU attributes support.
3412 case tok::kw___attribute:
Craig Topper161e4db2014-05-21 06:02:52 +00003413 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
Chris Lattnerb95cca02006-10-17 03:01:08 +00003414 continue;
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003415
3416 // Microsoft declspec support.
3417 case tok::kw___declspec:
Aaron Ballman068aa512015-05-20 20:58:33 +00003418 ParseMicrosoftDeclSpecs(DS.getAttributes());
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003419 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003420
Steve Naroff44ac7772008-12-25 14:16:32 +00003421 // Microsoft single token adornments.
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003422 case tok::kw___forceinline: {
Serge Pavlov750db652013-11-13 06:57:53 +00003423 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003424 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Richard Smithda837032012-09-14 18:27:01 +00003425 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00003426 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00003427 nullptr, 0, ParsedAttr::AS_Keyword);
Richard Smithda837032012-09-14 18:27:01 +00003428 break;
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003429 }
Eli Friedman53339e02009-06-08 23:27:34 +00003430
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003431 case tok::kw___unaligned:
3432 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3433 getLangOpts());
3434 break;
3435
Aaron Ballman317a77f2013-05-22 23:25:32 +00003436 case tok::kw___sptr:
3437 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00003438 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00003439 case tok::kw___ptr32:
Steve Narofff9c29d42008-12-25 14:41:26 +00003440 case tok::kw___w64:
Steve Naroff44ac7772008-12-25 14:16:32 +00003441 case tok::kw___cdecl:
3442 case tok::kw___stdcall:
3443 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00003444 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00003445 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00003446 case tok::kw___vectorcall:
John McCall53fa7142010-12-24 02:08:15 +00003447 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00003448 continue;
3449
Dawn Perchik335e16b2010-09-03 01:29:35 +00003450 // Borland single token adornments.
3451 case tok::kw___pascal:
John McCall53fa7142010-12-24 02:08:15 +00003452 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00003453 continue;
3454
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003455 // OpenCL single token adornments.
3456 case tok::kw___kernel:
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +00003457 ParseOpenCLKernelAttributes(DS.getAttributes());
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003458 continue;
3459
Douglas Gregor261a89b2015-06-19 17:51:05 +00003460 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00003461 case tok::kw__Nonnull:
3462 case tok::kw__Nullable:
3463 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00003464 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3465 continue;
3466
Douglas Gregorab209d82015-07-07 03:58:42 +00003467 // Objective-C 'kindof' types.
3468 case tok::kw___kindof:
3469 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00003470 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00003471 (void)ConsumeToken();
3472 continue;
3473
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003474 // storage-class-specifier
3475 case tok::kw_typedef:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003476 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003477 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003478 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003479 break;
3480 case tok::kw_extern:
Richard Smithb4a9e862013-04-12 22:46:28 +00003481 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003482 Diag(Tok, diag::ext_thread_before) << "extern";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003483 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003484 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003485 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003486 break;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003487 case tok::kw___private_extern__:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003488 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003489 Loc, PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003490 isStorageClass = true;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003491 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003492 case tok::kw_static:
Richard Smithb4a9e862013-04-12 22:46:28 +00003493 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003494 Diag(Tok, diag::ext_thread_before) << "static";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003495 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003496 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003497 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003498 break;
3499 case tok::kw_auto:
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003500 if (getLangOpts().CPlusPlus11) {
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003501 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003502 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003503 PrevSpec, DiagID, Policy);
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003504 if (!isInvalid)
Richard Smith58c74332011-09-04 19:54:14 +00003505 Diag(Tok, diag::ext_auto_storage_class)
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003506 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith58c74332011-09-04 19:54:14 +00003507 } else
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003508 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003509 DiagID, Policy);
Richard Smith58c74332011-09-04 19:54:14 +00003510 } else
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003511 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003512 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003513 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003514 break;
Richard Smithe301ba22015-11-11 02:02:15 +00003515 case tok::kw___auto_type:
3516 Diag(Tok, diag::ext_auto_type);
3517 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3518 DiagID, Policy);
3519 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003520 case tok::kw_register:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003521 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003522 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003523 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003524 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003525 case tok::kw_mutable:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003526 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003527 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003528 isStorageClass = true;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003529 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003530 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00003531 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3532 PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003533 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003534 break;
3535 case tok::kw_thread_local:
3536 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3537 PrevSpec, DiagID);
Sven van Haastregtc4100832018-04-24 14:47:29 +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,
3542 Loc, PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003543 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003544 break;
Mike Stump11289f42009-09-09 15:08:12 +00003545
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003546 // function-specifier
3547 case tok::kw_inline:
Serge Pavlov750db652013-11-13 06:57:53 +00003548 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003549 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003550 case tok::kw_virtual:
Sven van Haastregt49ffffb2018-04-23 11:23:47 +00003551 // OpenCL C++ v1.0 s2.9: the virtual function qualifier is not supported.
3552 if (getLangOpts().OpenCLCPlusPlus) {
3553 DiagID = diag::err_openclcxx_virtual_function;
3554 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3555 isInvalid = true;
3556 }
3557 else {
3558 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3559 }
Douglas Gregor61956c42008-10-31 09:07:45 +00003560 break;
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00003561 case tok::kw_explicit:
3562 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
Douglas Gregor61956c42008-10-31 09:07:45 +00003563 break;
Richard Smith0015f092013-01-17 22:16:11 +00003564 case tok::kw__Noreturn:
3565 if (!getLangOpts().C11)
3566 Diag(Loc, diag::ext_c11_noreturn);
Serge Pavlov750db652013-11-13 06:57:53 +00003567 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
Richard Smith0015f092013-01-17 22:16:11 +00003568 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003569
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003570 // alignment-specifier
3571 case tok::kw__Alignas:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003572 if (!getLangOpts().C11)
Jordan Rose58d54722012-06-30 21:33:57 +00003573 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003574 ParseAlignmentSpecifier(DS.getAttributes());
3575 continue;
3576
Anders Carlssoncd8db412009-05-06 04:46:28 +00003577 // friend
3578 case tok::kw_friend:
Faisal Vali7db85c52017-12-31 00:06:40 +00003579 if (DSContext == DeclSpecContext::DSC_class)
John McCall07e91c02009-08-06 02:15:43 +00003580 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3581 else {
3582 PrevSpec = ""; // not actually used by the diagnostic
3583 DiagID = diag::err_friend_invalid_in_context;
3584 isInvalid = true;
3585 }
Anders Carlssoncd8db412009-05-06 04:46:28 +00003586 break;
Mike Stump11289f42009-09-09 15:08:12 +00003587
Douglas Gregor26701a42011-09-09 02:06:17 +00003588 // Modules
3589 case tok::kw___module_private__:
3590 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3591 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003592
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00003593 // constexpr
3594 case tok::kw_constexpr:
3595 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3596 break;
3597
Chris Lattnere387d9e2009-01-21 19:48:37 +00003598 // type-specifier
3599 case tok::kw_short:
John McCall49bfce42009-08-03 20:12:06 +00003600 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003601 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003602 break;
3603 case tok::kw_long:
3604 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
John McCall49bfce42009-08-03 20:12:06 +00003605 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003606 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003607 else
John McCall49bfce42009-08-03 20:12:06 +00003608 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003609 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003610 break;
Francois Pichet84133e42011-04-28 01:59:37 +00003611 case tok::kw___int64:
3612 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003613 DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00003614 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003615 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00003616 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3617 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003618 break;
3619 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00003620 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3621 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003622 break;
3623 case tok::kw__Complex:
John McCall49bfce42009-08-03 20:12:06 +00003624 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3625 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003626 break;
3627 case tok::kw__Imaginary:
John McCall49bfce42009-08-03 20:12:06 +00003628 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3629 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003630 break;
3631 case tok::kw_void:
John McCall49bfce42009-08-03 20:12:06 +00003632 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003633 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003634 break;
3635 case tok::kw_char:
John McCall49bfce42009-08-03 20:12:06 +00003636 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003637 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003638 break;
3639 case tok::kw_int:
John McCall49bfce42009-08-03 20:12:06 +00003640 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003641 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003642 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00003643 case tok::kw___int128:
3644 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003645 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003646 break;
3647 case tok::kw_half:
3648 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003649 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003650 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003651 case tok::kw_float:
John McCall49bfce42009-08-03 20:12:06 +00003652 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003653 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003654 break;
3655 case tok::kw_double:
John McCall49bfce42009-08-03 20:12:06 +00003656 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003657 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003658 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00003659 case tok::kw__Float16:
3660 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3661 DiagID, Policy);
3662 break;
Leonard Chanf921d852018-06-04 16:07:52 +00003663 case tok::kw__Accum:
3664 if (!getLangOpts().FixedPoint) {
Leonard Chanab80f3c2018-06-14 14:53:51 +00003665 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
Leonard Chanf921d852018-06-04 16:07:52 +00003666 } else {
3667 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3668 DiagID, Policy);
3669 }
3670 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00003671 case tok::kw__Fract:
3672 if (!getLangOpts().FixedPoint) {
3673 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3674 } else {
3675 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3676 DiagID, Policy);
3677 }
3678 break;
3679 case tok::kw__Sat:
3680 if (!getLangOpts().FixedPoint) {
3681 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3682 } else {
3683 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3684 }
3685 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003686 case tok::kw___float128:
3687 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3688 DiagID, Policy);
3689 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003690 case tok::kw_wchar_t:
John McCall49bfce42009-08-03 20:12:06 +00003691 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003692 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003693 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00003694 case tok::kw_char8_t:
3695 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3696 DiagID, Policy);
3697 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003698 case tok::kw_char16_t:
John McCall49bfce42009-08-03 20:12:06 +00003699 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003700 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003701 break;
3702 case tok::kw_char32_t:
John McCall49bfce42009-08-03 20:12:06 +00003703 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003704 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003705 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003706 case tok::kw_bool:
3707 case tok::kw__Bool:
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003708 if (Tok.is(tok::kw_bool) &&
3709 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3710 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3711 PrevSpec = ""; // Not used by the diagnostic.
3712 DiagID = diag::err_bool_redeclaration;
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003713 // For better error recovery.
3714 Tok.setKind(tok::identifier);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003715 isInvalid = true;
3716 } else {
3717 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003718 DiagID, Policy);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003719 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003720 break;
3721 case tok::kw__Decimal32:
John McCall49bfce42009-08-03 20:12:06 +00003722 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003723 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003724 break;
3725 case tok::kw__Decimal64:
John McCall49bfce42009-08-03 20:12:06 +00003726 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003727 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003728 break;
3729 case tok::kw__Decimal128:
John McCall49bfce42009-08-03 20:12:06 +00003730 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003731 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003732 break;
John Thompson22334602010-02-05 00:12:22 +00003733 case tok::kw___vector:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003734 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003735 break;
3736 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003737 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003738 break;
Bill Seurercf2c96b2015-01-12 19:35:51 +00003739 case tok::kw___bool:
3740 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3741 break;
Xiuli Pan9c14e282016-01-09 12:53:17 +00003742 case tok::kw_pipe:
3743 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3744 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3745 // support the "pipe" word as identifier.
3746 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3747 goto DoneWithDeclSpec;
3748 }
3749 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3750 break;
Alexey Bader954ba212016-04-08 13:40:33 +00003751#define GENERIC_IMAGE_TYPE(ImgType, Id) \
3752 case tok::kw_##ImgType##_t: \
3753 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3754 DiagID, Policy); \
3755 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00003756#include "clang/Basic/OpenCLImageTypes.def"
John McCall39439732011-04-09 22:50:59 +00003757 case tok::kw___unknown_anytype:
Faisal Vali090da2d2018-01-01 18:23:28 +00003758 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003759 PrevSpec, DiagID, Policy);
John McCall39439732011-04-09 22:50:59 +00003760 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003761
3762 // class-specifier:
3763 case tok::kw_class:
3764 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00003765 case tok::kw___interface:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003766 case tok::kw_union: {
3767 tok::TokenKind Kind = Tok.getKind();
3768 ConsumeToken();
Michael Han9407e502012-11-26 22:54:45 +00003769
3770 // These are attributes following class specifiers.
3771 // To produce better diagnostic, we parse them when
3772 // parsing class specifier.
Bill Wendling44426052012-12-20 19:22:21 +00003773 ParsedAttributesWithRange Attributes(AttrFactory);
Richard Smithc5b05522012-03-12 07:56:15 +00003774 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
Bill Wendling44426052012-12-20 19:22:21 +00003775 EnteringContext, DSContext, Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003776
3777 // If there are attributes following class specifier,
3778 // take them over and handle them here.
Bill Wendling44426052012-12-20 19:22:21 +00003779 if (!Attributes.empty()) {
Michael Han9407e502012-11-26 22:54:45 +00003780 AttrsLastTime = true;
Bill Wendling44426052012-12-20 19:22:21 +00003781 attrs.takeAllFrom(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003782 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003783 continue;
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003784 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003785
3786 // enum-specifier:
3787 case tok::kw_enum:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003788 ConsumeToken();
Richard Smithc5b05522012-03-12 07:56:15 +00003789 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003790 continue;
Faisal Valia534f072018-04-26 00:42:40 +00003791
Chris Lattnere387d9e2009-01-21 19:48:37 +00003792 // cv-qualifier:
3793 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00003794 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003795 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003796 break;
3797 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00003798 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003799 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003800 break;
3801 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00003802 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003803 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003804 break;
3805
Douglas Gregor333489b2009-03-27 23:10:48 +00003806 // C++ typename-specifier:
3807 case tok::kw_typename:
John McCall1f476a12010-02-26 08:45:28 +00003808 if (TryAnnotateTypeOrScopeToken()) {
3809 DS.SetTypeSpecError();
3810 goto DoneWithDeclSpec;
3811 }
3812 if (!Tok.is(tok::kw_typename))
Douglas Gregor333489b2009-03-27 23:10:48 +00003813 continue;
3814 break;
3815
Chris Lattnere387d9e2009-01-21 19:48:37 +00003816 // GNU typeof support.
3817 case tok::kw_typeof:
3818 ParseTypeofSpecifier(DS);
3819 continue;
3820
David Blaikie15a430a2011-12-04 05:04:18 +00003821 case tok::annot_decltype:
Anders Carlsson74948d02009-06-24 17:47:40 +00003822 ParseDecltypeSpecifier(DS);
3823 continue;
3824
David Majnemer15b311c2016-06-14 03:20:28 +00003825 case tok::annot_pragma_pack:
3826 HandlePragmaPack();
3827 continue;
3828
3829 case tok::annot_pragma_ms_pragma:
3830 HandlePragmaMSPragma();
3831 continue;
3832
3833 case tok::annot_pragma_ms_vtordisp:
3834 HandlePragmaMSVtorDisp();
3835 continue;
3836
3837 case tok::annot_pragma_ms_pointers_to_members:
3838 HandlePragmaMSPointersToMembers();
3839 continue;
3840
Alexis Hunt4a257072011-05-19 05:37:45 +00003841 case tok::kw___underlying_type:
3842 ParseUnderlyingTypeSpecifier(DS);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003843 continue;
3844
3845 case tok::kw__Atomic:
Richard Smith8e1ac332013-03-28 01:55:44 +00003846 // C11 6.7.2.4/4:
3847 // If the _Atomic keyword is immediately followed by a left parenthesis,
3848 // it is interpreted as a type specifier (with a type name), not as a
3849 // type qualifier.
3850 if (NextToken().is(tok::l_paren)) {
3851 ParseAtomicSpecifier(DS);
3852 continue;
3853 }
3854 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3855 getLangOpts());
3856 break;
Alexis Hunt4a257072011-05-19 05:37:45 +00003857
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003858 // OpenCL address space qualifiers:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003859 case tok::kw___generic:
3860 // generic address space is introduced only in OpenCL v2.0
3861 // see OpenCL C Spec v2.0 s6.5.5
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003862 if (Actions.getLangOpts().OpenCLVersion < 200 &&
3863 !Actions.getLangOpts().OpenCLCPlusPlus) {
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003864 DiagID = diag::err_opencl_unknown_type_specifier;
3865 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3866 isInvalid = true;
3867 break;
3868 };
Galina Kistanova77674252017-06-01 21:15:34 +00003869 LLVM_FALLTHROUGH;
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003870 case tok::kw_private:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003871 case tok::kw___private:
3872 case tok::kw___global:
3873 case tok::kw___local:
3874 case tok::kw___constant:
Anastasia Stulova2c4730d2019-02-15 12:07:57 +00003875 // OpenCL access qualifiers:
3876 case tok::kw___read_only:
3877 case tok::kw___write_only:
3878 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00003879 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003880 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003881
Steve Naroffcfdf6162008-06-05 00:02:44 +00003882 case tok::less:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003883 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
Chris Lattner0974b232008-07-26 00:20:22 +00003884 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3885 // but we support it.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003886 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
Chris Lattner0974b232008-07-26 00:20:22 +00003887 goto DoneWithDeclSpec;
Mike Stump11289f42009-09-09 15:08:12 +00003888
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003889 SourceLocation StartLoc = Tok.getLocation();
3890 SourceLocation EndLoc;
3891 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3892 if (Type.isUsable()) {
3893 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3894 PrevSpec, DiagID, Type.get(),
3895 Actions.getASTContext().getPrintingPolicy()))
3896 Diag(StartLoc, DiagID) << PrevSpec;
Fangrui Song6907ce22018-07-30 19:24:48 +00003897
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003898 DS.SetRangeEnd(EndLoc);
3899 } else {
3900 DS.SetTypeSpecError();
3901 }
Chad Rosierc1183952012-06-26 22:30:43 +00003902
Douglas Gregor06e41ae2010-10-21 23:17:00 +00003903 // Need to support trailing type qualifiers (e.g. "id<p> const").
3904 // If a type specifier follows, it will be diagnosed elsewhere.
3905 continue;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003906 }
John McCall49bfce42009-08-03 20:12:06 +00003907 // If the specifier wasn't legal, issue a diagnostic.
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003908 if (isInvalid) {
3909 assert(PrevSpec && "Method did not return previous specifier!");
John McCall49bfce42009-08-03 20:12:06 +00003910 assert(DiagID);
Chad Rosierc1183952012-06-26 22:30:43 +00003911
Nick Desaulniers150ca532018-10-03 23:09:29 +00003912 if (DiagID == diag::ext_duplicate_declspec ||
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00003913 DiagID == diag::ext_warn_duplicate_declspec)
3914 Diag(Tok, DiagID)
3915 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003916 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00003917 Diag(Tok, DiagID) << getLangOpts().OpenCLCPlusPlus
3918 << getLangOpts().getOpenCLVersionTuple().getAsString()
3919 << PrevSpec << isStorageClass;
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003920 } else
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00003921 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003922 }
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003923
Hans Wennborgd2b9fc82019-05-06 09:51:10 +00003924 DS.SetRangeEnd(Tok.getLocation());
3925 if (DiagID != diag::err_bool_redeclaration)
Volodymyr Sapsai9f7b5cc2018-04-10 18:29:47 +00003926 // After an error the next token can be an annotation token.
3927 ConsumeAnyToken();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003928
3929 AttrsLastTime = false;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003930 }
3931}
Douglas Gregoreb31f392008-12-01 23:54:00 +00003932
Chris Lattner70ae4912007-10-29 04:42:53 +00003933/// ParseStructDeclaration - Parse a struct declaration without the terminating
3934/// semicolon.
3935///
Nico Weber98dd0852019-03-14 14:18:56 +00003936/// Note that a struct declaration refers to a declaration in a struct,
3937/// not to the declaration of a struct.
3938///
Chris Lattner90a26b02007-01-23 04:38:16 +00003939/// struct-declaration:
Aaron Ballman606093a2017-10-15 15:01:42 +00003940/// [C2x] attributes-specifier-seq[opt]
3941/// specifier-qualifier-list struct-declarator-list
Chris Lattner736ed5d2007-06-09 05:59:07 +00003942/// [GNU] __extension__ struct-declaration
Chris Lattner70ae4912007-10-29 04:42:53 +00003943/// [GNU] specifier-qualifier-list
Chris Lattner90a26b02007-01-23 04:38:16 +00003944/// struct-declarator-list:
3945/// struct-declarator
3946/// struct-declarator-list ',' struct-declarator
3947/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3948/// struct-declarator:
3949/// declarator
3950/// [GNU] declarator attributes[opt]
3951/// declarator[opt] ':' constant-expression
3952/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3953///
Benjamin Kramera39beb92014-09-03 11:06:10 +00003954void Parser::ParseStructDeclaration(
3955 ParsingDeclSpec &DS,
3956 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
Chad Rosierc1183952012-06-26 22:30:43 +00003957
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003958 if (Tok.is(tok::kw___extension__)) {
3959 // __extension__ silences extension warnings in the subexpression.
3960 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Steve Naroff97170802007-08-20 22:28:22 +00003961 ConsumeToken();
Benjamin Kramera39beb92014-09-03 11:06:10 +00003962 return ParseStructDeclaration(DS, FieldsCallback);
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003963 }
Mike Stump11289f42009-09-09 15:08:12 +00003964
Aaron Ballman606093a2017-10-15 15:01:42 +00003965 // Parse leading attributes.
3966 ParsedAttributesWithRange Attrs(AttrFactory);
3967 MaybeParseCXX11Attributes(Attrs);
3968 DS.takeAttributesFrom(Attrs);
3969
Steve Naroff97170802007-08-20 22:28:22 +00003970 // Parse the common specifier-qualifiers-list piece.
Steve Naroff97170802007-08-20 22:28:22 +00003971 ParseSpecifierQualifierList(DS);
Mike Stump11289f42009-09-09 15:08:12 +00003972
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003973 // If there are no declarators, this is a free-standing declaration
3974 // specifier. Let the actions module cope with it.
Chris Lattner76c72282007-10-09 17:33:22 +00003975 if (Tok.is(tok::semi)) {
Nico Weber7b837f52016-01-28 19:25:00 +00003976 RecordDecl *AnonRecord = nullptr;
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003977 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00003978 DS, AnonRecord);
3979 assert(!AnonRecord && "Did not expect anonymous struct or union here");
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003980 DS.complete(TheDecl);
Steve Naroff97170802007-08-20 22:28:22 +00003981 return;
3982 }
3983
3984 // Read struct-declarators until we find the semicolon.
John McCallcfefb6d2009-11-03 02:38:08 +00003985 bool FirstDeclarator = true;
Richard Smith8d06f422012-01-12 23:53:29 +00003986 SourceLocation CommaLoc;
Steve Naroff97170802007-08-20 22:28:22 +00003987 while (1) {
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003988 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
Richard Smith8d06f422012-01-12 23:53:29 +00003989 DeclaratorInfo.D.setCommaLoc(CommaLoc);
John McCallcfefb6d2009-11-03 02:38:08 +00003990
Bill Wendling44426052012-12-20 19:22:21 +00003991 // Attributes are only allowed here on successive declarators.
John McCall53fa7142010-12-24 02:08:15 +00003992 if (!FirstDeclarator)
3993 MaybeParseGNUAttributes(DeclaratorInfo.D);
Mike Stump11289f42009-09-09 15:08:12 +00003994
Steve Naroff97170802007-08-20 22:28:22 +00003995 /// struct-declarator: declarator
3996 /// struct-declarator: declarator[opt] ':' constant-expression
Chris Lattner17c3b1f2009-12-10 01:59:24 +00003997 if (Tok.isNot(tok::colon)) {
3998 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3999 ColonProtectionRAIIObject X(*this);
Chris Lattnera12405b2008-04-10 06:46:29 +00004000 ParseDeclarator(DeclaratorInfo.D);
Richard Smith3d1a94c2014-08-12 00:22:39 +00004001 } else
4002 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004003
Alp Toker8fbec672013-12-17 23:29:36 +00004004 if (TryConsumeToken(tok::colon)) {
John McCalldadc5752010-08-24 06:29:42 +00004005 ExprResult Res(ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004006 if (Res.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00004007 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner32295d32008-04-10 06:15:14 +00004008 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004009 DeclaratorInfo.BitfieldSize = Res.get();
Steve Naroff97170802007-08-20 22:28:22 +00004010 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004011
Steve Naroff97170802007-08-20 22:28:22 +00004012 // If attributes exist after the declarator, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004013 MaybeParseGNUAttributes(DeclaratorInfo.D);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004014
John McCallcfefb6d2009-11-03 02:38:08 +00004015 // We're done with this declarator; invoke the callback.
Benjamin Kramera39beb92014-09-03 11:06:10 +00004016 FieldsCallback(DeclaratorInfo);
John McCallcfefb6d2009-11-03 02:38:08 +00004017
Steve Naroff97170802007-08-20 22:28:22 +00004018 // If we don't have a comma, it is either the end of the list (a ';')
4019 // or an error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00004020 if (!TryConsumeToken(tok::comma, CommaLoc))
Chris Lattner70ae4912007-10-29 04:42:53 +00004021 return;
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004022
John McCallcfefb6d2009-11-03 02:38:08 +00004023 FirstDeclarator = false;
Steve Naroff97170802007-08-20 22:28:22 +00004024 }
Steve Naroff97170802007-08-20 22:28:22 +00004025}
4026
4027/// ParseStructUnionBody
4028/// struct-contents:
4029/// struct-declaration-list
4030/// [EXT] empty
4031/// [GNU] "struct-declaration-list" without terminatoring ';'
4032/// struct-declaration-list:
4033/// struct-declaration
4034/// struct-declaration-list struct-declaration
Chris Lattner535b8302008-06-21 19:39:06 +00004035/// [OBC] '@' 'defs' '(' class-name ')'
Steve Naroff97170802007-08-20 22:28:22 +00004036///
Chris Lattner1300fb92007-01-23 23:42:53 +00004037void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00004038 unsigned TagType, Decl *TagDecl) {
Jordan Rose1e879d82018-03-23 00:07:18 +00004039 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00004040 "parsing struct/union body");
Andy Gibbs22e140b2013-04-03 09:31:19 +00004041 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
Mike Stump11289f42009-09-09 15:08:12 +00004042
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004043 BalancedDelimiterTracker T(*this, tok::l_brace);
4044 if (T.consumeOpen())
4045 return;
Mike Stump11289f42009-09-09 15:08:12 +00004046
Douglas Gregor658b9552009-01-09 22:42:13 +00004047 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004048 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004049
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004050 SmallVector<Decl *, 32> FieldDecls;
Chris Lattnera12405b2008-04-10 06:46:29 +00004051
Chris Lattner7b9ace62007-01-23 20:11:08 +00004052 // While we still have something to read, read the declarations in the struct.
Richard Smith752ada82015-11-17 23:32:01 +00004053 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4054 Tok.isNot(tok::eof)) {
Chris Lattner90a26b02007-01-23 04:38:16 +00004055 // Each iteration of this loop reads one struct-declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004056
Chris Lattner736ed5d2007-06-09 05:59:07 +00004057 // Check for extraneous top-level semicolon.
Chris Lattner76c72282007-10-09 17:33:22 +00004058 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004059 ConsumeExtraSemi(InsideStruct, TagType);
Chris Lattner36e46a22007-06-09 05:49:55 +00004060 continue;
4061 }
Chris Lattnera12405b2008-04-10 06:46:29 +00004062
Andy Gibbsc804e082013-04-03 09:46:04 +00004063 // Parse _Static_assert declaration.
4064 if (Tok.is(tok::kw__Static_assert)) {
4065 SourceLocation DeclEnd;
4066 ParseStaticAssertDeclaration(DeclEnd);
4067 continue;
4068 }
4069
Argyrios Kyrtzidis71c12fb2013-04-18 01:42:35 +00004070 if (Tok.is(tok::annot_pragma_pack)) {
4071 HandlePragmaPack();
4072 continue;
4073 }
4074
4075 if (Tok.is(tok::annot_pragma_align)) {
4076 HandlePragmaAlign();
4077 continue;
4078 }
4079
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004080 if (Tok.is(tok::annot_pragma_openmp)) {
Alexey Bataev587e1de2016-03-30 10:43:55 +00004081 // Result can be ignored, because it must be always empty.
4082 AccessSpecifier AS = AS_none;
4083 ParsedAttributesWithRange Attrs(AttrFactory);
4084 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004085 continue;
4086 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004087
John McCallcfefb6d2009-11-03 02:38:08 +00004088 if (!Tok.is(tok::at)) {
Benjamin Kramera39beb92014-09-03 11:06:10 +00004089 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4090 // Install the declarator into the current TagDecl.
4091 Decl *Field =
4092 Actions.ActOnField(getCurScope(), TagDecl,
4093 FD.D.getDeclSpec().getSourceRange().getBegin(),
4094 FD.D, FD.BitfieldSize);
4095 FieldDecls.push_back(Field);
4096 FD.complete(Field);
4097 };
John McCallcfefb6d2009-11-03 02:38:08 +00004098
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004099 // Parse all the comma separated declarators.
4100 ParsingDeclSpec DS(*this);
Benjamin Kramera39beb92014-09-03 11:06:10 +00004101 ParseStructDeclaration(DS, CFieldCallback);
Chris Lattner535b8302008-06-21 19:39:06 +00004102 } else { // Handle @defs
4103 ConsumeToken();
4104 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4105 Diag(Tok, diag::err_unexpected_at);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004106 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004107 continue;
4108 }
4109 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004110 ExpectAndConsume(tok::l_paren);
Chris Lattner535b8302008-06-21 19:39:06 +00004111 if (!Tok.is(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004112 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004113 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004114 continue;
4115 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004116 SmallVector<Decl *, 16> Fields;
Douglas Gregor0be31a22010-07-02 17:43:08 +00004117 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004118 Tok.getIdentifierInfo(), Fields);
Chris Lattner535b8302008-06-21 19:39:06 +00004119 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4120 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004121 ExpectAndConsume(tok::r_paren);
Mike Stump11289f42009-09-09 15:08:12 +00004122 }
Chris Lattner736ed5d2007-06-09 05:59:07 +00004123
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004124 if (TryConsumeToken(tok::semi))
4125 continue;
4126
4127 if (Tok.is(tok::r_brace)) {
Chris Lattner245c5332010-02-02 00:37:27 +00004128 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
Chris Lattner0c7e82d2007-06-09 05:54:40 +00004129 break;
Chris Lattner90a26b02007-01-23 04:38:16 +00004130 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004131
4132 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4133 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4134 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4135 // If we stopped at a ';', eat it.
4136 TryConsumeToken(tok::semi);
Chris Lattner90a26b02007-01-23 04:38:16 +00004137 }
Mike Stump11289f42009-09-09 15:08:12 +00004138
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004139 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +00004140
John McCall084e83d2011-03-24 11:26:52 +00004141 ParsedAttributes attrs(AttrFactory);
Chris Lattner90a26b02007-01-23 04:38:16 +00004142 // If attributes exist after struct contents, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004143 MaybeParseGNUAttributes(attrs);
Daniel Dunbar15619c72008-10-03 02:03:53 +00004144
Erich Keanec480f302018-07-12 21:09:05 +00004145 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4146 T.getOpenLocation(), T.getCloseLocation(), attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004147 StructScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004148 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
Chris Lattner90a26b02007-01-23 04:38:16 +00004149}
4150
Chris Lattner3b561a32006-08-13 00:12:11 +00004151/// ParseEnumSpecifier
Chris Lattner1890ac82006-08-13 01:16:23 +00004152/// enum-specifier: [C99 6.7.2.2]
Chris Lattner3b561a32006-08-13 00:12:11 +00004153/// 'enum' identifier[opt] '{' enumerator-list '}'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004154///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
Chris Lattnere37e2332006-08-15 04:50:22 +00004155/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4156/// '}' attributes[opt]
Aaron Ballman9ecff022012-03-01 04:09:28 +00004157/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4158/// '}'
Chris Lattner3b561a32006-08-13 00:12:11 +00004159/// 'enum' identifier
Chris Lattnere37e2332006-08-15 04:50:22 +00004160/// [GNU] 'enum' attributes[opt] identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004161///
Richard Smith7d137e32012-03-23 03:33:32 +00004162/// [C++11] enum-head '{' enumerator-list[opt] '}'
4163/// [C++11] enum-head '{' enumerator-list ',' '}'
Douglas Gregor0bf31402010-10-08 23:50:27 +00004164///
Richard Smith7d137e32012-03-23 03:33:32 +00004165/// enum-head: [C++11]
4166/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4167/// enum-key attribute-specifier-seq[opt] nested-name-specifier
4168/// identifier enum-base[opt]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004169///
Richard Smith7d137e32012-03-23 03:33:32 +00004170/// enum-key: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004171/// 'enum'
4172/// 'enum' 'class'
4173/// 'enum' 'struct'
4174///
Richard Smith7d137e32012-03-23 03:33:32 +00004175/// enum-base: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004176/// ':' type-specifier-seq
4177///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004178/// [C++] elaborated-type-specifier:
4179/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4180///
Chris Lattnerffaa0e62009-04-12 21:49:30 +00004181void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregordc70c3a2010-03-02 17:53:14 +00004182 const ParsedTemplateInfo &TemplateInfo,
Richard Smithc5b05522012-03-12 07:56:15 +00004183 AccessSpecifier AS, DeclSpecContext DSC) {
Chris Lattnerffbc2712007-01-25 06:05:38 +00004184 // Parse the tag portion of this.
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004185 if (Tok.is(tok::code_completion)) {
4186 // Code completion for an enum name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004187 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00004188 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004189 }
John McCallcb432fa2011-07-06 05:58:41 +00004190
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004191 // If attributes exist after tag, parse them.
4192 ParsedAttributesWithRange attrs(AttrFactory);
4193 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004194 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004195 MaybeParseMicrosoftDeclSpecs(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004196
Richard Smith0f8ee222012-01-10 01:33:14 +00004197 SourceLocation ScopedEnumKWLoc;
John McCallcb432fa2011-07-06 05:58:41 +00004198 bool IsScopedUsingClassTag = false;
4199
John McCallbeae29a2012-06-23 22:30:04 +00004200 // In C++11, recognize 'enum class' and 'enum struct'.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004201 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
Richard Trieud0d87b52013-04-23 02:47:36 +00004202 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4203 : diag::ext_scoped_enum);
John McCallcb432fa2011-07-06 05:58:41 +00004204 IsScopedUsingClassTag = Tok.is(tok::kw_class);
Richard Smith0f8ee222012-01-10 01:33:14 +00004205 ScopedEnumKWLoc = ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004206
Bill Wendling44426052012-12-20 19:22:21 +00004207 // Attributes are not allowed between these keywords. Diagnose,
John McCallbeae29a2012-06-23 22:30:04 +00004208 // but then just treat them like they appeared in the right place.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004209 ProhibitAttributes(attrs);
John McCallbeae29a2012-06-23 22:30:04 +00004210
4211 // They are allowed afterwards, though.
4212 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004213 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004214 MaybeParseMicrosoftDeclSpecs(attrs);
John McCallcb432fa2011-07-06 05:58:41 +00004215 }
Richard Smith7d137e32012-03-23 03:33:32 +00004216
John McCall6347b682012-05-07 06:16:58 +00004217 // C++11 [temp.explicit]p12:
4218 // The usual access controls do not apply to names used to specify
4219 // explicit instantiations.
4220 // We extend this to also cover explicit specializations. Note that
4221 // we don't suppress if this turns out to be an elaborated type
4222 // specifier.
4223 bool shouldDelayDiagsInTag =
4224 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4225 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4226 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Richard Smith7d137e32012-03-23 03:33:32 +00004227
Richard Smithbfdb1082012-03-12 08:56:40 +00004228 // Enum definitions should not be parsed in a trailing-return-type.
Faisal Vali7db85c52017-12-31 00:06:40 +00004229 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
Richard Smithbfdb1082012-03-12 08:56:40 +00004230
Abramo Bagnarad7548482010-05-19 21:37:53 +00004231 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004232 if (getLangOpts().CPlusPlus) {
John McCallcb432fa2011-07-06 05:58:41 +00004233 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4234 // if a fixed underlying type is allowed.
Erik Pilkington6f11db12018-09-28 20:24:58 +00004235 ColonProtectionRAIIObject X(*this, AllowDeclaration);
Chad Rosierc1183952012-06-26 22:30:43 +00004236
Nico Webercfaa4cd2015-02-15 07:26:13 +00004237 CXXScopeSpec Spec;
David Blaikieefdccaa2016-01-15 23:43:34 +00004238 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
Richard Smith1d4b2e12013-04-01 21:43:41 +00004239 /*EnteringContext=*/true))
John McCall1f476a12010-02-26 08:45:28 +00004240 return;
4241
Nico Webercfaa4cd2015-02-15 07:26:13 +00004242 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004243 Diag(Tok, diag::err_expected) << tok::identifier;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004244 if (Tok.isNot(tok::l_brace)) {
4245 // Has no name and is not a definition.
4246 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004247 SkipUntil(tok::comma, StopAtSemi);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004248 return;
4249 }
4250 }
Nico Webercfaa4cd2015-02-15 07:26:13 +00004251
4252 SS = Spec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004253 }
Mike Stump11289f42009-09-09 15:08:12 +00004254
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004255 // Must have either 'enum name' or 'enum {...}'.
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004256 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
Erik Pilkington6f11db12018-09-28 20:24:58 +00004257 !(AllowDeclaration && Tok.is(tok::colon))) {
Alp Tokerec543272013-12-24 09:48:30 +00004258 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
Mike Stump11289f42009-09-09 15:08:12 +00004259
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004260 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004261 SkipUntil(tok::comma, StopAtSemi);
Chris Lattner3b561a32006-08-13 00:12:11 +00004262 return;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004263 }
Mike Stump11289f42009-09-09 15:08:12 +00004264
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004265 // If an identifier is present, consume and remember it.
Craig Topper161e4db2014-05-21 06:02:52 +00004266 IdentifierInfo *Name = nullptr;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004267 SourceLocation NameLoc;
4268 if (Tok.is(tok::identifier)) {
4269 Name = Tok.getIdentifierInfo();
4270 NameLoc = ConsumeToken();
4271 }
Mike Stump11289f42009-09-09 15:08:12 +00004272
Richard Smith0f8ee222012-01-10 01:33:14 +00004273 if (!Name && ScopedEnumKWLoc.isValid()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00004274 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4275 // declaration of a scoped enumeration.
4276 Diag(Tok, diag::err_scoped_enum_missing_identifier);
Richard Smith0f8ee222012-01-10 01:33:14 +00004277 ScopedEnumKWLoc = SourceLocation();
Abramo Bagnara0e05e242010-12-03 18:54:17 +00004278 IsScopedUsingClassTag = false;
Douglas Gregor0bf31402010-10-08 23:50:27 +00004279 }
4280
John McCall6347b682012-05-07 06:16:58 +00004281 // Okay, end the suppression area. We'll decide whether to emit the
4282 // diagnostics in a second.
4283 if (shouldDelayDiagsInTag)
4284 diagsFromTag.done();
Richard Smith7d137e32012-03-23 03:33:32 +00004285
Douglas Gregor0bf31402010-10-08 23:50:27 +00004286 TypeResult BaseType;
4287
Douglas Gregord1f69f62010-12-01 17:42:47 +00004288 // Parse the fixed underlying type.
Richard Smith200f47c2012-07-02 19:14:01 +00004289 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
Erik Pilkington6f11db12018-09-28 20:24:58 +00004290 if (AllowDeclaration && Tok.is(tok::colon)) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004291 bool PossibleBitfield = false;
Richard Smith200f47c2012-07-02 19:14:01 +00004292 if (CanBeBitfield) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004293 // If we're in class scope, this can either be an enum declaration with
4294 // an underlying type, or a declaration of a bitfield member. We try to
4295 // use a simple disambiguation scheme first to catch the common cases
Chad Rosierc1183952012-06-26 22:30:43 +00004296 // (integer literal, sizeof); if it's still ambiguous, we then consider
4297 // anything that's a simple-type-specifier followed by '(' as an
4298 // expression. This suffices because function types are not valid
Douglas Gregord1f69f62010-12-01 17:42:47 +00004299 // underlying types anyway.
Faisal Valid143a0c2017-04-01 21:30:49 +00004300 EnterExpressionEvaluationContext Unevaluated(
4301 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregord1f69f62010-12-01 17:42:47 +00004302 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
Chad Rosierc1183952012-06-26 22:30:43 +00004303 // If the next token starts an expression, we know we're parsing a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004304 // bit-field. This is the common case.
Richard Smithee390432014-05-16 01:56:53 +00004305 if (TPR == TPResult::True)
Douglas Gregord1f69f62010-12-01 17:42:47 +00004306 PossibleBitfield = true;
4307 // If the next token starts a type-specifier-seq, it may be either a
4308 // a fixed underlying type or the start of a function-style cast in C++;
Chad Rosierc1183952012-06-26 22:30:43 +00004309 // lookahead one more token to see if it's obvious that we have a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004310 // fixed underlying type.
Richard Smithee390432014-05-16 01:56:53 +00004311 else if (TPR == TPResult::False &&
Douglas Gregord1f69f62010-12-01 17:42:47 +00004312 GetLookAheadToken(2).getKind() == tok::semi) {
4313 // Consume the ':'.
4314 ConsumeToken();
4315 } else {
4316 // We have the start of a type-specifier-seq, so we have to perform
4317 // tentative parsing to determine whether we have an expression or a
4318 // type.
4319 TentativeParsingAction TPA(*this);
4320
4321 // Consume the ':'.
4322 ConsumeToken();
Richard Smith1e3b0f02012-02-23 01:36:12 +00004323
4324 // If we see a type specifier followed by an open-brace, we have an
4325 // ambiguity between an underlying type and a C++11 braced
4326 // function-style cast. Resolve this by always treating it as an
4327 // underlying type.
4328 // FIXME: The standard is not entirely clear on how to disambiguate in
4329 // this case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004330 if ((getLangOpts().CPlusPlus &&
Richard Smithee390432014-05-16 01:56:53 +00004331 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00004332 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004333 // We'll parse this as a bitfield later.
4334 PossibleBitfield = true;
4335 TPA.Revert();
4336 } else {
4337 // We have a type-specifier-seq.
4338 TPA.Commit();
4339 }
4340 }
4341 } else {
4342 // Consume the ':'.
4343 ConsumeToken();
4344 }
4345
4346 if (!PossibleBitfield) {
4347 SourceRange Range;
4348 BaseType = ParseTypeName(&Range);
Chad Rosierc1183952012-06-26 22:30:43 +00004349
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004350 if (!getLangOpts().ObjC) {
Erik Pilkington6f11db12018-09-28 20:24:58 +00004351 if (getLangOpts().CPlusPlus11)
4352 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4353 else if (getLangOpts().CPlusPlus)
4354 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4355 else if (getLangOpts().MicrosoftExt)
4356 Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004357 else
Erik Pilkington6f11db12018-09-28 20:24:58 +00004358 Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004359 }
Douglas Gregord1f69f62010-12-01 17:42:47 +00004360 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004361 }
4362
Richard Smith0f8ee222012-01-10 01:33:14 +00004363 // There are four options here. If we have 'friend enum foo;' then this is a
4364 // friend declaration, and cannot have an accompanying definition. If we have
4365 // 'enum foo;', then this is a forward declaration. If we have
4366 // 'enum foo {...' then this is a definition. Otherwise we have something
4367 // like 'enum foo xyz', a reference.
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004368 //
4369 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4370 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4371 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4372 //
John McCallfaf5fb42010-08-26 23:41:50 +00004373 Sema::TagUseKind TUK;
John McCall6347b682012-05-07 06:16:58 +00004374 if (!AllowDeclaration) {
Richard Smithbfdb1082012-03-12 08:56:40 +00004375 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004376 } else if (Tok.is(tok::l_brace)) {
4377 if (DS.isFriendSpecified()) {
4378 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4379 << SourceRange(DS.getFriendSpecLoc());
4380 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004381 SkipUntil(tok::r_brace, StopAtSemi);
John McCall6347b682012-05-07 06:16:58 +00004382 TUK = Sema::TUK_Friend;
4383 } else {
4384 TUK = Sema::TUK_Definition;
4385 }
Richard Smith649c7b062014-01-08 00:56:48 +00004386 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00004387 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00004388 (Tok.isAtStartOfLine() &&
4389 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
Richard Smith369b9f92012-06-25 21:37:02 +00004390 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4391 if (Tok.isNot(tok::semi)) {
4392 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00004393 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004394 PP.EnterToken(Tok);
4395 Tok.setKind(tok::semi);
4396 }
John McCall6347b682012-05-07 06:16:58 +00004397 } else {
John McCallfaf5fb42010-08-26 23:41:50 +00004398 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004399 }
4400
4401 // If this is an elaborated type specifier, and we delayed
4402 // diagnostics before, just merge them into the current pool.
4403 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4404 diagsFromTag.redelay();
4405 }
Richard Smith7d137e32012-03-23 03:33:32 +00004406
4407 MultiTemplateParamsArg TParams;
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004408 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
John McCallfaf5fb42010-08-26 23:41:50 +00004409 TUK != Sema::TUK_Reference) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004410 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
Richard Smith7d137e32012-03-23 03:33:32 +00004411 // Skip the rest of this declarator, up until the comma or semicolon.
4412 Diag(Tok, diag::err_enum_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004413 SkipUntil(tok::comma, StopAtSemi);
Richard Smith7d137e32012-03-23 03:33:32 +00004414 return;
4415 }
4416
4417 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4418 // Enumerations can't be explicitly instantiated.
4419 DS.SetTypeSpecError();
4420 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4421 return;
4422 }
4423
4424 assert(TemplateInfo.TemplateParams && "no template parameters");
4425 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4426 TemplateInfo.TemplateParams->size());
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004427 }
Chad Rosierc1183952012-06-26 22:30:43 +00004428
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004429 if (TUK == Sema::TUK_Reference)
4430 ProhibitAttributes(attrs);
Richard Smith7d137e32012-03-23 03:33:32 +00004431
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004432 if (!Name && TUK != Sema::TUK_Definition) {
4433 Diag(Tok, diag::err_enumerator_unnamed_no_def);
Richard Smith7d137e32012-03-23 03:33:32 +00004434
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004435 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004436 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004437 return;
4438 }
Richard Smith7d137e32012-03-23 03:33:32 +00004439
Nico Weber32a0fc72016-09-03 03:01:32 +00004440 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00004441
Richard Smithd9ba2242015-05-07 03:54:19 +00004442 Sema::SkipBodyInfo SkipBody;
4443 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4444 NextToken().is(tok::identifier))
4445 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4446 NextToken().getIdentifierInfo(),
4447 NextToken().getLocation());
4448
Douglas Gregord6ab8742009-05-28 23:31:59 +00004449 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004450 bool IsDependent = false;
Craig Topper161e4db2014-05-21 06:02:52 +00004451 const char *PrevSpec = nullptr;
Douglas Gregorba41d012010-04-24 16:38:41 +00004452 unsigned DiagID;
Faisal Vali7db85c52017-12-31 00:06:40 +00004453 Decl *TagDecl = Actions.ActOnTag(
4454 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
Erich Keanec480f302018-07-12 21:09:05 +00004455 attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4456 ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
Faisal Vali7db85c52017-12-31 00:06:40 +00004457 DSC == DeclSpecContext::DSC_type_specifier,
4458 DSC == DeclSpecContext::DSC_template_param ||
4459 DSC == DeclSpecContext::DSC_template_type_arg,
4460 &SkipBody);
Richard Smithd9ba2242015-05-07 03:54:19 +00004461
4462 if (SkipBody.ShouldSkip) {
4463 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4464
4465 BalancedDelimiterTracker T(*this, tok::l_brace);
4466 T.consumeOpen();
4467 T.skipToEnd();
4468
4469 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4470 NameLoc.isValid() ? NameLoc : StartLoc,
4471 PrevSpec, DiagID, TagDecl, Owned,
4472 Actions.getASTContext().getPrintingPolicy()))
4473 Diag(StartLoc, DiagID) << PrevSpec;
4474 return;
4475 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004476
Douglas Gregorba41d012010-04-24 16:38:41 +00004477 if (IsDependent) {
Chad Rosierc1183952012-06-26 22:30:43 +00004478 // This enum has a dependent nested-name-specifier. Handle it as a
Douglas Gregorba41d012010-04-24 16:38:41 +00004479 // dependent tag.
4480 if (!Name) {
4481 DS.SetTypeSpecError();
4482 Diag(Tok, diag::err_expected_type_name_after_typename);
4483 return;
4484 }
Chad Rosierc1183952012-06-26 22:30:43 +00004485
Nico Weber83ea0122014-05-03 21:57:40 +00004486 TypeResult Type = Actions.ActOnDependentTag(
4487 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
Douglas Gregorba41d012010-04-24 16:38:41 +00004488 if (Type.isInvalid()) {
4489 DS.SetTypeSpecError();
4490 return;
4491 }
Chad Rosierc1183952012-06-26 22:30:43 +00004492
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004493 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4494 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004495 PrevSpec, DiagID, Type.get(),
4496 Actions.getASTContext().getPrintingPolicy()))
Douglas Gregorba41d012010-04-24 16:38:41 +00004497 Diag(StartLoc, DiagID) << PrevSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00004498
Douglas Gregorba41d012010-04-24 16:38:41 +00004499 return;
4500 }
Mike Stump11289f42009-09-09 15:08:12 +00004501
John McCall48871652010-08-21 09:40:31 +00004502 if (!TagDecl) {
Chad Rosierc1183952012-06-26 22:30:43 +00004503 // The action failed to produce an enumeration tag. If this is a
Douglas Gregorba41d012010-04-24 16:38:41 +00004504 // definition, consume the entire definition.
Richard Smithbfdb1082012-03-12 08:56:40 +00004505 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
Douglas Gregorba41d012010-04-24 16:38:41 +00004506 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004507 SkipUntil(tok::r_brace, StopAtSemi);
Douglas Gregorba41d012010-04-24 16:38:41 +00004508 }
Chad Rosierc1183952012-06-26 22:30:43 +00004509
Douglas Gregorba41d012010-04-24 16:38:41 +00004510 DS.SetTypeSpecError();
4511 return;
4512 }
Richard Smith0f8ee222012-01-10 01:33:14 +00004513
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004514 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4515 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4516 ParseEnumBody(StartLoc, D);
4517 if (SkipBody.CheckSameAsPrevious &&
4518 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4519 DS.SetTypeSpecError();
4520 return;
4521 }
4522 }
Mike Stump11289f42009-09-09 15:08:12 +00004523
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004524 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4525 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004526 PrevSpec, DiagID, TagDecl, Owned,
4527 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00004528 Diag(StartLoc, DiagID) << PrevSpec;
Chris Lattner3b561a32006-08-13 00:12:11 +00004529}
4530
Chris Lattnerc1915e22007-01-25 07:29:02 +00004531/// ParseEnumBody - Parse a {} enclosed enumerator-list.
4532/// enumerator-list:
4533/// enumerator
4534/// enumerator-list ',' enumerator
4535/// enumerator:
Aaron Ballman730476b2014-11-08 15:33:35 +00004536/// enumeration-constant attributes[opt]
4537/// enumeration-constant attributes[opt] '=' constant-expression
Chris Lattnerc1915e22007-01-25 07:29:02 +00004538/// enumeration-constant:
4539/// identifier
4540///
John McCall48871652010-08-21 09:40:31 +00004541void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004542 // Enter the scope of the enum body and start the definition.
Hans Wennborgfe781452014-06-17 00:00:18 +00004543 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004544 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
Douglas Gregor07665a62009-01-05 19:45:36 +00004545
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004546 BalancedDelimiterTracker T(*this, tok::l_brace);
4547 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00004548
Chris Lattner37256fb2007-08-27 17:24:30 +00004549 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
David Blaikiebbafb8a2012-03-11 07:00:24 +00004550 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
Richard Smithf8812672016-12-02 22:38:31 +00004551 Diag(Tok, diag::err_empty_enum);
Mike Stump11289f42009-09-09 15:08:12 +00004552
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004553 SmallVector<Decl *, 32> EnumConstantDecls;
Jordan Rose60ac3162015-04-30 17:20:30 +00004554 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
Chris Lattnerc1915e22007-01-25 07:29:02 +00004555
Craig Topper161e4db2014-05-21 06:02:52 +00004556 Decl *LastEnumConstDecl = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004557
Chris Lattnerc1915e22007-01-25 07:29:02 +00004558 // Parse the enumerator-list.
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004559 while (Tok.isNot(tok::r_brace)) {
4560 // Parse enumerator. If failed, try skipping till the start of the next
4561 // enumerator definition.
4562 if (Tok.isNot(tok::identifier)) {
4563 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4564 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4565 TryConsumeToken(tok::comma))
4566 continue;
4567 break;
4568 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004569 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4570 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00004571
John McCall811a0f52010-10-22 23:36:17 +00004572 // If attributes exist after the enumerator, parse them.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004573 ParsedAttributesWithRange attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004574 MaybeParseGNUAttributes(attrs);
Aaron Ballman730476b2014-11-08 15:33:35 +00004575 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
Aaron Ballman606093a2017-10-15 15:01:42 +00004576 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4577 if (getLangOpts().CPlusPlus)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004578 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Aaron Ballman606093a2017-10-15 15:01:42 +00004579 ? diag::warn_cxx14_compat_ns_enum_attribute
4580 : diag::ext_ns_enum_attribute)
4581 << 1 /*enumerator*/;
Aaron Ballman730476b2014-11-08 15:33:35 +00004582 ParseCXX11Attributes(attrs);
4583 }
John McCall811a0f52010-10-22 23:36:17 +00004584
Chris Lattnerc1915e22007-01-25 07:29:02 +00004585 SourceLocation EqualLoc;
John McCalldadc5752010-08-24 06:29:42 +00004586 ExprResult AssignedVal;
Jordan Rose60ac3162015-04-30 17:20:30 +00004587 EnumAvailabilityDiags.emplace_back(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00004588
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004589 if (TryConsumeToken(tok::equal, EqualLoc)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004590 AssignedVal = ParseConstantExpression();
4591 if (AssignedVal.isInvalid())
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004592 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
Chris Lattnerc1915e22007-01-25 07:29:02 +00004593 }
Mike Stump11289f42009-09-09 15:08:12 +00004594
Chris Lattnerc1915e22007-01-25 07:29:02 +00004595 // Install the enumerator constant into EnumDecl.
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004596 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
Erich Keanec480f302018-07-12 21:09:05 +00004597 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4598 EqualLoc, AssignedVal.get());
Jordan Rose60ac3162015-04-30 17:20:30 +00004599 EnumAvailabilityDiags.back().done();
Chad Rosierc1183952012-06-26 22:30:43 +00004600
Chris Lattner4ef40012007-06-11 01:28:17 +00004601 EnumConstantDecls.push_back(EnumConstDecl);
4602 LastEnumConstDecl = EnumConstDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004603
Douglas Gregorce66d022010-09-07 14:51:08 +00004604 if (Tok.is(tok::identifier)) {
4605 // We're missing a comma between enumerators.
Richard Smithbdb84f32016-07-22 23:36:59 +00004606 SourceLocation Loc = getEndOfPreviousToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004607 Diag(Loc, diag::err_enumerator_list_missing_comma)
Douglas Gregorce66d022010-09-07 14:51:08 +00004608 << FixItHint::CreateInsertion(Loc, ", ");
4609 continue;
4610 }
Chad Rosierc1183952012-06-26 22:30:43 +00004611
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004612 // Emumerator definition must be finished, only comma or r_brace are
4613 // allowed here.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004614 SourceLocation CommaLoc;
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004615 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4616 if (EqualLoc.isValid())
4617 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4618 << tok::comma;
4619 else
4620 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4621 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4622 if (TryConsumeToken(tok::comma, CommaLoc))
4623 continue;
4624 } else {
4625 break;
4626 }
4627 }
Mike Stump11289f42009-09-09 15:08:12 +00004628
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004629 // If comma is followed by r_brace, emit appropriate warning.
4630 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004631 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
Richard Smith87f5dc52012-07-23 05:45:25 +00004632 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4633 diag::ext_enumerator_list_comma_cxx :
4634 diag::ext_enumerator_list_comma_c)
Richard Smith5d164bc2011-10-15 05:09:34 +00004635 << FixItHint::CreateRemoval(CommaLoc);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004636 else if (getLangOpts().CPlusPlus11)
Richard Smith5d164bc2011-10-15 05:09:34 +00004637 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4638 << FixItHint::CreateRemoval(CommaLoc);
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004639 break;
Richard Smith5d164bc2011-10-15 05:09:34 +00004640 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004641 }
Mike Stump11289f42009-09-09 15:08:12 +00004642
Chris Lattnerc1915e22007-01-25 07:29:02 +00004643 // Eat the }.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004644 T.consumeClose();
Chris Lattnerc1915e22007-01-25 07:29:02 +00004645
Chris Lattnerc1915e22007-01-25 07:29:02 +00004646 // If attributes exist after the identifier list, parse them.
John McCall084e83d2011-03-24 11:26:52 +00004647 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004648 MaybeParseGNUAttributes(attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004649
Erich Keanec480f302018-07-12 21:09:05 +00004650 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4651 getCurScope(), attrs);
Mike Stump11289f42009-09-09 15:08:12 +00004652
Jordan Rose60ac3162015-04-30 17:20:30 +00004653 // Now handle enum constant availability diagnostics.
4654 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4655 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4656 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4657 EnumAvailabilityDiags[i].redelay();
4658 PD.complete(EnumConstantDecls[i]);
4659 }
4660
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004661 EnumScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004662 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
Richard Smith369b9f92012-06-25 21:37:02 +00004663
4664 // The next token must be valid after an enum definition. If not, a ';'
4665 // was probably forgotten.
Richard Smith200f47c2012-07-02 19:14:01 +00004666 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4667 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
Alp Toker383d2c42014-01-01 03:08:43 +00004668 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004669 // Push this token back into the preprocessor and change our current token
4670 // to ';' so that the rest of the code recovers as though there were an
4671 // ';' after the definition.
4672 PP.EnterToken(Tok);
4673 Tok.setKind(tok::semi);
4674 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004675}
Chris Lattner3b561a32006-08-13 00:12:11 +00004676
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004677/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4678/// is definitely a type-specifier. Return false if it isn't part of a type
4679/// specifier or if we're not sure.
4680bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4681 switch (Tok.getKind()) {
4682 default: return false;
4683 // type-specifiers
4684 case tok::kw_short:
4685 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004686 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004687 case tok::kw___int128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004688 case tok::kw_signed:
4689 case tok::kw_unsigned:
4690 case tok::kw__Complex:
4691 case tok::kw__Imaginary:
4692 case tok::kw_void:
4693 case tok::kw_char:
4694 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004695 case tok::kw_char8_t:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004696 case tok::kw_char16_t:
4697 case tok::kw_char32_t:
4698 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004699 case tok::kw_half:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004700 case tok::kw_float:
4701 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004702 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004703 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004704 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004705 case tok::kw___float128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004706 case tok::kw_bool:
4707 case tok::kw__Bool:
4708 case tok::kw__Decimal32:
4709 case tok::kw__Decimal64:
4710 case tok::kw__Decimal128:
4711 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004712#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004713#include "clang/Basic/OpenCLImageTypes.def"
Chad Rosierc1183952012-06-26 22:30:43 +00004714
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004715 // struct-or-union-specifier (C99) or class-specifier (C++)
4716 case tok::kw_class:
4717 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004718 case tok::kw___interface:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004719 case tok::kw_union:
4720 // enum-specifier
4721 case tok::kw_enum:
Chad Rosierc1183952012-06-26 22:30:43 +00004722
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004723 // typedef-name
4724 case tok::annot_typename:
4725 return true;
4726 }
4727}
4728
Steve Naroff69e8f9e2008-02-11 23:15:56 +00004729/// isTypeSpecifierQualifier - Return true if the current token could be the
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004730/// start of a specifier-qualifier-list.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004731bool Parser::isTypeSpecifierQualifier() {
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004732 switch (Tok.getKind()) {
4733 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004734
Chris Lattner020bab92009-01-04 23:41:41 +00004735 case tok::identifier: // foo::bar
John Thompson22334602010-02-05 00:12:22 +00004736 if (TryAltiVecVectorToken())
4737 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004738 LLVM_FALLTHROUGH;
Douglas Gregor333489b2009-03-27 23:10:48 +00004739 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004740 // Annotate typenames and C++ scope specifiers. If we get one, just
4741 // recurse to handle whatever we get.
4742 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004743 return true;
4744 if (Tok.is(tok::identifier))
4745 return false;
4746 return isTypeSpecifierQualifier();
Douglas Gregor333489b2009-03-27 23:10:48 +00004747
Chris Lattner020bab92009-01-04 23:41:41 +00004748 case tok::coloncolon: // ::foo::bar
4749 if (NextToken().is(tok::kw_new) || // ::new
4750 NextToken().is(tok::kw_delete)) // ::delete
4751 return false;
4752
Chris Lattner020bab92009-01-04 23:41:41 +00004753 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004754 return true;
4755 return isTypeSpecifierQualifier();
Mike Stump11289f42009-09-09 15:08:12 +00004756
Chris Lattnere37e2332006-08-15 04:50:22 +00004757 // GNU attributes support.
4758 case tok::kw___attribute:
Steve Naroffad373bd2007-07-31 12:34:36 +00004759 // GNU typeof support.
4760 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004761
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004762 // type-specifiers
4763 case tok::kw_short:
4764 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004765 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004766 case tok::kw___int128:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004767 case tok::kw_signed:
4768 case tok::kw_unsigned:
4769 case tok::kw__Complex:
4770 case tok::kw__Imaginary:
4771 case tok::kw_void:
4772 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004773 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004774 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004775 case tok::kw_char16_t:
4776 case tok::kw_char32_t:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004777 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004778 case tok::kw_half:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004779 case tok::kw_float:
4780 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004781 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004782 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004783 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004784 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004785 case tok::kw_bool:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004786 case tok::kw__Bool:
4787 case tok::kw__Decimal32:
4788 case tok::kw__Decimal64:
4789 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004790 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004791#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004792#include "clang/Basic/OpenCLImageTypes.def"
Mike Stump11289f42009-09-09 15:08:12 +00004793
Chris Lattner861a2262008-04-13 18:59:07 +00004794 // struct-or-union-specifier (C99) or class-specifier (C++)
4795 case tok::kw_class:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004796 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004797 case tok::kw___interface:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004798 case tok::kw_union:
4799 // enum-specifier
4800 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004801
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004802 // type-qualifier
4803 case tok::kw_const:
4804 case tok::kw_volatile:
4805 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004806 case tok::kw__Sat:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004807
John McCallea0a39e2012-11-14 00:49:39 +00004808 // Debugger support.
4809 case tok::kw___unknown_anytype:
4810
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004811 // typedef-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00004812 case tok::annot_typename:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004813 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004814
Chris Lattner409bf7d2008-10-20 00:25:30 +00004815 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4816 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004817 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00004818
Steve Naroff44ac7772008-12-25 14:16:32 +00004819 case tok::kw___cdecl:
4820 case tok::kw___stdcall:
4821 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004822 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004823 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004824 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004825 case tok::kw___w64:
4826 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004827 case tok::kw___ptr32:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004828 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004829 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004830
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004831 case tok::kw__Nonnull:
4832 case tok::kw__Nullable:
4833 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004834
Douglas Gregorab209d82015-07-07 03:58:42 +00004835 case tok::kw___kindof:
4836
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004837 case tok::kw___private:
4838 case tok::kw___local:
4839 case tok::kw___global:
4840 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004841 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004842 case tok::kw___read_only:
4843 case tok::kw___read_write:
4844 case tok::kw___write_only:
Eli Friedman53339e02009-06-08 23:27:34 +00004845 return true;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004846
Anastasia Stulova314fab62019-03-28 11:47:14 +00004847 case tok::kw_private:
4848 return getLangOpts().OpenCL;
4849
Richard Smith8e1ac332013-03-28 01:55:44 +00004850 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004851 case tok::kw__Atomic:
4852 return true;
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004853 }
4854}
4855
Chris Lattneracd58a32006-08-06 17:24:14 +00004856/// isDeclarationSpecifier() - Return true if the current token is part of a
4857/// declaration specifier.
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004858///
4859/// \param DisambiguatingWithExpression True to indicate that the purpose of
4860/// this check is to disambiguate between an expression and a declaration.
4861bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
Chris Lattneracd58a32006-08-06 17:24:14 +00004862 switch (Tok.getKind()) {
4863 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004864
Xiuli Pan9c14e282016-01-09 12:53:17 +00004865 case tok::kw_pipe:
4866 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4867
Chris Lattner020bab92009-01-04 23:41:41 +00004868 case tok::identifier: // foo::bar
Steve Naroff9527bbf2009-03-09 21:12:44 +00004869 // Unfortunate hack to support "Class.factoryMethod" notation.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004870 if (getLangOpts().ObjC && NextToken().is(tok::period))
Steve Naroff9527bbf2009-03-09 21:12:44 +00004871 return false;
John Thompson22334602010-02-05 00:12:22 +00004872 if (TryAltiVecVectorToken())
4873 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004874 LLVM_FALLTHROUGH;
David Blaikie15a430a2011-12-04 05:04:18 +00004875 case tok::kw_decltype: // decltype(T())::type
Douglas Gregor333489b2009-03-27 23:10:48 +00004876 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004877 // Annotate typenames and C++ scope specifiers. If we get one, just
4878 // recurse to handle whatever we get.
4879 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004880 return true;
4881 if (Tok.is(tok::identifier))
4882 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004883
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004884 // If we're in Objective-C and we have an Objective-C class type followed
Chad Rosierc1183952012-06-26 22:30:43 +00004885 // by an identifier and then either ':' or ']', in a place where an
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004886 // expression is permitted, then this is probably a class message send
4887 // missing the initial '['. In this case, we won't consider this to be
4888 // the start of a declaration.
Chad Rosierc1183952012-06-26 22:30:43 +00004889 if (DisambiguatingWithExpression &&
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004890 isStartOfObjCClassMessageMissingOpenBracket())
4891 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004892
John McCall1f476a12010-02-26 08:45:28 +00004893 return isDeclarationSpecifier();
4894
Chris Lattner020bab92009-01-04 23:41:41 +00004895 case tok::coloncolon: // ::foo::bar
4896 if (NextToken().is(tok::kw_new) || // ::new
4897 NextToken().is(tok::kw_delete)) // ::delete
4898 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004899
Chris Lattner020bab92009-01-04 23:41:41 +00004900 // Annotate typenames and C++ scope specifiers. If we get one, just
4901 // recurse to handle whatever we get.
4902 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004903 return true;
4904 return isDeclarationSpecifier();
Mike Stump11289f42009-09-09 15:08:12 +00004905
Chris Lattneracd58a32006-08-06 17:24:14 +00004906 // storage-class-specifier
4907 case tok::kw_typedef:
4908 case tok::kw_extern:
Steve Naroff2050b0d2007-12-18 00:16:02 +00004909 case tok::kw___private_extern__:
Chris Lattneracd58a32006-08-06 17:24:14 +00004910 case tok::kw_static:
4911 case tok::kw_auto:
Richard Smithe301ba22015-11-11 02:02:15 +00004912 case tok::kw___auto_type:
Chris Lattneracd58a32006-08-06 17:24:14 +00004913 case tok::kw_register:
4914 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00004915 case tok::kw_thread_local:
4916 case tok::kw__Thread_local:
Mike Stump11289f42009-09-09 15:08:12 +00004917
Douglas Gregor26701a42011-09-09 02:06:17 +00004918 // Modules
4919 case tok::kw___module_private__:
Chad Rosierc1183952012-06-26 22:30:43 +00004920
John McCallea0a39e2012-11-14 00:49:39 +00004921 // Debugger support
4922 case tok::kw___unknown_anytype:
4923
Chris Lattneracd58a32006-08-06 17:24:14 +00004924 // type-specifiers
4925 case tok::kw_short:
4926 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004927 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004928 case tok::kw___int128:
Chris Lattneracd58a32006-08-06 17:24:14 +00004929 case tok::kw_signed:
4930 case tok::kw_unsigned:
4931 case tok::kw__Complex:
4932 case tok::kw__Imaginary:
4933 case tok::kw_void:
4934 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004935 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004936 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004937 case tok::kw_char16_t:
4938 case tok::kw_char32_t:
4939
Chris Lattneracd58a32006-08-06 17:24:14 +00004940 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004941 case tok::kw_half:
Chris Lattneracd58a32006-08-06 17:24:14 +00004942 case tok::kw_float:
4943 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004944 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004945 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004946 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004947 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004948 case tok::kw_bool:
Chris Lattneracd58a32006-08-06 17:24:14 +00004949 case tok::kw__Bool:
4950 case tok::kw__Decimal32:
4951 case tok::kw__Decimal64:
4952 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004953 case tok::kw___vector:
Mike Stump11289f42009-09-09 15:08:12 +00004954
Chris Lattner861a2262008-04-13 18:59:07 +00004955 // struct-or-union-specifier (C99) or class-specifier (C++)
4956 case tok::kw_class:
Chris Lattneracd58a32006-08-06 17:24:14 +00004957 case tok::kw_struct:
4958 case tok::kw_union:
Joao Matosdc86f942012-08-31 18:45:21 +00004959 case tok::kw___interface:
Chris Lattneracd58a32006-08-06 17:24:14 +00004960 // enum-specifier
4961 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004962
Chris Lattneracd58a32006-08-06 17:24:14 +00004963 // type-qualifier
4964 case tok::kw_const:
4965 case tok::kw_volatile:
4966 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004967 case tok::kw__Sat:
Steve Naroffad373bd2007-07-31 12:34:36 +00004968
Chris Lattneracd58a32006-08-06 17:24:14 +00004969 // function-specifier
4970 case tok::kw_inline:
Douglas Gregor61956c42008-10-31 09:07:45 +00004971 case tok::kw_virtual:
4972 case tok::kw_explicit:
Richard Smith0015f092013-01-17 22:16:11 +00004973 case tok::kw__Noreturn:
Chris Lattner7b20dc72007-08-09 16:40:21 +00004974
Richard Smith1dba27c2013-01-29 09:02:09 +00004975 // alignment-specifier
4976 case tok::kw__Alignas:
4977
Richard Smithd16fe122012-10-25 00:00:53 +00004978 // friend keyword.
4979 case tok::kw_friend:
4980
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00004981 // static_assert-declaration
4982 case tok::kw__Static_assert:
4983
Chris Lattner599e47e2007-08-09 17:01:07 +00004984 // GNU typeof support.
4985 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004986
Chris Lattner599e47e2007-08-09 17:01:07 +00004987 // GNU attributes.
Chris Lattner7b20dc72007-08-09 16:40:21 +00004988 case tok::kw___attribute:
Mike Stump11289f42009-09-09 15:08:12 +00004989
Richard Smithd16fe122012-10-25 00:00:53 +00004990 // C++11 decltype and constexpr.
David Blaikie15a430a2011-12-04 05:04:18 +00004991 case tok::annot_decltype:
Richard Smithd16fe122012-10-25 00:00:53 +00004992 case tok::kw_constexpr:
Francois Pichete878cb62011-06-19 08:02:06 +00004993
Richard Smith8e1ac332013-03-28 01:55:44 +00004994 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004995 case tok::kw__Atomic:
4996 return true;
4997
Chris Lattner8b2ec162008-07-26 03:38:44 +00004998 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4999 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005000 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00005001
Douglas Gregor19b7acf2011-04-27 05:41:15 +00005002 // typedef-name
5003 case tok::annot_typename:
5004 return !DisambiguatingWithExpression ||
5005 !isStartOfObjCClassMessageMissingOpenBracket();
Chad Rosierc1183952012-06-26 22:30:43 +00005006
Steve Narofff192fab2009-01-06 19:34:12 +00005007 case tok::kw___declspec:
Steve Naroff44ac7772008-12-25 14:16:32 +00005008 case tok::kw___cdecl:
5009 case tok::kw___stdcall:
5010 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005011 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005012 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005013 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00005014 case tok::kw___w64:
Aaron Ballman317a77f2013-05-22 23:25:32 +00005015 case tok::kw___sptr:
5016 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005017 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005018 case tok::kw___ptr32:
Eli Friedman53339e02009-06-08 23:27:34 +00005019 case tok::kw___forceinline:
Dawn Perchik335e16b2010-09-03 01:29:35 +00005020 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00005021 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005022
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005023 case tok::kw__Nonnull:
5024 case tok::kw__Nullable:
5025 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005026
Douglas Gregorab209d82015-07-07 03:58:42 +00005027 case tok::kw___kindof:
5028
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005029 case tok::kw___private:
5030 case tok::kw___local:
5031 case tok::kw___global:
5032 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005033 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005034 case tok::kw___read_only:
5035 case tok::kw___read_write:
5036 case tok::kw___write_only:
Alexey Bader954ba212016-04-08 13:40:33 +00005037#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00005038#include "clang/Basic/OpenCLImageTypes.def"
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005039
Eli Friedman53339e02009-06-08 23:27:34 +00005040 return true;
Anastasia Stulova314fab62019-03-28 11:47:14 +00005041
5042 case tok::kw_private:
5043 return getLangOpts().OpenCL;
Chris Lattneracd58a32006-08-06 17:24:14 +00005044 }
5045}
5046
Richard Smith35845152017-02-07 01:37:30 +00005047bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005048 TentativeParsingAction TPA(*this);
5049
5050 // Parse the C++ scope specifier.
5051 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005052 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005053 /*EnteringContext=*/true)) {
John McCall1f476a12010-02-26 08:45:28 +00005054 TPA.Revert();
5055 return false;
5056 }
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005057
5058 // Parse the constructor name.
Richard Smithaf3b3252017-05-18 19:21:48 +00005059 if (Tok.is(tok::identifier)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005060 // We already know that we have a constructor name; just consume
5061 // the token.
5062 ConsumeToken();
Richard Smithaf3b3252017-05-18 19:21:48 +00005063 } else if (Tok.is(tok::annot_template_id)) {
5064 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005065 } else {
5066 TPA.Revert();
5067 return false;
5068 }
5069
Richard Smith8f8697f2017-02-08 01:16:55 +00005070 // There may be attributes here, appertaining to the constructor name or type
5071 // we just stepped past.
5072 SkipCXX11Attributes();
5073
Richard Smith43f340f2012-03-27 23:05:05 +00005074 // Current class name must be followed by a left parenthesis.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005075 if (Tok.isNot(tok::l_paren)) {
5076 TPA.Revert();
5077 return false;
5078 }
5079 ConsumeParen();
5080
Richard Smith43f340f2012-03-27 23:05:05 +00005081 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5082 // that we have a constructor.
5083 if (Tok.is(tok::r_paren) ||
5084 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005085 TPA.Revert();
5086 return true;
5087 }
5088
Richard Smithf2163662013-09-06 00:12:20 +00005089 // A C++11 attribute here signals that we have a constructor, and is an
5090 // attribute on the first constructor parameter.
5091 if (getLangOpts().CPlusPlus11 &&
5092 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5093 /*OuterMightBeMessageSend*/ true)) {
5094 TPA.Revert();
5095 return true;
5096 }
5097
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005098 // If we need to, enter the specified scope.
5099 DeclaratorScopeObj DeclScopeObj(*this, SS);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005100 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005101 DeclScopeObj.EnterDeclaratorScope();
5102
Francois Pichet79f3a872011-01-31 04:54:32 +00005103 // Optionally skip Microsoft attributes.
John McCall084e83d2011-03-24 11:26:52 +00005104 ParsedAttributes Attrs(AttrFactory);
Francois Pichet79f3a872011-01-31 04:54:32 +00005105 MaybeParseMicrosoftAttributes(Attrs);
5106
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005107 // Check whether the next token(s) are part of a declaration
5108 // specifier, in which case we have the start of a parameter and,
5109 // therefore, we know that this is a constructor.
Richard Smithefd009d2012-03-27 00:56:56 +00005110 bool IsConstructor = false;
5111 if (isDeclarationSpecifier())
5112 IsConstructor = true;
5113 else if (Tok.is(tok::identifier) ||
5114 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5115 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5116 // This might be a parenthesized member name, but is more likely to
5117 // be a constructor declaration with an invalid argument type. Keep
5118 // looking.
5119 if (Tok.is(tok::annot_cxxscope))
Richard Smithaf3b3252017-05-18 19:21:48 +00005120 ConsumeAnnotationToken();
Richard Smithefd009d2012-03-27 00:56:56 +00005121 ConsumeToken();
5122
5123 // If this is not a constructor, we must be parsing a declarator,
Richard Smith1453e312012-03-27 01:42:32 +00005124 // which must have one of the following syntactic forms (see the
5125 // grammar extract at the start of ParseDirectDeclarator):
Richard Smithefd009d2012-03-27 00:56:56 +00005126 switch (Tok.getKind()) {
5127 case tok::l_paren:
5128 // C(X ( int));
5129 case tok::l_square:
5130 // C(X [ 5]);
5131 // C(X [ [attribute]]);
5132 case tok::coloncolon:
5133 // C(X :: Y);
5134 // C(X :: *p);
Richard Smithefd009d2012-03-27 00:56:56 +00005135 // Assume this isn't a constructor, rather than assuming it's a
5136 // constructor with an unnamed parameter of an ill-formed type.
5137 break;
5138
Richard Smith446161b2014-03-03 21:12:53 +00005139 case tok::r_paren:
5140 // C(X )
Richard Smith8f8697f2017-02-08 01:16:55 +00005141
5142 // Skip past the right-paren and any following attributes to get to
5143 // the function body or trailing-return-type.
5144 ConsumeParen();
5145 SkipCXX11Attributes();
5146
Richard Smith35845152017-02-07 01:37:30 +00005147 if (DeductionGuide) {
5148 // C(X) -> ... is a deduction guide.
Richard Smith8f8697f2017-02-08 01:16:55 +00005149 IsConstructor = Tok.is(tok::arrow);
Richard Smith35845152017-02-07 01:37:30 +00005150 break;
5151 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005152 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
Richard Smith446161b2014-03-03 21:12:53 +00005153 // Assume these were meant to be constructors:
5154 // C(X) : (the name of a bit-field cannot be parenthesized).
5155 // C(X) try (this is otherwise ill-formed).
5156 IsConstructor = true;
5157 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005158 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
Richard Smith446161b2014-03-03 21:12:53 +00005159 // If we have a constructor name within the class definition,
5160 // assume these were meant to be constructors:
5161 // C(X) {
5162 // C(X) ;
5163 // ... because otherwise we would be declaring a non-static data
5164 // member that is ill-formed because it's of the same type as its
5165 // surrounding class.
5166 //
5167 // FIXME: We can actually do this whether or not the name is qualified,
5168 // because if it is qualified in this context it must be being used as
Richard Smith35845152017-02-07 01:37:30 +00005169 // a constructor name.
Richard Smith446161b2014-03-03 21:12:53 +00005170 // currently, so we're somewhat conservative here.
5171 IsConstructor = IsUnqualified;
5172 }
5173 break;
5174
Richard Smithefd009d2012-03-27 00:56:56 +00005175 default:
5176 IsConstructor = true;
5177 break;
5178 }
5179 }
5180
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005181 TPA.Revert();
5182 return IsConstructor;
5183}
Chris Lattnerb9093cd2006-08-04 04:39:53 +00005184
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005185/// ParseTypeQualifierListOpt
Dawn Perchik335e16b2010-09-03 01:29:35 +00005186/// type-qualifier-list: [C99 6.7.5]
5187/// type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005188/// [vendor] attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005189/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005190/// type-qualifier-list type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005191/// [vendor] type-qualifier-list attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005192/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005193/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
Aaron Ballman08b06592014-07-22 12:44:22 +00005194/// [ only if AttReqs & AR_CXX11AttributesParsed ]
5195/// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5196/// AttrRequirements bitmask values.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005197void Parser::ParseTypeQualifierListOpt(
5198 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5199 bool IdentifierRequired,
5200 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
Aaron Ballman606093a2017-10-15 15:01:42 +00005201 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005202 isCXX11AttributeSpecifier()) {
John McCall084e83d2011-03-24 11:26:52 +00005203 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith3dff2512012-04-10 03:25:07 +00005204 ParseCXX11Attributes(attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005205 DS.takeAttributesFrom(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005206 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005207
5208 SourceLocation EndLoc;
5209
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005210 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00005211 bool isInvalid = false;
Craig Topper161e4db2014-05-21 06:02:52 +00005212 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00005213 unsigned DiagID = 0;
Chris Lattner60809f52006-11-28 05:18:46 +00005214 SourceLocation Loc = Tok.getLocation();
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005215
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005216 switch (Tok.getKind()) {
Douglas Gregor28c78432010-08-27 17:35:51 +00005217 case tok::code_completion:
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005218 if (CodeCompletionHandler)
5219 (*CodeCompletionHandler)();
5220 else
5221 Actions.CodeCompleteTypeQualifiers(DS);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00005222 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00005223
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005224 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00005225 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005226 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005227 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005228 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00005229 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005230 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005231 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005232 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00005233 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005234 getLangOpts());
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005235 break;
Richard Smith8e1ac332013-03-28 01:55:44 +00005236 case tok::kw__Atomic:
5237 if (!AtomicAllowed)
5238 goto DoneWithTypeQuals;
5239 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5240 getLangOpts());
5241 break;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005242
5243 // OpenCL qualifiers:
Anastasia Stulova948e37c2019-03-25 11:54:02 +00005244 case tok::kw_private:
Anastasia Stulova314fab62019-03-28 11:47:14 +00005245 if (!getLangOpts().OpenCL)
5246 goto DoneWithTypeQuals;
5247 LLVM_FALLTHROUGH;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005248 case tok::kw___private:
5249 case tok::kw___global:
5250 case tok::kw___local:
5251 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005252 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005253 case tok::kw___read_only:
5254 case tok::kw___write_only:
5255 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00005256 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005257 break;
5258
Andrey Bokhanko45d41322016-05-11 18:38:21 +00005259 case tok::kw___unaligned:
5260 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5261 getLangOpts());
5262 break;
Aaron Ballman317a77f2013-05-22 23:25:32 +00005263 case tok::kw___uptr:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005264 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
Alp Toker62c5b572013-11-26 01:30:10 +00005265 // with the MS modifier keyword.
Aaron Ballman08b06592014-07-22 12:44:22 +00005266 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
Alp Toker47642d22013-12-03 06:13:01 +00005267 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5268 if (TryKeywordIdentFallback(false))
5269 continue;
Alp Toker62c5b572013-11-26 01:30:10 +00005270 }
Galina Kistanova77674252017-06-01 21:15:34 +00005271 LLVM_FALLTHROUGH;
Alp Toker62c5b572013-11-26 01:30:10 +00005272 case tok::kw___sptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005273 case tok::kw___w64:
Steve Narofff9c29d42008-12-25 14:41:26 +00005274 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005275 case tok::kw___ptr32:
Steve Naroff44ac7772008-12-25 14:16:32 +00005276 case tok::kw___cdecl:
5277 case tok::kw___stdcall:
5278 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005279 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005280 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005281 case tok::kw___vectorcall:
Aaron Ballman08b06592014-07-22 12:44:22 +00005282 if (AttrReqs & AR_DeclspecAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005283 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00005284 continue;
5285 }
5286 goto DoneWithTypeQuals;
Dawn Perchik335e16b2010-09-03 01:29:35 +00005287 case tok::kw___pascal:
Aaron Ballman08b06592014-07-22 12:44:22 +00005288 if (AttrReqs & AR_VendorAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005289 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00005290 continue;
5291 }
5292 goto DoneWithTypeQuals;
Douglas Gregor261a89b2015-06-19 17:51:05 +00005293
5294 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005295 case tok::kw__Nonnull:
5296 case tok::kw__Nullable:
5297 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005298 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5299 continue;
5300
Douglas Gregorab209d82015-07-07 03:58:42 +00005301 // Objective-C 'kindof' types.
5302 case tok::kw___kindof:
5303 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00005304 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00005305 (void)ConsumeToken();
5306 continue;
5307
Chris Lattnere37e2332006-08-15 04:50:22 +00005308 case tok::kw___attribute:
Aaron Ballman08b06592014-07-22 12:44:22 +00005309 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5310 // When GNU attributes are expressly forbidden, diagnose their usage.
5311 Diag(Tok, diag::err_attributes_not_allowed);
5312
5313 // Parse the attributes even if they are rejected to ensure that error
5314 // recovery is graceful.
5315 if (AttrReqs & AR_GNUAttributesParsed ||
5316 AttrReqs & AR_GNUAttributesParsedAndRejected) {
John McCall53fa7142010-12-24 02:08:15 +00005317 ParseGNUAttributes(DS.getAttributes());
Chris Lattnercf0bab22008-12-18 07:02:59 +00005318 continue; // do *not* consume the next token!
5319 }
5320 // otherwise, FALL THROUGH!
Galina Kistanova77674252017-06-01 21:15:34 +00005321 LLVM_FALLTHROUGH;
Chris Lattnercf0bab22008-12-18 07:02:59 +00005322 default:
Steve Naroff44ac7772008-12-25 14:16:32 +00005323 DoneWithTypeQuals:
Chris Lattnercf0bab22008-12-18 07:02:59 +00005324 // If this is not a type-qualifier token, we're done reading type
5325 // qualifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00005326 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005327 if (EndLoc.isValid())
5328 DS.SetRangeEnd(EndLoc);
Chris Lattnercf0bab22008-12-18 07:02:59 +00005329 return;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005330 }
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00005331
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005332 // If the specifier combination wasn't legal, issue a diagnostic.
5333 if (isInvalid) {
5334 assert(PrevSpec && "Method did not return previous specifier!");
Chris Lattner6d29c102008-11-18 07:48:38 +00005335 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005336 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005337 EndLoc = ConsumeToken();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005338 }
5339}
5340
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005341/// ParseDeclarator - Parse and verify a newly-initialized declarator.
5342///
5343void Parser::ParseDeclarator(Declarator &D) {
5344 /// This implements the 'declarator' production in the C grammar, then checks
5345 /// for well-formedness and issues diagnostics.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005346 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005347}
5348
Richard Smith0b350b92014-10-28 16:55:02 +00005349static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
Faisal Vali421b2d12017-12-29 05:41:00 +00005350 DeclaratorContext TheContext) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005351 if (Kind == tok::star || Kind == tok::caret)
5352 return true;
5353
Xiuli Pan9c14e282016-01-09 12:53:17 +00005354 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5355 return true;
5356
Richard Smith0efa75c2012-03-29 01:16:42 +00005357 if (!Lang.CPlusPlus)
5358 return false;
5359
Richard Smith0b350b92014-10-28 16:55:02 +00005360 if (Kind == tok::amp)
5361 return true;
5362
5363 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5364 // But we must not parse them in conversion-type-ids and new-type-ids, since
5365 // those can be legitimately followed by a && operator.
5366 // (The same thing can in theory happen after a trailing-return-type, but
5367 // since those are a C++11 feature, there is no rejects-valid issue there.)
5368 if (Kind == tok::ampamp)
Faisal Vali421b2d12017-12-29 05:41:00 +00005369 return Lang.CPlusPlus11 ||
5370 (TheContext != DeclaratorContext::ConversionIdContext &&
5371 TheContext != DeclaratorContext::CXXNewContext);
Richard Smith0b350b92014-10-28 16:55:02 +00005372
5373 return false;
Richard Smith0efa75c2012-03-29 01:16:42 +00005374}
5375
Xiuli Pan9c14e282016-01-09 12:53:17 +00005376// Indicates whether the given declarator is a pipe declarator.
5377static bool isPipeDeclerator(const Declarator &D) {
5378 const unsigned NumTypes = D.getNumTypeObjects();
5379
5380 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5381 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5382 return true;
5383
5384 return false;
5385}
5386
Sebastian Redlbd150f42008-11-21 19:14:01 +00005387/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5388/// is parsed by the function passed to it. Pass null, and the direct-declarator
5389/// isn't parsed at all, making this function effectively parse the C++
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005390/// ptr-operator production.
5391///
Richard Smith09f76ee2011-10-19 21:33:05 +00005392/// If the grammar of this construct is extended, matching changes must also be
Richard Smith1453e312012-03-27 01:42:32 +00005393/// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5394/// isConstructorDeclarator.
Richard Smith09f76ee2011-10-19 21:33:05 +00005395///
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005396/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5397/// [C] pointer[opt] direct-declarator
5398/// [C++] direct-declarator
5399/// [C++] ptr-operator declarator
Chris Lattner6c7416c2006-08-07 00:19:33 +00005400///
5401/// pointer: [C99 6.7.5]
5402/// '*' type-qualifier-list[opt]
5403/// '*' type-qualifier-list[opt] pointer
5404///
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005405/// ptr-operator:
5406/// '*' cv-qualifier-seq[opt]
5407/// '&'
Sebastian Redled0f3b02009-03-15 22:02:01 +00005408/// [C++0x] '&&'
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005409/// [GNU] '&' restrict[opt] attributes[opt]
Sebastian Redled0f3b02009-03-15 22:02:01 +00005410/// [GNU?] '&&' restrict[opt] attributes[opt]
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005411/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
Sebastian Redlbd150f42008-11-21 19:14:01 +00005412void Parser::ParseDeclaratorInternal(Declarator &D,
5413 DirectDeclParseFunction DirectDeclParser) {
Douglas Gregor66a985d2009-08-26 14:27:30 +00005414 if (Diags.hasAllExtensionsSilenced())
5415 D.setExtension();
Chad Rosierc1183952012-06-26 22:30:43 +00005416
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005417 // C++ member pointers start with a '::' or a nested-name.
5418 // Member pointers get special handling, since there's no place for the
5419 // scope spec in the generic path below.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005420 if (getLangOpts().CPlusPlus &&
Richard Smith83c2ecf2016-02-02 23:34:49 +00005421 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
Serge Pavlov458ea762014-07-16 05:16:52 +00005422 (Tok.is(tok::identifier) &&
5423 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
Chris Lattner803802d2009-03-24 17:04:48 +00005424 Tok.is(tok::annot_cxxscope))) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005425 bool EnteringContext =
5426 D.getContext() == DeclaratorContext::FileContext ||
5427 D.getContext() == DeclaratorContext::MemberContext;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005428 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005429 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005430
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +00005431 if (SS.isNotEmpty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005432 if (Tok.isNot(tok::star)) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005433 // The scope spec really belongs to the direct-declarator.
Richard Smith5f044ad2013-01-08 22:43:49 +00005434 if (D.mayHaveIdentifier())
5435 D.getCXXScopeSpec() = SS;
5436 else
5437 AnnotateScopeToken(SS, true);
5438
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005439 if (DirectDeclParser)
5440 (this->*DirectDeclParser)(D);
5441 return;
5442 }
5443
5444 SourceLocation Loc = ConsumeToken();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005445 D.SetRangeEnd(Loc);
John McCall084e83d2011-03-24 11:26:52 +00005446 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005447 ParseTypeQualifierListOpt(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005448 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005449
5450 // Recurse to parse whatever is left.
5451 ParseDeclaratorInternal(D, DirectDeclParser);
5452
5453 // Sema will have to catch (syntactically invalid) pointers into global
5454 // scope. It has to catch pointers into namespace scope anyway.
Erich Keanec480f302018-07-12 21:09:05 +00005455 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005456 SS, DS.getTypeQualifiers(), DS.getEndLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005457 std::move(DS.getAttributes()),
5458 /* Don't replace range end. */ SourceLocation());
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005459 return;
5460 }
5461 }
5462
5463 tok::TokenKind Kind = Tok.getKind();
Xiuli Pan9c14e282016-01-09 12:53:17 +00005464
5465 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
Xiuli Pan11e13f62016-02-26 03:13:03 +00005466 DeclSpec DS(AttrFactory);
5467 ParseTypeQualifierListOpt(DS);
Xiuli Pan9c14e282016-01-09 12:53:17 +00005468
5469 D.AddTypeInfo(
5470 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005471 std::move(DS.getAttributes()), SourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00005472 }
5473
Steve Naroffec33ed92008-08-27 16:04:49 +00005474 // Not a pointer, C++ reference, or block.
Richard Smith0b350b92014-10-28 16:55:02 +00005475 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00005476 if (DirectDeclParser)
5477 (this->*DirectDeclParser)(D);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005478 return;
5479 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005480
Sebastian Redled0f3b02009-03-15 22:02:01 +00005481 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5482 // '&&' -> rvalue reference
Sebastian Redl3b27be62009-03-23 00:00:23 +00005483 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005484 D.SetRangeEnd(Loc);
Bill Wendling3708c182007-05-27 10:15:43 +00005485
Chris Lattner9eac9312009-03-27 04:18:06 +00005486 if (Kind == tok::star || Kind == tok::caret) {
Chris Lattner788404f2008-02-21 01:32:26 +00005487 // Is a pointer.
John McCall084e83d2011-03-24 11:26:52 +00005488 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005489
Aaron Ballman08b06592014-07-22 12:44:22 +00005490 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5491 // C++11 attributes are allowed.
5492 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
Faisal Vali421b2d12017-12-29 05:41:00 +00005493 ((D.getContext() != DeclaratorContext::CXXNewContext)
5494 ? AR_GNUAttributesParsed
5495 : AR_GNUAttributesParsedAndRejected);
Aaron Ballman08b06592014-07-22 12:44:22 +00005496 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005497 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005498
Bill Wendling3708c182007-05-27 10:15:43 +00005499 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005500 ParseDeclaratorInternal(D, DirectDeclParser);
Steve Naroffec33ed92008-08-27 16:04:49 +00005501 if (Kind == tok::star)
5502 // Remember that we parsed a pointer type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005503 D.AddTypeInfo(DeclaratorChunk::getPointer(
5504 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5505 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5506 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5507 std::move(DS.getAttributes()), SourceLocation());
Steve Naroffec33ed92008-08-27 16:04:49 +00005508 else
5509 // Remember that we parsed a Block type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005510 D.AddTypeInfo(
5511 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5512 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005513 } else {
5514 // Is a reference
John McCall084e83d2011-03-24 11:26:52 +00005515 DeclSpec DS(AttrFactory);
Bill Wendling93efb222007-06-02 23:28:54 +00005516
Sebastian Redl3b27be62009-03-23 00:00:23 +00005517 // Complain about rvalue references in C++03, but then go on and build
5518 // the declarator.
Richard Smith5d164bc2011-10-15 05:09:34 +00005519 if (Kind == tok::ampamp)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005520 Diag(Loc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00005521 diag::warn_cxx98_compat_rvalue_reference :
5522 diag::ext_rvalue_reference);
Sebastian Redl3b27be62009-03-23 00:00:23 +00005523
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005524 // GNU-style and C++11 attributes are allowed here, as is restrict.
5525 ParseTypeQualifierListOpt(DS);
5526 D.ExtendWithDeclSpec(DS);
5527
Bill Wendling93efb222007-06-02 23:28:54 +00005528 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5529 // cv-qualifiers are introduced through the use of a typedef or of a
5530 // template type argument, in which case the cv-qualifiers are ignored.
Bill Wendling93efb222007-06-02 23:28:54 +00005531 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5532 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5533 Diag(DS.getConstSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005534 diag::err_invalid_reference_qualifier_application) << "const";
Bill Wendling93efb222007-06-02 23:28:54 +00005535 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5536 Diag(DS.getVolatileSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005537 diag::err_invalid_reference_qualifier_application) << "volatile";
Richard Smith8e1ac332013-03-28 01:55:44 +00005538 // 'restrict' is permitted as an extension.
5539 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5540 Diag(DS.getAtomicSpecLoc(),
5541 diag::err_invalid_reference_qualifier_application) << "_Atomic";
Bill Wendling93efb222007-06-02 23:28:54 +00005542 }
Bill Wendling3708c182007-05-27 10:15:43 +00005543
5544 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005545 ParseDeclaratorInternal(D, DirectDeclParser);
Bill Wendling3708c182007-05-27 10:15:43 +00005546
Douglas Gregor66583c52008-11-03 15:51:28 +00005547 if (D.getNumTypeObjects() > 0) {
5548 // C++ [dcl.ref]p4: There shall be no references to references.
5549 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5550 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
Chris Lattnerebad6a22008-11-19 07:37:42 +00005551 if (const IdentifierInfo *II = D.getIdentifier())
5552 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5553 << II;
5554 else
5555 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5556 << "type name";
Douglas Gregor66583c52008-11-03 15:51:28 +00005557
Sebastian Redlbd150f42008-11-21 19:14:01 +00005558 // Once we've complained about the reference-to-reference, we
Douglas Gregor66583c52008-11-03 15:51:28 +00005559 // can go ahead and build the (technically ill-formed)
5560 // declarator: reference collapsing will take care of it.
5561 }
5562 }
5563
Richard Smith8e1ac332013-03-28 01:55:44 +00005564 // Remember that we parsed a reference type.
Chris Lattner788404f2008-02-21 01:32:26 +00005565 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
Sebastian Redled0f3b02009-03-15 22:02:01 +00005566 Kind == tok::amp),
Erich Keanec480f302018-07-12 21:09:05 +00005567 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005568 }
Chris Lattner6c7416c2006-08-07 00:19:33 +00005569}
5570
Richard Trieuf4b81d02014-06-24 23:14:24 +00005571// When correcting from misplaced brackets before the identifier, the location
5572// is saved inside the declarator so that other diagnostic messages can use
5573// them. This extracts and returns that location, or returns the provided
5574// location if a stored location does not exist.
5575static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5576 SourceLocation Loc) {
5577 if (D.getName().StartLocation.isInvalid() &&
5578 D.getName().EndLocation.isValid())
5579 return D.getName().EndLocation;
5580
5581 return Loc;
5582}
5583
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005584/// ParseDirectDeclarator
5585/// direct-declarator: [C99 6.7.5]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005586/// [C99] identifier
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005587/// '(' declarator ')'
5588/// [GNU] '(' attributes declarator ')'
Chris Lattnere8074e62006-08-06 18:30:15 +00005589/// [C90] direct-declarator '[' constant-expression[opt] ']'
5590/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5591/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5592/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5593/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005594/// [C++11] direct-declarator '[' constant-expression[opt] ']'
5595/// attribute-specifier-seq[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005596/// direct-declarator '(' parameter-type-list ')'
5597/// direct-declarator '(' identifier-list[opt] ')'
5598/// [GNU] direct-declarator '(' parameter-forward-declarations
5599/// parameter-type-list[opt] ')'
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00005600/// [C++] direct-declarator '(' parameter-declaration-clause ')'
5601/// cv-qualifier-seq[opt] exception-specification[opt]
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005602/// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5603/// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5604/// ref-qualifier[opt] exception-specification[opt]
Douglas Gregor61956c42008-10-31 09:07:45 +00005605/// [C++] declarator-id
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005606/// [C++11] declarator-id attribute-specifier-seq[opt]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005607///
5608/// declarator-id: [C++ 8]
Douglas Gregor27b4c162010-12-23 22:44:42 +00005609/// '...'[opt] id-expression
Douglas Gregor831c93f2008-11-05 20:51:48 +00005610/// '::'[opt] nested-name-specifier[opt] type-name
5611///
5612/// id-expression: [C++ 5.1]
5613/// unqualified-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005614/// qualified-id
Douglas Gregor831c93f2008-11-05 20:51:48 +00005615///
5616/// unqualified-id: [C++ 5.1]
Mike Stump11289f42009-09-09 15:08:12 +00005617/// identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005618/// operator-function-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005619/// conversion-function-id
Mike Stump11289f42009-09-09 15:08:12 +00005620/// '~' class-name
Douglas Gregor7f741122009-02-25 19:37:18 +00005621/// template-id
Argyrios Kyrtzidise4426352008-11-07 22:02:30 +00005622///
Richard Smithbdb84f32016-07-22 23:36:59 +00005623/// C++17 adds the following, which we also handle here:
5624///
5625/// simple-declaration:
5626/// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5627///
Richard Smith1453e312012-03-27 01:42:32 +00005628/// Note, any additional constructs added here may need corresponding changes
5629/// in isConstructorDeclarator.
Chris Lattneracd58a32006-08-06 17:24:14 +00005630void Parser::ParseDirectDeclarator(Declarator &D) {
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005631 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005632
David Blaikiebbafb8a2012-03-11 07:00:24 +00005633 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
Richard Smithbdb84f32016-07-22 23:36:59 +00005634 // This might be a C++17 structured binding.
5635 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5636 D.getCXXScopeSpec().isEmpty())
5637 return ParseDecompositionDeclarator(D);
5638
Serge Pavlov458ea762014-07-16 05:16:52 +00005639 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5640 // this context it is a bitfield. Also in range-based for statement colon
5641 // may delimit for-range-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00005642 ColonProtectionRAIIObject X(
5643 *this, D.getContext() == DeclaratorContext::MemberContext ||
5644 (D.getContext() == DeclaratorContext::ForContext &&
5645 getLangOpts().CPlusPlus11));
Serge Pavlov458ea762014-07-16 05:16:52 +00005646
Douglas Gregor7861a802009-11-03 01:35:08 +00005647 // ParseDeclaratorInternal might already have parsed the scope.
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005648 if (D.getCXXScopeSpec().isEmpty()) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005649 bool EnteringContext =
5650 D.getContext() == DeclaratorContext::FileContext ||
5651 D.getContext() == DeclaratorContext::MemberContext;
David Blaikieefdccaa2016-01-15 23:43:34 +00005652 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005653 EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005654 }
5655
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005656 if (D.getCXXScopeSpec().isValid()) {
Richard Smith64e033f2015-01-15 00:48:52 +00005657 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5658 D.getCXXScopeSpec()))
John McCall2b058ef2009-12-11 20:04:54 +00005659 // Change the declaration context for name lookup, until this function
5660 // is exited (and the declarator has been parsed).
5661 DeclScopeObj.EnterDeclaratorScope();
Alex Lorenze151f0102016-12-07 10:24:44 +00005662 else if (getObjCDeclContext()) {
5663 // Ensure that we don't interpret the next token as an identifier when
5664 // dealing with declarations in an Objective-C container.
5665 D.SetIdentifier(nullptr, Tok.getLocation());
5666 D.setInvalidType(true);
5667 ConsumeToken();
5668 goto PastIdentifier;
5669 }
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005670 }
5671
Douglas Gregor27b4c162010-12-23 22:44:42 +00005672 // C++0x [dcl.fct]p14:
Faisal Vali8435a692014-12-04 12:40:21 +00005673 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5674 // parameter-declaration-clause without a preceding comma. In this case,
5675 // the ellipsis is parsed as part of the abstract-declarator if the type
5676 // of the parameter either names a template parameter pack that has not
5677 // been expanded or contains auto; otherwise, it is parsed as part of the
5678 // parameter-declaration-clause.
Richard Smith0efa75c2012-03-29 01:16:42 +00005679 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00005680 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5681 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5682 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
Douglas Gregor27b4c162010-12-23 22:44:42 +00005683 NextToken().is(tok::r_paren) &&
Richard Smithb19337f2013-02-20 20:19:27 +00005684 !D.hasGroupingParens() &&
Faisal Vali8435a692014-12-04 12:40:21 +00005685 !Actions.containsUnexpandedParameterPacks(D) &&
Faisal Vali090da2d2018-01-01 18:23:28 +00005686 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005687 SourceLocation EllipsisLoc = ConsumeToken();
Richard Smith0b350b92014-10-28 16:55:02 +00005688 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005689 // The ellipsis was put in the wrong place. Recover, and explain to
5690 // the user what they should have done.
5691 ParseDeclarator(D);
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00005692 if (EllipsisLoc.isValid())
5693 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00005694 return;
5695 } else
5696 D.setEllipsisLoc(EllipsisLoc);
5697
5698 // The ellipsis can't be followed by a parenthesized declarator. We
5699 // check for that in ParseParenDeclarator, after we have disambiguated
5700 // the l_paren token.
5701 }
5702
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005703 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5704 tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00005705 // We found something that indicates the start of an unqualified-id.
5706 // Parse that unqualified-id.
John McCall84821e72010-04-13 06:39:49 +00005707 bool AllowConstructorName;
Richard Smith35845152017-02-07 01:37:30 +00005708 bool AllowDeductionGuide;
5709 if (D.getDeclSpec().hasTypeSpecifier()) {
John McCall84821e72010-04-13 06:39:49 +00005710 AllowConstructorName = false;
Richard Smith35845152017-02-07 01:37:30 +00005711 AllowDeductionGuide = false;
5712 } else if (D.getCXXScopeSpec().isSet()) {
John McCall84821e72010-04-13 06:39:49 +00005713 AllowConstructorName =
Faisal Vali421b2d12017-12-29 05:41:00 +00005714 (D.getContext() == DeclaratorContext::FileContext ||
5715 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005716 AllowDeductionGuide = false;
5717 } else {
Faisal Vali421b2d12017-12-29 05:41:00 +00005718 AllowConstructorName =
5719 (D.getContext() == DeclaratorContext::MemberContext);
Fangrui Song6907ce22018-07-30 19:24:48 +00005720 AllowDeductionGuide =
Faisal Vali421b2d12017-12-29 05:41:00 +00005721 (D.getContext() == DeclaratorContext::FileContext ||
5722 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005723 }
John McCall84821e72010-04-13 06:39:49 +00005724
Richard Smith64e033f2015-01-15 00:48:52 +00005725 bool HadScope = D.getCXXScopeSpec().isValid();
Chad Rosierc1183952012-06-26 22:30:43 +00005726 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5727 /*EnteringContext=*/true,
David Blaikieefdccaa2016-01-15 23:43:34 +00005728 /*AllowDestructorName=*/true, AllowConstructorName,
Richard Smithc08b6932018-04-27 02:00:13 +00005729 AllowDeductionGuide, nullptr, nullptr,
Richard Smith35845152017-02-07 01:37:30 +00005730 D.getName()) ||
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005731 // Once we're past the identifier, if the scope was bad, mark the
5732 // whole declarator bad.
5733 D.getCXXScopeSpec().isInvalid()) {
Craig Topper161e4db2014-05-21 06:02:52 +00005734 D.SetIdentifier(nullptr, Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005735 D.setInvalidType(true);
Douglas Gregor7861a802009-11-03 01:35:08 +00005736 } else {
Richard Smith64e033f2015-01-15 00:48:52 +00005737 // ParseUnqualifiedId might have parsed a scope specifier during error
5738 // recovery. If it did so, enter that scope.
5739 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5740 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5741 D.getCXXScopeSpec()))
5742 DeclScopeObj.EnterDeclaratorScope();
5743
Douglas Gregor7861a802009-11-03 01:35:08 +00005744 // Parsed the unqualified-id; update range information and move along.
5745 if (D.getSourceRange().getBegin().isInvalid())
5746 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5747 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005748 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005749 goto PastIdentifier;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005750 }
Richard Smithd63db6e2015-12-19 02:40:19 +00005751
5752 if (D.getCXXScopeSpec().isNotEmpty()) {
5753 // We have a scope specifier but no following unqualified-id.
5754 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5755 diag::err_expected_unqualified_id)
5756 << /*C++*/1;
5757 D.SetIdentifier(nullptr, Tok.getLocation());
5758 goto PastIdentifier;
5759 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005760 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005761 assert(!getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005762 "There's a C++-specific check for tok::identifier above");
5763 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5764 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Richard Trieu2664dc12014-05-05 22:06:50 +00005765 D.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005766 ConsumeToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00005767 goto PastIdentifier;
Richard Smith74639b12017-05-19 01:54:59 +00005768 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5769 // We're not allowed an identifier here, but we got one. Try to figure out
5770 // if the user was trying to attach a name to the type, or whether the name
5771 // is some unrelated trailing syntax.
5772 bool DiagnoseIdentifier = false;
5773 if (D.hasGroupingParens())
5774 // An identifier within parens is unlikely to be intended to be anything
5775 // other than a name being "declared".
5776 DiagnoseIdentifier = true;
Richard Smith77a9c602018-02-28 03:02:23 +00005777 else if (D.getContext() == DeclaratorContext::TemplateArgContext)
Richard Smith74639b12017-05-19 01:54:59 +00005778 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5779 DiagnoseIdentifier =
5780 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali421b2d12017-12-29 05:41:00 +00005781 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5782 D.getContext() == DeclaratorContext::AliasTemplateContext)
Richard Smith74639b12017-05-19 01:54:59 +00005783 // The most likely error is that the ';' was forgotten.
5784 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
Richard Smithe303e352018-02-02 22:24:54 +00005785 else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5786 D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
Richard Smith74639b12017-05-19 01:54:59 +00005787 !isCXX11VirtSpecifier(Tok))
5788 DiagnoseIdentifier = NextToken().isOneOf(
5789 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5790 if (DiagnoseIdentifier) {
Richard Smithf39720b2013-10-13 22:12:28 +00005791 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5792 << FixItHint::CreateRemoval(Tok.getLocation());
Craig Topper161e4db2014-05-21 06:02:52 +00005793 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithf39720b2013-10-13 22:12:28 +00005794 ConsumeToken();
5795 goto PastIdentifier;
5796 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005797 }
Richard Smith0efa75c2012-03-29 01:16:42 +00005798
Douglas Gregor7861a802009-11-03 01:35:08 +00005799 if (Tok.is(tok::l_paren)) {
Richard Smithe303e352018-02-02 22:24:54 +00005800 // If this might be an abstract-declarator followed by a direct-initializer,
5801 // check whether this is a valid declarator chunk. If it can't be, assume
5802 // that it's an initializer instead.
5803 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5804 RevertingTentativeParsingAction PA(*this);
5805 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5806 TPResult::False) {
5807 D.SetIdentifier(nullptr, Tok.getLocation());
5808 goto PastIdentifier;
5809 }
5810 }
5811
Chris Lattneracd58a32006-08-06 17:24:14 +00005812 // direct-declarator: '(' declarator ')'
Chris Lattnere37e2332006-08-15 04:50:22 +00005813 // direct-declarator: '(' attributes declarator ')'
Chris Lattneracd58a32006-08-06 17:24:14 +00005814 // Example: 'char (*X)' or 'int (*XX)(void)'
5815 ParseParenDeclarator(D);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005816
5817 // If the declarator was parenthesized, we entered the declarator
5818 // scope when parsing the parenthesized declarator, then exited
5819 // the scope already. Re-enter the scope, if we need to.
5820 if (D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005821 // If there was an error parsing parenthesized declarator, declarator
Richard Smith0efa75c2012-03-29 01:16:42 +00005822 // scope may have been entered before. Don't do it again.
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005823 if (!D.isInvalidType() &&
Nico Weber6b05f382015-02-18 04:53:03 +00005824 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5825 D.getCXXScopeSpec()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005826 // Change the declaration context for name lookup, until this function
5827 // is exited (and the declarator has been parsed).
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005828 DeclScopeObj.EnterDeclaratorScope();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005829 }
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005830 } else if (D.mayOmitIdentifier()) {
Chris Lattneracd58a32006-08-06 17:24:14 +00005831 // This could be something simple like "int" (in which case the declarator
5832 // portion is empty), if an abstract-declarator is allowed.
Craig Topper161e4db2014-05-21 06:02:52 +00005833 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithb19337f2013-02-20 20:19:27 +00005834
5835 // The grammar for abstract-pack-declarator does not allow grouping parens.
5836 // FIXME: Revisit this once core issue 1488 is resolved.
5837 if (D.hasEllipsis() && D.hasGroupingParens())
5838 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5839 diag::ext_abstract_pack_declarator_parens);
Chris Lattneracd58a32006-08-06 17:24:14 +00005840 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00005841 if (Tok.getKind() == tok::annot_pragma_parser_crash)
David Blaikie5bd4c2a2012-08-21 18:56:49 +00005842 LLVM_BUILTIN_TRAP;
Richard Trieuf4b81d02014-06-24 23:14:24 +00005843 if (Tok.is(tok::l_square))
5844 return ParseMisplacedBracketDeclarator(D);
Faisal Vali421b2d12017-12-29 05:41:00 +00005845 if (D.getContext() == DeclaratorContext::MemberContext) {
Alex Lorenzf1278212017-04-11 15:01:53 +00005846 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5847 // treating these keyword as valid member names.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005848 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
Alex Lorenzf1278212017-04-11 15:01:53 +00005849 Tok.getIdentifierInfo() &&
5850 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5851 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5852 diag::err_expected_member_name_or_semi_objcxx_keyword)
5853 << Tok.getIdentifierInfo()
5854 << (D.getDeclSpec().isEmpty() ? SourceRange()
5855 : D.getDeclSpec().getSourceRange());
5856 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5857 D.SetRangeEnd(Tok.getLocation());
5858 ConsumeToken();
5859 goto PastIdentifier;
5860 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005861 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5862 diag::err_expected_member_name_or_semi)
Richard Trieua1342402014-05-02 23:40:32 +00005863 << (D.getDeclSpec().isEmpty() ? SourceRange()
5864 : D.getDeclSpec().getSourceRange());
Richard Trieuf4b81d02014-06-24 23:14:24 +00005865 } else if (getLangOpts().CPlusPlus) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005866 if (Tok.isOneOf(tok::period, tok::arrow))
Richard Trieu9c672672013-01-26 02:31:38 +00005867 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
Richard Trieu2f586962013-09-05 02:31:33 +00005868 else {
5869 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5870 if (Tok.isAtStartOfLine() && Loc.isValid())
5871 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5872 << getLangOpts().CPlusPlus;
5873 else
Richard Trieuf4b81d02014-06-24 23:14:24 +00005874 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5875 diag::err_expected_unqualified_id)
Richard Trieu2f586962013-09-05 02:31:33 +00005876 << getLangOpts().CPlusPlus;
5877 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005878 } else {
5879 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5880 diag::err_expected_either)
5881 << tok::identifier << tok::l_paren;
5882 }
Craig Topper161e4db2014-05-21 06:02:52 +00005883 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattner8c5dd732008-11-11 06:13:16 +00005884 D.setInvalidType(true);
Chris Lattneracd58a32006-08-06 17:24:14 +00005885 }
Mike Stump11289f42009-09-09 15:08:12 +00005886
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005887 PastIdentifier:
Chris Lattneracd58a32006-08-06 17:24:14 +00005888 assert(D.isPastIdentifier() &&
5889 "Haven't past the location of the identifier yet?");
Mike Stump11289f42009-09-09 15:08:12 +00005890
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005891 // Don't parse attributes unless we have parsed an unparenthesized name.
5892 if (D.hasName() && !D.getNumTypeObjects())
Richard Smith89645bc2013-01-02 12:01:23 +00005893 MaybeParseCXX11Attributes(D);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005894
Chris Lattneracd58a32006-08-06 17:24:14 +00005895 while (1) {
Chris Lattner76c72282007-10-09 17:33:22 +00005896 if (Tok.is(tok::l_paren)) {
David Blaikie15a430a2011-12-04 05:04:18 +00005897 // Enter function-declaration scope, limiting any declarators to the
5898 // function prototype scope, including parameter declarators.
5899 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00005900 Scope::FunctionPrototypeScope|Scope::DeclScope|
5901 (D.isFunctionDeclaratorAFunctionDeclaration()
5902 ? Scope::FunctionDeclarationScope : 0));
5903
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005904 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5905 // In such a case, check if we actually have a function declarator; if it
5906 // is not, the declarator has been fully parsed.
Richard Smith943c4402012-07-30 21:30:52 +00005907 bool IsAmbiguous = false;
Richard Smith4f605af2012-08-18 00:55:03 +00005908 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5909 // The name of the declarator, if any, is tentatively declared within
5910 // a possible direct initializer.
5911 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5912 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5913 TentativelyDeclaredIdentifiers.pop_back();
5914 if (!IsFunctionDecl)
5915 break;
5916 }
John McCall084e83d2011-03-24 11:26:52 +00005917 ParsedAttributes attrs(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005918 BalancedDelimiterTracker T(*this, tok::l_paren);
5919 T.consumeOpen();
Richard Smith943c4402012-07-30 21:30:52 +00005920 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
David Blaikie15a430a2011-12-04 05:04:18 +00005921 PrototypeScope.Exit();
Chris Lattner76c72282007-10-09 17:33:22 +00005922 } else if (Tok.is(tok::l_square)) {
Chris Lattnere8074e62006-08-06 18:30:15 +00005923 ParseBracketDeclarator(D);
Chris Lattneracd58a32006-08-06 17:24:14 +00005924 } else {
5925 break;
5926 }
5927 }
Chad Rosierc1183952012-06-26 22:30:43 +00005928}
Chris Lattneracd58a32006-08-06 17:24:14 +00005929
Richard Smithbdb84f32016-07-22 23:36:59 +00005930void Parser::ParseDecompositionDeclarator(Declarator &D) {
5931 assert(Tok.is(tok::l_square));
5932
5933 // If this doesn't look like a structured binding, maybe it's a misplaced
5934 // array declarator.
5935 // FIXME: Consume the l_square first so we don't need extra lookahead for
5936 // this.
5937 if (!(NextToken().is(tok::identifier) &&
5938 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5939 !(NextToken().is(tok::r_square) &&
5940 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5941 return ParseMisplacedBracketDeclarator(D);
5942
5943 BalancedDelimiterTracker T(*this, tok::l_square);
5944 T.consumeOpen();
5945
5946 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5947 while (Tok.isNot(tok::r_square)) {
5948 if (!Bindings.empty()) {
5949 if (Tok.is(tok::comma))
5950 ConsumeToken();
5951 else {
5952 if (Tok.is(tok::identifier)) {
5953 SourceLocation EndLoc = getEndOfPreviousToken();
5954 Diag(EndLoc, diag::err_expected)
5955 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5956 } else {
5957 Diag(Tok, diag::err_expected_comma_or_rsquare);
5958 }
5959
5960 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5961 StopAtSemi | StopBeforeMatch);
5962 if (Tok.is(tok::comma))
5963 ConsumeToken();
5964 else if (Tok.isNot(tok::identifier))
5965 break;
5966 }
5967 }
5968
5969 if (Tok.isNot(tok::identifier)) {
5970 Diag(Tok, diag::err_expected) << tok::identifier;
5971 break;
5972 }
5973
5974 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
5975 ConsumeToken();
5976 }
5977
5978 if (Tok.isNot(tok::r_square))
5979 // We've already diagnosed a problem here.
5980 T.skipToEnd();
5981 else {
5982 // C++17 does not allow the identifier-list in a structured binding
5983 // to be empty.
5984 if (Bindings.empty())
5985 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
5986
5987 T.consumeClose();
5988 }
5989
5990 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
5991 T.getCloseLocation());
5992}
5993
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005994/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5995/// only called before the identifier, so these are most likely just grouping
Mike Stump11289f42009-09-09 15:08:12 +00005996/// parens for precedence. If we find that these are actually function
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005997/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5998///
5999/// direct-declarator:
6000/// '(' declarator ')'
6001/// [GNU] '(' attributes declarator ')'
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006002/// direct-declarator '(' parameter-type-list ')'
6003/// direct-declarator '(' identifier-list[opt] ')'
6004/// [GNU] direct-declarator '(' parameter-forward-declarations
6005/// parameter-type-list[opt] ')'
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006006///
6007void Parser::ParseParenDeclarator(Declarator &D) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006008 BalancedDelimiterTracker T(*this, tok::l_paren);
6009 T.consumeOpen();
6010
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006011 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
Mike Stump11289f42009-09-09 15:08:12 +00006012
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006013 // Eat any attributes before we look at whether this is a grouping or function
6014 // declarator paren. If this is a grouping paren, the attribute applies to
6015 // the type being built up, for example:
6016 // int (__attribute__(()) *x)(long y)
6017 // If this ends up not being a grouping paren, the attribute applies to the
6018 // first argument, for example:
6019 // int (__attribute__(()) int x)
6020 // In either case, we need to eat any attributes to be able to determine what
6021 // sort of paren this is.
6022 //
John McCall084e83d2011-03-24 11:26:52 +00006023 ParsedAttributes attrs(AttrFactory);
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006024 bool RequiresArg = false;
6025 if (Tok.is(tok::kw___attribute)) {
John McCall53fa7142010-12-24 02:08:15 +00006026 ParseGNUAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006027
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006028 // We require that the argument list (if this is a non-grouping paren) be
6029 // present even if the attribute list was empty.
6030 RequiresArg = true;
6031 }
Chad Rosiereea9ca72012-12-21 21:22:20 +00006032
Steve Naroff44ac7772008-12-25 14:16:32 +00006033 // Eat any Microsoft extensions.
Chad Rosiereea9ca72012-12-21 21:22:20 +00006034 ParseMicrosoftTypeAttributes(attrs);
6035
Dawn Perchik335e16b2010-09-03 01:29:35 +00006036 // Eat any Borland extensions.
Ted Kremenek5eec2b02010-11-10 05:59:39 +00006037 if (Tok.is(tok::kw___pascal))
John McCall53fa7142010-12-24 02:08:15 +00006038 ParseBorlandTypeAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006039
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006040 // If we haven't past the identifier yet (or where the identifier would be
6041 // stored, if this is an abstract declarator), then this is probably just
6042 // grouping parens. However, if this could be an abstract-declarator, then
6043 // this could also be the start of function arguments (consider 'void()').
6044 bool isGrouping;
Mike Stump11289f42009-09-09 15:08:12 +00006045
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006046 if (!D.mayOmitIdentifier()) {
6047 // If this can't be an abstract-declarator, this *must* be a grouping
6048 // paren, because we haven't seen the identifier yet.
6049 isGrouping = true;
6050 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
Richard Smith43f340f2012-03-27 23:05:05 +00006051 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6052 NextToken().is(tok::r_paren)) || // C++ int(...)
Richard Smith2620cd92012-04-11 04:01:28 +00006053 isDeclarationSpecifier() || // 'int(int)' is a function.
6054 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006055 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6056 // considered to be a type, not a K&R identifier-list.
6057 isGrouping = false;
6058 } else {
6059 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6060 isGrouping = true;
6061 }
Mike Stump11289f42009-09-09 15:08:12 +00006062
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006063 // If this is a grouping paren, handle:
6064 // direct-declarator: '(' declarator ')'
6065 // direct-declarator: '(' attributes declarator ')'
6066 if (isGrouping) {
Richard Smith0efa75c2012-03-29 01:16:42 +00006067 SourceLocation EllipsisLoc = D.getEllipsisLoc();
6068 D.setEllipsisLoc(SourceLocation());
6069
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006070 bool hadGroupingParens = D.hasGroupingParens();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006071 D.setGroupingParens(true);
Sebastian Redlbd150f42008-11-21 19:14:01 +00006072 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006073 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006074 T.consumeClose();
Erich Keanec480f302018-07-12 21:09:05 +00006075 D.AddTypeInfo(
6076 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6077 std::move(attrs), T.getCloseLocation());
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006078
6079 D.setGroupingParens(hadGroupingParens);
Richard Smith0efa75c2012-03-29 01:16:42 +00006080
6081 // An ellipsis cannot be placed outside parentheses.
6082 if (EllipsisLoc.isValid())
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00006083 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00006084
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006085 return;
6086 }
Mike Stump11289f42009-09-09 15:08:12 +00006087
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006088 // Okay, if this wasn't a grouping paren, it must be the start of a function
6089 // argument list. Recognize that this declarator will never have an
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006090 // identifier (and remember where it would have been), then call into
6091 // ParseFunctionDeclarator to handle of argument list.
Craig Topper161e4db2014-05-21 06:02:52 +00006092 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006093
David Blaikie15a430a2011-12-04 05:04:18 +00006094 // Enter function-declaration scope, limiting any declarators to the
6095 // function prototype scope, including parameter declarators.
6096 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00006097 Scope::FunctionPrototypeScope | Scope::DeclScope |
6098 (D.isFunctionDeclaratorAFunctionDeclaration()
6099 ? Scope::FunctionDeclarationScope : 0));
Richard Smith943c4402012-07-30 21:30:52 +00006100 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
David Blaikie15a430a2011-12-04 05:04:18 +00006101 PrototypeScope.Exit();
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006102}
6103
6104/// ParseFunctionDeclarator - We are after the identifier and have parsed the
6105/// declarator D up to a paren, which indicates that we are parsing function
6106/// arguments.
Chris Lattneracd58a32006-08-06 17:24:14 +00006107///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006108/// If FirstArgAttrs is non-null, then the caller parsed those arguments
6109/// immediately after the open paren - they should be considered to be the
6110/// first argument of a parameter.
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006111///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006112/// If RequiresArg is true, then the first argument of the function is required
6113/// to be present and required to not be an identifier list.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006114///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006115/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6116/// (C++11) ref-qualifier[opt], exception-specification[opt],
6117/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
6118///
6119/// [C++11] exception-specification:
Douglas Gregor9e66af42011-07-05 16:44:18 +00006120/// dynamic-exception-specification
6121/// noexcept-specification
6122///
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006123void Parser::ParseFunctionDeclarator(Declarator &D,
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006124 ParsedAttributes &FirstArgAttrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006125 BalancedDelimiterTracker &Tracker,
Richard Smith943c4402012-07-30 21:30:52 +00006126 bool IsAmbiguous,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006127 bool RequiresArg) {
Chad Rosierc1183952012-06-26 22:30:43 +00006128 assert(getCurScope()->isFunctionPrototypeScope() &&
David Blaikie15a430a2011-12-04 05:04:18 +00006129 "Should call from a Function scope");
Douglas Gregor9e66af42011-07-05 16:44:18 +00006130 // lparen is already consumed!
6131 assert(D.isPastIdentifier() && "Should not call before identifier!");
6132
6133 // This should be true when the function has typed arguments.
6134 // Otherwise, it is treated as a K&R-style function.
6135 bool HasProto = false;
6136 // Build up an array of information about the parsed arguments.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006137 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006138 // Remember where we see an ellipsis, if any.
6139 SourceLocation EllipsisLoc;
6140
6141 DeclSpec DS(AttrFactory);
6142 bool RefQualifierIsLValueRef = true;
6143 SourceLocation RefQualifierLoc;
6144 ExceptionSpecificationType ESpecType = EST_None;
6145 SourceRange ESpecRange;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006146 SmallVector<ParsedType, 2> DynamicExceptions;
6147 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006148 ExprResult NoexceptExpr;
Hans Wennborgdcfba332015-10-06 23:40:43 +00006149 CachedTokens *ExceptionSpecTokens = nullptr;
Aaron Ballman606093a2017-10-15 15:01:42 +00006150 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith700537c2012-06-12 01:51:59 +00006151 TypeResult TrailingReturnType;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006152
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006153 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6154 EndLoc is the end location for the function declarator.
6155 They differ for trailing return types. */
6156 SourceLocation StartLoc, LocalEndLoc, EndLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006157 SourceLocation LParenLoc, RParenLoc;
6158 LParenLoc = Tracker.getOpenLocation();
6159 StartLoc = LParenLoc;
6160
Douglas Gregor9e66af42011-07-05 16:44:18 +00006161 if (isFunctionDeclaratorIdentifierList()) {
6162 if (RequiresArg)
6163 Diag(Tok, diag::err_argument_required_after_attribute);
6164
6165 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6166
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006167 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006168 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006169 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006170 EndLoc = RParenLoc;
Aaron Ballman606093a2017-10-15 15:01:42 +00006171
Fangrui Song6907ce22018-07-30 19:24:48 +00006172 // If there are attributes following the identifier list, parse them and
Aaron Ballman606093a2017-10-15 15:01:42 +00006173 // prohibit them.
6174 MaybeParseCXX11Attributes(FnAttrs);
6175 ProhibitAttributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006176 } else {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006177 if (Tok.isNot(tok::r_paren))
Fangrui Song6907ce22018-07-30 19:24:48 +00006178 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
Faisal Vali2b391ab2013-09-26 19:54:12 +00006179 EllipsisLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006180 else if (RequiresArg)
6181 Diag(Tok, diag::err_argument_required_after_attribute);
6182
Alexey Bader1f277942017-10-11 11:16:31 +00006183 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6184 || getLangOpts().OpenCL;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006185
6186 // If we have the closing ')', eat it.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006187 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006188 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006189 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006190 EndLoc = RParenLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006191
David Blaikiebbafb8a2012-03-11 07:00:24 +00006192 if (getLangOpts().CPlusPlus) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006193 // FIXME: Accept these components in any order, and produce fixits to
6194 // correct the order if the user gets it wrong. Ideally we should deal
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00006195 // with the pure-specifier in the same way.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006196
6197 // Parse cv-qualifier-seq[opt].
Aaron Ballman08b06592014-07-22 12:44:22 +00006198 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
Alex Lorenz8f4d3992017-02-13 23:19:40 +00006199 /*AtomicAllowed*/ false,
6200 /*IdentifierRequired=*/false,
6201 llvm::function_ref<void()>([&]() {
6202 Actions.CodeCompleteFunctionQualifiers(DS, D);
6203 }));
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006204 if (!DS.getSourceRange().getEnd().isInvalid()) {
6205 EndLoc = DS.getSourceRange().getEnd();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006206 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006207
6208 // Parse ref-qualifier[opt].
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006209 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
Douglas Gregor9e66af42011-07-05 16:44:18 +00006210 EndLoc = RefQualifierLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006211
Douglas Gregor3024f072012-04-16 07:05:22 +00006212 // C++11 [expr.prim.general]p3:
Chad Rosierc1183952012-06-26 22:30:43 +00006213 // If a declaration declares a member function or member function
6214 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00006215 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Chad Rosierc1183952012-06-26 22:30:43 +00006216 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00006217 // declarator.
Richard Smithad1bbb92013-03-15 00:41:52 +00006218 // FIXME: currently, "static" case isn't handled correctly.
Chad Rosierc1183952012-06-26 22:30:43 +00006219 bool IsCXX11MemberFunction =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006220 getLangOpts().CPlusPlus11 &&
Richard Smith990a6922014-01-17 21:01:18 +00006221 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
Faisal Vali421b2d12017-12-29 05:41:00 +00006222 (D.getContext() == DeclaratorContext::MemberContext
Richard Smithad1bbb92013-03-15 00:41:52 +00006223 ? !D.getDeclSpec().isFriendSpecified()
Faisal Vali421b2d12017-12-29 05:41:00 +00006224 : D.getContext() == DeclaratorContext::FileContext &&
Richard Smithad1bbb92013-03-15 00:41:52 +00006225 D.getCXXScopeSpec().isValid() &&
6226 Actions.CurContext->isRecord());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006227
6228 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6229 if (D.getDeclSpec().isConstexprSpecified() && !getLangOpts().CPlusPlus14)
6230 Q.addConst();
Anastasia Stulova5cffa452019-01-21 16:01:38 +00006231 // FIXME: Collect C++ address spaces.
6232 // If there are multiple different address spaces, the source is invalid.
6233 // Carry on using the first addr space for the qualifiers of 'this'.
6234 // The diagnostic will be given later while creating the function
6235 // prototype for the method.
6236 if (getLangOpts().OpenCLCPlusPlus) {
6237 for (ParsedAttr &attr : DS.getAttributes()) {
6238 LangAS ASIdx = attr.asOpenCLLangAS();
6239 if (ASIdx != LangAS::Default) {
6240 Q.addAddressSpace(ASIdx);
6241 break;
6242 }
6243 }
6244 }
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006245
6246 Sema::CXXThisScopeRAII ThisScope(
6247 Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6248 IsCXX11MemberFunction);
Richard Smith2331bbf2012-05-02 22:22:32 +00006249
Douglas Gregor9e66af42011-07-05 16:44:18 +00006250 // Parse exception-specification[opt].
Richard Smith0b3a4622014-11-13 20:01:57 +00006251 bool Delayed = D.isFirstDeclarationOfMember() &&
Richard Smith3ef3e892014-11-20 22:32:11 +00006252 D.isFunctionDeclaratorAFunctionDeclaration();
6253 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6254 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6255 GetLookAheadToken(1).is(tok::l_paren) &&
6256 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6257 GetLookAheadToken(3).is(tok::l_paren) &&
6258 GetLookAheadToken(4).is(tok::identifier) &&
6259 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6260 // HACK: We've got an exception-specification
6261 // noexcept(noexcept(swap(...)))
6262 // or
6263 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6264 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6265 // for 'swap' will only find the function we're currently declaring,
6266 // whereas it expects to find a non-member swap through ADL. Turn off
6267 // delayed parsing to give it a chance to find what it expects.
6268 Delayed = false;
6269 }
Richard Smith0b3a4622014-11-13 20:01:57 +00006270 ESpecType = tryParseExceptionSpecification(Delayed,
6271 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00006272 DynamicExceptions,
6273 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00006274 NoexceptExpr,
6275 ExceptionSpecTokens);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006276 if (ESpecType != EST_None)
6277 EndLoc = ESpecRange.getEnd();
6278
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006279 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6280 // after the exception-specification.
Richard Smith89645bc2013-01-02 12:01:23 +00006281 MaybeParseCXX11Attributes(FnAttrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006282
Douglas Gregor9e66af42011-07-05 16:44:18 +00006283 // Parse trailing-return-type[opt].
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006284 LocalEndLoc = EndLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006285 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00006286 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
Faisal Vali090da2d2018-01-01 18:23:28 +00006287 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006288 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006289 LocalEndLoc = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00006290 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00006291 TrailingReturnType =
6292 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006293 EndLoc = Range.getEnd();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006294 }
Aaron Ballman606093a2017-10-15 15:01:42 +00006295 } else if (standardAttributesAllowed()) {
6296 MaybeParseCXX11Attributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006297 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006298 }
6299
Reid Kleckner078aea92016-12-09 17:14:05 +00006300 // Collect non-parameter declarations from the prototype if this is a function
6301 // declaration. They will be moved into the scope of the function. Only do
6302 // this in C and not C++, where the decls will continue to live in the
6303 // surrounding context.
6304 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6305 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6306 !getLangOpts().CPlusPlus) {
6307 for (Decl *D : getCurScope()->decls()) {
6308 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6309 if (!ND || isa<ParmVarDecl>(ND))
6310 continue;
6311 DeclsInPrototype.push_back(ND);
6312 }
6313 }
6314
Douglas Gregor9e66af42011-07-05 16:44:18 +00006315 // Remember that we parsed a function type, and remember the attributes.
Erich Keanec480f302018-07-12 21:09:05 +00006316 D.AddTypeInfo(DeclaratorChunk::getFunction(
6317 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6318 ParamInfo.size(), EllipsisLoc, RParenLoc,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00006319 RefQualifierIsLValueRef, RefQualifierLoc,
6320 /*MutableLoc=*/SourceLocation(),
6321 ESpecType, ESpecRange, DynamicExceptions.data(),
6322 DynamicExceptionRanges.data(), DynamicExceptions.size(),
Erich Keanec480f302018-07-12 21:09:05 +00006323 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6324 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00006325 LocalEndLoc, D, TrailingReturnType, &DS),
Erich Keanec480f302018-07-12 21:09:05 +00006326 std::move(FnAttrs), EndLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006327}
6328
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006329/// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6330/// true if a ref-qualifier is found.
6331bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6332 SourceLocation &RefQualifierLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00006333 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006334 Diag(Tok, getLangOpts().CPlusPlus11 ?
6335 diag::warn_cxx98_compat_ref_qualifier :
6336 diag::ext_ref_qualifier);
6337
6338 RefQualifierIsLValueRef = Tok.is(tok::amp);
6339 RefQualifierLoc = ConsumeToken();
6340 return true;
6341 }
6342 return false;
6343}
6344
Douglas Gregor9e66af42011-07-05 16:44:18 +00006345/// isFunctionDeclaratorIdentifierList - This parameter list may have an
6346/// identifier list form for a K&R-style function: void foo(a,b,c)
6347///
6348/// Note that identifier-lists are only allowed for normal declarators, not for
6349/// abstract-declarators.
6350bool Parser::isFunctionDeclaratorIdentifierList() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006351 return !getLangOpts().CPlusPlus
Douglas Gregor9e66af42011-07-05 16:44:18 +00006352 && Tok.is(tok::identifier)
6353 && !TryAltiVecVectorToken()
6354 // K&R identifier lists can't have typedefs as identifiers, per C99
6355 // 6.7.5.3p11.
6356 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6357 // Identifier lists follow a really simple grammar: the identifiers can
6358 // be followed *only* by a ", identifier" or ")". However, K&R
6359 // identifier lists are really rare in the brave new modern world, and
6360 // it is very common for someone to typo a type in a non-K&R style
6361 // list. If we are presented with something like: "void foo(intptr x,
6362 // float y)", we don't want to start parsing the function declarator as
6363 // though it is a K&R style declarator just because intptr is an
6364 // invalid type.
6365 //
6366 // To handle this, we check to see if the token after the first
6367 // identifier is a "," or ")". Only then do we parse it as an
6368 // identifier list.
Bruno Cardoso Lopes218c8742016-09-13 20:04:35 +00006369 && (!Tok.is(tok::eof) &&
6370 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006371}
6372
6373/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6374/// we found a K&R-style identifier list instead of a typed parameter list.
6375///
6376/// After returning, ParamInfo will hold the parsed parameters.
6377///
6378/// identifier-list: [C99 6.7.5]
6379/// identifier
6380/// identifier-list ',' identifier
6381///
6382void Parser::ParseFunctionDeclaratorIdentifierList(
6383 Declarator &D,
Craig Topper5603df42013-07-05 19:34:19 +00006384 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006385 // If there was no identifier specified for the declarator, either we are in
6386 // an abstract-declarator, or we are in a parameter declarator which was found
6387 // to be abstract. In abstract-declarators, identifier lists are not valid:
6388 // diagnose this.
6389 if (!D.getIdentifier())
6390 Diag(Tok, diag::ext_ident_list_in_param);
6391
6392 // Maintain an efficient lookup of params we have seen so far.
6393 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6394
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006395 do {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006396 // If this isn't an identifier, report the error and skip until ')'.
6397 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00006398 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00006399 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006400 // Forget we parsed anything.
6401 ParamInfo.clear();
6402 return;
6403 }
6404
6405 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6406
6407 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6408 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6409 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6410
6411 // Verify that the argument identifier has not already been mentioned.
David Blaikie82e95a32014-11-19 07:49:47 +00006412 if (!ParamsSoFar.insert(ParmII).second) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006413 Diag(Tok, diag::err_param_redefinition) << ParmII;
6414 } else {
6415 // Remember this identifier in ParamInfo.
6416 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6417 Tok.getLocation(),
Craig Topper161e4db2014-05-21 06:02:52 +00006418 nullptr));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006419 }
6420
6421 // Eat the identifier.
6422 ConsumeToken();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006423 // The list continues if we see a comma.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006424 } while (TryConsumeToken(tok::comma));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006425}
6426
6427/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6428/// after the opening parenthesis. This function will not parse a K&R-style
6429/// identifier list.
6430///
Richard Smith2620cd92012-04-11 04:01:28 +00006431/// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6432/// caller parsed those arguments immediately after the open paren - they should
6433/// be considered to be part of the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006434///
6435/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6436/// be the location of the ellipsis, if any was parsed.
6437///
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006438/// parameter-type-list: [C99 6.7.5]
6439/// parameter-list
6440/// parameter-list ',' '...'
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006441/// [C++] parameter-list '...'
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006442///
6443/// parameter-list: [C99 6.7.5]
6444/// parameter-declaration
6445/// parameter-list ',' parameter-declaration
6446///
6447/// parameter-declaration: [C99 6.7.5]
6448/// declaration-specifiers declarator
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006449/// [C++] declaration-specifiers declarator '=' assignment-expression
Sebastian Redldb63af22012-03-14 15:54:00 +00006450/// [C++11] initializer-clause
Chris Lattnere37e2332006-08-15 04:50:22 +00006451/// [GNU] declaration-specifiers declarator attributes
Sebastian Redlf769df52009-03-24 22:27:57 +00006452/// declaration-specifiers abstract-declarator[opt]
6453/// [C++] declaration-specifiers abstract-declarator[opt]
Chris Lattner58258242008-04-10 02:22:51 +00006454/// '=' assignment-expression
Chris Lattnere37e2332006-08-15 04:50:22 +00006455/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
Richard Smith2620cd92012-04-11 04:01:28 +00006456/// [C++11] attribute-specifier-seq parameter-declaration
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006457///
Douglas Gregor9e66af42011-07-05 16:44:18 +00006458void Parser::ParseParameterDeclarationClause(
6459 Declarator &D,
Richard Smith2620cd92012-04-11 04:01:28 +00006460 ParsedAttributes &FirstArgAttrs,
Craig Topper5603df42013-07-05 19:34:19 +00006461 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006462 SourceLocation &EllipsisLoc) {
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006463 do {
6464 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6465 // before deciding this was a parameter-declaration-clause.
6466 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Chris Lattner371ed4e2008-04-06 06:57:35 +00006467 break;
Mike Stump11289f42009-09-09 15:08:12 +00006468
Chris Lattner371ed4e2008-04-06 06:57:35 +00006469 // Parse the declaration-specifiers.
John McCall28a6aea2009-11-04 02:18:39 +00006470 // Just use the ParsingDeclaration "scope" of the declarator.
John McCall084e83d2011-03-24 11:26:52 +00006471 DeclSpec DS(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006472
Richard Smith2620cd92012-04-11 04:01:28 +00006473 // Parse any C++11 attributes.
Richard Smith89645bc2013-01-02 12:01:23 +00006474 MaybeParseCXX11Attributes(DS.getAttributes());
Richard Smith2620cd92012-04-11 04:01:28 +00006475
John McCall53fa7142010-12-24 02:08:15 +00006476 // Skip any Microsoft attributes before a param.
Chad Rosierf8a2e702012-12-20 20:37:53 +00006477 MaybeParseMicrosoftAttributes(DS.getAttributes());
John McCall53fa7142010-12-24 02:08:15 +00006478
6479 SourceLocation DSStart = Tok.getLocation();
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006480
6481 // If the caller parsed attributes for the first argument, add them now.
John McCall53fa7142010-12-24 02:08:15 +00006482 // Take them so that we only apply the attributes to the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006483 // FIXME: If we can leave the attributes in the token stream somehow, we can
Richard Smith2620cd92012-04-11 04:01:28 +00006484 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6485 // too much hassle.
6486 DS.takeAttributesFrom(FirstArgAttrs);
John McCall53fa7142010-12-24 02:08:15 +00006487
Faisal Valia534f072018-04-26 00:42:40 +00006488 ParseDeclarationSpecifiers(DS);
Mike Stump11289f42009-09-09 15:08:12 +00006489
Faisal Vali2b391ab2013-09-26 19:54:12 +00006490
Fangrui Song6907ce22018-07-30 19:24:48 +00006491 // Parse the declarator. This is "PrototypeContext" or
6492 // "LambdaExprParameterContext", because we must accept either
Faisal Vali2b391ab2013-09-26 19:54:12 +00006493 // 'declarator' or 'abstract-declarator' here.
Faisal Vali421b2d12017-12-29 05:41:00 +00006494 Declarator ParmDeclarator(
6495 DS, D.getContext() == DeclaratorContext::LambdaExprContext
6496 ? DeclaratorContext::LambdaExprParameterContext
6497 : DeclaratorContext::PrototypeContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00006498 ParseDeclarator(ParmDeclarator);
Chris Lattner371ed4e2008-04-06 06:57:35 +00006499
6500 // Parse GNU attributes, if present.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006501 MaybeParseGNUAttributes(ParmDeclarator);
Mike Stump11289f42009-09-09 15:08:12 +00006502
Chris Lattner371ed4e2008-04-06 06:57:35 +00006503 // Remember this parsed parameter in ParamInfo.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006504 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
Mike Stump11289f42009-09-09 15:08:12 +00006505
Douglas Gregor4d87df52008-12-16 21:30:33 +00006506 // DefArgToks is used when the parsing of default arguments needs
6507 // to be delayed.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006508 std::unique_ptr<CachedTokens> DefArgToks;
Douglas Gregor4d87df52008-12-16 21:30:33 +00006509
Chris Lattner371ed4e2008-04-06 06:57:35 +00006510 // If no parameter was specified, verify that *something* was specified,
6511 // otherwise we have a missing type and identifier.
Craig Topper161e4db2014-05-21 06:02:52 +00006512 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
Faisal Vali2b391ab2013-09-26 19:54:12 +00006513 ParmDeclarator.getNumTypeObjects() == 0) {
Chris Lattner371ed4e2008-04-06 06:57:35 +00006514 // Completely missing, emit error.
6515 Diag(DSStart, diag::err_missing_param);
6516 } else {
6517 // Otherwise, we have something. Add it and let semantic analysis try
6518 // to grok it and add the result to the ParamInfo we are building.
Mike Stump11289f42009-09-09 15:08:12 +00006519
Richard Smith36ee9fb2014-08-11 23:30:23 +00006520 // Last chance to recover from a misplaced ellipsis in an attempted
6521 // parameter pack declaration.
6522 if (Tok.is(tok::ellipsis) &&
6523 (NextToken().isNot(tok::r_paren) ||
6524 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6525 !Actions.isUnexpandedParameterPackPermitted())) &&
6526 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6527 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6528
Chris Lattner371ed4e2008-04-06 06:57:35 +00006529 // Inform the actions module about the parameter declarator, so it gets
6530 // added to the current scope.
Richard Smith95e1fb02014-08-27 03:23:12 +00006531 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006532 // Parse the default argument, if any. We parse the default
6533 // arguments in all dialects; the semantic analysis in
6534 // ActOnParamDefaultArgument will reject the default argument in
6535 // C.
6536 if (Tok.is(tok::equal)) {
Douglas Gregor58354032008-12-24 00:01:03 +00006537 SourceLocation EqualLoc = Tok.getLocation();
6538
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006539 // Parse the default argument
Faisal Vali421b2d12017-12-29 05:41:00 +00006540 if (D.getContext() == DeclaratorContext::MemberContext) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006541 // If we're inside a class definition, cache the tokens
6542 // corresponding to the default argument. We'll actually parse
6543 // them when we see the end of the class definition.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006544 DefArgToks.reset(new CachedTokens);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006545
David Majnemer906ed272015-01-13 05:28:24 +00006546 SourceLocation ArgStartLoc = NextToken().getLocation();
Richard Smith1fff95c2013-09-12 23:28:08 +00006547 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006548 DefArgToks.reset();
Serge Pavlovb4b35782014-07-22 01:54:49 +00006549 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006550 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006551 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
David Majnemer906ed272015-01-13 05:28:24 +00006552 ArgStartLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006553 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006554 } else {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006555 // Consume the '='.
Douglas Gregor58354032008-12-24 00:01:03 +00006556 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00006557
Chad Rosierc1183952012-06-26 22:30:43 +00006558 // The argument isn't actually potentially evaluated unless it is
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006559 // used.
Faisal Valid143a0c2017-04-01 21:30:49 +00006560 EnterExpressionEvaluationContext Eval(
6561 Actions,
6562 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6563 Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006564
Sebastian Redldb63af22012-03-14 15:54:00 +00006565 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006566 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006567 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +00006568 DefArgResult = ParseBraceInitializer();
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006569 } else
Sebastian Redldb63af22012-03-14 15:54:00 +00006570 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +00006571 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006572 if (DefArgResult.isInvalid()) {
Serge Pavlovb4b35782014-07-22 01:54:49 +00006573 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Alexey Bataevee6507d2013-11-18 08:17:37 +00006574 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006575 } else {
6576 // Inform the actions module about the default argument
6577 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006578 DefArgResult.get());
Douglas Gregor4d87df52008-12-16 21:30:33 +00006579 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006580 }
6581 }
Mike Stump11289f42009-09-09 15:08:12 +00006582
6583 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
Fangrui Song6907ce22018-07-30 19:24:48 +00006584 ParmDeclarator.getIdentifierLoc(),
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006585 Param, std::move(DefArgToks)));
Chris Lattner371ed4e2008-04-06 06:57:35 +00006586 }
6587
Richard Smith36ee9fb2014-08-11 23:30:23 +00006588 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6589 if (!getLangOpts().CPlusPlus) {
6590 // We have ellipsis without a preceding ',', which is ill-formed
6591 // in C. Complain and provide the fix.
6592 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6593 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6594 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6595 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6596 // It looks like this was supposed to be a parameter pack. Warn and
6597 // point out where the ellipsis should have gone.
6598 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6599 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6600 << ParmEllipsis.isValid() << ParmEllipsis;
6601 if (ParmEllipsis.isValid()) {
6602 Diag(ParmEllipsis,
6603 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6604 } else {
6605 Diag(ParmDeclarator.getIdentifierLoc(),
6606 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6607 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6608 "...")
6609 << !ParmDeclarator.hasName();
6610 }
6611 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006612 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
Richard Smith36ee9fb2014-08-11 23:30:23 +00006613 }
6614
6615 // We can't have any more parameters after an ellipsis.
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006616 break;
6617 }
Mike Stump11289f42009-09-09 15:08:12 +00006618
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006619 // If the next token is a comma, consume it and keep reading arguments.
6620 } while (TryConsumeToken(tok::comma));
Chris Lattner6c940e62008-04-06 06:34:08 +00006621}
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006622
Chris Lattnere8074e62006-08-06 18:30:15 +00006623/// [C90] direct-declarator '[' constant-expression[opt] ']'
6624/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6625/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6626/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6627/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006628/// [C++11] direct-declarator '[' constant-expression[opt] ']'
6629/// attribute-specifier-seq[opt]
Chris Lattnere8074e62006-08-06 18:30:15 +00006630void Parser::ParseBracketDeclarator(Declarator &D) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006631 if (CheckProhibitedCXX11Attribute())
6632 return;
6633
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006634 BalancedDelimiterTracker T(*this, tok::l_square);
6635 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00006636
Chris Lattner84a11622008-12-18 07:27:21 +00006637 // C array syntax has many features, but by-far the most common is [] and [4].
6638 // This code does a fast path to handle some of the most obvious cases.
6639 if (Tok.getKind() == tok::r_square) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006640 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006641 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006642 MaybeParseCXX11Attributes(attrs);
Chad Rosierc1183952012-06-26 22:30:43 +00006643
Chris Lattner84a11622008-12-18 07:27:21 +00006644 // Remember that we parsed the empty array type.
Craig Topper161e4db2014-05-21 06:02:52 +00006645 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006646 T.getOpenLocation(),
6647 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006648 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006649 return;
6650 } else if (Tok.getKind() == tok::numeric_constant &&
6651 GetLookAheadToken(1).is(tok::r_square)) {
6652 // [4] is very common. Parse the numeric constant expression.
Richard Smithbcc22fc2012-03-09 08:00:36 +00006653 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
Chris Lattner84a11622008-12-18 07:27:21 +00006654 ConsumeToken();
6655
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006656 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006657 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006658 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006659
Chris Lattner84a11622008-12-18 07:27:21 +00006660 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006661 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006662 T.getOpenLocation(),
6663 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006664 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006665 return;
Benjamin Kramer72dae622016-02-18 15:30:24 +00006666 } else if (Tok.getKind() == tok::code_completion) {
6667 Actions.CodeCompleteBracketDeclarator(getCurScope());
6668 return cutOffParsing();
Chris Lattner84a11622008-12-18 07:27:21 +00006669 }
Mike Stump11289f42009-09-09 15:08:12 +00006670
Chris Lattnere8074e62006-08-06 18:30:15 +00006671 // If valid, this location is the position where we read the 'static' keyword.
6672 SourceLocation StaticLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006673 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006674
Chris Lattnere8074e62006-08-06 18:30:15 +00006675 // If there is a type-qualifier-list, read it now.
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006676 // Type qualifiers in an array subscript are a C99 feature.
John McCall084e83d2011-03-24 11:26:52 +00006677 DeclSpec DS(AttrFactory);
Aaron Ballman08b06592014-07-22 12:44:22 +00006678 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
Mike Stump11289f42009-09-09 15:08:12 +00006679
Chris Lattnere8074e62006-08-06 18:30:15 +00006680 // If we haven't already read 'static', check to see if there is one after the
6681 // type-qualifier-list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006682 if (!StaticLoc.isValid())
6683 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006684
Chris Lattnere8074e62006-08-06 18:30:15 +00006685 // Handle "direct-declarator [ type-qual-list[opt] * ]".
Chris Lattnere8074e62006-08-06 18:30:15 +00006686 bool isStar = false;
John McCalldadc5752010-08-24 06:29:42 +00006687 ExprResult NumElements;
Mike Stump11289f42009-09-09 15:08:12 +00006688
Chris Lattner521ff2b2008-04-06 05:26:30 +00006689 // Handle the case where we have '[*]' as the array size. However, a leading
6690 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
Sylvestre Ledru830885c2012-07-23 08:59:39 +00006691 // the token after the star is a ']'. Since stars in arrays are
Chris Lattner521ff2b2008-04-06 05:26:30 +00006692 // infrequent, use of lookahead is not costly here.
6693 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
Chris Lattnerc439f0d2008-04-06 05:27:21 +00006694 ConsumeToken(); // Eat the '*'.
Chris Lattner1906f802006-08-06 19:14:46 +00006695
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006696 if (StaticLoc.isValid()) {
Chris Lattner521ff2b2008-04-06 05:26:30 +00006697 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006698 StaticLoc = SourceLocation(); // Drop the static.
6699 }
Chris Lattner521ff2b2008-04-06 05:26:30 +00006700 isStar = true;
Chris Lattner76c72282007-10-09 17:33:22 +00006701 } else if (Tok.isNot(tok::r_square)) {
Chris Lattner84a11622008-12-18 07:27:21 +00006702 // Note, in C89, this production uses the constant-expr production instead
6703 // of assignment-expr. The only difference is that assignment-expr allows
6704 // things like '=' and '*='. Sema rejects these in C89 mode because they
6705 // are not i-c-e's, so we don't need to distinguish between the two here.
Mike Stump11289f42009-09-09 15:08:12 +00006706
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006707 // Parse the constant-expression or assignment-expression now (depending
6708 // on dialect).
David Blaikiebbafb8a2012-03-11 07:00:24 +00006709 if (getLangOpts().CPlusPlus) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006710 NumElements = ParseConstantExpression();
Eli Friedmane0afc982012-01-21 01:01:51 +00006711 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00006712 EnterExpressionEvaluationContext Unevaluated(
6713 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Kaelyn Takata15867822014-11-21 18:48:04 +00006714 NumElements =
6715 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Eli Friedmane0afc982012-01-21 01:01:51 +00006716 }
David Majnemerf9834d52014-08-08 07:21:18 +00006717 } else {
6718 if (StaticLoc.isValid()) {
6719 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6720 StaticLoc = SourceLocation(); // Drop the static.
6721 }
Chris Lattner62591722006-08-12 18:40:58 +00006722 }
Mike Stump11289f42009-09-09 15:08:12 +00006723
Chris Lattner62591722006-08-12 18:40:58 +00006724 // If there was an error parsing the assignment-expression, recover.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00006725 if (NumElements.isInvalid()) {
Chris Lattnercd2a8c52009-04-24 22:30:50 +00006726 D.setInvalidType(true);
Chris Lattner62591722006-08-12 18:40:58 +00006727 // If the expression was invalid, skip it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00006728 SkipUntil(tok::r_square, StopAtSemi);
Chris Lattner62591722006-08-12 18:40:58 +00006729 return;
Chris Lattnere8074e62006-08-06 18:30:15 +00006730 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006731
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006732 T.consumeClose();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006733
Jordan Rose303e2f12016-11-10 23:28:17 +00006734 MaybeParseCXX11Attributes(DS.getAttributes());
Alexis Hunt96d5c762009-11-21 08:43:09 +00006735
Chris Lattner84a11622008-12-18 07:27:21 +00006736 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006737 D.AddTypeInfo(
6738 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6739 isStar, NumElements.get(), T.getOpenLocation(),
6740 T.getCloseLocation()),
6741 std::move(DS.getAttributes()), T.getCloseLocation());
Chris Lattnere8074e62006-08-06 18:30:15 +00006742}
6743
Richard Trieuf4b81d02014-06-24 23:14:24 +00006744/// Diagnose brackets before an identifier.
6745void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6746 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6747 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6748
6749 SourceLocation StartBracketLoc = Tok.getLocation();
6750 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6751
6752 while (Tok.is(tok::l_square)) {
6753 ParseBracketDeclarator(TempDeclarator);
6754 }
6755
6756 // Stuff the location of the start of the brackets into the Declarator.
6757 // The diagnostics from ParseDirectDeclarator will make more sense if
6758 // they use this location instead.
6759 if (Tok.is(tok::semi))
6760 D.getName().EndLocation = StartBracketLoc;
6761
6762 SourceLocation SuggestParenLoc = Tok.getLocation();
6763
6764 // Now that the brackets are removed, try parsing the declarator again.
6765 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6766
6767 // Something went wrong parsing the brackets, in which case,
6768 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6769 // one here.
6770 if (TempDeclarator.getNumTypeObjects() == 0)
6771 return;
6772
6773 // Determine if parens will need to be suggested in the diagnostic.
6774 bool NeedParens = false;
6775 if (D.getNumTypeObjects() != 0) {
6776 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6777 case DeclaratorChunk::Pointer:
6778 case DeclaratorChunk::Reference:
6779 case DeclaratorChunk::BlockPointer:
6780 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00006781 case DeclaratorChunk::Pipe:
Richard Trieuf4b81d02014-06-24 23:14:24 +00006782 NeedParens = true;
6783 break;
6784 case DeclaratorChunk::Array:
6785 case DeclaratorChunk::Function:
6786 case DeclaratorChunk::Paren:
6787 break;
6788 }
6789 }
6790
6791 if (NeedParens) {
6792 // Create a DeclaratorChunk for the inserted parens.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006793 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Erich Keanec480f302018-07-12 21:09:05 +00006794 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
Richard Trieuf4b81d02014-06-24 23:14:24 +00006795 SourceLocation());
6796 }
6797
6798 // Adding back the bracket info to the end of the Declarator.
6799 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6800 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
Erich Keanec480f302018-07-12 21:09:05 +00006801 D.AddTypeInfo(Chunk, SourceLocation());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006802 }
6803
6804 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6805 // If parentheses are required, always suggest them.
6806 if (!D.getIdentifier() && !NeedParens)
6807 return;
6808
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006809 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
Richard Trieuf4b81d02014-06-24 23:14:24 +00006810
6811 // Generate the move bracket error message.
6812 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006813 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006814
6815 if (NeedParens) {
6816 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6817 << getLangOpts().CPlusPlus
6818 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6819 << FixItHint::CreateInsertion(EndLoc, ")")
6820 << FixItHint::CreateInsertionFromRange(
6821 EndLoc, CharSourceRange(BracketRange, true))
6822 << FixItHint::CreateRemoval(BracketRange);
6823 } else {
6824 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6825 << getLangOpts().CPlusPlus
6826 << FixItHint::CreateInsertionFromRange(
6827 EndLoc, CharSourceRange(BracketRange, true))
6828 << FixItHint::CreateRemoval(BracketRange);
6829 }
6830}
6831
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006832/// [GNU] typeof-specifier:
6833/// typeof ( expressions )
6834/// typeof ( type-name )
6835/// [GNU/C++] typeof unary-expression
Steve Naroffad373bd2007-07-31 12:34:36 +00006836///
6837void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
Chris Lattner76c72282007-10-09 17:33:22 +00006838 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006839 Token OpTok = Tok;
Steve Naroffad373bd2007-07-31 12:34:36 +00006840 SourceLocation StartLoc = ConsumeToken();
6841
John McCalle8595032010-01-13 20:03:27 +00006842 const bool hasParens = Tok.is(tok::l_paren);
6843
Faisal Valid143a0c2017-04-01 21:30:49 +00006844 EnterExpressionEvaluationContext Unevaluated(
6845 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6846 Sema::ReuseLambdaContextDecl);
Eli Friedmane0afc982012-01-21 01:01:51 +00006847
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006848 bool isCastExpr;
John McCallba7bf592010-08-24 05:47:05 +00006849 ParsedType CastTy;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006850 SourceRange CastRange;
Kaelyn Takata911260742014-12-19 01:28:40 +00006851 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6852 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
John McCalle8595032010-01-13 20:03:27 +00006853 if (hasParens)
6854 DS.setTypeofParensRange(CastRange);
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006855
6856 if (CastRange.getEnd().isInvalid())
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006857 // FIXME: Not accurate, the range gets one token more than it should.
6858 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006859 else
6860 DS.SetRangeEnd(CastRange.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +00006861
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006862 if (isCastExpr) {
6863 if (!CastTy) {
6864 DS.SetTypeSpecError();
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006865 return;
Douglas Gregor220cac52009-02-18 17:45:20 +00006866 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006867
Craig Topper161e4db2014-05-21 06:02:52 +00006868 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006869 unsigned DiagID;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006870 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6871 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006872 DiagID, CastTy,
6873 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006874 Diag(StartLoc, DiagID) << PrevSpec;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006875 return;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006876 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006877
Hiroshi Inoue533777f2017-07-02 06:12:49 +00006878 // If we get here, the operand to the typeof was an expression.
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006879 if (Operand.isInvalid()) {
6880 DS.SetTypeSpecError();
Steve Naroff4bd2f712007-08-02 02:53:48 +00006881 return;
Steve Naroffad373bd2007-07-31 12:34:36 +00006882 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006883
Eli Friedmane0afc982012-01-21 01:01:51 +00006884 // We might need to transform the operand if it is potentially evaluated.
6885 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6886 if (Operand.isInvalid()) {
6887 DS.SetTypeSpecError();
6888 return;
6889 }
6890
Craig Topper161e4db2014-05-21 06:02:52 +00006891 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006892 unsigned DiagID;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006893 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6894 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006895 DiagID, Operand.get(),
6896 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006897 Diag(StartLoc, DiagID) << PrevSpec;
Steve Naroffad373bd2007-07-31 12:34:36 +00006898}
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006899
Benjamin Kramere56f3932011-12-23 17:00:35 +00006900/// [C11] atomic-specifier:
Eli Friedman0dfb8892011-10-06 23:00:33 +00006901/// _Atomic ( type-name )
6902///
6903void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
Richard Smith8e1ac332013-03-28 01:55:44 +00006904 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6905 "Not an atomic specifier");
Eli Friedman0dfb8892011-10-06 23:00:33 +00006906
6907 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006908 BalancedDelimiterTracker T(*this, tok::l_paren);
Richard Smith8e1ac332013-03-28 01:55:44 +00006909 if (T.consumeOpen())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006910 return;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006911
6912 TypeResult Result = ParseTypeName();
6913 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00006914 SkipUntil(tok::r_paren, StopAtSemi);
Eli Friedman0dfb8892011-10-06 23:00:33 +00006915 return;
6916 }
6917
6918 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006919 T.consumeClose();
Eli Friedman0dfb8892011-10-06 23:00:33 +00006920
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006921 if (T.getCloseLocation().isInvalid())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006922 return;
6923
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006924 DS.setTypeofParensRange(T.getRange());
6925 DS.SetRangeEnd(T.getCloseLocation());
Eli Friedman0dfb8892011-10-06 23:00:33 +00006926
Craig Topper161e4db2014-05-21 06:02:52 +00006927 const char *PrevSpec = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006928 unsigned DiagID;
6929 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006930 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006931 Actions.getASTContext().getPrintingPolicy()))
Eli Friedman0dfb8892011-10-06 23:00:33 +00006932 Diag(StartLoc, DiagID) << PrevSpec;
6933}
6934
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006935/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6936/// from TryAltiVecVectorToken.
6937bool Parser::TryAltiVecVectorTokenOutOfLine() {
6938 Token Next = NextToken();
6939 switch (Next.getKind()) {
6940 default: return false;
6941 case tok::kw_short:
6942 case tok::kw_long:
6943 case tok::kw_signed:
6944 case tok::kw_unsigned:
6945 case tok::kw_void:
6946 case tok::kw_char:
6947 case tok::kw_int:
6948 case tok::kw_float:
6949 case tok::kw_double:
6950 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006951 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006952 case tok::kw___pixel:
6953 Tok.setKind(tok::kw___vector);
6954 return true;
6955 case tok::identifier:
6956 if (Next.getIdentifierInfo() == Ident_pixel) {
6957 Tok.setKind(tok::kw___vector);
6958 return true;
6959 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006960 if (Next.getIdentifierInfo() == Ident_bool) {
6961 Tok.setKind(tok::kw___vector);
6962 return true;
6963 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006964 return false;
6965 }
6966}
6967
6968bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6969 const char *&PrevSpec, unsigned &DiagID,
6970 bool &isInvalid) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006971 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006972 if (Tok.getIdentifierInfo() == Ident_vector) {
6973 Token Next = NextToken();
6974 switch (Next.getKind()) {
6975 case tok::kw_short:
6976 case tok::kw_long:
6977 case tok::kw_signed:
6978 case tok::kw_unsigned:
6979 case tok::kw_void:
6980 case tok::kw_char:
6981 case tok::kw_int:
6982 case tok::kw_float:
6983 case tok::kw_double:
6984 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006985 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006986 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006987 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006988 return true;
6989 case tok::identifier:
6990 if (Next.getIdentifierInfo() == Ident_pixel) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006991 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006992 return true;
6993 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006994 if (Next.getIdentifierInfo() == Ident_bool) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006995 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00006996 return true;
6997 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006998 break;
6999 default:
7000 break;
7001 }
Douglas Gregor9938e3b2010-06-16 15:28:57 +00007002 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007003 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007004 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007005 return true;
Bill Schmidt99a084b2013-07-03 20:54:09 +00007006 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
7007 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007008 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00007009 return true;
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007010 }
7011 return false;
7012}