blob: bbead42f0315b929c7760f8c816596be1e35973e [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
Alexis Hunt96d5c762009-11-21 08:43:09 +000088/// ParseGNUAttributes - Parse a non-empty attributes list.
Chris Lattnerb8cd5c22006-08-15 04:10:46 +000089///
90/// [GNU] attributes:
91/// attribute
92/// attributes attribute
93///
94/// [GNU] attribute:
95/// '__attribute__' '(' '(' attribute-list ')' ')'
96///
97/// [GNU] attribute-list:
98/// attrib
99/// attribute_list ',' attrib
100///
101/// [GNU] attrib:
102/// empty
Steve Naroff0f2fe172007-06-01 17:11:19 +0000103/// attrib-name
104/// attrib-name '(' identifier ')'
105/// attrib-name '(' identifier ',' nonempty-expr-list ')'
106/// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
Chris Lattnerb8cd5c22006-08-15 04:10:46 +0000107///
Steve Naroff0f2fe172007-06-01 17:11:19 +0000108/// [GNU] attrib-name:
109/// identifier
110/// typespec
111/// typequal
112/// storageclass
Mike Stump11289f42009-09-09 15:08:12 +0000113///
Richard Smithf7ca0c02013-09-03 18:57:36 +0000114/// Whether an attribute takes an 'identifier' is determined by the
115/// attrib-name. GCC's behavior here is not worth imitating:
Steve Naroff0f2fe172007-06-01 17:11:19 +0000116///
Richard Smithf7ca0c02013-09-03 18:57:36 +0000117/// * In C mode, if the attribute argument list starts with an identifier
118/// followed by a ',' or an ')', and the identifier doesn't resolve to
119/// a type, it is parsed as an identifier. If the attribute actually
120/// wanted an expression, it's out of luck (but it turns out that no
121/// attributes work that way, because C constant expressions are very
122/// limited).
123/// * In C++ mode, if the attribute argument list starts with an identifier,
124/// and the attribute *wants* an identifier, it is parsed as an identifier.
125/// At block scope, any additional tokens between the identifier and the
126/// ',' or ')' are ignored, otherwise they produce a parse error.
Richard Smithb12bf692011-10-17 21:20:17 +0000127///
Richard Smithf7ca0c02013-09-03 18:57:36 +0000128/// We follow the C++ model, but don't allow junk after the identifier.
John McCall53fa7142010-12-24 02:08:15 +0000129void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000130 SourceLocation *endLoc,
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000131 LateParsedAttrList *LateAttrs,
132 Declarator *D) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000133 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
Mike Stump11289f42009-09-09 15:08:12 +0000134
Chris Lattner76c72282007-10-09 17:33:22 +0000135 while (Tok.is(tok::kw___attribute)) {
Steve Naroff0f2fe172007-06-01 17:11:19 +0000136 ConsumeToken();
137 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
138 "attribute")) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000139 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
John McCall53fa7142010-12-24 02:08:15 +0000140 return;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000141 }
142 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000143 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
John McCall53fa7142010-12-24 02:08:15 +0000144 return;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000145 }
146 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
Alp Toker094e5212014-01-05 03:27:11 +0000147 while (true) {
148 // Allow empty/non-empty attributes. ((__vector_size__(16),,,,))
149 if (TryConsumeToken(tok::comma))
Steve Naroff0f2fe172007-06-01 17:11:19 +0000150 continue;
Alp Toker094e5212014-01-05 03:27:11 +0000151
152 // Expect an identifier or declaration specifier (const, int, etc.)
David Majnemer22fe7712015-01-03 19:41:00 +0000153 if (Tok.isAnnotation())
154 break;
155 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
156 if (!AttrName)
Alp Toker094e5212014-01-05 03:27:11 +0000157 break;
158
Steve Naroff0f2fe172007-06-01 17:11:19 +0000159 SourceLocation AttrNameLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000160
Alp Toker094e5212014-01-05 03:27:11 +0000161 if (Tok.isNot(tok::l_paren)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000162 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000163 ParsedAttr::AS_GNU);
Alp Toker094e5212014-01-05 03:27:11 +0000164 continue;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000165 }
Alp Toker094e5212014-01-05 03:27:11 +0000166
167 // Handle "parameterized" attributes
168 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000169 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
Erich Keanee891aa92018-07-13 15:07:47 +0000170 SourceLocation(), ParsedAttr::AS_GNU, D);
Alp Toker094e5212014-01-05 03:27:11 +0000171 continue;
172 }
173
174 // Handle attributes with arguments that require late parsing.
175 LateParsedAttribute *LA =
176 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
177 LateAttrs->push_back(LA);
178
179 // Attributes in a class are parsed at the end of the class, along
180 // with other late-parsed declarations.
181 if (!ClassStack.empty() && !LateAttrs->parseSoon())
182 getCurrentClass().LateParsedDeclarations.push_back(LA);
183
George Burgess IVc8b95372017-01-04 22:43:01 +0000184 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
185 // recursively consumes balanced parens.
186 LA->Toks.push_back(Tok);
187 ConsumeParen();
188 // Consume everything up to and including the matching right parens.
189 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
Alp Toker094e5212014-01-05 03:27:11 +0000190
191 Token Eof;
192 Eof.startToken();
193 Eof.setLocation(Tok.getLocation());
194 LA->Toks.push_back(Eof);
Steve Naroff0f2fe172007-06-01 17:11:19 +0000195 }
Alp Toker094e5212014-01-05 03:27:11 +0000196
Alp Toker383d2c42014-01-01 03:08:43 +0000197 if (ExpectAndConsume(tok::r_paren))
Alexey Bataevee6507d2013-11-18 08:17:37 +0000198 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000199 SourceLocation Loc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000200 if (ExpectAndConsume(tok::r_paren))
Alexey Bataevee6507d2013-11-18 08:17:37 +0000201 SkipUntil(tok::r_paren, StopAtSemi);
John McCall53fa7142010-12-24 02:08:15 +0000202 if (endLoc)
203 *endLoc = Loc;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000204 }
Steve Naroff0f2fe172007-06-01 17:11:19 +0000205}
Chris Lattnerf5fbd792006-08-10 23:56:11 +0000206
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000207/// Determine whether the given attribute has an identifier argument.
Aaron Ballman4768b312013-11-04 12:55:56 +0000208static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000209#define CLANG_ATTR_IDENTIFIER_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000210 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000211#include "clang/Parse/AttrParserStringSwitches.inc"
Douglas Gregord2472d42013-05-02 23:25:32 +0000212 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000213#undef CLANG_ATTR_IDENTIFIER_ARG_LIST
Douglas Gregord2472d42013-05-02 23:25:32 +0000214}
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000215
Erich Keane3efe0022018-07-20 14:13:28 +0000216/// Determine whether the given attribute has a variadic identifier argument.
217static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
218#define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
219 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
220#include "clang/Parse/AttrParserStringSwitches.inc"
221 .Default(false);
222#undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
223}
224
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000225/// Determine whether the given attribute treats kw_this as an identifier.
226static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II) {
227#define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
228 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
229#include "clang/Parse/AttrParserStringSwitches.inc"
230 .Default(false);
231#undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
232}
233
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000234/// Determine whether the given attribute parses a type argument.
Aaron Ballman4768b312013-11-04 12:55:56 +0000235static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000236#define CLANG_ATTR_TYPE_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000237 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000238#include "clang/Parse/AttrParserStringSwitches.inc"
Aaron Ballman4768b312013-11-04 12:55:56 +0000239 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000240#undef CLANG_ATTR_TYPE_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000241}
242
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000243/// Determine whether the given attribute requires parsing its arguments
Aaron Ballman15b27b92014-01-09 19:39:35 +0000244/// in an unevaluated context or not.
245static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000246#define CLANG_ATTR_ARG_CONTEXT_LIST
Aaron Ballman15b27b92014-01-09 19:39:35 +0000247 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000248#include "clang/Parse/AttrParserStringSwitches.inc"
Aaron Ballman15b27b92014-01-09 19:39:35 +0000249 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000250#undef CLANG_ATTR_ARG_CONTEXT_LIST
Aaron Ballman15b27b92014-01-09 19:39:35 +0000251}
252
Richard Smithfeefaf52013-09-03 18:01:40 +0000253IdentifierLoc *Parser::ParseIdentifierLoc() {
254 assert(Tok.is(tok::identifier) && "expected an identifier");
255 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
256 Tok.getLocation(),
257 Tok.getIdentifierInfo());
258 ConsumeToken();
259 return IL;
260}
261
Richard Smithb1f9a282013-10-31 01:56:18 +0000262void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
263 SourceLocation AttrNameLoc,
264 ParsedAttributes &Attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000265 SourceLocation *EndLoc,
266 IdentifierInfo *ScopeName,
267 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000268 ParsedAttr::Syntax Syntax) {
Richard Smithb1f9a282013-10-31 01:56:18 +0000269 BalancedDelimiterTracker Parens(*this, tok::l_paren);
270 Parens.consumeOpen();
271
272 TypeResult T;
273 if (Tok.isNot(tok::r_paren))
274 T = ParseTypeName();
275
276 if (Parens.consumeClose())
277 return;
278
279 if (T.isInvalid())
280 return;
281
282 if (T.isUsable())
283 Attrs.addNewTypeAttr(&AttrName,
Craig Topper161e4db2014-05-21 06:02:52 +0000284 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000285 ScopeName, ScopeLoc, T.get(), Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000286 else
287 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000288 ScopeName, ScopeLoc, nullptr, 0, Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000289}
290
Aaron Ballman35f94212014-04-14 16:03:22 +0000291unsigned Parser::ParseAttributeArgsCommon(
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000292 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
293 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +0000294 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000295 // Ignore the left paren location for now.
296 ConsumeParen();
297
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000298 bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
299
300 // Interpret "kw_this" as an identifier if the attributed requests it.
301 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
302 Tok.setKind(tok::identifier);
303
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000304 ArgsVector ArgExprs;
305 if (Tok.is(tok::identifier)) {
306 // If this attribute wants an 'identifier' argument, make it so.
Erich Keane3efe0022018-07-20 14:13:28 +0000307 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
308 attributeHasVariadicIdentifierArg(*AttrName);
Erich Keanee891aa92018-07-13 15:07:47 +0000309 ParsedAttr::Kind AttrKind =
310 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000311
312 // If we don't know how to parse this attribute, but this is the only
313 // token in this argument, assume it's meant to be an identifier.
Erich Keanee891aa92018-07-13 15:07:47 +0000314 if (AttrKind == ParsedAttr::UnknownAttribute ||
315 AttrKind == ParsedAttr::IgnoredAttribute) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000316 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000317 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000318 }
319
320 if (IsIdentifierArg)
321 ArgExprs.push_back(ParseIdentifierLoc());
322 }
323
324 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
325 // Eat the comma.
326 if (!ArgExprs.empty())
327 ConsumeToken();
328
329 // Parse the non-empty comma-separated list of expressions.
330 do {
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000331 // Interpret "kw_this" as an identifier if the attributed requests it.
332 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
333 Tok.setKind(tok::identifier);
334
Erich Keane3efe0022018-07-20 14:13:28 +0000335 ExprResult ArgExpr;
336 if (Tok.is(tok::identifier) &&
337 attributeHasVariadicIdentifierArg(*AttrName)) {
338 ArgExprs.push_back(ParseIdentifierLoc());
339 } else {
340 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
341 EnterExpressionEvaluationContext Unevaluated(
342 Actions,
343 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
344 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000345
Erich Keane3efe0022018-07-20 14:13:28 +0000346 ExprResult ArgExpr(
347 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
348 if (ArgExpr.isInvalid()) {
349 SkipUntil(tok::r_paren, StopAtSemi);
350 return 0;
351 }
352 ArgExprs.push_back(ArgExpr.get());
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000353 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000354 // Eat the comma, move to the next argument
355 } while (TryConsumeToken(tok::comma));
356 }
357
358 SourceLocation RParen = Tok.getLocation();
359 if (!ExpectAndConsume(tok::r_paren)) {
360 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
361 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
362 ArgExprs.data(), ArgExprs.size(), Syntax);
363 }
364
365 if (EndLoc)
366 *EndLoc = RParen;
Aaron Ballman35f94212014-04-14 16:03:22 +0000367
368 return static_cast<unsigned>(ArgExprs.size());
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000369}
370
Michael Han23214e52012-10-03 01:56:22 +0000371/// Parse the arguments to a parameterized GNU attribute or
372/// a C++11 attribute in "gnu" namespace.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000373void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
374 SourceLocation AttrNameLoc,
375 ParsedAttributes &Attrs,
Michael Han23214e52012-10-03 01:56:22 +0000376 SourceLocation *EndLoc,
377 IdentifierInfo *ScopeName,
378 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000379 ParsedAttr::Syntax Syntax,
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000380 Declarator *D) {
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000381
382 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
383
Erich Keanee891aa92018-07-13 15:07:47 +0000384 ParsedAttr::Kind AttrKind =
385 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Richard Smith66e71682013-10-24 01:07:54 +0000386
Erich Keanee891aa92018-07-13 15:07:47 +0000387 if (AttrKind == ParsedAttr::AT_Availability) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000388 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
389 ScopeLoc, Syntax);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000390 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000391 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000392 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
393 ScopeName, ScopeLoc, Syntax);
394 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000395 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000396 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
397 ScopeName, ScopeLoc, Syntax);
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +0000398 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000399 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000400 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
401 ScopeName, ScopeLoc, Syntax);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000402 return;
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000403 } else if (attributeIsTypeArgAttr(*AttrName)) {
404 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
405 ScopeLoc, Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000406 return;
407 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000408
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000409 // These may refer to the function arguments, but need to be parsed early to
410 // participate in determining whether it's a redeclaration.
George Burgess IVa19ea342016-11-10 20:43:52 +0000411 llvm::Optional<ParseScope> PrototypeScope;
Ulrich Weigandef5aa292015-07-13 14:13:01 +0000412 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
413 D && D->isFunctionDeclarator()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000414 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
George Burgess IVa19ea342016-11-10 20:43:52 +0000415 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
416 Scope::FunctionDeclarationScope |
417 Scope::DeclScope);
Alp Tokerc5350722014-02-26 22:27:52 +0000418 for (unsigned i = 0; i != FTI.NumParams; ++i) {
419 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000420 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
421 }
422 }
423
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000424 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
425 ScopeLoc, Syntax);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000426}
427
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000428unsigned Parser::ParseClangAttributeArgs(
429 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
430 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +0000431 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000432 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
433
Erich Keanee891aa92018-07-13 15:07:47 +0000434 ParsedAttr::Kind AttrKind =
435 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000436
Aaron Ballman38bbc162018-02-24 17:16:42 +0000437 switch (AttrKind) {
438 default:
439 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
440 ScopeName, ScopeLoc, Syntax);
Erich Keanee891aa92018-07-13 15:07:47 +0000441 case ParsedAttr::AT_ExternalSourceSymbol:
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000442 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
443 ScopeName, ScopeLoc, Syntax);
Aaron Ballman38bbc162018-02-24 17:16:42 +0000444 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000445 case ParsedAttr::AT_Availability:
Aaron Ballman38bbc162018-02-24 17:16:42 +0000446 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
447 ScopeLoc, Syntax);
448 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000449 case ParsedAttr::AT_ObjCBridgeRelated:
Aaron Ballmanc248b0f2018-02-24 17:37:37 +0000450 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
451 ScopeName, ScopeLoc, Syntax);
452 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000453 case ParsedAttr::AT_TypeTagForDatatype:
Aaron Ballmana26d8ee2018-02-25 14:01:04 +0000454 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
455 ScopeName, ScopeLoc, Syntax);
456 break;
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000457 }
Erich Keanec480f302018-07-12 21:09:05 +0000458 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000459}
460
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000461bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
462 SourceLocation AttrNameLoc,
463 ParsedAttributes &Attrs) {
464 // If the attribute isn't known, we will not attempt to parse any
465 // arguments.
466 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
Bob Wilson7c730832015-07-20 22:57:31 +0000467 getTargetInfo(), getLangOpts())) {
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000468 // Eat the left paren, then skip to the ending right paren.
469 ConsumeParen();
470 SkipUntil(tok::r_paren);
471 return false;
Aaron Ballman478faed2012-06-19 22:09:27 +0000472 }
Aaron Ballman478faed2012-06-19 22:09:27 +0000473
Aaron Ballman95d57032014-04-14 16:44:26 +0000474 SourceLocation OpenParenLoc = Tok.getLocation();
475
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000476 if (AttrName->getName() == "property") {
Aaron Ballman478faed2012-06-19 22:09:27 +0000477 // The property declspec is more complex in that it can take one or two
Chad Rosierc1183952012-06-26 22:30:43 +0000478 // assignment expressions as a parameter, but the lhs of the assignment
Aaron Ballman478faed2012-06-19 22:09:27 +0000479 // must be named get or put.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000480
John McCall5e77d762013-04-16 07:28:30 +0000481 BalancedDelimiterTracker T(*this, tok::l_paren);
482 T.expectAndConsume(diag::err_expected_lparen_after,
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000483 AttrName->getNameStart(), tok::r_paren);
John McCall5e77d762013-04-16 07:28:30 +0000484
485 enum AccessorKind {
486 AK_Invalid = -1,
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000487 AK_Put = 0,
488 AK_Get = 1 // indices into AccessorNames
John McCall5e77d762013-04-16 07:28:30 +0000489 };
Craig Topper161e4db2014-05-21 06:02:52 +0000490 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
John McCall5e77d762013-04-16 07:28:30 +0000491 bool HasInvalidAccessor = false;
492
493 // Parse the accessor specifications.
494 while (true) {
495 // Stop if this doesn't look like an accessor spec.
496 if (!Tok.is(tok::identifier)) {
497 // If the user wrote a completely empty list, use a special diagnostic.
498 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
Craig Topper161e4db2014-05-21 06:02:52 +0000499 AccessorNames[AK_Put] == nullptr &&
500 AccessorNames[AK_Get] == nullptr) {
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000501 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
John McCall5e77d762013-04-16 07:28:30 +0000502 break;
503 }
504
505 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
506 break;
507 }
508
509 AccessorKind Kind;
510 SourceLocation KindLoc = Tok.getLocation();
511 StringRef KindStr = Tok.getIdentifierInfo()->getName();
512 if (KindStr == "get") {
513 Kind = AK_Get;
514 } else if (KindStr == "put") {
515 Kind = AK_Put;
516
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000517 // Recover from the common mistake of using 'set' instead of 'put'.
John McCall5e77d762013-04-16 07:28:30 +0000518 } else if (KindStr == "set") {
519 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000520 << FixItHint::CreateReplacement(KindLoc, "put");
John McCall5e77d762013-04-16 07:28:30 +0000521 Kind = AK_Put;
522
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000523 // Handle the mistake of forgetting the accessor kind by skipping
524 // this accessor.
John McCall5e77d762013-04-16 07:28:30 +0000525 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
526 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
527 ConsumeToken();
528 HasInvalidAccessor = true;
529 goto next_property_accessor;
530
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000531 // Otherwise, complain about the unknown accessor kind.
John McCall5e77d762013-04-16 07:28:30 +0000532 } else {
533 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
534 HasInvalidAccessor = true;
535 Kind = AK_Invalid;
536
537 // Try to keep parsing unless it doesn't look like an accessor spec.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000538 if (!NextToken().is(tok::equal))
539 break;
John McCall5e77d762013-04-16 07:28:30 +0000540 }
541
542 // Consume the identifier.
543 ConsumeToken();
544
545 // Consume the '='.
Alp Toker8fbec672013-12-17 23:29:36 +0000546 if (!TryConsumeToken(tok::equal)) {
John McCall5e77d762013-04-16 07:28:30 +0000547 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000548 << KindStr;
John McCall5e77d762013-04-16 07:28:30 +0000549 break;
550 }
551
552 // Expect the method name.
553 if (!Tok.is(tok::identifier)) {
554 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
555 break;
556 }
557
558 if (Kind == AK_Invalid) {
559 // Just drop invalid accessors.
Craig Topper161e4db2014-05-21 06:02:52 +0000560 } else if (AccessorNames[Kind] != nullptr) {
John McCall5e77d762013-04-16 07:28:30 +0000561 // Complain about the repeated accessor, ignore it, and keep parsing.
562 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
563 } else {
564 AccessorNames[Kind] = Tok.getIdentifierInfo();
565 }
566 ConsumeToken();
567
568 next_property_accessor:
569 // Keep processing accessors until we run out.
Alp Toker094e5212014-01-05 03:27:11 +0000570 if (TryConsumeToken(tok::comma))
John McCall5e77d762013-04-16 07:28:30 +0000571 continue;
572
573 // If we run into the ')', stop without consuming it.
Alp Toker094e5212014-01-05 03:27:11 +0000574 if (Tok.is(tok::r_paren))
John McCall5e77d762013-04-16 07:28:30 +0000575 break;
Alp Toker094e5212014-01-05 03:27:11 +0000576
577 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
578 break;
John McCall5e77d762013-04-16 07:28:30 +0000579 }
580
581 // Only add the property attribute if it was well-formed.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000582 if (!HasInvalidAccessor)
Craig Topper161e4db2014-05-21 06:02:52 +0000583 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
John McCall5e77d762013-04-16 07:28:30 +0000584 AccessorNames[AK_Get], AccessorNames[AK_Put],
Erich Keanee891aa92018-07-13 15:07:47 +0000585 ParsedAttr::AS_Declspec);
Aaron Ballman478faed2012-06-19 22:09:27 +0000586 T.skipToEnd();
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000587 return !HasInvalidAccessor;
Aaron Ballman478faed2012-06-19 22:09:27 +0000588 }
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000589
Aaron Ballman95d57032014-04-14 16:44:26 +0000590 unsigned NumArgs =
591 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
Erich Keanee891aa92018-07-13 15:07:47 +0000592 SourceLocation(), ParsedAttr::AS_Declspec);
Aaron Ballman95d57032014-04-14 16:44:26 +0000593
594 // If this attribute's args were parsed, and it was expected to have
595 // arguments but none were provided, emit a diagnostic.
Erich Keanec480f302018-07-12 21:09:05 +0000596 if (!Attrs.empty() && Attrs.begin()->getMaxArgs() && !NumArgs) {
Aaron Ballmanef5d94c2014-04-15 00:36:39 +0000597 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Aaron Ballman95d57032014-04-14 16:44:26 +0000598 return false;
599 }
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000600 return true;
Aaron Ballman478faed2012-06-19 22:09:27 +0000601}
602
Eli Friedman06de2b52009-06-08 07:21:15 +0000603/// [MS] decl-specifier:
604/// __declspec ( extended-decl-modifier-seq )
605///
606/// [MS] extended-decl-modifier-seq:
607/// extended-decl-modifier[opt]
608/// extended-decl-modifier extended-decl-modifier-seq
Aaron Ballman068aa512015-05-20 20:58:33 +0000609void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
610 SourceLocation *End) {
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +0000611 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
Steve Naroff3a9b7e02008-12-24 20:59:21 +0000612 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
Eli Friedman06de2b52009-06-08 07:21:15 +0000613
Aaron Ballman068aa512015-05-20 20:58:33 +0000614 while (Tok.is(tok::kw___declspec)) {
615 ConsumeToken();
616 BalancedDelimiterTracker T(*this, tok::l_paren);
617 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
618 tok::r_paren))
Aaron Ballman478faed2012-06-19 22:09:27 +0000619 return;
Aaron Ballman478faed2012-06-19 22:09:27 +0000620
Aaron Ballman068aa512015-05-20 20:58:33 +0000621 // An empty declspec is perfectly legal and should not warn. Additionally,
622 // you can specify multiple attributes per declspec.
623 while (Tok.isNot(tok::r_paren)) {
624 // Attribute not present.
625 if (TryConsumeToken(tok::comma))
626 continue;
627
628 // We expect either a well-known identifier or a generic string. Anything
629 // else is a malformed declspec.
630 bool IsString = Tok.getKind() == tok::string_literal;
631 if (!IsString && Tok.getKind() != tok::identifier &&
632 Tok.getKind() != tok::kw_restrict) {
633 Diag(Tok, diag::err_ms_declspec_type);
Aaron Ballman478faed2012-06-19 22:09:27 +0000634 T.skipToEnd();
635 return;
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000636 }
Aaron Ballman068aa512015-05-20 20:58:33 +0000637
638 IdentifierInfo *AttrName;
639 SourceLocation AttrNameLoc;
640 if (IsString) {
641 SmallString<8> StrBuffer;
642 bool Invalid = false;
643 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
644 if (Invalid) {
645 T.skipToEnd();
646 return;
647 }
648 AttrName = PP.getIdentifierInfo(Str);
649 AttrNameLoc = ConsumeStringToken();
650 } else {
651 AttrName = Tok.getIdentifierInfo();
652 AttrNameLoc = ConsumeToken();
653 }
654
655 bool AttrHandled = false;
656
657 // Parse attribute arguments.
658 if (Tok.is(tok::l_paren))
659 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
660 else if (AttrName->getName() == "property")
661 // The property attribute must have an argument list.
662 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
663 << AttrName->getName();
664
665 if (!AttrHandled)
666 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000667 ParsedAttr::AS_Declspec);
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000668 }
Aaron Ballman068aa512015-05-20 20:58:33 +0000669 T.consumeClose();
670 if (End)
671 *End = T.getCloseLocation();
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000672 }
Eli Friedman53339e02009-06-08 23:27:34 +0000673}
674
John McCall53fa7142010-12-24 02:08:15 +0000675void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
Eli Friedman53339e02009-06-08 23:27:34 +0000676 // Treat these like attributes
Reid Klecknerd7857f02014-10-24 17:42:17 +0000677 while (true) {
678 switch (Tok.getKind()) {
679 case tok::kw___fastcall:
680 case tok::kw___stdcall:
681 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +0000682 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +0000683 case tok::kw___cdecl:
684 case tok::kw___vectorcall:
685 case tok::kw___ptr64:
686 case tok::kw___w64:
687 case tok::kw___ptr32:
Reid Klecknerd7857f02014-10-24 17:42:17 +0000688 case tok::kw___sptr:
689 case tok::kw___uptr: {
690 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
691 SourceLocation AttrNameLoc = ConsumeToken();
692 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000693 ParsedAttr::AS_Keyword);
Reid Klecknerd7857f02014-10-24 17:42:17 +0000694 break;
695 }
696 default:
697 return;
698 }
Eli Friedman53339e02009-06-08 23:27:34 +0000699 }
Steve Naroff3a9b7e02008-12-24 20:59:21 +0000700}
701
Nico Rieckeaaae272014-12-04 23:31:08 +0000702void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
703 SourceLocation StartLoc = Tok.getLocation();
704 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
705
706 if (EndLoc.isValid()) {
707 SourceRange Range(StartLoc, EndLoc);
708 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
709 }
710}
711
712SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
713 SourceLocation EndLoc;
714
715 while (true) {
716 switch (Tok.getKind()) {
717 case tok::kw_const:
718 case tok::kw_volatile:
719 case tok::kw___fastcall:
720 case tok::kw___stdcall:
721 case tok::kw___thiscall:
722 case tok::kw___cdecl:
723 case tok::kw___vectorcall:
724 case tok::kw___ptr32:
725 case tok::kw___ptr64:
726 case tok::kw___w64:
727 case tok::kw___unaligned:
728 case tok::kw___sptr:
729 case tok::kw___uptr:
730 EndLoc = ConsumeToken();
731 break;
732 default:
733 return EndLoc;
734 }
735 }
736}
737
John McCall53fa7142010-12-24 02:08:15 +0000738void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
Dawn Perchik335e16b2010-09-03 01:29:35 +0000739 // Treat these like attributes
740 while (Tok.is(tok::kw___pascal)) {
741 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
742 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000743 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000744 ParsedAttr::AS_Keyword);
Dawn Perchik335e16b2010-09-03 01:29:35 +0000745 }
John McCall53fa7142010-12-24 02:08:15 +0000746}
747
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +0000748void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000749 // Treat these like attributes
750 while (Tok.is(tok::kw___kernel)) {
Richard Smith0cdcc982013-01-29 01:24:26 +0000751 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000752 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000753 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000754 ParsedAttr::AS_Keyword);
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000755 }
756}
757
Aaron Ballman05d76ea2014-01-14 01:29:54 +0000758void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
759 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
760 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +0000761 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000762 ParsedAttr::AS_Keyword);
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000763}
764
Douglas Gregor261a89b2015-06-19 17:51:05 +0000765void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
766 // Treat these like attributes, even though they're type specifiers.
767 while (true) {
768 switch (Tok.getKind()) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +0000769 case tok::kw__Nonnull:
770 case tok::kw__Nullable:
771 case tok::kw__Null_unspecified: {
Douglas Gregor261a89b2015-06-19 17:51:05 +0000772 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
773 SourceLocation AttrNameLoc = ConsumeToken();
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000774 if (!getLangOpts().ObjC)
Douglas Gregor261a89b2015-06-19 17:51:05 +0000775 Diag(AttrNameLoc, diag::ext_nullability)
776 << AttrName;
Fangrui Song6907ce22018-07-30 19:24:48 +0000777 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000778 ParsedAttr::AS_Keyword);
Douglas Gregor261a89b2015-06-19 17:51:05 +0000779 break;
780 }
781 default:
782 return;
783 }
784 }
785}
786
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000787static bool VersionNumberSeparator(const char Separator) {
788 return (Separator == '.' || Separator == '_');
789}
790
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000791/// Parse a version number.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000792///
793/// version:
794/// simple-integer
Jan Korous23255692018-05-17 11:51:49 +0000795/// simple-integer '.' simple-integer
796/// simple-integer '_' simple-integer
797/// simple-integer '.' simple-integer '.' simple-integer
798/// simple-integer '_' simple-integer '_' simple-integer
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000799VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
Erik Pilkington29099de2016-07-16 00:35:23 +0000800 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000801
802 if (!Tok.is(tok::numeric_constant)) {
803 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000804 SkipUntil(tok::comma, tok::r_paren,
805 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000806 return VersionTuple();
807 }
808
809 // Parse the major (and possibly minor and subminor) versions, which
810 // are stored in the numeric constant. We utilize a quirk of the
811 // lexer, which is that it handles something like 1.2.3 as a single
812 // numeric constant, rather than two separate tokens.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000813 SmallString<512> Buffer;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000814 Buffer.resize(Tok.getLength()+1);
815 const char *ThisTokBegin = &Buffer[0];
816
817 // Get the spelling of the token, which eliminates trigraphs, etc.
818 bool Invalid = false;
819 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
820 if (Invalid)
821 return VersionTuple();
822
823 // Parse the major version.
824 unsigned AfterMajor = 0;
825 unsigned Major = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000826 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000827 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
828 ++AfterMajor;
829 }
830
831 if (AfterMajor == 0) {
832 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000833 SkipUntil(tok::comma, tok::r_paren,
834 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000835 return VersionTuple();
836 }
837
838 if (AfterMajor == ActualLength) {
839 ConsumeToken();
840
841 // We only had a single version component.
842 if (Major == 0) {
843 Diag(Tok, diag::err_zero_version);
844 return VersionTuple();
845 }
846
847 return VersionTuple(Major);
848 }
849
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000850 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
851 if (!VersionNumberSeparator(AfterMajorSeparator)
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000852 || (AfterMajor + 1 == ActualLength)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000853 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000854 SkipUntil(tok::comma, tok::r_paren,
855 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000856 return VersionTuple();
857 }
858
859 // Parse the minor version.
860 unsigned AfterMinor = AfterMajor + 1;
861 unsigned Minor = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000862 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000863 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
864 ++AfterMinor;
865 }
866
867 if (AfterMinor == ActualLength) {
868 ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +0000869
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000870 // We had major.minor.
871 if (Major == 0 && Minor == 0) {
872 Diag(Tok, diag::err_zero_version);
873 return VersionTuple();
874 }
875
Jan Korous23255692018-05-17 11:51:49 +0000876 return VersionTuple(Major, Minor);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000877 }
878
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000879 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000880 // If what follows is not a '.' or '_', we have a problem.
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000881 if (!VersionNumberSeparator(AfterMinorSeparator)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000882 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000883 SkipUntil(tok::comma, tok::r_paren,
884 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Chad Rosierc1183952012-06-26 22:30:43 +0000885 return VersionTuple();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000886 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000887
Fariborz Jahanianb6161612014-10-03 17:21:12 +0000888 // Warn if separators, be it '.' or '_', do not match.
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000889 if (AfterMajorSeparator != AfterMinorSeparator)
890 Diag(Tok, diag::warn_expected_consistent_version_separator);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000891
892 // Parse the subminor version.
893 unsigned AfterSubminor = AfterMinor + 1;
894 unsigned Subminor = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000895 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000896 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
897 ++AfterSubminor;
898 }
899
900 if (AfterSubminor != ActualLength) {
901 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000902 SkipUntil(tok::comma, tok::r_paren,
903 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000904 return VersionTuple();
905 }
906 ConsumeToken();
Jan Korous23255692018-05-17 11:51:49 +0000907 return VersionTuple(Major, Minor, Subminor);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000908}
909
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000910/// Parse the contents of the "availability" attribute.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000911///
912/// availability-attribute:
Manman Ren75bc6762016-03-21 17:30:55 +0000913/// 'availability' '(' platform ',' opt-strict version-arg-list,
914/// opt-replacement, opt-message')'
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000915///
916/// platform:
917/// identifier
918///
Manman Rend8039df2016-02-22 04:47:24 +0000919/// opt-strict:
920/// 'strict' ','
Manman Renb636b902016-02-17 22:05:48 +0000921///
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000922/// version-arg-list:
923/// version-arg
924/// version-arg ',' version-arg-list
925///
926/// version-arg:
927/// 'introduced' '=' version
928/// 'deprecated' '=' version
Douglas Gregorfdd417f2012-03-11 04:53:21 +0000929/// 'obsoleted' = version
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000930/// 'unavailable'
Manman Ren75bc6762016-03-21 17:30:55 +0000931/// opt-replacement:
932/// 'replacement' '=' <string>
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000933/// opt-message:
934/// 'message' '=' <string>
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000935void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
936 SourceLocation AvailabilityLoc,
937 ParsedAttributes &attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000938 SourceLocation *endLoc,
939 IdentifierInfo *ScopeName,
940 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000941 ParsedAttr::Syntax Syntax) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000942 enum { Introduced, Deprecated, Obsoleted, Unknown };
943 AvailabilityChange Changes[Unknown];
Manman Ren75bc6762016-03-21 17:30:55 +0000944 ExprResult MessageExpr, ReplacementExpr;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000945
946 // Opening '('.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000947 BalancedDelimiterTracker T(*this, tok::l_paren);
948 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000949 Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000950 return;
951 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000952
Manman Renb636b902016-02-17 22:05:48 +0000953 // Parse the platform name.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000954 if (Tok.isNot(tok::identifier)) {
955 Diag(Tok, diag::err_availability_expected_platform);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000956 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000957 return;
958 }
Richard Smithfeefaf52013-09-03 18:01:40 +0000959 IdentifierLoc *Platform = ParseIdentifierLoc();
Alex Lorenz0b1ce8b2017-08-15 14:42:01 +0000960 if (const IdentifierInfo *const Ident = Platform->Ident) {
961 // Canonicalize platform name from "macosx" to "macos".
962 if (Ident->getName() == "macosx")
963 Platform->Ident = PP.getIdentifierInfo("macos");
964 // Canonicalize platform name from "macosx_app_extension" to
965 // "macos_app_extension".
966 else if (Ident->getName() == "macosx_app_extension")
967 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
968 else
969 Platform->Ident = PP.getIdentifierInfo(
970 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
971 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000972
973 // Parse the ',' following the platform name.
Alp Toker383d2c42014-01-01 03:08:43 +0000974 if (ExpectAndConsume(tok::comma)) {
975 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000976 return;
Alp Toker383d2c42014-01-01 03:08:43 +0000977 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000978
979 // If we haven't grabbed the pointers for the identifiers
980 // "introduced", "deprecated", and "obsoleted", do so now.
981 if (!Ident_introduced) {
982 Ident_introduced = PP.getIdentifierInfo("introduced");
983 Ident_deprecated = PP.getIdentifierInfo("deprecated");
984 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000985 Ident_unavailable = PP.getIdentifierInfo("unavailable");
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000986 Ident_message = PP.getIdentifierInfo("message");
Manman Rend8039df2016-02-22 04:47:24 +0000987 Ident_strict = PP.getIdentifierInfo("strict");
Manman Ren75bc6762016-03-21 17:30:55 +0000988 Ident_replacement = PP.getIdentifierInfo("replacement");
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000989 }
990
Manman Ren75bc6762016-03-21 17:30:55 +0000991 // Parse the optional "strict", the optional "replacement" and the set of
Manman Renb636b902016-02-17 22:05:48 +0000992 // introductions/deprecations/removals.
Manman Rend8039df2016-02-22 04:47:24 +0000993 SourceLocation UnavailableLoc, StrictLoc;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000994 do {
995 if (Tok.isNot(tok::identifier)) {
996 Diag(Tok, diag::err_availability_expected_change);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000997 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000998 return;
999 }
1000 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1001 SourceLocation KeywordLoc = ConsumeToken();
1002
Manman Rend8039df2016-02-22 04:47:24 +00001003 if (Keyword == Ident_strict) {
1004 if (StrictLoc.isValid()) {
Manman Renb636b902016-02-17 22:05:48 +00001005 Diag(KeywordLoc, diag::err_availability_redundant)
Manman Rend8039df2016-02-22 04:47:24 +00001006 << Keyword << SourceRange(StrictLoc);
Manman Renb636b902016-02-17 22:05:48 +00001007 }
Manman Rend8039df2016-02-22 04:47:24 +00001008 StrictLoc = KeywordLoc;
Manman Renb636b902016-02-17 22:05:48 +00001009 continue;
1010 }
1011
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001012 if (Keyword == Ident_unavailable) {
1013 if (UnavailableLoc.isValid()) {
1014 Diag(KeywordLoc, diag::err_availability_redundant)
1015 << Keyword << SourceRange(UnavailableLoc);
Chad Rosierc1183952012-06-26 22:30:43 +00001016 }
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001017 UnavailableLoc = KeywordLoc;
Alp Toker97650562014-01-10 11:19:30 +00001018 continue;
Chad Rosierc1183952012-06-26 22:30:43 +00001019 }
1020
Michael Wu260e9622018-11-12 02:44:33 +00001021 if (Keyword == Ident_deprecated && Platform->Ident &&
1022 Platform->Ident->isStr("swift")) {
1023 // For swift, we deprecate for all versions.
1024 if (Changes[Deprecated].KeywordLoc.isValid()) {
1025 Diag(KeywordLoc, diag::err_availability_redundant)
1026 << Keyword
1027 << SourceRange(Changes[Deprecated].KeywordLoc);
1028 }
1029
1030 Changes[Deprecated].KeywordLoc = KeywordLoc;
1031 // Use a fake version here.
1032 Changes[Deprecated].Version = VersionTuple(1);
1033 continue;
1034 }
1035
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001036 if (Tok.isNot(tok::equal)) {
Alp Tokerec543272013-12-24 09:48:30 +00001037 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001038 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001039 return;
1040 }
1041 ConsumeToken();
Manman Ren75bc6762016-03-21 17:30:55 +00001042 if (Keyword == Ident_message || Keyword == Ident_replacement) {
David Majnemer2e498302014-07-18 05:43:12 +00001043 if (Tok.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001044 Diag(Tok, diag::err_expected_string_literal)
1045 << /*Source='availability attribute'*/2;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001046 SkipUntil(tok::r_paren, StopAtSemi);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001047 return;
1048 }
Manman Ren75bc6762016-03-21 17:30:55 +00001049 if (Keyword == Ident_message)
1050 MessageExpr = ParseStringLiteralExpression();
1051 else
1052 ReplacementExpr = ParseStringLiteralExpression();
David Majnemer2e498302014-07-18 05:43:12 +00001053 // Also reject wide string literals.
1054 if (StringLiteral *MessageStringLiteral =
1055 cast_or_null<StringLiteral>(MessageExpr.get())) {
1056 if (MessageStringLiteral->getCharByteWidth() != 1) {
1057 Diag(MessageStringLiteral->getSourceRange().getBegin(),
1058 diag::err_expected_string_literal)
1059 << /*Source='availability attribute'*/ 2;
1060 SkipUntil(tok::r_paren, StopAtSemi);
1061 return;
1062 }
1063 }
Manman Ren75bc6762016-03-21 17:30:55 +00001064 if (Keyword == Ident_message)
1065 break;
1066 else
1067 continue;
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001068 }
Chad Rosierc1183952012-06-26 22:30:43 +00001069
Fariborz Jahanian5a29e6a2014-11-05 23:58:55 +00001070 // Special handling of 'NA' only when applied to introduced or
1071 // deprecated.
1072 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1073 Tok.is(tok::identifier)) {
1074 IdentifierInfo *NA = Tok.getIdentifierInfo();
1075 if (NA->getName() == "NA") {
1076 ConsumeToken();
1077 if (Keyword == Ident_introduced)
1078 UnavailableLoc = KeywordLoc;
1079 continue;
1080 }
1081 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001082
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001083 SourceRange VersionRange;
1084 VersionTuple Version = ParseVersionTuple(VersionRange);
Chad Rosierc1183952012-06-26 22:30:43 +00001085
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001086 if (Version.empty()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001087 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001088 return;
1089 }
1090
1091 unsigned Index;
1092 if (Keyword == Ident_introduced)
1093 Index = Introduced;
1094 else if (Keyword == Ident_deprecated)
1095 Index = Deprecated;
1096 else if (Keyword == Ident_obsoleted)
1097 Index = Obsoleted;
Chad Rosierc1183952012-06-26 22:30:43 +00001098 else
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001099 Index = Unknown;
1100
1101 if (Index < Unknown) {
1102 if (!Changes[Index].KeywordLoc.isInvalid()) {
1103 Diag(KeywordLoc, diag::err_availability_redundant)
Chad Rosierc1183952012-06-26 22:30:43 +00001104 << Keyword
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001105 << SourceRange(Changes[Index].KeywordLoc,
1106 Changes[Index].VersionRange.getEnd());
1107 }
1108
1109 Changes[Index].KeywordLoc = KeywordLoc;
1110 Changes[Index].Version = Version;
1111 Changes[Index].VersionRange = VersionRange;
1112 } else {
1113 Diag(KeywordLoc, diag::err_availability_unknown_change)
1114 << Keyword << VersionRange;
1115 }
1116
Alp Toker97650562014-01-10 11:19:30 +00001117 } while (TryConsumeToken(tok::comma));
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001118
1119 // Closing ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001120 if (T.consumeClose())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001121 return;
1122
1123 if (endLoc)
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001124 *endLoc = T.getCloseLocation();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001125
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001126 // The 'unavailable' availability cannot be combined with any other
1127 // availability changes. Make sure that hasn't happened.
1128 if (UnavailableLoc.isValid()) {
1129 bool Complained = false;
1130 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1131 if (Changes[Index].KeywordLoc.isValid()) {
1132 if (!Complained) {
1133 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1134 << SourceRange(Changes[Index].KeywordLoc,
1135 Changes[Index].VersionRange.getEnd());
1136 Complained = true;
1137 }
1138
1139 // Clear out the availability.
1140 Changes[Index] = AvailabilityChange();
1141 }
1142 }
1143 }
1144
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001145 // Record this attribute
Chad Rosierc1183952012-06-26 22:30:43 +00001146 attrs.addNew(&Availability,
1147 SourceRange(AvailabilityLoc, T.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001148 ScopeName, ScopeLoc,
Aaron Ballman00e99962013-08-31 01:11:41 +00001149 Platform,
John McCall084e83d2011-03-24 11:26:52 +00001150 Changes[Introduced],
1151 Changes[Deprecated],
Chad Rosierc1183952012-06-26 22:30:43 +00001152 Changes[Obsoleted],
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001153 UnavailableLoc, MessageExpr.get(),
Manman Ren75bc6762016-03-21 17:30:55 +00001154 Syntax, StrictLoc, ReplacementExpr.get());
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001155}
1156
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001157/// Parse the contents of the "external_source_symbol" attribute.
Alex Lorenzd5d27e12017-03-01 18:06:25 +00001158///
1159/// external-source-symbol-attribute:
1160/// 'external_source_symbol' '(' keyword-arg-list ')'
1161///
1162/// keyword-arg-list:
1163/// keyword-arg
1164/// keyword-arg ',' keyword-arg-list
1165///
1166/// keyword-arg:
1167/// 'language' '=' <string>
1168/// 'defined_in' '=' <string>
1169/// 'generated_declaration'
1170void Parser::ParseExternalSourceSymbolAttribute(
1171 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1172 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +00001173 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00001174 // Opening '('.
1175 BalancedDelimiterTracker T(*this, tok::l_paren);
1176 if (T.expectAndConsume())
1177 return;
1178
1179 // Initialize the pointers for the keyword identifiers when required.
1180 if (!Ident_language) {
1181 Ident_language = PP.getIdentifierInfo("language");
1182 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1183 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1184 }
1185
1186 ExprResult Language;
1187 bool HasLanguage = false;
1188 ExprResult DefinedInExpr;
1189 bool HasDefinedIn = false;
1190 IdentifierLoc *GeneratedDeclaration = nullptr;
1191
1192 // Parse the language/defined_in/generated_declaration keywords
1193 do {
1194 if (Tok.isNot(tok::identifier)) {
1195 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1196 SkipUntil(tok::r_paren, StopAtSemi);
1197 return;
1198 }
1199
1200 SourceLocation KeywordLoc = Tok.getLocation();
1201 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1202 if (Keyword == Ident_generated_declaration) {
1203 if (GeneratedDeclaration) {
1204 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1205 SkipUntil(tok::r_paren, StopAtSemi);
1206 return;
1207 }
1208 GeneratedDeclaration = ParseIdentifierLoc();
1209 continue;
1210 }
1211
1212 if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1213 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1214 SkipUntil(tok::r_paren, StopAtSemi);
1215 return;
1216 }
1217
1218 ConsumeToken();
1219 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1220 Keyword->getName())) {
1221 SkipUntil(tok::r_paren, StopAtSemi);
1222 return;
1223 }
1224
1225 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1226 if (Keyword == Ident_language)
1227 HasLanguage = true;
1228 else
1229 HasDefinedIn = true;
1230
1231 if (Tok.isNot(tok::string_literal)) {
1232 Diag(Tok, diag::err_expected_string_literal)
1233 << /*Source='external_source_symbol attribute'*/ 3
1234 << /*language | source container*/ (Keyword != Ident_language);
1235 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1236 continue;
1237 }
1238 if (Keyword == Ident_language) {
1239 if (HadLanguage) {
1240 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1241 << Keyword;
1242 ParseStringLiteralExpression();
1243 continue;
1244 }
1245 Language = ParseStringLiteralExpression();
1246 } else {
1247 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1248 if (HadDefinedIn) {
1249 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1250 << Keyword;
1251 ParseStringLiteralExpression();
1252 continue;
1253 }
1254 DefinedInExpr = ParseStringLiteralExpression();
1255 }
1256 } while (TryConsumeToken(tok::comma));
1257
1258 // Closing ')'.
1259 if (T.consumeClose())
1260 return;
1261 if (EndLoc)
1262 *EndLoc = T.getCloseLocation();
1263
1264 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1265 GeneratedDeclaration};
1266 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1267 ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1268}
1269
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001270/// Parse the contents of the "objc_bridge_related" attribute.
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001271/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1272/// related_class:
1273/// Identifier
1274///
1275/// opt-class_method:
1276/// Identifier: | <empty>
1277///
1278/// opt-instance_method:
1279/// Identifier | <empty>
1280///
1281void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1282 SourceLocation ObjCBridgeRelatedLoc,
1283 ParsedAttributes &attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001284 SourceLocation *endLoc,
1285 IdentifierInfo *ScopeName,
1286 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001287 ParsedAttr::Syntax Syntax) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001288 // Opening '('.
1289 BalancedDelimiterTracker T(*this, tok::l_paren);
1290 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00001291 Diag(Tok, diag::err_expected) << tok::l_paren;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001292 return;
1293 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001294
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001295 // Parse the related class name.
1296 if (Tok.isNot(tok::identifier)) {
1297 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1298 SkipUntil(tok::r_paren, StopAtSemi);
1299 return;
1300 }
1301 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
Alp Toker97650562014-01-10 11:19:30 +00001302 if (ExpectAndConsume(tok::comma)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001303 SkipUntil(tok::r_paren, StopAtSemi);
1304 return;
1305 }
Alp Toker8fbec672013-12-17 23:29:36 +00001306
Aaron Ballman48a533d2018-02-27 23:49:28 +00001307 // Parse class method name. It's non-optional in the sense that a trailing
1308 // comma is required, but it can be the empty string, and then we record a
1309 // nullptr.
Craig Topper161e4db2014-05-21 06:02:52 +00001310 IdentifierLoc *ClassMethod = nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001311 if (Tok.is(tok::identifier)) {
1312 ClassMethod = ParseIdentifierLoc();
Alp Toker8fbec672013-12-17 23:29:36 +00001313 if (!TryConsumeToken(tok::colon)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001314 Diag(Tok, diag::err_objcbridge_related_selector_name);
1315 SkipUntil(tok::r_paren, StopAtSemi);
1316 return;
1317 }
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001318 }
Alp Toker8fbec672013-12-17 23:29:36 +00001319 if (!TryConsumeToken(tok::comma)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001320 if (Tok.is(tok::colon))
1321 Diag(Tok, diag::err_objcbridge_related_selector_name);
1322 else
Alp Tokerec543272013-12-24 09:48:30 +00001323 Diag(Tok, diag::err_expected) << tok::comma;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001324 SkipUntil(tok::r_paren, StopAtSemi);
1325 return;
1326 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001327
Aaron Ballman48a533d2018-02-27 23:49:28 +00001328 // Parse instance method name. Also non-optional but empty string is
1329 // permitted.
Craig Topper161e4db2014-05-21 06:02:52 +00001330 IdentifierLoc *InstanceMethod = nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001331 if (Tok.is(tok::identifier))
1332 InstanceMethod = ParseIdentifierLoc();
1333 else if (Tok.isNot(tok::r_paren)) {
Alp Tokerec543272013-12-24 09:48:30 +00001334 Diag(Tok, diag::err_expected) << tok::r_paren;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001335 SkipUntil(tok::r_paren, StopAtSemi);
1336 return;
1337 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001338
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001339 // Closing ')'.
1340 if (T.consumeClose())
1341 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001342
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001343 if (endLoc)
1344 *endLoc = T.getCloseLocation();
Fangrui Song6907ce22018-07-30 19:24:48 +00001345
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001346 // Record this attribute
1347 attrs.addNew(&ObjCBridgeRelated,
1348 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001349 ScopeName, ScopeLoc,
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001350 RelatedClass,
1351 ClassMethod,
1352 InstanceMethod,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001353 Syntax);
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001354}
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001355
Bill Wendling44426052012-12-20 19:22:21 +00001356// Late Parsed Attributes:
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001357// See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1358
1359void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1360
1361void Parser::LateParsedClass::ParseLexedAttributes() {
1362 Self->ParseLexedAttributes(*Class);
1363}
1364
1365void Parser::LateParsedAttribute::ParseLexedAttributes() {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001366 Self->ParseLexedAttribute(*this, true, false);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001367}
1368
1369/// Wrapper class which calls ParseLexedAttribute, after setting up the
1370/// scope appropriately.
1371void Parser::ParseLexedAttributes(ParsingClass &Class) {
1372 // Deal with templates
1373 // FIXME: Test cases to make sure this does the right thing for templates.
1374 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1375 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1376 HasTemplateScope);
1377 if (HasTemplateScope)
1378 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1379
Douglas Gregor3024f072012-04-16 07:05:22 +00001380 // Set or update the scope flags.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001381 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +00001382 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001383 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1384 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1385
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001386 // Enter the scope of nested classes
1387 if (!AlreadyHasClassScope)
1388 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1389 Class.TagOrTemplate);
Benjamin Kramer1d373c62012-05-17 12:01:52 +00001390 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001391 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1392 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1393 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001394 }
Chad Rosierc1183952012-06-26 22:30:43 +00001395
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001396 if (!AlreadyHasClassScope)
1397 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1398 Class.TagOrTemplate);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001399}
1400
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001401/// Parse all attributes in LAs, and attach them to Decl D.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001402void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1403 bool EnterScope, bool OnDefinition) {
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001404 assert(LAs.parseSoon() &&
1405 "Attribute list should be marked for immediate parsing.");
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001406 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
DeLesley Hutchins19c722d2012-08-15 22:41:04 +00001407 if (D)
1408 LAs[i]->addDecl(D);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001409 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
Benjamin Kramerbafc49a2012-04-14 12:44:47 +00001410 delete LAs[i];
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001411 }
1412 LAs.clear();
1413}
1414
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001415/// Finish parsing an attribute for which parsing was delayed.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001416/// This will be called at the end of parsing a class declaration
1417/// for each LateParsedAttribute. We consume the saved tokens and
Chad Rosierc1183952012-06-26 22:30:43 +00001418/// create an attribute with the arguments filled in. We add this
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001419/// to the Attribute list for the decl.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001420void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1421 bool EnterScope, bool OnDefinition) {
David Majnemerd5946f52015-01-13 08:35:24 +00001422 // Create a fake EOF so that attribute parsing won't go off the end of the
1423 // attribute.
1424 Token AttrEnd;
1425 AttrEnd.startToken();
1426 AttrEnd.setKind(tok::eof);
1427 AttrEnd.setLocation(Tok.getLocation());
1428 AttrEnd.setEofData(LA.Toks.data());
1429 LA.Toks.push_back(AttrEnd);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001430
1431 // Append the current token at the end of the new token stream so that it
1432 // doesn't get lost.
1433 LA.Toks.push_back(Tok);
David Blaikie2eabcc92016-02-09 18:52:09 +00001434 PP.EnterTokenStream(LA.Toks, true);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001435 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +00001436 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001437
1438 ParsedAttributes Attrs(AttrFactory);
1439 SourceLocation endLoc;
1440
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001441 if (LA.Decls.size() > 0) {
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001442 Decl *D = LA.Decls[0];
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001443 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1444 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001445
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001446 // Allow 'this' within late-parsed attributes.
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001447 Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
Richard Smithc3d2ebb2013-06-07 02:33:37 +00001448 ND && ND->isCXXInstanceMember());
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001449
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001450 if (LA.Decls.size() == 1) {
1451 // If the Decl is templatized, add template parameters to scope.
1452 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1453 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1454 if (HasTemplateScope)
1455 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001456
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001457 // If the Decl is on a function, add function parameters to the scope.
1458 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
Momchil Velikov57c681f2017-08-10 15:43:06 +00001459 ParseScope FnScope(
1460 this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
1461 HasFunScope);
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001462 if (HasFunScope)
1463 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001464
Michael Han23214e52012-10-03 01:56:22 +00001465 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001466 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
Craig Topper161e4db2014-05-21 06:02:52 +00001467 nullptr);
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001468
1469 if (HasFunScope) {
1470 Actions.ActOnExitFunctionContext();
1471 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1472 }
1473 if (HasTemplateScope) {
1474 TempScope.Exit();
1475 }
1476 } else {
1477 // If there are multiple decls, then the decl cannot be within the
1478 // function scope.
Michael Han23214e52012-10-03 01:56:22 +00001479 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001480 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
Craig Topper161e4db2014-05-21 06:02:52 +00001481 nullptr);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001482 }
DeLesley Hutchins71d61032012-03-02 22:29:50 +00001483 } else {
1484 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001485 }
1486
Erich Keanec480f302018-07-12 21:09:05 +00001487 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
1488 Attrs.begin()->isKnownToGCC())
Aaron Ballman9a99e0d2014-01-20 17:18:35 +00001489 Diag(Tok, diag::warn_attribute_on_function_definition)
1490 << &LA.AttrName;
1491
1492 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001493 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001494
David Majnemerd5946f52015-01-13 08:35:24 +00001495 // Due to a parsing error, we either went over the cached tokens or
1496 // there are still cached tokens left, so we skip the leftover tokens.
1497 while (Tok.isNot(tok::eof))
1498 ConsumeAnyToken();
1499
1500 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1501 ConsumeAnyToken();
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001502}
1503
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001504void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1505 SourceLocation AttrNameLoc,
1506 ParsedAttributes &Attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001507 SourceLocation *EndLoc,
1508 IdentifierInfo *ScopeName,
1509 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001510 ParsedAttr::Syntax Syntax) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001511 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1512
1513 BalancedDelimiterTracker T(*this, tok::l_paren);
1514 T.consumeOpen();
1515
1516 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001517 Diag(Tok, diag::err_expected) << tok::identifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001518 T.skipToEnd();
1519 return;
1520 }
Richard Smithfeefaf52013-09-03 18:01:40 +00001521 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001522
Alp Toker094e5212014-01-05 03:27:11 +00001523 if (ExpectAndConsume(tok::comma)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001524 T.skipToEnd();
1525 return;
1526 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001527
1528 SourceRange MatchingCTypeRange;
1529 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1530 if (MatchingCType.isInvalid()) {
1531 T.skipToEnd();
1532 return;
1533 }
1534
1535 bool LayoutCompatible = false;
1536 bool MustBeNull = false;
Alp Toker8fbec672013-12-17 23:29:36 +00001537 while (TryConsumeToken(tok::comma)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001538 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001539 Diag(Tok, diag::err_expected) << tok::identifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001540 T.skipToEnd();
1541 return;
1542 }
1543 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1544 if (Flag->isStr("layout_compatible"))
1545 LayoutCompatible = true;
1546 else if (Flag->isStr("must_be_null"))
1547 MustBeNull = true;
1548 else {
1549 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1550 T.skipToEnd();
1551 return;
1552 }
1553 ConsumeToken(); // consume flag
1554 }
1555
1556 if (!T.consumeClose()) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001557 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001558 ArgumentKind, MatchingCType.get(),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001559 LayoutCompatible, MustBeNull, Syntax);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001560 }
1561
1562 if (EndLoc)
1563 *EndLoc = T.getCloseLocation();
1564}
1565
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001566/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1567/// of a C++11 attribute-specifier in a location where an attribute is not
1568/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1569/// situation.
1570///
1571/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1572/// this doesn't appear to actually be an attribute-specifier, and the caller
1573/// should try to parse it.
1574bool Parser::DiagnoseProhibitedCXX11Attribute() {
1575 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1576
1577 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1578 case CAK_NotAttributeSpecifier:
1579 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1580 return false;
1581
1582 case CAK_InvalidAttributeSpecifier:
1583 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1584 return false;
1585
1586 case CAK_AttributeSpecifier:
1587 // Parse and discard the attributes.
1588 SourceLocation BeginLoc = ConsumeBracket();
1589 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001590 SkipUntil(tok::r_square);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001591 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1592 SourceLocation EndLoc = ConsumeBracket();
1593 Diag(BeginLoc, diag::err_attributes_not_allowed)
1594 << SourceRange(BeginLoc, EndLoc);
1595 return true;
1596 }
Chandler Carruthd8f7d382012-04-10 16:03:08 +00001597 llvm_unreachable("All cases handled above.");
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001598}
1599
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001600/// We have found the opening square brackets of a C++11
Richard Smith98155ad2013-02-20 01:17:14 +00001601/// attribute-specifier in a location where an attribute is not permitted, but
1602/// we know where the attributes ought to be written. Parse them anyway, and
1603/// provide a fixit moving them to the right place.
Richard Smith4c96e992013-02-19 23:47:15 +00001604void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1605 SourceLocation CorrectLocation) {
1606 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1607 Tok.is(tok::kw_alignas));
1608
1609 // Consume the attributes.
1610 SourceLocation Loc = Tok.getLocation();
1611 ParseCXX11Attributes(Attrs);
1612 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
Faisal Valic5089c02017-12-25 22:23:20 +00001613 // FIXME: use err_attributes_misplaced
Richard Smith4c96e992013-02-19 23:47:15 +00001614 Diag(Loc, diag::err_attributes_not_allowed)
1615 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1616 << FixItHint::CreateRemoval(AttrRange);
1617}
1618
Erich Keanec480f302018-07-12 21:09:05 +00001619void Parser::DiagnoseProhibitedAttributes(
1620 const SourceRange &Range, const SourceLocation CorrectLocation) {
Faisal Valic5089c02017-12-25 22:23:20 +00001621 if (CorrectLocation.isValid()) {
Erich Keanec480f302018-07-12 21:09:05 +00001622 CharSourceRange AttrRange(Range, true);
Faisal Valic5089c02017-12-25 22:23:20 +00001623 Diag(CorrectLocation, diag::err_attributes_misplaced)
1624 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1625 << FixItHint::CreateRemoval(AttrRange);
1626 } else
Erich Keanec480f302018-07-12 21:09:05 +00001627 Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
Dawn Perchik335e16b2010-09-03 01:29:35 +00001628}
1629
Richard Smith49cc1cc2016-08-18 21:59:42 +00001630void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1631 unsigned DiagID) {
Erich Keanee891aa92018-07-13 15:07:47 +00001632 for (const ParsedAttr &AL : Attrs) {
Erich Keanec480f302018-07-12 21:09:05 +00001633 if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
Richard Smith49cc1cc2016-08-18 21:59:42 +00001634 continue;
Erich Keanee891aa92018-07-13 15:07:47 +00001635 if (AL.getKind() == ParsedAttr::UnknownAttribute)
Erich Keanec480f302018-07-12 21:09:05 +00001636 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL.getName();
Richard Smith49cc1cc2016-08-18 21:59:42 +00001637 else {
Erich Keanec480f302018-07-12 21:09:05 +00001638 Diag(AL.getLoc(), DiagID) << AL.getName();
1639 AL.setInvalid();
Michael Han64536a62012-11-06 19:34:54 +00001640 }
Michael Han64536a62012-11-06 19:34:54 +00001641 }
1642}
1643
Nico Weber32a0fc72016-09-03 03:01:32 +00001644// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1645// applies to var, not the type Foo.
David Majnemer936b4112015-04-19 07:53:29 +00001646// As an exception to the rule, __declspec(align(...)) before the
1647// class-key affects the type instead of the variable.
Nico Weber32a0fc72016-09-03 03:01:32 +00001648// Also, Microsoft-style [attributes] seem to affect the type instead of the
1649// variable.
1650// This function moves attributes that should apply to the type off DS to Attrs.
1651void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1652 DeclSpec &DS,
1653 Sema::TagUseKind TUK) {
David Majnemer936b4112015-04-19 07:53:29 +00001654 if (TUK == Sema::TUK_Reference)
1655 return;
1656
Erich Keanee891aa92018-07-13 15:07:47 +00001657 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
David Majnemer936b4112015-04-19 07:53:29 +00001658
Erich Keanee891aa92018-07-13 15:07:47 +00001659 for (ParsedAttr &AL : DS.getAttributes()) {
1660 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
Erich Keanec480f302018-07-12 21:09:05 +00001661 AL.isDeclspecAttribute()) ||
1662 AL.isMicrosoftAttribute())
1663 ToBeMoved.push_back(&AL);
David Majnemer936b4112015-04-19 07:53:29 +00001664 }
Nico Weber88f5ed92016-09-13 18:55:26 +00001665
Erich Keanee891aa92018-07-13 15:07:47 +00001666 for (ParsedAttr *AL : ToBeMoved) {
Erich Keanec480f302018-07-12 21:09:05 +00001667 DS.getAttributes().remove(AL);
1668 Attrs.addAtEnd(AL);
1669 }
David Majnemer936b4112015-04-19 07:53:29 +00001670}
1671
Chris Lattner53361ac2006-08-10 05:19:57 +00001672/// ParseDeclaration - Parse a full 'declaration', which consists of
1673/// declaration-specifiers, some number of declarators, and a semicolon.
Faisal Vali421b2d12017-12-29 05:41:00 +00001674/// 'Context' should be a DeclaratorContext value. This returns the
Chris Lattner49836b42009-04-02 04:16:50 +00001675/// location of the semicolon in DeclEnd.
Chris Lattnera5235172007-08-25 06:57:03 +00001676///
1677/// declaration: [C99 6.7]
1678/// block-declaration ->
1679/// simple-declaration
1680/// others [FIXME]
Douglas Gregoreb31f392008-12-01 23:54:00 +00001681/// [C++] template-declaration
Chris Lattnera5235172007-08-25 06:57:03 +00001682/// [C++] namespace-definition
Douglas Gregord7c4d982008-12-30 03:27:21 +00001683/// [C++] using-directive
Douglas Gregor77b50e12009-06-22 23:06:13 +00001684/// [C++] using-declaration
Richard Smithc202b282012-04-14 00:33:13 +00001685/// [C++11/C11] static_assert-declaration
Chris Lattnera5235172007-08-25 06:57:03 +00001686/// others... [FIXME]
1687///
Faisal Vali421b2d12017-12-29 05:41:00 +00001688Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
Alexis Hunt96d5c762009-11-21 08:43:09 +00001689 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +00001690 ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +00001691 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Fariborz Jahanian59b75282011-08-30 17:10:52 +00001692 // Must temporarily exit the objective-c container scope for
1693 // parsing c none objective-c decls.
1694 ObjCDeclContextSwitch ObjCDC(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00001695
Craig Topper161e4db2014-05-21 06:02:52 +00001696 Decl *SingleDecl = nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +00001697 switch (Tok.getKind()) {
Douglas Gregoreb31f392008-12-01 23:54:00 +00001698 case tok::kw_template:
Douglas Gregor23996282009-05-12 21:31:51 +00001699 case tok::kw_export:
John McCall53fa7142010-12-24 02:08:15 +00001700 ProhibitAttributes(attrs);
Erich Keanec480f302018-07-12 21:09:05 +00001701 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001702 break;
Sebastian Redl67667942010-08-27 23:12:46 +00001703 case tok::kw_inline:
Sebastian Redl5a5f2c72010-08-31 00:36:45 +00001704 // Could be the start of an inline namespace. Allowed as an ext in C++03.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001705 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
John McCall53fa7142010-12-24 02:08:15 +00001706 ProhibitAttributes(attrs);
Sebastian Redl67667942010-08-27 23:12:46 +00001707 SourceLocation InlineLoc = ConsumeToken();
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00001708 return ParseNamespace(Context, DeclEnd, InlineLoc);
Sebastian Redl67667942010-08-27 23:12:46 +00001709 }
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001710 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
Fariborz Jahanian1db5c942010-09-28 20:42:35 +00001711 true);
Chris Lattnera5235172007-08-25 06:57:03 +00001712 case tok::kw_namespace:
John McCall53fa7142010-12-24 02:08:15 +00001713 ProhibitAttributes(attrs);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00001714 return ParseNamespace(Context, DeclEnd);
Douglas Gregord7c4d982008-12-30 03:27:21 +00001715 case tok::kw_using:
Richard Smith6f1daa42016-12-16 00:58:48 +00001716 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1717 DeclEnd, attrs);
Anders Carlssonf24fcff62009-03-11 16:27:10 +00001718 case tok::kw_static_assert:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00001719 case tok::kw__Static_assert:
John McCall53fa7142010-12-24 02:08:15 +00001720 ProhibitAttributes(attrs);
Chris Lattner49836b42009-04-02 04:16:50 +00001721 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001722 break;
Chris Lattnera5235172007-08-25 06:57:03 +00001723 default:
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001724 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
Chris Lattnera5235172007-08-25 06:57:03 +00001725 }
Chad Rosierc1183952012-06-26 22:30:43 +00001726
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001727 // This routine returns a DeclGroup, if the thing we parsed only contains a
Richard Smith6f1daa42016-12-16 00:58:48 +00001728 // single decl, convert it now.
1729 return Actions.ConvertDeclToDeclGroup(SingleDecl);
Chris Lattnera5235172007-08-25 06:57:03 +00001730}
1731
1732/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1733/// declaration-specifiers init-declarator-list[opt] ';'
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001734/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1735/// init-declarator-list ';'
Chris Lattnera5235172007-08-25 06:57:03 +00001736///[C90/C++]init-declarator-list ';' [TODO]
1737/// [OMP] threadprivate-directive [TODO]
Chris Lattner32dc41c2009-03-29 17:27:48 +00001738///
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001739/// for-range-declaration: [C++11 6.5p1: stmt.ranged]
Richard Smith02e85f32011-04-14 22:09:26 +00001740/// attribute-specifier-seq[opt] type-specifier-seq declarator
1741///
Chris Lattner32dc41c2009-03-29 17:27:48 +00001742/// If RequireSemi is false, this does not check for a ';' at the end of the
Chris Lattner005fc1b2010-04-05 18:18:31 +00001743/// declaration. If it is true, it checks for and eats it.
Richard Smith02e85f32011-04-14 22:09:26 +00001744///
1745/// If FRI is non-null, we might be parsing a for-range-declaration instead
1746/// of a simple-declaration. If we find that we are, we also parse the
1747/// for-range-initializer, and place it here.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001748Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +00001749Parser::ParseSimpleDeclaration(DeclaratorContext Context,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001750 SourceLocation &DeclEnd,
Richard Smith2386c8b2013-02-22 09:06:26 +00001751 ParsedAttributesWithRange &Attrs,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001752 bool RequireSemi, ForRangeInit *FRI) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001753 // Parse the common declaration-specifiers piece.
John McCall28a6aea2009-11-04 02:18:39 +00001754 ParsingDeclSpec DS(*this);
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001755
Richard Smith404dfb42013-11-19 22:47:36 +00001756 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
Faisal Valia534f072018-04-26 00:42:40 +00001757 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
Richard Smith404dfb42013-11-19 22:47:36 +00001758
1759 // If we had a free-standing type definition with a missing semicolon, we
1760 // may get this far before the problem becomes obvious.
1761 if (DS.hasTagDefinition() &&
1762 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
David Blaikie0403cb12016-01-15 23:43:25 +00001763 return nullptr;
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001764
Chris Lattner0e894622006-08-13 19:58:17 +00001765 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1766 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner76c72282007-10-09 17:33:22 +00001767 if (Tok.is(tok::semi)) {
Richard Smith2386c8b2013-02-22 09:06:26 +00001768 ProhibitAttributes(Attrs);
Argyrios Kyrtzidisfbb2bb52012-05-16 23:49:15 +00001769 DeclEnd = Tok.getLocation();
Chris Lattner005fc1b2010-04-05 18:18:31 +00001770 if (RequireSemi) ConsumeToken();
Nico Weber7b837f52016-01-28 19:25:00 +00001771 RecordDecl *AnonRecord = nullptr;
John McCall48871652010-08-21 09:40:31 +00001772 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00001773 DS, AnonRecord);
John McCall28a6aea2009-11-04 02:18:39 +00001774 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00001775 if (AnonRecord) {
1776 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00001777 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00001778 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001779 return Actions.ConvertDeclToDeclGroup(TheDecl);
Chris Lattner0e894622006-08-13 19:58:17 +00001780 }
Chad Rosierc1183952012-06-26 22:30:43 +00001781
Richard Smith2386c8b2013-02-22 09:06:26 +00001782 DS.takeAttributesFrom(Attrs);
Reid Klecknerd61a3112014-12-15 23:16:32 +00001783 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
John McCalld5a36322009-11-03 19:26:08 +00001784}
Mike Stump11289f42009-09-09 15:08:12 +00001785
Richard Smith09f76ee2011-10-19 21:33:05 +00001786/// Returns true if this might be the start of a declarator, or a common typo
1787/// for a declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001788bool Parser::MightBeDeclarator(DeclaratorContext Context) {
Richard Smith09f76ee2011-10-19 21:33:05 +00001789 switch (Tok.getKind()) {
1790 case tok::annot_cxxscope:
1791 case tok::annot_template_id:
1792 case tok::caret:
1793 case tok::code_completion:
1794 case tok::coloncolon:
1795 case tok::ellipsis:
1796 case tok::kw___attribute:
1797 case tok::kw_operator:
1798 case tok::l_paren:
1799 case tok::star:
1800 return true;
1801
1802 case tok::amp:
1803 case tok::ampamp:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001804 return getLangOpts().CPlusPlus;
Richard Smith09f76ee2011-10-19 21:33:05 +00001805
Richard Smithc8a79032012-01-09 22:31:44 +00001806 case tok::l_square: // Might be an attribute on an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001807 return Context == DeclaratorContext::MemberContext &&
1808 getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
Richard Smithc8a79032012-01-09 22:31:44 +00001809
1810 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001811 return Context == DeclaratorContext::MemberContext ||
1812 getLangOpts().CPlusPlus;
Richard Smithc8a79032012-01-09 22:31:44 +00001813
Richard Smith09f76ee2011-10-19 21:33:05 +00001814 case tok::identifier:
1815 switch (NextToken().getKind()) {
1816 case tok::code_completion:
1817 case tok::coloncolon:
1818 case tok::comma:
1819 case tok::equal:
1820 case tok::equalequal: // Might be a typo for '='.
1821 case tok::kw_alignas:
1822 case tok::kw_asm:
1823 case tok::kw___attribute:
1824 case tok::l_brace:
1825 case tok::l_paren:
1826 case tok::l_square:
1827 case tok::less:
1828 case tok::r_brace:
1829 case tok::r_paren:
1830 case tok::r_square:
1831 case tok::semi:
1832 return true;
1833
1834 case tok::colon:
1835 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
Richard Smithc8a79032012-01-09 22:31:44 +00001836 // and in block scope it's probably a label. Inside a class definition,
1837 // this is a bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001838 return Context == DeclaratorContext::MemberContext ||
1839 (getLangOpts().CPlusPlus &&
1840 Context == DeclaratorContext::FileContext);
Richard Smithc8a79032012-01-09 22:31:44 +00001841
1842 case tok::identifier: // Possible virt-specifier.
Richard Smith89645bc2013-01-02 12:01:23 +00001843 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
Richard Smith09f76ee2011-10-19 21:33:05 +00001844
1845 default:
1846 return false;
1847 }
1848
1849 default:
1850 return false;
1851 }
1852}
1853
Richard Smithb8caac82012-04-11 20:59:20 +00001854/// Skip until we reach something which seems like a sensible place to pick
1855/// up parsing after a malformed declaration. This will sometimes stop sooner
1856/// than SkipUntil(tok::r_brace) would, but will never stop later.
1857void Parser::SkipMalformedDecl() {
1858 while (true) {
1859 switch (Tok.getKind()) {
1860 case tok::l_brace:
1861 // Skip until matching }, then stop. We've probably skipped over
1862 // a malformed class or function definition or similar.
1863 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001864 SkipUntil(tok::r_brace);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001865 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
Richard Smithb8caac82012-04-11 20:59:20 +00001866 // This declaration isn't over yet. Keep skipping.
1867 continue;
1868 }
Alp Toker8fbec672013-12-17 23:29:36 +00001869 TryConsumeToken(tok::semi);
Richard Smithb8caac82012-04-11 20:59:20 +00001870 return;
1871
1872 case tok::l_square:
1873 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001874 SkipUntil(tok::r_square);
Richard Smithb8caac82012-04-11 20:59:20 +00001875 continue;
1876
1877 case tok::l_paren:
1878 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001879 SkipUntil(tok::r_paren);
Richard Smithb8caac82012-04-11 20:59:20 +00001880 continue;
1881
1882 case tok::r_brace:
1883 return;
1884
1885 case tok::semi:
1886 ConsumeToken();
1887 return;
1888
1889 case tok::kw_inline:
1890 // 'inline namespace' at the start of a line is almost certainly
Jordan Rose12e730c2012-07-09 16:54:53 +00001891 // a good place to pick back up parsing, except in an Objective-C
1892 // @interface context.
1893 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1894 (!ParsingInObjCContainer || CurParsedObjCImpl))
Richard Smithb8caac82012-04-11 20:59:20 +00001895 return;
1896 break;
1897
1898 case tok::kw_namespace:
1899 // 'namespace' at the start of a line is almost certainly a good
Jordan Rose12e730c2012-07-09 16:54:53 +00001900 // place to pick back up parsing, except in an Objective-C
1901 // @interface context.
1902 if (Tok.isAtStartOfLine() &&
1903 (!ParsingInObjCContainer || CurParsedObjCImpl))
1904 return;
1905 break;
1906
1907 case tok::at:
1908 // @end is very much like } in Objective-C contexts.
1909 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1910 ParsingInObjCContainer)
1911 return;
1912 break;
1913
1914 case tok::minus:
1915 case tok::plus:
1916 // - and + probably start new method declarations in Objective-C contexts.
1917 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
Richard Smithb8caac82012-04-11 20:59:20 +00001918 return;
1919 break;
1920
1921 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001922 case tok::annot_module_begin:
1923 case tok::annot_module_end:
1924 case tok::annot_module_include:
Richard Smithb8caac82012-04-11 20:59:20 +00001925 return;
1926
1927 default:
1928 break;
1929 }
1930
1931 ConsumeAnyToken();
1932 }
1933}
1934
John McCalld5a36322009-11-03 19:26:08 +00001935/// ParseDeclGroup - Having concluded that this is either a function
1936/// definition or a group of object declarations, actually parse the
1937/// result.
John McCall28a6aea2009-11-04 02:18:39 +00001938Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
Faisal Vali421b2d12017-12-29 05:41:00 +00001939 DeclaratorContext Context,
Richard Smith02e85f32011-04-14 22:09:26 +00001940 SourceLocation *DeclEnd,
1941 ForRangeInit *FRI) {
John McCalld5a36322009-11-03 19:26:08 +00001942 // Parse the first declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001943 ParsingDeclarator D(*this, DS, Context);
John McCalld5a36322009-11-03 19:26:08 +00001944 ParseDeclarator(D);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001945
John McCalld5a36322009-11-03 19:26:08 +00001946 // Bail out if the first declarator didn't seem well-formed.
1947 if (!D.hasName() && !D.mayOmitIdentifier()) {
Richard Smithb8caac82012-04-11 20:59:20 +00001948 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00001949 return nullptr;
Chris Lattnerefb0f112009-03-29 17:18:04 +00001950 }
Mike Stump11289f42009-09-09 15:08:12 +00001951
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001952 // Save late-parsed attributes for now; they need to be parsed in the
1953 // appropriate function scope after the function Decl has been constructed.
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001954 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1955 LateParsedAttrList LateParsedAttrs(true);
Richard Smith99c464c2014-11-10 21:10:32 +00001956 if (D.isFunctionDeclarator()) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001957 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1958
Richard Smith99c464c2014-11-10 21:10:32 +00001959 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1960 // attribute. If we find the keyword here, tell the user to put it
1961 // at the start instead.
1962 if (Tok.is(tok::kw__Noreturn)) {
1963 SourceLocation Loc = ConsumeToken();
1964 const char *PrevSpec;
1965 unsigned DiagID;
1966
1967 // We can offer a fixit if it's valid to mark this function as _Noreturn
1968 // and we don't have any other declarators in this declaration.
1969 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1970 MaybeParseGNUAttributes(D, &LateParsedAttrs);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001971 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
Richard Smith99c464c2014-11-10 21:10:32 +00001972
1973 Diag(Loc, diag::err_c11_noreturn_misplaced)
1974 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001975 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
Richard Smith99c464c2014-11-10 21:10:32 +00001976 : FixItHint());
1977 }
1978 }
1979
Chris Lattnerdbb1e932010-07-11 22:24:20 +00001980 // Check to see if we have a function *definition* which must have a body.
Douglas Gregor012efe22013-04-16 16:01:32 +00001981 if (D.isFunctionDeclarator() &&
Chris Lattnerdbb1e932010-07-11 22:24:20 +00001982 // Look at the next token to make sure that this isn't a function
1983 // declaration. We have to check this because __attribute__ might be the
1984 // start of a function definition in GCC-extended K&R C.
Fariborz Jahanian712bb812012-08-10 15:54:40 +00001985 !isDeclarationAfterDeclarator()) {
Chad Rosierc1183952012-06-26 22:30:43 +00001986
Reid Klecknerd61a3112014-12-15 23:16:32 +00001987 // Function definitions are only allowed at file scope and in C++ classes.
1988 // The C++ inline method definition case is handled elsewhere, so we only
1989 // need to handle the file scope definition case.
Faisal Vali421b2d12017-12-29 05:41:00 +00001990 if (Context == DeclaratorContext::FileContext) {
Douglas Gregor012efe22013-04-16 16:01:32 +00001991 if (isStartOfFunctionDefinition(D)) {
1992 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1993 Diag(Tok, diag::err_function_declared_typedef);
John McCalld5a36322009-11-03 19:26:08 +00001994
Douglas Gregor012efe22013-04-16 16:01:32 +00001995 // Recover by treating the 'typedef' as spurious.
1996 DS.ClearStorageClassSpecs();
1997 }
1998
1999 Decl *TheDecl =
2000 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
2001 return Actions.ConvertDeclToDeclGroup(TheDecl);
John McCalld5a36322009-11-03 19:26:08 +00002002 }
2003
Douglas Gregor012efe22013-04-16 16:01:32 +00002004 if (isDeclarationSpecifier()) {
Nico Weber6b05f382015-02-18 04:53:03 +00002005 // If there is an invalid declaration specifier right after the
2006 // function prototype, then we must be in a missing semicolon case
2007 // where this isn't actually a body. Just fall through into the code
2008 // that handles it as a prototype, and let the top-level code handle
2009 // the erroneous declspec where it would otherwise expect a comma or
2010 // semicolon.
Douglas Gregor012efe22013-04-16 16:01:32 +00002011 } else {
2012 Diag(Tok, diag::err_expected_fn_body);
2013 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002014 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00002015 }
John McCalld5a36322009-11-03 19:26:08 +00002016 } else {
Douglas Gregor012efe22013-04-16 16:01:32 +00002017 if (Tok.is(tok::l_brace)) {
2018 Diag(Tok, diag::err_function_definition_not_allowed);
Serge Pavlov1de51512013-12-09 05:25:47 +00002019 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00002020 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00002021 }
John McCalld5a36322009-11-03 19:26:08 +00002022 }
2023 }
2024
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002025 if (ParseAsmAttributesAfterDeclarator(D))
David Blaikie0403cb12016-01-15 23:43:25 +00002026 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00002027
2028 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2029 // must parse and analyze the for-range-initializer before the declaration is
2030 // analyzed.
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002031 //
2032 // Handle the Objective-C for-in loop variable similarly, although we
2033 // don't need to parse the container in advance.
2034 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2035 bool IsForRangeLoop = false;
Alp Toker8fbec672013-12-17 23:29:36 +00002036 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002037 IsForRangeLoop = true;
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002038 if (Tok.is(tok::l_brace))
2039 FRI->RangeExpr = ParseBraceInitializer();
2040 else
2041 FRI->RangeExpr = ParseExpression();
2042 }
2043
Richard Smith02e85f32011-04-14 22:09:26 +00002044 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
George Karpenkovec38cf72018-03-29 00:56:24 +00002045 if (IsForRangeLoop) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002046 Actions.ActOnCXXForRangeDecl(ThisDecl);
George Karpenkovec38cf72018-03-29 00:56:24 +00002047 } else {
2048 // Obj-C for loop
2049 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2050 VD->setObjCForDecl(true);
2051 }
Richard Smith02e85f32011-04-14 22:09:26 +00002052 Actions.FinalizeDeclaration(ThisDecl);
John McCallcf6e0c82012-01-27 01:29:43 +00002053 D.complete(ThisDecl);
Rafael Espindolaab417692013-07-09 12:05:01 +00002054 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
Richard Smith02e85f32011-04-14 22:09:26 +00002055 }
2056
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002057 SmallVector<Decl *, 8> DeclsInGroup;
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002058 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2059 D, ParsedTemplateInfo(), FRI);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002060 if (LateParsedAttrs.size() > 0)
2061 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
John McCall28a6aea2009-11-04 02:18:39 +00002062 D.complete(FirstDecl);
John McCall48871652010-08-21 09:40:31 +00002063 if (FirstDecl)
John McCalld5a36322009-11-03 19:26:08 +00002064 DeclsInGroup.push_back(FirstDecl);
2065
Faisal Vali421b2d12017-12-29 05:41:00 +00002066 bool ExpectSemi = Context != DeclaratorContext::ForContext;
Fangrui Song6907ce22018-07-30 19:24:48 +00002067
John McCalld5a36322009-11-03 19:26:08 +00002068 // If we don't have a comma, it is either the end of the list (a ';') or an
2069 // error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00002070 SourceLocation CommaLoc;
2071 while (TryConsumeToken(tok::comma, CommaLoc)) {
Richard Smith09f76ee2011-10-19 21:33:05 +00002072 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2073 // This comma was followed by a line-break and something which can't be
2074 // the start of a declarator. The comma was probably a typo for a
2075 // semicolon.
2076 Diag(CommaLoc, diag::err_expected_semi_declaration)
2077 << FixItHint::CreateReplacement(CommaLoc, ";");
2078 ExpectSemi = false;
2079 break;
2080 }
John McCalld5a36322009-11-03 19:26:08 +00002081
2082 // Parse the next declarator.
2083 D.clear();
Richard Smith8d06f422012-01-12 23:53:29 +00002084 D.setCommaLoc(CommaLoc);
John McCalld5a36322009-11-03 19:26:08 +00002085
2086 // Accept attributes in an init-declarator. In the first declarator in a
2087 // declaration, these would be part of the declspec. In subsequent
2088 // declarators, they become part of the declarator itself, so that they
2089 // don't apply to declarators after *this* one. Examples:
2090 // short __attribute__((common)) var; -> declspec
2091 // short var __attribute__((common)); -> declarator
2092 // short x, __attribute__((common)) var; -> declarator
John McCall53fa7142010-12-24 02:08:15 +00002093 MaybeParseGNUAttributes(D);
John McCalld5a36322009-11-03 19:26:08 +00002094
Nico Rieckeaaae272014-12-04 23:31:08 +00002095 // MSVC parses but ignores qualifiers after the comma as an extension.
2096 if (getLangOpts().MicrosoftExt)
2097 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2098
John McCalld5a36322009-11-03 19:26:08 +00002099 ParseDeclarator(D);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002100 if (!D.isInvalidType()) {
2101 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2102 D.complete(ThisDecl);
2103 if (ThisDecl)
Chad Rosierc1183952012-06-26 22:30:43 +00002104 DeclsInGroup.push_back(ThisDecl);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002105 }
John McCalld5a36322009-11-03 19:26:08 +00002106 }
2107
2108 if (DeclEnd)
2109 *DeclEnd = Tok.getLocation();
2110
Richard Smith09f76ee2011-10-19 21:33:05 +00002111 if (ExpectSemi &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002112 ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
Chris Lattner02f1b612012-04-28 16:12:17 +00002113 ? diag::err_invalid_token_after_toplevel_declarator
2114 : diag::err_expected_semi_declaration)) {
Chris Lattner13901342010-07-11 22:42:07 +00002115 // Okay, there was no semicolon and one was expected. If we see a
2116 // declaration specifier, just assume it was missing and continue parsing.
2117 // Otherwise things are very confused and we skip to recover.
2118 if (!isDeclarationSpecifier()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002119 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Alp Toker8fbec672013-12-17 23:29:36 +00002120 TryConsumeToken(tok::semi);
Chris Lattner13901342010-07-11 22:42:07 +00002121 }
John McCalld5a36322009-11-03 19:26:08 +00002122 }
2123
Rafael Espindolaab417692013-07-09 12:05:01 +00002124 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner53361ac2006-08-10 05:19:57 +00002125}
2126
Richard Smith02e85f32011-04-14 22:09:26 +00002127/// Parse an optional simple-asm-expr and attributes, and attach them to a
2128/// declarator. Returns true on an error.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002129bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
Richard Smith02e85f32011-04-14 22:09:26 +00002130 // If a simple-asm-expr is present, parse it.
2131 if (Tok.is(tok::kw_asm)) {
2132 SourceLocation Loc;
2133 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2134 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002135 SkipUntil(tok::semi, StopBeforeMatch);
Richard Smith02e85f32011-04-14 22:09:26 +00002136 return true;
2137 }
2138
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002139 D.setAsmLabel(AsmLabel.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002140 D.SetRangeEnd(Loc);
2141 }
2142
2143 MaybeParseGNUAttributes(D);
2144 return false;
2145}
2146
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002147/// Parse 'declaration' after parsing 'declaration-specifiers
Douglas Gregor23996282009-05-12 21:31:51 +00002148/// declarator'. This method parses the remainder of the declaration
2149/// (including any attributes or initializer, among other things) and
2150/// finalizes the declaration.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002151///
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002152/// init-declarator: [C99 6.7]
2153/// declarator
2154/// declarator '=' initializer
Chris Lattner6d7e6342006-08-15 03:41:14 +00002155/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2156/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002157/// [C++] declarator initializer[opt]
2158///
2159/// [C++] initializer:
2160/// [C++] '=' initializer-clause
2161/// [C++] '(' expression-list ')'
Sebastian Redlf769df52009-03-24 22:27:57 +00002162/// [C++0x] '=' 'default' [TODO]
2163/// [C++0x] '=' 'delete'
Sebastian Redl3da34892011-06-05 12:23:16 +00002164/// [C++0x] braced-init-list
Sebastian Redlf769df52009-03-24 22:27:57 +00002165///
2166/// According to the standard grammar, =default and =delete are function
2167/// definitions, but that definitely doesn't fit with the parser here.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002168///
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002169Decl *Parser::ParseDeclarationAfterDeclarator(
2170 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002171 if (ParseAsmAttributesAfterDeclarator(D))
Craig Topper161e4db2014-05-21 06:02:52 +00002172 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002173
Richard Smith02e85f32011-04-14 22:09:26 +00002174 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2175}
Mike Stump11289f42009-09-09 15:08:12 +00002176
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002177Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2178 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
Richard Smithc95d2c52017-09-22 04:25:05 +00002179 // RAII type used to track whether we're inside an initializer.
2180 struct InitializerScopeRAII {
2181 Parser &P;
2182 Declarator &D;
2183 Decl *ThisDecl;
2184
2185 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2186 : P(P), D(D), ThisDecl(ThisDecl) {
2187 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2188 Scope *S = nullptr;
2189 if (D.getCXXScopeSpec().isSet()) {
2190 P.EnterScope(0);
2191 S = P.getCurScope();
2192 }
2193 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2194 }
2195 }
2196 ~InitializerScopeRAII() { pop(); }
2197 void pop() {
2198 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2199 Scope *S = nullptr;
2200 if (D.getCXXScopeSpec().isSet())
2201 S = P.getCurScope();
2202 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2203 if (S)
2204 P.ExitScope();
2205 }
2206 ThisDecl = nullptr;
2207 }
2208 };
2209
Douglas Gregor23996282009-05-12 21:31:51 +00002210 // Inform the current actions module that we just parsed this declarator.
Craig Topper161e4db2014-05-21 06:02:52 +00002211 Decl *ThisDecl = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00002212 switch (TemplateInfo.Kind) {
2213 case ParsedTemplateInfo::NonTemplate:
Douglas Gregor0be31a22010-07-02 17:43:08 +00002214 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
Douglas Gregor450f00842009-09-25 18:43:00 +00002215 break;
Chad Rosierc1183952012-06-26 22:30:43 +00002216
Douglas Gregor450f00842009-09-25 18:43:00 +00002217 case ParsedTemplateInfo::Template:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002218 case ParsedTemplateInfo::ExplicitSpecialization: {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002219 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002220 *TemplateInfo.TemplateParams,
Douglas Gregor450f00842009-09-25 18:43:00 +00002221 D);
Larisse Voufo833b05a2013-08-06 07:33:00 +00002222 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002223 // Re-direct this decl to refer to the templated decl so that we can
2224 // initialize it.
2225 ThisDecl = VT->getTemplatedDecl();
2226 break;
2227 }
2228 case ParsedTemplateInfo::ExplicitInstantiation: {
2229 if (Tok.is(tok::semi)) {
2230 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2231 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2232 if (ThisRes.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002233 SkipUntil(tok::semi, StopBeforeMatch);
Craig Topper161e4db2014-05-21 06:02:52 +00002234 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002235 }
2236 ThisDecl = ThisRes.get();
2237 } else {
2238 // FIXME: This check should be for a variable template instantiation only.
2239
2240 // Check that this is a valid instantiation
Faisal Vali2ab8c152017-12-30 04:15:27 +00002241 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002242 // If the declarator-id is not a template-id, issue a diagnostic and
2243 // recover by ignoring the 'template' keyword.
2244 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2245 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2246 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2247 } else {
2248 SourceLocation LAngleLoc =
2249 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2250 Diag(D.getIdentifierLoc(),
2251 diag::err_explicit_instantiation_with_definition)
2252 << SourceRange(TemplateInfo.TemplateLoc)
2253 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2254
2255 // Recover as if it were an explicit specialization.
2256 TemplateParameterLists FakedParamLists;
2257 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00002258 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00002259 LAngleLoc, nullptr));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002260
2261 ThisDecl =
2262 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2263 }
2264 }
Douglas Gregor450f00842009-09-25 18:43:00 +00002265 break;
2266 }
2267 }
Mike Stump11289f42009-09-09 15:08:12 +00002268
Douglas Gregor23996282009-05-12 21:31:51 +00002269 // Parse declarator '=' initializer.
Richard Trieuc64d3232012-01-18 22:54:52 +00002270 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Trieu4972a6d2012-01-19 22:01:51 +00002271 if (isTokenEqualOrEqualTypo()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002272 SourceLocation EqualLoc = ConsumeToken();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002273
Anders Carlsson991285e2010-09-24 21:25:25 +00002274 if (Tok.is(tok::kw_delete)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002275 if (D.isFunctionDeclarator())
2276 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2277 << 1 /* delete */;
2278 else
2279 Diag(ConsumeToken(), diag::err_deleted_non_function);
Alexis Hunt5dafebc2011-05-06 01:42:00 +00002280 } else if (Tok.is(tok::kw_default)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002281 if (D.isFunctionDeclarator())
Sebastian Redl46afb552012-02-11 23:51:21 +00002282 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2283 << 0 /* default */;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002284 else
2285 Diag(ConsumeToken(), diag::err_default_special_members);
Douglas Gregor23996282009-05-12 21:31:51 +00002286 } else {
Richard Smithc95d2c52017-09-22 04:25:05 +00002287 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002288
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002289 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002290 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
Peter Collingbourne6b4fdc22012-07-27 12:56:09 +00002291 Actions.FinalizeDeclaration(ThisDecl);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002292 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +00002293 return nullptr;
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002294 }
Chad Rosierc1183952012-06-26 22:30:43 +00002295
John McCalldadc5752010-08-24 06:29:42 +00002296 ExprResult Init(ParseInitializer());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002297
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002298 // If this is the only decl in (possibly) range based for statement,
2299 // our best guess is that the user meant ':' instead of '='.
2300 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2301 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2302 << FixItHint::CreateReplacement(EqualLoc, ":");
2303 // We are trying to stop parser from looking for ';' in this for
2304 // statement, therefore preventing spurious errors to be issued.
2305 FRI->ColonLoc = EqualLoc;
2306 Init = ExprError();
2307 FRI->RangeExpr = Init;
2308 }
2309
Richard Smithc95d2c52017-09-22 04:25:05 +00002310 InitScope.pop();
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002311
Douglas Gregor23996282009-05-12 21:31:51 +00002312 if (Init.isInvalid()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002313 SmallVector<tok::TokenKind, 2> StopTokens;
2314 StopTokens.push_back(tok::comma);
Faisal Vali421b2d12017-12-29 05:41:00 +00002315 if (D.getContext() == DeclaratorContext::ForContext ||
2316 D.getContext() == DeclaratorContext::InitStmtContext)
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002317 StopTokens.push_back(tok::r_paren);
2318 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
Douglas Gregor604c3022010-03-01 18:27:54 +00002319 Actions.ActOnInitializerError(ThisDecl);
2320 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002321 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002322 /*DirectInit=*/false);
Douglas Gregor23996282009-05-12 21:31:51 +00002323 }
2324 } else if (Tok.is(tok::l_paren)) {
2325 // Parse C++ direct initializer: '(' expression-list ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002326 BalancedDelimiterTracker T(*this, tok::l_paren);
2327 T.consumeOpen();
2328
Benjamin Kramerf0623432012-08-23 22:51:59 +00002329 ExprVector Exprs;
Douglas Gregor23996282009-05-12 21:31:51 +00002330 CommaLocsTy CommaLocs;
2331
Richard Smithc95d2c52017-09-22 04:25:05 +00002332 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Douglas Gregor613bf102009-12-22 17:47:17 +00002333
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002334 llvm::function_ref<void()> ExprListCompleter;
2335 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2336 auto ConstructorCompleter = [&, ThisVarDecl] {
Ilya Biryukov832c4af2018-09-07 14:04:39 +00002337 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002338 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
Ilya Biryukov2fab2352018-08-30 13:08:03 +00002339 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002340 CalledSignatureHelp = true;
Ilya Biryukov832c4af2018-09-07 14:04:39 +00002341 Actions.CodeCompleteExpression(getCurScope(), PreferredType);
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002342 };
2343 if (ThisVarDecl) {
2344 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2345 // VarDecl. This is an error and it is reported in a call to
2346 // Actions.ActOnInitializerError(). However, we call
Ilya Biryukov832c4af2018-09-07 14:04:39 +00002347 // ProduceConstructorSignatureHelp only on VarDecls, falling back to
2348 // default completer in other cases.
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002349 ExprListCompleter = ConstructorCompleter;
2350 }
2351
2352 if (ParseExpressionList(Exprs, CommaLocs, ExprListCompleter)) {
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002353 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2354 Actions.ProduceConstructorSignatureHelp(
2355 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2356 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2357 CalledSignatureHelp = true;
2358 }
David Blaikieeae04112012-10-10 23:15:05 +00002359 Actions.ActOnInitializerError(ThisDecl);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002360 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor23996282009-05-12 21:31:51 +00002361 } else {
2362 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002363 T.consumeClose();
Douglas Gregor23996282009-05-12 21:31:51 +00002364
2365 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2366 "Unexpected number of commas!");
Douglas Gregor613bf102009-12-22 17:47:17 +00002367
Richard Smithc95d2c52017-09-22 04:25:05 +00002368 InitScope.pop();
Douglas Gregor613bf102009-12-22 17:47:17 +00002369
Sebastian Redla9351792012-02-11 23:51:47 +00002370 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2371 T.getCloseLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002372 Exprs);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002373 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002374 /*DirectInit=*/true);
Douglas Gregor23996282009-05-12 21:31:51 +00002375 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002376 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
Fariborz Jahanian8be1ecd2012-07-03 23:22:13 +00002377 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
Sebastian Redl3da34892011-06-05 12:23:16 +00002378 // Parse C++0x braced-init-list.
Richard Smith5d164bc2011-10-15 05:09:34 +00002379 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2380
Richard Smithc95d2c52017-09-22 04:25:05 +00002381 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Sebastian Redl3da34892011-06-05 12:23:16 +00002382
2383 ExprResult Init(ParseBraceInitializer());
2384
Richard Smithc95d2c52017-09-22 04:25:05 +00002385 InitScope.pop();
Sebastian Redl3da34892011-06-05 12:23:16 +00002386
2387 if (Init.isInvalid()) {
2388 Actions.ActOnInitializerError(ThisDecl);
2389 } else
Richard Smith3beb7c62017-01-12 02:27:38 +00002390 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
Sebastian Redl3da34892011-06-05 12:23:16 +00002391
Douglas Gregor23996282009-05-12 21:31:51 +00002392 } else {
Richard Smith3beb7c62017-01-12 02:27:38 +00002393 Actions.ActOnUninitializedDecl(ThisDecl);
Douglas Gregor23996282009-05-12 21:31:51 +00002394 }
2395
Richard Smithb2bc2e62011-02-21 20:05:19 +00002396 Actions.FinalizeDeclaration(ThisDecl);
2397
Douglas Gregor23996282009-05-12 21:31:51 +00002398 return ThisDecl;
2399}
2400
Chris Lattner1890ac82006-08-13 01:16:23 +00002401/// ParseSpecifierQualifierList
2402/// specifier-qualifier-list:
2403/// type-specifier specifier-qualifier-list[opt]
2404/// type-qualifier specifier-qualifier-list[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002405/// [GNU] attributes specifier-qualifier-list[opt]
Chris Lattner1890ac82006-08-13 01:16:23 +00002406///
Richard Smithc5b05522012-03-12 07:56:15 +00002407void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2408 DeclSpecContext DSC) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002409 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2410 /// parse declaration-specifiers and complain about extra stuff.
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002411 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
Faisal Valia534f072018-04-26 00:42:40 +00002412 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
Mike Stump11289f42009-09-09 15:08:12 +00002413
Chris Lattner1890ac82006-08-13 01:16:23 +00002414 // Validate declspec for type-name.
2415 unsigned Specs = DS.getParsedSpecifiers();
Richard Smith649c7b062014-01-08 00:56:48 +00002416 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
Richard Smithc5b05522012-03-12 07:56:15 +00002417 Diag(Tok, diag::err_expected_type);
2418 DS.SetTypeSpecError();
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00002419 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002420 Diag(Tok, diag::err_typename_requires_specqual);
Richard Smithc5b05522012-03-12 07:56:15 +00002421 if (!DS.hasTypeSpecifier())
2422 DS.SetTypeSpecError();
2423 }
Mike Stump11289f42009-09-09 15:08:12 +00002424
Chris Lattner1b22eed2006-11-28 05:12:07 +00002425 // Issue diagnostic and remove storage class if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002426 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
Chris Lattner1b22eed2006-11-28 05:12:07 +00002427 if (DS.getStorageClassSpecLoc().isValid())
2428 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2429 else
Richard Smithb4a9e862013-04-12 22:46:28 +00002430 Diag(DS.getThreadStorageClassSpecLoc(),
2431 diag::err_typename_invalid_storageclass);
Chris Lattnera925dc62006-11-28 04:33:46 +00002432 DS.ClearStorageClassSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002433 }
Mike Stump11289f42009-09-09 15:08:12 +00002434
Craig Topper3f13d4d22015-11-14 18:15:55 +00002435 // Issue diagnostic and remove function specifier if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002436 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
Douglas Gregor61956c42008-10-31 09:07:45 +00002437 if (DS.isInlineSpecified())
2438 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2439 if (DS.isVirtualSpecified())
2440 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2441 if (DS.isExplicitSpecified())
2442 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
Chris Lattnera925dc62006-11-28 04:33:46 +00002443 DS.ClearFunctionSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002444 }
Richard Smithc5b05522012-03-12 07:56:15 +00002445
2446 // Issue diagnostic and remove constexpr specfier if present.
Faisal Vali7db85c52017-12-31 00:06:40 +00002447 if (DS.isConstexprSpecified() && DSC != DeclSpecContext::DSC_condition) {
Richard Smithc5b05522012-03-12 07:56:15 +00002448 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2449 DS.ClearConstexprSpec();
2450 }
Chris Lattner1890ac82006-08-13 01:16:23 +00002451}
Chris Lattner53361ac2006-08-10 05:19:57 +00002452
Chris Lattner6cc055a2009-04-12 20:42:31 +00002453/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2454/// specified token is valid after the identifier in a declarator which
2455/// immediately follows the declspec. For example, these things are valid:
2456///
2457/// int x [ 4]; // direct-declarator
2458/// int x ( int y); // direct-declarator
2459/// int(int x ) // direct-declarator
2460/// int x ; // simple-declaration
2461/// int x = 17; // init-declarator-list
2462/// int x , y; // init-declarator-list
2463/// int x __asm__ ("foo"); // init-declarator-list
Chris Lattnera723ba92009-04-14 21:16:09 +00002464/// int x : 4; // struct-declarator
Chris Lattner2b988c12009-04-12 22:29:43 +00002465/// int x { 5}; // C++'0x unified initializers
Chris Lattner6cc055a2009-04-12 20:42:31 +00002466///
2467/// This is not, because 'x' does not immediately follow the declspec (though
2468/// ')' happens to be valid anyway).
2469/// int (x)
2470///
2471static bool isValidAfterIdentifierInDeclarator(const Token &T) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002472 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2473 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2474 tok::colon);
Chris Lattner6cc055a2009-04-12 20:42:31 +00002475}
2476
Chris Lattner20a0c612009-04-14 21:34:55 +00002477/// ParseImplicitInt - This method is called when we have an non-typename
2478/// identifier in a declspec (which normally terminates the decl spec) when
2479/// the declspec has no type specifier. In this case, the declspec is either
2480/// malformed or is "implicit int" (in K&R and C89).
2481///
2482/// This method handles diagnosing this prettily and returns false if the
2483/// declspec is done being processed. If it recovers and thinks there may be
2484/// other pieces of declspec after it, it returns true.
2485///
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002486bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002487 const ParsedTemplateInfo &TemplateInfo,
Richard Smitha0a5d502014-05-08 22:32:00 +00002488 AccessSpecifier AS, DeclSpecContext DSC,
Michael Han9407e502012-11-26 22:54:45 +00002489 ParsedAttributesWithRange &Attrs) {
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002490 assert(Tok.is(tok::identifier) && "should have identifier");
Mike Stump11289f42009-09-09 15:08:12 +00002491
Chris Lattner20a0c612009-04-14 21:34:55 +00002492 SourceLocation Loc = Tok.getLocation();
2493 // If we see an identifier that is not a type name, we normally would
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002494 // parse it as the identifier being declared. However, when a typename
Chris Lattner20a0c612009-04-14 21:34:55 +00002495 // is typo'd or the definition is not included, this will incorrectly
2496 // parse the typename as the identifier name and fall over misparsing
2497 // later parts of the diagnostic.
2498 //
2499 // As such, we try to do some look-ahead in cases where this would
2500 // otherwise be an "implicit-int" case to see if this is invalid. For
2501 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2502 // an identifier with implicit int, we'd get a parse error because the
2503 // next token is obviously invalid for a type. Parse these as a case
2504 // with an invalid type specifier.
2505 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
Mike Stump11289f42009-09-09 15:08:12 +00002506
Chris Lattner20a0c612009-04-14 21:34:55 +00002507 // Since we know that this either implicit int (which is rare) or an
Richard Smitha952ebb2012-05-15 21:01:51 +00002508 // error, do lookahead to try to do better recovery. This never applies
2509 // within a type specifier. Outside of C++, we allow this even if the
2510 // language doesn't "officially" support implicit int -- we support
Richard Smith3b870382013-04-30 22:43:51 +00002511 // implicit int as an extension in C99 and C11.
Richard Smith649c7b062014-01-08 00:56:48 +00002512 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
Richard Smithc5b05522012-03-12 07:56:15 +00002513 isValidAfterIdentifierInDeclarator(NextToken())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002514 // If this token is valid for implicit int, e.g. "static x = 4", then
2515 // we just avoid eating the identifier, so it will be parsed as the
2516 // identifier in the declarator.
2517 return false;
2518 }
Mike Stump11289f42009-09-09 15:08:12 +00002519
Richard Smitha952ebb2012-05-15 21:01:51 +00002520 if (getLangOpts().CPlusPlus &&
2521 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2522 // Don't require a type specifier if we have the 'auto' storage class
2523 // specifier in C++98 -- we'll promote it to a type specifier.
Richard Smithfb8b7b92013-10-15 00:00:26 +00002524 if (SS)
2525 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
Richard Smitha952ebb2012-05-15 21:01:51 +00002526 return false;
2527 }
2528
Reid Kleckner9a96e422016-05-24 21:23:54 +00002529 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2530 getLangOpts().MSVCCompat) {
2531 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2532 // Give Sema a chance to recover if we are in a template with dependent base
2533 // classes.
2534 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2535 *Tok.getIdentifierInfo(), Tok.getLocation(),
Faisal Vali7db85c52017-12-31 00:06:40 +00002536 DSC == DeclSpecContext::DSC_template_type_arg)) {
Reid Kleckner9a96e422016-05-24 21:23:54 +00002537 const char *PrevSpec;
2538 unsigned DiagID;
2539 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2540 Actions.getASTContext().getPrintingPolicy());
2541 DS.SetRangeEnd(Tok.getLocation());
2542 ConsumeToken();
2543 return false;
2544 }
2545 }
2546
Chris Lattner20a0c612009-04-14 21:34:55 +00002547 // Otherwise, if we don't consume this token, we are going to emit an
2548 // error anyway. Try to recover from various common problems. Check
2549 // to see if this was a reference to a tag name without a tag specified.
2550 // This is a common problem in C (saying 'foo' instead of 'struct foo').
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002551 //
2552 // C++ doesn't need this, and isTagName doesn't take SS.
Craig Topper161e4db2014-05-21 06:02:52 +00002553 if (SS == nullptr) {
2554 const char *TagName = nullptr, *FixitTagName = nullptr;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002555 tok::TokenKind TagKind = tok::unknown;
Mike Stump11289f42009-09-09 15:08:12 +00002556
Douglas Gregor0be31a22010-07-02 17:43:08 +00002557 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002558 default: break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002559 case DeclSpec::TST_enum:
2560 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2561 case DeclSpec::TST_union:
2562 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2563 case DeclSpec::TST_struct:
2564 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
Joao Matosdc86f942012-08-31 18:45:21 +00002565 case DeclSpec::TST_interface:
2566 TagName="__interface"; FixitTagName = "__interface ";
2567 TagKind=tok::kw___interface;break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002568 case DeclSpec::TST_class:
2569 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
Chris Lattner20a0c612009-04-14 21:34:55 +00002570 }
Mike Stump11289f42009-09-09 15:08:12 +00002571
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002572 if (TagName) {
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002573 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2574 LookupResult R(Actions, TokenName, SourceLocation(),
2575 Sema::LookupOrdinaryName);
2576
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002577 Diag(Loc, diag::err_use_of_tag_name_without_tag)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002578 << TokenName << TagName << getLangOpts().CPlusPlus
2579 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2580
2581 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2582 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2583 I != IEnd; ++I)
Kaelyn Uhrain3fe3f852012-04-27 18:26:49 +00002584 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002585 << TokenName << TagName;
2586 }
Mike Stump11289f42009-09-09 15:08:12 +00002587
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002588 // Parse this as a tag as if the missing tag were present.
2589 if (TagKind == tok::kw_enum)
Faisal Vali7db85c52017-12-31 00:06:40 +00002590 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2591 DeclSpecContext::DSC_normal);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002592 else
Richard Smithc5b05522012-03-12 07:56:15 +00002593 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
Faisal Vali7db85c52017-12-31 00:06:40 +00002594 /*EnteringContext*/ false,
2595 DeclSpecContext::DSC_normal, Attrs);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002596 return true;
2597 }
Chris Lattner20a0c612009-04-14 21:34:55 +00002598 }
Mike Stump11289f42009-09-09 15:08:12 +00002599
Richard Smithfe904f02012-05-15 21:29:55 +00002600 // Determine whether this identifier could plausibly be the name of something
Richard Smithedd124e2012-05-15 21:42:17 +00002601 // being declared (with a missing type).
Faisal Vali7db85c52017-12-31 00:06:40 +00002602 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2603 DSC == DeclSpecContext::DSC_class)) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002604 // Look ahead to the next token to try to figure out what this declaration
2605 // was supposed to be.
2606 switch (NextToken().getKind()) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002607 case tok::l_paren: {
2608 // static x(4); // 'x' is not a type
2609 // x(int n); // 'x' is not a type
2610 // x (*p)[]; // 'x' is a type
2611 //
Richard Smitha0a5d502014-05-08 22:32:00 +00002612 // Since we're in an error case, we can afford to perform a tentative
2613 // parse to determine which case we're in.
Richard Smitha952ebb2012-05-15 21:01:51 +00002614 TentativeParsingAction PA(*this);
2615 ConsumeToken();
2616 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2617 PA.Revert();
Richard Smithfb8b7b92013-10-15 00:00:26 +00002618
Richard Smithee390432014-05-16 01:56:53 +00002619 if (TPR != TPResult::False) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002620 // The identifier is followed by a parenthesized declarator.
2621 // It's supposed to be a type.
2622 break;
2623 }
2624
2625 // If we're in a context where we could be declaring a constructor,
2626 // check whether this is a constructor declaration with a bogus name.
Faisal Vali7db85c52017-12-31 00:06:40 +00002627 if (DSC == DeclSpecContext::DSC_class ||
2628 (DSC == DeclSpecContext::DSC_top_level && SS)) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002629 IdentifierInfo *II = Tok.getIdentifierInfo();
2630 if (Actions.isCurrentClassNameTypo(II, SS)) {
2631 Diag(Loc, diag::err_constructor_bad_name)
2632 << Tok.getIdentifierInfo() << II
2633 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2634 Tok.setIdentifierInfo(II);
2635 }
2636 }
2637 // Fall through.
Galina Kistanova77674252017-06-01 21:15:34 +00002638 LLVM_FALLTHROUGH;
Richard Smitha952ebb2012-05-15 21:01:51 +00002639 }
Richard Smithfb8b7b92013-10-15 00:00:26 +00002640 case tok::comma:
2641 case tok::equal:
2642 case tok::kw_asm:
2643 case tok::l_brace:
2644 case tok::l_square:
2645 case tok::semi:
2646 // This looks like a variable or function declaration. The type is
2647 // probably missing. We're done parsing decl-specifiers.
2648 if (SS)
2649 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2650 return false;
Richard Smitha952ebb2012-05-15 21:01:51 +00002651
2652 default:
2653 // This is probably supposed to be a type. This includes cases like:
2654 // int f(itn);
2655 // struct S { unsinged : 4; };
2656 break;
2657 }
2658 }
2659
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002660 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2661 // and attempt to recover.
John McCallba7bf592010-08-24 05:47:05 +00002662 ParsedType T;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +00002663 IdentifierInfo *II = Tok.getIdentifierInfo();
Richard Smith52f8d192017-05-10 21:32:16 +00002664 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002665 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
Richard Smith52f8d192017-05-10 21:32:16 +00002666 IsTemplateName);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002667 if (T) {
2668 // The action has suggested that the type T could be used. Set that as
2669 // the type in the declaration specifiers, consume the would-be type
2670 // name token, and we're done.
2671 const char *PrevSpec;
2672 unsigned DiagID;
2673 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2674 Actions.getASTContext().getPrintingPolicy());
2675 DS.SetRangeEnd(Tok.getLocation());
2676 ConsumeToken();
2677 // There may be other declaration specifiers after this.
2678 return true;
2679 } else if (II != Tok.getIdentifierInfo()) {
2680 // If no type was suggested, the correction is to a keyword
2681 Tok.setKind(II->getTokenID());
2682 // There may be other declaration specifiers after this.
2683 return true;
Douglas Gregor15e56022009-10-13 23:27:22 +00002684 }
Mike Stump11289f42009-09-09 15:08:12 +00002685
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002686 // Otherwise, the action had no suggestion for us. Mark this as an error.
Richard Smithc5b05522012-03-12 07:56:15 +00002687 DS.SetTypeSpecError();
Chris Lattner20a0c612009-04-14 21:34:55 +00002688 DS.SetRangeEnd(Tok.getLocation());
2689 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002690
Richard Smith52f8d192017-05-10 21:32:16 +00002691 // Eat any following template arguments.
2692 if (IsTemplateName) {
2693 SourceLocation LAngle, RAngle;
2694 TemplateArgList Args;
2695 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2696 }
2697
Chris Lattner20a0c612009-04-14 21:34:55 +00002698 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2699 // avoid rippling error messages on subsequent uses of the same type,
2700 // could be useful if #include was forgotten.
2701 return false;
2702}
2703
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002704/// Determine the declaration specifier context from the declarator
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002705/// context.
2706///
2707/// \param Context the declarator context, which is one of the
Faisal Vali421b2d12017-12-29 05:41:00 +00002708/// DeclaratorContext enumerator values.
Chad Rosierc1183952012-06-26 22:30:43 +00002709Parser::DeclSpecContext
Faisal Vali421b2d12017-12-29 05:41:00 +00002710Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2711 if (Context == DeclaratorContext::MemberContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002712 return DeclSpecContext::DSC_class;
Faisal Vali421b2d12017-12-29 05:41:00 +00002713 if (Context == DeclaratorContext::FileContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002714 return DeclSpecContext::DSC_top_level;
Faisal Vali421b2d12017-12-29 05:41:00 +00002715 if (Context == DeclaratorContext::TemplateParamContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002716 return DeclSpecContext::DSC_template_param;
Richard Smith77a9c602018-02-28 03:02:23 +00002717 if (Context == DeclaratorContext::TemplateArgContext ||
2718 Context == DeclaratorContext::TemplateTypeArgContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002719 return DeclSpecContext::DSC_template_type_arg;
Richard Smithe303e352018-02-02 22:24:54 +00002720 if (Context == DeclaratorContext::TrailingReturnContext ||
2721 Context == DeclaratorContext::TrailingReturnVarContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002722 return DeclSpecContext::DSC_trailing;
Faisal Vali421b2d12017-12-29 05:41:00 +00002723 if (Context == DeclaratorContext::AliasDeclContext ||
2724 Context == DeclaratorContext::AliasTemplateContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002725 return DeclSpecContext::DSC_alias_declaration;
2726 return DeclSpecContext::DSC_normal;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002727}
2728
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002729/// ParseAlignArgument - Parse the argument to an alignment-specifier.
2730///
2731/// FIXME: Simply returns an alignof() expression if the argument is a
2732/// type. Ideally, the type should be propagated directly into Sema.
2733///
Benjamin Kramere56f3932011-12-23 17:00:35 +00002734/// [C11] type-id
2735/// [C11] constant-expression
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002736/// [C++0x] type-id ...[opt]
2737/// [C++0x] assignment-expression ...[opt]
2738ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2739 SourceLocation &EllipsisLoc) {
2740 ExprResult ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002741 if (isTypeIdInParens()) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002742 SourceLocation TypeLoc = Tok.getLocation();
2743 ParsedType Ty = ParseTypeName().get();
2744 SourceRange TypeRange(Start, Tok.getLocation());
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002745 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2746 Ty.getAsOpaquePtr(), TypeRange);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002747 } else
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002748 ER = ParseConstantExpression();
2749
Alp Toker8fbec672013-12-17 23:29:36 +00002750 if (getLangOpts().CPlusPlus11)
2751 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002752
2753 return ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002754}
2755
2756/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2757/// attribute to Attrs.
2758///
2759/// alignment-specifier:
Benjamin Kramere56f3932011-12-23 17:00:35 +00002760/// [C11] '_Alignas' '(' type-id ')'
2761/// [C11] '_Alignas' '(' constant-expression ')'
Richard Smithd11c7a12013-01-29 01:48:07 +00002762/// [C++11] 'alignas' '(' type-id ...[opt] ')'
2763/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002764void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
Richard Smith44c247f2013-02-22 08:32:16 +00002765 SourceLocation *EndLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002766 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002767 "Not an alignment-specifier!");
2768
Richard Smithd11c7a12013-01-29 01:48:07 +00002769 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2770 SourceLocation KWLoc = ConsumeToken();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002771
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002772 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002773 if (T.expectAndConsume())
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002774 return;
2775
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002776 SourceLocation EllipsisLoc;
2777 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002778 if (ArgExpr.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002779 T.skipToEnd();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002780 return;
2781 }
2782
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002783 T.consumeClose();
Richard Smith44c247f2013-02-22 08:32:16 +00002784 if (EndLoc)
2785 *EndLoc = T.getCloseLocation();
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002786
Aaron Ballman00e99962013-08-31 01:11:41 +00002787 ArgsVector ArgExprs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002788 ArgExprs.push_back(ArgExpr.get());
Craig Topper161e4db2014-05-21 06:02:52 +00002789 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
Erich Keanee891aa92018-07-13 15:07:47 +00002790 ParsedAttr::AS_Keyword, EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002791}
2792
Richard Smith404dfb42013-11-19 22:47:36 +00002793/// Determine whether we're looking at something that might be a declarator
2794/// in a simple-declaration. If it can't possibly be a declarator, maybe
2795/// diagnose a missing semicolon after a prior tag definition in the decl
2796/// specifier.
2797///
2798/// \return \c true if an error occurred and this can't be any kind of
2799/// declaration.
2800bool
2801Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2802 DeclSpecContext DSContext,
2803 LateParsedAttrList *LateAttrs) {
2804 assert(DS.hasTagDefinition() && "shouldn't call this");
2805
Faisal Vali7db85c52017-12-31 00:06:40 +00002806 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2807 DSContext == DeclSpecContext::DSC_top_level);
Richard Smith404dfb42013-11-19 22:47:36 +00002808
2809 if (getLangOpts().CPlusPlus &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002810 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2811 tok::annot_template_id) &&
Richard Smith404dfb42013-11-19 22:47:36 +00002812 TryAnnotateCXXScopeToken(EnteringContext)) {
2813 SkipMalformedDecl();
2814 return true;
2815 }
2816
Richard Smith698875a2013-11-20 23:40:57 +00002817 bool HasScope = Tok.is(tok::annot_cxxscope);
2818 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2819 Token AfterScope = HasScope ? NextToken() : Tok;
2820
Richard Smith404dfb42013-11-19 22:47:36 +00002821 // Determine whether the following tokens could possibly be a
2822 // declarator.
Richard Smith698875a2013-11-20 23:40:57 +00002823 bool MightBeDeclarator = true;
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002824 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
Richard Smith698875a2013-11-20 23:40:57 +00002825 // A declarator-id can't start with 'typename'.
2826 MightBeDeclarator = false;
2827 } else if (AfterScope.is(tok::annot_template_id)) {
2828 // If we have a type expressed as a template-id, this cannot be a
2829 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2830 TemplateIdAnnotation *Annot =
2831 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2832 if (Annot->Kind == TNK_Type_template)
2833 MightBeDeclarator = false;
2834 } else if (AfterScope.is(tok::identifier)) {
2835 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2836
Richard Smith404dfb42013-11-19 22:47:36 +00002837 // These tokens cannot come after the declarator-id in a
2838 // simple-declaration, and are likely to come after a type-specifier.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002839 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2840 tok::annot_cxxscope, tok::coloncolon)) {
Richard Smith698875a2013-11-20 23:40:57 +00002841 // Missing a semicolon.
2842 MightBeDeclarator = false;
2843 } else if (HasScope) {
2844 // If the declarator-id has a scope specifier, it must redeclare a
2845 // previously-declared entity. If that's a type (and this is not a
2846 // typedef), that's an error.
2847 CXXScopeSpec SS;
2848 Actions.RestoreNestedNameSpecifierAnnotation(
2849 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2850 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2851 Sema::NameClassification Classification = Actions.ClassifyName(
2852 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2853 /*IsAddressOfOperand*/false);
2854 switch (Classification.getKind()) {
2855 case Sema::NC_Error:
2856 SkipMalformedDecl();
2857 return true;
Richard Smith404dfb42013-11-19 22:47:36 +00002858
Richard Smith698875a2013-11-20 23:40:57 +00002859 case Sema::NC_Keyword:
2860 case Sema::NC_NestedNameSpecifier:
2861 llvm_unreachable("typo correction and nested name specifiers not "
2862 "possible here");
Richard Smith404dfb42013-11-19 22:47:36 +00002863
Richard Smith698875a2013-11-20 23:40:57 +00002864 case Sema::NC_Type:
2865 case Sema::NC_TypeTemplate:
2866 // Not a previously-declared non-type entity.
2867 MightBeDeclarator = false;
2868 break;
Richard Smith404dfb42013-11-19 22:47:36 +00002869
Richard Smith698875a2013-11-20 23:40:57 +00002870 case Sema::NC_Unknown:
2871 case Sema::NC_Expression:
2872 case Sema::NC_VarTemplate:
2873 case Sema::NC_FunctionTemplate:
2874 // Might be a redeclaration of a prior entity.
2875 break;
2876 }
Richard Smith404dfb42013-11-19 22:47:36 +00002877 }
Richard Smith404dfb42013-11-19 22:47:36 +00002878 }
2879
Richard Smith698875a2013-11-20 23:40:57 +00002880 if (MightBeDeclarator)
Richard Smith404dfb42013-11-19 22:47:36 +00002881 return false;
2882
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002883 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002884 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
Alp Toker383d2c42014-01-01 03:08:43 +00002885 diag::err_expected_after)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002886 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
Richard Smith404dfb42013-11-19 22:47:36 +00002887
2888 // Try to recover from the typo, by dropping the tag definition and parsing
2889 // the problematic tokens as a type.
2890 //
2891 // FIXME: Split the DeclSpec into pieces for the standalone
2892 // declaration and pieces for the following declaration, instead
2893 // of assuming that all the other pieces attach to new declaration,
2894 // and call ParsedFreeStandingDeclSpec as appropriate.
2895 DS.ClearTypeSpecType();
2896 ParsedTemplateInfo NotATemplate;
Faisal Valia534f072018-04-26 00:42:40 +00002897 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
Richard Smith404dfb42013-11-19 22:47:36 +00002898 return false;
2899}
2900
Leonard Chanab80f3c2018-06-14 14:53:51 +00002901// Choose the apprpriate diagnostic error for why fixed point types are
2902// disabled, set the previous specifier, and mark as invalid.
2903static void SetupFixedPointError(const LangOptions &LangOpts,
2904 const char *&PrevSpec, unsigned &DiagID,
2905 bool &isInvalid) {
2906 assert(!LangOpts.FixedPoint);
2907 DiagID = diag::err_fixed_point_not_enabled;
2908 PrevSpec = ""; // Not used by diagnostic
2909 isInvalid = true;
2910}
2911
Faisal Valia534f072018-04-26 00:42:40 +00002912/// ParseDeclarationSpecifiers
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002913/// declaration-specifiers: [C99 6.7]
Chris Lattner3b561a32006-08-13 00:12:11 +00002914/// storage-class-specifier declaration-specifiers[opt]
2915/// type-specifier declaration-specifiers[opt]
Chris Lattner3b561a32006-08-13 00:12:11 +00002916/// [C99] function-specifier declaration-specifiers[opt]
Benjamin Kramere56f3932011-12-23 17:00:35 +00002917/// [C11] alignment-specifier declaration-specifiers[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002918/// [GNU] attributes declaration-specifiers[opt]
Douglas Gregor26701a42011-09-09 02:06:17 +00002919/// [Clang] '__module_private__' declaration-specifiers[opt]
Douglas Gregorab209d82015-07-07 03:58:42 +00002920/// [ObjC1] '__kindof' declaration-specifiers[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002921///
Chris Lattnerf63f89a2006-08-05 03:28:50 +00002922/// storage-class-specifier: [C99 6.7.1]
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002923/// 'typedef'
2924/// 'extern'
2925/// 'static'
2926/// 'auto'
2927/// 'register'
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002928/// [C++] 'mutable'
Richard Smithb4a9e862013-04-12 22:46:28 +00002929/// [C++11] 'thread_local'
2930/// [C11] '_Thread_local'
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002931/// [GNU] '__thread'
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002932/// function-specifier: [C99 6.7.4]
Chris Lattner3b561a32006-08-13 00:12:11 +00002933/// [C99] 'inline'
Douglas Gregor61956c42008-10-31 09:07:45 +00002934/// [C++] 'virtual'
2935/// [C++] 'explicit'
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00002936/// [OpenCL] '__kernel'
Anders Carlssoncd8db412009-05-06 04:46:28 +00002937/// 'friend': [C++ dcl.friend]
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00002938/// 'constexpr': [C++0x dcl.constexpr]
Faisal Valia534f072018-04-26 00:42:40 +00002939void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002940 const ParsedTemplateInfo &TemplateInfo,
John McCall07e91c02009-08-06 02:15:43 +00002941 AccessSpecifier AS,
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002942 DeclSpecContext DSContext,
2943 LateParsedAttrList *LateAttrs) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002944 if (DS.getSourceRange().isInvalid()) {
David Majnemer24b28302014-07-26 05:41:31 +00002945 // Start the range at the current token but make the end of the range
2946 // invalid. This will make the entire range invalid unless we successfully
2947 // consume a token.
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002948 DS.SetRangeStart(Tok.getLocation());
David Majnemer24b28302014-07-26 05:41:31 +00002949 DS.SetRangeEnd(SourceLocation());
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002950 }
Chad Rosierc1183952012-06-26 22:30:43 +00002951
Faisal Vali7db85c52017-12-31 00:06:40 +00002952 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2953 DSContext == DeclSpecContext::DSC_top_level);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002954 bool AttrsLastTime = false;
2955 ParsedAttributesWithRange attrs(AttrFactory);
Benjamin Kramere4812142015-03-12 14:28:38 +00002956 // We use Sema's policy to get bool macros right.
Richard Smith301bc212016-05-19 01:39:10 +00002957 PrintingPolicy Policy = Actions.getPrintingPolicy();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002958 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00002959 bool isInvalid = false;
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00002960 bool isStorageClass = false;
Craig Topper161e4db2014-05-21 06:02:52 +00002961 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00002962 unsigned DiagID = 0;
2963
David Majnemer51fd8a02015-07-22 23:46:18 +00002964 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2965 // implementation for VS2013 uses _Atomic as an identifier for one of the
2966 // classes in <atomic>.
2967 //
2968 // A typedef declaration containing _Atomic<...> is among the places where
2969 // the class is used. If we are currently parsing such a declaration, treat
2970 // the token as an identifier.
2971 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2972 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2973 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2974 Tok.setKind(tok::identifier);
2975
Chris Lattner4d8f8732006-11-28 05:05:08 +00002976 SourceLocation Loc = Tok.getLocation();
Douglas Gregor450c75a2008-11-07 15:42:26 +00002977
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002978 switch (Tok.getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00002979 default:
Chris Lattner0974b232008-07-26 00:20:22 +00002980 DoneWithDeclSpec:
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002981 if (!AttrsLastTime)
2982 ProhibitAttributes(attrs);
Michael Han64536a62012-11-06 19:34:54 +00002983 else {
2984 // Reject C++11 attributes that appertain to decl specifiers as
2985 // we don't support any C++11 attributes that appertain to decl
2986 // specifiers. This also conforms to what g++ 4.8 is doing.
Richard Smith49cc1cc2016-08-18 21:59:42 +00002987 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
Michael Han64536a62012-11-06 19:34:54 +00002988
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002989 DS.takeAttributesFrom(attrs);
Michael Han64536a62012-11-06 19:34:54 +00002990 }
Peter Collingbourne70188b32011-09-29 18:03:57 +00002991
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002992 // If this is not a declaration specifier token, we're done reading decl
2993 // specifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00002994 DS.Finish(Actions, Policy);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002995 return;
Mike Stump11289f42009-09-09 15:08:12 +00002996
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002997 case tok::l_square:
2998 case tok::kw_alignas:
Aaron Ballman606093a2017-10-15 15:01:42 +00002999 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003000 goto DoneWithDeclSpec;
3001
3002 ProhibitAttributes(attrs);
3003 // FIXME: It would be good to recover by accepting the attributes,
3004 // but attempting to do that now would cause serious
3005 // madness in terms of diagnostics.
3006 attrs.clear();
3007 attrs.Range = SourceRange();
3008
3009 ParseCXX11Attributes(attrs);
3010 AttrsLastTime = true;
Chad Rosierc1183952012-06-26 22:30:43 +00003011 continue;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003012
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003013 case tok::code_completion: {
John McCallfaf5fb42010-08-26 23:41:50 +00003014 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003015 if (DS.hasTypeSpecifier()) {
3016 bool AllowNonIdentifiers
3017 = (getCurScope()->getFlags() & (Scope::ControlScope |
3018 Scope::BlockScope |
3019 Scope::TemplateParamScope |
3020 Scope::FunctionPrototypeScope |
3021 Scope::AtCatchScope)) == 0;
3022 bool AllowNestedNameSpecifiers
Faisal Vali7db85c52017-12-31 00:06:40 +00003023 = DSContext == DeclSpecContext::DSC_top_level ||
3024 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003025
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003026 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
Chad Rosierc1183952012-06-26 22:30:43 +00003027 AllowNonIdentifiers,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003028 AllowNestedNameSpecifiers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003029 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00003030 }
3031
Douglas Gregor80039242011-02-15 20:33:25 +00003032 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3033 CCC = Sema::PCC_LocalDeclarationSpecifiers;
3034 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
Faisal Vali7db85c52017-12-31 00:06:40 +00003035 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3036 : Sema::PCC_Template;
3037 else if (DSContext == DeclSpecContext::DSC_class)
John McCallfaf5fb42010-08-26 23:41:50 +00003038 CCC = Sema::PCC_Class;
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +00003039 else if (CurParsedObjCImpl)
John McCallfaf5fb42010-08-26 23:41:50 +00003040 CCC = Sema::PCC_ObjCImplementation;
Chad Rosierc1183952012-06-26 22:30:43 +00003041
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003042 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003043 return cutOffParsing();
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003044 }
3045
Chris Lattnerbd31aa32009-01-05 00:07:25 +00003046 case tok::coloncolon: // ::foo::bar
John McCall1f476a12010-02-26 08:45:28 +00003047 // C++ scope specifier. Annotate and loop, or bail out on error.
Eli Friedman2a1d9a92013-08-15 23:59:20 +00003048 if (TryAnnotateCXXScopeToken(EnteringContext)) {
John McCall1f476a12010-02-26 08:45:28 +00003049 if (!DS.hasTypeSpecifier())
3050 DS.SetTypeSpecError();
3051 goto DoneWithDeclSpec;
3052 }
John McCall8bc2a702010-03-01 18:20:46 +00003053 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3054 goto DoneWithDeclSpec;
John McCall1f476a12010-02-26 08:45:28 +00003055 continue;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003056
3057 case tok::annot_cxxscope: {
Richard Smith3092a3b2012-05-09 18:56:43 +00003058 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003059 goto DoneWithDeclSpec;
3060
John McCall9dab4e62009-12-12 11:40:51 +00003061 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00003062 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3063 Tok.getAnnotationRange(),
3064 SS);
John McCall9dab4e62009-12-12 11:40:51 +00003065
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003066 // We are looking for a qualified typename.
Douglas Gregor167fa622009-03-25 15:40:00 +00003067 Token Next = NextToken();
Mike Stump11289f42009-09-09 15:08:12 +00003068 if (Next.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003069 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
Douglas Gregorb67535d2009-03-31 00:43:58 +00003070 ->Kind == TNK_Type_template) {
Douglas Gregor167fa622009-03-25 15:40:00 +00003071 // We have a qualified template-id, e.g., N::A<int>
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003072
Richard Smith74f02342017-01-19 21:00:13 +00003073 // If this would be a valid constructor declaration with template
3074 // arguments, we will reject the attempt to form an invalid type-id
3075 // referring to the injected-class-name when we annotate the token,
3076 // per C++ [class.qual]p2.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003077 //
Richard Smith74f02342017-01-19 21:00:13 +00003078 // To improve diagnostics for this case, parse the declaration as a
3079 // constructor (and reject the extra template arguments later).
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003080 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
Faisal Vali7db85c52017-12-31 00:06:40 +00003081 if ((DSContext == DeclSpecContext::DSC_top_level ||
3082 DSContext == DeclSpecContext::DSC_class) &&
John McCall84821e72010-04-13 06:39:49 +00003083 TemplateId->Name &&
Richard Smith74f02342017-01-19 21:00:13 +00003084 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003085 isConstructorDeclarator(/*Unqualified*/ false)) {
Richard Smith74f02342017-01-19 21:00:13 +00003086 // The user meant this to be an out-of-line constructor
3087 // definition, but template arguments are not allowed
3088 // there. Just allow this as a constructor; we'll
3089 // complain about it later.
3090 goto DoneWithDeclSpec;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003091 }
3092
John McCall9dab4e62009-12-12 11:40:51 +00003093 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003094 ConsumeAnnotationToken(); // The C++ scope.
Mike Stump11289f42009-09-09 15:08:12 +00003095 assert(Tok.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003096 "ParseOptionalCXXScopeSpecifier not working");
Douglas Gregore7c20652011-03-02 00:47:37 +00003097 AnnotateTemplateIdTokenAsType();
Douglas Gregor167fa622009-03-25 15:40:00 +00003098 continue;
3099 }
3100
Douglas Gregorc5790df2009-09-28 07:26:33 +00003101 if (Next.is(tok::annot_typename)) {
John McCall9dab4e62009-12-12 11:40:51 +00003102 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003103 ConsumeAnnotationToken(); // The C++ scope.
John McCallba7bf592010-08-24 05:47:05 +00003104 if (Tok.getAnnotationValue()) {
3105 ParsedType T = getTypeAnnotation(Tok);
Nico Weber77430342010-11-22 10:30:56 +00003106 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
Chad Rosierc1183952012-06-26 22:30:43 +00003107 Tok.getAnnotationEndLoc(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003108 PrevSpec, DiagID, T, Policy);
Richard Smithda837032012-09-14 18:27:01 +00003109 if (isInvalid)
3110 break;
John McCallba7bf592010-08-24 05:47:05 +00003111 }
Douglas Gregorc5790df2009-09-28 07:26:33 +00003112 else
3113 DS.SetTypeSpecError();
3114 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003115 ConsumeAnnotationToken(); // The typename
Douglas Gregorc5790df2009-09-28 07:26:33 +00003116 }
3117
Douglas Gregor167fa622009-03-25 15:40:00 +00003118 if (Next.isNot(tok::identifier))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003119 goto DoneWithDeclSpec;
3120
Richard Smith74f02342017-01-19 21:00:13 +00003121 // Check whether this is a constructor declaration. If we're in a
3122 // context where the identifier could be a class name, and it has the
3123 // shape of a constructor declaration, process it as one.
Faisal Vali7db85c52017-12-31 00:06:40 +00003124 if ((DSContext == DeclSpecContext::DSC_top_level ||
3125 DSContext == DeclSpecContext::DSC_class) &&
Chad Rosierc1183952012-06-26 22:30:43 +00003126 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
Richard Smith74f02342017-01-19 21:00:13 +00003127 &SS) &&
3128 isConstructorDeclarator(/*Unqualified*/ false))
3129 goto DoneWithDeclSpec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003130
David Blaikieefdccaa2016-01-15 23:43:34 +00003131 ParsedType TypeRep =
3132 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3133 getCurScope(), &SS, false, false, nullptr,
3134 /*IsCtorOrDtorName=*/false,
Richard Smith600b5262017-01-26 20:40:47 +00003135 /*WantNonTrivialSourceInfo=*/true,
3136 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003137
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003138 // If the referenced identifier is not a type, then this declspec is
3139 // erroneous: We already checked about that it has no type specifier, and
3140 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
Mike Stump11289f42009-09-09 15:08:12 +00003141 // typename.
David Blaikie7d170102013-05-15 07:37:26 +00003142 if (!TypeRep) {
Richard Smithaf3b3252017-05-18 19:21:48 +00003143 // Eat the scope spec so the identifier is current.
3144 ConsumeAnnotationToken();
Michael Han9407e502012-11-26 22:54:45 +00003145 ParsedAttributesWithRange Attrs(AttrFactory);
3146 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3147 if (!Attrs.empty()) {
3148 AttrsLastTime = true;
3149 attrs.takeAllFrom(Attrs);
3150 }
3151 continue;
3152 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003153 goto DoneWithDeclSpec;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003154 }
Mike Stump11289f42009-09-09 15:08:12 +00003155
John McCall9dab4e62009-12-12 11:40:51 +00003156 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003157 ConsumeAnnotationToken(); // The C++ scope.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003158
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003159 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003160 DiagID, TypeRep, Policy);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003161 if (isInvalid)
3162 break;
Mike Stump11289f42009-09-09 15:08:12 +00003163
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003164 DS.SetRangeEnd(Tok.getLocation());
3165 ConsumeToken(); // The typename.
3166
3167 continue;
3168 }
Mike Stump11289f42009-09-09 15:08:12 +00003169
Chris Lattnere387d9e2009-01-21 19:48:37 +00003170 case tok::annot_typename: {
Richard Smith404dfb42013-11-19 22:47:36 +00003171 // If we've previously seen a tag definition, we were almost surely
3172 // missing a semicolon after it.
3173 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3174 goto DoneWithDeclSpec;
3175
John McCallba7bf592010-08-24 05:47:05 +00003176 if (Tok.getAnnotationValue()) {
3177 ParsedType T = getTypeAnnotation(Tok);
Nico Weber7f8bb362010-11-22 12:50:03 +00003178 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003179 DiagID, T, Policy);
John McCallba7bf592010-08-24 05:47:05 +00003180 } else
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003181 DS.SetTypeSpecError();
Chad Rosierc1183952012-06-26 22:30:43 +00003182
Chris Lattner005fc1b2010-04-05 18:18:31 +00003183 if (isInvalid)
3184 break;
3185
Chris Lattnere387d9e2009-01-21 19:48:37 +00003186 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003187 ConsumeAnnotationToken(); // The typename
Mike Stump11289f42009-09-09 15:08:12 +00003188
Chris Lattnere387d9e2009-01-21 19:48:37 +00003189 continue;
3190 }
Mike Stump11289f42009-09-09 15:08:12 +00003191
Douglas Gregor06873092011-04-28 15:48:45 +00003192 case tok::kw___is_signed:
3193 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3194 // typically treats it as a trait. If we see __is_signed as it appears
3195 // in libstdc++, e.g.,
3196 //
3197 // static const bool __is_signed;
3198 //
3199 // then treat __is_signed as an identifier rather than as a keyword.
Faisal Vali090da2d2018-01-01 18:23:28 +00003200 if (DS.getTypeSpecType() == TST_bool &&
Douglas Gregor06873092011-04-28 15:48:45 +00003201 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
Alp Toker47642d22013-12-03 06:13:01 +00003202 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3203 TryKeywordIdentFallback(true);
Douglas Gregor06873092011-04-28 15:48:45 +00003204
3205 // We're done with the declaration-specifiers.
3206 goto DoneWithDeclSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00003207
Chris Lattner16fac4f2008-07-26 01:18:38 +00003208 // typedef-name
Nikola Smiljanic67860242014-09-26 00:28:20 +00003209 case tok::kw___super:
David Blaikie15a430a2011-12-04 05:04:18 +00003210 case tok::kw_decltype:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003211 case tok::identifier: {
Reid Klecknerc582f012014-07-14 18:19:58 +00003212 // This identifier can only be a typedef name if we haven't already seen
3213 // a type-specifier. Without this check we misparse:
3214 // typedef int X; struct Y { short X; }; as 'short int'.
3215 if (DS.hasTypeSpecifier())
3216 goto DoneWithDeclSpec;
3217
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003218 // If the token is an identifier named "__declspec" and Microsoft
3219 // extensions are not enabled, it is likely that there will be cascading
3220 // parse errors if this really is a __declspec attribute. Attempt to
3221 // recognize that scenario and recover gracefully.
3222 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3223 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3224 Diag(Loc, diag::err_ms_attributes_not_enabled);
3225
3226 // The next token should be an open paren. If it is, eat the entire
3227 // attribute declaration and continue.
3228 if (NextToken().is(tok::l_paren)) {
3229 // Consume the __declspec identifier.
Richard Trieuba057372017-02-14 23:56:55 +00003230 ConsumeToken();
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003231
3232 // Eat the parens and everything between them.
3233 BalancedDelimiterTracker T(*this, tok::l_paren);
3234 if (T.consumeOpen()) {
3235 assert(false && "Not a left paren?");
3236 return;
3237 }
3238 T.skipToEnd();
3239 continue;
3240 }
3241 }
3242
Serge Pavlov458ea762014-07-16 05:16:52 +00003243 // In C++, check to see if this is a scope specifier like foo::bar::, if
3244 // so handle it as such. This is important for ctor parsing.
3245 if (getLangOpts().CPlusPlus) {
3246 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3247 DS.SetTypeSpecError();
3248 goto DoneWithDeclSpec;
3249 }
3250 if (!Tok.is(tok::identifier))
3251 continue;
3252 }
3253
John Thompson22334602010-02-05 00:12:22 +00003254 // Check for need to substitute AltiVec keyword tokens.
3255 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3256 break;
3257
Richard Smith3092a3b2012-05-09 18:56:43 +00003258 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3259 // allow the use of a typedef name as a type specifier.
3260 if (DS.isTypeAltiVecVector())
3261 goto DoneWithDeclSpec;
3262
Faisal Vali7db85c52017-12-31 00:06:40 +00003263 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3264 isObjCInstancetype()) {
Douglas Gregor5c0870a2015-06-19 23:18:00 +00003265 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3266 assert(TypeRep);
3267 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3268 DiagID, TypeRep, Policy);
3269 if (isInvalid)
3270 break;
3271
3272 DS.SetRangeEnd(Loc);
3273 ConsumeToken();
3274 continue;
3275 }
3276
Richard Smith715ee072018-06-20 21:58:20 +00003277 // If we're in a context where the identifier could be a class name,
3278 // check whether this is a constructor declaration.
3279 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3280 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3281 isConstructorDeclarator(/*Unqualified*/true))
3282 goto DoneWithDeclSpec;
3283
Richard Smith600b5262017-01-26 20:40:47 +00003284 ParsedType TypeRep = Actions.getTypeName(
3285 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3286 false, false, nullptr, false, false,
3287 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003288
Chris Lattner6cc055a2009-04-12 20:42:31 +00003289 // If this is not a typedef name, don't parse it as part of the declspec,
3290 // it must be an implicit int or an error.
John McCallba7bf592010-08-24 05:47:05 +00003291 if (!TypeRep) {
Michael Han9407e502012-11-26 22:54:45 +00003292 ParsedAttributesWithRange Attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +00003293 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
Michael Han9407e502012-11-26 22:54:45 +00003294 if (!Attrs.empty()) {
3295 AttrsLastTime = true;
3296 attrs.takeAllFrom(Attrs);
3297 }
3298 continue;
3299 }
Chris Lattner16fac4f2008-07-26 01:18:38 +00003300 goto DoneWithDeclSpec;
Chris Lattner6cc055a2009-04-12 20:42:31 +00003301 }
Douglas Gregor8bf42052009-02-09 18:46:07 +00003302
Richard Smith35845152017-02-07 01:37:30 +00003303 // Likewise, if this is a context where the identifier could be a template
3304 // name, check whether this is a deduction guide declaration.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003305 if (getLangOpts().CPlusPlus17 &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003306 (DSContext == DeclSpecContext::DSC_class ||
3307 DSContext == DeclSpecContext::DSC_top_level) &&
Richard Smith35845152017-02-07 01:37:30 +00003308 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3309 Tok.getLocation()) &&
3310 isConstructorDeclarator(/*Unqualified*/ true,
3311 /*DeductionGuide*/ true))
3312 goto DoneWithDeclSpec;
3313
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003314 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003315 DiagID, TypeRep, Policy);
Chris Lattner16fac4f2008-07-26 01:18:38 +00003316 if (isInvalid)
3317 break;
Mike Stump11289f42009-09-09 15:08:12 +00003318
Chris Lattner16fac4f2008-07-26 01:18:38 +00003319 DS.SetRangeEnd(Tok.getLocation());
3320 ConsumeToken(); // The identifier
3321
Douglas Gregore9d95f12015-07-07 03:57:35 +00003322 // Objective-C supports type arguments and protocol references
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003323 // following an Objective-C object or object pointer
3324 // type. Handle either one of them.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003325 if (Tok.is(tok::less) && getLangOpts().ObjC) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003326 SourceLocation NewEndLoc;
3327 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3328 Loc, TypeRep, /*consumeLastToken=*/true,
3329 NewEndLoc);
3330 if (NewTypeRep.isUsable()) {
3331 DS.UpdateTypeRep(NewTypeRep.get());
3332 DS.SetRangeEnd(NewEndLoc);
3333 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00003334 }
Chad Rosierc1183952012-06-26 22:30:43 +00003335
Steve Naroffcd5e7822008-09-22 10:28:57 +00003336 // Need to support trailing type qualifiers (e.g. "id<p> const").
3337 // If a type specifier follows, it will be diagnosed elsewhere.
3338 continue;
Chris Lattner16fac4f2008-07-26 01:18:38 +00003339 }
Douglas Gregor7f741122009-02-25 19:37:18 +00003340
3341 // type-name
3342 case tok::annot_template_id: {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003343 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorb67535d2009-03-31 00:43:58 +00003344 if (TemplateId->Kind != TNK_Type_template) {
Douglas Gregor7f741122009-02-25 19:37:18 +00003345 // This template-id does not refer to a type name, so we're
3346 // done with the type-specifiers.
3347 goto DoneWithDeclSpec;
3348 }
3349
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003350 // If we're in a context where the template-id could be a
3351 // constructor name or specialization, check whether this is a
3352 // constructor declaration.
Faisal Vali7db85c52017-12-31 00:06:40 +00003353 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00003354 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
Richard Smith446161b2014-03-03 21:12:53 +00003355 isConstructorDeclarator(TemplateId->SS.isEmpty()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003356 goto DoneWithDeclSpec;
3357
Douglas Gregor7f741122009-02-25 19:37:18 +00003358 // Turn the template-id annotation token into a type annotation
3359 // token, then try again to parse it as a type-specifier.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003360 AnnotateTemplateIdTokenAsType();
Douglas Gregor7f741122009-02-25 19:37:18 +00003361 continue;
3362 }
3363
Chris Lattnere37e2332006-08-15 04:50:22 +00003364 // GNU attributes support.
3365 case tok::kw___attribute:
Craig Topper161e4db2014-05-21 06:02:52 +00003366 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
Chris Lattnerb95cca02006-10-17 03:01:08 +00003367 continue;
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003368
3369 // Microsoft declspec support.
3370 case tok::kw___declspec:
Aaron Ballman068aa512015-05-20 20:58:33 +00003371 ParseMicrosoftDeclSpecs(DS.getAttributes());
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003372 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003373
Steve Naroff44ac7772008-12-25 14:16:32 +00003374 // Microsoft single token adornments.
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003375 case tok::kw___forceinline: {
Serge Pavlov750db652013-11-13 06:57:53 +00003376 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003377 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Richard Smithda837032012-09-14 18:27:01 +00003378 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00003379 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00003380 nullptr, 0, ParsedAttr::AS_Keyword);
Richard Smithda837032012-09-14 18:27:01 +00003381 break;
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003382 }
Eli Friedman53339e02009-06-08 23:27:34 +00003383
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003384 case tok::kw___unaligned:
3385 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3386 getLangOpts());
3387 break;
3388
Aaron Ballman317a77f2013-05-22 23:25:32 +00003389 case tok::kw___sptr:
3390 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00003391 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00003392 case tok::kw___ptr32:
Steve Narofff9c29d42008-12-25 14:41:26 +00003393 case tok::kw___w64:
Steve Naroff44ac7772008-12-25 14:16:32 +00003394 case tok::kw___cdecl:
3395 case tok::kw___stdcall:
3396 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00003397 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00003398 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00003399 case tok::kw___vectorcall:
John McCall53fa7142010-12-24 02:08:15 +00003400 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00003401 continue;
3402
Dawn Perchik335e16b2010-09-03 01:29:35 +00003403 // Borland single token adornments.
3404 case tok::kw___pascal:
John McCall53fa7142010-12-24 02:08:15 +00003405 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00003406 continue;
3407
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003408 // OpenCL single token adornments.
3409 case tok::kw___kernel:
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +00003410 ParseOpenCLKernelAttributes(DS.getAttributes());
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003411 continue;
3412
Douglas Gregor261a89b2015-06-19 17:51:05 +00003413 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00003414 case tok::kw__Nonnull:
3415 case tok::kw__Nullable:
3416 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00003417 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3418 continue;
3419
Douglas Gregorab209d82015-07-07 03:58:42 +00003420 // Objective-C 'kindof' types.
3421 case tok::kw___kindof:
3422 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00003423 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00003424 (void)ConsumeToken();
3425 continue;
3426
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003427 // storage-class-specifier
3428 case tok::kw_typedef:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003429 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003430 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003431 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003432 break;
3433 case tok::kw_extern:
Richard Smithb4a9e862013-04-12 22:46:28 +00003434 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003435 Diag(Tok, diag::ext_thread_before) << "extern";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003436 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003437 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003438 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003439 break;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003440 case tok::kw___private_extern__:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003441 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003442 Loc, PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003443 isStorageClass = true;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003444 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003445 case tok::kw_static:
Richard Smithb4a9e862013-04-12 22:46:28 +00003446 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003447 Diag(Tok, diag::ext_thread_before) << "static";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003448 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003449 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003450 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003451 break;
3452 case tok::kw_auto:
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003453 if (getLangOpts().CPlusPlus11) {
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003454 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003455 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003456 PrevSpec, DiagID, Policy);
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003457 if (!isInvalid)
Richard Smith58c74332011-09-04 19:54:14 +00003458 Diag(Tok, diag::ext_auto_storage_class)
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003459 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith58c74332011-09-04 19:54:14 +00003460 } else
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003461 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003462 DiagID, Policy);
Richard Smith58c74332011-09-04 19:54:14 +00003463 } else
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003464 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003465 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003466 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003467 break;
Richard Smithe301ba22015-11-11 02:02:15 +00003468 case tok::kw___auto_type:
3469 Diag(Tok, diag::ext_auto_type);
3470 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3471 DiagID, Policy);
3472 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003473 case tok::kw_register:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003474 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003475 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003476 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003477 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003478 case tok::kw_mutable:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003479 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003480 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003481 isStorageClass = true;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003482 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003483 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00003484 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3485 PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003486 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003487 break;
3488 case tok::kw_thread_local:
3489 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3490 PrevSpec, DiagID);
Sven van Haastregtc4100832018-04-24 14:47:29 +00003491 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003492 break;
3493 case tok::kw__Thread_local:
3494 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3495 Loc, PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003496 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003497 break;
Mike Stump11289f42009-09-09 15:08:12 +00003498
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003499 // function-specifier
3500 case tok::kw_inline:
Serge Pavlov750db652013-11-13 06:57:53 +00003501 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003502 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003503 case tok::kw_virtual:
Sven van Haastregt49ffffb2018-04-23 11:23:47 +00003504 // OpenCL C++ v1.0 s2.9: the virtual function qualifier is not supported.
3505 if (getLangOpts().OpenCLCPlusPlus) {
3506 DiagID = diag::err_openclcxx_virtual_function;
3507 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3508 isInvalid = true;
3509 }
3510 else {
3511 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3512 }
Douglas Gregor61956c42008-10-31 09:07:45 +00003513 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003514 case tok::kw_explicit:
Serge Pavlov750db652013-11-13 06:57:53 +00003515 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
Douglas Gregor61956c42008-10-31 09:07:45 +00003516 break;
Richard Smith0015f092013-01-17 22:16:11 +00003517 case tok::kw__Noreturn:
3518 if (!getLangOpts().C11)
3519 Diag(Loc, diag::ext_c11_noreturn);
Serge Pavlov750db652013-11-13 06:57:53 +00003520 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
Richard Smith0015f092013-01-17 22:16:11 +00003521 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003522
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003523 // alignment-specifier
3524 case tok::kw__Alignas:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003525 if (!getLangOpts().C11)
Jordan Rose58d54722012-06-30 21:33:57 +00003526 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003527 ParseAlignmentSpecifier(DS.getAttributes());
3528 continue;
3529
Anders Carlssoncd8db412009-05-06 04:46:28 +00003530 // friend
3531 case tok::kw_friend:
Faisal Vali7db85c52017-12-31 00:06:40 +00003532 if (DSContext == DeclSpecContext::DSC_class)
John McCall07e91c02009-08-06 02:15:43 +00003533 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3534 else {
3535 PrevSpec = ""; // not actually used by the diagnostic
3536 DiagID = diag::err_friend_invalid_in_context;
3537 isInvalid = true;
3538 }
Anders Carlssoncd8db412009-05-06 04:46:28 +00003539 break;
Mike Stump11289f42009-09-09 15:08:12 +00003540
Douglas Gregor26701a42011-09-09 02:06:17 +00003541 // Modules
3542 case tok::kw___module_private__:
3543 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3544 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003545
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00003546 // constexpr
3547 case tok::kw_constexpr:
3548 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3549 break;
3550
Chris Lattnere387d9e2009-01-21 19:48:37 +00003551 // type-specifier
3552 case tok::kw_short:
John McCall49bfce42009-08-03 20:12:06 +00003553 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003554 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003555 break;
3556 case tok::kw_long:
3557 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
John McCall49bfce42009-08-03 20:12:06 +00003558 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003559 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003560 else
John McCall49bfce42009-08-03 20:12:06 +00003561 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003562 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003563 break;
Francois Pichet84133e42011-04-28 01:59:37 +00003564 case tok::kw___int64:
3565 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003566 DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00003567 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003568 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00003569 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3570 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003571 break;
3572 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00003573 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3574 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003575 break;
3576 case tok::kw__Complex:
John McCall49bfce42009-08-03 20:12:06 +00003577 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3578 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003579 break;
3580 case tok::kw__Imaginary:
John McCall49bfce42009-08-03 20:12:06 +00003581 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3582 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003583 break;
3584 case tok::kw_void:
John McCall49bfce42009-08-03 20:12:06 +00003585 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003586 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003587 break;
3588 case tok::kw_char:
John McCall49bfce42009-08-03 20:12:06 +00003589 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003590 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003591 break;
3592 case tok::kw_int:
John McCall49bfce42009-08-03 20:12:06 +00003593 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003594 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003595 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00003596 case tok::kw___int128:
3597 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003598 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003599 break;
3600 case tok::kw_half:
3601 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003602 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003603 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003604 case tok::kw_float:
John McCall49bfce42009-08-03 20:12:06 +00003605 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003606 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003607 break;
3608 case tok::kw_double:
John McCall49bfce42009-08-03 20:12:06 +00003609 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003610 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003611 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00003612 case tok::kw__Float16:
3613 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3614 DiagID, Policy);
3615 break;
Leonard Chanf921d852018-06-04 16:07:52 +00003616 case tok::kw__Accum:
3617 if (!getLangOpts().FixedPoint) {
Leonard Chanab80f3c2018-06-14 14:53:51 +00003618 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
Leonard Chanf921d852018-06-04 16:07:52 +00003619 } else {
3620 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3621 DiagID, Policy);
3622 }
3623 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00003624 case tok::kw__Fract:
3625 if (!getLangOpts().FixedPoint) {
3626 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3627 } else {
3628 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3629 DiagID, Policy);
3630 }
3631 break;
3632 case tok::kw__Sat:
3633 if (!getLangOpts().FixedPoint) {
3634 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3635 } else {
3636 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3637 }
3638 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003639 case tok::kw___float128:
3640 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3641 DiagID, Policy);
3642 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003643 case tok::kw_wchar_t:
John McCall49bfce42009-08-03 20:12:06 +00003644 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003645 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003646 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00003647 case tok::kw_char8_t:
3648 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3649 DiagID, Policy);
3650 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003651 case tok::kw_char16_t:
John McCall49bfce42009-08-03 20:12:06 +00003652 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003653 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003654 break;
3655 case tok::kw_char32_t:
John McCall49bfce42009-08-03 20:12:06 +00003656 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003657 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003658 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003659 case tok::kw_bool:
3660 case tok::kw__Bool:
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003661 if (Tok.is(tok::kw_bool) &&
3662 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3663 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3664 PrevSpec = ""; // Not used by the diagnostic.
3665 DiagID = diag::err_bool_redeclaration;
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003666 // For better error recovery.
3667 Tok.setKind(tok::identifier);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003668 isInvalid = true;
3669 } else {
3670 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003671 DiagID, Policy);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003672 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003673 break;
3674 case tok::kw__Decimal32:
John McCall49bfce42009-08-03 20:12:06 +00003675 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003676 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003677 break;
3678 case tok::kw__Decimal64:
John McCall49bfce42009-08-03 20:12:06 +00003679 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003680 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003681 break;
3682 case tok::kw__Decimal128:
John McCall49bfce42009-08-03 20:12:06 +00003683 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003684 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003685 break;
John Thompson22334602010-02-05 00:12:22 +00003686 case tok::kw___vector:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003687 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003688 break;
3689 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003690 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003691 break;
Bill Seurercf2c96b2015-01-12 19:35:51 +00003692 case tok::kw___bool:
3693 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3694 break;
Xiuli Pan9c14e282016-01-09 12:53:17 +00003695 case tok::kw_pipe:
3696 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3697 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3698 // support the "pipe" word as identifier.
3699 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3700 goto DoneWithDeclSpec;
3701 }
3702 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3703 break;
Alexey Bader954ba212016-04-08 13:40:33 +00003704#define GENERIC_IMAGE_TYPE(ImgType, Id) \
3705 case tok::kw_##ImgType##_t: \
3706 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3707 DiagID, Policy); \
3708 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00003709#include "clang/Basic/OpenCLImageTypes.def"
John McCall39439732011-04-09 22:50:59 +00003710 case tok::kw___unknown_anytype:
Faisal Vali090da2d2018-01-01 18:23:28 +00003711 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003712 PrevSpec, DiagID, Policy);
John McCall39439732011-04-09 22:50:59 +00003713 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003714
3715 // class-specifier:
3716 case tok::kw_class:
3717 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00003718 case tok::kw___interface:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003719 case tok::kw_union: {
3720 tok::TokenKind Kind = Tok.getKind();
3721 ConsumeToken();
Michael Han9407e502012-11-26 22:54:45 +00003722
3723 // These are attributes following class specifiers.
3724 // To produce better diagnostic, we parse them when
3725 // parsing class specifier.
Bill Wendling44426052012-12-20 19:22:21 +00003726 ParsedAttributesWithRange Attributes(AttrFactory);
Richard Smithc5b05522012-03-12 07:56:15 +00003727 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
Bill Wendling44426052012-12-20 19:22:21 +00003728 EnteringContext, DSContext, Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003729
3730 // If there are attributes following class specifier,
3731 // take them over and handle them here.
Bill Wendling44426052012-12-20 19:22:21 +00003732 if (!Attributes.empty()) {
Michael Han9407e502012-11-26 22:54:45 +00003733 AttrsLastTime = true;
Bill Wendling44426052012-12-20 19:22:21 +00003734 attrs.takeAllFrom(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003735 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003736 continue;
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003737 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003738
3739 // enum-specifier:
3740 case tok::kw_enum:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003741 ConsumeToken();
Richard Smithc5b05522012-03-12 07:56:15 +00003742 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003743 continue;
Faisal Valia534f072018-04-26 00:42:40 +00003744
Chris Lattnere387d9e2009-01-21 19:48:37 +00003745 // cv-qualifier:
3746 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00003747 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003748 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003749 break;
3750 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00003751 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003752 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003753 break;
3754 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00003755 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003756 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003757 break;
3758
Douglas Gregor333489b2009-03-27 23:10:48 +00003759 // C++ typename-specifier:
3760 case tok::kw_typename:
John McCall1f476a12010-02-26 08:45:28 +00003761 if (TryAnnotateTypeOrScopeToken()) {
3762 DS.SetTypeSpecError();
3763 goto DoneWithDeclSpec;
3764 }
3765 if (!Tok.is(tok::kw_typename))
Douglas Gregor333489b2009-03-27 23:10:48 +00003766 continue;
3767 break;
3768
Chris Lattnere387d9e2009-01-21 19:48:37 +00003769 // GNU typeof support.
3770 case tok::kw_typeof:
3771 ParseTypeofSpecifier(DS);
3772 continue;
3773
David Blaikie15a430a2011-12-04 05:04:18 +00003774 case tok::annot_decltype:
Anders Carlsson74948d02009-06-24 17:47:40 +00003775 ParseDecltypeSpecifier(DS);
3776 continue;
3777
David Majnemer15b311c2016-06-14 03:20:28 +00003778 case tok::annot_pragma_pack:
3779 HandlePragmaPack();
3780 continue;
3781
3782 case tok::annot_pragma_ms_pragma:
3783 HandlePragmaMSPragma();
3784 continue;
3785
3786 case tok::annot_pragma_ms_vtordisp:
3787 HandlePragmaMSVtorDisp();
3788 continue;
3789
3790 case tok::annot_pragma_ms_pointers_to_members:
3791 HandlePragmaMSPointersToMembers();
3792 continue;
3793
Alexis Hunt4a257072011-05-19 05:37:45 +00003794 case tok::kw___underlying_type:
3795 ParseUnderlyingTypeSpecifier(DS);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003796 continue;
3797
3798 case tok::kw__Atomic:
Richard Smith8e1ac332013-03-28 01:55:44 +00003799 // C11 6.7.2.4/4:
3800 // If the _Atomic keyword is immediately followed by a left parenthesis,
3801 // it is interpreted as a type specifier (with a type name), not as a
3802 // type qualifier.
3803 if (NextToken().is(tok::l_paren)) {
3804 ParseAtomicSpecifier(DS);
3805 continue;
3806 }
3807 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3808 getLangOpts());
3809 break;
Alexis Hunt4a257072011-05-19 05:37:45 +00003810
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003811 // OpenCL access qualifiers:
3812 case tok::kw___read_only:
3813 case tok::kw___write_only:
3814 case tok::kw___read_write:
3815 // OpenCL C++ 1.0 s2.2: access qualifiers are reserved keywords.
3816 if (Actions.getLangOpts().OpenCLCPlusPlus) {
3817 DiagID = diag::err_openclcxx_reserved;
3818 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3819 isInvalid = true;
3820 }
3821 ParseOpenCLQualifiers(DS.getAttributes());
3822 break;
3823
3824 // OpenCL address space qualifiers:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003825 case tok::kw___generic:
3826 // generic address space is introduced only in OpenCL v2.0
3827 // see OpenCL C Spec v2.0 s6.5.5
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003828 if (Actions.getLangOpts().OpenCLVersion < 200 &&
3829 !Actions.getLangOpts().OpenCLCPlusPlus) {
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003830 DiagID = diag::err_opencl_unknown_type_specifier;
3831 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3832 isInvalid = true;
3833 break;
3834 };
Galina Kistanova77674252017-06-01 21:15:34 +00003835 LLVM_FALLTHROUGH;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003836 case tok::kw___private:
3837 case tok::kw___global:
3838 case tok::kw___local:
3839 case tok::kw___constant:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00003840 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003841 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003842
Steve Naroffcfdf6162008-06-05 00:02:44 +00003843 case tok::less:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003844 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
Chris Lattner0974b232008-07-26 00:20:22 +00003845 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3846 // but we support it.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003847 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
Chris Lattner0974b232008-07-26 00:20:22 +00003848 goto DoneWithDeclSpec;
Mike Stump11289f42009-09-09 15:08:12 +00003849
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003850 SourceLocation StartLoc = Tok.getLocation();
3851 SourceLocation EndLoc;
3852 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3853 if (Type.isUsable()) {
3854 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3855 PrevSpec, DiagID, Type.get(),
3856 Actions.getASTContext().getPrintingPolicy()))
3857 Diag(StartLoc, DiagID) << PrevSpec;
Fangrui Song6907ce22018-07-30 19:24:48 +00003858
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003859 DS.SetRangeEnd(EndLoc);
3860 } else {
3861 DS.SetTypeSpecError();
3862 }
Chad Rosierc1183952012-06-26 22:30:43 +00003863
Douglas Gregor06e41ae2010-10-21 23:17:00 +00003864 // Need to support trailing type qualifiers (e.g. "id<p> const").
3865 // If a type specifier follows, it will be diagnosed elsewhere.
3866 continue;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003867 }
John McCall49bfce42009-08-03 20:12:06 +00003868 // If the specifier wasn't legal, issue a diagnostic.
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003869 if (isInvalid) {
3870 assert(PrevSpec && "Method did not return previous specifier!");
John McCall49bfce42009-08-03 20:12:06 +00003871 assert(DiagID);
Chad Rosierc1183952012-06-26 22:30:43 +00003872
Nick Desaulniers150ca532018-10-03 23:09:29 +00003873 if (DiagID == diag::ext_duplicate_declspec ||
3874 DiagID == diag::ext_warn_duplicate_declspec)
Douglas Gregora05f5ab2010-08-23 14:34:43 +00003875 Diag(Tok, DiagID)
3876 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003877 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003878 Diag(Tok, DiagID) << getLangOpts().OpenCLCPlusPlus
3879 << getLangOpts().getOpenCLVersionTuple().getAsString()
3880 << PrevSpec << isStorageClass;
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003881 } else
Douglas Gregora05f5ab2010-08-23 14:34:43 +00003882 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003883 }
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003884
Chris Lattner2e232092008-03-13 06:29:04 +00003885 DS.SetRangeEnd(Tok.getLocation());
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003886 if (DiagID != diag::err_bool_redeclaration)
Volodymyr Sapsai9f7b5cc2018-04-10 18:29:47 +00003887 // After an error the next token can be an annotation token.
3888 ConsumeAnyToken();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003889
3890 AttrsLastTime = false;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003891 }
3892}
Douglas Gregoreb31f392008-12-01 23:54:00 +00003893
Chris Lattner70ae4912007-10-29 04:42:53 +00003894/// ParseStructDeclaration - Parse a struct declaration without the terminating
3895/// semicolon.
3896///
Chris Lattner90a26b02007-01-23 04:38:16 +00003897/// struct-declaration:
Aaron Ballman606093a2017-10-15 15:01:42 +00003898/// [C2x] attributes-specifier-seq[opt]
3899/// specifier-qualifier-list struct-declarator-list
Chris Lattner736ed5d2007-06-09 05:59:07 +00003900/// [GNU] __extension__ struct-declaration
Chris Lattner70ae4912007-10-29 04:42:53 +00003901/// [GNU] specifier-qualifier-list
Chris Lattner90a26b02007-01-23 04:38:16 +00003902/// struct-declarator-list:
3903/// struct-declarator
3904/// struct-declarator-list ',' struct-declarator
3905/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3906/// struct-declarator:
3907/// declarator
3908/// [GNU] declarator attributes[opt]
3909/// declarator[opt] ':' constant-expression
3910/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3911///
Benjamin Kramera39beb92014-09-03 11:06:10 +00003912void Parser::ParseStructDeclaration(
3913 ParsingDeclSpec &DS,
3914 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
Chad Rosierc1183952012-06-26 22:30:43 +00003915
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003916 if (Tok.is(tok::kw___extension__)) {
3917 // __extension__ silences extension warnings in the subexpression.
3918 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Steve Naroff97170802007-08-20 22:28:22 +00003919 ConsumeToken();
Benjamin Kramera39beb92014-09-03 11:06:10 +00003920 return ParseStructDeclaration(DS, FieldsCallback);
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003921 }
Mike Stump11289f42009-09-09 15:08:12 +00003922
Aaron Ballman606093a2017-10-15 15:01:42 +00003923 // Parse leading attributes.
3924 ParsedAttributesWithRange Attrs(AttrFactory);
3925 MaybeParseCXX11Attributes(Attrs);
3926 DS.takeAttributesFrom(Attrs);
3927
Steve Naroff97170802007-08-20 22:28:22 +00003928 // Parse the common specifier-qualifiers-list piece.
Steve Naroff97170802007-08-20 22:28:22 +00003929 ParseSpecifierQualifierList(DS);
Mike Stump11289f42009-09-09 15:08:12 +00003930
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003931 // If there are no declarators, this is a free-standing declaration
3932 // specifier. Let the actions module cope with it.
Chris Lattner76c72282007-10-09 17:33:22 +00003933 if (Tok.is(tok::semi)) {
Nico Weber7b837f52016-01-28 19:25:00 +00003934 RecordDecl *AnonRecord = nullptr;
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003935 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00003936 DS, AnonRecord);
3937 assert(!AnonRecord && "Did not expect anonymous struct or union here");
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003938 DS.complete(TheDecl);
Steve Naroff97170802007-08-20 22:28:22 +00003939 return;
3940 }
3941
3942 // Read struct-declarators until we find the semicolon.
John McCallcfefb6d2009-11-03 02:38:08 +00003943 bool FirstDeclarator = true;
Richard Smith8d06f422012-01-12 23:53:29 +00003944 SourceLocation CommaLoc;
Steve Naroff97170802007-08-20 22:28:22 +00003945 while (1) {
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003946 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
Richard Smith8d06f422012-01-12 23:53:29 +00003947 DeclaratorInfo.D.setCommaLoc(CommaLoc);
John McCallcfefb6d2009-11-03 02:38:08 +00003948
Bill Wendling44426052012-12-20 19:22:21 +00003949 // Attributes are only allowed here on successive declarators.
John McCall53fa7142010-12-24 02:08:15 +00003950 if (!FirstDeclarator)
3951 MaybeParseGNUAttributes(DeclaratorInfo.D);
Mike Stump11289f42009-09-09 15:08:12 +00003952
Steve Naroff97170802007-08-20 22:28:22 +00003953 /// struct-declarator: declarator
3954 /// struct-declarator: declarator[opt] ':' constant-expression
Chris Lattner17c3b1f2009-12-10 01:59:24 +00003955 if (Tok.isNot(tok::colon)) {
3956 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3957 ColonProtectionRAIIObject X(*this);
Chris Lattnera12405b2008-04-10 06:46:29 +00003958 ParseDeclarator(DeclaratorInfo.D);
Richard Smith3d1a94c2014-08-12 00:22:39 +00003959 } else
3960 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003961
Alp Toker8fbec672013-12-17 23:29:36 +00003962 if (TryConsumeToken(tok::colon)) {
John McCalldadc5752010-08-24 06:29:42 +00003963 ExprResult Res(ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00003964 if (Res.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00003965 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner32295d32008-04-10 06:15:14 +00003966 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003967 DeclaratorInfo.BitfieldSize = Res.get();
Steve Naroff97170802007-08-20 22:28:22 +00003968 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003969
Steve Naroff97170802007-08-20 22:28:22 +00003970 // If attributes exist after the declarator, parse them.
John McCall53fa7142010-12-24 02:08:15 +00003971 MaybeParseGNUAttributes(DeclaratorInfo.D);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003972
John McCallcfefb6d2009-11-03 02:38:08 +00003973 // We're done with this declarator; invoke the callback.
Benjamin Kramera39beb92014-09-03 11:06:10 +00003974 FieldsCallback(DeclaratorInfo);
John McCallcfefb6d2009-11-03 02:38:08 +00003975
Steve Naroff97170802007-08-20 22:28:22 +00003976 // If we don't have a comma, it is either the end of the list (a ';')
3977 // or an error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00003978 if (!TryConsumeToken(tok::comma, CommaLoc))
Chris Lattner70ae4912007-10-29 04:42:53 +00003979 return;
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003980
John McCallcfefb6d2009-11-03 02:38:08 +00003981 FirstDeclarator = false;
Steve Naroff97170802007-08-20 22:28:22 +00003982 }
Steve Naroff97170802007-08-20 22:28:22 +00003983}
3984
3985/// ParseStructUnionBody
3986/// struct-contents:
3987/// struct-declaration-list
3988/// [EXT] empty
3989/// [GNU] "struct-declaration-list" without terminatoring ';'
3990/// struct-declaration-list:
3991/// struct-declaration
3992/// struct-declaration-list struct-declaration
Chris Lattner535b8302008-06-21 19:39:06 +00003993/// [OBC] '@' 'defs' '(' class-name ')'
Steve Naroff97170802007-08-20 22:28:22 +00003994///
Chris Lattner1300fb92007-01-23 23:42:53 +00003995void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00003996 unsigned TagType, Decl *TagDecl) {
Jordan Rose1e879d82018-03-23 00:07:18 +00003997 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003998 "parsing struct/union body");
Andy Gibbs22e140b2013-04-03 09:31:19 +00003999 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
Mike Stump11289f42009-09-09 15:08:12 +00004000
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004001 BalancedDelimiterTracker T(*this, tok::l_brace);
4002 if (T.consumeOpen())
4003 return;
Mike Stump11289f42009-09-09 15:08:12 +00004004
Douglas Gregor658b9552009-01-09 22:42:13 +00004005 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004006 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004007
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004008 SmallVector<Decl *, 32> FieldDecls;
Chris Lattnera12405b2008-04-10 06:46:29 +00004009
Chris Lattner7b9ace62007-01-23 20:11:08 +00004010 // While we still have something to read, read the declarations in the struct.
Richard Smith752ada82015-11-17 23:32:01 +00004011 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4012 Tok.isNot(tok::eof)) {
Chris Lattner90a26b02007-01-23 04:38:16 +00004013 // Each iteration of this loop reads one struct-declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004014
Chris Lattner736ed5d2007-06-09 05:59:07 +00004015 // Check for extraneous top-level semicolon.
Chris Lattner76c72282007-10-09 17:33:22 +00004016 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004017 ConsumeExtraSemi(InsideStruct, TagType);
Chris Lattner36e46a22007-06-09 05:49:55 +00004018 continue;
4019 }
Chris Lattnera12405b2008-04-10 06:46:29 +00004020
Andy Gibbsc804e082013-04-03 09:46:04 +00004021 // Parse _Static_assert declaration.
4022 if (Tok.is(tok::kw__Static_assert)) {
4023 SourceLocation DeclEnd;
4024 ParseStaticAssertDeclaration(DeclEnd);
4025 continue;
4026 }
4027
Argyrios Kyrtzidis71c12fb2013-04-18 01:42:35 +00004028 if (Tok.is(tok::annot_pragma_pack)) {
4029 HandlePragmaPack();
4030 continue;
4031 }
4032
4033 if (Tok.is(tok::annot_pragma_align)) {
4034 HandlePragmaAlign();
4035 continue;
4036 }
4037
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004038 if (Tok.is(tok::annot_pragma_openmp)) {
Alexey Bataev587e1de2016-03-30 10:43:55 +00004039 // Result can be ignored, because it must be always empty.
4040 AccessSpecifier AS = AS_none;
4041 ParsedAttributesWithRange Attrs(AttrFactory);
4042 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004043 continue;
4044 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004045
John McCallcfefb6d2009-11-03 02:38:08 +00004046 if (!Tok.is(tok::at)) {
Benjamin Kramera39beb92014-09-03 11:06:10 +00004047 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4048 // Install the declarator into the current TagDecl.
4049 Decl *Field =
4050 Actions.ActOnField(getCurScope(), TagDecl,
4051 FD.D.getDeclSpec().getSourceRange().getBegin(),
4052 FD.D, FD.BitfieldSize);
4053 FieldDecls.push_back(Field);
4054 FD.complete(Field);
4055 };
John McCallcfefb6d2009-11-03 02:38:08 +00004056
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004057 // Parse all the comma separated declarators.
4058 ParsingDeclSpec DS(*this);
Benjamin Kramera39beb92014-09-03 11:06:10 +00004059 ParseStructDeclaration(DS, CFieldCallback);
Chris Lattner535b8302008-06-21 19:39:06 +00004060 } else { // Handle @defs
4061 ConsumeToken();
4062 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4063 Diag(Tok, diag::err_unexpected_at);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004064 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004065 continue;
4066 }
4067 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004068 ExpectAndConsume(tok::l_paren);
Chris Lattner535b8302008-06-21 19:39:06 +00004069 if (!Tok.is(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004070 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004071 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004072 continue;
4073 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004074 SmallVector<Decl *, 16> Fields;
Douglas Gregor0be31a22010-07-02 17:43:08 +00004075 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004076 Tok.getIdentifierInfo(), Fields);
Chris Lattner535b8302008-06-21 19:39:06 +00004077 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4078 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004079 ExpectAndConsume(tok::r_paren);
Mike Stump11289f42009-09-09 15:08:12 +00004080 }
Chris Lattner736ed5d2007-06-09 05:59:07 +00004081
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004082 if (TryConsumeToken(tok::semi))
4083 continue;
4084
4085 if (Tok.is(tok::r_brace)) {
Chris Lattner245c5332010-02-02 00:37:27 +00004086 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
Chris Lattner0c7e82d2007-06-09 05:54:40 +00004087 break;
Chris Lattner90a26b02007-01-23 04:38:16 +00004088 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004089
4090 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4091 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4092 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4093 // If we stopped at a ';', eat it.
4094 TryConsumeToken(tok::semi);
Chris Lattner90a26b02007-01-23 04:38:16 +00004095 }
Mike Stump11289f42009-09-09 15:08:12 +00004096
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004097 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +00004098
John McCall084e83d2011-03-24 11:26:52 +00004099 ParsedAttributes attrs(AttrFactory);
Chris Lattner90a26b02007-01-23 04:38:16 +00004100 // If attributes exist after struct contents, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004101 MaybeParseGNUAttributes(attrs);
Daniel Dunbar15619c72008-10-03 02:03:53 +00004102
Erich Keanec480f302018-07-12 21:09:05 +00004103 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4104 T.getOpenLocation(), T.getCloseLocation(), attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004105 StructScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004106 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
Chris Lattner90a26b02007-01-23 04:38:16 +00004107}
4108
Chris Lattner3b561a32006-08-13 00:12:11 +00004109/// ParseEnumSpecifier
Chris Lattner1890ac82006-08-13 01:16:23 +00004110/// enum-specifier: [C99 6.7.2.2]
Chris Lattner3b561a32006-08-13 00:12:11 +00004111/// 'enum' identifier[opt] '{' enumerator-list '}'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004112///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
Chris Lattnere37e2332006-08-15 04:50:22 +00004113/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4114/// '}' attributes[opt]
Aaron Ballman9ecff022012-03-01 04:09:28 +00004115/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4116/// '}'
Chris Lattner3b561a32006-08-13 00:12:11 +00004117/// 'enum' identifier
Chris Lattnere37e2332006-08-15 04:50:22 +00004118/// [GNU] 'enum' attributes[opt] identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004119///
Richard Smith7d137e32012-03-23 03:33:32 +00004120/// [C++11] enum-head '{' enumerator-list[opt] '}'
4121/// [C++11] enum-head '{' enumerator-list ',' '}'
Douglas Gregor0bf31402010-10-08 23:50:27 +00004122///
Richard Smith7d137e32012-03-23 03:33:32 +00004123/// enum-head: [C++11]
4124/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4125/// enum-key attribute-specifier-seq[opt] nested-name-specifier
4126/// identifier enum-base[opt]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004127///
Richard Smith7d137e32012-03-23 03:33:32 +00004128/// enum-key: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004129/// 'enum'
4130/// 'enum' 'class'
4131/// 'enum' 'struct'
4132///
Richard Smith7d137e32012-03-23 03:33:32 +00004133/// enum-base: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004134/// ':' type-specifier-seq
4135///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004136/// [C++] elaborated-type-specifier:
4137/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4138///
Chris Lattnerffaa0e62009-04-12 21:49:30 +00004139void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregordc70c3a2010-03-02 17:53:14 +00004140 const ParsedTemplateInfo &TemplateInfo,
Richard Smithc5b05522012-03-12 07:56:15 +00004141 AccessSpecifier AS, DeclSpecContext DSC) {
Chris Lattnerffbc2712007-01-25 06:05:38 +00004142 // Parse the tag portion of this.
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004143 if (Tok.is(tok::code_completion)) {
4144 // Code completion for an enum name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004145 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00004146 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004147 }
John McCallcb432fa2011-07-06 05:58:41 +00004148
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004149 // If attributes exist after tag, parse them.
4150 ParsedAttributesWithRange attrs(AttrFactory);
4151 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004152 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004153 MaybeParseMicrosoftDeclSpecs(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004154
Richard Smith0f8ee222012-01-10 01:33:14 +00004155 SourceLocation ScopedEnumKWLoc;
John McCallcb432fa2011-07-06 05:58:41 +00004156 bool IsScopedUsingClassTag = false;
4157
John McCallbeae29a2012-06-23 22:30:04 +00004158 // In C++11, recognize 'enum class' and 'enum struct'.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004159 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
Richard Trieud0d87b52013-04-23 02:47:36 +00004160 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4161 : diag::ext_scoped_enum);
John McCallcb432fa2011-07-06 05:58:41 +00004162 IsScopedUsingClassTag = Tok.is(tok::kw_class);
Richard Smith0f8ee222012-01-10 01:33:14 +00004163 ScopedEnumKWLoc = ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004164
Bill Wendling44426052012-12-20 19:22:21 +00004165 // Attributes are not allowed between these keywords. Diagnose,
John McCallbeae29a2012-06-23 22:30:04 +00004166 // but then just treat them like they appeared in the right place.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004167 ProhibitAttributes(attrs);
John McCallbeae29a2012-06-23 22:30:04 +00004168
4169 // They are allowed afterwards, though.
4170 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004171 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004172 MaybeParseMicrosoftDeclSpecs(attrs);
John McCallcb432fa2011-07-06 05:58:41 +00004173 }
Richard Smith7d137e32012-03-23 03:33:32 +00004174
John McCall6347b682012-05-07 06:16:58 +00004175 // C++11 [temp.explicit]p12:
4176 // The usual access controls do not apply to names used to specify
4177 // explicit instantiations.
4178 // We extend this to also cover explicit specializations. Note that
4179 // we don't suppress if this turns out to be an elaborated type
4180 // specifier.
4181 bool shouldDelayDiagsInTag =
4182 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4183 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4184 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Richard Smith7d137e32012-03-23 03:33:32 +00004185
Richard Smithbfdb1082012-03-12 08:56:40 +00004186 // Enum definitions should not be parsed in a trailing-return-type.
Faisal Vali7db85c52017-12-31 00:06:40 +00004187 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
Richard Smithbfdb1082012-03-12 08:56:40 +00004188
Abramo Bagnarad7548482010-05-19 21:37:53 +00004189 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004190 if (getLangOpts().CPlusPlus) {
John McCallcb432fa2011-07-06 05:58:41 +00004191 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4192 // if a fixed underlying type is allowed.
Erik Pilkington6f11db12018-09-28 20:24:58 +00004193 ColonProtectionRAIIObject X(*this, AllowDeclaration);
Chad Rosierc1183952012-06-26 22:30:43 +00004194
Nico Webercfaa4cd2015-02-15 07:26:13 +00004195 CXXScopeSpec Spec;
David Blaikieefdccaa2016-01-15 23:43:34 +00004196 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
Richard Smith1d4b2e12013-04-01 21:43:41 +00004197 /*EnteringContext=*/true))
John McCall1f476a12010-02-26 08:45:28 +00004198 return;
4199
Nico Webercfaa4cd2015-02-15 07:26:13 +00004200 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004201 Diag(Tok, diag::err_expected) << tok::identifier;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004202 if (Tok.isNot(tok::l_brace)) {
4203 // Has no name and is not a definition.
4204 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004205 SkipUntil(tok::comma, StopAtSemi);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004206 return;
4207 }
4208 }
Nico Webercfaa4cd2015-02-15 07:26:13 +00004209
4210 SS = Spec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004211 }
Mike Stump11289f42009-09-09 15:08:12 +00004212
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004213 // Must have either 'enum name' or 'enum {...}'.
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004214 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
Erik Pilkington6f11db12018-09-28 20:24:58 +00004215 !(AllowDeclaration && Tok.is(tok::colon))) {
Alp Tokerec543272013-12-24 09:48:30 +00004216 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
Mike Stump11289f42009-09-09 15:08:12 +00004217
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004218 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004219 SkipUntil(tok::comma, StopAtSemi);
Chris Lattner3b561a32006-08-13 00:12:11 +00004220 return;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004221 }
Mike Stump11289f42009-09-09 15:08:12 +00004222
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004223 // If an identifier is present, consume and remember it.
Craig Topper161e4db2014-05-21 06:02:52 +00004224 IdentifierInfo *Name = nullptr;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004225 SourceLocation NameLoc;
4226 if (Tok.is(tok::identifier)) {
4227 Name = Tok.getIdentifierInfo();
4228 NameLoc = ConsumeToken();
4229 }
Mike Stump11289f42009-09-09 15:08:12 +00004230
Richard Smith0f8ee222012-01-10 01:33:14 +00004231 if (!Name && ScopedEnumKWLoc.isValid()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00004232 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4233 // declaration of a scoped enumeration.
4234 Diag(Tok, diag::err_scoped_enum_missing_identifier);
Richard Smith0f8ee222012-01-10 01:33:14 +00004235 ScopedEnumKWLoc = SourceLocation();
Abramo Bagnara0e05e242010-12-03 18:54:17 +00004236 IsScopedUsingClassTag = false;
Douglas Gregor0bf31402010-10-08 23:50:27 +00004237 }
4238
John McCall6347b682012-05-07 06:16:58 +00004239 // Okay, end the suppression area. We'll decide whether to emit the
4240 // diagnostics in a second.
4241 if (shouldDelayDiagsInTag)
4242 diagsFromTag.done();
Richard Smith7d137e32012-03-23 03:33:32 +00004243
Douglas Gregor0bf31402010-10-08 23:50:27 +00004244 TypeResult BaseType;
4245
Douglas Gregord1f69f62010-12-01 17:42:47 +00004246 // Parse the fixed underlying type.
Richard Smith200f47c2012-07-02 19:14:01 +00004247 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
Erik Pilkington6f11db12018-09-28 20:24:58 +00004248 if (AllowDeclaration && Tok.is(tok::colon)) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004249 bool PossibleBitfield = false;
Richard Smith200f47c2012-07-02 19:14:01 +00004250 if (CanBeBitfield) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004251 // If we're in class scope, this can either be an enum declaration with
4252 // an underlying type, or a declaration of a bitfield member. We try to
4253 // use a simple disambiguation scheme first to catch the common cases
Chad Rosierc1183952012-06-26 22:30:43 +00004254 // (integer literal, sizeof); if it's still ambiguous, we then consider
4255 // anything that's a simple-type-specifier followed by '(' as an
4256 // expression. This suffices because function types are not valid
Douglas Gregord1f69f62010-12-01 17:42:47 +00004257 // underlying types anyway.
Faisal Valid143a0c2017-04-01 21:30:49 +00004258 EnterExpressionEvaluationContext Unevaluated(
4259 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregord1f69f62010-12-01 17:42:47 +00004260 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
Chad Rosierc1183952012-06-26 22:30:43 +00004261 // If the next token starts an expression, we know we're parsing a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004262 // bit-field. This is the common case.
Richard Smithee390432014-05-16 01:56:53 +00004263 if (TPR == TPResult::True)
Douglas Gregord1f69f62010-12-01 17:42:47 +00004264 PossibleBitfield = true;
4265 // If the next token starts a type-specifier-seq, it may be either a
4266 // a fixed underlying type or the start of a function-style cast in C++;
Chad Rosierc1183952012-06-26 22:30:43 +00004267 // lookahead one more token to see if it's obvious that we have a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004268 // fixed underlying type.
Richard Smithee390432014-05-16 01:56:53 +00004269 else if (TPR == TPResult::False &&
Douglas Gregord1f69f62010-12-01 17:42:47 +00004270 GetLookAheadToken(2).getKind() == tok::semi) {
4271 // Consume the ':'.
4272 ConsumeToken();
4273 } else {
4274 // We have the start of a type-specifier-seq, so we have to perform
4275 // tentative parsing to determine whether we have an expression or a
4276 // type.
4277 TentativeParsingAction TPA(*this);
4278
4279 // Consume the ':'.
4280 ConsumeToken();
Richard Smith1e3b0f02012-02-23 01:36:12 +00004281
4282 // If we see a type specifier followed by an open-brace, we have an
4283 // ambiguity between an underlying type and a C++11 braced
4284 // function-style cast. Resolve this by always treating it as an
4285 // underlying type.
4286 // FIXME: The standard is not entirely clear on how to disambiguate in
4287 // this case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004288 if ((getLangOpts().CPlusPlus &&
Richard Smithee390432014-05-16 01:56:53 +00004289 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00004290 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004291 // We'll parse this as a bitfield later.
4292 PossibleBitfield = true;
4293 TPA.Revert();
4294 } else {
4295 // We have a type-specifier-seq.
4296 TPA.Commit();
4297 }
4298 }
4299 } else {
4300 // Consume the ':'.
4301 ConsumeToken();
4302 }
4303
4304 if (!PossibleBitfield) {
4305 SourceRange Range;
4306 BaseType = ParseTypeName(&Range);
Chad Rosierc1183952012-06-26 22:30:43 +00004307
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004308 if (!getLangOpts().ObjC) {
Erik Pilkington6f11db12018-09-28 20:24:58 +00004309 if (getLangOpts().CPlusPlus11)
4310 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4311 else if (getLangOpts().CPlusPlus)
4312 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4313 else if (getLangOpts().MicrosoftExt)
4314 Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004315 else
Erik Pilkington6f11db12018-09-28 20:24:58 +00004316 Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004317 }
Douglas Gregord1f69f62010-12-01 17:42:47 +00004318 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004319 }
4320
Richard Smith0f8ee222012-01-10 01:33:14 +00004321 // There are four options here. If we have 'friend enum foo;' then this is a
4322 // friend declaration, and cannot have an accompanying definition. If we have
4323 // 'enum foo;', then this is a forward declaration. If we have
4324 // 'enum foo {...' then this is a definition. Otherwise we have something
4325 // like 'enum foo xyz', a reference.
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004326 //
4327 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4328 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4329 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4330 //
John McCallfaf5fb42010-08-26 23:41:50 +00004331 Sema::TagUseKind TUK;
John McCall6347b682012-05-07 06:16:58 +00004332 if (!AllowDeclaration) {
Richard Smithbfdb1082012-03-12 08:56:40 +00004333 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004334 } else if (Tok.is(tok::l_brace)) {
4335 if (DS.isFriendSpecified()) {
4336 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4337 << SourceRange(DS.getFriendSpecLoc());
4338 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004339 SkipUntil(tok::r_brace, StopAtSemi);
John McCall6347b682012-05-07 06:16:58 +00004340 TUK = Sema::TUK_Friend;
4341 } else {
4342 TUK = Sema::TUK_Definition;
4343 }
Richard Smith649c7b062014-01-08 00:56:48 +00004344 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00004345 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00004346 (Tok.isAtStartOfLine() &&
4347 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
Richard Smith369b9f92012-06-25 21:37:02 +00004348 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4349 if (Tok.isNot(tok::semi)) {
4350 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00004351 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004352 PP.EnterToken(Tok);
4353 Tok.setKind(tok::semi);
4354 }
John McCall6347b682012-05-07 06:16:58 +00004355 } else {
John McCallfaf5fb42010-08-26 23:41:50 +00004356 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004357 }
4358
4359 // If this is an elaborated type specifier, and we delayed
4360 // diagnostics before, just merge them into the current pool.
4361 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4362 diagsFromTag.redelay();
4363 }
Richard Smith7d137e32012-03-23 03:33:32 +00004364
4365 MultiTemplateParamsArg TParams;
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004366 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
John McCallfaf5fb42010-08-26 23:41:50 +00004367 TUK != Sema::TUK_Reference) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004368 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
Richard Smith7d137e32012-03-23 03:33:32 +00004369 // Skip the rest of this declarator, up until the comma or semicolon.
4370 Diag(Tok, diag::err_enum_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004371 SkipUntil(tok::comma, StopAtSemi);
Richard Smith7d137e32012-03-23 03:33:32 +00004372 return;
4373 }
4374
4375 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4376 // Enumerations can't be explicitly instantiated.
4377 DS.SetTypeSpecError();
4378 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4379 return;
4380 }
4381
4382 assert(TemplateInfo.TemplateParams && "no template parameters");
4383 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4384 TemplateInfo.TemplateParams->size());
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004385 }
Chad Rosierc1183952012-06-26 22:30:43 +00004386
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004387 if (TUK == Sema::TUK_Reference)
4388 ProhibitAttributes(attrs);
Richard Smith7d137e32012-03-23 03:33:32 +00004389
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004390 if (!Name && TUK != Sema::TUK_Definition) {
4391 Diag(Tok, diag::err_enumerator_unnamed_no_def);
Richard Smith7d137e32012-03-23 03:33:32 +00004392
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004393 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004394 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004395 return;
4396 }
Richard Smith7d137e32012-03-23 03:33:32 +00004397
Nico Weber32a0fc72016-09-03 03:01:32 +00004398 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00004399
Richard Smithd9ba2242015-05-07 03:54:19 +00004400 Sema::SkipBodyInfo SkipBody;
4401 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4402 NextToken().is(tok::identifier))
4403 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4404 NextToken().getIdentifierInfo(),
4405 NextToken().getLocation());
4406
Douglas Gregord6ab8742009-05-28 23:31:59 +00004407 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004408 bool IsDependent = false;
Craig Topper161e4db2014-05-21 06:02:52 +00004409 const char *PrevSpec = nullptr;
Douglas Gregorba41d012010-04-24 16:38:41 +00004410 unsigned DiagID;
Faisal Vali7db85c52017-12-31 00:06:40 +00004411 Decl *TagDecl = Actions.ActOnTag(
4412 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
Erich Keanec480f302018-07-12 21:09:05 +00004413 attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4414 ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
Faisal Vali7db85c52017-12-31 00:06:40 +00004415 DSC == DeclSpecContext::DSC_type_specifier,
4416 DSC == DeclSpecContext::DSC_template_param ||
4417 DSC == DeclSpecContext::DSC_template_type_arg,
4418 &SkipBody);
Richard Smithd9ba2242015-05-07 03:54:19 +00004419
4420 if (SkipBody.ShouldSkip) {
4421 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4422
4423 BalancedDelimiterTracker T(*this, tok::l_brace);
4424 T.consumeOpen();
4425 T.skipToEnd();
4426
4427 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4428 NameLoc.isValid() ? NameLoc : StartLoc,
4429 PrevSpec, DiagID, TagDecl, Owned,
4430 Actions.getASTContext().getPrintingPolicy()))
4431 Diag(StartLoc, DiagID) << PrevSpec;
4432 return;
4433 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004434
Douglas Gregorba41d012010-04-24 16:38:41 +00004435 if (IsDependent) {
Chad Rosierc1183952012-06-26 22:30:43 +00004436 // This enum has a dependent nested-name-specifier. Handle it as a
Douglas Gregorba41d012010-04-24 16:38:41 +00004437 // dependent tag.
4438 if (!Name) {
4439 DS.SetTypeSpecError();
4440 Diag(Tok, diag::err_expected_type_name_after_typename);
4441 return;
4442 }
Chad Rosierc1183952012-06-26 22:30:43 +00004443
Nico Weber83ea0122014-05-03 21:57:40 +00004444 TypeResult Type = Actions.ActOnDependentTag(
4445 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
Douglas Gregorba41d012010-04-24 16:38:41 +00004446 if (Type.isInvalid()) {
4447 DS.SetTypeSpecError();
4448 return;
4449 }
Chad Rosierc1183952012-06-26 22:30:43 +00004450
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004451 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4452 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004453 PrevSpec, DiagID, Type.get(),
4454 Actions.getASTContext().getPrintingPolicy()))
Douglas Gregorba41d012010-04-24 16:38:41 +00004455 Diag(StartLoc, DiagID) << PrevSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00004456
Douglas Gregorba41d012010-04-24 16:38:41 +00004457 return;
4458 }
Mike Stump11289f42009-09-09 15:08:12 +00004459
John McCall48871652010-08-21 09:40:31 +00004460 if (!TagDecl) {
Chad Rosierc1183952012-06-26 22:30:43 +00004461 // The action failed to produce an enumeration tag. If this is a
Douglas Gregorba41d012010-04-24 16:38:41 +00004462 // definition, consume the entire definition.
Richard Smithbfdb1082012-03-12 08:56:40 +00004463 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
Douglas Gregorba41d012010-04-24 16:38:41 +00004464 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004465 SkipUntil(tok::r_brace, StopAtSemi);
Douglas Gregorba41d012010-04-24 16:38:41 +00004466 }
Chad Rosierc1183952012-06-26 22:30:43 +00004467
Douglas Gregorba41d012010-04-24 16:38:41 +00004468 DS.SetTypeSpecError();
4469 return;
4470 }
Richard Smith0f8ee222012-01-10 01:33:14 +00004471
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004472 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4473 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4474 ParseEnumBody(StartLoc, D);
4475 if (SkipBody.CheckSameAsPrevious &&
4476 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4477 DS.SetTypeSpecError();
4478 return;
4479 }
4480 }
Mike Stump11289f42009-09-09 15:08:12 +00004481
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004482 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4483 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004484 PrevSpec, DiagID, TagDecl, Owned,
4485 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00004486 Diag(StartLoc, DiagID) << PrevSpec;
Chris Lattner3b561a32006-08-13 00:12:11 +00004487}
4488
Chris Lattnerc1915e22007-01-25 07:29:02 +00004489/// ParseEnumBody - Parse a {} enclosed enumerator-list.
4490/// enumerator-list:
4491/// enumerator
4492/// enumerator-list ',' enumerator
4493/// enumerator:
Aaron Ballman730476b2014-11-08 15:33:35 +00004494/// enumeration-constant attributes[opt]
4495/// enumeration-constant attributes[opt] '=' constant-expression
Chris Lattnerc1915e22007-01-25 07:29:02 +00004496/// enumeration-constant:
4497/// identifier
4498///
John McCall48871652010-08-21 09:40:31 +00004499void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004500 // Enter the scope of the enum body and start the definition.
Hans Wennborgfe781452014-06-17 00:00:18 +00004501 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004502 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
Douglas Gregor07665a62009-01-05 19:45:36 +00004503
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004504 BalancedDelimiterTracker T(*this, tok::l_brace);
4505 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00004506
Chris Lattner37256fb2007-08-27 17:24:30 +00004507 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
David Blaikiebbafb8a2012-03-11 07:00:24 +00004508 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
Richard Smithf8812672016-12-02 22:38:31 +00004509 Diag(Tok, diag::err_empty_enum);
Mike Stump11289f42009-09-09 15:08:12 +00004510
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004511 SmallVector<Decl *, 32> EnumConstantDecls;
Jordan Rose60ac3162015-04-30 17:20:30 +00004512 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
Chris Lattnerc1915e22007-01-25 07:29:02 +00004513
Craig Topper161e4db2014-05-21 06:02:52 +00004514 Decl *LastEnumConstDecl = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004515
Chris Lattnerc1915e22007-01-25 07:29:02 +00004516 // Parse the enumerator-list.
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004517 while (Tok.isNot(tok::r_brace)) {
4518 // Parse enumerator. If failed, try skipping till the start of the next
4519 // enumerator definition.
4520 if (Tok.isNot(tok::identifier)) {
4521 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4522 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4523 TryConsumeToken(tok::comma))
4524 continue;
4525 break;
4526 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004527 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4528 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00004529
John McCall811a0f52010-10-22 23:36:17 +00004530 // If attributes exist after the enumerator, parse them.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004531 ParsedAttributesWithRange attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004532 MaybeParseGNUAttributes(attrs);
Aaron Ballman730476b2014-11-08 15:33:35 +00004533 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
Aaron Ballman606093a2017-10-15 15:01:42 +00004534 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4535 if (getLangOpts().CPlusPlus)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004536 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Aaron Ballman606093a2017-10-15 15:01:42 +00004537 ? diag::warn_cxx14_compat_ns_enum_attribute
4538 : diag::ext_ns_enum_attribute)
4539 << 1 /*enumerator*/;
Aaron Ballman730476b2014-11-08 15:33:35 +00004540 ParseCXX11Attributes(attrs);
4541 }
John McCall811a0f52010-10-22 23:36:17 +00004542
Chris Lattnerc1915e22007-01-25 07:29:02 +00004543 SourceLocation EqualLoc;
John McCalldadc5752010-08-24 06:29:42 +00004544 ExprResult AssignedVal;
Jordan Rose60ac3162015-04-30 17:20:30 +00004545 EnumAvailabilityDiags.emplace_back(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00004546
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004547 if (TryConsumeToken(tok::equal, EqualLoc)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004548 AssignedVal = ParseConstantExpression();
4549 if (AssignedVal.isInvalid())
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004550 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
Chris Lattnerc1915e22007-01-25 07:29:02 +00004551 }
Mike Stump11289f42009-09-09 15:08:12 +00004552
Chris Lattnerc1915e22007-01-25 07:29:02 +00004553 // Install the enumerator constant into EnumDecl.
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004554 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
Erich Keanec480f302018-07-12 21:09:05 +00004555 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4556 EqualLoc, AssignedVal.get());
Jordan Rose60ac3162015-04-30 17:20:30 +00004557 EnumAvailabilityDiags.back().done();
Chad Rosierc1183952012-06-26 22:30:43 +00004558
Chris Lattner4ef40012007-06-11 01:28:17 +00004559 EnumConstantDecls.push_back(EnumConstDecl);
4560 LastEnumConstDecl = EnumConstDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004561
Douglas Gregorce66d022010-09-07 14:51:08 +00004562 if (Tok.is(tok::identifier)) {
4563 // We're missing a comma between enumerators.
Richard Smithbdb84f32016-07-22 23:36:59 +00004564 SourceLocation Loc = getEndOfPreviousToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004565 Diag(Loc, diag::err_enumerator_list_missing_comma)
Douglas Gregorce66d022010-09-07 14:51:08 +00004566 << FixItHint::CreateInsertion(Loc, ", ");
4567 continue;
4568 }
Chad Rosierc1183952012-06-26 22:30:43 +00004569
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004570 // Emumerator definition must be finished, only comma or r_brace are
4571 // allowed here.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004572 SourceLocation CommaLoc;
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004573 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4574 if (EqualLoc.isValid())
4575 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4576 << tok::comma;
4577 else
4578 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4579 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4580 if (TryConsumeToken(tok::comma, CommaLoc))
4581 continue;
4582 } else {
4583 break;
4584 }
4585 }
Mike Stump11289f42009-09-09 15:08:12 +00004586
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004587 // If comma is followed by r_brace, emit appropriate warning.
4588 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004589 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
Richard Smith87f5dc52012-07-23 05:45:25 +00004590 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4591 diag::ext_enumerator_list_comma_cxx :
4592 diag::ext_enumerator_list_comma_c)
Richard Smith5d164bc2011-10-15 05:09:34 +00004593 << FixItHint::CreateRemoval(CommaLoc);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004594 else if (getLangOpts().CPlusPlus11)
Richard Smith5d164bc2011-10-15 05:09:34 +00004595 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4596 << FixItHint::CreateRemoval(CommaLoc);
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004597 break;
Richard Smith5d164bc2011-10-15 05:09:34 +00004598 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004599 }
Mike Stump11289f42009-09-09 15:08:12 +00004600
Chris Lattnerc1915e22007-01-25 07:29:02 +00004601 // Eat the }.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004602 T.consumeClose();
Chris Lattnerc1915e22007-01-25 07:29:02 +00004603
Chris Lattnerc1915e22007-01-25 07:29:02 +00004604 // If attributes exist after the identifier list, parse them.
John McCall084e83d2011-03-24 11:26:52 +00004605 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004606 MaybeParseGNUAttributes(attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004607
Erich Keanec480f302018-07-12 21:09:05 +00004608 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4609 getCurScope(), attrs);
Mike Stump11289f42009-09-09 15:08:12 +00004610
Jordan Rose60ac3162015-04-30 17:20:30 +00004611 // Now handle enum constant availability diagnostics.
4612 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4613 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4614 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4615 EnumAvailabilityDiags[i].redelay();
4616 PD.complete(EnumConstantDecls[i]);
4617 }
4618
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004619 EnumScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004620 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
Richard Smith369b9f92012-06-25 21:37:02 +00004621
4622 // The next token must be valid after an enum definition. If not, a ';'
4623 // was probably forgotten.
Richard Smith200f47c2012-07-02 19:14:01 +00004624 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4625 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
Alp Toker383d2c42014-01-01 03:08:43 +00004626 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004627 // Push this token back into the preprocessor and change our current token
4628 // to ';' so that the rest of the code recovers as though there were an
4629 // ';' after the definition.
4630 PP.EnterToken(Tok);
4631 Tok.setKind(tok::semi);
4632 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004633}
Chris Lattner3b561a32006-08-13 00:12:11 +00004634
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004635/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4636/// is definitely a type-specifier. Return false if it isn't part of a type
4637/// specifier or if we're not sure.
4638bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4639 switch (Tok.getKind()) {
4640 default: return false;
4641 // type-specifiers
4642 case tok::kw_short:
4643 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004644 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004645 case tok::kw___int128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004646 case tok::kw_signed:
4647 case tok::kw_unsigned:
4648 case tok::kw__Complex:
4649 case tok::kw__Imaginary:
4650 case tok::kw_void:
4651 case tok::kw_char:
4652 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004653 case tok::kw_char8_t:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004654 case tok::kw_char16_t:
4655 case tok::kw_char32_t:
4656 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004657 case tok::kw_half:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004658 case tok::kw_float:
4659 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004660 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004661 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004662 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004663 case tok::kw___float128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004664 case tok::kw_bool:
4665 case tok::kw__Bool:
4666 case tok::kw__Decimal32:
4667 case tok::kw__Decimal64:
4668 case tok::kw__Decimal128:
4669 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004670#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004671#include "clang/Basic/OpenCLImageTypes.def"
Chad Rosierc1183952012-06-26 22:30:43 +00004672
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004673 // struct-or-union-specifier (C99) or class-specifier (C++)
4674 case tok::kw_class:
4675 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004676 case tok::kw___interface:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004677 case tok::kw_union:
4678 // enum-specifier
4679 case tok::kw_enum:
Chad Rosierc1183952012-06-26 22:30:43 +00004680
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004681 // typedef-name
4682 case tok::annot_typename:
4683 return true;
4684 }
4685}
4686
Steve Naroff69e8f9e2008-02-11 23:15:56 +00004687/// isTypeSpecifierQualifier - Return true if the current token could be the
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004688/// start of a specifier-qualifier-list.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004689bool Parser::isTypeSpecifierQualifier() {
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004690 switch (Tok.getKind()) {
4691 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004692
Chris Lattner020bab92009-01-04 23:41:41 +00004693 case tok::identifier: // foo::bar
John Thompson22334602010-02-05 00:12:22 +00004694 if (TryAltiVecVectorToken())
4695 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004696 LLVM_FALLTHROUGH;
Douglas Gregor333489b2009-03-27 23:10:48 +00004697 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004698 // Annotate typenames and C++ scope specifiers. If we get one, just
4699 // recurse to handle whatever we get.
4700 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004701 return true;
4702 if (Tok.is(tok::identifier))
4703 return false;
4704 return isTypeSpecifierQualifier();
Douglas Gregor333489b2009-03-27 23:10:48 +00004705
Chris Lattner020bab92009-01-04 23:41:41 +00004706 case tok::coloncolon: // ::foo::bar
4707 if (NextToken().is(tok::kw_new) || // ::new
4708 NextToken().is(tok::kw_delete)) // ::delete
4709 return false;
4710
Chris Lattner020bab92009-01-04 23:41:41 +00004711 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004712 return true;
4713 return isTypeSpecifierQualifier();
Mike Stump11289f42009-09-09 15:08:12 +00004714
Chris Lattnere37e2332006-08-15 04:50:22 +00004715 // GNU attributes support.
4716 case tok::kw___attribute:
Steve Naroffad373bd2007-07-31 12:34:36 +00004717 // GNU typeof support.
4718 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004719
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004720 // type-specifiers
4721 case tok::kw_short:
4722 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004723 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004724 case tok::kw___int128:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004725 case tok::kw_signed:
4726 case tok::kw_unsigned:
4727 case tok::kw__Complex:
4728 case tok::kw__Imaginary:
4729 case tok::kw_void:
4730 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004731 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004732 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004733 case tok::kw_char16_t:
4734 case tok::kw_char32_t:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004735 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004736 case tok::kw_half:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004737 case tok::kw_float:
4738 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004739 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004740 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004741 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004742 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004743 case tok::kw_bool:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004744 case tok::kw__Bool:
4745 case tok::kw__Decimal32:
4746 case tok::kw__Decimal64:
4747 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004748 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004749#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004750#include "clang/Basic/OpenCLImageTypes.def"
Mike Stump11289f42009-09-09 15:08:12 +00004751
Chris Lattner861a2262008-04-13 18:59:07 +00004752 // struct-or-union-specifier (C99) or class-specifier (C++)
4753 case tok::kw_class:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004754 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004755 case tok::kw___interface:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004756 case tok::kw_union:
4757 // enum-specifier
4758 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004759
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004760 // type-qualifier
4761 case tok::kw_const:
4762 case tok::kw_volatile:
4763 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004764 case tok::kw__Sat:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004765
John McCallea0a39e2012-11-14 00:49:39 +00004766 // Debugger support.
4767 case tok::kw___unknown_anytype:
4768
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004769 // typedef-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00004770 case tok::annot_typename:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004771 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004772
Chris Lattner409bf7d2008-10-20 00:25:30 +00004773 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4774 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004775 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00004776
Steve Naroff44ac7772008-12-25 14:16:32 +00004777 case tok::kw___cdecl:
4778 case tok::kw___stdcall:
4779 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004780 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004781 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004782 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004783 case tok::kw___w64:
4784 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004785 case tok::kw___ptr32:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004786 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004787 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004788
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004789 case tok::kw__Nonnull:
4790 case tok::kw__Nullable:
4791 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004792
Douglas Gregorab209d82015-07-07 03:58:42 +00004793 case tok::kw___kindof:
4794
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004795 case tok::kw___private:
4796 case tok::kw___local:
4797 case tok::kw___global:
4798 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004799 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004800 case tok::kw___read_only:
4801 case tok::kw___read_write:
4802 case tok::kw___write_only:
4803
Eli Friedman53339e02009-06-08 23:27:34 +00004804 return true;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004805
Richard Smith8e1ac332013-03-28 01:55:44 +00004806 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004807 case tok::kw__Atomic:
4808 return true;
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004809 }
4810}
4811
Chris Lattneracd58a32006-08-06 17:24:14 +00004812/// isDeclarationSpecifier() - Return true if the current token is part of a
4813/// declaration specifier.
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004814///
4815/// \param DisambiguatingWithExpression True to indicate that the purpose of
4816/// this check is to disambiguate between an expression and a declaration.
4817bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
Chris Lattneracd58a32006-08-06 17:24:14 +00004818 switch (Tok.getKind()) {
4819 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004820
Xiuli Pan9c14e282016-01-09 12:53:17 +00004821 case tok::kw_pipe:
4822 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4823
Chris Lattner020bab92009-01-04 23:41:41 +00004824 case tok::identifier: // foo::bar
Steve Naroff9527bbf2009-03-09 21:12:44 +00004825 // Unfortunate hack to support "Class.factoryMethod" notation.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004826 if (getLangOpts().ObjC && NextToken().is(tok::period))
Steve Naroff9527bbf2009-03-09 21:12:44 +00004827 return false;
John Thompson22334602010-02-05 00:12:22 +00004828 if (TryAltiVecVectorToken())
4829 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004830 LLVM_FALLTHROUGH;
David Blaikie15a430a2011-12-04 05:04:18 +00004831 case tok::kw_decltype: // decltype(T())::type
Douglas Gregor333489b2009-03-27 23:10:48 +00004832 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004833 // Annotate typenames and C++ scope specifiers. If we get one, just
4834 // recurse to handle whatever we get.
4835 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004836 return true;
4837 if (Tok.is(tok::identifier))
4838 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004839
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004840 // If we're in Objective-C and we have an Objective-C class type followed
Chad Rosierc1183952012-06-26 22:30:43 +00004841 // by an identifier and then either ':' or ']', in a place where an
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004842 // expression is permitted, then this is probably a class message send
4843 // missing the initial '['. In this case, we won't consider this to be
4844 // the start of a declaration.
Chad Rosierc1183952012-06-26 22:30:43 +00004845 if (DisambiguatingWithExpression &&
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004846 isStartOfObjCClassMessageMissingOpenBracket())
4847 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004848
John McCall1f476a12010-02-26 08:45:28 +00004849 return isDeclarationSpecifier();
4850
Chris Lattner020bab92009-01-04 23:41:41 +00004851 case tok::coloncolon: // ::foo::bar
4852 if (NextToken().is(tok::kw_new) || // ::new
4853 NextToken().is(tok::kw_delete)) // ::delete
4854 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004855
Chris Lattner020bab92009-01-04 23:41:41 +00004856 // Annotate typenames and C++ scope specifiers. If we get one, just
4857 // recurse to handle whatever we get.
4858 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004859 return true;
4860 return isDeclarationSpecifier();
Mike Stump11289f42009-09-09 15:08:12 +00004861
Chris Lattneracd58a32006-08-06 17:24:14 +00004862 // storage-class-specifier
4863 case tok::kw_typedef:
4864 case tok::kw_extern:
Steve Naroff2050b0d2007-12-18 00:16:02 +00004865 case tok::kw___private_extern__:
Chris Lattneracd58a32006-08-06 17:24:14 +00004866 case tok::kw_static:
4867 case tok::kw_auto:
Richard Smithe301ba22015-11-11 02:02:15 +00004868 case tok::kw___auto_type:
Chris Lattneracd58a32006-08-06 17:24:14 +00004869 case tok::kw_register:
4870 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00004871 case tok::kw_thread_local:
4872 case tok::kw__Thread_local:
Mike Stump11289f42009-09-09 15:08:12 +00004873
Douglas Gregor26701a42011-09-09 02:06:17 +00004874 // Modules
4875 case tok::kw___module_private__:
Chad Rosierc1183952012-06-26 22:30:43 +00004876
John McCallea0a39e2012-11-14 00:49:39 +00004877 // Debugger support
4878 case tok::kw___unknown_anytype:
4879
Chris Lattneracd58a32006-08-06 17:24:14 +00004880 // type-specifiers
4881 case tok::kw_short:
4882 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004883 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004884 case tok::kw___int128:
Chris Lattneracd58a32006-08-06 17:24:14 +00004885 case tok::kw_signed:
4886 case tok::kw_unsigned:
4887 case tok::kw__Complex:
4888 case tok::kw__Imaginary:
4889 case tok::kw_void:
4890 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004891 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004892 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004893 case tok::kw_char16_t:
4894 case tok::kw_char32_t:
4895
Chris Lattneracd58a32006-08-06 17:24:14 +00004896 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004897 case tok::kw_half:
Chris Lattneracd58a32006-08-06 17:24:14 +00004898 case tok::kw_float:
4899 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004900 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004901 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004902 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004903 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004904 case tok::kw_bool:
Chris Lattneracd58a32006-08-06 17:24:14 +00004905 case tok::kw__Bool:
4906 case tok::kw__Decimal32:
4907 case tok::kw__Decimal64:
4908 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004909 case tok::kw___vector:
Mike Stump11289f42009-09-09 15:08:12 +00004910
Chris Lattner861a2262008-04-13 18:59:07 +00004911 // struct-or-union-specifier (C99) or class-specifier (C++)
4912 case tok::kw_class:
Chris Lattneracd58a32006-08-06 17:24:14 +00004913 case tok::kw_struct:
4914 case tok::kw_union:
Joao Matosdc86f942012-08-31 18:45:21 +00004915 case tok::kw___interface:
Chris Lattneracd58a32006-08-06 17:24:14 +00004916 // enum-specifier
4917 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004918
Chris Lattneracd58a32006-08-06 17:24:14 +00004919 // type-qualifier
4920 case tok::kw_const:
4921 case tok::kw_volatile:
4922 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004923 case tok::kw__Sat:
Steve Naroffad373bd2007-07-31 12:34:36 +00004924
Chris Lattneracd58a32006-08-06 17:24:14 +00004925 // function-specifier
4926 case tok::kw_inline:
Douglas Gregor61956c42008-10-31 09:07:45 +00004927 case tok::kw_virtual:
4928 case tok::kw_explicit:
Richard Smith0015f092013-01-17 22:16:11 +00004929 case tok::kw__Noreturn:
Chris Lattner7b20dc72007-08-09 16:40:21 +00004930
Richard Smith1dba27c2013-01-29 09:02:09 +00004931 // alignment-specifier
4932 case tok::kw__Alignas:
4933
Richard Smithd16fe122012-10-25 00:00:53 +00004934 // friend keyword.
4935 case tok::kw_friend:
4936
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00004937 // static_assert-declaration
4938 case tok::kw__Static_assert:
4939
Chris Lattner599e47e2007-08-09 17:01:07 +00004940 // GNU typeof support.
4941 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004942
Chris Lattner599e47e2007-08-09 17:01:07 +00004943 // GNU attributes.
Chris Lattner7b20dc72007-08-09 16:40:21 +00004944 case tok::kw___attribute:
Mike Stump11289f42009-09-09 15:08:12 +00004945
Richard Smithd16fe122012-10-25 00:00:53 +00004946 // C++11 decltype and constexpr.
David Blaikie15a430a2011-12-04 05:04:18 +00004947 case tok::annot_decltype:
Richard Smithd16fe122012-10-25 00:00:53 +00004948 case tok::kw_constexpr:
Francois Pichete878cb62011-06-19 08:02:06 +00004949
Richard Smith8e1ac332013-03-28 01:55:44 +00004950 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004951 case tok::kw__Atomic:
4952 return true;
4953
Chris Lattner8b2ec162008-07-26 03:38:44 +00004954 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4955 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004956 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00004957
Douglas Gregor19b7acf2011-04-27 05:41:15 +00004958 // typedef-name
4959 case tok::annot_typename:
4960 return !DisambiguatingWithExpression ||
4961 !isStartOfObjCClassMessageMissingOpenBracket();
Chad Rosierc1183952012-06-26 22:30:43 +00004962
Steve Narofff192fab2009-01-06 19:34:12 +00004963 case tok::kw___declspec:
Steve Naroff44ac7772008-12-25 14:16:32 +00004964 case tok::kw___cdecl:
4965 case tok::kw___stdcall:
4966 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004967 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004968 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004969 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004970 case tok::kw___w64:
Aaron Ballman317a77f2013-05-22 23:25:32 +00004971 case tok::kw___sptr:
4972 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00004973 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004974 case tok::kw___ptr32:
Eli Friedman53339e02009-06-08 23:27:34 +00004975 case tok::kw___forceinline:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004976 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004977 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004978
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004979 case tok::kw__Nonnull:
4980 case tok::kw__Nullable:
4981 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004982
Douglas Gregorab209d82015-07-07 03:58:42 +00004983 case tok::kw___kindof:
4984
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004985 case tok::kw___private:
4986 case tok::kw___local:
4987 case tok::kw___global:
4988 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004989 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004990 case tok::kw___read_only:
4991 case tok::kw___read_write:
4992 case tok::kw___write_only:
Alexey Bader954ba212016-04-08 13:40:33 +00004993#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004994#include "clang/Basic/OpenCLImageTypes.def"
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004995
Eli Friedman53339e02009-06-08 23:27:34 +00004996 return true;
Chris Lattneracd58a32006-08-06 17:24:14 +00004997 }
4998}
4999
Richard Smith35845152017-02-07 01:37:30 +00005000bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005001 TentativeParsingAction TPA(*this);
5002
5003 // Parse the C++ scope specifier.
5004 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005005 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005006 /*EnteringContext=*/true)) {
John McCall1f476a12010-02-26 08:45:28 +00005007 TPA.Revert();
5008 return false;
5009 }
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005010
5011 // Parse the constructor name.
Richard Smithaf3b3252017-05-18 19:21:48 +00005012 if (Tok.is(tok::identifier)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005013 // We already know that we have a constructor name; just consume
5014 // the token.
5015 ConsumeToken();
Richard Smithaf3b3252017-05-18 19:21:48 +00005016 } else if (Tok.is(tok::annot_template_id)) {
5017 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005018 } else {
5019 TPA.Revert();
5020 return false;
5021 }
5022
Richard Smith8f8697f2017-02-08 01:16:55 +00005023 // There may be attributes here, appertaining to the constructor name or type
5024 // we just stepped past.
5025 SkipCXX11Attributes();
5026
Richard Smith43f340f2012-03-27 23:05:05 +00005027 // Current class name must be followed by a left parenthesis.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005028 if (Tok.isNot(tok::l_paren)) {
5029 TPA.Revert();
5030 return false;
5031 }
5032 ConsumeParen();
5033
Richard Smith43f340f2012-03-27 23:05:05 +00005034 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5035 // that we have a constructor.
5036 if (Tok.is(tok::r_paren) ||
5037 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005038 TPA.Revert();
5039 return true;
5040 }
5041
Richard Smithf2163662013-09-06 00:12:20 +00005042 // A C++11 attribute here signals that we have a constructor, and is an
5043 // attribute on the first constructor parameter.
5044 if (getLangOpts().CPlusPlus11 &&
5045 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5046 /*OuterMightBeMessageSend*/ true)) {
5047 TPA.Revert();
5048 return true;
5049 }
5050
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005051 // If we need to, enter the specified scope.
5052 DeclaratorScopeObj DeclScopeObj(*this, SS);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005053 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005054 DeclScopeObj.EnterDeclaratorScope();
5055
Francois Pichet79f3a872011-01-31 04:54:32 +00005056 // Optionally skip Microsoft attributes.
John McCall084e83d2011-03-24 11:26:52 +00005057 ParsedAttributes Attrs(AttrFactory);
Francois Pichet79f3a872011-01-31 04:54:32 +00005058 MaybeParseMicrosoftAttributes(Attrs);
5059
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005060 // Check whether the next token(s) are part of a declaration
5061 // specifier, in which case we have the start of a parameter and,
5062 // therefore, we know that this is a constructor.
Richard Smithefd009d2012-03-27 00:56:56 +00005063 bool IsConstructor = false;
5064 if (isDeclarationSpecifier())
5065 IsConstructor = true;
5066 else if (Tok.is(tok::identifier) ||
5067 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5068 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5069 // This might be a parenthesized member name, but is more likely to
5070 // be a constructor declaration with an invalid argument type. Keep
5071 // looking.
5072 if (Tok.is(tok::annot_cxxscope))
Richard Smithaf3b3252017-05-18 19:21:48 +00005073 ConsumeAnnotationToken();
Richard Smithefd009d2012-03-27 00:56:56 +00005074 ConsumeToken();
5075
5076 // If this is not a constructor, we must be parsing a declarator,
Richard Smith1453e312012-03-27 01:42:32 +00005077 // which must have one of the following syntactic forms (see the
5078 // grammar extract at the start of ParseDirectDeclarator):
Richard Smithefd009d2012-03-27 00:56:56 +00005079 switch (Tok.getKind()) {
5080 case tok::l_paren:
5081 // C(X ( int));
5082 case tok::l_square:
5083 // C(X [ 5]);
5084 // C(X [ [attribute]]);
5085 case tok::coloncolon:
5086 // C(X :: Y);
5087 // C(X :: *p);
Richard Smithefd009d2012-03-27 00:56:56 +00005088 // Assume this isn't a constructor, rather than assuming it's a
5089 // constructor with an unnamed parameter of an ill-formed type.
5090 break;
5091
Richard Smith446161b2014-03-03 21:12:53 +00005092 case tok::r_paren:
5093 // C(X )
Richard Smith8f8697f2017-02-08 01:16:55 +00005094
5095 // Skip past the right-paren and any following attributes to get to
5096 // the function body or trailing-return-type.
5097 ConsumeParen();
5098 SkipCXX11Attributes();
5099
Richard Smith35845152017-02-07 01:37:30 +00005100 if (DeductionGuide) {
5101 // C(X) -> ... is a deduction guide.
Richard Smith8f8697f2017-02-08 01:16:55 +00005102 IsConstructor = Tok.is(tok::arrow);
Richard Smith35845152017-02-07 01:37:30 +00005103 break;
5104 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005105 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
Richard Smith446161b2014-03-03 21:12:53 +00005106 // Assume these were meant to be constructors:
5107 // C(X) : (the name of a bit-field cannot be parenthesized).
5108 // C(X) try (this is otherwise ill-formed).
5109 IsConstructor = true;
5110 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005111 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
Richard Smith446161b2014-03-03 21:12:53 +00005112 // If we have a constructor name within the class definition,
5113 // assume these were meant to be constructors:
5114 // C(X) {
5115 // C(X) ;
5116 // ... because otherwise we would be declaring a non-static data
5117 // member that is ill-formed because it's of the same type as its
5118 // surrounding class.
5119 //
5120 // FIXME: We can actually do this whether or not the name is qualified,
5121 // because if it is qualified in this context it must be being used as
Richard Smith35845152017-02-07 01:37:30 +00005122 // a constructor name.
Richard Smith446161b2014-03-03 21:12:53 +00005123 // currently, so we're somewhat conservative here.
5124 IsConstructor = IsUnqualified;
5125 }
5126 break;
5127
Richard Smithefd009d2012-03-27 00:56:56 +00005128 default:
5129 IsConstructor = true;
5130 break;
5131 }
5132 }
5133
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005134 TPA.Revert();
5135 return IsConstructor;
5136}
Chris Lattnerb9093cd2006-08-04 04:39:53 +00005137
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005138/// ParseTypeQualifierListOpt
Dawn Perchik335e16b2010-09-03 01:29:35 +00005139/// type-qualifier-list: [C99 6.7.5]
5140/// type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005141/// [vendor] attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005142/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005143/// type-qualifier-list type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005144/// [vendor] type-qualifier-list attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005145/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005146/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
Aaron Ballman08b06592014-07-22 12:44:22 +00005147/// [ only if AttReqs & AR_CXX11AttributesParsed ]
5148/// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5149/// AttrRequirements bitmask values.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005150void Parser::ParseTypeQualifierListOpt(
5151 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5152 bool IdentifierRequired,
5153 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
Aaron Ballman606093a2017-10-15 15:01:42 +00005154 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005155 isCXX11AttributeSpecifier()) {
John McCall084e83d2011-03-24 11:26:52 +00005156 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith3dff2512012-04-10 03:25:07 +00005157 ParseCXX11Attributes(attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005158 DS.takeAttributesFrom(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005159 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005160
5161 SourceLocation EndLoc;
5162
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005163 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00005164 bool isInvalid = false;
Craig Topper161e4db2014-05-21 06:02:52 +00005165 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00005166 unsigned DiagID = 0;
Chris Lattner60809f52006-11-28 05:18:46 +00005167 SourceLocation Loc = Tok.getLocation();
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005168
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005169 switch (Tok.getKind()) {
Douglas Gregor28c78432010-08-27 17:35:51 +00005170 case tok::code_completion:
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005171 if (CodeCompletionHandler)
5172 (*CodeCompletionHandler)();
5173 else
5174 Actions.CodeCompleteTypeQualifiers(DS);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00005175 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00005176
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005177 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00005178 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005179 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005180 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005181 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00005182 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005183 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005184 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005185 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00005186 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005187 getLangOpts());
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005188 break;
Richard Smith8e1ac332013-03-28 01:55:44 +00005189 case tok::kw__Atomic:
5190 if (!AtomicAllowed)
5191 goto DoneWithTypeQuals;
5192 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5193 getLangOpts());
5194 break;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005195
5196 // OpenCL qualifiers:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005197 case tok::kw___private:
5198 case tok::kw___global:
5199 case tok::kw___local:
5200 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005201 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005202 case tok::kw___read_only:
5203 case tok::kw___write_only:
5204 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00005205 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005206 break;
5207
Andrey Bokhanko45d41322016-05-11 18:38:21 +00005208 case tok::kw___unaligned:
5209 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5210 getLangOpts());
5211 break;
Aaron Ballman317a77f2013-05-22 23:25:32 +00005212 case tok::kw___uptr:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005213 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
Alp Toker62c5b572013-11-26 01:30:10 +00005214 // with the MS modifier keyword.
Aaron Ballman08b06592014-07-22 12:44:22 +00005215 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
Alp Toker47642d22013-12-03 06:13:01 +00005216 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5217 if (TryKeywordIdentFallback(false))
5218 continue;
Alp Toker62c5b572013-11-26 01:30:10 +00005219 }
Galina Kistanova77674252017-06-01 21:15:34 +00005220 LLVM_FALLTHROUGH;
Alp Toker62c5b572013-11-26 01:30:10 +00005221 case tok::kw___sptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005222 case tok::kw___w64:
Steve Narofff9c29d42008-12-25 14:41:26 +00005223 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005224 case tok::kw___ptr32:
Steve Naroff44ac7772008-12-25 14:16:32 +00005225 case tok::kw___cdecl:
5226 case tok::kw___stdcall:
5227 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005228 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005229 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005230 case tok::kw___vectorcall:
Aaron Ballman08b06592014-07-22 12:44:22 +00005231 if (AttrReqs & AR_DeclspecAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005232 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00005233 continue;
5234 }
5235 goto DoneWithTypeQuals;
Dawn Perchik335e16b2010-09-03 01:29:35 +00005236 case tok::kw___pascal:
Aaron Ballman08b06592014-07-22 12:44:22 +00005237 if (AttrReqs & AR_VendorAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005238 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00005239 continue;
5240 }
5241 goto DoneWithTypeQuals;
Douglas Gregor261a89b2015-06-19 17:51:05 +00005242
5243 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005244 case tok::kw__Nonnull:
5245 case tok::kw__Nullable:
5246 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005247 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5248 continue;
5249
Douglas Gregorab209d82015-07-07 03:58:42 +00005250 // Objective-C 'kindof' types.
5251 case tok::kw___kindof:
5252 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00005253 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00005254 (void)ConsumeToken();
5255 continue;
5256
Chris Lattnere37e2332006-08-15 04:50:22 +00005257 case tok::kw___attribute:
Aaron Ballman08b06592014-07-22 12:44:22 +00005258 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5259 // When GNU attributes are expressly forbidden, diagnose their usage.
5260 Diag(Tok, diag::err_attributes_not_allowed);
5261
5262 // Parse the attributes even if they are rejected to ensure that error
5263 // recovery is graceful.
5264 if (AttrReqs & AR_GNUAttributesParsed ||
5265 AttrReqs & AR_GNUAttributesParsedAndRejected) {
John McCall53fa7142010-12-24 02:08:15 +00005266 ParseGNUAttributes(DS.getAttributes());
Chris Lattnercf0bab22008-12-18 07:02:59 +00005267 continue; // do *not* consume the next token!
5268 }
5269 // otherwise, FALL THROUGH!
Galina Kistanova77674252017-06-01 21:15:34 +00005270 LLVM_FALLTHROUGH;
Chris Lattnercf0bab22008-12-18 07:02:59 +00005271 default:
Steve Naroff44ac7772008-12-25 14:16:32 +00005272 DoneWithTypeQuals:
Chris Lattnercf0bab22008-12-18 07:02:59 +00005273 // If this is not a type-qualifier token, we're done reading type
5274 // qualifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00005275 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005276 if (EndLoc.isValid())
5277 DS.SetRangeEnd(EndLoc);
Chris Lattnercf0bab22008-12-18 07:02:59 +00005278 return;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005279 }
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00005280
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005281 // If the specifier combination wasn't legal, issue a diagnostic.
5282 if (isInvalid) {
5283 assert(PrevSpec && "Method did not return previous specifier!");
Chris Lattner6d29c102008-11-18 07:48:38 +00005284 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005285 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005286 EndLoc = ConsumeToken();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005287 }
5288}
5289
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005290/// ParseDeclarator - Parse and verify a newly-initialized declarator.
5291///
5292void Parser::ParseDeclarator(Declarator &D) {
5293 /// This implements the 'declarator' production in the C grammar, then checks
5294 /// for well-formedness and issues diagnostics.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005295 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005296}
5297
Richard Smith0b350b92014-10-28 16:55:02 +00005298static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
Faisal Vali421b2d12017-12-29 05:41:00 +00005299 DeclaratorContext TheContext) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005300 if (Kind == tok::star || Kind == tok::caret)
5301 return true;
5302
Xiuli Pan9c14e282016-01-09 12:53:17 +00005303 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5304 return true;
5305
Richard Smith0efa75c2012-03-29 01:16:42 +00005306 if (!Lang.CPlusPlus)
5307 return false;
5308
Richard Smith0b350b92014-10-28 16:55:02 +00005309 if (Kind == tok::amp)
5310 return true;
5311
5312 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5313 // But we must not parse them in conversion-type-ids and new-type-ids, since
5314 // those can be legitimately followed by a && operator.
5315 // (The same thing can in theory happen after a trailing-return-type, but
5316 // since those are a C++11 feature, there is no rejects-valid issue there.)
5317 if (Kind == tok::ampamp)
Faisal Vali421b2d12017-12-29 05:41:00 +00005318 return Lang.CPlusPlus11 ||
5319 (TheContext != DeclaratorContext::ConversionIdContext &&
5320 TheContext != DeclaratorContext::CXXNewContext);
Richard Smith0b350b92014-10-28 16:55:02 +00005321
5322 return false;
Richard Smith0efa75c2012-03-29 01:16:42 +00005323}
5324
Xiuli Pan9c14e282016-01-09 12:53:17 +00005325// Indicates whether the given declarator is a pipe declarator.
5326static bool isPipeDeclerator(const Declarator &D) {
5327 const unsigned NumTypes = D.getNumTypeObjects();
5328
5329 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5330 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5331 return true;
5332
5333 return false;
5334}
5335
Sebastian Redlbd150f42008-11-21 19:14:01 +00005336/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5337/// is parsed by the function passed to it. Pass null, and the direct-declarator
5338/// isn't parsed at all, making this function effectively parse the C++
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005339/// ptr-operator production.
5340///
Richard Smith09f76ee2011-10-19 21:33:05 +00005341/// If the grammar of this construct is extended, matching changes must also be
Richard Smith1453e312012-03-27 01:42:32 +00005342/// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5343/// isConstructorDeclarator.
Richard Smith09f76ee2011-10-19 21:33:05 +00005344///
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005345/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5346/// [C] pointer[opt] direct-declarator
5347/// [C++] direct-declarator
5348/// [C++] ptr-operator declarator
Chris Lattner6c7416c2006-08-07 00:19:33 +00005349///
5350/// pointer: [C99 6.7.5]
5351/// '*' type-qualifier-list[opt]
5352/// '*' type-qualifier-list[opt] pointer
5353///
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005354/// ptr-operator:
5355/// '*' cv-qualifier-seq[opt]
5356/// '&'
Sebastian Redled0f3b02009-03-15 22:02:01 +00005357/// [C++0x] '&&'
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005358/// [GNU] '&' restrict[opt] attributes[opt]
Sebastian Redled0f3b02009-03-15 22:02:01 +00005359/// [GNU?] '&&' restrict[opt] attributes[opt]
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005360/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
Sebastian Redlbd150f42008-11-21 19:14:01 +00005361void Parser::ParseDeclaratorInternal(Declarator &D,
5362 DirectDeclParseFunction DirectDeclParser) {
Douglas Gregor66a985d2009-08-26 14:27:30 +00005363 if (Diags.hasAllExtensionsSilenced())
5364 D.setExtension();
Chad Rosierc1183952012-06-26 22:30:43 +00005365
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005366 // C++ member pointers start with a '::' or a nested-name.
5367 // Member pointers get special handling, since there's no place for the
5368 // scope spec in the generic path below.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005369 if (getLangOpts().CPlusPlus &&
Richard Smith83c2ecf2016-02-02 23:34:49 +00005370 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
Serge Pavlov458ea762014-07-16 05:16:52 +00005371 (Tok.is(tok::identifier) &&
5372 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
Chris Lattner803802d2009-03-24 17:04:48 +00005373 Tok.is(tok::annot_cxxscope))) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005374 bool EnteringContext =
5375 D.getContext() == DeclaratorContext::FileContext ||
5376 D.getContext() == DeclaratorContext::MemberContext;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005377 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005378 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005379
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +00005380 if (SS.isNotEmpty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005381 if (Tok.isNot(tok::star)) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005382 // The scope spec really belongs to the direct-declarator.
Richard Smith5f044ad2013-01-08 22:43:49 +00005383 if (D.mayHaveIdentifier())
5384 D.getCXXScopeSpec() = SS;
5385 else
5386 AnnotateScopeToken(SS, true);
5387
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005388 if (DirectDeclParser)
5389 (this->*DirectDeclParser)(D);
5390 return;
5391 }
5392
5393 SourceLocation Loc = ConsumeToken();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005394 D.SetRangeEnd(Loc);
John McCall084e83d2011-03-24 11:26:52 +00005395 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005396 ParseTypeQualifierListOpt(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005397 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005398
5399 // Recurse to parse whatever is left.
5400 ParseDeclaratorInternal(D, DirectDeclParser);
5401
5402 // Sema will have to catch (syntactically invalid) pointers into global
5403 // scope. It has to catch pointers into namespace scope anyway.
Erich Keanec480f302018-07-12 21:09:05 +00005404 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005405 SS, DS.getTypeQualifiers(), DS.getEndLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005406 std::move(DS.getAttributes()),
5407 /* Don't replace range end. */ SourceLocation());
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005408 return;
5409 }
5410 }
5411
5412 tok::TokenKind Kind = Tok.getKind();
Xiuli Pan9c14e282016-01-09 12:53:17 +00005413
5414 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
Xiuli Pan11e13f62016-02-26 03:13:03 +00005415 DeclSpec DS(AttrFactory);
5416 ParseTypeQualifierListOpt(DS);
Xiuli Pan9c14e282016-01-09 12:53:17 +00005417
5418 D.AddTypeInfo(
5419 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005420 std::move(DS.getAttributes()), SourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00005421 }
5422
Steve Naroffec33ed92008-08-27 16:04:49 +00005423 // Not a pointer, C++ reference, or block.
Richard Smith0b350b92014-10-28 16:55:02 +00005424 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00005425 if (DirectDeclParser)
5426 (this->*DirectDeclParser)(D);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005427 return;
5428 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005429
Sebastian Redled0f3b02009-03-15 22:02:01 +00005430 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5431 // '&&' -> rvalue reference
Sebastian Redl3b27be62009-03-23 00:00:23 +00005432 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005433 D.SetRangeEnd(Loc);
Bill Wendling3708c182007-05-27 10:15:43 +00005434
Chris Lattner9eac9312009-03-27 04:18:06 +00005435 if (Kind == tok::star || Kind == tok::caret) {
Chris Lattner788404f2008-02-21 01:32:26 +00005436 // Is a pointer.
John McCall084e83d2011-03-24 11:26:52 +00005437 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005438
Aaron Ballman08b06592014-07-22 12:44:22 +00005439 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5440 // C++11 attributes are allowed.
5441 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
Faisal Vali421b2d12017-12-29 05:41:00 +00005442 ((D.getContext() != DeclaratorContext::CXXNewContext)
5443 ? AR_GNUAttributesParsed
5444 : AR_GNUAttributesParsedAndRejected);
Aaron Ballman08b06592014-07-22 12:44:22 +00005445 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005446 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005447
Bill Wendling3708c182007-05-27 10:15:43 +00005448 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005449 ParseDeclaratorInternal(D, DirectDeclParser);
Steve Naroffec33ed92008-08-27 16:04:49 +00005450 if (Kind == tok::star)
5451 // Remember that we parsed a pointer type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005452 D.AddTypeInfo(DeclaratorChunk::getPointer(
5453 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5454 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5455 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5456 std::move(DS.getAttributes()), SourceLocation());
Steve Naroffec33ed92008-08-27 16:04:49 +00005457 else
5458 // Remember that we parsed a Block type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005459 D.AddTypeInfo(
5460 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5461 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005462 } else {
5463 // Is a reference
John McCall084e83d2011-03-24 11:26:52 +00005464 DeclSpec DS(AttrFactory);
Bill Wendling93efb222007-06-02 23:28:54 +00005465
Sebastian Redl3b27be62009-03-23 00:00:23 +00005466 // Complain about rvalue references in C++03, but then go on and build
5467 // the declarator.
Richard Smith5d164bc2011-10-15 05:09:34 +00005468 if (Kind == tok::ampamp)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005469 Diag(Loc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00005470 diag::warn_cxx98_compat_rvalue_reference :
5471 diag::ext_rvalue_reference);
Sebastian Redl3b27be62009-03-23 00:00:23 +00005472
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005473 // GNU-style and C++11 attributes are allowed here, as is restrict.
5474 ParseTypeQualifierListOpt(DS);
5475 D.ExtendWithDeclSpec(DS);
5476
Bill Wendling93efb222007-06-02 23:28:54 +00005477 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5478 // cv-qualifiers are introduced through the use of a typedef or of a
5479 // template type argument, in which case the cv-qualifiers are ignored.
Bill Wendling93efb222007-06-02 23:28:54 +00005480 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5481 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5482 Diag(DS.getConstSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005483 diag::err_invalid_reference_qualifier_application) << "const";
Bill Wendling93efb222007-06-02 23:28:54 +00005484 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5485 Diag(DS.getVolatileSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005486 diag::err_invalid_reference_qualifier_application) << "volatile";
Richard Smith8e1ac332013-03-28 01:55:44 +00005487 // 'restrict' is permitted as an extension.
5488 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5489 Diag(DS.getAtomicSpecLoc(),
5490 diag::err_invalid_reference_qualifier_application) << "_Atomic";
Bill Wendling93efb222007-06-02 23:28:54 +00005491 }
Bill Wendling3708c182007-05-27 10:15:43 +00005492
5493 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005494 ParseDeclaratorInternal(D, DirectDeclParser);
Bill Wendling3708c182007-05-27 10:15:43 +00005495
Douglas Gregor66583c52008-11-03 15:51:28 +00005496 if (D.getNumTypeObjects() > 0) {
5497 // C++ [dcl.ref]p4: There shall be no references to references.
5498 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5499 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
Chris Lattnerebad6a22008-11-19 07:37:42 +00005500 if (const IdentifierInfo *II = D.getIdentifier())
5501 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5502 << II;
5503 else
5504 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5505 << "type name";
Douglas Gregor66583c52008-11-03 15:51:28 +00005506
Sebastian Redlbd150f42008-11-21 19:14:01 +00005507 // Once we've complained about the reference-to-reference, we
Douglas Gregor66583c52008-11-03 15:51:28 +00005508 // can go ahead and build the (technically ill-formed)
5509 // declarator: reference collapsing will take care of it.
5510 }
5511 }
5512
Richard Smith8e1ac332013-03-28 01:55:44 +00005513 // Remember that we parsed a reference type.
Chris Lattner788404f2008-02-21 01:32:26 +00005514 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
Sebastian Redled0f3b02009-03-15 22:02:01 +00005515 Kind == tok::amp),
Erich Keanec480f302018-07-12 21:09:05 +00005516 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005517 }
Chris Lattner6c7416c2006-08-07 00:19:33 +00005518}
5519
Richard Trieuf4b81d02014-06-24 23:14:24 +00005520// When correcting from misplaced brackets before the identifier, the location
5521// is saved inside the declarator so that other diagnostic messages can use
5522// them. This extracts and returns that location, or returns the provided
5523// location if a stored location does not exist.
5524static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5525 SourceLocation Loc) {
5526 if (D.getName().StartLocation.isInvalid() &&
5527 D.getName().EndLocation.isValid())
5528 return D.getName().EndLocation;
5529
5530 return Loc;
5531}
5532
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005533/// ParseDirectDeclarator
5534/// direct-declarator: [C99 6.7.5]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005535/// [C99] identifier
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005536/// '(' declarator ')'
5537/// [GNU] '(' attributes declarator ')'
Chris Lattnere8074e62006-08-06 18:30:15 +00005538/// [C90] direct-declarator '[' constant-expression[opt] ']'
5539/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5540/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5541/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5542/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005543/// [C++11] direct-declarator '[' constant-expression[opt] ']'
5544/// attribute-specifier-seq[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005545/// direct-declarator '(' parameter-type-list ')'
5546/// direct-declarator '(' identifier-list[opt] ')'
5547/// [GNU] direct-declarator '(' parameter-forward-declarations
5548/// parameter-type-list[opt] ')'
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00005549/// [C++] direct-declarator '(' parameter-declaration-clause ')'
5550/// cv-qualifier-seq[opt] exception-specification[opt]
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005551/// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5552/// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5553/// ref-qualifier[opt] exception-specification[opt]
Douglas Gregor61956c42008-10-31 09:07:45 +00005554/// [C++] declarator-id
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005555/// [C++11] declarator-id attribute-specifier-seq[opt]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005556///
5557/// declarator-id: [C++ 8]
Douglas Gregor27b4c162010-12-23 22:44:42 +00005558/// '...'[opt] id-expression
Douglas Gregor831c93f2008-11-05 20:51:48 +00005559/// '::'[opt] nested-name-specifier[opt] type-name
5560///
5561/// id-expression: [C++ 5.1]
5562/// unqualified-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005563/// qualified-id
Douglas Gregor831c93f2008-11-05 20:51:48 +00005564///
5565/// unqualified-id: [C++ 5.1]
Mike Stump11289f42009-09-09 15:08:12 +00005566/// identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005567/// operator-function-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005568/// conversion-function-id
Mike Stump11289f42009-09-09 15:08:12 +00005569/// '~' class-name
Douglas Gregor7f741122009-02-25 19:37:18 +00005570/// template-id
Argyrios Kyrtzidise4426352008-11-07 22:02:30 +00005571///
Richard Smithbdb84f32016-07-22 23:36:59 +00005572/// C++17 adds the following, which we also handle here:
5573///
5574/// simple-declaration:
5575/// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5576///
Richard Smith1453e312012-03-27 01:42:32 +00005577/// Note, any additional constructs added here may need corresponding changes
5578/// in isConstructorDeclarator.
Chris Lattneracd58a32006-08-06 17:24:14 +00005579void Parser::ParseDirectDeclarator(Declarator &D) {
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005580 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005581
David Blaikiebbafb8a2012-03-11 07:00:24 +00005582 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
Richard Smithbdb84f32016-07-22 23:36:59 +00005583 // This might be a C++17 structured binding.
5584 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5585 D.getCXXScopeSpec().isEmpty())
5586 return ParseDecompositionDeclarator(D);
5587
Serge Pavlov458ea762014-07-16 05:16:52 +00005588 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5589 // this context it is a bitfield. Also in range-based for statement colon
5590 // may delimit for-range-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00005591 ColonProtectionRAIIObject X(
5592 *this, D.getContext() == DeclaratorContext::MemberContext ||
5593 (D.getContext() == DeclaratorContext::ForContext &&
5594 getLangOpts().CPlusPlus11));
Serge Pavlov458ea762014-07-16 05:16:52 +00005595
Douglas Gregor7861a802009-11-03 01:35:08 +00005596 // ParseDeclaratorInternal might already have parsed the scope.
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005597 if (D.getCXXScopeSpec().isEmpty()) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005598 bool EnteringContext =
5599 D.getContext() == DeclaratorContext::FileContext ||
5600 D.getContext() == DeclaratorContext::MemberContext;
David Blaikieefdccaa2016-01-15 23:43:34 +00005601 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005602 EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005603 }
5604
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005605 if (D.getCXXScopeSpec().isValid()) {
Richard Smith64e033f2015-01-15 00:48:52 +00005606 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5607 D.getCXXScopeSpec()))
John McCall2b058ef2009-12-11 20:04:54 +00005608 // Change the declaration context for name lookup, until this function
5609 // is exited (and the declarator has been parsed).
5610 DeclScopeObj.EnterDeclaratorScope();
Alex Lorenze151f0102016-12-07 10:24:44 +00005611 else if (getObjCDeclContext()) {
5612 // Ensure that we don't interpret the next token as an identifier when
5613 // dealing with declarations in an Objective-C container.
5614 D.SetIdentifier(nullptr, Tok.getLocation());
5615 D.setInvalidType(true);
5616 ConsumeToken();
5617 goto PastIdentifier;
5618 }
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005619 }
5620
Douglas Gregor27b4c162010-12-23 22:44:42 +00005621 // C++0x [dcl.fct]p14:
Faisal Vali8435a692014-12-04 12:40:21 +00005622 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5623 // parameter-declaration-clause without a preceding comma. In this case,
5624 // the ellipsis is parsed as part of the abstract-declarator if the type
5625 // of the parameter either names a template parameter pack that has not
5626 // been expanded or contains auto; otherwise, it is parsed as part of the
5627 // parameter-declaration-clause.
Richard Smith0efa75c2012-03-29 01:16:42 +00005628 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00005629 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5630 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5631 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
Douglas Gregor27b4c162010-12-23 22:44:42 +00005632 NextToken().is(tok::r_paren) &&
Richard Smithb19337f2013-02-20 20:19:27 +00005633 !D.hasGroupingParens() &&
Faisal Vali8435a692014-12-04 12:40:21 +00005634 !Actions.containsUnexpandedParameterPacks(D) &&
Faisal Vali090da2d2018-01-01 18:23:28 +00005635 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005636 SourceLocation EllipsisLoc = ConsumeToken();
Richard Smith0b350b92014-10-28 16:55:02 +00005637 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005638 // The ellipsis was put in the wrong place. Recover, and explain to
5639 // the user what they should have done.
5640 ParseDeclarator(D);
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00005641 if (EllipsisLoc.isValid())
5642 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00005643 return;
5644 } else
5645 D.setEllipsisLoc(EllipsisLoc);
5646
5647 // The ellipsis can't be followed by a parenthesized declarator. We
5648 // check for that in ParseParenDeclarator, after we have disambiguated
5649 // the l_paren token.
5650 }
5651
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005652 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5653 tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00005654 // We found something that indicates the start of an unqualified-id.
5655 // Parse that unqualified-id.
John McCall84821e72010-04-13 06:39:49 +00005656 bool AllowConstructorName;
Richard Smith35845152017-02-07 01:37:30 +00005657 bool AllowDeductionGuide;
5658 if (D.getDeclSpec().hasTypeSpecifier()) {
John McCall84821e72010-04-13 06:39:49 +00005659 AllowConstructorName = false;
Richard Smith35845152017-02-07 01:37:30 +00005660 AllowDeductionGuide = false;
5661 } else if (D.getCXXScopeSpec().isSet()) {
John McCall84821e72010-04-13 06:39:49 +00005662 AllowConstructorName =
Faisal Vali421b2d12017-12-29 05:41:00 +00005663 (D.getContext() == DeclaratorContext::FileContext ||
5664 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005665 AllowDeductionGuide = false;
5666 } else {
Faisal Vali421b2d12017-12-29 05:41:00 +00005667 AllowConstructorName =
5668 (D.getContext() == DeclaratorContext::MemberContext);
Fangrui Song6907ce22018-07-30 19:24:48 +00005669 AllowDeductionGuide =
Faisal Vali421b2d12017-12-29 05:41:00 +00005670 (D.getContext() == DeclaratorContext::FileContext ||
5671 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005672 }
John McCall84821e72010-04-13 06:39:49 +00005673
Richard Smith64e033f2015-01-15 00:48:52 +00005674 bool HadScope = D.getCXXScopeSpec().isValid();
Chad Rosierc1183952012-06-26 22:30:43 +00005675 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5676 /*EnteringContext=*/true,
David Blaikieefdccaa2016-01-15 23:43:34 +00005677 /*AllowDestructorName=*/true, AllowConstructorName,
Richard Smithc08b6932018-04-27 02:00:13 +00005678 AllowDeductionGuide, nullptr, nullptr,
Richard Smith35845152017-02-07 01:37:30 +00005679 D.getName()) ||
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005680 // Once we're past the identifier, if the scope was bad, mark the
5681 // whole declarator bad.
5682 D.getCXXScopeSpec().isInvalid()) {
Craig Topper161e4db2014-05-21 06:02:52 +00005683 D.SetIdentifier(nullptr, Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005684 D.setInvalidType(true);
Douglas Gregor7861a802009-11-03 01:35:08 +00005685 } else {
Richard Smith64e033f2015-01-15 00:48:52 +00005686 // ParseUnqualifiedId might have parsed a scope specifier during error
5687 // recovery. If it did so, enter that scope.
5688 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5689 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5690 D.getCXXScopeSpec()))
5691 DeclScopeObj.EnterDeclaratorScope();
5692
Douglas Gregor7861a802009-11-03 01:35:08 +00005693 // Parsed the unqualified-id; update range information and move along.
5694 if (D.getSourceRange().getBegin().isInvalid())
5695 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5696 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005697 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005698 goto PastIdentifier;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005699 }
Richard Smithd63db6e2015-12-19 02:40:19 +00005700
5701 if (D.getCXXScopeSpec().isNotEmpty()) {
5702 // We have a scope specifier but no following unqualified-id.
5703 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5704 diag::err_expected_unqualified_id)
5705 << /*C++*/1;
5706 D.SetIdentifier(nullptr, Tok.getLocation());
5707 goto PastIdentifier;
5708 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005709 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005710 assert(!getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005711 "There's a C++-specific check for tok::identifier above");
5712 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5713 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Richard Trieu2664dc12014-05-05 22:06:50 +00005714 D.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005715 ConsumeToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00005716 goto PastIdentifier;
Richard Smith74639b12017-05-19 01:54:59 +00005717 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5718 // We're not allowed an identifier here, but we got one. Try to figure out
5719 // if the user was trying to attach a name to the type, or whether the name
5720 // is some unrelated trailing syntax.
5721 bool DiagnoseIdentifier = false;
5722 if (D.hasGroupingParens())
5723 // An identifier within parens is unlikely to be intended to be anything
5724 // other than a name being "declared".
5725 DiagnoseIdentifier = true;
Richard Smith77a9c602018-02-28 03:02:23 +00005726 else if (D.getContext() == DeclaratorContext::TemplateArgContext)
Richard Smith74639b12017-05-19 01:54:59 +00005727 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5728 DiagnoseIdentifier =
5729 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali421b2d12017-12-29 05:41:00 +00005730 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5731 D.getContext() == DeclaratorContext::AliasTemplateContext)
Richard Smith74639b12017-05-19 01:54:59 +00005732 // The most likely error is that the ';' was forgotten.
5733 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
Richard Smithe303e352018-02-02 22:24:54 +00005734 else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5735 D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
Richard Smith74639b12017-05-19 01:54:59 +00005736 !isCXX11VirtSpecifier(Tok))
5737 DiagnoseIdentifier = NextToken().isOneOf(
5738 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5739 if (DiagnoseIdentifier) {
Richard Smithf39720b2013-10-13 22:12:28 +00005740 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5741 << FixItHint::CreateRemoval(Tok.getLocation());
Craig Topper161e4db2014-05-21 06:02:52 +00005742 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithf39720b2013-10-13 22:12:28 +00005743 ConsumeToken();
5744 goto PastIdentifier;
5745 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005746 }
Richard Smith0efa75c2012-03-29 01:16:42 +00005747
Douglas Gregor7861a802009-11-03 01:35:08 +00005748 if (Tok.is(tok::l_paren)) {
Richard Smithe303e352018-02-02 22:24:54 +00005749 // If this might be an abstract-declarator followed by a direct-initializer,
5750 // check whether this is a valid declarator chunk. If it can't be, assume
5751 // that it's an initializer instead.
5752 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5753 RevertingTentativeParsingAction PA(*this);
5754 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5755 TPResult::False) {
5756 D.SetIdentifier(nullptr, Tok.getLocation());
5757 goto PastIdentifier;
5758 }
5759 }
5760
Chris Lattneracd58a32006-08-06 17:24:14 +00005761 // direct-declarator: '(' declarator ')'
Chris Lattnere37e2332006-08-15 04:50:22 +00005762 // direct-declarator: '(' attributes declarator ')'
Chris Lattneracd58a32006-08-06 17:24:14 +00005763 // Example: 'char (*X)' or 'int (*XX)(void)'
5764 ParseParenDeclarator(D);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005765
5766 // If the declarator was parenthesized, we entered the declarator
5767 // scope when parsing the parenthesized declarator, then exited
5768 // the scope already. Re-enter the scope, if we need to.
5769 if (D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005770 // If there was an error parsing parenthesized declarator, declarator
Richard Smith0efa75c2012-03-29 01:16:42 +00005771 // scope may have been entered before. Don't do it again.
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005772 if (!D.isInvalidType() &&
Nico Weber6b05f382015-02-18 04:53:03 +00005773 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5774 D.getCXXScopeSpec()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005775 // Change the declaration context for name lookup, until this function
5776 // is exited (and the declarator has been parsed).
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005777 DeclScopeObj.EnterDeclaratorScope();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005778 }
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005779 } else if (D.mayOmitIdentifier()) {
Chris Lattneracd58a32006-08-06 17:24:14 +00005780 // This could be something simple like "int" (in which case the declarator
5781 // portion is empty), if an abstract-declarator is allowed.
Craig Topper161e4db2014-05-21 06:02:52 +00005782 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithb19337f2013-02-20 20:19:27 +00005783
5784 // The grammar for abstract-pack-declarator does not allow grouping parens.
5785 // FIXME: Revisit this once core issue 1488 is resolved.
5786 if (D.hasEllipsis() && D.hasGroupingParens())
5787 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5788 diag::ext_abstract_pack_declarator_parens);
Chris Lattneracd58a32006-08-06 17:24:14 +00005789 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00005790 if (Tok.getKind() == tok::annot_pragma_parser_crash)
David Blaikie5bd4c2a2012-08-21 18:56:49 +00005791 LLVM_BUILTIN_TRAP;
Richard Trieuf4b81d02014-06-24 23:14:24 +00005792 if (Tok.is(tok::l_square))
5793 return ParseMisplacedBracketDeclarator(D);
Faisal Vali421b2d12017-12-29 05:41:00 +00005794 if (D.getContext() == DeclaratorContext::MemberContext) {
Alex Lorenzf1278212017-04-11 15:01:53 +00005795 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5796 // treating these keyword as valid member names.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005797 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
Alex Lorenzf1278212017-04-11 15:01:53 +00005798 Tok.getIdentifierInfo() &&
5799 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5800 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5801 diag::err_expected_member_name_or_semi_objcxx_keyword)
5802 << Tok.getIdentifierInfo()
5803 << (D.getDeclSpec().isEmpty() ? SourceRange()
5804 : D.getDeclSpec().getSourceRange());
5805 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5806 D.SetRangeEnd(Tok.getLocation());
5807 ConsumeToken();
5808 goto PastIdentifier;
5809 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005810 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5811 diag::err_expected_member_name_or_semi)
Richard Trieua1342402014-05-02 23:40:32 +00005812 << (D.getDeclSpec().isEmpty() ? SourceRange()
5813 : D.getDeclSpec().getSourceRange());
Richard Trieuf4b81d02014-06-24 23:14:24 +00005814 } else if (getLangOpts().CPlusPlus) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005815 if (Tok.isOneOf(tok::period, tok::arrow))
Richard Trieu9c672672013-01-26 02:31:38 +00005816 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
Richard Trieu2f586962013-09-05 02:31:33 +00005817 else {
5818 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5819 if (Tok.isAtStartOfLine() && Loc.isValid())
5820 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5821 << getLangOpts().CPlusPlus;
5822 else
Richard Trieuf4b81d02014-06-24 23:14:24 +00005823 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5824 diag::err_expected_unqualified_id)
Richard Trieu2f586962013-09-05 02:31:33 +00005825 << getLangOpts().CPlusPlus;
5826 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005827 } else {
5828 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5829 diag::err_expected_either)
5830 << tok::identifier << tok::l_paren;
5831 }
Craig Topper161e4db2014-05-21 06:02:52 +00005832 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattner8c5dd732008-11-11 06:13:16 +00005833 D.setInvalidType(true);
Chris Lattneracd58a32006-08-06 17:24:14 +00005834 }
Mike Stump11289f42009-09-09 15:08:12 +00005835
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005836 PastIdentifier:
Chris Lattneracd58a32006-08-06 17:24:14 +00005837 assert(D.isPastIdentifier() &&
5838 "Haven't past the location of the identifier yet?");
Mike Stump11289f42009-09-09 15:08:12 +00005839
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005840 // Don't parse attributes unless we have parsed an unparenthesized name.
5841 if (D.hasName() && !D.getNumTypeObjects())
Richard Smith89645bc2013-01-02 12:01:23 +00005842 MaybeParseCXX11Attributes(D);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005843
Chris Lattneracd58a32006-08-06 17:24:14 +00005844 while (1) {
Chris Lattner76c72282007-10-09 17:33:22 +00005845 if (Tok.is(tok::l_paren)) {
David Blaikie15a430a2011-12-04 05:04:18 +00005846 // Enter function-declaration scope, limiting any declarators to the
5847 // function prototype scope, including parameter declarators.
5848 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00005849 Scope::FunctionPrototypeScope|Scope::DeclScope|
5850 (D.isFunctionDeclaratorAFunctionDeclaration()
5851 ? Scope::FunctionDeclarationScope : 0));
5852
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005853 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5854 // In such a case, check if we actually have a function declarator; if it
5855 // is not, the declarator has been fully parsed.
Richard Smith943c4402012-07-30 21:30:52 +00005856 bool IsAmbiguous = false;
Richard Smith4f605af2012-08-18 00:55:03 +00005857 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5858 // The name of the declarator, if any, is tentatively declared within
5859 // a possible direct initializer.
5860 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5861 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5862 TentativelyDeclaredIdentifiers.pop_back();
5863 if (!IsFunctionDecl)
5864 break;
5865 }
John McCall084e83d2011-03-24 11:26:52 +00005866 ParsedAttributes attrs(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005867 BalancedDelimiterTracker T(*this, tok::l_paren);
5868 T.consumeOpen();
Richard Smith943c4402012-07-30 21:30:52 +00005869 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
David Blaikie15a430a2011-12-04 05:04:18 +00005870 PrototypeScope.Exit();
Chris Lattner76c72282007-10-09 17:33:22 +00005871 } else if (Tok.is(tok::l_square)) {
Chris Lattnere8074e62006-08-06 18:30:15 +00005872 ParseBracketDeclarator(D);
Chris Lattneracd58a32006-08-06 17:24:14 +00005873 } else {
5874 break;
5875 }
5876 }
Chad Rosierc1183952012-06-26 22:30:43 +00005877}
Chris Lattneracd58a32006-08-06 17:24:14 +00005878
Richard Smithbdb84f32016-07-22 23:36:59 +00005879void Parser::ParseDecompositionDeclarator(Declarator &D) {
5880 assert(Tok.is(tok::l_square));
5881
5882 // If this doesn't look like a structured binding, maybe it's a misplaced
5883 // array declarator.
5884 // FIXME: Consume the l_square first so we don't need extra lookahead for
5885 // this.
5886 if (!(NextToken().is(tok::identifier) &&
5887 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5888 !(NextToken().is(tok::r_square) &&
5889 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5890 return ParseMisplacedBracketDeclarator(D);
5891
5892 BalancedDelimiterTracker T(*this, tok::l_square);
5893 T.consumeOpen();
5894
5895 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5896 while (Tok.isNot(tok::r_square)) {
5897 if (!Bindings.empty()) {
5898 if (Tok.is(tok::comma))
5899 ConsumeToken();
5900 else {
5901 if (Tok.is(tok::identifier)) {
5902 SourceLocation EndLoc = getEndOfPreviousToken();
5903 Diag(EndLoc, diag::err_expected)
5904 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5905 } else {
5906 Diag(Tok, diag::err_expected_comma_or_rsquare);
5907 }
5908
5909 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5910 StopAtSemi | StopBeforeMatch);
5911 if (Tok.is(tok::comma))
5912 ConsumeToken();
5913 else if (Tok.isNot(tok::identifier))
5914 break;
5915 }
5916 }
5917
5918 if (Tok.isNot(tok::identifier)) {
5919 Diag(Tok, diag::err_expected) << tok::identifier;
5920 break;
5921 }
5922
5923 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
5924 ConsumeToken();
5925 }
5926
5927 if (Tok.isNot(tok::r_square))
5928 // We've already diagnosed a problem here.
5929 T.skipToEnd();
5930 else {
5931 // C++17 does not allow the identifier-list in a structured binding
5932 // to be empty.
5933 if (Bindings.empty())
5934 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
5935
5936 T.consumeClose();
5937 }
5938
5939 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
5940 T.getCloseLocation());
5941}
5942
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005943/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5944/// only called before the identifier, so these are most likely just grouping
Mike Stump11289f42009-09-09 15:08:12 +00005945/// parens for precedence. If we find that these are actually function
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005946/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5947///
5948/// direct-declarator:
5949/// '(' declarator ')'
5950/// [GNU] '(' attributes declarator ')'
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005951/// direct-declarator '(' parameter-type-list ')'
5952/// direct-declarator '(' identifier-list[opt] ')'
5953/// [GNU] direct-declarator '(' parameter-forward-declarations
5954/// parameter-type-list[opt] ')'
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005955///
5956void Parser::ParseParenDeclarator(Declarator &D) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005957 BalancedDelimiterTracker T(*this, tok::l_paren);
5958 T.consumeOpen();
5959
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005960 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
Mike Stump11289f42009-09-09 15:08:12 +00005961
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005962 // Eat any attributes before we look at whether this is a grouping or function
5963 // declarator paren. If this is a grouping paren, the attribute applies to
5964 // the type being built up, for example:
5965 // int (__attribute__(()) *x)(long y)
5966 // If this ends up not being a grouping paren, the attribute applies to the
5967 // first argument, for example:
5968 // int (__attribute__(()) int x)
5969 // In either case, we need to eat any attributes to be able to determine what
5970 // sort of paren this is.
5971 //
John McCall084e83d2011-03-24 11:26:52 +00005972 ParsedAttributes attrs(AttrFactory);
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005973 bool RequiresArg = false;
5974 if (Tok.is(tok::kw___attribute)) {
John McCall53fa7142010-12-24 02:08:15 +00005975 ParseGNUAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00005976
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005977 // We require that the argument list (if this is a non-grouping paren) be
5978 // present even if the attribute list was empty.
5979 RequiresArg = true;
5980 }
Chad Rosiereea9ca72012-12-21 21:22:20 +00005981
Steve Naroff44ac7772008-12-25 14:16:32 +00005982 // Eat any Microsoft extensions.
Chad Rosiereea9ca72012-12-21 21:22:20 +00005983 ParseMicrosoftTypeAttributes(attrs);
5984
Dawn Perchik335e16b2010-09-03 01:29:35 +00005985 // Eat any Borland extensions.
Ted Kremenek5eec2b02010-11-10 05:59:39 +00005986 if (Tok.is(tok::kw___pascal))
John McCall53fa7142010-12-24 02:08:15 +00005987 ParseBorlandTypeAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00005988
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005989 // If we haven't past the identifier yet (or where the identifier would be
5990 // stored, if this is an abstract declarator), then this is probably just
5991 // grouping parens. However, if this could be an abstract-declarator, then
5992 // this could also be the start of function arguments (consider 'void()').
5993 bool isGrouping;
Mike Stump11289f42009-09-09 15:08:12 +00005994
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005995 if (!D.mayOmitIdentifier()) {
5996 // If this can't be an abstract-declarator, this *must* be a grouping
5997 // paren, because we haven't seen the identifier yet.
5998 isGrouping = true;
5999 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
Richard Smith43f340f2012-03-27 23:05:05 +00006000 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6001 NextToken().is(tok::r_paren)) || // C++ int(...)
Richard Smith2620cd92012-04-11 04:01:28 +00006002 isDeclarationSpecifier() || // 'int(int)' is a function.
6003 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006004 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6005 // considered to be a type, not a K&R identifier-list.
6006 isGrouping = false;
6007 } else {
6008 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6009 isGrouping = true;
6010 }
Mike Stump11289f42009-09-09 15:08:12 +00006011
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006012 // If this is a grouping paren, handle:
6013 // direct-declarator: '(' declarator ')'
6014 // direct-declarator: '(' attributes declarator ')'
6015 if (isGrouping) {
Richard Smith0efa75c2012-03-29 01:16:42 +00006016 SourceLocation EllipsisLoc = D.getEllipsisLoc();
6017 D.setEllipsisLoc(SourceLocation());
6018
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006019 bool hadGroupingParens = D.hasGroupingParens();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006020 D.setGroupingParens(true);
Sebastian Redlbd150f42008-11-21 19:14:01 +00006021 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006022 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006023 T.consumeClose();
Erich Keanec480f302018-07-12 21:09:05 +00006024 D.AddTypeInfo(
6025 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6026 std::move(attrs), T.getCloseLocation());
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006027
6028 D.setGroupingParens(hadGroupingParens);
Richard Smith0efa75c2012-03-29 01:16:42 +00006029
6030 // An ellipsis cannot be placed outside parentheses.
6031 if (EllipsisLoc.isValid())
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00006032 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00006033
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006034 return;
6035 }
Mike Stump11289f42009-09-09 15:08:12 +00006036
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006037 // Okay, if this wasn't a grouping paren, it must be the start of a function
6038 // argument list. Recognize that this declarator will never have an
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006039 // identifier (and remember where it would have been), then call into
6040 // ParseFunctionDeclarator to handle of argument list.
Craig Topper161e4db2014-05-21 06:02:52 +00006041 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006042
David Blaikie15a430a2011-12-04 05:04:18 +00006043 // Enter function-declaration scope, limiting any declarators to the
6044 // function prototype scope, including parameter declarators.
6045 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00006046 Scope::FunctionPrototypeScope | Scope::DeclScope |
6047 (D.isFunctionDeclaratorAFunctionDeclaration()
6048 ? Scope::FunctionDeclarationScope : 0));
Richard Smith943c4402012-07-30 21:30:52 +00006049 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
David Blaikie15a430a2011-12-04 05:04:18 +00006050 PrototypeScope.Exit();
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006051}
6052
6053/// ParseFunctionDeclarator - We are after the identifier and have parsed the
6054/// declarator D up to a paren, which indicates that we are parsing function
6055/// arguments.
Chris Lattneracd58a32006-08-06 17:24:14 +00006056///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006057/// If FirstArgAttrs is non-null, then the caller parsed those arguments
6058/// immediately after the open paren - they should be considered to be the
6059/// first argument of a parameter.
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006060///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006061/// If RequiresArg is true, then the first argument of the function is required
6062/// to be present and required to not be an identifier list.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006063///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006064/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6065/// (C++11) ref-qualifier[opt], exception-specification[opt],
6066/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
6067///
6068/// [C++11] exception-specification:
Douglas Gregor9e66af42011-07-05 16:44:18 +00006069/// dynamic-exception-specification
6070/// noexcept-specification
6071///
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006072void Parser::ParseFunctionDeclarator(Declarator &D,
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006073 ParsedAttributes &FirstArgAttrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006074 BalancedDelimiterTracker &Tracker,
Richard Smith943c4402012-07-30 21:30:52 +00006075 bool IsAmbiguous,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006076 bool RequiresArg) {
Chad Rosierc1183952012-06-26 22:30:43 +00006077 assert(getCurScope()->isFunctionPrototypeScope() &&
David Blaikie15a430a2011-12-04 05:04:18 +00006078 "Should call from a Function scope");
Douglas Gregor9e66af42011-07-05 16:44:18 +00006079 // lparen is already consumed!
6080 assert(D.isPastIdentifier() && "Should not call before identifier!");
6081
6082 // This should be true when the function has typed arguments.
6083 // Otherwise, it is treated as a K&R-style function.
6084 bool HasProto = false;
6085 // Build up an array of information about the parsed arguments.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006086 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006087 // Remember where we see an ellipsis, if any.
6088 SourceLocation EllipsisLoc;
6089
6090 DeclSpec DS(AttrFactory);
6091 bool RefQualifierIsLValueRef = true;
6092 SourceLocation RefQualifierLoc;
6093 ExceptionSpecificationType ESpecType = EST_None;
6094 SourceRange ESpecRange;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006095 SmallVector<ParsedType, 2> DynamicExceptions;
6096 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006097 ExprResult NoexceptExpr;
Hans Wennborgdcfba332015-10-06 23:40:43 +00006098 CachedTokens *ExceptionSpecTokens = nullptr;
Aaron Ballman606093a2017-10-15 15:01:42 +00006099 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith700537c2012-06-12 01:51:59 +00006100 TypeResult TrailingReturnType;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006101
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006102 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6103 EndLoc is the end location for the function declarator.
6104 They differ for trailing return types. */
6105 SourceLocation StartLoc, LocalEndLoc, EndLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006106 SourceLocation LParenLoc, RParenLoc;
6107 LParenLoc = Tracker.getOpenLocation();
6108 StartLoc = LParenLoc;
6109
Douglas Gregor9e66af42011-07-05 16:44:18 +00006110 if (isFunctionDeclaratorIdentifierList()) {
6111 if (RequiresArg)
6112 Diag(Tok, diag::err_argument_required_after_attribute);
6113
6114 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6115
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006116 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006117 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006118 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006119 EndLoc = RParenLoc;
Aaron Ballman606093a2017-10-15 15:01:42 +00006120
Fangrui Song6907ce22018-07-30 19:24:48 +00006121 // If there are attributes following the identifier list, parse them and
Aaron Ballman606093a2017-10-15 15:01:42 +00006122 // prohibit them.
6123 MaybeParseCXX11Attributes(FnAttrs);
6124 ProhibitAttributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006125 } else {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006126 if (Tok.isNot(tok::r_paren))
Fangrui Song6907ce22018-07-30 19:24:48 +00006127 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
Faisal Vali2b391ab2013-09-26 19:54:12 +00006128 EllipsisLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006129 else if (RequiresArg)
6130 Diag(Tok, diag::err_argument_required_after_attribute);
6131
Alexey Bader1f277942017-10-11 11:16:31 +00006132 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6133 || getLangOpts().OpenCL;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006134
6135 // If we have the closing ')', eat it.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006136 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006137 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006138 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006139 EndLoc = RParenLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006140
David Blaikiebbafb8a2012-03-11 07:00:24 +00006141 if (getLangOpts().CPlusPlus) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006142 // FIXME: Accept these components in any order, and produce fixits to
6143 // correct the order if the user gets it wrong. Ideally we should deal
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00006144 // with the pure-specifier in the same way.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006145
6146 // Parse cv-qualifier-seq[opt].
Aaron Ballman08b06592014-07-22 12:44:22 +00006147 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
Alex Lorenz8f4d3992017-02-13 23:19:40 +00006148 /*AtomicAllowed*/ false,
6149 /*IdentifierRequired=*/false,
6150 llvm::function_ref<void()>([&]() {
6151 Actions.CodeCompleteFunctionQualifiers(DS, D);
6152 }));
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006153 if (!DS.getSourceRange().getEnd().isInvalid()) {
6154 EndLoc = DS.getSourceRange().getEnd();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006155 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006156
6157 // Parse ref-qualifier[opt].
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006158 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
Douglas Gregor9e66af42011-07-05 16:44:18 +00006159 EndLoc = RefQualifierLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006160
Douglas Gregor3024f072012-04-16 07:05:22 +00006161 // C++11 [expr.prim.general]p3:
Chad Rosierc1183952012-06-26 22:30:43 +00006162 // If a declaration declares a member function or member function
6163 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00006164 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Chad Rosierc1183952012-06-26 22:30:43 +00006165 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00006166 // declarator.
Richard Smithad1bbb92013-03-15 00:41:52 +00006167 // FIXME: currently, "static" case isn't handled correctly.
Chad Rosierc1183952012-06-26 22:30:43 +00006168 bool IsCXX11MemberFunction =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006169 getLangOpts().CPlusPlus11 &&
Richard Smith990a6922014-01-17 21:01:18 +00006170 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
Faisal Vali421b2d12017-12-29 05:41:00 +00006171 (D.getContext() == DeclaratorContext::MemberContext
Richard Smithad1bbb92013-03-15 00:41:52 +00006172 ? !D.getDeclSpec().isFriendSpecified()
Faisal Vali421b2d12017-12-29 05:41:00 +00006173 : D.getContext() == DeclaratorContext::FileContext &&
Richard Smithad1bbb92013-03-15 00:41:52 +00006174 D.getCXXScopeSpec().isValid() &&
6175 Actions.CurContext->isRecord());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006176
6177 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6178 if (D.getDeclSpec().isConstexprSpecified() && !getLangOpts().CPlusPlus14)
6179 Q.addConst();
Anastasia Stulova5cffa452019-01-21 16:01:38 +00006180 // FIXME: Collect C++ address spaces.
6181 // If there are multiple different address spaces, the source is invalid.
6182 // Carry on using the first addr space for the qualifiers of 'this'.
6183 // The diagnostic will be given later while creating the function
6184 // prototype for the method.
6185 if (getLangOpts().OpenCLCPlusPlus) {
6186 for (ParsedAttr &attr : DS.getAttributes()) {
6187 LangAS ASIdx = attr.asOpenCLLangAS();
6188 if (ASIdx != LangAS::Default) {
6189 Q.addAddressSpace(ASIdx);
6190 break;
6191 }
6192 }
6193 }
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006194
6195 Sema::CXXThisScopeRAII ThisScope(
6196 Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6197 IsCXX11MemberFunction);
Richard Smith2331bbf2012-05-02 22:22:32 +00006198
Douglas Gregor9e66af42011-07-05 16:44:18 +00006199 // Parse exception-specification[opt].
Richard Smith0b3a4622014-11-13 20:01:57 +00006200 bool Delayed = D.isFirstDeclarationOfMember() &&
Richard Smith3ef3e892014-11-20 22:32:11 +00006201 D.isFunctionDeclaratorAFunctionDeclaration();
6202 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6203 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6204 GetLookAheadToken(1).is(tok::l_paren) &&
6205 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6206 GetLookAheadToken(3).is(tok::l_paren) &&
6207 GetLookAheadToken(4).is(tok::identifier) &&
6208 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6209 // HACK: We've got an exception-specification
6210 // noexcept(noexcept(swap(...)))
6211 // or
6212 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6213 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6214 // for 'swap' will only find the function we're currently declaring,
6215 // whereas it expects to find a non-member swap through ADL. Turn off
6216 // delayed parsing to give it a chance to find what it expects.
6217 Delayed = false;
6218 }
Richard Smith0b3a4622014-11-13 20:01:57 +00006219 ESpecType = tryParseExceptionSpecification(Delayed,
6220 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00006221 DynamicExceptions,
6222 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00006223 NoexceptExpr,
6224 ExceptionSpecTokens);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006225 if (ESpecType != EST_None)
6226 EndLoc = ESpecRange.getEnd();
6227
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006228 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6229 // after the exception-specification.
Richard Smith89645bc2013-01-02 12:01:23 +00006230 MaybeParseCXX11Attributes(FnAttrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006231
Douglas Gregor9e66af42011-07-05 16:44:18 +00006232 // Parse trailing-return-type[opt].
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006233 LocalEndLoc = EndLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006234 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00006235 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
Faisal Vali090da2d2018-01-01 18:23:28 +00006236 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006237 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006238 LocalEndLoc = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00006239 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00006240 TrailingReturnType =
6241 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006242 EndLoc = Range.getEnd();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006243 }
Aaron Ballman606093a2017-10-15 15:01:42 +00006244 } else if (standardAttributesAllowed()) {
6245 MaybeParseCXX11Attributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006246 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006247 }
6248
Reid Kleckner078aea92016-12-09 17:14:05 +00006249 // Collect non-parameter declarations from the prototype if this is a function
6250 // declaration. They will be moved into the scope of the function. Only do
6251 // this in C and not C++, where the decls will continue to live in the
6252 // surrounding context.
6253 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6254 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6255 !getLangOpts().CPlusPlus) {
6256 for (Decl *D : getCurScope()->decls()) {
6257 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6258 if (!ND || isa<ParmVarDecl>(ND))
6259 continue;
6260 DeclsInPrototype.push_back(ND);
6261 }
6262 }
6263
Douglas Gregor9e66af42011-07-05 16:44:18 +00006264 // Remember that we parsed a function type, and remember the attributes.
Erich Keanec480f302018-07-12 21:09:05 +00006265 D.AddTypeInfo(DeclaratorChunk::getFunction(
6266 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6267 ParamInfo.size(), EllipsisLoc, RParenLoc,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00006268 RefQualifierIsLValueRef, RefQualifierLoc,
6269 /*MutableLoc=*/SourceLocation(),
6270 ESpecType, ESpecRange, DynamicExceptions.data(),
6271 DynamicExceptionRanges.data(), DynamicExceptions.size(),
Erich Keanec480f302018-07-12 21:09:05 +00006272 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6273 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00006274 LocalEndLoc, D, TrailingReturnType, &DS),
Erich Keanec480f302018-07-12 21:09:05 +00006275 std::move(FnAttrs), EndLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006276}
6277
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006278/// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6279/// true if a ref-qualifier is found.
6280bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6281 SourceLocation &RefQualifierLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00006282 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006283 Diag(Tok, getLangOpts().CPlusPlus11 ?
6284 diag::warn_cxx98_compat_ref_qualifier :
6285 diag::ext_ref_qualifier);
6286
6287 RefQualifierIsLValueRef = Tok.is(tok::amp);
6288 RefQualifierLoc = ConsumeToken();
6289 return true;
6290 }
6291 return false;
6292}
6293
Douglas Gregor9e66af42011-07-05 16:44:18 +00006294/// isFunctionDeclaratorIdentifierList - This parameter list may have an
6295/// identifier list form for a K&R-style function: void foo(a,b,c)
6296///
6297/// Note that identifier-lists are only allowed for normal declarators, not for
6298/// abstract-declarators.
6299bool Parser::isFunctionDeclaratorIdentifierList() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006300 return !getLangOpts().CPlusPlus
Douglas Gregor9e66af42011-07-05 16:44:18 +00006301 && Tok.is(tok::identifier)
6302 && !TryAltiVecVectorToken()
6303 // K&R identifier lists can't have typedefs as identifiers, per C99
6304 // 6.7.5.3p11.
6305 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6306 // Identifier lists follow a really simple grammar: the identifiers can
6307 // be followed *only* by a ", identifier" or ")". However, K&R
6308 // identifier lists are really rare in the brave new modern world, and
6309 // it is very common for someone to typo a type in a non-K&R style
6310 // list. If we are presented with something like: "void foo(intptr x,
6311 // float y)", we don't want to start parsing the function declarator as
6312 // though it is a K&R style declarator just because intptr is an
6313 // invalid type.
6314 //
6315 // To handle this, we check to see if the token after the first
6316 // identifier is a "," or ")". Only then do we parse it as an
6317 // identifier list.
Bruno Cardoso Lopes218c8742016-09-13 20:04:35 +00006318 && (!Tok.is(tok::eof) &&
6319 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006320}
6321
6322/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6323/// we found a K&R-style identifier list instead of a typed parameter list.
6324///
6325/// After returning, ParamInfo will hold the parsed parameters.
6326///
6327/// identifier-list: [C99 6.7.5]
6328/// identifier
6329/// identifier-list ',' identifier
6330///
6331void Parser::ParseFunctionDeclaratorIdentifierList(
6332 Declarator &D,
Craig Topper5603df42013-07-05 19:34:19 +00006333 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006334 // If there was no identifier specified for the declarator, either we are in
6335 // an abstract-declarator, or we are in a parameter declarator which was found
6336 // to be abstract. In abstract-declarators, identifier lists are not valid:
6337 // diagnose this.
6338 if (!D.getIdentifier())
6339 Diag(Tok, diag::ext_ident_list_in_param);
6340
6341 // Maintain an efficient lookup of params we have seen so far.
6342 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6343
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006344 do {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006345 // If this isn't an identifier, report the error and skip until ')'.
6346 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00006347 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00006348 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006349 // Forget we parsed anything.
6350 ParamInfo.clear();
6351 return;
6352 }
6353
6354 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6355
6356 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6357 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6358 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6359
6360 // Verify that the argument identifier has not already been mentioned.
David Blaikie82e95a32014-11-19 07:49:47 +00006361 if (!ParamsSoFar.insert(ParmII).second) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006362 Diag(Tok, diag::err_param_redefinition) << ParmII;
6363 } else {
6364 // Remember this identifier in ParamInfo.
6365 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6366 Tok.getLocation(),
Craig Topper161e4db2014-05-21 06:02:52 +00006367 nullptr));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006368 }
6369
6370 // Eat the identifier.
6371 ConsumeToken();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006372 // The list continues if we see a comma.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006373 } while (TryConsumeToken(tok::comma));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006374}
6375
6376/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6377/// after the opening parenthesis. This function will not parse a K&R-style
6378/// identifier list.
6379///
Richard Smith2620cd92012-04-11 04:01:28 +00006380/// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6381/// caller parsed those arguments immediately after the open paren - they should
6382/// be considered to be part of the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006383///
6384/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6385/// be the location of the ellipsis, if any was parsed.
6386///
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006387/// parameter-type-list: [C99 6.7.5]
6388/// parameter-list
6389/// parameter-list ',' '...'
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006390/// [C++] parameter-list '...'
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006391///
6392/// parameter-list: [C99 6.7.5]
6393/// parameter-declaration
6394/// parameter-list ',' parameter-declaration
6395///
6396/// parameter-declaration: [C99 6.7.5]
6397/// declaration-specifiers declarator
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006398/// [C++] declaration-specifiers declarator '=' assignment-expression
Sebastian Redldb63af22012-03-14 15:54:00 +00006399/// [C++11] initializer-clause
Chris Lattnere37e2332006-08-15 04:50:22 +00006400/// [GNU] declaration-specifiers declarator attributes
Sebastian Redlf769df52009-03-24 22:27:57 +00006401/// declaration-specifiers abstract-declarator[opt]
6402/// [C++] declaration-specifiers abstract-declarator[opt]
Chris Lattner58258242008-04-10 02:22:51 +00006403/// '=' assignment-expression
Chris Lattnere37e2332006-08-15 04:50:22 +00006404/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
Richard Smith2620cd92012-04-11 04:01:28 +00006405/// [C++11] attribute-specifier-seq parameter-declaration
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006406///
Douglas Gregor9e66af42011-07-05 16:44:18 +00006407void Parser::ParseParameterDeclarationClause(
6408 Declarator &D,
Richard Smith2620cd92012-04-11 04:01:28 +00006409 ParsedAttributes &FirstArgAttrs,
Craig Topper5603df42013-07-05 19:34:19 +00006410 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006411 SourceLocation &EllipsisLoc) {
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006412 do {
6413 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6414 // before deciding this was a parameter-declaration-clause.
6415 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Chris Lattner371ed4e2008-04-06 06:57:35 +00006416 break;
Mike Stump11289f42009-09-09 15:08:12 +00006417
Chris Lattner371ed4e2008-04-06 06:57:35 +00006418 // Parse the declaration-specifiers.
John McCall28a6aea2009-11-04 02:18:39 +00006419 // Just use the ParsingDeclaration "scope" of the declarator.
John McCall084e83d2011-03-24 11:26:52 +00006420 DeclSpec DS(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006421
Richard Smith2620cd92012-04-11 04:01:28 +00006422 // Parse any C++11 attributes.
Richard Smith89645bc2013-01-02 12:01:23 +00006423 MaybeParseCXX11Attributes(DS.getAttributes());
Richard Smith2620cd92012-04-11 04:01:28 +00006424
John McCall53fa7142010-12-24 02:08:15 +00006425 // Skip any Microsoft attributes before a param.
Chad Rosierf8a2e702012-12-20 20:37:53 +00006426 MaybeParseMicrosoftAttributes(DS.getAttributes());
John McCall53fa7142010-12-24 02:08:15 +00006427
6428 SourceLocation DSStart = Tok.getLocation();
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006429
6430 // If the caller parsed attributes for the first argument, add them now.
John McCall53fa7142010-12-24 02:08:15 +00006431 // Take them so that we only apply the attributes to the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006432 // FIXME: If we can leave the attributes in the token stream somehow, we can
Richard Smith2620cd92012-04-11 04:01:28 +00006433 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6434 // too much hassle.
6435 DS.takeAttributesFrom(FirstArgAttrs);
John McCall53fa7142010-12-24 02:08:15 +00006436
Faisal Valia534f072018-04-26 00:42:40 +00006437 ParseDeclarationSpecifiers(DS);
Mike Stump11289f42009-09-09 15:08:12 +00006438
Faisal Vali2b391ab2013-09-26 19:54:12 +00006439
Fangrui Song6907ce22018-07-30 19:24:48 +00006440 // Parse the declarator. This is "PrototypeContext" or
6441 // "LambdaExprParameterContext", because we must accept either
Faisal Vali2b391ab2013-09-26 19:54:12 +00006442 // 'declarator' or 'abstract-declarator' here.
Faisal Vali421b2d12017-12-29 05:41:00 +00006443 Declarator ParmDeclarator(
6444 DS, D.getContext() == DeclaratorContext::LambdaExprContext
6445 ? DeclaratorContext::LambdaExprParameterContext
6446 : DeclaratorContext::PrototypeContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00006447 ParseDeclarator(ParmDeclarator);
Chris Lattner371ed4e2008-04-06 06:57:35 +00006448
6449 // Parse GNU attributes, if present.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006450 MaybeParseGNUAttributes(ParmDeclarator);
Mike Stump11289f42009-09-09 15:08:12 +00006451
Chris Lattner371ed4e2008-04-06 06:57:35 +00006452 // Remember this parsed parameter in ParamInfo.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006453 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
Mike Stump11289f42009-09-09 15:08:12 +00006454
Douglas Gregor4d87df52008-12-16 21:30:33 +00006455 // DefArgToks is used when the parsing of default arguments needs
6456 // to be delayed.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006457 std::unique_ptr<CachedTokens> DefArgToks;
Douglas Gregor4d87df52008-12-16 21:30:33 +00006458
Chris Lattner371ed4e2008-04-06 06:57:35 +00006459 // If no parameter was specified, verify that *something* was specified,
6460 // otherwise we have a missing type and identifier.
Craig Topper161e4db2014-05-21 06:02:52 +00006461 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
Faisal Vali2b391ab2013-09-26 19:54:12 +00006462 ParmDeclarator.getNumTypeObjects() == 0) {
Chris Lattner371ed4e2008-04-06 06:57:35 +00006463 // Completely missing, emit error.
6464 Diag(DSStart, diag::err_missing_param);
6465 } else {
6466 // Otherwise, we have something. Add it and let semantic analysis try
6467 // to grok it and add the result to the ParamInfo we are building.
Mike Stump11289f42009-09-09 15:08:12 +00006468
Richard Smith36ee9fb2014-08-11 23:30:23 +00006469 // Last chance to recover from a misplaced ellipsis in an attempted
6470 // parameter pack declaration.
6471 if (Tok.is(tok::ellipsis) &&
6472 (NextToken().isNot(tok::r_paren) ||
6473 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6474 !Actions.isUnexpandedParameterPackPermitted())) &&
6475 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6476 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6477
Chris Lattner371ed4e2008-04-06 06:57:35 +00006478 // Inform the actions module about the parameter declarator, so it gets
6479 // added to the current scope.
Richard Smith95e1fb02014-08-27 03:23:12 +00006480 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006481 // Parse the default argument, if any. We parse the default
6482 // arguments in all dialects; the semantic analysis in
6483 // ActOnParamDefaultArgument will reject the default argument in
6484 // C.
6485 if (Tok.is(tok::equal)) {
Douglas Gregor58354032008-12-24 00:01:03 +00006486 SourceLocation EqualLoc = Tok.getLocation();
6487
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006488 // Parse the default argument
Faisal Vali421b2d12017-12-29 05:41:00 +00006489 if (D.getContext() == DeclaratorContext::MemberContext) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006490 // If we're inside a class definition, cache the tokens
6491 // corresponding to the default argument. We'll actually parse
6492 // them when we see the end of the class definition.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006493 DefArgToks.reset(new CachedTokens);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006494
David Majnemer906ed272015-01-13 05:28:24 +00006495 SourceLocation ArgStartLoc = NextToken().getLocation();
Richard Smith1fff95c2013-09-12 23:28:08 +00006496 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006497 DefArgToks.reset();
Serge Pavlovb4b35782014-07-22 01:54:49 +00006498 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006499 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006500 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
David Majnemer906ed272015-01-13 05:28:24 +00006501 ArgStartLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006502 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006503 } else {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006504 // Consume the '='.
Douglas Gregor58354032008-12-24 00:01:03 +00006505 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00006506
Chad Rosierc1183952012-06-26 22:30:43 +00006507 // The argument isn't actually potentially evaluated unless it is
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006508 // used.
Faisal Valid143a0c2017-04-01 21:30:49 +00006509 EnterExpressionEvaluationContext Eval(
6510 Actions,
6511 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6512 Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006513
Sebastian Redldb63af22012-03-14 15:54:00 +00006514 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006515 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006516 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +00006517 DefArgResult = ParseBraceInitializer();
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006518 } else
Sebastian Redldb63af22012-03-14 15:54:00 +00006519 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +00006520 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006521 if (DefArgResult.isInvalid()) {
Serge Pavlovb4b35782014-07-22 01:54:49 +00006522 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Alexey Bataevee6507d2013-11-18 08:17:37 +00006523 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006524 } else {
6525 // Inform the actions module about the default argument
6526 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006527 DefArgResult.get());
Douglas Gregor4d87df52008-12-16 21:30:33 +00006528 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006529 }
6530 }
Mike Stump11289f42009-09-09 15:08:12 +00006531
6532 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
Fangrui Song6907ce22018-07-30 19:24:48 +00006533 ParmDeclarator.getIdentifierLoc(),
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006534 Param, std::move(DefArgToks)));
Chris Lattner371ed4e2008-04-06 06:57:35 +00006535 }
6536
Richard Smith36ee9fb2014-08-11 23:30:23 +00006537 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6538 if (!getLangOpts().CPlusPlus) {
6539 // We have ellipsis without a preceding ',', which is ill-formed
6540 // in C. Complain and provide the fix.
6541 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6542 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6543 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6544 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6545 // It looks like this was supposed to be a parameter pack. Warn and
6546 // point out where the ellipsis should have gone.
6547 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6548 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6549 << ParmEllipsis.isValid() << ParmEllipsis;
6550 if (ParmEllipsis.isValid()) {
6551 Diag(ParmEllipsis,
6552 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6553 } else {
6554 Diag(ParmDeclarator.getIdentifierLoc(),
6555 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6556 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6557 "...")
6558 << !ParmDeclarator.hasName();
6559 }
6560 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006561 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
Richard Smith36ee9fb2014-08-11 23:30:23 +00006562 }
6563
6564 // We can't have any more parameters after an ellipsis.
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006565 break;
6566 }
Mike Stump11289f42009-09-09 15:08:12 +00006567
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006568 // If the next token is a comma, consume it and keep reading arguments.
6569 } while (TryConsumeToken(tok::comma));
Chris Lattner6c940e62008-04-06 06:34:08 +00006570}
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006571
Chris Lattnere8074e62006-08-06 18:30:15 +00006572/// [C90] direct-declarator '[' constant-expression[opt] ']'
6573/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6574/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6575/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6576/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006577/// [C++11] direct-declarator '[' constant-expression[opt] ']'
6578/// attribute-specifier-seq[opt]
Chris Lattnere8074e62006-08-06 18:30:15 +00006579void Parser::ParseBracketDeclarator(Declarator &D) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006580 if (CheckProhibitedCXX11Attribute())
6581 return;
6582
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006583 BalancedDelimiterTracker T(*this, tok::l_square);
6584 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00006585
Chris Lattner84a11622008-12-18 07:27:21 +00006586 // C array syntax has many features, but by-far the most common is [] and [4].
6587 // This code does a fast path to handle some of the most obvious cases.
6588 if (Tok.getKind() == tok::r_square) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006589 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006590 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006591 MaybeParseCXX11Attributes(attrs);
Chad Rosierc1183952012-06-26 22:30:43 +00006592
Chris Lattner84a11622008-12-18 07:27:21 +00006593 // Remember that we parsed the empty array type.
Craig Topper161e4db2014-05-21 06:02:52 +00006594 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006595 T.getOpenLocation(),
6596 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006597 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006598 return;
6599 } else if (Tok.getKind() == tok::numeric_constant &&
6600 GetLookAheadToken(1).is(tok::r_square)) {
6601 // [4] is very common. Parse the numeric constant expression.
Richard Smithbcc22fc2012-03-09 08:00:36 +00006602 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
Chris Lattner84a11622008-12-18 07:27:21 +00006603 ConsumeToken();
6604
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006605 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006606 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006607 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006608
Chris Lattner84a11622008-12-18 07:27:21 +00006609 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006610 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006611 T.getOpenLocation(),
6612 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006613 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006614 return;
Benjamin Kramer72dae622016-02-18 15:30:24 +00006615 } else if (Tok.getKind() == tok::code_completion) {
6616 Actions.CodeCompleteBracketDeclarator(getCurScope());
6617 return cutOffParsing();
Chris Lattner84a11622008-12-18 07:27:21 +00006618 }
Mike Stump11289f42009-09-09 15:08:12 +00006619
Chris Lattnere8074e62006-08-06 18:30:15 +00006620 // If valid, this location is the position where we read the 'static' keyword.
6621 SourceLocation StaticLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006622 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006623
Chris Lattnere8074e62006-08-06 18:30:15 +00006624 // If there is a type-qualifier-list, read it now.
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006625 // Type qualifiers in an array subscript are a C99 feature.
John McCall084e83d2011-03-24 11:26:52 +00006626 DeclSpec DS(AttrFactory);
Aaron Ballman08b06592014-07-22 12:44:22 +00006627 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
Mike Stump11289f42009-09-09 15:08:12 +00006628
Chris Lattnere8074e62006-08-06 18:30:15 +00006629 // If we haven't already read 'static', check to see if there is one after the
6630 // type-qualifier-list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006631 if (!StaticLoc.isValid())
6632 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006633
Chris Lattnere8074e62006-08-06 18:30:15 +00006634 // Handle "direct-declarator [ type-qual-list[opt] * ]".
Chris Lattnere8074e62006-08-06 18:30:15 +00006635 bool isStar = false;
John McCalldadc5752010-08-24 06:29:42 +00006636 ExprResult NumElements;
Mike Stump11289f42009-09-09 15:08:12 +00006637
Chris Lattner521ff2b2008-04-06 05:26:30 +00006638 // Handle the case where we have '[*]' as the array size. However, a leading
6639 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
Sylvestre Ledru830885c2012-07-23 08:59:39 +00006640 // the token after the star is a ']'. Since stars in arrays are
Chris Lattner521ff2b2008-04-06 05:26:30 +00006641 // infrequent, use of lookahead is not costly here.
6642 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
Chris Lattnerc439f0d2008-04-06 05:27:21 +00006643 ConsumeToken(); // Eat the '*'.
Chris Lattner1906f802006-08-06 19:14:46 +00006644
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006645 if (StaticLoc.isValid()) {
Chris Lattner521ff2b2008-04-06 05:26:30 +00006646 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006647 StaticLoc = SourceLocation(); // Drop the static.
6648 }
Chris Lattner521ff2b2008-04-06 05:26:30 +00006649 isStar = true;
Chris Lattner76c72282007-10-09 17:33:22 +00006650 } else if (Tok.isNot(tok::r_square)) {
Chris Lattner84a11622008-12-18 07:27:21 +00006651 // Note, in C89, this production uses the constant-expr production instead
6652 // of assignment-expr. The only difference is that assignment-expr allows
6653 // things like '=' and '*='. Sema rejects these in C89 mode because they
6654 // are not i-c-e's, so we don't need to distinguish between the two here.
Mike Stump11289f42009-09-09 15:08:12 +00006655
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006656 // Parse the constant-expression or assignment-expression now (depending
6657 // on dialect).
David Blaikiebbafb8a2012-03-11 07:00:24 +00006658 if (getLangOpts().CPlusPlus) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006659 NumElements = ParseConstantExpression();
Eli Friedmane0afc982012-01-21 01:01:51 +00006660 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00006661 EnterExpressionEvaluationContext Unevaluated(
6662 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Kaelyn Takata15867822014-11-21 18:48:04 +00006663 NumElements =
6664 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Eli Friedmane0afc982012-01-21 01:01:51 +00006665 }
David Majnemerf9834d52014-08-08 07:21:18 +00006666 } else {
6667 if (StaticLoc.isValid()) {
6668 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6669 StaticLoc = SourceLocation(); // Drop the static.
6670 }
Chris Lattner62591722006-08-12 18:40:58 +00006671 }
Mike Stump11289f42009-09-09 15:08:12 +00006672
Chris Lattner62591722006-08-12 18:40:58 +00006673 // If there was an error parsing the assignment-expression, recover.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00006674 if (NumElements.isInvalid()) {
Chris Lattnercd2a8c52009-04-24 22:30:50 +00006675 D.setInvalidType(true);
Chris Lattner62591722006-08-12 18:40:58 +00006676 // If the expression was invalid, skip it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00006677 SkipUntil(tok::r_square, StopAtSemi);
Chris Lattner62591722006-08-12 18:40:58 +00006678 return;
Chris Lattnere8074e62006-08-06 18:30:15 +00006679 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006680
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006681 T.consumeClose();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006682
Jordan Rose303e2f12016-11-10 23:28:17 +00006683 MaybeParseCXX11Attributes(DS.getAttributes());
Alexis Hunt96d5c762009-11-21 08:43:09 +00006684
Chris Lattner84a11622008-12-18 07:27:21 +00006685 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006686 D.AddTypeInfo(
6687 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6688 isStar, NumElements.get(), T.getOpenLocation(),
6689 T.getCloseLocation()),
6690 std::move(DS.getAttributes()), T.getCloseLocation());
Chris Lattnere8074e62006-08-06 18:30:15 +00006691}
6692
Richard Trieuf4b81d02014-06-24 23:14:24 +00006693/// Diagnose brackets before an identifier.
6694void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6695 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6696 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6697
6698 SourceLocation StartBracketLoc = Tok.getLocation();
6699 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6700
6701 while (Tok.is(tok::l_square)) {
6702 ParseBracketDeclarator(TempDeclarator);
6703 }
6704
6705 // Stuff the location of the start of the brackets into the Declarator.
6706 // The diagnostics from ParseDirectDeclarator will make more sense if
6707 // they use this location instead.
6708 if (Tok.is(tok::semi))
6709 D.getName().EndLocation = StartBracketLoc;
6710
6711 SourceLocation SuggestParenLoc = Tok.getLocation();
6712
6713 // Now that the brackets are removed, try parsing the declarator again.
6714 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6715
6716 // Something went wrong parsing the brackets, in which case,
6717 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6718 // one here.
6719 if (TempDeclarator.getNumTypeObjects() == 0)
6720 return;
6721
6722 // Determine if parens will need to be suggested in the diagnostic.
6723 bool NeedParens = false;
6724 if (D.getNumTypeObjects() != 0) {
6725 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6726 case DeclaratorChunk::Pointer:
6727 case DeclaratorChunk::Reference:
6728 case DeclaratorChunk::BlockPointer:
6729 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00006730 case DeclaratorChunk::Pipe:
Richard Trieuf4b81d02014-06-24 23:14:24 +00006731 NeedParens = true;
6732 break;
6733 case DeclaratorChunk::Array:
6734 case DeclaratorChunk::Function:
6735 case DeclaratorChunk::Paren:
6736 break;
6737 }
6738 }
6739
6740 if (NeedParens) {
6741 // Create a DeclaratorChunk for the inserted parens.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006742 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Erich Keanec480f302018-07-12 21:09:05 +00006743 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
Richard Trieuf4b81d02014-06-24 23:14:24 +00006744 SourceLocation());
6745 }
6746
6747 // Adding back the bracket info to the end of the Declarator.
6748 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6749 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
Erich Keanec480f302018-07-12 21:09:05 +00006750 D.AddTypeInfo(Chunk, SourceLocation());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006751 }
6752
6753 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6754 // If parentheses are required, always suggest them.
6755 if (!D.getIdentifier() && !NeedParens)
6756 return;
6757
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006758 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
Richard Trieuf4b81d02014-06-24 23:14:24 +00006759
6760 // Generate the move bracket error message.
6761 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006762 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006763
6764 if (NeedParens) {
6765 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6766 << getLangOpts().CPlusPlus
6767 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6768 << FixItHint::CreateInsertion(EndLoc, ")")
6769 << FixItHint::CreateInsertionFromRange(
6770 EndLoc, CharSourceRange(BracketRange, true))
6771 << FixItHint::CreateRemoval(BracketRange);
6772 } else {
6773 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6774 << getLangOpts().CPlusPlus
6775 << FixItHint::CreateInsertionFromRange(
6776 EndLoc, CharSourceRange(BracketRange, true))
6777 << FixItHint::CreateRemoval(BracketRange);
6778 }
6779}
6780
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006781/// [GNU] typeof-specifier:
6782/// typeof ( expressions )
6783/// typeof ( type-name )
6784/// [GNU/C++] typeof unary-expression
Steve Naroffad373bd2007-07-31 12:34:36 +00006785///
6786void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
Chris Lattner76c72282007-10-09 17:33:22 +00006787 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006788 Token OpTok = Tok;
Steve Naroffad373bd2007-07-31 12:34:36 +00006789 SourceLocation StartLoc = ConsumeToken();
6790
John McCalle8595032010-01-13 20:03:27 +00006791 const bool hasParens = Tok.is(tok::l_paren);
6792
Faisal Valid143a0c2017-04-01 21:30:49 +00006793 EnterExpressionEvaluationContext Unevaluated(
6794 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6795 Sema::ReuseLambdaContextDecl);
Eli Friedmane0afc982012-01-21 01:01:51 +00006796
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006797 bool isCastExpr;
John McCallba7bf592010-08-24 05:47:05 +00006798 ParsedType CastTy;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006799 SourceRange CastRange;
Kaelyn Takata911260742014-12-19 01:28:40 +00006800 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6801 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
John McCalle8595032010-01-13 20:03:27 +00006802 if (hasParens)
6803 DS.setTypeofParensRange(CastRange);
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006804
6805 if (CastRange.getEnd().isInvalid())
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006806 // FIXME: Not accurate, the range gets one token more than it should.
6807 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006808 else
6809 DS.SetRangeEnd(CastRange.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +00006810
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006811 if (isCastExpr) {
6812 if (!CastTy) {
6813 DS.SetTypeSpecError();
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006814 return;
Douglas Gregor220cac52009-02-18 17:45:20 +00006815 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006816
Craig Topper161e4db2014-05-21 06:02:52 +00006817 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006818 unsigned DiagID;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006819 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6820 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006821 DiagID, CastTy,
6822 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006823 Diag(StartLoc, DiagID) << PrevSpec;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006824 return;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006825 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006826
Hiroshi Inoue533777f2017-07-02 06:12:49 +00006827 // If we get here, the operand to the typeof was an expression.
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006828 if (Operand.isInvalid()) {
6829 DS.SetTypeSpecError();
Steve Naroff4bd2f712007-08-02 02:53:48 +00006830 return;
Steve Naroffad373bd2007-07-31 12:34:36 +00006831 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006832
Eli Friedmane0afc982012-01-21 01:01:51 +00006833 // We might need to transform the operand if it is potentially evaluated.
6834 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6835 if (Operand.isInvalid()) {
6836 DS.SetTypeSpecError();
6837 return;
6838 }
6839
Craig Topper161e4db2014-05-21 06:02:52 +00006840 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006841 unsigned DiagID;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006842 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6843 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006844 DiagID, Operand.get(),
6845 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006846 Diag(StartLoc, DiagID) << PrevSpec;
Steve Naroffad373bd2007-07-31 12:34:36 +00006847}
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006848
Benjamin Kramere56f3932011-12-23 17:00:35 +00006849/// [C11] atomic-specifier:
Eli Friedman0dfb8892011-10-06 23:00:33 +00006850/// _Atomic ( type-name )
6851///
6852void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
Richard Smith8e1ac332013-03-28 01:55:44 +00006853 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6854 "Not an atomic specifier");
Eli Friedman0dfb8892011-10-06 23:00:33 +00006855
6856 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006857 BalancedDelimiterTracker T(*this, tok::l_paren);
Richard Smith8e1ac332013-03-28 01:55:44 +00006858 if (T.consumeOpen())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006859 return;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006860
6861 TypeResult Result = ParseTypeName();
6862 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00006863 SkipUntil(tok::r_paren, StopAtSemi);
Eli Friedman0dfb8892011-10-06 23:00:33 +00006864 return;
6865 }
6866
6867 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006868 T.consumeClose();
Eli Friedman0dfb8892011-10-06 23:00:33 +00006869
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006870 if (T.getCloseLocation().isInvalid())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006871 return;
6872
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006873 DS.setTypeofParensRange(T.getRange());
6874 DS.SetRangeEnd(T.getCloseLocation());
Eli Friedman0dfb8892011-10-06 23:00:33 +00006875
Craig Topper161e4db2014-05-21 06:02:52 +00006876 const char *PrevSpec = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006877 unsigned DiagID;
6878 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006879 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006880 Actions.getASTContext().getPrintingPolicy()))
Eli Friedman0dfb8892011-10-06 23:00:33 +00006881 Diag(StartLoc, DiagID) << PrevSpec;
6882}
6883
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006884/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6885/// from TryAltiVecVectorToken.
6886bool Parser::TryAltiVecVectorTokenOutOfLine() {
6887 Token Next = NextToken();
6888 switch (Next.getKind()) {
6889 default: return false;
6890 case tok::kw_short:
6891 case tok::kw_long:
6892 case tok::kw_signed:
6893 case tok::kw_unsigned:
6894 case tok::kw_void:
6895 case tok::kw_char:
6896 case tok::kw_int:
6897 case tok::kw_float:
6898 case tok::kw_double:
6899 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006900 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006901 case tok::kw___pixel:
6902 Tok.setKind(tok::kw___vector);
6903 return true;
6904 case tok::identifier:
6905 if (Next.getIdentifierInfo() == Ident_pixel) {
6906 Tok.setKind(tok::kw___vector);
6907 return true;
6908 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006909 if (Next.getIdentifierInfo() == Ident_bool) {
6910 Tok.setKind(tok::kw___vector);
6911 return true;
6912 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006913 return false;
6914 }
6915}
6916
6917bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6918 const char *&PrevSpec, unsigned &DiagID,
6919 bool &isInvalid) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006920 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006921 if (Tok.getIdentifierInfo() == Ident_vector) {
6922 Token Next = NextToken();
6923 switch (Next.getKind()) {
6924 case tok::kw_short:
6925 case tok::kw_long:
6926 case tok::kw_signed:
6927 case tok::kw_unsigned:
6928 case tok::kw_void:
6929 case tok::kw_char:
6930 case tok::kw_int:
6931 case tok::kw_float:
6932 case tok::kw_double:
6933 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006934 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006935 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006936 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006937 return true;
6938 case tok::identifier:
6939 if (Next.getIdentifierInfo() == Ident_pixel) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006940 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006941 return true;
6942 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006943 if (Next.getIdentifierInfo() == Ident_bool) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006944 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00006945 return true;
6946 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006947 break;
6948 default:
6949 break;
6950 }
Douglas Gregor9938e3b2010-06-16 15:28:57 +00006951 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006952 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006953 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006954 return true;
Bill Schmidt99a084b2013-07-03 20:54:09 +00006955 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6956 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006957 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00006958 return true;
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006959 }
6960 return false;
6961}