blob: 86fb8897e62af0d962c6f73eb08d90ae7a8d151f [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);
Richard Smith76b90272019-05-09 03:59:21 +00002483 if (DS.hasExplicitSpecifier())
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
Richard Smith76b90272019-05-09 03:59:21 +00002488 // Issue diagnostic and remove constexpr specifier 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
Richard Smithba24f352019-05-09 19:45:46 +00003010 // This value needs to be set to the location of the last token if the last
3011 // token of the specifier is already consumed.
3012 SourceLocation ConsumedEnd;
Richard Smith76b90272019-05-09 03:59:21 +00003013
David Majnemer51fd8a02015-07-22 23:46:18 +00003014 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3015 // implementation for VS2013 uses _Atomic as an identifier for one of the
3016 // classes in <atomic>.
3017 //
3018 // A typedef declaration containing _Atomic<...> is among the places where
3019 // the class is used. If we are currently parsing such a declaration, treat
3020 // the token as an identifier.
3021 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3022 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
3023 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3024 Tok.setKind(tok::identifier);
3025
Chris Lattner4d8f8732006-11-28 05:05:08 +00003026 SourceLocation Loc = Tok.getLocation();
Douglas Gregor450c75a2008-11-07 15:42:26 +00003027
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003028 switch (Tok.getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00003029 default:
Chris Lattner0974b232008-07-26 00:20:22 +00003030 DoneWithDeclSpec:
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003031 if (!AttrsLastTime)
3032 ProhibitAttributes(attrs);
Michael Han64536a62012-11-06 19:34:54 +00003033 else {
3034 // Reject C++11 attributes that appertain to decl specifiers as
3035 // we don't support any C++11 attributes that appertain to decl
3036 // specifiers. This also conforms to what g++ 4.8 is doing.
Richard Smith49cc1cc2016-08-18 21:59:42 +00003037 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
Michael Han64536a62012-11-06 19:34:54 +00003038
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003039 DS.takeAttributesFrom(attrs);
Michael Han64536a62012-11-06 19:34:54 +00003040 }
Peter Collingbourne70188b32011-09-29 18:03:57 +00003041
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003042 // If this is not a declaration specifier token, we're done reading decl
3043 // specifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00003044 DS.Finish(Actions, Policy);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003045 return;
Mike Stump11289f42009-09-09 15:08:12 +00003046
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003047 case tok::l_square:
3048 case tok::kw_alignas:
Aaron Ballman606093a2017-10-15 15:01:42 +00003049 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003050 goto DoneWithDeclSpec;
3051
3052 ProhibitAttributes(attrs);
3053 // FIXME: It would be good to recover by accepting the attributes,
3054 // but attempting to do that now would cause serious
3055 // madness in terms of diagnostics.
3056 attrs.clear();
3057 attrs.Range = SourceRange();
3058
3059 ParseCXX11Attributes(attrs);
3060 AttrsLastTime = true;
Chad Rosierc1183952012-06-26 22:30:43 +00003061 continue;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003062
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003063 case tok::code_completion: {
John McCallfaf5fb42010-08-26 23:41:50 +00003064 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003065 if (DS.hasTypeSpecifier()) {
3066 bool AllowNonIdentifiers
3067 = (getCurScope()->getFlags() & (Scope::ControlScope |
3068 Scope::BlockScope |
3069 Scope::TemplateParamScope |
3070 Scope::FunctionPrototypeScope |
3071 Scope::AtCatchScope)) == 0;
3072 bool AllowNestedNameSpecifiers
Faisal Vali7db85c52017-12-31 00:06:40 +00003073 = DSContext == DeclSpecContext::DSC_top_level ||
3074 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003075
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003076 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
Chad Rosierc1183952012-06-26 22:30:43 +00003077 AllowNonIdentifiers,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003078 AllowNestedNameSpecifiers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003079 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00003080 }
3081
Douglas Gregor80039242011-02-15 20:33:25 +00003082 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3083 CCC = Sema::PCC_LocalDeclarationSpecifiers;
3084 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
Faisal Vali7db85c52017-12-31 00:06:40 +00003085 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3086 : Sema::PCC_Template;
3087 else if (DSContext == DeclSpecContext::DSC_class)
John McCallfaf5fb42010-08-26 23:41:50 +00003088 CCC = Sema::PCC_Class;
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +00003089 else if (CurParsedObjCImpl)
John McCallfaf5fb42010-08-26 23:41:50 +00003090 CCC = Sema::PCC_ObjCImplementation;
Chad Rosierc1183952012-06-26 22:30:43 +00003091
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003092 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003093 return cutOffParsing();
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003094 }
3095
Chris Lattnerbd31aa32009-01-05 00:07:25 +00003096 case tok::coloncolon: // ::foo::bar
John McCall1f476a12010-02-26 08:45:28 +00003097 // C++ scope specifier. Annotate and loop, or bail out on error.
Eli Friedman2a1d9a92013-08-15 23:59:20 +00003098 if (TryAnnotateCXXScopeToken(EnteringContext)) {
John McCall1f476a12010-02-26 08:45:28 +00003099 if (!DS.hasTypeSpecifier())
3100 DS.SetTypeSpecError();
3101 goto DoneWithDeclSpec;
3102 }
John McCall8bc2a702010-03-01 18:20:46 +00003103 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3104 goto DoneWithDeclSpec;
John McCall1f476a12010-02-26 08:45:28 +00003105 continue;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003106
3107 case tok::annot_cxxscope: {
Richard Smith3092a3b2012-05-09 18:56:43 +00003108 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003109 goto DoneWithDeclSpec;
3110
John McCall9dab4e62009-12-12 11:40:51 +00003111 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00003112 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3113 Tok.getAnnotationRange(),
3114 SS);
John McCall9dab4e62009-12-12 11:40:51 +00003115
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003116 // We are looking for a qualified typename.
Douglas Gregor167fa622009-03-25 15:40:00 +00003117 Token Next = NextToken();
Mike Stump11289f42009-09-09 15:08:12 +00003118 if (Next.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003119 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
Douglas Gregorb67535d2009-03-31 00:43:58 +00003120 ->Kind == TNK_Type_template) {
Douglas Gregor167fa622009-03-25 15:40:00 +00003121 // We have a qualified template-id, e.g., N::A<int>
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003122
Richard Smith74f02342017-01-19 21:00:13 +00003123 // If this would be a valid constructor declaration with template
3124 // arguments, we will reject the attempt to form an invalid type-id
3125 // referring to the injected-class-name when we annotate the token,
3126 // per C++ [class.qual]p2.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003127 //
Richard Smith74f02342017-01-19 21:00:13 +00003128 // To improve diagnostics for this case, parse the declaration as a
3129 // constructor (and reject the extra template arguments later).
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003130 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
Faisal Vali7db85c52017-12-31 00:06:40 +00003131 if ((DSContext == DeclSpecContext::DSC_top_level ||
3132 DSContext == DeclSpecContext::DSC_class) &&
John McCall84821e72010-04-13 06:39:49 +00003133 TemplateId->Name &&
Richard Smith74f02342017-01-19 21:00:13 +00003134 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003135 isConstructorDeclarator(/*Unqualified*/ false)) {
Richard Smith74f02342017-01-19 21:00:13 +00003136 // The user meant this to be an out-of-line constructor
3137 // definition, but template arguments are not allowed
3138 // there. Just allow this as a constructor; we'll
3139 // complain about it later.
3140 goto DoneWithDeclSpec;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003141 }
3142
John McCall9dab4e62009-12-12 11:40:51 +00003143 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003144 ConsumeAnnotationToken(); // The C++ scope.
Mike Stump11289f42009-09-09 15:08:12 +00003145 assert(Tok.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003146 "ParseOptionalCXXScopeSpecifier not working");
Douglas Gregore7c20652011-03-02 00:47:37 +00003147 AnnotateTemplateIdTokenAsType();
Douglas Gregor167fa622009-03-25 15:40:00 +00003148 continue;
3149 }
3150
Douglas Gregorc5790df2009-09-28 07:26:33 +00003151 if (Next.is(tok::annot_typename)) {
John McCall9dab4e62009-12-12 11:40:51 +00003152 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003153 ConsumeAnnotationToken(); // The C++ scope.
John McCallba7bf592010-08-24 05:47:05 +00003154 if (Tok.getAnnotationValue()) {
3155 ParsedType T = getTypeAnnotation(Tok);
Nico Weber77430342010-11-22 10:30:56 +00003156 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
Chad Rosierc1183952012-06-26 22:30:43 +00003157 Tok.getAnnotationEndLoc(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003158 PrevSpec, DiagID, T, Policy);
Richard Smithda837032012-09-14 18:27:01 +00003159 if (isInvalid)
3160 break;
John McCallba7bf592010-08-24 05:47:05 +00003161 }
Douglas Gregorc5790df2009-09-28 07:26:33 +00003162 else
3163 DS.SetTypeSpecError();
3164 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003165 ConsumeAnnotationToken(); // The typename
Douglas Gregorc5790df2009-09-28 07:26:33 +00003166 }
3167
Douglas Gregor167fa622009-03-25 15:40:00 +00003168 if (Next.isNot(tok::identifier))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003169 goto DoneWithDeclSpec;
3170
Richard Smith74f02342017-01-19 21:00:13 +00003171 // Check whether this is a constructor declaration. If we're in a
3172 // context where the identifier could be a class name, and it has the
3173 // shape of a constructor declaration, process it as one.
Faisal Vali7db85c52017-12-31 00:06:40 +00003174 if ((DSContext == DeclSpecContext::DSC_top_level ||
3175 DSContext == DeclSpecContext::DSC_class) &&
Chad Rosierc1183952012-06-26 22:30:43 +00003176 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
Richard Smith74f02342017-01-19 21:00:13 +00003177 &SS) &&
3178 isConstructorDeclarator(/*Unqualified*/ false))
3179 goto DoneWithDeclSpec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003180
David Blaikieefdccaa2016-01-15 23:43:34 +00003181 ParsedType TypeRep =
3182 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3183 getCurScope(), &SS, false, false, nullptr,
3184 /*IsCtorOrDtorName=*/false,
Richard Smith600b5262017-01-26 20:40:47 +00003185 /*WantNonTrivialSourceInfo=*/true,
3186 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003187
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003188 // If the referenced identifier is not a type, then this declspec is
3189 // erroneous: We already checked about that it has no type specifier, and
3190 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
Mike Stump11289f42009-09-09 15:08:12 +00003191 // typename.
David Blaikie7d170102013-05-15 07:37:26 +00003192 if (!TypeRep) {
Richard Smithaf3b3252017-05-18 19:21:48 +00003193 // Eat the scope spec so the identifier is current.
3194 ConsumeAnnotationToken();
Michael Han9407e502012-11-26 22:54:45 +00003195 ParsedAttributesWithRange Attrs(AttrFactory);
3196 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3197 if (!Attrs.empty()) {
3198 AttrsLastTime = true;
3199 attrs.takeAllFrom(Attrs);
3200 }
3201 continue;
3202 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003203 goto DoneWithDeclSpec;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003204 }
Mike Stump11289f42009-09-09 15:08:12 +00003205
John McCall9dab4e62009-12-12 11:40:51 +00003206 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003207 ConsumeAnnotationToken(); // The C++ scope.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003208
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003209 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003210 DiagID, TypeRep, Policy);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003211 if (isInvalid)
3212 break;
Mike Stump11289f42009-09-09 15:08:12 +00003213
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003214 DS.SetRangeEnd(Tok.getLocation());
3215 ConsumeToken(); // The typename.
3216
3217 continue;
3218 }
Mike Stump11289f42009-09-09 15:08:12 +00003219
Chris Lattnere387d9e2009-01-21 19:48:37 +00003220 case tok::annot_typename: {
Richard Smith404dfb42013-11-19 22:47:36 +00003221 // If we've previously seen a tag definition, we were almost surely
3222 // missing a semicolon after it.
3223 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3224 goto DoneWithDeclSpec;
3225
John McCallba7bf592010-08-24 05:47:05 +00003226 if (Tok.getAnnotationValue()) {
3227 ParsedType T = getTypeAnnotation(Tok);
Nico Weber7f8bb362010-11-22 12:50:03 +00003228 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003229 DiagID, T, Policy);
John McCallba7bf592010-08-24 05:47:05 +00003230 } else
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003231 DS.SetTypeSpecError();
Chad Rosierc1183952012-06-26 22:30:43 +00003232
Chris Lattner005fc1b2010-04-05 18:18:31 +00003233 if (isInvalid)
3234 break;
3235
Chris Lattnere387d9e2009-01-21 19:48:37 +00003236 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003237 ConsumeAnnotationToken(); // The typename
Mike Stump11289f42009-09-09 15:08:12 +00003238
Chris Lattnere387d9e2009-01-21 19:48:37 +00003239 continue;
3240 }
Mike Stump11289f42009-09-09 15:08:12 +00003241
Douglas Gregor06873092011-04-28 15:48:45 +00003242 case tok::kw___is_signed:
3243 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3244 // typically treats it as a trait. If we see __is_signed as it appears
3245 // in libstdc++, e.g.,
3246 //
3247 // static const bool __is_signed;
3248 //
3249 // then treat __is_signed as an identifier rather than as a keyword.
Faisal Vali090da2d2018-01-01 18:23:28 +00003250 if (DS.getTypeSpecType() == TST_bool &&
Douglas Gregor06873092011-04-28 15:48:45 +00003251 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
Alp Toker47642d22013-12-03 06:13:01 +00003252 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3253 TryKeywordIdentFallback(true);
Douglas Gregor06873092011-04-28 15:48:45 +00003254
3255 // We're done with the declaration-specifiers.
3256 goto DoneWithDeclSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00003257
Chris Lattner16fac4f2008-07-26 01:18:38 +00003258 // typedef-name
Nikola Smiljanic67860242014-09-26 00:28:20 +00003259 case tok::kw___super:
David Blaikie15a430a2011-12-04 05:04:18 +00003260 case tok::kw_decltype:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003261 case tok::identifier: {
Reid Klecknerc582f012014-07-14 18:19:58 +00003262 // This identifier can only be a typedef name if we haven't already seen
3263 // a type-specifier. Without this check we misparse:
3264 // typedef int X; struct Y { short X; }; as 'short int'.
3265 if (DS.hasTypeSpecifier())
3266 goto DoneWithDeclSpec;
3267
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003268 // If the token is an identifier named "__declspec" and Microsoft
3269 // extensions are not enabled, it is likely that there will be cascading
3270 // parse errors if this really is a __declspec attribute. Attempt to
3271 // recognize that scenario and recover gracefully.
3272 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3273 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3274 Diag(Loc, diag::err_ms_attributes_not_enabled);
3275
3276 // The next token should be an open paren. If it is, eat the entire
3277 // attribute declaration and continue.
3278 if (NextToken().is(tok::l_paren)) {
3279 // Consume the __declspec identifier.
Richard Trieuba057372017-02-14 23:56:55 +00003280 ConsumeToken();
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003281
3282 // Eat the parens and everything between them.
3283 BalancedDelimiterTracker T(*this, tok::l_paren);
3284 if (T.consumeOpen()) {
3285 assert(false && "Not a left paren?");
3286 return;
3287 }
3288 T.skipToEnd();
3289 continue;
3290 }
3291 }
3292
Serge Pavlov458ea762014-07-16 05:16:52 +00003293 // In C++, check to see if this is a scope specifier like foo::bar::, if
3294 // so handle it as such. This is important for ctor parsing.
3295 if (getLangOpts().CPlusPlus) {
3296 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3297 DS.SetTypeSpecError();
3298 goto DoneWithDeclSpec;
3299 }
3300 if (!Tok.is(tok::identifier))
3301 continue;
3302 }
3303
John Thompson22334602010-02-05 00:12:22 +00003304 // Check for need to substitute AltiVec keyword tokens.
3305 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3306 break;
3307
Richard Smith3092a3b2012-05-09 18:56:43 +00003308 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3309 // allow the use of a typedef name as a type specifier.
3310 if (DS.isTypeAltiVecVector())
3311 goto DoneWithDeclSpec;
3312
Faisal Vali7db85c52017-12-31 00:06:40 +00003313 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3314 isObjCInstancetype()) {
Douglas Gregor5c0870a2015-06-19 23:18:00 +00003315 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3316 assert(TypeRep);
3317 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3318 DiagID, TypeRep, Policy);
3319 if (isInvalid)
3320 break;
3321
3322 DS.SetRangeEnd(Loc);
3323 ConsumeToken();
3324 continue;
3325 }
3326
Richard Smith715ee072018-06-20 21:58:20 +00003327 // If we're in a context where the identifier could be a class name,
3328 // check whether this is a constructor declaration.
3329 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3330 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3331 isConstructorDeclarator(/*Unqualified*/true))
3332 goto DoneWithDeclSpec;
3333
Richard Smith600b5262017-01-26 20:40:47 +00003334 ParsedType TypeRep = Actions.getTypeName(
3335 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3336 false, false, nullptr, false, false,
3337 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003338
Chris Lattner6cc055a2009-04-12 20:42:31 +00003339 // If this is not a typedef name, don't parse it as part of the declspec,
3340 // it must be an implicit int or an error.
John McCallba7bf592010-08-24 05:47:05 +00003341 if (!TypeRep) {
Michael Han9407e502012-11-26 22:54:45 +00003342 ParsedAttributesWithRange Attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +00003343 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
Michael Han9407e502012-11-26 22:54:45 +00003344 if (!Attrs.empty()) {
3345 AttrsLastTime = true;
3346 attrs.takeAllFrom(Attrs);
3347 }
3348 continue;
3349 }
Chris Lattner16fac4f2008-07-26 01:18:38 +00003350 goto DoneWithDeclSpec;
Chris Lattner6cc055a2009-04-12 20:42:31 +00003351 }
Douglas Gregor8bf42052009-02-09 18:46:07 +00003352
Richard Smith35845152017-02-07 01:37:30 +00003353 // Likewise, if this is a context where the identifier could be a template
3354 // name, check whether this is a deduction guide declaration.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003355 if (getLangOpts().CPlusPlus17 &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003356 (DSContext == DeclSpecContext::DSC_class ||
3357 DSContext == DeclSpecContext::DSC_top_level) &&
Richard Smith35845152017-02-07 01:37:30 +00003358 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3359 Tok.getLocation()) &&
3360 isConstructorDeclarator(/*Unqualified*/ true,
3361 /*DeductionGuide*/ true))
3362 goto DoneWithDeclSpec;
3363
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003364 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003365 DiagID, TypeRep, Policy);
Chris Lattner16fac4f2008-07-26 01:18:38 +00003366 if (isInvalid)
3367 break;
Mike Stump11289f42009-09-09 15:08:12 +00003368
Chris Lattner16fac4f2008-07-26 01:18:38 +00003369 DS.SetRangeEnd(Tok.getLocation());
3370 ConsumeToken(); // The identifier
3371
Douglas Gregore9d95f12015-07-07 03:57:35 +00003372 // Objective-C supports type arguments and protocol references
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003373 // following an Objective-C object or object pointer
3374 // type. Handle either one of them.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003375 if (Tok.is(tok::less) && getLangOpts().ObjC) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003376 SourceLocation NewEndLoc;
3377 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3378 Loc, TypeRep, /*consumeLastToken=*/true,
3379 NewEndLoc);
3380 if (NewTypeRep.isUsable()) {
3381 DS.UpdateTypeRep(NewTypeRep.get());
3382 DS.SetRangeEnd(NewEndLoc);
3383 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00003384 }
Chad Rosierc1183952012-06-26 22:30:43 +00003385
Steve Naroffcd5e7822008-09-22 10:28:57 +00003386 // Need to support trailing type qualifiers (e.g. "id<p> const").
3387 // If a type specifier follows, it will be diagnosed elsewhere.
3388 continue;
Chris Lattner16fac4f2008-07-26 01:18:38 +00003389 }
Douglas Gregor7f741122009-02-25 19:37:18 +00003390
3391 // type-name
3392 case tok::annot_template_id: {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003393 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Richard Smithb23c5e82019-05-09 03:31:27 +00003394 if (TemplateId->Kind != TNK_Type_template &&
3395 TemplateId->Kind != TNK_Undeclared_template) {
Douglas Gregor7f741122009-02-25 19:37:18 +00003396 // This template-id does not refer to a type name, so we're
3397 // done with the type-specifiers.
3398 goto DoneWithDeclSpec;
3399 }
3400
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003401 // If we're in a context where the template-id could be a
3402 // constructor name or specialization, check whether this is a
3403 // constructor declaration.
Faisal Vali7db85c52017-12-31 00:06:40 +00003404 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00003405 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
Richard Smith446161b2014-03-03 21:12:53 +00003406 isConstructorDeclarator(TemplateId->SS.isEmpty()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003407 goto DoneWithDeclSpec;
3408
Douglas Gregor7f741122009-02-25 19:37:18 +00003409 // Turn the template-id annotation token into a type annotation
3410 // token, then try again to parse it as a type-specifier.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003411 AnnotateTemplateIdTokenAsType();
Douglas Gregor7f741122009-02-25 19:37:18 +00003412 continue;
3413 }
3414
Chris Lattnere37e2332006-08-15 04:50:22 +00003415 // GNU attributes support.
3416 case tok::kw___attribute:
Craig Topper161e4db2014-05-21 06:02:52 +00003417 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
Chris Lattnerb95cca02006-10-17 03:01:08 +00003418 continue;
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003419
3420 // Microsoft declspec support.
3421 case tok::kw___declspec:
Aaron Ballman068aa512015-05-20 20:58:33 +00003422 ParseMicrosoftDeclSpecs(DS.getAttributes());
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003423 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003424
Steve Naroff44ac7772008-12-25 14:16:32 +00003425 // Microsoft single token adornments.
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003426 case tok::kw___forceinline: {
Serge Pavlov750db652013-11-13 06:57:53 +00003427 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003428 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Richard Smithda837032012-09-14 18:27:01 +00003429 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00003430 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00003431 nullptr, 0, ParsedAttr::AS_Keyword);
Richard Smithda837032012-09-14 18:27:01 +00003432 break;
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003433 }
Eli Friedman53339e02009-06-08 23:27:34 +00003434
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003435 case tok::kw___unaligned:
3436 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3437 getLangOpts());
3438 break;
3439
Aaron Ballman317a77f2013-05-22 23:25:32 +00003440 case tok::kw___sptr:
3441 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00003442 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00003443 case tok::kw___ptr32:
Steve Narofff9c29d42008-12-25 14:41:26 +00003444 case tok::kw___w64:
Steve Naroff44ac7772008-12-25 14:16:32 +00003445 case tok::kw___cdecl:
3446 case tok::kw___stdcall:
3447 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00003448 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00003449 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00003450 case tok::kw___vectorcall:
John McCall53fa7142010-12-24 02:08:15 +00003451 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00003452 continue;
3453
Dawn Perchik335e16b2010-09-03 01:29:35 +00003454 // Borland single token adornments.
3455 case tok::kw___pascal:
John McCall53fa7142010-12-24 02:08:15 +00003456 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00003457 continue;
3458
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003459 // OpenCL single token adornments.
3460 case tok::kw___kernel:
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +00003461 ParseOpenCLKernelAttributes(DS.getAttributes());
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003462 continue;
3463
Douglas Gregor261a89b2015-06-19 17:51:05 +00003464 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00003465 case tok::kw__Nonnull:
3466 case tok::kw__Nullable:
3467 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00003468 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3469 continue;
3470
Douglas Gregorab209d82015-07-07 03:58:42 +00003471 // Objective-C 'kindof' types.
3472 case tok::kw___kindof:
3473 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00003474 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00003475 (void)ConsumeToken();
3476 continue;
3477
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003478 // storage-class-specifier
3479 case tok::kw_typedef:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003480 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003481 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003482 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003483 break;
3484 case tok::kw_extern:
Richard Smithb4a9e862013-04-12 22:46:28 +00003485 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003486 Diag(Tok, diag::ext_thread_before) << "extern";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003487 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003488 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003489 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003490 break;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003491 case tok::kw___private_extern__:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003492 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003493 Loc, PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003494 isStorageClass = true;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003495 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003496 case tok::kw_static:
Richard Smithb4a9e862013-04-12 22:46:28 +00003497 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003498 Diag(Tok, diag::ext_thread_before) << "static";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003499 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003500 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003501 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003502 break;
3503 case tok::kw_auto:
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003504 if (getLangOpts().CPlusPlus11) {
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003505 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003506 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003507 PrevSpec, DiagID, Policy);
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003508 if (!isInvalid)
Richard Smith58c74332011-09-04 19:54:14 +00003509 Diag(Tok, diag::ext_auto_storage_class)
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003510 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith58c74332011-09-04 19:54:14 +00003511 } else
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003512 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003513 DiagID, Policy);
Richard Smith58c74332011-09-04 19:54:14 +00003514 } else
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003515 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003516 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003517 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003518 break;
Richard Smithe301ba22015-11-11 02:02:15 +00003519 case tok::kw___auto_type:
3520 Diag(Tok, diag::ext_auto_type);
3521 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3522 DiagID, Policy);
3523 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003524 case tok::kw_register:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003525 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003526 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003527 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003528 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003529 case tok::kw_mutable:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003530 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003531 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003532 isStorageClass = true;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003533 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003534 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00003535 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3536 PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003537 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003538 break;
3539 case tok::kw_thread_local:
3540 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3541 PrevSpec, DiagID);
Sven van Haastregtc4100832018-04-24 14:47:29 +00003542 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003543 break;
3544 case tok::kw__Thread_local:
3545 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3546 Loc, PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003547 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003548 break;
Mike Stump11289f42009-09-09 15:08:12 +00003549
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003550 // function-specifier
3551 case tok::kw_inline:
Serge Pavlov750db652013-11-13 06:57:53 +00003552 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003553 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003554 case tok::kw_virtual:
Sven van Haastregt49ffffb2018-04-23 11:23:47 +00003555 // OpenCL C++ v1.0 s2.9: the virtual function qualifier is not supported.
3556 if (getLangOpts().OpenCLCPlusPlus) {
3557 DiagID = diag::err_openclcxx_virtual_function;
3558 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3559 isInvalid = true;
3560 }
3561 else {
3562 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3563 }
Douglas Gregor61956c42008-10-31 09:07:45 +00003564 break;
Richard Smith76b90272019-05-09 03:59:21 +00003565 case tok::kw_explicit: {
3566 SourceLocation ExplicitLoc = Loc;
3567 SourceLocation CloseParenLoc;
3568 ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
Richard Smithba24f352019-05-09 19:45:46 +00003569 ConsumedEnd = ExplicitLoc;
Richard Smith76b90272019-05-09 03:59:21 +00003570 ConsumeToken(); // kw_explicit
3571 if (Tok.is(tok::l_paren)) {
3572 if (getLangOpts().CPlusPlus2a) {
3573 ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3574 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3575 Tracker.consumeOpen();
3576 ExplicitExpr = ParseConstantExpression();
Richard Smithba24f352019-05-09 19:45:46 +00003577 ConsumedEnd = Tok.getLocation();
Richard Smith76b90272019-05-09 03:59:21 +00003578 if (ExplicitExpr.isUsable()) {
3579 CloseParenLoc = Tok.getLocation();
3580 Tracker.consumeClose();
3581 ExplicitSpec =
3582 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3583 } else
3584 Tracker.skipToEnd();
3585 } else
3586 Diag(Tok.getLocation(), diag::warn_cxx2a_compat_explicit_bool);
3587 }
3588 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3589 ExplicitSpec, CloseParenLoc);
Douglas Gregor61956c42008-10-31 09:07:45 +00003590 break;
Richard Smith76b90272019-05-09 03:59:21 +00003591 }
Richard Smith0015f092013-01-17 22:16:11 +00003592 case tok::kw__Noreturn:
3593 if (!getLangOpts().C11)
3594 Diag(Loc, diag::ext_c11_noreturn);
Serge Pavlov750db652013-11-13 06:57:53 +00003595 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
Richard Smith0015f092013-01-17 22:16:11 +00003596 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003597
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003598 // alignment-specifier
3599 case tok::kw__Alignas:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003600 if (!getLangOpts().C11)
Jordan Rose58d54722012-06-30 21:33:57 +00003601 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003602 ParseAlignmentSpecifier(DS.getAttributes());
3603 continue;
3604
Anders Carlssoncd8db412009-05-06 04:46:28 +00003605 // friend
3606 case tok::kw_friend:
Faisal Vali7db85c52017-12-31 00:06:40 +00003607 if (DSContext == DeclSpecContext::DSC_class)
John McCall07e91c02009-08-06 02:15:43 +00003608 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3609 else {
3610 PrevSpec = ""; // not actually used by the diagnostic
3611 DiagID = diag::err_friend_invalid_in_context;
3612 isInvalid = true;
3613 }
Anders Carlssoncd8db412009-05-06 04:46:28 +00003614 break;
Mike Stump11289f42009-09-09 15:08:12 +00003615
Douglas Gregor26701a42011-09-09 02:06:17 +00003616 // Modules
3617 case tok::kw___module_private__:
3618 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3619 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003620
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00003621 // constexpr
3622 case tok::kw_constexpr:
3623 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3624 break;
3625
Chris Lattnere387d9e2009-01-21 19:48:37 +00003626 // type-specifier
3627 case tok::kw_short:
John McCall49bfce42009-08-03 20:12:06 +00003628 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003629 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003630 break;
3631 case tok::kw_long:
3632 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
John McCall49bfce42009-08-03 20:12:06 +00003633 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003634 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003635 else
John McCall49bfce42009-08-03 20:12:06 +00003636 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003637 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003638 break;
Francois Pichet84133e42011-04-28 01:59:37 +00003639 case tok::kw___int64:
3640 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003641 DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00003642 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003643 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00003644 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3645 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003646 break;
3647 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00003648 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3649 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003650 break;
3651 case tok::kw__Complex:
John McCall49bfce42009-08-03 20:12:06 +00003652 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3653 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003654 break;
3655 case tok::kw__Imaginary:
John McCall49bfce42009-08-03 20:12:06 +00003656 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3657 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003658 break;
3659 case tok::kw_void:
John McCall49bfce42009-08-03 20:12:06 +00003660 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003661 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003662 break;
3663 case tok::kw_char:
John McCall49bfce42009-08-03 20:12:06 +00003664 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003665 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003666 break;
3667 case tok::kw_int:
John McCall49bfce42009-08-03 20:12:06 +00003668 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003669 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003670 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00003671 case tok::kw___int128:
3672 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003673 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003674 break;
3675 case tok::kw_half:
3676 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003677 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003678 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003679 case tok::kw_float:
John McCall49bfce42009-08-03 20:12:06 +00003680 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003681 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003682 break;
3683 case tok::kw_double:
John McCall49bfce42009-08-03 20:12:06 +00003684 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003685 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003686 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00003687 case tok::kw__Float16:
3688 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3689 DiagID, Policy);
3690 break;
Leonard Chanf921d852018-06-04 16:07:52 +00003691 case tok::kw__Accum:
3692 if (!getLangOpts().FixedPoint) {
Leonard Chanab80f3c2018-06-14 14:53:51 +00003693 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
Leonard Chanf921d852018-06-04 16:07:52 +00003694 } else {
3695 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3696 DiagID, Policy);
3697 }
3698 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00003699 case tok::kw__Fract:
3700 if (!getLangOpts().FixedPoint) {
3701 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3702 } else {
3703 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3704 DiagID, Policy);
3705 }
3706 break;
3707 case tok::kw__Sat:
3708 if (!getLangOpts().FixedPoint) {
3709 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3710 } else {
3711 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3712 }
3713 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003714 case tok::kw___float128:
3715 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3716 DiagID, Policy);
3717 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003718 case tok::kw_wchar_t:
John McCall49bfce42009-08-03 20:12:06 +00003719 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003720 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003721 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00003722 case tok::kw_char8_t:
3723 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3724 DiagID, Policy);
3725 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003726 case tok::kw_char16_t:
John McCall49bfce42009-08-03 20:12:06 +00003727 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003728 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003729 break;
3730 case tok::kw_char32_t:
John McCall49bfce42009-08-03 20:12:06 +00003731 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003732 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003733 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003734 case tok::kw_bool:
3735 case tok::kw__Bool:
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003736 if (Tok.is(tok::kw_bool) &&
3737 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3738 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3739 PrevSpec = ""; // Not used by the diagnostic.
3740 DiagID = diag::err_bool_redeclaration;
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003741 // For better error recovery.
3742 Tok.setKind(tok::identifier);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003743 isInvalid = true;
3744 } else {
3745 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003746 DiagID, Policy);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003747 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003748 break;
3749 case tok::kw__Decimal32:
John McCall49bfce42009-08-03 20:12:06 +00003750 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003751 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003752 break;
3753 case tok::kw__Decimal64:
John McCall49bfce42009-08-03 20:12:06 +00003754 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003755 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003756 break;
3757 case tok::kw__Decimal128:
John McCall49bfce42009-08-03 20:12:06 +00003758 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003759 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003760 break;
John Thompson22334602010-02-05 00:12:22 +00003761 case tok::kw___vector:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003762 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003763 break;
3764 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003765 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003766 break;
Bill Seurercf2c96b2015-01-12 19:35:51 +00003767 case tok::kw___bool:
3768 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3769 break;
Xiuli Pan9c14e282016-01-09 12:53:17 +00003770 case tok::kw_pipe:
3771 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3772 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3773 // support the "pipe" word as identifier.
3774 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3775 goto DoneWithDeclSpec;
3776 }
3777 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3778 break;
Alexey Bader954ba212016-04-08 13:40:33 +00003779#define GENERIC_IMAGE_TYPE(ImgType, Id) \
3780 case tok::kw_##ImgType##_t: \
3781 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3782 DiagID, Policy); \
3783 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00003784#include "clang/Basic/OpenCLImageTypes.def"
John McCall39439732011-04-09 22:50:59 +00003785 case tok::kw___unknown_anytype:
Faisal Vali090da2d2018-01-01 18:23:28 +00003786 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003787 PrevSpec, DiagID, Policy);
John McCall39439732011-04-09 22:50:59 +00003788 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003789
3790 // class-specifier:
3791 case tok::kw_class:
3792 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00003793 case tok::kw___interface:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003794 case tok::kw_union: {
3795 tok::TokenKind Kind = Tok.getKind();
3796 ConsumeToken();
Michael Han9407e502012-11-26 22:54:45 +00003797
3798 // These are attributes following class specifiers.
3799 // To produce better diagnostic, we parse them when
3800 // parsing class specifier.
Bill Wendling44426052012-12-20 19:22:21 +00003801 ParsedAttributesWithRange Attributes(AttrFactory);
Richard Smithc5b05522012-03-12 07:56:15 +00003802 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
Bill Wendling44426052012-12-20 19:22:21 +00003803 EnteringContext, DSContext, Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003804
3805 // If there are attributes following class specifier,
3806 // take them over and handle them here.
Bill Wendling44426052012-12-20 19:22:21 +00003807 if (!Attributes.empty()) {
Michael Han9407e502012-11-26 22:54:45 +00003808 AttrsLastTime = true;
Bill Wendling44426052012-12-20 19:22:21 +00003809 attrs.takeAllFrom(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003810 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003811 continue;
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003812 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003813
3814 // enum-specifier:
3815 case tok::kw_enum:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003816 ConsumeToken();
Richard Smithc5b05522012-03-12 07:56:15 +00003817 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003818 continue;
Faisal Valia534f072018-04-26 00:42:40 +00003819
Chris Lattnere387d9e2009-01-21 19:48:37 +00003820 // cv-qualifier:
3821 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00003822 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003823 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003824 break;
3825 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00003826 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003827 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003828 break;
3829 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00003830 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003831 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003832 break;
3833
Douglas Gregor333489b2009-03-27 23:10:48 +00003834 // C++ typename-specifier:
3835 case tok::kw_typename:
John McCall1f476a12010-02-26 08:45:28 +00003836 if (TryAnnotateTypeOrScopeToken()) {
3837 DS.SetTypeSpecError();
3838 goto DoneWithDeclSpec;
3839 }
3840 if (!Tok.is(tok::kw_typename))
Douglas Gregor333489b2009-03-27 23:10:48 +00003841 continue;
3842 break;
3843
Chris Lattnere387d9e2009-01-21 19:48:37 +00003844 // GNU typeof support.
3845 case tok::kw_typeof:
3846 ParseTypeofSpecifier(DS);
3847 continue;
3848
David Blaikie15a430a2011-12-04 05:04:18 +00003849 case tok::annot_decltype:
Anders Carlsson74948d02009-06-24 17:47:40 +00003850 ParseDecltypeSpecifier(DS);
3851 continue;
3852
David Majnemer15b311c2016-06-14 03:20:28 +00003853 case tok::annot_pragma_pack:
3854 HandlePragmaPack();
3855 continue;
3856
3857 case tok::annot_pragma_ms_pragma:
3858 HandlePragmaMSPragma();
3859 continue;
3860
3861 case tok::annot_pragma_ms_vtordisp:
3862 HandlePragmaMSVtorDisp();
3863 continue;
3864
3865 case tok::annot_pragma_ms_pointers_to_members:
3866 HandlePragmaMSPointersToMembers();
3867 continue;
3868
Alexis Hunt4a257072011-05-19 05:37:45 +00003869 case tok::kw___underlying_type:
3870 ParseUnderlyingTypeSpecifier(DS);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003871 continue;
3872
3873 case tok::kw__Atomic:
Richard Smith8e1ac332013-03-28 01:55:44 +00003874 // C11 6.7.2.4/4:
3875 // If the _Atomic keyword is immediately followed by a left parenthesis,
3876 // it is interpreted as a type specifier (with a type name), not as a
3877 // type qualifier.
3878 if (NextToken().is(tok::l_paren)) {
3879 ParseAtomicSpecifier(DS);
3880 continue;
3881 }
3882 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3883 getLangOpts());
3884 break;
Alexis Hunt4a257072011-05-19 05:37:45 +00003885
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003886 // OpenCL address space qualifiers:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003887 case tok::kw___generic:
3888 // generic address space is introduced only in OpenCL v2.0
3889 // see OpenCL C Spec v2.0 s6.5.5
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003890 if (Actions.getLangOpts().OpenCLVersion < 200 &&
3891 !Actions.getLangOpts().OpenCLCPlusPlus) {
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003892 DiagID = diag::err_opencl_unknown_type_specifier;
3893 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3894 isInvalid = true;
3895 break;
3896 };
Galina Kistanova77674252017-06-01 21:15:34 +00003897 LLVM_FALLTHROUGH;
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003898 case tok::kw_private:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003899 case tok::kw___private:
3900 case tok::kw___global:
3901 case tok::kw___local:
3902 case tok::kw___constant:
Anastasia Stulova2c4730d2019-02-15 12:07:57 +00003903 // OpenCL access qualifiers:
3904 case tok::kw___read_only:
3905 case tok::kw___write_only:
3906 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00003907 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003908 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003909
Steve Naroffcfdf6162008-06-05 00:02:44 +00003910 case tok::less:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003911 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
Chris Lattner0974b232008-07-26 00:20:22 +00003912 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3913 // but we support it.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003914 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
Chris Lattner0974b232008-07-26 00:20:22 +00003915 goto DoneWithDeclSpec;
Mike Stump11289f42009-09-09 15:08:12 +00003916
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003917 SourceLocation StartLoc = Tok.getLocation();
3918 SourceLocation EndLoc;
3919 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3920 if (Type.isUsable()) {
3921 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3922 PrevSpec, DiagID, Type.get(),
3923 Actions.getASTContext().getPrintingPolicy()))
3924 Diag(StartLoc, DiagID) << PrevSpec;
Fangrui Song6907ce22018-07-30 19:24:48 +00003925
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003926 DS.SetRangeEnd(EndLoc);
3927 } else {
3928 DS.SetTypeSpecError();
3929 }
Chad Rosierc1183952012-06-26 22:30:43 +00003930
Douglas Gregor06e41ae2010-10-21 23:17:00 +00003931 // Need to support trailing type qualifiers (e.g. "id<p> const").
3932 // If a type specifier follows, it will be diagnosed elsewhere.
3933 continue;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003934 }
Richard Smith76b90272019-05-09 03:59:21 +00003935
Richard Smithba24f352019-05-09 19:45:46 +00003936 DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
Richard Smith76b90272019-05-09 03:59:21 +00003937
John McCall49bfce42009-08-03 20:12:06 +00003938 // If the specifier wasn't legal, issue a diagnostic.
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003939 if (isInvalid) {
3940 assert(PrevSpec && "Method did not return previous specifier!");
John McCall49bfce42009-08-03 20:12:06 +00003941 assert(DiagID);
Chad Rosierc1183952012-06-26 22:30:43 +00003942
Nick Desaulniers150ca532018-10-03 23:09:29 +00003943 if (DiagID == diag::ext_duplicate_declspec ||
Richard Smith76b90272019-05-09 03:59:21 +00003944 DiagID == diag::ext_warn_duplicate_declspec ||
3945 DiagID == diag::err_duplicate_declspec)
3946 Diag(Loc, DiagID) << PrevSpec
3947 << FixItHint::CreateRemoval(
3948 SourceRange(Loc, DS.getEndLoc()));
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003949 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
Richard Smith76b90272019-05-09 03:59:21 +00003950 Diag(Loc, DiagID) << getLangOpts().OpenCLCPlusPlus
3951 << getLangOpts().getOpenCLVersionTuple().getAsString()
3952 << PrevSpec << isStorageClass;
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003953 } else
Richard Smith76b90272019-05-09 03:59:21 +00003954 Diag(Loc, DiagID) << PrevSpec;
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003955 }
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003956
Richard Smithba24f352019-05-09 19:45:46 +00003957 if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
Volodymyr Sapsai9f7b5cc2018-04-10 18:29:47 +00003958 // After an error the next token can be an annotation token.
3959 ConsumeAnyToken();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003960
3961 AttrsLastTime = false;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003962 }
3963}
Douglas Gregoreb31f392008-12-01 23:54:00 +00003964
Chris Lattner70ae4912007-10-29 04:42:53 +00003965/// ParseStructDeclaration - Parse a struct declaration without the terminating
3966/// semicolon.
3967///
Nico Weber98dd0852019-03-14 14:18:56 +00003968/// Note that a struct declaration refers to a declaration in a struct,
3969/// not to the declaration of a struct.
3970///
Chris Lattner90a26b02007-01-23 04:38:16 +00003971/// struct-declaration:
Aaron Ballman606093a2017-10-15 15:01:42 +00003972/// [C2x] attributes-specifier-seq[opt]
3973/// specifier-qualifier-list struct-declarator-list
Chris Lattner736ed5d2007-06-09 05:59:07 +00003974/// [GNU] __extension__ struct-declaration
Chris Lattner70ae4912007-10-29 04:42:53 +00003975/// [GNU] specifier-qualifier-list
Chris Lattner90a26b02007-01-23 04:38:16 +00003976/// struct-declarator-list:
3977/// struct-declarator
3978/// struct-declarator-list ',' struct-declarator
3979/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3980/// struct-declarator:
3981/// declarator
3982/// [GNU] declarator attributes[opt]
3983/// declarator[opt] ':' constant-expression
3984/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3985///
Benjamin Kramera39beb92014-09-03 11:06:10 +00003986void Parser::ParseStructDeclaration(
3987 ParsingDeclSpec &DS,
3988 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
Chad Rosierc1183952012-06-26 22:30:43 +00003989
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003990 if (Tok.is(tok::kw___extension__)) {
3991 // __extension__ silences extension warnings in the subexpression.
3992 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Steve Naroff97170802007-08-20 22:28:22 +00003993 ConsumeToken();
Benjamin Kramera39beb92014-09-03 11:06:10 +00003994 return ParseStructDeclaration(DS, FieldsCallback);
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003995 }
Mike Stump11289f42009-09-09 15:08:12 +00003996
Aaron Ballman606093a2017-10-15 15:01:42 +00003997 // Parse leading attributes.
3998 ParsedAttributesWithRange Attrs(AttrFactory);
3999 MaybeParseCXX11Attributes(Attrs);
4000 DS.takeAttributesFrom(Attrs);
4001
Steve Naroff97170802007-08-20 22:28:22 +00004002 // Parse the common specifier-qualifiers-list piece.
Steve Naroff97170802007-08-20 22:28:22 +00004003 ParseSpecifierQualifierList(DS);
Mike Stump11289f42009-09-09 15:08:12 +00004004
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00004005 // If there are no declarators, this is a free-standing declaration
4006 // specifier. Let the actions module cope with it.
Chris Lattner76c72282007-10-09 17:33:22 +00004007 if (Tok.is(tok::semi)) {
Nico Weber7b837f52016-01-28 19:25:00 +00004008 RecordDecl *AnonRecord = nullptr;
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004009 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00004010 DS, AnonRecord);
4011 assert(!AnonRecord && "Did not expect anonymous struct or union here");
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004012 DS.complete(TheDecl);
Steve Naroff97170802007-08-20 22:28:22 +00004013 return;
4014 }
4015
4016 // Read struct-declarators until we find the semicolon.
John McCallcfefb6d2009-11-03 02:38:08 +00004017 bool FirstDeclarator = true;
Richard Smith8d06f422012-01-12 23:53:29 +00004018 SourceLocation CommaLoc;
Steve Naroff97170802007-08-20 22:28:22 +00004019 while (1) {
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004020 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
Richard Smith8d06f422012-01-12 23:53:29 +00004021 DeclaratorInfo.D.setCommaLoc(CommaLoc);
John McCallcfefb6d2009-11-03 02:38:08 +00004022
Bill Wendling44426052012-12-20 19:22:21 +00004023 // Attributes are only allowed here on successive declarators.
John McCall53fa7142010-12-24 02:08:15 +00004024 if (!FirstDeclarator)
4025 MaybeParseGNUAttributes(DeclaratorInfo.D);
Mike Stump11289f42009-09-09 15:08:12 +00004026
Steve Naroff97170802007-08-20 22:28:22 +00004027 /// struct-declarator: declarator
4028 /// struct-declarator: declarator[opt] ':' constant-expression
Chris Lattner17c3b1f2009-12-10 01:59:24 +00004029 if (Tok.isNot(tok::colon)) {
4030 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4031 ColonProtectionRAIIObject X(*this);
Chris Lattnera12405b2008-04-10 06:46:29 +00004032 ParseDeclarator(DeclaratorInfo.D);
Richard Smith3d1a94c2014-08-12 00:22:39 +00004033 } else
4034 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004035
Alp Toker8fbec672013-12-17 23:29:36 +00004036 if (TryConsumeToken(tok::colon)) {
John McCalldadc5752010-08-24 06:29:42 +00004037 ExprResult Res(ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004038 if (Res.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00004039 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner32295d32008-04-10 06:15:14 +00004040 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004041 DeclaratorInfo.BitfieldSize = Res.get();
Steve Naroff97170802007-08-20 22:28:22 +00004042 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004043
Steve Naroff97170802007-08-20 22:28:22 +00004044 // If attributes exist after the declarator, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004045 MaybeParseGNUAttributes(DeclaratorInfo.D);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004046
John McCallcfefb6d2009-11-03 02:38:08 +00004047 // We're done with this declarator; invoke the callback.
Benjamin Kramera39beb92014-09-03 11:06:10 +00004048 FieldsCallback(DeclaratorInfo);
John McCallcfefb6d2009-11-03 02:38:08 +00004049
Steve Naroff97170802007-08-20 22:28:22 +00004050 // If we don't have a comma, it is either the end of the list (a ';')
4051 // or an error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00004052 if (!TryConsumeToken(tok::comma, CommaLoc))
Chris Lattner70ae4912007-10-29 04:42:53 +00004053 return;
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004054
John McCallcfefb6d2009-11-03 02:38:08 +00004055 FirstDeclarator = false;
Steve Naroff97170802007-08-20 22:28:22 +00004056 }
Steve Naroff97170802007-08-20 22:28:22 +00004057}
4058
4059/// ParseStructUnionBody
4060/// struct-contents:
4061/// struct-declaration-list
4062/// [EXT] empty
4063/// [GNU] "struct-declaration-list" without terminatoring ';'
4064/// struct-declaration-list:
4065/// struct-declaration
4066/// struct-declaration-list struct-declaration
Chris Lattner535b8302008-06-21 19:39:06 +00004067/// [OBC] '@' 'defs' '(' class-name ')'
Steve Naroff97170802007-08-20 22:28:22 +00004068///
Chris Lattner1300fb92007-01-23 23:42:53 +00004069void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00004070 unsigned TagType, Decl *TagDecl) {
Jordan Rose1e879d82018-03-23 00:07:18 +00004071 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00004072 "parsing struct/union body");
Andy Gibbs22e140b2013-04-03 09:31:19 +00004073 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
Mike Stump11289f42009-09-09 15:08:12 +00004074
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004075 BalancedDelimiterTracker T(*this, tok::l_brace);
4076 if (T.consumeOpen())
4077 return;
Mike Stump11289f42009-09-09 15:08:12 +00004078
Douglas Gregor658b9552009-01-09 22:42:13 +00004079 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004080 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004081
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004082 SmallVector<Decl *, 32> FieldDecls;
Chris Lattnera12405b2008-04-10 06:46:29 +00004083
Chris Lattner7b9ace62007-01-23 20:11:08 +00004084 // While we still have something to read, read the declarations in the struct.
Richard Smith752ada82015-11-17 23:32:01 +00004085 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4086 Tok.isNot(tok::eof)) {
Chris Lattner90a26b02007-01-23 04:38:16 +00004087 // Each iteration of this loop reads one struct-declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004088
Chris Lattner736ed5d2007-06-09 05:59:07 +00004089 // Check for extraneous top-level semicolon.
Chris Lattner76c72282007-10-09 17:33:22 +00004090 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004091 ConsumeExtraSemi(InsideStruct, TagType);
Chris Lattner36e46a22007-06-09 05:49:55 +00004092 continue;
4093 }
Chris Lattnera12405b2008-04-10 06:46:29 +00004094
Andy Gibbsc804e082013-04-03 09:46:04 +00004095 // Parse _Static_assert declaration.
4096 if (Tok.is(tok::kw__Static_assert)) {
4097 SourceLocation DeclEnd;
4098 ParseStaticAssertDeclaration(DeclEnd);
4099 continue;
4100 }
4101
Argyrios Kyrtzidis71c12fb2013-04-18 01:42:35 +00004102 if (Tok.is(tok::annot_pragma_pack)) {
4103 HandlePragmaPack();
4104 continue;
4105 }
4106
4107 if (Tok.is(tok::annot_pragma_align)) {
4108 HandlePragmaAlign();
4109 continue;
4110 }
4111
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004112 if (Tok.is(tok::annot_pragma_openmp)) {
Alexey Bataev587e1de2016-03-30 10:43:55 +00004113 // Result can be ignored, because it must be always empty.
4114 AccessSpecifier AS = AS_none;
4115 ParsedAttributesWithRange Attrs(AttrFactory);
4116 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004117 continue;
4118 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004119
John McCallcfefb6d2009-11-03 02:38:08 +00004120 if (!Tok.is(tok::at)) {
Benjamin Kramera39beb92014-09-03 11:06:10 +00004121 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4122 // Install the declarator into the current TagDecl.
4123 Decl *Field =
4124 Actions.ActOnField(getCurScope(), TagDecl,
4125 FD.D.getDeclSpec().getSourceRange().getBegin(),
4126 FD.D, FD.BitfieldSize);
4127 FieldDecls.push_back(Field);
4128 FD.complete(Field);
4129 };
John McCallcfefb6d2009-11-03 02:38:08 +00004130
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004131 // Parse all the comma separated declarators.
4132 ParsingDeclSpec DS(*this);
Benjamin Kramera39beb92014-09-03 11:06:10 +00004133 ParseStructDeclaration(DS, CFieldCallback);
Chris Lattner535b8302008-06-21 19:39:06 +00004134 } else { // Handle @defs
4135 ConsumeToken();
4136 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4137 Diag(Tok, diag::err_unexpected_at);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004138 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004139 continue;
4140 }
4141 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004142 ExpectAndConsume(tok::l_paren);
Chris Lattner535b8302008-06-21 19:39:06 +00004143 if (!Tok.is(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004144 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004145 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004146 continue;
4147 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004148 SmallVector<Decl *, 16> Fields;
Douglas Gregor0be31a22010-07-02 17:43:08 +00004149 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004150 Tok.getIdentifierInfo(), Fields);
Chris Lattner535b8302008-06-21 19:39:06 +00004151 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4152 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004153 ExpectAndConsume(tok::r_paren);
Mike Stump11289f42009-09-09 15:08:12 +00004154 }
Chris Lattner736ed5d2007-06-09 05:59:07 +00004155
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004156 if (TryConsumeToken(tok::semi))
4157 continue;
4158
4159 if (Tok.is(tok::r_brace)) {
Chris Lattner245c5332010-02-02 00:37:27 +00004160 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
Chris Lattner0c7e82d2007-06-09 05:54:40 +00004161 break;
Chris Lattner90a26b02007-01-23 04:38:16 +00004162 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004163
4164 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4165 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4166 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4167 // If we stopped at a ';', eat it.
4168 TryConsumeToken(tok::semi);
Chris Lattner90a26b02007-01-23 04:38:16 +00004169 }
Mike Stump11289f42009-09-09 15:08:12 +00004170
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004171 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +00004172
John McCall084e83d2011-03-24 11:26:52 +00004173 ParsedAttributes attrs(AttrFactory);
Chris Lattner90a26b02007-01-23 04:38:16 +00004174 // If attributes exist after struct contents, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004175 MaybeParseGNUAttributes(attrs);
Daniel Dunbar15619c72008-10-03 02:03:53 +00004176
Erich Keanec480f302018-07-12 21:09:05 +00004177 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4178 T.getOpenLocation(), T.getCloseLocation(), attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004179 StructScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004180 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
Chris Lattner90a26b02007-01-23 04:38:16 +00004181}
4182
Chris Lattner3b561a32006-08-13 00:12:11 +00004183/// ParseEnumSpecifier
Chris Lattner1890ac82006-08-13 01:16:23 +00004184/// enum-specifier: [C99 6.7.2.2]
Chris Lattner3b561a32006-08-13 00:12:11 +00004185/// 'enum' identifier[opt] '{' enumerator-list '}'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004186///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
Chris Lattnere37e2332006-08-15 04:50:22 +00004187/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4188/// '}' attributes[opt]
Aaron Ballman9ecff022012-03-01 04:09:28 +00004189/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4190/// '}'
Chris Lattner3b561a32006-08-13 00:12:11 +00004191/// 'enum' identifier
Chris Lattnere37e2332006-08-15 04:50:22 +00004192/// [GNU] 'enum' attributes[opt] identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004193///
Richard Smith7d137e32012-03-23 03:33:32 +00004194/// [C++11] enum-head '{' enumerator-list[opt] '}'
4195/// [C++11] enum-head '{' enumerator-list ',' '}'
Douglas Gregor0bf31402010-10-08 23:50:27 +00004196///
Richard Smith7d137e32012-03-23 03:33:32 +00004197/// enum-head: [C++11]
4198/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4199/// enum-key attribute-specifier-seq[opt] nested-name-specifier
4200/// identifier enum-base[opt]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004201///
Richard Smith7d137e32012-03-23 03:33:32 +00004202/// enum-key: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004203/// 'enum'
4204/// 'enum' 'class'
4205/// 'enum' 'struct'
4206///
Richard Smith7d137e32012-03-23 03:33:32 +00004207/// enum-base: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004208/// ':' type-specifier-seq
4209///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004210/// [C++] elaborated-type-specifier:
4211/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4212///
Chris Lattnerffaa0e62009-04-12 21:49:30 +00004213void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregordc70c3a2010-03-02 17:53:14 +00004214 const ParsedTemplateInfo &TemplateInfo,
Richard Smithc5b05522012-03-12 07:56:15 +00004215 AccessSpecifier AS, DeclSpecContext DSC) {
Chris Lattnerffbc2712007-01-25 06:05:38 +00004216 // Parse the tag portion of this.
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004217 if (Tok.is(tok::code_completion)) {
4218 // Code completion for an enum name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004219 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00004220 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004221 }
John McCallcb432fa2011-07-06 05:58:41 +00004222
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004223 // If attributes exist after tag, parse them.
4224 ParsedAttributesWithRange attrs(AttrFactory);
4225 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004226 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004227 MaybeParseMicrosoftDeclSpecs(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004228
Richard Smith0f8ee222012-01-10 01:33:14 +00004229 SourceLocation ScopedEnumKWLoc;
John McCallcb432fa2011-07-06 05:58:41 +00004230 bool IsScopedUsingClassTag = false;
4231
John McCallbeae29a2012-06-23 22:30:04 +00004232 // In C++11, recognize 'enum class' and 'enum struct'.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004233 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
Richard Trieud0d87b52013-04-23 02:47:36 +00004234 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4235 : diag::ext_scoped_enum);
John McCallcb432fa2011-07-06 05:58:41 +00004236 IsScopedUsingClassTag = Tok.is(tok::kw_class);
Richard Smith0f8ee222012-01-10 01:33:14 +00004237 ScopedEnumKWLoc = ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004238
Bill Wendling44426052012-12-20 19:22:21 +00004239 // Attributes are not allowed between these keywords. Diagnose,
John McCallbeae29a2012-06-23 22:30:04 +00004240 // but then just treat them like they appeared in the right place.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004241 ProhibitAttributes(attrs);
John McCallbeae29a2012-06-23 22:30:04 +00004242
4243 // They are allowed afterwards, though.
4244 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004245 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004246 MaybeParseMicrosoftDeclSpecs(attrs);
John McCallcb432fa2011-07-06 05:58:41 +00004247 }
Richard Smith7d137e32012-03-23 03:33:32 +00004248
John McCall6347b682012-05-07 06:16:58 +00004249 // C++11 [temp.explicit]p12:
4250 // The usual access controls do not apply to names used to specify
4251 // explicit instantiations.
4252 // We extend this to also cover explicit specializations. Note that
4253 // we don't suppress if this turns out to be an elaborated type
4254 // specifier.
4255 bool shouldDelayDiagsInTag =
4256 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4257 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4258 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Richard Smith7d137e32012-03-23 03:33:32 +00004259
Richard Smithbfdb1082012-03-12 08:56:40 +00004260 // Enum definitions should not be parsed in a trailing-return-type.
Faisal Vali7db85c52017-12-31 00:06:40 +00004261 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
Richard Smithbfdb1082012-03-12 08:56:40 +00004262
Abramo Bagnarad7548482010-05-19 21:37:53 +00004263 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004264 if (getLangOpts().CPlusPlus) {
John McCallcb432fa2011-07-06 05:58:41 +00004265 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4266 // if a fixed underlying type is allowed.
Erik Pilkington6f11db12018-09-28 20:24:58 +00004267 ColonProtectionRAIIObject X(*this, AllowDeclaration);
Chad Rosierc1183952012-06-26 22:30:43 +00004268
Nico Webercfaa4cd2015-02-15 07:26:13 +00004269 CXXScopeSpec Spec;
David Blaikieefdccaa2016-01-15 23:43:34 +00004270 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
Richard Smith1d4b2e12013-04-01 21:43:41 +00004271 /*EnteringContext=*/true))
John McCall1f476a12010-02-26 08:45:28 +00004272 return;
4273
Nico Webercfaa4cd2015-02-15 07:26:13 +00004274 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004275 Diag(Tok, diag::err_expected) << tok::identifier;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004276 if (Tok.isNot(tok::l_brace)) {
4277 // Has no name and is not a definition.
4278 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004279 SkipUntil(tok::comma, StopAtSemi);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004280 return;
4281 }
4282 }
Nico Webercfaa4cd2015-02-15 07:26:13 +00004283
4284 SS = Spec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004285 }
Mike Stump11289f42009-09-09 15:08:12 +00004286
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004287 // Must have either 'enum name' or 'enum {...}'.
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004288 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
Erik Pilkington6f11db12018-09-28 20:24:58 +00004289 !(AllowDeclaration && Tok.is(tok::colon))) {
Alp Tokerec543272013-12-24 09:48:30 +00004290 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
Mike Stump11289f42009-09-09 15:08:12 +00004291
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004292 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004293 SkipUntil(tok::comma, StopAtSemi);
Chris Lattner3b561a32006-08-13 00:12:11 +00004294 return;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004295 }
Mike Stump11289f42009-09-09 15:08:12 +00004296
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004297 // If an identifier is present, consume and remember it.
Craig Topper161e4db2014-05-21 06:02:52 +00004298 IdentifierInfo *Name = nullptr;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004299 SourceLocation NameLoc;
4300 if (Tok.is(tok::identifier)) {
4301 Name = Tok.getIdentifierInfo();
4302 NameLoc = ConsumeToken();
4303 }
Mike Stump11289f42009-09-09 15:08:12 +00004304
Richard Smith0f8ee222012-01-10 01:33:14 +00004305 if (!Name && ScopedEnumKWLoc.isValid()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00004306 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4307 // declaration of a scoped enumeration.
4308 Diag(Tok, diag::err_scoped_enum_missing_identifier);
Richard Smith0f8ee222012-01-10 01:33:14 +00004309 ScopedEnumKWLoc = SourceLocation();
Abramo Bagnara0e05e242010-12-03 18:54:17 +00004310 IsScopedUsingClassTag = false;
Douglas Gregor0bf31402010-10-08 23:50:27 +00004311 }
4312
John McCall6347b682012-05-07 06:16:58 +00004313 // Okay, end the suppression area. We'll decide whether to emit the
4314 // diagnostics in a second.
4315 if (shouldDelayDiagsInTag)
4316 diagsFromTag.done();
Richard Smith7d137e32012-03-23 03:33:32 +00004317
Douglas Gregor0bf31402010-10-08 23:50:27 +00004318 TypeResult BaseType;
4319
Douglas Gregord1f69f62010-12-01 17:42:47 +00004320 // Parse the fixed underlying type.
Richard Smith200f47c2012-07-02 19:14:01 +00004321 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
Erik Pilkington6f11db12018-09-28 20:24:58 +00004322 if (AllowDeclaration && Tok.is(tok::colon)) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004323 bool PossibleBitfield = false;
Richard Smith200f47c2012-07-02 19:14:01 +00004324 if (CanBeBitfield) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004325 // If we're in class scope, this can either be an enum declaration with
4326 // an underlying type, or a declaration of a bitfield member. We try to
4327 // use a simple disambiguation scheme first to catch the common cases
Chad Rosierc1183952012-06-26 22:30:43 +00004328 // (integer literal, sizeof); if it's still ambiguous, we then consider
4329 // anything that's a simple-type-specifier followed by '(' as an
4330 // expression. This suffices because function types are not valid
Douglas Gregord1f69f62010-12-01 17:42:47 +00004331 // underlying types anyway.
Faisal Valid143a0c2017-04-01 21:30:49 +00004332 EnterExpressionEvaluationContext Unevaluated(
4333 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregord1f69f62010-12-01 17:42:47 +00004334 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
Chad Rosierc1183952012-06-26 22:30:43 +00004335 // If the next token starts an expression, we know we're parsing a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004336 // bit-field. This is the common case.
Richard Smithee390432014-05-16 01:56:53 +00004337 if (TPR == TPResult::True)
Douglas Gregord1f69f62010-12-01 17:42:47 +00004338 PossibleBitfield = true;
4339 // If the next token starts a type-specifier-seq, it may be either a
4340 // a fixed underlying type or the start of a function-style cast in C++;
Chad Rosierc1183952012-06-26 22:30:43 +00004341 // lookahead one more token to see if it's obvious that we have a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004342 // fixed underlying type.
Richard Smithee390432014-05-16 01:56:53 +00004343 else if (TPR == TPResult::False &&
Douglas Gregord1f69f62010-12-01 17:42:47 +00004344 GetLookAheadToken(2).getKind() == tok::semi) {
4345 // Consume the ':'.
4346 ConsumeToken();
4347 } else {
4348 // We have the start of a type-specifier-seq, so we have to perform
4349 // tentative parsing to determine whether we have an expression or a
4350 // type.
4351 TentativeParsingAction TPA(*this);
4352
4353 // Consume the ':'.
4354 ConsumeToken();
Richard Smith1e3b0f02012-02-23 01:36:12 +00004355
4356 // If we see a type specifier followed by an open-brace, we have an
4357 // ambiguity between an underlying type and a C++11 braced
4358 // function-style cast. Resolve this by always treating it as an
4359 // underlying type.
4360 // FIXME: The standard is not entirely clear on how to disambiguate in
4361 // this case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004362 if ((getLangOpts().CPlusPlus &&
Richard Smithee390432014-05-16 01:56:53 +00004363 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00004364 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004365 // We'll parse this as a bitfield later.
4366 PossibleBitfield = true;
4367 TPA.Revert();
4368 } else {
4369 // We have a type-specifier-seq.
4370 TPA.Commit();
4371 }
4372 }
4373 } else {
4374 // Consume the ':'.
4375 ConsumeToken();
4376 }
4377
4378 if (!PossibleBitfield) {
4379 SourceRange Range;
4380 BaseType = ParseTypeName(&Range);
Chad Rosierc1183952012-06-26 22:30:43 +00004381
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004382 if (!getLangOpts().ObjC) {
Erik Pilkington6f11db12018-09-28 20:24:58 +00004383 if (getLangOpts().CPlusPlus11)
4384 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4385 else if (getLangOpts().CPlusPlus)
4386 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4387 else if (getLangOpts().MicrosoftExt)
4388 Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004389 else
Erik Pilkington6f11db12018-09-28 20:24:58 +00004390 Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004391 }
Douglas Gregord1f69f62010-12-01 17:42:47 +00004392 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004393 }
4394
Richard Smith0f8ee222012-01-10 01:33:14 +00004395 // There are four options here. If we have 'friend enum foo;' then this is a
4396 // friend declaration, and cannot have an accompanying definition. If we have
4397 // 'enum foo;', then this is a forward declaration. If we have
4398 // 'enum foo {...' then this is a definition. Otherwise we have something
4399 // like 'enum foo xyz', a reference.
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004400 //
4401 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4402 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4403 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4404 //
John McCallfaf5fb42010-08-26 23:41:50 +00004405 Sema::TagUseKind TUK;
John McCall6347b682012-05-07 06:16:58 +00004406 if (!AllowDeclaration) {
Richard Smithbfdb1082012-03-12 08:56:40 +00004407 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004408 } else if (Tok.is(tok::l_brace)) {
4409 if (DS.isFriendSpecified()) {
4410 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4411 << SourceRange(DS.getFriendSpecLoc());
4412 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004413 SkipUntil(tok::r_brace, StopAtSemi);
John McCall6347b682012-05-07 06:16:58 +00004414 TUK = Sema::TUK_Friend;
4415 } else {
4416 TUK = Sema::TUK_Definition;
4417 }
Richard Smith649c7b062014-01-08 00:56:48 +00004418 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00004419 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00004420 (Tok.isAtStartOfLine() &&
4421 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
Richard Smith369b9f92012-06-25 21:37:02 +00004422 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4423 if (Tok.isNot(tok::semi)) {
4424 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00004425 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004426 PP.EnterToken(Tok);
4427 Tok.setKind(tok::semi);
4428 }
John McCall6347b682012-05-07 06:16:58 +00004429 } else {
John McCallfaf5fb42010-08-26 23:41:50 +00004430 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004431 }
4432
4433 // If this is an elaborated type specifier, and we delayed
4434 // diagnostics before, just merge them into the current pool.
4435 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4436 diagsFromTag.redelay();
4437 }
Richard Smith7d137e32012-03-23 03:33:32 +00004438
4439 MultiTemplateParamsArg TParams;
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004440 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
John McCallfaf5fb42010-08-26 23:41:50 +00004441 TUK != Sema::TUK_Reference) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004442 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
Richard Smith7d137e32012-03-23 03:33:32 +00004443 // Skip the rest of this declarator, up until the comma or semicolon.
4444 Diag(Tok, diag::err_enum_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004445 SkipUntil(tok::comma, StopAtSemi);
Richard Smith7d137e32012-03-23 03:33:32 +00004446 return;
4447 }
4448
4449 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4450 // Enumerations can't be explicitly instantiated.
4451 DS.SetTypeSpecError();
4452 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4453 return;
4454 }
4455
4456 assert(TemplateInfo.TemplateParams && "no template parameters");
4457 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4458 TemplateInfo.TemplateParams->size());
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004459 }
Chad Rosierc1183952012-06-26 22:30:43 +00004460
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004461 if (TUK == Sema::TUK_Reference)
4462 ProhibitAttributes(attrs);
Richard Smith7d137e32012-03-23 03:33:32 +00004463
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004464 if (!Name && TUK != Sema::TUK_Definition) {
4465 Diag(Tok, diag::err_enumerator_unnamed_no_def);
Richard Smith7d137e32012-03-23 03:33:32 +00004466
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004467 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004468 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004469 return;
4470 }
Richard Smith7d137e32012-03-23 03:33:32 +00004471
Nico Weber32a0fc72016-09-03 03:01:32 +00004472 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00004473
Richard Smithd9ba2242015-05-07 03:54:19 +00004474 Sema::SkipBodyInfo SkipBody;
4475 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4476 NextToken().is(tok::identifier))
4477 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4478 NextToken().getIdentifierInfo(),
4479 NextToken().getLocation());
4480
Douglas Gregord6ab8742009-05-28 23:31:59 +00004481 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004482 bool IsDependent = false;
Craig Topper161e4db2014-05-21 06:02:52 +00004483 const char *PrevSpec = nullptr;
Douglas Gregorba41d012010-04-24 16:38:41 +00004484 unsigned DiagID;
Faisal Vali7db85c52017-12-31 00:06:40 +00004485 Decl *TagDecl = Actions.ActOnTag(
4486 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
Erich Keanec480f302018-07-12 21:09:05 +00004487 attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4488 ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
Faisal Vali7db85c52017-12-31 00:06:40 +00004489 DSC == DeclSpecContext::DSC_type_specifier,
4490 DSC == DeclSpecContext::DSC_template_param ||
4491 DSC == DeclSpecContext::DSC_template_type_arg,
4492 &SkipBody);
Richard Smithd9ba2242015-05-07 03:54:19 +00004493
4494 if (SkipBody.ShouldSkip) {
4495 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4496
4497 BalancedDelimiterTracker T(*this, tok::l_brace);
4498 T.consumeOpen();
4499 T.skipToEnd();
4500
4501 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4502 NameLoc.isValid() ? NameLoc : StartLoc,
4503 PrevSpec, DiagID, TagDecl, Owned,
4504 Actions.getASTContext().getPrintingPolicy()))
4505 Diag(StartLoc, DiagID) << PrevSpec;
4506 return;
4507 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004508
Douglas Gregorba41d012010-04-24 16:38:41 +00004509 if (IsDependent) {
Chad Rosierc1183952012-06-26 22:30:43 +00004510 // This enum has a dependent nested-name-specifier. Handle it as a
Douglas Gregorba41d012010-04-24 16:38:41 +00004511 // dependent tag.
4512 if (!Name) {
4513 DS.SetTypeSpecError();
4514 Diag(Tok, diag::err_expected_type_name_after_typename);
4515 return;
4516 }
Chad Rosierc1183952012-06-26 22:30:43 +00004517
Nico Weber83ea0122014-05-03 21:57:40 +00004518 TypeResult Type = Actions.ActOnDependentTag(
4519 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
Douglas Gregorba41d012010-04-24 16:38:41 +00004520 if (Type.isInvalid()) {
4521 DS.SetTypeSpecError();
4522 return;
4523 }
Chad Rosierc1183952012-06-26 22:30:43 +00004524
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004525 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4526 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004527 PrevSpec, DiagID, Type.get(),
4528 Actions.getASTContext().getPrintingPolicy()))
Douglas Gregorba41d012010-04-24 16:38:41 +00004529 Diag(StartLoc, DiagID) << PrevSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00004530
Douglas Gregorba41d012010-04-24 16:38:41 +00004531 return;
4532 }
Mike Stump11289f42009-09-09 15:08:12 +00004533
John McCall48871652010-08-21 09:40:31 +00004534 if (!TagDecl) {
Chad Rosierc1183952012-06-26 22:30:43 +00004535 // The action failed to produce an enumeration tag. If this is a
Douglas Gregorba41d012010-04-24 16:38:41 +00004536 // definition, consume the entire definition.
Richard Smithbfdb1082012-03-12 08:56:40 +00004537 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
Douglas Gregorba41d012010-04-24 16:38:41 +00004538 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004539 SkipUntil(tok::r_brace, StopAtSemi);
Douglas Gregorba41d012010-04-24 16:38:41 +00004540 }
Chad Rosierc1183952012-06-26 22:30:43 +00004541
Douglas Gregorba41d012010-04-24 16:38:41 +00004542 DS.SetTypeSpecError();
4543 return;
4544 }
Richard Smith0f8ee222012-01-10 01:33:14 +00004545
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004546 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4547 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4548 ParseEnumBody(StartLoc, D);
4549 if (SkipBody.CheckSameAsPrevious &&
4550 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4551 DS.SetTypeSpecError();
4552 return;
4553 }
4554 }
Mike Stump11289f42009-09-09 15:08:12 +00004555
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004556 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4557 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004558 PrevSpec, DiagID, TagDecl, Owned,
4559 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00004560 Diag(StartLoc, DiagID) << PrevSpec;
Chris Lattner3b561a32006-08-13 00:12:11 +00004561}
4562
Chris Lattnerc1915e22007-01-25 07:29:02 +00004563/// ParseEnumBody - Parse a {} enclosed enumerator-list.
4564/// enumerator-list:
4565/// enumerator
4566/// enumerator-list ',' enumerator
4567/// enumerator:
Aaron Ballman730476b2014-11-08 15:33:35 +00004568/// enumeration-constant attributes[opt]
4569/// enumeration-constant attributes[opt] '=' constant-expression
Chris Lattnerc1915e22007-01-25 07:29:02 +00004570/// enumeration-constant:
4571/// identifier
4572///
John McCall48871652010-08-21 09:40:31 +00004573void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004574 // Enter the scope of the enum body and start the definition.
Hans Wennborgfe781452014-06-17 00:00:18 +00004575 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004576 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
Douglas Gregor07665a62009-01-05 19:45:36 +00004577
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004578 BalancedDelimiterTracker T(*this, tok::l_brace);
4579 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00004580
Chris Lattner37256fb2007-08-27 17:24:30 +00004581 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
David Blaikiebbafb8a2012-03-11 07:00:24 +00004582 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
Richard Smithf8812672016-12-02 22:38:31 +00004583 Diag(Tok, diag::err_empty_enum);
Mike Stump11289f42009-09-09 15:08:12 +00004584
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004585 SmallVector<Decl *, 32> EnumConstantDecls;
Jordan Rose60ac3162015-04-30 17:20:30 +00004586 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
Chris Lattnerc1915e22007-01-25 07:29:02 +00004587
Craig Topper161e4db2014-05-21 06:02:52 +00004588 Decl *LastEnumConstDecl = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004589
Chris Lattnerc1915e22007-01-25 07:29:02 +00004590 // Parse the enumerator-list.
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004591 while (Tok.isNot(tok::r_brace)) {
4592 // Parse enumerator. If failed, try skipping till the start of the next
4593 // enumerator definition.
4594 if (Tok.isNot(tok::identifier)) {
4595 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4596 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4597 TryConsumeToken(tok::comma))
4598 continue;
4599 break;
4600 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004601 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4602 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00004603
John McCall811a0f52010-10-22 23:36:17 +00004604 // If attributes exist after the enumerator, parse them.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004605 ParsedAttributesWithRange attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004606 MaybeParseGNUAttributes(attrs);
Aaron Ballman730476b2014-11-08 15:33:35 +00004607 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
Aaron Ballman606093a2017-10-15 15:01:42 +00004608 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4609 if (getLangOpts().CPlusPlus)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004610 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Aaron Ballman606093a2017-10-15 15:01:42 +00004611 ? diag::warn_cxx14_compat_ns_enum_attribute
4612 : diag::ext_ns_enum_attribute)
4613 << 1 /*enumerator*/;
Aaron Ballman730476b2014-11-08 15:33:35 +00004614 ParseCXX11Attributes(attrs);
4615 }
John McCall811a0f52010-10-22 23:36:17 +00004616
Chris Lattnerc1915e22007-01-25 07:29:02 +00004617 SourceLocation EqualLoc;
John McCalldadc5752010-08-24 06:29:42 +00004618 ExprResult AssignedVal;
Jordan Rose60ac3162015-04-30 17:20:30 +00004619 EnumAvailabilityDiags.emplace_back(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00004620
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004621 if (TryConsumeToken(tok::equal, EqualLoc)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004622 AssignedVal = ParseConstantExpression();
4623 if (AssignedVal.isInvalid())
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004624 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
Chris Lattnerc1915e22007-01-25 07:29:02 +00004625 }
Mike Stump11289f42009-09-09 15:08:12 +00004626
Chris Lattnerc1915e22007-01-25 07:29:02 +00004627 // Install the enumerator constant into EnumDecl.
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004628 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
Erich Keanec480f302018-07-12 21:09:05 +00004629 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4630 EqualLoc, AssignedVal.get());
Jordan Rose60ac3162015-04-30 17:20:30 +00004631 EnumAvailabilityDiags.back().done();
Chad Rosierc1183952012-06-26 22:30:43 +00004632
Chris Lattner4ef40012007-06-11 01:28:17 +00004633 EnumConstantDecls.push_back(EnumConstDecl);
4634 LastEnumConstDecl = EnumConstDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004635
Douglas Gregorce66d022010-09-07 14:51:08 +00004636 if (Tok.is(tok::identifier)) {
4637 // We're missing a comma between enumerators.
Richard Smithbdb84f32016-07-22 23:36:59 +00004638 SourceLocation Loc = getEndOfPreviousToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004639 Diag(Loc, diag::err_enumerator_list_missing_comma)
Douglas Gregorce66d022010-09-07 14:51:08 +00004640 << FixItHint::CreateInsertion(Loc, ", ");
4641 continue;
4642 }
Chad Rosierc1183952012-06-26 22:30:43 +00004643
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004644 // Emumerator definition must be finished, only comma or r_brace are
4645 // allowed here.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004646 SourceLocation CommaLoc;
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004647 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4648 if (EqualLoc.isValid())
4649 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4650 << tok::comma;
4651 else
4652 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4653 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4654 if (TryConsumeToken(tok::comma, CommaLoc))
4655 continue;
4656 } else {
4657 break;
4658 }
4659 }
Mike Stump11289f42009-09-09 15:08:12 +00004660
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004661 // If comma is followed by r_brace, emit appropriate warning.
4662 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004663 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
Richard Smith87f5dc52012-07-23 05:45:25 +00004664 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4665 diag::ext_enumerator_list_comma_cxx :
4666 diag::ext_enumerator_list_comma_c)
Richard Smith5d164bc2011-10-15 05:09:34 +00004667 << FixItHint::CreateRemoval(CommaLoc);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004668 else if (getLangOpts().CPlusPlus11)
Richard Smith5d164bc2011-10-15 05:09:34 +00004669 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4670 << FixItHint::CreateRemoval(CommaLoc);
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004671 break;
Richard Smith5d164bc2011-10-15 05:09:34 +00004672 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004673 }
Mike Stump11289f42009-09-09 15:08:12 +00004674
Chris Lattnerc1915e22007-01-25 07:29:02 +00004675 // Eat the }.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004676 T.consumeClose();
Chris Lattnerc1915e22007-01-25 07:29:02 +00004677
Chris Lattnerc1915e22007-01-25 07:29:02 +00004678 // If attributes exist after the identifier list, parse them.
John McCall084e83d2011-03-24 11:26:52 +00004679 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004680 MaybeParseGNUAttributes(attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004681
Erich Keanec480f302018-07-12 21:09:05 +00004682 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4683 getCurScope(), attrs);
Mike Stump11289f42009-09-09 15:08:12 +00004684
Jordan Rose60ac3162015-04-30 17:20:30 +00004685 // Now handle enum constant availability diagnostics.
4686 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4687 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4688 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4689 EnumAvailabilityDiags[i].redelay();
4690 PD.complete(EnumConstantDecls[i]);
4691 }
4692
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004693 EnumScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004694 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
Richard Smith369b9f92012-06-25 21:37:02 +00004695
4696 // The next token must be valid after an enum definition. If not, a ';'
4697 // was probably forgotten.
Richard Smith200f47c2012-07-02 19:14:01 +00004698 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4699 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
Alp Toker383d2c42014-01-01 03:08:43 +00004700 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004701 // Push this token back into the preprocessor and change our current token
4702 // to ';' so that the rest of the code recovers as though there were an
4703 // ';' after the definition.
4704 PP.EnterToken(Tok);
4705 Tok.setKind(tok::semi);
4706 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004707}
Chris Lattner3b561a32006-08-13 00:12:11 +00004708
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004709/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4710/// is definitely a type-specifier. Return false if it isn't part of a type
4711/// specifier or if we're not sure.
4712bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4713 switch (Tok.getKind()) {
4714 default: return false;
4715 // type-specifiers
4716 case tok::kw_short:
4717 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004718 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004719 case tok::kw___int128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004720 case tok::kw_signed:
4721 case tok::kw_unsigned:
4722 case tok::kw__Complex:
4723 case tok::kw__Imaginary:
4724 case tok::kw_void:
4725 case tok::kw_char:
4726 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004727 case tok::kw_char8_t:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004728 case tok::kw_char16_t:
4729 case tok::kw_char32_t:
4730 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004731 case tok::kw_half:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004732 case tok::kw_float:
4733 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004734 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004735 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004736 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004737 case tok::kw___float128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004738 case tok::kw_bool:
4739 case tok::kw__Bool:
4740 case tok::kw__Decimal32:
4741 case tok::kw__Decimal64:
4742 case tok::kw__Decimal128:
4743 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004744#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004745#include "clang/Basic/OpenCLImageTypes.def"
Chad Rosierc1183952012-06-26 22:30:43 +00004746
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004747 // struct-or-union-specifier (C99) or class-specifier (C++)
4748 case tok::kw_class:
4749 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004750 case tok::kw___interface:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004751 case tok::kw_union:
4752 // enum-specifier
4753 case tok::kw_enum:
Chad Rosierc1183952012-06-26 22:30:43 +00004754
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004755 // typedef-name
4756 case tok::annot_typename:
4757 return true;
4758 }
4759}
4760
Steve Naroff69e8f9e2008-02-11 23:15:56 +00004761/// isTypeSpecifierQualifier - Return true if the current token could be the
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004762/// start of a specifier-qualifier-list.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004763bool Parser::isTypeSpecifierQualifier() {
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004764 switch (Tok.getKind()) {
4765 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004766
Chris Lattner020bab92009-01-04 23:41:41 +00004767 case tok::identifier: // foo::bar
John Thompson22334602010-02-05 00:12:22 +00004768 if (TryAltiVecVectorToken())
4769 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004770 LLVM_FALLTHROUGH;
Douglas Gregor333489b2009-03-27 23:10:48 +00004771 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004772 // Annotate typenames and C++ scope specifiers. If we get one, just
4773 // recurse to handle whatever we get.
4774 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004775 return true;
4776 if (Tok.is(tok::identifier))
4777 return false;
4778 return isTypeSpecifierQualifier();
Douglas Gregor333489b2009-03-27 23:10:48 +00004779
Chris Lattner020bab92009-01-04 23:41:41 +00004780 case tok::coloncolon: // ::foo::bar
4781 if (NextToken().is(tok::kw_new) || // ::new
4782 NextToken().is(tok::kw_delete)) // ::delete
4783 return false;
4784
Chris Lattner020bab92009-01-04 23:41:41 +00004785 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004786 return true;
4787 return isTypeSpecifierQualifier();
Mike Stump11289f42009-09-09 15:08:12 +00004788
Chris Lattnere37e2332006-08-15 04:50:22 +00004789 // GNU attributes support.
4790 case tok::kw___attribute:
Steve Naroffad373bd2007-07-31 12:34:36 +00004791 // GNU typeof support.
4792 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004793
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004794 // type-specifiers
4795 case tok::kw_short:
4796 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004797 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004798 case tok::kw___int128:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004799 case tok::kw_signed:
4800 case tok::kw_unsigned:
4801 case tok::kw__Complex:
4802 case tok::kw__Imaginary:
4803 case tok::kw_void:
4804 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004805 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004806 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004807 case tok::kw_char16_t:
4808 case tok::kw_char32_t:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004809 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004810 case tok::kw_half:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004811 case tok::kw_float:
4812 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004813 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004814 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004815 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004816 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004817 case tok::kw_bool:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004818 case tok::kw__Bool:
4819 case tok::kw__Decimal32:
4820 case tok::kw__Decimal64:
4821 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004822 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004823#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004824#include "clang/Basic/OpenCLImageTypes.def"
Mike Stump11289f42009-09-09 15:08:12 +00004825
Chris Lattner861a2262008-04-13 18:59:07 +00004826 // struct-or-union-specifier (C99) or class-specifier (C++)
4827 case tok::kw_class:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004828 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004829 case tok::kw___interface:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004830 case tok::kw_union:
4831 // enum-specifier
4832 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004833
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004834 // type-qualifier
4835 case tok::kw_const:
4836 case tok::kw_volatile:
4837 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004838 case tok::kw__Sat:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004839
John McCallea0a39e2012-11-14 00:49:39 +00004840 // Debugger support.
4841 case tok::kw___unknown_anytype:
4842
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004843 // typedef-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00004844 case tok::annot_typename:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004845 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004846
Chris Lattner409bf7d2008-10-20 00:25:30 +00004847 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4848 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004849 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00004850
Steve Naroff44ac7772008-12-25 14:16:32 +00004851 case tok::kw___cdecl:
4852 case tok::kw___stdcall:
4853 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004854 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004855 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004856 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004857 case tok::kw___w64:
4858 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004859 case tok::kw___ptr32:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004860 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004861 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004862
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004863 case tok::kw__Nonnull:
4864 case tok::kw__Nullable:
4865 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004866
Douglas Gregorab209d82015-07-07 03:58:42 +00004867 case tok::kw___kindof:
4868
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004869 case tok::kw___private:
4870 case tok::kw___local:
4871 case tok::kw___global:
4872 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004873 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004874 case tok::kw___read_only:
4875 case tok::kw___read_write:
4876 case tok::kw___write_only:
Eli Friedman53339e02009-06-08 23:27:34 +00004877 return true;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004878
Anastasia Stulova314fab62019-03-28 11:47:14 +00004879 case tok::kw_private:
4880 return getLangOpts().OpenCL;
4881
Richard Smith8e1ac332013-03-28 01:55:44 +00004882 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004883 case tok::kw__Atomic:
4884 return true;
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004885 }
4886}
4887
Chris Lattneracd58a32006-08-06 17:24:14 +00004888/// isDeclarationSpecifier() - Return true if the current token is part of a
4889/// declaration specifier.
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004890///
4891/// \param DisambiguatingWithExpression True to indicate that the purpose of
4892/// this check is to disambiguate between an expression and a declaration.
4893bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
Chris Lattneracd58a32006-08-06 17:24:14 +00004894 switch (Tok.getKind()) {
4895 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004896
Xiuli Pan9c14e282016-01-09 12:53:17 +00004897 case tok::kw_pipe:
4898 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4899
Chris Lattner020bab92009-01-04 23:41:41 +00004900 case tok::identifier: // foo::bar
Steve Naroff9527bbf2009-03-09 21:12:44 +00004901 // Unfortunate hack to support "Class.factoryMethod" notation.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004902 if (getLangOpts().ObjC && NextToken().is(tok::period))
Steve Naroff9527bbf2009-03-09 21:12:44 +00004903 return false;
John Thompson22334602010-02-05 00:12:22 +00004904 if (TryAltiVecVectorToken())
4905 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004906 LLVM_FALLTHROUGH;
David Blaikie15a430a2011-12-04 05:04:18 +00004907 case tok::kw_decltype: // decltype(T())::type
Douglas Gregor333489b2009-03-27 23:10:48 +00004908 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004909 // Annotate typenames and C++ scope specifiers. If we get one, just
4910 // recurse to handle whatever we get.
4911 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004912 return true;
4913 if (Tok.is(tok::identifier))
4914 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004915
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004916 // If we're in Objective-C and we have an Objective-C class type followed
Chad Rosierc1183952012-06-26 22:30:43 +00004917 // by an identifier and then either ':' or ']', in a place where an
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004918 // expression is permitted, then this is probably a class message send
4919 // missing the initial '['. In this case, we won't consider this to be
4920 // the start of a declaration.
Chad Rosierc1183952012-06-26 22:30:43 +00004921 if (DisambiguatingWithExpression &&
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004922 isStartOfObjCClassMessageMissingOpenBracket())
4923 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004924
John McCall1f476a12010-02-26 08:45:28 +00004925 return isDeclarationSpecifier();
4926
Chris Lattner020bab92009-01-04 23:41:41 +00004927 case tok::coloncolon: // ::foo::bar
4928 if (NextToken().is(tok::kw_new) || // ::new
4929 NextToken().is(tok::kw_delete)) // ::delete
4930 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004931
Chris Lattner020bab92009-01-04 23:41:41 +00004932 // Annotate typenames and C++ scope specifiers. If we get one, just
4933 // recurse to handle whatever we get.
4934 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004935 return true;
4936 return isDeclarationSpecifier();
Mike Stump11289f42009-09-09 15:08:12 +00004937
Chris Lattneracd58a32006-08-06 17:24:14 +00004938 // storage-class-specifier
4939 case tok::kw_typedef:
4940 case tok::kw_extern:
Steve Naroff2050b0d2007-12-18 00:16:02 +00004941 case tok::kw___private_extern__:
Chris Lattneracd58a32006-08-06 17:24:14 +00004942 case tok::kw_static:
4943 case tok::kw_auto:
Richard Smithe301ba22015-11-11 02:02:15 +00004944 case tok::kw___auto_type:
Chris Lattneracd58a32006-08-06 17:24:14 +00004945 case tok::kw_register:
4946 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00004947 case tok::kw_thread_local:
4948 case tok::kw__Thread_local:
Mike Stump11289f42009-09-09 15:08:12 +00004949
Douglas Gregor26701a42011-09-09 02:06:17 +00004950 // Modules
4951 case tok::kw___module_private__:
Chad Rosierc1183952012-06-26 22:30:43 +00004952
John McCallea0a39e2012-11-14 00:49:39 +00004953 // Debugger support
4954 case tok::kw___unknown_anytype:
4955
Chris Lattneracd58a32006-08-06 17:24:14 +00004956 // type-specifiers
4957 case tok::kw_short:
4958 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004959 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004960 case tok::kw___int128:
Chris Lattneracd58a32006-08-06 17:24:14 +00004961 case tok::kw_signed:
4962 case tok::kw_unsigned:
4963 case tok::kw__Complex:
4964 case tok::kw__Imaginary:
4965 case tok::kw_void:
4966 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004967 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004968 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004969 case tok::kw_char16_t:
4970 case tok::kw_char32_t:
4971
Chris Lattneracd58a32006-08-06 17:24:14 +00004972 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004973 case tok::kw_half:
Chris Lattneracd58a32006-08-06 17:24:14 +00004974 case tok::kw_float:
4975 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004976 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004977 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004978 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004979 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004980 case tok::kw_bool:
Chris Lattneracd58a32006-08-06 17:24:14 +00004981 case tok::kw__Bool:
4982 case tok::kw__Decimal32:
4983 case tok::kw__Decimal64:
4984 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004985 case tok::kw___vector:
Mike Stump11289f42009-09-09 15:08:12 +00004986
Chris Lattner861a2262008-04-13 18:59:07 +00004987 // struct-or-union-specifier (C99) or class-specifier (C++)
4988 case tok::kw_class:
Chris Lattneracd58a32006-08-06 17:24:14 +00004989 case tok::kw_struct:
4990 case tok::kw_union:
Joao Matosdc86f942012-08-31 18:45:21 +00004991 case tok::kw___interface:
Chris Lattneracd58a32006-08-06 17:24:14 +00004992 // enum-specifier
4993 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004994
Chris Lattneracd58a32006-08-06 17:24:14 +00004995 // type-qualifier
4996 case tok::kw_const:
4997 case tok::kw_volatile:
4998 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004999 case tok::kw__Sat:
Steve Naroffad373bd2007-07-31 12:34:36 +00005000
Chris Lattneracd58a32006-08-06 17:24:14 +00005001 // function-specifier
5002 case tok::kw_inline:
Douglas Gregor61956c42008-10-31 09:07:45 +00005003 case tok::kw_virtual:
5004 case tok::kw_explicit:
Richard Smith0015f092013-01-17 22:16:11 +00005005 case tok::kw__Noreturn:
Chris Lattner7b20dc72007-08-09 16:40:21 +00005006
Richard Smith1dba27c2013-01-29 09:02:09 +00005007 // alignment-specifier
5008 case tok::kw__Alignas:
5009
Richard Smithd16fe122012-10-25 00:00:53 +00005010 // friend keyword.
5011 case tok::kw_friend:
5012
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00005013 // static_assert-declaration
5014 case tok::kw__Static_assert:
5015
Chris Lattner599e47e2007-08-09 17:01:07 +00005016 // GNU typeof support.
5017 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00005018
Chris Lattner599e47e2007-08-09 17:01:07 +00005019 // GNU attributes.
Chris Lattner7b20dc72007-08-09 16:40:21 +00005020 case tok::kw___attribute:
Mike Stump11289f42009-09-09 15:08:12 +00005021
Richard Smithd16fe122012-10-25 00:00:53 +00005022 // C++11 decltype and constexpr.
David Blaikie15a430a2011-12-04 05:04:18 +00005023 case tok::annot_decltype:
Richard Smithd16fe122012-10-25 00:00:53 +00005024 case tok::kw_constexpr:
Francois Pichete878cb62011-06-19 08:02:06 +00005025
Richard Smith8e1ac332013-03-28 01:55:44 +00005026 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00005027 case tok::kw__Atomic:
5028 return true;
5029
Chris Lattner8b2ec162008-07-26 03:38:44 +00005030 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5031 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005032 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00005033
Douglas Gregor19b7acf2011-04-27 05:41:15 +00005034 // typedef-name
5035 case tok::annot_typename:
5036 return !DisambiguatingWithExpression ||
5037 !isStartOfObjCClassMessageMissingOpenBracket();
Chad Rosierc1183952012-06-26 22:30:43 +00005038
Steve Narofff192fab2009-01-06 19:34:12 +00005039 case tok::kw___declspec:
Steve Naroff44ac7772008-12-25 14:16:32 +00005040 case tok::kw___cdecl:
5041 case tok::kw___stdcall:
5042 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005043 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005044 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005045 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00005046 case tok::kw___w64:
Aaron Ballman317a77f2013-05-22 23:25:32 +00005047 case tok::kw___sptr:
5048 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005049 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005050 case tok::kw___ptr32:
Eli Friedman53339e02009-06-08 23:27:34 +00005051 case tok::kw___forceinline:
Dawn Perchik335e16b2010-09-03 01:29:35 +00005052 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00005053 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005054
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005055 case tok::kw__Nonnull:
5056 case tok::kw__Nullable:
5057 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005058
Douglas Gregorab209d82015-07-07 03:58:42 +00005059 case tok::kw___kindof:
5060
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005061 case tok::kw___private:
5062 case tok::kw___local:
5063 case tok::kw___global:
5064 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005065 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005066 case tok::kw___read_only:
5067 case tok::kw___read_write:
5068 case tok::kw___write_only:
Alexey Bader954ba212016-04-08 13:40:33 +00005069#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00005070#include "clang/Basic/OpenCLImageTypes.def"
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005071
Eli Friedman53339e02009-06-08 23:27:34 +00005072 return true;
Anastasia Stulova314fab62019-03-28 11:47:14 +00005073
5074 case tok::kw_private:
5075 return getLangOpts().OpenCL;
Chris Lattneracd58a32006-08-06 17:24:14 +00005076 }
5077}
5078
Richard Smith35845152017-02-07 01:37:30 +00005079bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005080 TentativeParsingAction TPA(*this);
5081
5082 // Parse the C++ scope specifier.
5083 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005084 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005085 /*EnteringContext=*/true)) {
John McCall1f476a12010-02-26 08:45:28 +00005086 TPA.Revert();
5087 return false;
5088 }
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005089
5090 // Parse the constructor name.
Richard Smithaf3b3252017-05-18 19:21:48 +00005091 if (Tok.is(tok::identifier)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005092 // We already know that we have a constructor name; just consume
5093 // the token.
5094 ConsumeToken();
Richard Smithaf3b3252017-05-18 19:21:48 +00005095 } else if (Tok.is(tok::annot_template_id)) {
5096 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005097 } else {
5098 TPA.Revert();
5099 return false;
5100 }
5101
Richard Smith8f8697f2017-02-08 01:16:55 +00005102 // There may be attributes here, appertaining to the constructor name or type
5103 // we just stepped past.
5104 SkipCXX11Attributes();
5105
Richard Smith43f340f2012-03-27 23:05:05 +00005106 // Current class name must be followed by a left parenthesis.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005107 if (Tok.isNot(tok::l_paren)) {
5108 TPA.Revert();
5109 return false;
5110 }
5111 ConsumeParen();
5112
Richard Smith43f340f2012-03-27 23:05:05 +00005113 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5114 // that we have a constructor.
5115 if (Tok.is(tok::r_paren) ||
5116 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005117 TPA.Revert();
5118 return true;
5119 }
5120
Richard Smithf2163662013-09-06 00:12:20 +00005121 // A C++11 attribute here signals that we have a constructor, and is an
5122 // attribute on the first constructor parameter.
5123 if (getLangOpts().CPlusPlus11 &&
5124 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5125 /*OuterMightBeMessageSend*/ true)) {
5126 TPA.Revert();
5127 return true;
5128 }
5129
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005130 // If we need to, enter the specified scope.
5131 DeclaratorScopeObj DeclScopeObj(*this, SS);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005132 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005133 DeclScopeObj.EnterDeclaratorScope();
5134
Francois Pichet79f3a872011-01-31 04:54:32 +00005135 // Optionally skip Microsoft attributes.
John McCall084e83d2011-03-24 11:26:52 +00005136 ParsedAttributes Attrs(AttrFactory);
Francois Pichet79f3a872011-01-31 04:54:32 +00005137 MaybeParseMicrosoftAttributes(Attrs);
5138
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005139 // Check whether the next token(s) are part of a declaration
5140 // specifier, in which case we have the start of a parameter and,
5141 // therefore, we know that this is a constructor.
Richard Smithefd009d2012-03-27 00:56:56 +00005142 bool IsConstructor = false;
5143 if (isDeclarationSpecifier())
5144 IsConstructor = true;
5145 else if (Tok.is(tok::identifier) ||
5146 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5147 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5148 // This might be a parenthesized member name, but is more likely to
5149 // be a constructor declaration with an invalid argument type. Keep
5150 // looking.
5151 if (Tok.is(tok::annot_cxxscope))
Richard Smithaf3b3252017-05-18 19:21:48 +00005152 ConsumeAnnotationToken();
Richard Smithefd009d2012-03-27 00:56:56 +00005153 ConsumeToken();
5154
5155 // If this is not a constructor, we must be parsing a declarator,
Richard Smith1453e312012-03-27 01:42:32 +00005156 // which must have one of the following syntactic forms (see the
5157 // grammar extract at the start of ParseDirectDeclarator):
Richard Smithefd009d2012-03-27 00:56:56 +00005158 switch (Tok.getKind()) {
5159 case tok::l_paren:
5160 // C(X ( int));
5161 case tok::l_square:
5162 // C(X [ 5]);
5163 // C(X [ [attribute]]);
5164 case tok::coloncolon:
5165 // C(X :: Y);
5166 // C(X :: *p);
Richard Smithefd009d2012-03-27 00:56:56 +00005167 // Assume this isn't a constructor, rather than assuming it's a
5168 // constructor with an unnamed parameter of an ill-formed type.
5169 break;
5170
Richard Smith446161b2014-03-03 21:12:53 +00005171 case tok::r_paren:
5172 // C(X )
Richard Smith8f8697f2017-02-08 01:16:55 +00005173
5174 // Skip past the right-paren and any following attributes to get to
5175 // the function body or trailing-return-type.
5176 ConsumeParen();
5177 SkipCXX11Attributes();
5178
Richard Smith35845152017-02-07 01:37:30 +00005179 if (DeductionGuide) {
5180 // C(X) -> ... is a deduction guide.
Richard Smith8f8697f2017-02-08 01:16:55 +00005181 IsConstructor = Tok.is(tok::arrow);
Richard Smith35845152017-02-07 01:37:30 +00005182 break;
5183 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005184 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
Richard Smith446161b2014-03-03 21:12:53 +00005185 // Assume these were meant to be constructors:
5186 // C(X) : (the name of a bit-field cannot be parenthesized).
5187 // C(X) try (this is otherwise ill-formed).
5188 IsConstructor = true;
5189 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005190 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
Richard Smith446161b2014-03-03 21:12:53 +00005191 // If we have a constructor name within the class definition,
5192 // assume these were meant to be constructors:
5193 // C(X) {
5194 // C(X) ;
5195 // ... because otherwise we would be declaring a non-static data
5196 // member that is ill-formed because it's of the same type as its
5197 // surrounding class.
5198 //
5199 // FIXME: We can actually do this whether or not the name is qualified,
5200 // because if it is qualified in this context it must be being used as
Richard Smith35845152017-02-07 01:37:30 +00005201 // a constructor name.
Richard Smith446161b2014-03-03 21:12:53 +00005202 // currently, so we're somewhat conservative here.
5203 IsConstructor = IsUnqualified;
5204 }
5205 break;
5206
Richard Smithefd009d2012-03-27 00:56:56 +00005207 default:
5208 IsConstructor = true;
5209 break;
5210 }
5211 }
5212
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005213 TPA.Revert();
5214 return IsConstructor;
5215}
Chris Lattnerb9093cd2006-08-04 04:39:53 +00005216
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005217/// ParseTypeQualifierListOpt
Dawn Perchik335e16b2010-09-03 01:29:35 +00005218/// type-qualifier-list: [C99 6.7.5]
5219/// type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005220/// [vendor] attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005221/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005222/// type-qualifier-list type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005223/// [vendor] type-qualifier-list attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005224/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005225/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
Aaron Ballman08b06592014-07-22 12:44:22 +00005226/// [ only if AttReqs & AR_CXX11AttributesParsed ]
5227/// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5228/// AttrRequirements bitmask values.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005229void Parser::ParseTypeQualifierListOpt(
5230 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5231 bool IdentifierRequired,
5232 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
Aaron Ballman606093a2017-10-15 15:01:42 +00005233 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005234 isCXX11AttributeSpecifier()) {
John McCall084e83d2011-03-24 11:26:52 +00005235 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith3dff2512012-04-10 03:25:07 +00005236 ParseCXX11Attributes(attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005237 DS.takeAttributesFrom(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005238 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005239
5240 SourceLocation EndLoc;
5241
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005242 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00005243 bool isInvalid = false;
Craig Topper161e4db2014-05-21 06:02:52 +00005244 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00005245 unsigned DiagID = 0;
Chris Lattner60809f52006-11-28 05:18:46 +00005246 SourceLocation Loc = Tok.getLocation();
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005247
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005248 switch (Tok.getKind()) {
Douglas Gregor28c78432010-08-27 17:35:51 +00005249 case tok::code_completion:
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005250 if (CodeCompletionHandler)
5251 (*CodeCompletionHandler)();
5252 else
5253 Actions.CodeCompleteTypeQualifiers(DS);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00005254 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00005255
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005256 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00005257 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005258 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005259 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005260 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00005261 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005262 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005263 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005264 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00005265 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005266 getLangOpts());
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005267 break;
Richard Smith8e1ac332013-03-28 01:55:44 +00005268 case tok::kw__Atomic:
5269 if (!AtomicAllowed)
5270 goto DoneWithTypeQuals;
5271 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5272 getLangOpts());
5273 break;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005274
5275 // OpenCL qualifiers:
Anastasia Stulova948e37c2019-03-25 11:54:02 +00005276 case tok::kw_private:
Anastasia Stulova314fab62019-03-28 11:47:14 +00005277 if (!getLangOpts().OpenCL)
5278 goto DoneWithTypeQuals;
5279 LLVM_FALLTHROUGH;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005280 case tok::kw___private:
5281 case tok::kw___global:
5282 case tok::kw___local:
5283 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005284 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005285 case tok::kw___read_only:
5286 case tok::kw___write_only:
5287 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00005288 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005289 break;
5290
Andrey Bokhanko45d41322016-05-11 18:38:21 +00005291 case tok::kw___unaligned:
5292 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5293 getLangOpts());
5294 break;
Aaron Ballman317a77f2013-05-22 23:25:32 +00005295 case tok::kw___uptr:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005296 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
Alp Toker62c5b572013-11-26 01:30:10 +00005297 // with the MS modifier keyword.
Aaron Ballman08b06592014-07-22 12:44:22 +00005298 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
Alp Toker47642d22013-12-03 06:13:01 +00005299 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5300 if (TryKeywordIdentFallback(false))
5301 continue;
Alp Toker62c5b572013-11-26 01:30:10 +00005302 }
Galina Kistanova77674252017-06-01 21:15:34 +00005303 LLVM_FALLTHROUGH;
Alp Toker62c5b572013-11-26 01:30:10 +00005304 case tok::kw___sptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005305 case tok::kw___w64:
Steve Narofff9c29d42008-12-25 14:41:26 +00005306 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005307 case tok::kw___ptr32:
Steve Naroff44ac7772008-12-25 14:16:32 +00005308 case tok::kw___cdecl:
5309 case tok::kw___stdcall:
5310 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005311 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005312 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005313 case tok::kw___vectorcall:
Aaron Ballman08b06592014-07-22 12:44:22 +00005314 if (AttrReqs & AR_DeclspecAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005315 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00005316 continue;
5317 }
5318 goto DoneWithTypeQuals;
Dawn Perchik335e16b2010-09-03 01:29:35 +00005319 case tok::kw___pascal:
Aaron Ballman08b06592014-07-22 12:44:22 +00005320 if (AttrReqs & AR_VendorAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005321 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00005322 continue;
5323 }
5324 goto DoneWithTypeQuals;
Douglas Gregor261a89b2015-06-19 17:51:05 +00005325
5326 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005327 case tok::kw__Nonnull:
5328 case tok::kw__Nullable:
5329 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005330 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5331 continue;
5332
Douglas Gregorab209d82015-07-07 03:58:42 +00005333 // Objective-C 'kindof' types.
5334 case tok::kw___kindof:
5335 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00005336 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00005337 (void)ConsumeToken();
5338 continue;
5339
Chris Lattnere37e2332006-08-15 04:50:22 +00005340 case tok::kw___attribute:
Aaron Ballman08b06592014-07-22 12:44:22 +00005341 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5342 // When GNU attributes are expressly forbidden, diagnose their usage.
5343 Diag(Tok, diag::err_attributes_not_allowed);
5344
5345 // Parse the attributes even if they are rejected to ensure that error
5346 // recovery is graceful.
5347 if (AttrReqs & AR_GNUAttributesParsed ||
5348 AttrReqs & AR_GNUAttributesParsedAndRejected) {
John McCall53fa7142010-12-24 02:08:15 +00005349 ParseGNUAttributes(DS.getAttributes());
Chris Lattnercf0bab22008-12-18 07:02:59 +00005350 continue; // do *not* consume the next token!
5351 }
5352 // otherwise, FALL THROUGH!
Galina Kistanova77674252017-06-01 21:15:34 +00005353 LLVM_FALLTHROUGH;
Chris Lattnercf0bab22008-12-18 07:02:59 +00005354 default:
Steve Naroff44ac7772008-12-25 14:16:32 +00005355 DoneWithTypeQuals:
Chris Lattnercf0bab22008-12-18 07:02:59 +00005356 // If this is not a type-qualifier token, we're done reading type
5357 // qualifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00005358 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005359 if (EndLoc.isValid())
5360 DS.SetRangeEnd(EndLoc);
Chris Lattnercf0bab22008-12-18 07:02:59 +00005361 return;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005362 }
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00005363
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005364 // If the specifier combination wasn't legal, issue a diagnostic.
5365 if (isInvalid) {
5366 assert(PrevSpec && "Method did not return previous specifier!");
Chris Lattner6d29c102008-11-18 07:48:38 +00005367 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005368 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005369 EndLoc = ConsumeToken();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005370 }
5371}
5372
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005373/// ParseDeclarator - Parse and verify a newly-initialized declarator.
5374///
5375void Parser::ParseDeclarator(Declarator &D) {
5376 /// This implements the 'declarator' production in the C grammar, then checks
5377 /// for well-formedness and issues diagnostics.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005378 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005379}
5380
Richard Smith0b350b92014-10-28 16:55:02 +00005381static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
Faisal Vali421b2d12017-12-29 05:41:00 +00005382 DeclaratorContext TheContext) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005383 if (Kind == tok::star || Kind == tok::caret)
5384 return true;
5385
Xiuli Pan9c14e282016-01-09 12:53:17 +00005386 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5387 return true;
5388
Richard Smith0efa75c2012-03-29 01:16:42 +00005389 if (!Lang.CPlusPlus)
5390 return false;
5391
Richard Smith0b350b92014-10-28 16:55:02 +00005392 if (Kind == tok::amp)
5393 return true;
5394
5395 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5396 // But we must not parse them in conversion-type-ids and new-type-ids, since
5397 // those can be legitimately followed by a && operator.
5398 // (The same thing can in theory happen after a trailing-return-type, but
5399 // since those are a C++11 feature, there is no rejects-valid issue there.)
5400 if (Kind == tok::ampamp)
Faisal Vali421b2d12017-12-29 05:41:00 +00005401 return Lang.CPlusPlus11 ||
5402 (TheContext != DeclaratorContext::ConversionIdContext &&
5403 TheContext != DeclaratorContext::CXXNewContext);
Richard Smith0b350b92014-10-28 16:55:02 +00005404
5405 return false;
Richard Smith0efa75c2012-03-29 01:16:42 +00005406}
5407
Xiuli Pan9c14e282016-01-09 12:53:17 +00005408// Indicates whether the given declarator is a pipe declarator.
5409static bool isPipeDeclerator(const Declarator &D) {
5410 const unsigned NumTypes = D.getNumTypeObjects();
5411
5412 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5413 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5414 return true;
5415
5416 return false;
5417}
5418
Sebastian Redlbd150f42008-11-21 19:14:01 +00005419/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5420/// is parsed by the function passed to it. Pass null, and the direct-declarator
5421/// isn't parsed at all, making this function effectively parse the C++
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005422/// ptr-operator production.
5423///
Richard Smith09f76ee2011-10-19 21:33:05 +00005424/// If the grammar of this construct is extended, matching changes must also be
Richard Smith1453e312012-03-27 01:42:32 +00005425/// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5426/// isConstructorDeclarator.
Richard Smith09f76ee2011-10-19 21:33:05 +00005427///
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005428/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5429/// [C] pointer[opt] direct-declarator
5430/// [C++] direct-declarator
5431/// [C++] ptr-operator declarator
Chris Lattner6c7416c2006-08-07 00:19:33 +00005432///
5433/// pointer: [C99 6.7.5]
5434/// '*' type-qualifier-list[opt]
5435/// '*' type-qualifier-list[opt] pointer
5436///
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005437/// ptr-operator:
5438/// '*' cv-qualifier-seq[opt]
5439/// '&'
Sebastian Redled0f3b02009-03-15 22:02:01 +00005440/// [C++0x] '&&'
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005441/// [GNU] '&' restrict[opt] attributes[opt]
Sebastian Redled0f3b02009-03-15 22:02:01 +00005442/// [GNU?] '&&' restrict[opt] attributes[opt]
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005443/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
Sebastian Redlbd150f42008-11-21 19:14:01 +00005444void Parser::ParseDeclaratorInternal(Declarator &D,
5445 DirectDeclParseFunction DirectDeclParser) {
Douglas Gregor66a985d2009-08-26 14:27:30 +00005446 if (Diags.hasAllExtensionsSilenced())
5447 D.setExtension();
Chad Rosierc1183952012-06-26 22:30:43 +00005448
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005449 // C++ member pointers start with a '::' or a nested-name.
5450 // Member pointers get special handling, since there's no place for the
5451 // scope spec in the generic path below.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005452 if (getLangOpts().CPlusPlus &&
Richard Smith83c2ecf2016-02-02 23:34:49 +00005453 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
Serge Pavlov458ea762014-07-16 05:16:52 +00005454 (Tok.is(tok::identifier) &&
5455 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
Chris Lattner803802d2009-03-24 17:04:48 +00005456 Tok.is(tok::annot_cxxscope))) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005457 bool EnteringContext =
5458 D.getContext() == DeclaratorContext::FileContext ||
5459 D.getContext() == DeclaratorContext::MemberContext;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005460 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005461 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005462
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +00005463 if (SS.isNotEmpty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005464 if (Tok.isNot(tok::star)) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005465 // The scope spec really belongs to the direct-declarator.
Richard Smith5f044ad2013-01-08 22:43:49 +00005466 if (D.mayHaveIdentifier())
5467 D.getCXXScopeSpec() = SS;
5468 else
5469 AnnotateScopeToken(SS, true);
5470
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005471 if (DirectDeclParser)
5472 (this->*DirectDeclParser)(D);
5473 return;
5474 }
5475
5476 SourceLocation Loc = ConsumeToken();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005477 D.SetRangeEnd(Loc);
John McCall084e83d2011-03-24 11:26:52 +00005478 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005479 ParseTypeQualifierListOpt(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005480 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005481
5482 // Recurse to parse whatever is left.
5483 ParseDeclaratorInternal(D, DirectDeclParser);
5484
5485 // Sema will have to catch (syntactically invalid) pointers into global
5486 // scope. It has to catch pointers into namespace scope anyway.
Erich Keanec480f302018-07-12 21:09:05 +00005487 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005488 SS, DS.getTypeQualifiers(), DS.getEndLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005489 std::move(DS.getAttributes()),
5490 /* Don't replace range end. */ SourceLocation());
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005491 return;
5492 }
5493 }
5494
5495 tok::TokenKind Kind = Tok.getKind();
Xiuli Pan9c14e282016-01-09 12:53:17 +00005496
5497 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
Xiuli Pan11e13f62016-02-26 03:13:03 +00005498 DeclSpec DS(AttrFactory);
5499 ParseTypeQualifierListOpt(DS);
Xiuli Pan9c14e282016-01-09 12:53:17 +00005500
5501 D.AddTypeInfo(
5502 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005503 std::move(DS.getAttributes()), SourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00005504 }
5505
Steve Naroffec33ed92008-08-27 16:04:49 +00005506 // Not a pointer, C++ reference, or block.
Richard Smith0b350b92014-10-28 16:55:02 +00005507 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00005508 if (DirectDeclParser)
5509 (this->*DirectDeclParser)(D);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005510 return;
5511 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005512
Sebastian Redled0f3b02009-03-15 22:02:01 +00005513 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5514 // '&&' -> rvalue reference
Sebastian Redl3b27be62009-03-23 00:00:23 +00005515 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005516 D.SetRangeEnd(Loc);
Bill Wendling3708c182007-05-27 10:15:43 +00005517
Chris Lattner9eac9312009-03-27 04:18:06 +00005518 if (Kind == tok::star || Kind == tok::caret) {
Chris Lattner788404f2008-02-21 01:32:26 +00005519 // Is a pointer.
John McCall084e83d2011-03-24 11:26:52 +00005520 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005521
Aaron Ballman08b06592014-07-22 12:44:22 +00005522 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5523 // C++11 attributes are allowed.
5524 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
Faisal Vali421b2d12017-12-29 05:41:00 +00005525 ((D.getContext() != DeclaratorContext::CXXNewContext)
5526 ? AR_GNUAttributesParsed
5527 : AR_GNUAttributesParsedAndRejected);
Aaron Ballman08b06592014-07-22 12:44:22 +00005528 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005529 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005530
Bill Wendling3708c182007-05-27 10:15:43 +00005531 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005532 ParseDeclaratorInternal(D, DirectDeclParser);
Steve Naroffec33ed92008-08-27 16:04:49 +00005533 if (Kind == tok::star)
5534 // Remember that we parsed a pointer type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005535 D.AddTypeInfo(DeclaratorChunk::getPointer(
5536 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5537 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5538 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5539 std::move(DS.getAttributes()), SourceLocation());
Steve Naroffec33ed92008-08-27 16:04:49 +00005540 else
5541 // Remember that we parsed a Block type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005542 D.AddTypeInfo(
5543 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5544 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005545 } else {
5546 // Is a reference
John McCall084e83d2011-03-24 11:26:52 +00005547 DeclSpec DS(AttrFactory);
Bill Wendling93efb222007-06-02 23:28:54 +00005548
Sebastian Redl3b27be62009-03-23 00:00:23 +00005549 // Complain about rvalue references in C++03, but then go on and build
5550 // the declarator.
Richard Smith5d164bc2011-10-15 05:09:34 +00005551 if (Kind == tok::ampamp)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005552 Diag(Loc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00005553 diag::warn_cxx98_compat_rvalue_reference :
5554 diag::ext_rvalue_reference);
Sebastian Redl3b27be62009-03-23 00:00:23 +00005555
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005556 // GNU-style and C++11 attributes are allowed here, as is restrict.
5557 ParseTypeQualifierListOpt(DS);
5558 D.ExtendWithDeclSpec(DS);
5559
Bill Wendling93efb222007-06-02 23:28:54 +00005560 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5561 // cv-qualifiers are introduced through the use of a typedef or of a
5562 // template type argument, in which case the cv-qualifiers are ignored.
Bill Wendling93efb222007-06-02 23:28:54 +00005563 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5564 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5565 Diag(DS.getConstSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005566 diag::err_invalid_reference_qualifier_application) << "const";
Bill Wendling93efb222007-06-02 23:28:54 +00005567 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5568 Diag(DS.getVolatileSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005569 diag::err_invalid_reference_qualifier_application) << "volatile";
Richard Smith8e1ac332013-03-28 01:55:44 +00005570 // 'restrict' is permitted as an extension.
5571 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5572 Diag(DS.getAtomicSpecLoc(),
5573 diag::err_invalid_reference_qualifier_application) << "_Atomic";
Bill Wendling93efb222007-06-02 23:28:54 +00005574 }
Bill Wendling3708c182007-05-27 10:15:43 +00005575
5576 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005577 ParseDeclaratorInternal(D, DirectDeclParser);
Bill Wendling3708c182007-05-27 10:15:43 +00005578
Douglas Gregor66583c52008-11-03 15:51:28 +00005579 if (D.getNumTypeObjects() > 0) {
5580 // C++ [dcl.ref]p4: There shall be no references to references.
5581 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5582 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
Chris Lattnerebad6a22008-11-19 07:37:42 +00005583 if (const IdentifierInfo *II = D.getIdentifier())
5584 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5585 << II;
5586 else
5587 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5588 << "type name";
Douglas Gregor66583c52008-11-03 15:51:28 +00005589
Sebastian Redlbd150f42008-11-21 19:14:01 +00005590 // Once we've complained about the reference-to-reference, we
Douglas Gregor66583c52008-11-03 15:51:28 +00005591 // can go ahead and build the (technically ill-formed)
5592 // declarator: reference collapsing will take care of it.
5593 }
5594 }
5595
Richard Smith8e1ac332013-03-28 01:55:44 +00005596 // Remember that we parsed a reference type.
Chris Lattner788404f2008-02-21 01:32:26 +00005597 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
Sebastian Redled0f3b02009-03-15 22:02:01 +00005598 Kind == tok::amp),
Erich Keanec480f302018-07-12 21:09:05 +00005599 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005600 }
Chris Lattner6c7416c2006-08-07 00:19:33 +00005601}
5602
Richard Trieuf4b81d02014-06-24 23:14:24 +00005603// When correcting from misplaced brackets before the identifier, the location
5604// is saved inside the declarator so that other diagnostic messages can use
5605// them. This extracts and returns that location, or returns the provided
5606// location if a stored location does not exist.
5607static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5608 SourceLocation Loc) {
5609 if (D.getName().StartLocation.isInvalid() &&
5610 D.getName().EndLocation.isValid())
5611 return D.getName().EndLocation;
5612
5613 return Loc;
5614}
5615
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005616/// ParseDirectDeclarator
5617/// direct-declarator: [C99 6.7.5]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005618/// [C99] identifier
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005619/// '(' declarator ')'
5620/// [GNU] '(' attributes declarator ')'
Chris Lattnere8074e62006-08-06 18:30:15 +00005621/// [C90] direct-declarator '[' constant-expression[opt] ']'
5622/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5623/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5624/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5625/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005626/// [C++11] direct-declarator '[' constant-expression[opt] ']'
5627/// attribute-specifier-seq[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005628/// direct-declarator '(' parameter-type-list ')'
5629/// direct-declarator '(' identifier-list[opt] ')'
5630/// [GNU] direct-declarator '(' parameter-forward-declarations
5631/// parameter-type-list[opt] ')'
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00005632/// [C++] direct-declarator '(' parameter-declaration-clause ')'
5633/// cv-qualifier-seq[opt] exception-specification[opt]
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005634/// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5635/// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5636/// ref-qualifier[opt] exception-specification[opt]
Douglas Gregor61956c42008-10-31 09:07:45 +00005637/// [C++] declarator-id
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005638/// [C++11] declarator-id attribute-specifier-seq[opt]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005639///
5640/// declarator-id: [C++ 8]
Douglas Gregor27b4c162010-12-23 22:44:42 +00005641/// '...'[opt] id-expression
Douglas Gregor831c93f2008-11-05 20:51:48 +00005642/// '::'[opt] nested-name-specifier[opt] type-name
5643///
5644/// id-expression: [C++ 5.1]
5645/// unqualified-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005646/// qualified-id
Douglas Gregor831c93f2008-11-05 20:51:48 +00005647///
5648/// unqualified-id: [C++ 5.1]
Mike Stump11289f42009-09-09 15:08:12 +00005649/// identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005650/// operator-function-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005651/// conversion-function-id
Mike Stump11289f42009-09-09 15:08:12 +00005652/// '~' class-name
Douglas Gregor7f741122009-02-25 19:37:18 +00005653/// template-id
Argyrios Kyrtzidise4426352008-11-07 22:02:30 +00005654///
Richard Smithbdb84f32016-07-22 23:36:59 +00005655/// C++17 adds the following, which we also handle here:
5656///
5657/// simple-declaration:
5658/// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5659///
Richard Smith1453e312012-03-27 01:42:32 +00005660/// Note, any additional constructs added here may need corresponding changes
5661/// in isConstructorDeclarator.
Chris Lattneracd58a32006-08-06 17:24:14 +00005662void Parser::ParseDirectDeclarator(Declarator &D) {
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005663 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005664
David Blaikiebbafb8a2012-03-11 07:00:24 +00005665 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
Richard Smithbdb84f32016-07-22 23:36:59 +00005666 // This might be a C++17 structured binding.
5667 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5668 D.getCXXScopeSpec().isEmpty())
5669 return ParseDecompositionDeclarator(D);
5670
Serge Pavlov458ea762014-07-16 05:16:52 +00005671 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5672 // this context it is a bitfield. Also in range-based for statement colon
5673 // may delimit for-range-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00005674 ColonProtectionRAIIObject X(
5675 *this, D.getContext() == DeclaratorContext::MemberContext ||
5676 (D.getContext() == DeclaratorContext::ForContext &&
5677 getLangOpts().CPlusPlus11));
Serge Pavlov458ea762014-07-16 05:16:52 +00005678
Douglas Gregor7861a802009-11-03 01:35:08 +00005679 // ParseDeclaratorInternal might already have parsed the scope.
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005680 if (D.getCXXScopeSpec().isEmpty()) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005681 bool EnteringContext =
5682 D.getContext() == DeclaratorContext::FileContext ||
5683 D.getContext() == DeclaratorContext::MemberContext;
David Blaikieefdccaa2016-01-15 23:43:34 +00005684 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005685 EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005686 }
5687
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005688 if (D.getCXXScopeSpec().isValid()) {
Richard Smith64e033f2015-01-15 00:48:52 +00005689 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5690 D.getCXXScopeSpec()))
John McCall2b058ef2009-12-11 20:04:54 +00005691 // Change the declaration context for name lookup, until this function
5692 // is exited (and the declarator has been parsed).
5693 DeclScopeObj.EnterDeclaratorScope();
Alex Lorenze151f0102016-12-07 10:24:44 +00005694 else if (getObjCDeclContext()) {
5695 // Ensure that we don't interpret the next token as an identifier when
5696 // dealing with declarations in an Objective-C container.
5697 D.SetIdentifier(nullptr, Tok.getLocation());
5698 D.setInvalidType(true);
5699 ConsumeToken();
5700 goto PastIdentifier;
5701 }
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005702 }
5703
Douglas Gregor27b4c162010-12-23 22:44:42 +00005704 // C++0x [dcl.fct]p14:
Faisal Vali8435a692014-12-04 12:40:21 +00005705 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5706 // parameter-declaration-clause without a preceding comma. In this case,
5707 // the ellipsis is parsed as part of the abstract-declarator if the type
5708 // of the parameter either names a template parameter pack that has not
5709 // been expanded or contains auto; otherwise, it is parsed as part of the
5710 // parameter-declaration-clause.
Richard Smith0efa75c2012-03-29 01:16:42 +00005711 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00005712 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5713 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5714 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
Douglas Gregor27b4c162010-12-23 22:44:42 +00005715 NextToken().is(tok::r_paren) &&
Richard Smithb19337f2013-02-20 20:19:27 +00005716 !D.hasGroupingParens() &&
Faisal Vali8435a692014-12-04 12:40:21 +00005717 !Actions.containsUnexpandedParameterPacks(D) &&
Faisal Vali090da2d2018-01-01 18:23:28 +00005718 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005719 SourceLocation EllipsisLoc = ConsumeToken();
Richard Smith0b350b92014-10-28 16:55:02 +00005720 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005721 // The ellipsis was put in the wrong place. Recover, and explain to
5722 // the user what they should have done.
5723 ParseDeclarator(D);
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00005724 if (EllipsisLoc.isValid())
5725 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00005726 return;
5727 } else
5728 D.setEllipsisLoc(EllipsisLoc);
5729
5730 // The ellipsis can't be followed by a parenthesized declarator. We
5731 // check for that in ParseParenDeclarator, after we have disambiguated
5732 // the l_paren token.
5733 }
5734
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005735 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5736 tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00005737 // We found something that indicates the start of an unqualified-id.
5738 // Parse that unqualified-id.
John McCall84821e72010-04-13 06:39:49 +00005739 bool AllowConstructorName;
Richard Smith35845152017-02-07 01:37:30 +00005740 bool AllowDeductionGuide;
5741 if (D.getDeclSpec().hasTypeSpecifier()) {
John McCall84821e72010-04-13 06:39:49 +00005742 AllowConstructorName = false;
Richard Smith35845152017-02-07 01:37:30 +00005743 AllowDeductionGuide = false;
5744 } else if (D.getCXXScopeSpec().isSet()) {
John McCall84821e72010-04-13 06:39:49 +00005745 AllowConstructorName =
Faisal Vali421b2d12017-12-29 05:41:00 +00005746 (D.getContext() == DeclaratorContext::FileContext ||
5747 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005748 AllowDeductionGuide = false;
5749 } else {
Faisal Vali421b2d12017-12-29 05:41:00 +00005750 AllowConstructorName =
5751 (D.getContext() == DeclaratorContext::MemberContext);
Fangrui Song6907ce22018-07-30 19:24:48 +00005752 AllowDeductionGuide =
Faisal Vali421b2d12017-12-29 05:41:00 +00005753 (D.getContext() == DeclaratorContext::FileContext ||
5754 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005755 }
John McCall84821e72010-04-13 06:39:49 +00005756
Richard Smith64e033f2015-01-15 00:48:52 +00005757 bool HadScope = D.getCXXScopeSpec().isValid();
Chad Rosierc1183952012-06-26 22:30:43 +00005758 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5759 /*EnteringContext=*/true,
David Blaikieefdccaa2016-01-15 23:43:34 +00005760 /*AllowDestructorName=*/true, AllowConstructorName,
Richard Smithc08b6932018-04-27 02:00:13 +00005761 AllowDeductionGuide, nullptr, nullptr,
Richard Smith35845152017-02-07 01:37:30 +00005762 D.getName()) ||
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005763 // Once we're past the identifier, if the scope was bad, mark the
5764 // whole declarator bad.
5765 D.getCXXScopeSpec().isInvalid()) {
Craig Topper161e4db2014-05-21 06:02:52 +00005766 D.SetIdentifier(nullptr, Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005767 D.setInvalidType(true);
Douglas Gregor7861a802009-11-03 01:35:08 +00005768 } else {
Richard Smith64e033f2015-01-15 00:48:52 +00005769 // ParseUnqualifiedId might have parsed a scope specifier during error
5770 // recovery. If it did so, enter that scope.
5771 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5772 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5773 D.getCXXScopeSpec()))
5774 DeclScopeObj.EnterDeclaratorScope();
5775
Douglas Gregor7861a802009-11-03 01:35:08 +00005776 // Parsed the unqualified-id; update range information and move along.
5777 if (D.getSourceRange().getBegin().isInvalid())
5778 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5779 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005780 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005781 goto PastIdentifier;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005782 }
Richard Smithd63db6e2015-12-19 02:40:19 +00005783
5784 if (D.getCXXScopeSpec().isNotEmpty()) {
5785 // We have a scope specifier but no following unqualified-id.
5786 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5787 diag::err_expected_unqualified_id)
5788 << /*C++*/1;
5789 D.SetIdentifier(nullptr, Tok.getLocation());
5790 goto PastIdentifier;
5791 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005792 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005793 assert(!getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005794 "There's a C++-specific check for tok::identifier above");
5795 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5796 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Richard Trieu2664dc12014-05-05 22:06:50 +00005797 D.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005798 ConsumeToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00005799 goto PastIdentifier;
Richard Smith74639b12017-05-19 01:54:59 +00005800 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5801 // We're not allowed an identifier here, but we got one. Try to figure out
5802 // if the user was trying to attach a name to the type, or whether the name
5803 // is some unrelated trailing syntax.
5804 bool DiagnoseIdentifier = false;
5805 if (D.hasGroupingParens())
5806 // An identifier within parens is unlikely to be intended to be anything
5807 // other than a name being "declared".
5808 DiagnoseIdentifier = true;
Richard Smith77a9c602018-02-28 03:02:23 +00005809 else if (D.getContext() == DeclaratorContext::TemplateArgContext)
Richard Smith74639b12017-05-19 01:54:59 +00005810 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5811 DiagnoseIdentifier =
5812 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali421b2d12017-12-29 05:41:00 +00005813 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5814 D.getContext() == DeclaratorContext::AliasTemplateContext)
Richard Smith74639b12017-05-19 01:54:59 +00005815 // The most likely error is that the ';' was forgotten.
5816 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
Richard Smithe303e352018-02-02 22:24:54 +00005817 else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5818 D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
Richard Smith74639b12017-05-19 01:54:59 +00005819 !isCXX11VirtSpecifier(Tok))
5820 DiagnoseIdentifier = NextToken().isOneOf(
5821 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5822 if (DiagnoseIdentifier) {
Richard Smithf39720b2013-10-13 22:12:28 +00005823 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5824 << FixItHint::CreateRemoval(Tok.getLocation());
Craig Topper161e4db2014-05-21 06:02:52 +00005825 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithf39720b2013-10-13 22:12:28 +00005826 ConsumeToken();
5827 goto PastIdentifier;
5828 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005829 }
Richard Smith0efa75c2012-03-29 01:16:42 +00005830
Douglas Gregor7861a802009-11-03 01:35:08 +00005831 if (Tok.is(tok::l_paren)) {
Richard Smithe303e352018-02-02 22:24:54 +00005832 // If this might be an abstract-declarator followed by a direct-initializer,
5833 // check whether this is a valid declarator chunk. If it can't be, assume
5834 // that it's an initializer instead.
5835 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5836 RevertingTentativeParsingAction PA(*this);
5837 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5838 TPResult::False) {
5839 D.SetIdentifier(nullptr, Tok.getLocation());
5840 goto PastIdentifier;
5841 }
5842 }
5843
Chris Lattneracd58a32006-08-06 17:24:14 +00005844 // direct-declarator: '(' declarator ')'
Chris Lattnere37e2332006-08-15 04:50:22 +00005845 // direct-declarator: '(' attributes declarator ')'
Chris Lattneracd58a32006-08-06 17:24:14 +00005846 // Example: 'char (*X)' or 'int (*XX)(void)'
5847 ParseParenDeclarator(D);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005848
5849 // If the declarator was parenthesized, we entered the declarator
5850 // scope when parsing the parenthesized declarator, then exited
5851 // the scope already. Re-enter the scope, if we need to.
5852 if (D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005853 // If there was an error parsing parenthesized declarator, declarator
Richard Smith0efa75c2012-03-29 01:16:42 +00005854 // scope may have been entered before. Don't do it again.
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005855 if (!D.isInvalidType() &&
Nico Weber6b05f382015-02-18 04:53:03 +00005856 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5857 D.getCXXScopeSpec()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005858 // Change the declaration context for name lookup, until this function
5859 // is exited (and the declarator has been parsed).
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005860 DeclScopeObj.EnterDeclaratorScope();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005861 }
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005862 } else if (D.mayOmitIdentifier()) {
Chris Lattneracd58a32006-08-06 17:24:14 +00005863 // This could be something simple like "int" (in which case the declarator
5864 // portion is empty), if an abstract-declarator is allowed.
Craig Topper161e4db2014-05-21 06:02:52 +00005865 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithb19337f2013-02-20 20:19:27 +00005866
5867 // The grammar for abstract-pack-declarator does not allow grouping parens.
5868 // FIXME: Revisit this once core issue 1488 is resolved.
5869 if (D.hasEllipsis() && D.hasGroupingParens())
5870 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5871 diag::ext_abstract_pack_declarator_parens);
Chris Lattneracd58a32006-08-06 17:24:14 +00005872 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00005873 if (Tok.getKind() == tok::annot_pragma_parser_crash)
David Blaikie5bd4c2a2012-08-21 18:56:49 +00005874 LLVM_BUILTIN_TRAP;
Richard Trieuf4b81d02014-06-24 23:14:24 +00005875 if (Tok.is(tok::l_square))
5876 return ParseMisplacedBracketDeclarator(D);
Faisal Vali421b2d12017-12-29 05:41:00 +00005877 if (D.getContext() == DeclaratorContext::MemberContext) {
Alex Lorenzf1278212017-04-11 15:01:53 +00005878 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5879 // treating these keyword as valid member names.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005880 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
Alex Lorenzf1278212017-04-11 15:01:53 +00005881 Tok.getIdentifierInfo() &&
5882 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5883 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5884 diag::err_expected_member_name_or_semi_objcxx_keyword)
5885 << Tok.getIdentifierInfo()
5886 << (D.getDeclSpec().isEmpty() ? SourceRange()
5887 : D.getDeclSpec().getSourceRange());
5888 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5889 D.SetRangeEnd(Tok.getLocation());
5890 ConsumeToken();
5891 goto PastIdentifier;
5892 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005893 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5894 diag::err_expected_member_name_or_semi)
Richard Trieua1342402014-05-02 23:40:32 +00005895 << (D.getDeclSpec().isEmpty() ? SourceRange()
5896 : D.getDeclSpec().getSourceRange());
Richard Trieuf4b81d02014-06-24 23:14:24 +00005897 } else if (getLangOpts().CPlusPlus) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005898 if (Tok.isOneOf(tok::period, tok::arrow))
Richard Trieu9c672672013-01-26 02:31:38 +00005899 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
Richard Trieu2f586962013-09-05 02:31:33 +00005900 else {
5901 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5902 if (Tok.isAtStartOfLine() && Loc.isValid())
5903 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5904 << getLangOpts().CPlusPlus;
5905 else
Richard Trieuf4b81d02014-06-24 23:14:24 +00005906 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5907 diag::err_expected_unqualified_id)
Richard Trieu2f586962013-09-05 02:31:33 +00005908 << getLangOpts().CPlusPlus;
5909 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005910 } else {
5911 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5912 diag::err_expected_either)
5913 << tok::identifier << tok::l_paren;
5914 }
Craig Topper161e4db2014-05-21 06:02:52 +00005915 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattner8c5dd732008-11-11 06:13:16 +00005916 D.setInvalidType(true);
Chris Lattneracd58a32006-08-06 17:24:14 +00005917 }
Mike Stump11289f42009-09-09 15:08:12 +00005918
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005919 PastIdentifier:
Chris Lattneracd58a32006-08-06 17:24:14 +00005920 assert(D.isPastIdentifier() &&
5921 "Haven't past the location of the identifier yet?");
Mike Stump11289f42009-09-09 15:08:12 +00005922
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005923 // Don't parse attributes unless we have parsed an unparenthesized name.
5924 if (D.hasName() && !D.getNumTypeObjects())
Richard Smith89645bc2013-01-02 12:01:23 +00005925 MaybeParseCXX11Attributes(D);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005926
Chris Lattneracd58a32006-08-06 17:24:14 +00005927 while (1) {
Chris Lattner76c72282007-10-09 17:33:22 +00005928 if (Tok.is(tok::l_paren)) {
David Blaikie15a430a2011-12-04 05:04:18 +00005929 // Enter function-declaration scope, limiting any declarators to the
5930 // function prototype scope, including parameter declarators.
5931 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00005932 Scope::FunctionPrototypeScope|Scope::DeclScope|
5933 (D.isFunctionDeclaratorAFunctionDeclaration()
5934 ? Scope::FunctionDeclarationScope : 0));
5935
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005936 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5937 // In such a case, check if we actually have a function declarator; if it
5938 // is not, the declarator has been fully parsed.
Richard Smith943c4402012-07-30 21:30:52 +00005939 bool IsAmbiguous = false;
Richard Smith4f605af2012-08-18 00:55:03 +00005940 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5941 // The name of the declarator, if any, is tentatively declared within
5942 // a possible direct initializer.
5943 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5944 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5945 TentativelyDeclaredIdentifiers.pop_back();
5946 if (!IsFunctionDecl)
5947 break;
5948 }
John McCall084e83d2011-03-24 11:26:52 +00005949 ParsedAttributes attrs(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005950 BalancedDelimiterTracker T(*this, tok::l_paren);
5951 T.consumeOpen();
Richard Smith943c4402012-07-30 21:30:52 +00005952 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
David Blaikie15a430a2011-12-04 05:04:18 +00005953 PrototypeScope.Exit();
Chris Lattner76c72282007-10-09 17:33:22 +00005954 } else if (Tok.is(tok::l_square)) {
Chris Lattnere8074e62006-08-06 18:30:15 +00005955 ParseBracketDeclarator(D);
Chris Lattneracd58a32006-08-06 17:24:14 +00005956 } else {
5957 break;
5958 }
5959 }
Chad Rosierc1183952012-06-26 22:30:43 +00005960}
Chris Lattneracd58a32006-08-06 17:24:14 +00005961
Richard Smithbdb84f32016-07-22 23:36:59 +00005962void Parser::ParseDecompositionDeclarator(Declarator &D) {
5963 assert(Tok.is(tok::l_square));
5964
5965 // If this doesn't look like a structured binding, maybe it's a misplaced
5966 // array declarator.
5967 // FIXME: Consume the l_square first so we don't need extra lookahead for
5968 // this.
5969 if (!(NextToken().is(tok::identifier) &&
5970 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5971 !(NextToken().is(tok::r_square) &&
5972 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5973 return ParseMisplacedBracketDeclarator(D);
5974
5975 BalancedDelimiterTracker T(*this, tok::l_square);
5976 T.consumeOpen();
5977
5978 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5979 while (Tok.isNot(tok::r_square)) {
5980 if (!Bindings.empty()) {
5981 if (Tok.is(tok::comma))
5982 ConsumeToken();
5983 else {
5984 if (Tok.is(tok::identifier)) {
5985 SourceLocation EndLoc = getEndOfPreviousToken();
5986 Diag(EndLoc, diag::err_expected)
5987 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5988 } else {
5989 Diag(Tok, diag::err_expected_comma_or_rsquare);
5990 }
5991
5992 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5993 StopAtSemi | StopBeforeMatch);
5994 if (Tok.is(tok::comma))
5995 ConsumeToken();
5996 else if (Tok.isNot(tok::identifier))
5997 break;
5998 }
5999 }
6000
6001 if (Tok.isNot(tok::identifier)) {
6002 Diag(Tok, diag::err_expected) << tok::identifier;
6003 break;
6004 }
6005
6006 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
6007 ConsumeToken();
6008 }
6009
6010 if (Tok.isNot(tok::r_square))
6011 // We've already diagnosed a problem here.
6012 T.skipToEnd();
6013 else {
6014 // C++17 does not allow the identifier-list in a structured binding
6015 // to be empty.
6016 if (Bindings.empty())
6017 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
6018
6019 T.consumeClose();
6020 }
6021
6022 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
6023 T.getCloseLocation());
6024}
6025
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006026/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
6027/// only called before the identifier, so these are most likely just grouping
Mike Stump11289f42009-09-09 15:08:12 +00006028/// parens for precedence. If we find that these are actually function
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006029/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
6030///
6031/// direct-declarator:
6032/// '(' declarator ')'
6033/// [GNU] '(' attributes declarator ')'
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006034/// direct-declarator '(' parameter-type-list ')'
6035/// direct-declarator '(' identifier-list[opt] ')'
6036/// [GNU] direct-declarator '(' parameter-forward-declarations
6037/// parameter-type-list[opt] ')'
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006038///
6039void Parser::ParseParenDeclarator(Declarator &D) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006040 BalancedDelimiterTracker T(*this, tok::l_paren);
6041 T.consumeOpen();
6042
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006043 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
Mike Stump11289f42009-09-09 15:08:12 +00006044
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006045 // Eat any attributes before we look at whether this is a grouping or function
6046 // declarator paren. If this is a grouping paren, the attribute applies to
6047 // the type being built up, for example:
6048 // int (__attribute__(()) *x)(long y)
6049 // If this ends up not being a grouping paren, the attribute applies to the
6050 // first argument, for example:
6051 // int (__attribute__(()) int x)
6052 // In either case, we need to eat any attributes to be able to determine what
6053 // sort of paren this is.
6054 //
John McCall084e83d2011-03-24 11:26:52 +00006055 ParsedAttributes attrs(AttrFactory);
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006056 bool RequiresArg = false;
6057 if (Tok.is(tok::kw___attribute)) {
John McCall53fa7142010-12-24 02:08:15 +00006058 ParseGNUAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006059
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006060 // We require that the argument list (if this is a non-grouping paren) be
6061 // present even if the attribute list was empty.
6062 RequiresArg = true;
6063 }
Chad Rosiereea9ca72012-12-21 21:22:20 +00006064
Steve Naroff44ac7772008-12-25 14:16:32 +00006065 // Eat any Microsoft extensions.
Chad Rosiereea9ca72012-12-21 21:22:20 +00006066 ParseMicrosoftTypeAttributes(attrs);
6067
Dawn Perchik335e16b2010-09-03 01:29:35 +00006068 // Eat any Borland extensions.
Ted Kremenek5eec2b02010-11-10 05:59:39 +00006069 if (Tok.is(tok::kw___pascal))
John McCall53fa7142010-12-24 02:08:15 +00006070 ParseBorlandTypeAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006071
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006072 // If we haven't past the identifier yet (or where the identifier would be
6073 // stored, if this is an abstract declarator), then this is probably just
6074 // grouping parens. However, if this could be an abstract-declarator, then
6075 // this could also be the start of function arguments (consider 'void()').
6076 bool isGrouping;
Mike Stump11289f42009-09-09 15:08:12 +00006077
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006078 if (!D.mayOmitIdentifier()) {
6079 // If this can't be an abstract-declarator, this *must* be a grouping
6080 // paren, because we haven't seen the identifier yet.
6081 isGrouping = true;
6082 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
Richard Smith43f340f2012-03-27 23:05:05 +00006083 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6084 NextToken().is(tok::r_paren)) || // C++ int(...)
Richard Smith2620cd92012-04-11 04:01:28 +00006085 isDeclarationSpecifier() || // 'int(int)' is a function.
6086 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006087 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6088 // considered to be a type, not a K&R identifier-list.
6089 isGrouping = false;
6090 } else {
6091 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6092 isGrouping = true;
6093 }
Mike Stump11289f42009-09-09 15:08:12 +00006094
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006095 // If this is a grouping paren, handle:
6096 // direct-declarator: '(' declarator ')'
6097 // direct-declarator: '(' attributes declarator ')'
6098 if (isGrouping) {
Richard Smith0efa75c2012-03-29 01:16:42 +00006099 SourceLocation EllipsisLoc = D.getEllipsisLoc();
6100 D.setEllipsisLoc(SourceLocation());
6101
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006102 bool hadGroupingParens = D.hasGroupingParens();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006103 D.setGroupingParens(true);
Sebastian Redlbd150f42008-11-21 19:14:01 +00006104 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006105 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006106 T.consumeClose();
Erich Keanec480f302018-07-12 21:09:05 +00006107 D.AddTypeInfo(
6108 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6109 std::move(attrs), T.getCloseLocation());
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006110
6111 D.setGroupingParens(hadGroupingParens);
Richard Smith0efa75c2012-03-29 01:16:42 +00006112
6113 // An ellipsis cannot be placed outside parentheses.
6114 if (EllipsisLoc.isValid())
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00006115 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00006116
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006117 return;
6118 }
Mike Stump11289f42009-09-09 15:08:12 +00006119
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006120 // Okay, if this wasn't a grouping paren, it must be the start of a function
6121 // argument list. Recognize that this declarator will never have an
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006122 // identifier (and remember where it would have been), then call into
6123 // ParseFunctionDeclarator to handle of argument list.
Craig Topper161e4db2014-05-21 06:02:52 +00006124 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006125
David Blaikie15a430a2011-12-04 05:04:18 +00006126 // Enter function-declaration scope, limiting any declarators to the
6127 // function prototype scope, including parameter declarators.
6128 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00006129 Scope::FunctionPrototypeScope | Scope::DeclScope |
6130 (D.isFunctionDeclaratorAFunctionDeclaration()
6131 ? Scope::FunctionDeclarationScope : 0));
Richard Smith943c4402012-07-30 21:30:52 +00006132 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
David Blaikie15a430a2011-12-04 05:04:18 +00006133 PrototypeScope.Exit();
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006134}
6135
6136/// ParseFunctionDeclarator - We are after the identifier and have parsed the
6137/// declarator D up to a paren, which indicates that we are parsing function
6138/// arguments.
Chris Lattneracd58a32006-08-06 17:24:14 +00006139///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006140/// If FirstArgAttrs is non-null, then the caller parsed those arguments
6141/// immediately after the open paren - they should be considered to be the
6142/// first argument of a parameter.
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006143///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006144/// If RequiresArg is true, then the first argument of the function is required
6145/// to be present and required to not be an identifier list.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006146///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006147/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6148/// (C++11) ref-qualifier[opt], exception-specification[opt],
6149/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
6150///
6151/// [C++11] exception-specification:
Douglas Gregor9e66af42011-07-05 16:44:18 +00006152/// dynamic-exception-specification
6153/// noexcept-specification
6154///
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006155void Parser::ParseFunctionDeclarator(Declarator &D,
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006156 ParsedAttributes &FirstArgAttrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006157 BalancedDelimiterTracker &Tracker,
Richard Smith943c4402012-07-30 21:30:52 +00006158 bool IsAmbiguous,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006159 bool RequiresArg) {
Chad Rosierc1183952012-06-26 22:30:43 +00006160 assert(getCurScope()->isFunctionPrototypeScope() &&
David Blaikie15a430a2011-12-04 05:04:18 +00006161 "Should call from a Function scope");
Douglas Gregor9e66af42011-07-05 16:44:18 +00006162 // lparen is already consumed!
6163 assert(D.isPastIdentifier() && "Should not call before identifier!");
6164
6165 // This should be true when the function has typed arguments.
6166 // Otherwise, it is treated as a K&R-style function.
6167 bool HasProto = false;
6168 // Build up an array of information about the parsed arguments.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006169 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006170 // Remember where we see an ellipsis, if any.
6171 SourceLocation EllipsisLoc;
6172
6173 DeclSpec DS(AttrFactory);
6174 bool RefQualifierIsLValueRef = true;
6175 SourceLocation RefQualifierLoc;
6176 ExceptionSpecificationType ESpecType = EST_None;
6177 SourceRange ESpecRange;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006178 SmallVector<ParsedType, 2> DynamicExceptions;
6179 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006180 ExprResult NoexceptExpr;
Hans Wennborgdcfba332015-10-06 23:40:43 +00006181 CachedTokens *ExceptionSpecTokens = nullptr;
Aaron Ballman606093a2017-10-15 15:01:42 +00006182 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith700537c2012-06-12 01:51:59 +00006183 TypeResult TrailingReturnType;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006184
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006185 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6186 EndLoc is the end location for the function declarator.
6187 They differ for trailing return types. */
6188 SourceLocation StartLoc, LocalEndLoc, EndLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006189 SourceLocation LParenLoc, RParenLoc;
6190 LParenLoc = Tracker.getOpenLocation();
6191 StartLoc = LParenLoc;
6192
Douglas Gregor9e66af42011-07-05 16:44:18 +00006193 if (isFunctionDeclaratorIdentifierList()) {
6194 if (RequiresArg)
6195 Diag(Tok, diag::err_argument_required_after_attribute);
6196
6197 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6198
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006199 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006200 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006201 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006202 EndLoc = RParenLoc;
Aaron Ballman606093a2017-10-15 15:01:42 +00006203
Fangrui Song6907ce22018-07-30 19:24:48 +00006204 // If there are attributes following the identifier list, parse them and
Aaron Ballman606093a2017-10-15 15:01:42 +00006205 // prohibit them.
6206 MaybeParseCXX11Attributes(FnAttrs);
6207 ProhibitAttributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006208 } else {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006209 if (Tok.isNot(tok::r_paren))
Fangrui Song6907ce22018-07-30 19:24:48 +00006210 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
Faisal Vali2b391ab2013-09-26 19:54:12 +00006211 EllipsisLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006212 else if (RequiresArg)
6213 Diag(Tok, diag::err_argument_required_after_attribute);
6214
Alexey Bader1f277942017-10-11 11:16:31 +00006215 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6216 || getLangOpts().OpenCL;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006217
6218 // If we have the closing ')', eat it.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006219 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006220 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006221 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006222 EndLoc = RParenLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006223
David Blaikiebbafb8a2012-03-11 07:00:24 +00006224 if (getLangOpts().CPlusPlus) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006225 // FIXME: Accept these components in any order, and produce fixits to
6226 // correct the order if the user gets it wrong. Ideally we should deal
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00006227 // with the pure-specifier in the same way.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006228
6229 // Parse cv-qualifier-seq[opt].
Aaron Ballman08b06592014-07-22 12:44:22 +00006230 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
Alex Lorenz8f4d3992017-02-13 23:19:40 +00006231 /*AtomicAllowed*/ false,
6232 /*IdentifierRequired=*/false,
6233 llvm::function_ref<void()>([&]() {
6234 Actions.CodeCompleteFunctionQualifiers(DS, D);
6235 }));
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006236 if (!DS.getSourceRange().getEnd().isInvalid()) {
6237 EndLoc = DS.getSourceRange().getEnd();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006238 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006239
6240 // Parse ref-qualifier[opt].
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006241 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
Douglas Gregor9e66af42011-07-05 16:44:18 +00006242 EndLoc = RefQualifierLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006243
Douglas Gregor3024f072012-04-16 07:05:22 +00006244 // C++11 [expr.prim.general]p3:
Chad Rosierc1183952012-06-26 22:30:43 +00006245 // If a declaration declares a member function or member function
6246 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00006247 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Chad Rosierc1183952012-06-26 22:30:43 +00006248 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00006249 // declarator.
Richard Smithad1bbb92013-03-15 00:41:52 +00006250 // FIXME: currently, "static" case isn't handled correctly.
Chad Rosierc1183952012-06-26 22:30:43 +00006251 bool IsCXX11MemberFunction =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006252 getLangOpts().CPlusPlus11 &&
Richard Smith990a6922014-01-17 21:01:18 +00006253 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
Faisal Vali421b2d12017-12-29 05:41:00 +00006254 (D.getContext() == DeclaratorContext::MemberContext
Richard Smithad1bbb92013-03-15 00:41:52 +00006255 ? !D.getDeclSpec().isFriendSpecified()
Faisal Vali421b2d12017-12-29 05:41:00 +00006256 : D.getContext() == DeclaratorContext::FileContext &&
Richard Smithad1bbb92013-03-15 00:41:52 +00006257 D.getCXXScopeSpec().isValid() &&
6258 Actions.CurContext->isRecord());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006259
6260 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6261 if (D.getDeclSpec().isConstexprSpecified() && !getLangOpts().CPlusPlus14)
6262 Q.addConst();
Anastasia Stulova5cffa452019-01-21 16:01:38 +00006263 // FIXME: Collect C++ address spaces.
6264 // If there are multiple different address spaces, the source is invalid.
6265 // Carry on using the first addr space for the qualifiers of 'this'.
6266 // The diagnostic will be given later while creating the function
6267 // prototype for the method.
6268 if (getLangOpts().OpenCLCPlusPlus) {
6269 for (ParsedAttr &attr : DS.getAttributes()) {
6270 LangAS ASIdx = attr.asOpenCLLangAS();
6271 if (ASIdx != LangAS::Default) {
6272 Q.addAddressSpace(ASIdx);
6273 break;
6274 }
6275 }
6276 }
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006277
6278 Sema::CXXThisScopeRAII ThisScope(
6279 Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6280 IsCXX11MemberFunction);
Richard Smith2331bbf2012-05-02 22:22:32 +00006281
Douglas Gregor9e66af42011-07-05 16:44:18 +00006282 // Parse exception-specification[opt].
Richard Smith0b3a4622014-11-13 20:01:57 +00006283 bool Delayed = D.isFirstDeclarationOfMember() &&
Richard Smith3ef3e892014-11-20 22:32:11 +00006284 D.isFunctionDeclaratorAFunctionDeclaration();
6285 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6286 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6287 GetLookAheadToken(1).is(tok::l_paren) &&
6288 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6289 GetLookAheadToken(3).is(tok::l_paren) &&
6290 GetLookAheadToken(4).is(tok::identifier) &&
6291 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6292 // HACK: We've got an exception-specification
6293 // noexcept(noexcept(swap(...)))
6294 // or
6295 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6296 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6297 // for 'swap' will only find the function we're currently declaring,
6298 // whereas it expects to find a non-member swap through ADL. Turn off
6299 // delayed parsing to give it a chance to find what it expects.
6300 Delayed = false;
6301 }
Richard Smith0b3a4622014-11-13 20:01:57 +00006302 ESpecType = tryParseExceptionSpecification(Delayed,
6303 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00006304 DynamicExceptions,
6305 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00006306 NoexceptExpr,
6307 ExceptionSpecTokens);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006308 if (ESpecType != EST_None)
6309 EndLoc = ESpecRange.getEnd();
6310
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006311 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6312 // after the exception-specification.
Richard Smith89645bc2013-01-02 12:01:23 +00006313 MaybeParseCXX11Attributes(FnAttrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006314
Douglas Gregor9e66af42011-07-05 16:44:18 +00006315 // Parse trailing-return-type[opt].
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006316 LocalEndLoc = EndLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006317 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00006318 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
Faisal Vali090da2d2018-01-01 18:23:28 +00006319 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006320 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006321 LocalEndLoc = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00006322 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00006323 TrailingReturnType =
6324 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006325 EndLoc = Range.getEnd();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006326 }
Aaron Ballman606093a2017-10-15 15:01:42 +00006327 } else if (standardAttributesAllowed()) {
6328 MaybeParseCXX11Attributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006329 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006330 }
6331
Reid Kleckner078aea92016-12-09 17:14:05 +00006332 // Collect non-parameter declarations from the prototype if this is a function
6333 // declaration. They will be moved into the scope of the function. Only do
6334 // this in C and not C++, where the decls will continue to live in the
6335 // surrounding context.
6336 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6337 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6338 !getLangOpts().CPlusPlus) {
6339 for (Decl *D : getCurScope()->decls()) {
6340 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6341 if (!ND || isa<ParmVarDecl>(ND))
6342 continue;
6343 DeclsInPrototype.push_back(ND);
6344 }
6345 }
6346
Douglas Gregor9e66af42011-07-05 16:44:18 +00006347 // Remember that we parsed a function type, and remember the attributes.
Erich Keanec480f302018-07-12 21:09:05 +00006348 D.AddTypeInfo(DeclaratorChunk::getFunction(
6349 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6350 ParamInfo.size(), EllipsisLoc, RParenLoc,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00006351 RefQualifierIsLValueRef, RefQualifierLoc,
6352 /*MutableLoc=*/SourceLocation(),
6353 ESpecType, ESpecRange, DynamicExceptions.data(),
6354 DynamicExceptionRanges.data(), DynamicExceptions.size(),
Erich Keanec480f302018-07-12 21:09:05 +00006355 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6356 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00006357 LocalEndLoc, D, TrailingReturnType, &DS),
Erich Keanec480f302018-07-12 21:09:05 +00006358 std::move(FnAttrs), EndLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006359}
6360
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006361/// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6362/// true if a ref-qualifier is found.
6363bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6364 SourceLocation &RefQualifierLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00006365 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006366 Diag(Tok, getLangOpts().CPlusPlus11 ?
6367 diag::warn_cxx98_compat_ref_qualifier :
6368 diag::ext_ref_qualifier);
6369
6370 RefQualifierIsLValueRef = Tok.is(tok::amp);
6371 RefQualifierLoc = ConsumeToken();
6372 return true;
6373 }
6374 return false;
6375}
6376
Douglas Gregor9e66af42011-07-05 16:44:18 +00006377/// isFunctionDeclaratorIdentifierList - This parameter list may have an
6378/// identifier list form for a K&R-style function: void foo(a,b,c)
6379///
6380/// Note that identifier-lists are only allowed for normal declarators, not for
6381/// abstract-declarators.
6382bool Parser::isFunctionDeclaratorIdentifierList() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006383 return !getLangOpts().CPlusPlus
Douglas Gregor9e66af42011-07-05 16:44:18 +00006384 && Tok.is(tok::identifier)
6385 && !TryAltiVecVectorToken()
6386 // K&R identifier lists can't have typedefs as identifiers, per C99
6387 // 6.7.5.3p11.
6388 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6389 // Identifier lists follow a really simple grammar: the identifiers can
6390 // be followed *only* by a ", identifier" or ")". However, K&R
6391 // identifier lists are really rare in the brave new modern world, and
6392 // it is very common for someone to typo a type in a non-K&R style
6393 // list. If we are presented with something like: "void foo(intptr x,
6394 // float y)", we don't want to start parsing the function declarator as
6395 // though it is a K&R style declarator just because intptr is an
6396 // invalid type.
6397 //
6398 // To handle this, we check to see if the token after the first
6399 // identifier is a "," or ")". Only then do we parse it as an
6400 // identifier list.
Bruno Cardoso Lopes218c8742016-09-13 20:04:35 +00006401 && (!Tok.is(tok::eof) &&
6402 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006403}
6404
6405/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6406/// we found a K&R-style identifier list instead of a typed parameter list.
6407///
6408/// After returning, ParamInfo will hold the parsed parameters.
6409///
6410/// identifier-list: [C99 6.7.5]
6411/// identifier
6412/// identifier-list ',' identifier
6413///
6414void Parser::ParseFunctionDeclaratorIdentifierList(
6415 Declarator &D,
Craig Topper5603df42013-07-05 19:34:19 +00006416 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006417 // If there was no identifier specified for the declarator, either we are in
6418 // an abstract-declarator, or we are in a parameter declarator which was found
6419 // to be abstract. In abstract-declarators, identifier lists are not valid:
6420 // diagnose this.
6421 if (!D.getIdentifier())
6422 Diag(Tok, diag::ext_ident_list_in_param);
6423
6424 // Maintain an efficient lookup of params we have seen so far.
6425 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6426
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006427 do {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006428 // If this isn't an identifier, report the error and skip until ')'.
6429 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00006430 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00006431 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006432 // Forget we parsed anything.
6433 ParamInfo.clear();
6434 return;
6435 }
6436
6437 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6438
6439 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6440 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6441 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6442
6443 // Verify that the argument identifier has not already been mentioned.
David Blaikie82e95a32014-11-19 07:49:47 +00006444 if (!ParamsSoFar.insert(ParmII).second) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006445 Diag(Tok, diag::err_param_redefinition) << ParmII;
6446 } else {
6447 // Remember this identifier in ParamInfo.
6448 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6449 Tok.getLocation(),
Craig Topper161e4db2014-05-21 06:02:52 +00006450 nullptr));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006451 }
6452
6453 // Eat the identifier.
6454 ConsumeToken();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006455 // The list continues if we see a comma.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006456 } while (TryConsumeToken(tok::comma));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006457}
6458
6459/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6460/// after the opening parenthesis. This function will not parse a K&R-style
6461/// identifier list.
6462///
Richard Smith2620cd92012-04-11 04:01:28 +00006463/// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6464/// caller parsed those arguments immediately after the open paren - they should
6465/// be considered to be part of the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006466///
6467/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6468/// be the location of the ellipsis, if any was parsed.
6469///
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006470/// parameter-type-list: [C99 6.7.5]
6471/// parameter-list
6472/// parameter-list ',' '...'
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006473/// [C++] parameter-list '...'
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006474///
6475/// parameter-list: [C99 6.7.5]
6476/// parameter-declaration
6477/// parameter-list ',' parameter-declaration
6478///
6479/// parameter-declaration: [C99 6.7.5]
6480/// declaration-specifiers declarator
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006481/// [C++] declaration-specifiers declarator '=' assignment-expression
Sebastian Redldb63af22012-03-14 15:54:00 +00006482/// [C++11] initializer-clause
Chris Lattnere37e2332006-08-15 04:50:22 +00006483/// [GNU] declaration-specifiers declarator attributes
Sebastian Redlf769df52009-03-24 22:27:57 +00006484/// declaration-specifiers abstract-declarator[opt]
6485/// [C++] declaration-specifiers abstract-declarator[opt]
Chris Lattner58258242008-04-10 02:22:51 +00006486/// '=' assignment-expression
Chris Lattnere37e2332006-08-15 04:50:22 +00006487/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
Richard Smith2620cd92012-04-11 04:01:28 +00006488/// [C++11] attribute-specifier-seq parameter-declaration
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006489///
Douglas Gregor9e66af42011-07-05 16:44:18 +00006490void Parser::ParseParameterDeclarationClause(
6491 Declarator &D,
Richard Smith2620cd92012-04-11 04:01:28 +00006492 ParsedAttributes &FirstArgAttrs,
Craig Topper5603df42013-07-05 19:34:19 +00006493 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006494 SourceLocation &EllipsisLoc) {
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006495 do {
6496 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6497 // before deciding this was a parameter-declaration-clause.
6498 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Chris Lattner371ed4e2008-04-06 06:57:35 +00006499 break;
Mike Stump11289f42009-09-09 15:08:12 +00006500
Chris Lattner371ed4e2008-04-06 06:57:35 +00006501 // Parse the declaration-specifiers.
John McCall28a6aea2009-11-04 02:18:39 +00006502 // Just use the ParsingDeclaration "scope" of the declarator.
John McCall084e83d2011-03-24 11:26:52 +00006503 DeclSpec DS(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006504
Richard Smith2620cd92012-04-11 04:01:28 +00006505 // Parse any C++11 attributes.
Richard Smith89645bc2013-01-02 12:01:23 +00006506 MaybeParseCXX11Attributes(DS.getAttributes());
Richard Smith2620cd92012-04-11 04:01:28 +00006507
John McCall53fa7142010-12-24 02:08:15 +00006508 // Skip any Microsoft attributes before a param.
Chad Rosierf8a2e702012-12-20 20:37:53 +00006509 MaybeParseMicrosoftAttributes(DS.getAttributes());
John McCall53fa7142010-12-24 02:08:15 +00006510
6511 SourceLocation DSStart = Tok.getLocation();
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006512
6513 // If the caller parsed attributes for the first argument, add them now.
John McCall53fa7142010-12-24 02:08:15 +00006514 // Take them so that we only apply the attributes to the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006515 // FIXME: If we can leave the attributes in the token stream somehow, we can
Richard Smith2620cd92012-04-11 04:01:28 +00006516 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6517 // too much hassle.
6518 DS.takeAttributesFrom(FirstArgAttrs);
John McCall53fa7142010-12-24 02:08:15 +00006519
Faisal Valia534f072018-04-26 00:42:40 +00006520 ParseDeclarationSpecifiers(DS);
Mike Stump11289f42009-09-09 15:08:12 +00006521
Faisal Vali2b391ab2013-09-26 19:54:12 +00006522
Fangrui Song6907ce22018-07-30 19:24:48 +00006523 // Parse the declarator. This is "PrototypeContext" or
6524 // "LambdaExprParameterContext", because we must accept either
Faisal Vali2b391ab2013-09-26 19:54:12 +00006525 // 'declarator' or 'abstract-declarator' here.
Faisal Vali421b2d12017-12-29 05:41:00 +00006526 Declarator ParmDeclarator(
6527 DS, D.getContext() == DeclaratorContext::LambdaExprContext
6528 ? DeclaratorContext::LambdaExprParameterContext
6529 : DeclaratorContext::PrototypeContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00006530 ParseDeclarator(ParmDeclarator);
Chris Lattner371ed4e2008-04-06 06:57:35 +00006531
6532 // Parse GNU attributes, if present.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006533 MaybeParseGNUAttributes(ParmDeclarator);
Mike Stump11289f42009-09-09 15:08:12 +00006534
Chris Lattner371ed4e2008-04-06 06:57:35 +00006535 // Remember this parsed parameter in ParamInfo.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006536 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
Mike Stump11289f42009-09-09 15:08:12 +00006537
Douglas Gregor4d87df52008-12-16 21:30:33 +00006538 // DefArgToks is used when the parsing of default arguments needs
6539 // to be delayed.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006540 std::unique_ptr<CachedTokens> DefArgToks;
Douglas Gregor4d87df52008-12-16 21:30:33 +00006541
Chris Lattner371ed4e2008-04-06 06:57:35 +00006542 // If no parameter was specified, verify that *something* was specified,
6543 // otherwise we have a missing type and identifier.
Craig Topper161e4db2014-05-21 06:02:52 +00006544 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
Faisal Vali2b391ab2013-09-26 19:54:12 +00006545 ParmDeclarator.getNumTypeObjects() == 0) {
Chris Lattner371ed4e2008-04-06 06:57:35 +00006546 // Completely missing, emit error.
6547 Diag(DSStart, diag::err_missing_param);
6548 } else {
6549 // Otherwise, we have something. Add it and let semantic analysis try
6550 // to grok it and add the result to the ParamInfo we are building.
Mike Stump11289f42009-09-09 15:08:12 +00006551
Richard Smith36ee9fb2014-08-11 23:30:23 +00006552 // Last chance to recover from a misplaced ellipsis in an attempted
6553 // parameter pack declaration.
6554 if (Tok.is(tok::ellipsis) &&
6555 (NextToken().isNot(tok::r_paren) ||
6556 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6557 !Actions.isUnexpandedParameterPackPermitted())) &&
6558 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6559 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6560
Chris Lattner371ed4e2008-04-06 06:57:35 +00006561 // Inform the actions module about the parameter declarator, so it gets
6562 // added to the current scope.
Richard Smith95e1fb02014-08-27 03:23:12 +00006563 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006564 // Parse the default argument, if any. We parse the default
6565 // arguments in all dialects; the semantic analysis in
6566 // ActOnParamDefaultArgument will reject the default argument in
6567 // C.
6568 if (Tok.is(tok::equal)) {
Douglas Gregor58354032008-12-24 00:01:03 +00006569 SourceLocation EqualLoc = Tok.getLocation();
6570
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006571 // Parse the default argument
Faisal Vali421b2d12017-12-29 05:41:00 +00006572 if (D.getContext() == DeclaratorContext::MemberContext) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006573 // If we're inside a class definition, cache the tokens
6574 // corresponding to the default argument. We'll actually parse
6575 // them when we see the end of the class definition.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006576 DefArgToks.reset(new CachedTokens);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006577
David Majnemer906ed272015-01-13 05:28:24 +00006578 SourceLocation ArgStartLoc = NextToken().getLocation();
Richard Smith1fff95c2013-09-12 23:28:08 +00006579 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006580 DefArgToks.reset();
Serge Pavlovb4b35782014-07-22 01:54:49 +00006581 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006582 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006583 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
David Majnemer906ed272015-01-13 05:28:24 +00006584 ArgStartLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006585 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006586 } else {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006587 // Consume the '='.
Douglas Gregor58354032008-12-24 00:01:03 +00006588 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00006589
Chad Rosierc1183952012-06-26 22:30:43 +00006590 // The argument isn't actually potentially evaluated unless it is
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006591 // used.
Faisal Valid143a0c2017-04-01 21:30:49 +00006592 EnterExpressionEvaluationContext Eval(
6593 Actions,
6594 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6595 Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006596
Sebastian Redldb63af22012-03-14 15:54:00 +00006597 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006598 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006599 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +00006600 DefArgResult = ParseBraceInitializer();
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006601 } else
Sebastian Redldb63af22012-03-14 15:54:00 +00006602 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +00006603 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006604 if (DefArgResult.isInvalid()) {
Serge Pavlovb4b35782014-07-22 01:54:49 +00006605 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Alexey Bataevee6507d2013-11-18 08:17:37 +00006606 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006607 } else {
6608 // Inform the actions module about the default argument
6609 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006610 DefArgResult.get());
Douglas Gregor4d87df52008-12-16 21:30:33 +00006611 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006612 }
6613 }
Mike Stump11289f42009-09-09 15:08:12 +00006614
6615 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
Fangrui Song6907ce22018-07-30 19:24:48 +00006616 ParmDeclarator.getIdentifierLoc(),
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006617 Param, std::move(DefArgToks)));
Chris Lattner371ed4e2008-04-06 06:57:35 +00006618 }
6619
Richard Smith36ee9fb2014-08-11 23:30:23 +00006620 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6621 if (!getLangOpts().CPlusPlus) {
6622 // We have ellipsis without a preceding ',', which is ill-formed
6623 // in C. Complain and provide the fix.
6624 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6625 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6626 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6627 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6628 // It looks like this was supposed to be a parameter pack. Warn and
6629 // point out where the ellipsis should have gone.
6630 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6631 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6632 << ParmEllipsis.isValid() << ParmEllipsis;
6633 if (ParmEllipsis.isValid()) {
6634 Diag(ParmEllipsis,
6635 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6636 } else {
6637 Diag(ParmDeclarator.getIdentifierLoc(),
6638 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6639 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6640 "...")
6641 << !ParmDeclarator.hasName();
6642 }
6643 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006644 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
Richard Smith36ee9fb2014-08-11 23:30:23 +00006645 }
6646
6647 // We can't have any more parameters after an ellipsis.
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006648 break;
6649 }
Mike Stump11289f42009-09-09 15:08:12 +00006650
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006651 // If the next token is a comma, consume it and keep reading arguments.
6652 } while (TryConsumeToken(tok::comma));
Chris Lattner6c940e62008-04-06 06:34:08 +00006653}
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006654
Chris Lattnere8074e62006-08-06 18:30:15 +00006655/// [C90] direct-declarator '[' constant-expression[opt] ']'
6656/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6657/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6658/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6659/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006660/// [C++11] direct-declarator '[' constant-expression[opt] ']'
6661/// attribute-specifier-seq[opt]
Chris Lattnere8074e62006-08-06 18:30:15 +00006662void Parser::ParseBracketDeclarator(Declarator &D) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006663 if (CheckProhibitedCXX11Attribute())
6664 return;
6665
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006666 BalancedDelimiterTracker T(*this, tok::l_square);
6667 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00006668
Chris Lattner84a11622008-12-18 07:27:21 +00006669 // C array syntax has many features, but by-far the most common is [] and [4].
6670 // This code does a fast path to handle some of the most obvious cases.
6671 if (Tok.getKind() == tok::r_square) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006672 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006673 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006674 MaybeParseCXX11Attributes(attrs);
Chad Rosierc1183952012-06-26 22:30:43 +00006675
Chris Lattner84a11622008-12-18 07:27:21 +00006676 // Remember that we parsed the empty array type.
Craig Topper161e4db2014-05-21 06:02:52 +00006677 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006678 T.getOpenLocation(),
6679 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006680 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006681 return;
6682 } else if (Tok.getKind() == tok::numeric_constant &&
6683 GetLookAheadToken(1).is(tok::r_square)) {
6684 // [4] is very common. Parse the numeric constant expression.
Richard Smithbcc22fc2012-03-09 08:00:36 +00006685 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
Chris Lattner84a11622008-12-18 07:27:21 +00006686 ConsumeToken();
6687
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006688 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006689 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006690 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006691
Chris Lattner84a11622008-12-18 07:27:21 +00006692 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006693 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006694 T.getOpenLocation(),
6695 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006696 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006697 return;
Benjamin Kramer72dae622016-02-18 15:30:24 +00006698 } else if (Tok.getKind() == tok::code_completion) {
6699 Actions.CodeCompleteBracketDeclarator(getCurScope());
6700 return cutOffParsing();
Chris Lattner84a11622008-12-18 07:27:21 +00006701 }
Mike Stump11289f42009-09-09 15:08:12 +00006702
Chris Lattnere8074e62006-08-06 18:30:15 +00006703 // If valid, this location is the position where we read the 'static' keyword.
6704 SourceLocation StaticLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006705 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006706
Chris Lattnere8074e62006-08-06 18:30:15 +00006707 // If there is a type-qualifier-list, read it now.
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006708 // Type qualifiers in an array subscript are a C99 feature.
John McCall084e83d2011-03-24 11:26:52 +00006709 DeclSpec DS(AttrFactory);
Aaron Ballman08b06592014-07-22 12:44:22 +00006710 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
Mike Stump11289f42009-09-09 15:08:12 +00006711
Chris Lattnere8074e62006-08-06 18:30:15 +00006712 // If we haven't already read 'static', check to see if there is one after the
6713 // type-qualifier-list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006714 if (!StaticLoc.isValid())
6715 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006716
Chris Lattnere8074e62006-08-06 18:30:15 +00006717 // Handle "direct-declarator [ type-qual-list[opt] * ]".
Chris Lattnere8074e62006-08-06 18:30:15 +00006718 bool isStar = false;
John McCalldadc5752010-08-24 06:29:42 +00006719 ExprResult NumElements;
Mike Stump11289f42009-09-09 15:08:12 +00006720
Chris Lattner521ff2b2008-04-06 05:26:30 +00006721 // Handle the case where we have '[*]' as the array size. However, a leading
6722 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
Sylvestre Ledru830885c2012-07-23 08:59:39 +00006723 // the token after the star is a ']'. Since stars in arrays are
Chris Lattner521ff2b2008-04-06 05:26:30 +00006724 // infrequent, use of lookahead is not costly here.
6725 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
Chris Lattnerc439f0d2008-04-06 05:27:21 +00006726 ConsumeToken(); // Eat the '*'.
Chris Lattner1906f802006-08-06 19:14:46 +00006727
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006728 if (StaticLoc.isValid()) {
Chris Lattner521ff2b2008-04-06 05:26:30 +00006729 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006730 StaticLoc = SourceLocation(); // Drop the static.
6731 }
Chris Lattner521ff2b2008-04-06 05:26:30 +00006732 isStar = true;
Chris Lattner76c72282007-10-09 17:33:22 +00006733 } else if (Tok.isNot(tok::r_square)) {
Chris Lattner84a11622008-12-18 07:27:21 +00006734 // Note, in C89, this production uses the constant-expr production instead
6735 // of assignment-expr. The only difference is that assignment-expr allows
6736 // things like '=' and '*='. Sema rejects these in C89 mode because they
6737 // are not i-c-e's, so we don't need to distinguish between the two here.
Mike Stump11289f42009-09-09 15:08:12 +00006738
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006739 // Parse the constant-expression or assignment-expression now (depending
6740 // on dialect).
David Blaikiebbafb8a2012-03-11 07:00:24 +00006741 if (getLangOpts().CPlusPlus) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006742 NumElements = ParseConstantExpression();
Eli Friedmane0afc982012-01-21 01:01:51 +00006743 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00006744 EnterExpressionEvaluationContext Unevaluated(
6745 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Kaelyn Takata15867822014-11-21 18:48:04 +00006746 NumElements =
6747 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Eli Friedmane0afc982012-01-21 01:01:51 +00006748 }
David Majnemerf9834d52014-08-08 07:21:18 +00006749 } else {
6750 if (StaticLoc.isValid()) {
6751 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6752 StaticLoc = SourceLocation(); // Drop the static.
6753 }
Chris Lattner62591722006-08-12 18:40:58 +00006754 }
Mike Stump11289f42009-09-09 15:08:12 +00006755
Chris Lattner62591722006-08-12 18:40:58 +00006756 // If there was an error parsing the assignment-expression, recover.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00006757 if (NumElements.isInvalid()) {
Chris Lattnercd2a8c52009-04-24 22:30:50 +00006758 D.setInvalidType(true);
Chris Lattner62591722006-08-12 18:40:58 +00006759 // If the expression was invalid, skip it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00006760 SkipUntil(tok::r_square, StopAtSemi);
Chris Lattner62591722006-08-12 18:40:58 +00006761 return;
Chris Lattnere8074e62006-08-06 18:30:15 +00006762 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006763
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006764 T.consumeClose();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006765
Jordan Rose303e2f12016-11-10 23:28:17 +00006766 MaybeParseCXX11Attributes(DS.getAttributes());
Alexis Hunt96d5c762009-11-21 08:43:09 +00006767
Chris Lattner84a11622008-12-18 07:27:21 +00006768 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006769 D.AddTypeInfo(
6770 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6771 isStar, NumElements.get(), T.getOpenLocation(),
6772 T.getCloseLocation()),
6773 std::move(DS.getAttributes()), T.getCloseLocation());
Chris Lattnere8074e62006-08-06 18:30:15 +00006774}
6775
Richard Trieuf4b81d02014-06-24 23:14:24 +00006776/// Diagnose brackets before an identifier.
6777void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6778 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6779 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6780
6781 SourceLocation StartBracketLoc = Tok.getLocation();
6782 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6783
6784 while (Tok.is(tok::l_square)) {
6785 ParseBracketDeclarator(TempDeclarator);
6786 }
6787
6788 // Stuff the location of the start of the brackets into the Declarator.
6789 // The diagnostics from ParseDirectDeclarator will make more sense if
6790 // they use this location instead.
6791 if (Tok.is(tok::semi))
6792 D.getName().EndLocation = StartBracketLoc;
6793
6794 SourceLocation SuggestParenLoc = Tok.getLocation();
6795
6796 // Now that the brackets are removed, try parsing the declarator again.
6797 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6798
6799 // Something went wrong parsing the brackets, in which case,
6800 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6801 // one here.
6802 if (TempDeclarator.getNumTypeObjects() == 0)
6803 return;
6804
6805 // Determine if parens will need to be suggested in the diagnostic.
6806 bool NeedParens = false;
6807 if (D.getNumTypeObjects() != 0) {
6808 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6809 case DeclaratorChunk::Pointer:
6810 case DeclaratorChunk::Reference:
6811 case DeclaratorChunk::BlockPointer:
6812 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00006813 case DeclaratorChunk::Pipe:
Richard Trieuf4b81d02014-06-24 23:14:24 +00006814 NeedParens = true;
6815 break;
6816 case DeclaratorChunk::Array:
6817 case DeclaratorChunk::Function:
6818 case DeclaratorChunk::Paren:
6819 break;
6820 }
6821 }
6822
6823 if (NeedParens) {
6824 // Create a DeclaratorChunk for the inserted parens.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006825 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Erich Keanec480f302018-07-12 21:09:05 +00006826 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
Richard Trieuf4b81d02014-06-24 23:14:24 +00006827 SourceLocation());
6828 }
6829
6830 // Adding back the bracket info to the end of the Declarator.
6831 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6832 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
Erich Keanec480f302018-07-12 21:09:05 +00006833 D.AddTypeInfo(Chunk, SourceLocation());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006834 }
6835
6836 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6837 // If parentheses are required, always suggest them.
6838 if (!D.getIdentifier() && !NeedParens)
6839 return;
6840
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006841 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
Richard Trieuf4b81d02014-06-24 23:14:24 +00006842
6843 // Generate the move bracket error message.
6844 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006845 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006846
6847 if (NeedParens) {
6848 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6849 << getLangOpts().CPlusPlus
6850 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6851 << FixItHint::CreateInsertion(EndLoc, ")")
6852 << FixItHint::CreateInsertionFromRange(
6853 EndLoc, CharSourceRange(BracketRange, true))
6854 << FixItHint::CreateRemoval(BracketRange);
6855 } else {
6856 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6857 << getLangOpts().CPlusPlus
6858 << FixItHint::CreateInsertionFromRange(
6859 EndLoc, CharSourceRange(BracketRange, true))
6860 << FixItHint::CreateRemoval(BracketRange);
6861 }
6862}
6863
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006864/// [GNU] typeof-specifier:
6865/// typeof ( expressions )
6866/// typeof ( type-name )
6867/// [GNU/C++] typeof unary-expression
Steve Naroffad373bd2007-07-31 12:34:36 +00006868///
6869void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
Chris Lattner76c72282007-10-09 17:33:22 +00006870 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006871 Token OpTok = Tok;
Steve Naroffad373bd2007-07-31 12:34:36 +00006872 SourceLocation StartLoc = ConsumeToken();
6873
John McCalle8595032010-01-13 20:03:27 +00006874 const bool hasParens = Tok.is(tok::l_paren);
6875
Faisal Valid143a0c2017-04-01 21:30:49 +00006876 EnterExpressionEvaluationContext Unevaluated(
6877 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6878 Sema::ReuseLambdaContextDecl);
Eli Friedmane0afc982012-01-21 01:01:51 +00006879
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006880 bool isCastExpr;
John McCallba7bf592010-08-24 05:47:05 +00006881 ParsedType CastTy;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006882 SourceRange CastRange;
Kaelyn Takata911260742014-12-19 01:28:40 +00006883 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6884 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
John McCalle8595032010-01-13 20:03:27 +00006885 if (hasParens)
6886 DS.setTypeofParensRange(CastRange);
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006887
6888 if (CastRange.getEnd().isInvalid())
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006889 // FIXME: Not accurate, the range gets one token more than it should.
6890 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006891 else
6892 DS.SetRangeEnd(CastRange.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +00006893
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006894 if (isCastExpr) {
6895 if (!CastTy) {
6896 DS.SetTypeSpecError();
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006897 return;
Douglas Gregor220cac52009-02-18 17:45:20 +00006898 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006899
Craig Topper161e4db2014-05-21 06:02:52 +00006900 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006901 unsigned DiagID;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006902 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6903 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006904 DiagID, CastTy,
6905 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006906 Diag(StartLoc, DiagID) << PrevSpec;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006907 return;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006908 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006909
Hiroshi Inoue533777f2017-07-02 06:12:49 +00006910 // If we get here, the operand to the typeof was an expression.
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006911 if (Operand.isInvalid()) {
6912 DS.SetTypeSpecError();
Steve Naroff4bd2f712007-08-02 02:53:48 +00006913 return;
Steve Naroffad373bd2007-07-31 12:34:36 +00006914 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006915
Eli Friedmane0afc982012-01-21 01:01:51 +00006916 // We might need to transform the operand if it is potentially evaluated.
6917 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6918 if (Operand.isInvalid()) {
6919 DS.SetTypeSpecError();
6920 return;
6921 }
6922
Craig Topper161e4db2014-05-21 06:02:52 +00006923 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006924 unsigned DiagID;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006925 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6926 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006927 DiagID, Operand.get(),
6928 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006929 Diag(StartLoc, DiagID) << PrevSpec;
Steve Naroffad373bd2007-07-31 12:34:36 +00006930}
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006931
Benjamin Kramere56f3932011-12-23 17:00:35 +00006932/// [C11] atomic-specifier:
Eli Friedman0dfb8892011-10-06 23:00:33 +00006933/// _Atomic ( type-name )
6934///
6935void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
Richard Smith8e1ac332013-03-28 01:55:44 +00006936 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6937 "Not an atomic specifier");
Eli Friedman0dfb8892011-10-06 23:00:33 +00006938
6939 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006940 BalancedDelimiterTracker T(*this, tok::l_paren);
Richard Smith8e1ac332013-03-28 01:55:44 +00006941 if (T.consumeOpen())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006942 return;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006943
6944 TypeResult Result = ParseTypeName();
6945 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00006946 SkipUntil(tok::r_paren, StopAtSemi);
Eli Friedman0dfb8892011-10-06 23:00:33 +00006947 return;
6948 }
6949
6950 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006951 T.consumeClose();
Eli Friedman0dfb8892011-10-06 23:00:33 +00006952
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006953 if (T.getCloseLocation().isInvalid())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006954 return;
6955
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006956 DS.setTypeofParensRange(T.getRange());
6957 DS.SetRangeEnd(T.getCloseLocation());
Eli Friedman0dfb8892011-10-06 23:00:33 +00006958
Craig Topper161e4db2014-05-21 06:02:52 +00006959 const char *PrevSpec = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006960 unsigned DiagID;
6961 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006962 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006963 Actions.getASTContext().getPrintingPolicy()))
Eli Friedman0dfb8892011-10-06 23:00:33 +00006964 Diag(StartLoc, DiagID) << PrevSpec;
6965}
6966
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006967/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6968/// from TryAltiVecVectorToken.
6969bool Parser::TryAltiVecVectorTokenOutOfLine() {
6970 Token Next = NextToken();
6971 switch (Next.getKind()) {
6972 default: return false;
6973 case tok::kw_short:
6974 case tok::kw_long:
6975 case tok::kw_signed:
6976 case tok::kw_unsigned:
6977 case tok::kw_void:
6978 case tok::kw_char:
6979 case tok::kw_int:
6980 case tok::kw_float:
6981 case tok::kw_double:
6982 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006983 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006984 case tok::kw___pixel:
6985 Tok.setKind(tok::kw___vector);
6986 return true;
6987 case tok::identifier:
6988 if (Next.getIdentifierInfo() == Ident_pixel) {
6989 Tok.setKind(tok::kw___vector);
6990 return true;
6991 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006992 if (Next.getIdentifierInfo() == Ident_bool) {
6993 Tok.setKind(tok::kw___vector);
6994 return true;
6995 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006996 return false;
6997 }
6998}
6999
7000bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
7001 const char *&PrevSpec, unsigned &DiagID,
7002 bool &isInvalid) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007003 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007004 if (Tok.getIdentifierInfo() == Ident_vector) {
7005 Token Next = NextToken();
7006 switch (Next.getKind()) {
7007 case tok::kw_short:
7008 case tok::kw_long:
7009 case tok::kw_signed:
7010 case tok::kw_unsigned:
7011 case tok::kw_void:
7012 case tok::kw_char:
7013 case tok::kw_int:
7014 case tok::kw_float:
7015 case tok::kw_double:
7016 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00007017 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007018 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007019 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007020 return true;
7021 case tok::identifier:
7022 if (Next.getIdentifierInfo() == Ident_pixel) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007023 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007024 return true;
7025 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00007026 if (Next.getIdentifierInfo() == Ident_bool) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007027 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00007028 return true;
7029 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007030 break;
7031 default:
7032 break;
7033 }
Douglas Gregor9938e3b2010-06-16 15:28:57 +00007034 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007035 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007036 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007037 return true;
Bill Schmidt99a084b2013-07-03 20:54:09 +00007038 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
7039 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007040 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00007041 return true;
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007042 }
7043 return false;
7044}