blob: f883ecc45f1854792af33d6239e1e098e4e24b64 [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)) {
Leonard Chanef2dc252019-05-03 03:28:06 +0000136 ConsumeToken();
Steve Naroff0f2fe172007-06-01 17:11:19 +0000137 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]
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001737/// [OMP] threadprivate-directive
1738/// [OMP] allocate-directive [TODO]
Chris Lattner32dc41c2009-03-29 17:27:48 +00001739///
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001740/// for-range-declaration: [C++11 6.5p1: stmt.ranged]
Richard Smith02e85f32011-04-14 22:09:26 +00001741/// attribute-specifier-seq[opt] type-specifier-seq declarator
1742///
Chris Lattner32dc41c2009-03-29 17:27:48 +00001743/// If RequireSemi is false, this does not check for a ';' at the end of the
Chris Lattner005fc1b2010-04-05 18:18:31 +00001744/// declaration. If it is true, it checks for and eats it.
Richard Smith02e85f32011-04-14 22:09:26 +00001745///
1746/// If FRI is non-null, we might be parsing a for-range-declaration instead
1747/// of a simple-declaration. If we find that we are, we also parse the
1748/// for-range-initializer, and place it here.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001749Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +00001750Parser::ParseSimpleDeclaration(DeclaratorContext Context,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001751 SourceLocation &DeclEnd,
Richard Smith2386c8b2013-02-22 09:06:26 +00001752 ParsedAttributesWithRange &Attrs,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001753 bool RequireSemi, ForRangeInit *FRI) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001754 // Parse the common declaration-specifiers piece.
John McCall28a6aea2009-11-04 02:18:39 +00001755 ParsingDeclSpec DS(*this);
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001756
Richard Smith404dfb42013-11-19 22:47:36 +00001757 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
Faisal Valia534f072018-04-26 00:42:40 +00001758 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
Richard Smith404dfb42013-11-19 22:47:36 +00001759
1760 // If we had a free-standing type definition with a missing semicolon, we
1761 // may get this far before the problem becomes obvious.
1762 if (DS.hasTagDefinition() &&
1763 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
David Blaikie0403cb12016-01-15 23:43:25 +00001764 return nullptr;
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001765
Chris Lattner0e894622006-08-13 19:58:17 +00001766 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1767 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner76c72282007-10-09 17:33:22 +00001768 if (Tok.is(tok::semi)) {
Richard Smith2386c8b2013-02-22 09:06:26 +00001769 ProhibitAttributes(Attrs);
Argyrios Kyrtzidisfbb2bb52012-05-16 23:49:15 +00001770 DeclEnd = Tok.getLocation();
Chris Lattner005fc1b2010-04-05 18:18:31 +00001771 if (RequireSemi) ConsumeToken();
Nico Weber7b837f52016-01-28 19:25:00 +00001772 RecordDecl *AnonRecord = nullptr;
John McCall48871652010-08-21 09:40:31 +00001773 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00001774 DS, AnonRecord);
John McCall28a6aea2009-11-04 02:18:39 +00001775 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00001776 if (AnonRecord) {
1777 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00001778 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00001779 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001780 return Actions.ConvertDeclToDeclGroup(TheDecl);
Chris Lattner0e894622006-08-13 19:58:17 +00001781 }
Chad Rosierc1183952012-06-26 22:30:43 +00001782
Richard Smith2386c8b2013-02-22 09:06:26 +00001783 DS.takeAttributesFrom(Attrs);
Reid Klecknerd61a3112014-12-15 23:16:32 +00001784 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
John McCalld5a36322009-11-03 19:26:08 +00001785}
Mike Stump11289f42009-09-09 15:08:12 +00001786
Richard Smith09f76ee2011-10-19 21:33:05 +00001787/// Returns true if this might be the start of a declarator, or a common typo
1788/// for a declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001789bool Parser::MightBeDeclarator(DeclaratorContext Context) {
Richard Smith09f76ee2011-10-19 21:33:05 +00001790 switch (Tok.getKind()) {
1791 case tok::annot_cxxscope:
1792 case tok::annot_template_id:
1793 case tok::caret:
1794 case tok::code_completion:
1795 case tok::coloncolon:
1796 case tok::ellipsis:
1797 case tok::kw___attribute:
1798 case tok::kw_operator:
1799 case tok::l_paren:
1800 case tok::star:
1801 return true;
1802
1803 case tok::amp:
1804 case tok::ampamp:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001805 return getLangOpts().CPlusPlus;
Richard Smith09f76ee2011-10-19 21:33:05 +00001806
Richard Smithc8a79032012-01-09 22:31:44 +00001807 case tok::l_square: // Might be an attribute on an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001808 return Context == DeclaratorContext::MemberContext &&
1809 getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
Richard Smithc8a79032012-01-09 22:31:44 +00001810
1811 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001812 return Context == DeclaratorContext::MemberContext ||
1813 getLangOpts().CPlusPlus;
Richard Smithc8a79032012-01-09 22:31:44 +00001814
Richard Smith09f76ee2011-10-19 21:33:05 +00001815 case tok::identifier:
1816 switch (NextToken().getKind()) {
1817 case tok::code_completion:
1818 case tok::coloncolon:
1819 case tok::comma:
1820 case tok::equal:
1821 case tok::equalequal: // Might be a typo for '='.
1822 case tok::kw_alignas:
1823 case tok::kw_asm:
1824 case tok::kw___attribute:
1825 case tok::l_brace:
1826 case tok::l_paren:
1827 case tok::l_square:
1828 case tok::less:
1829 case tok::r_brace:
1830 case tok::r_paren:
1831 case tok::r_square:
1832 case tok::semi:
1833 return true;
1834
1835 case tok::colon:
1836 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
Richard Smithc8a79032012-01-09 22:31:44 +00001837 // and in block scope it's probably a label. Inside a class definition,
1838 // this is a bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001839 return Context == DeclaratorContext::MemberContext ||
1840 (getLangOpts().CPlusPlus &&
1841 Context == DeclaratorContext::FileContext);
Richard Smithc8a79032012-01-09 22:31:44 +00001842
1843 case tok::identifier: // Possible virt-specifier.
Richard Smith89645bc2013-01-02 12:01:23 +00001844 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
Richard Smith09f76ee2011-10-19 21:33:05 +00001845
1846 default:
1847 return false;
1848 }
1849
1850 default:
1851 return false;
1852 }
1853}
1854
Richard Smithb8caac82012-04-11 20:59:20 +00001855/// Skip until we reach something which seems like a sensible place to pick
1856/// up parsing after a malformed declaration. This will sometimes stop sooner
1857/// than SkipUntil(tok::r_brace) would, but will never stop later.
1858void Parser::SkipMalformedDecl() {
1859 while (true) {
1860 switch (Tok.getKind()) {
1861 case tok::l_brace:
1862 // Skip until matching }, then stop. We've probably skipped over
1863 // a malformed class or function definition or similar.
1864 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001865 SkipUntil(tok::r_brace);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001866 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
Richard Smithb8caac82012-04-11 20:59:20 +00001867 // This declaration isn't over yet. Keep skipping.
1868 continue;
1869 }
Alp Toker8fbec672013-12-17 23:29:36 +00001870 TryConsumeToken(tok::semi);
Richard Smithb8caac82012-04-11 20:59:20 +00001871 return;
1872
1873 case tok::l_square:
1874 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001875 SkipUntil(tok::r_square);
Richard Smithb8caac82012-04-11 20:59:20 +00001876 continue;
1877
1878 case tok::l_paren:
1879 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001880 SkipUntil(tok::r_paren);
Richard Smithb8caac82012-04-11 20:59:20 +00001881 continue;
1882
1883 case tok::r_brace:
1884 return;
1885
1886 case tok::semi:
1887 ConsumeToken();
1888 return;
1889
1890 case tok::kw_inline:
1891 // 'inline namespace' at the start of a line is almost certainly
Jordan Rose12e730c2012-07-09 16:54:53 +00001892 // a good place to pick back up parsing, except in an Objective-C
1893 // @interface context.
1894 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1895 (!ParsingInObjCContainer || CurParsedObjCImpl))
Richard Smithb8caac82012-04-11 20:59:20 +00001896 return;
1897 break;
1898
1899 case tok::kw_namespace:
1900 // 'namespace' at the start of a line is almost certainly a good
Jordan Rose12e730c2012-07-09 16:54:53 +00001901 // place to pick back up parsing, except in an Objective-C
1902 // @interface context.
1903 if (Tok.isAtStartOfLine() &&
1904 (!ParsingInObjCContainer || CurParsedObjCImpl))
1905 return;
1906 break;
1907
1908 case tok::at:
1909 // @end is very much like } in Objective-C contexts.
1910 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1911 ParsingInObjCContainer)
1912 return;
1913 break;
1914
1915 case tok::minus:
1916 case tok::plus:
1917 // - and + probably start new method declarations in Objective-C contexts.
1918 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
Richard Smithb8caac82012-04-11 20:59:20 +00001919 return;
1920 break;
1921
1922 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001923 case tok::annot_module_begin:
1924 case tok::annot_module_end:
1925 case tok::annot_module_include:
Richard Smithb8caac82012-04-11 20:59:20 +00001926 return;
1927
1928 default:
1929 break;
1930 }
1931
1932 ConsumeAnyToken();
1933 }
1934}
1935
John McCalld5a36322009-11-03 19:26:08 +00001936/// ParseDeclGroup - Having concluded that this is either a function
1937/// definition or a group of object declarations, actually parse the
1938/// result.
John McCall28a6aea2009-11-04 02:18:39 +00001939Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
Faisal Vali421b2d12017-12-29 05:41:00 +00001940 DeclaratorContext Context,
Richard Smith02e85f32011-04-14 22:09:26 +00001941 SourceLocation *DeclEnd,
1942 ForRangeInit *FRI) {
John McCalld5a36322009-11-03 19:26:08 +00001943 // Parse the first declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001944 ParsingDeclarator D(*this, DS, Context);
John McCalld5a36322009-11-03 19:26:08 +00001945 ParseDeclarator(D);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001946
John McCalld5a36322009-11-03 19:26:08 +00001947 // Bail out if the first declarator didn't seem well-formed.
1948 if (!D.hasName() && !D.mayOmitIdentifier()) {
Richard Smithb8caac82012-04-11 20:59:20 +00001949 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00001950 return nullptr;
Chris Lattnerefb0f112009-03-29 17:18:04 +00001951 }
Mike Stump11289f42009-09-09 15:08:12 +00001952
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001953 // Save late-parsed attributes for now; they need to be parsed in the
1954 // appropriate function scope after the function Decl has been constructed.
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001955 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1956 LateParsedAttrList LateParsedAttrs(true);
Richard Smith99c464c2014-11-10 21:10:32 +00001957 if (D.isFunctionDeclarator()) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001958 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1959
Richard Smith99c464c2014-11-10 21:10:32 +00001960 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1961 // attribute. If we find the keyword here, tell the user to put it
1962 // at the start instead.
1963 if (Tok.is(tok::kw__Noreturn)) {
1964 SourceLocation Loc = ConsumeToken();
1965 const char *PrevSpec;
1966 unsigned DiagID;
1967
1968 // We can offer a fixit if it's valid to mark this function as _Noreturn
1969 // and we don't have any other declarators in this declaration.
1970 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1971 MaybeParseGNUAttributes(D, &LateParsedAttrs);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001972 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
Richard Smith99c464c2014-11-10 21:10:32 +00001973
1974 Diag(Loc, diag::err_c11_noreturn_misplaced)
1975 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001976 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
Richard Smith99c464c2014-11-10 21:10:32 +00001977 : FixItHint());
1978 }
1979 }
1980
Chris Lattnerdbb1e932010-07-11 22:24:20 +00001981 // Check to see if we have a function *definition* which must have a body.
Douglas Gregor012efe22013-04-16 16:01:32 +00001982 if (D.isFunctionDeclarator() &&
Chris Lattnerdbb1e932010-07-11 22:24:20 +00001983 // Look at the next token to make sure that this isn't a function
1984 // declaration. We have to check this because __attribute__ might be the
1985 // start of a function definition in GCC-extended K&R C.
Fariborz Jahanian712bb812012-08-10 15:54:40 +00001986 !isDeclarationAfterDeclarator()) {
Chad Rosierc1183952012-06-26 22:30:43 +00001987
Reid Klecknerd61a3112014-12-15 23:16:32 +00001988 // Function definitions are only allowed at file scope and in C++ classes.
1989 // The C++ inline method definition case is handled elsewhere, so we only
1990 // need to handle the file scope definition case.
Faisal Vali421b2d12017-12-29 05:41:00 +00001991 if (Context == DeclaratorContext::FileContext) {
Douglas Gregor012efe22013-04-16 16:01:32 +00001992 if (isStartOfFunctionDefinition(D)) {
1993 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1994 Diag(Tok, diag::err_function_declared_typedef);
John McCalld5a36322009-11-03 19:26:08 +00001995
Douglas Gregor012efe22013-04-16 16:01:32 +00001996 // Recover by treating the 'typedef' as spurious.
1997 DS.ClearStorageClassSpecs();
1998 }
1999
2000 Decl *TheDecl =
2001 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
2002 return Actions.ConvertDeclToDeclGroup(TheDecl);
John McCalld5a36322009-11-03 19:26:08 +00002003 }
2004
Douglas Gregor012efe22013-04-16 16:01:32 +00002005 if (isDeclarationSpecifier()) {
Nico Weber6b05f382015-02-18 04:53:03 +00002006 // If there is an invalid declaration specifier right after the
2007 // function prototype, then we must be in a missing semicolon case
2008 // where this isn't actually a body. Just fall through into the code
2009 // that handles it as a prototype, and let the top-level code handle
2010 // the erroneous declspec where it would otherwise expect a comma or
2011 // semicolon.
Douglas Gregor012efe22013-04-16 16:01:32 +00002012 } else {
2013 Diag(Tok, diag::err_expected_fn_body);
2014 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002015 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00002016 }
John McCalld5a36322009-11-03 19:26:08 +00002017 } else {
Douglas Gregor012efe22013-04-16 16:01:32 +00002018 if (Tok.is(tok::l_brace)) {
2019 Diag(Tok, diag::err_function_definition_not_allowed);
Serge Pavlov1de51512013-12-09 05:25:47 +00002020 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00002021 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00002022 }
John McCalld5a36322009-11-03 19:26:08 +00002023 }
2024 }
2025
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002026 if (ParseAsmAttributesAfterDeclarator(D))
David Blaikie0403cb12016-01-15 23:43:25 +00002027 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00002028
2029 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2030 // must parse and analyze the for-range-initializer before the declaration is
2031 // analyzed.
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002032 //
2033 // Handle the Objective-C for-in loop variable similarly, although we
2034 // don't need to parse the container in advance.
2035 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2036 bool IsForRangeLoop = false;
Alp Toker8fbec672013-12-17 23:29:36 +00002037 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002038 IsForRangeLoop = true;
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002039 if (Tok.is(tok::l_brace))
2040 FRI->RangeExpr = ParseBraceInitializer();
2041 else
2042 FRI->RangeExpr = ParseExpression();
2043 }
2044
Richard Smith02e85f32011-04-14 22:09:26 +00002045 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
George Karpenkovec38cf72018-03-29 00:56:24 +00002046 if (IsForRangeLoop) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002047 Actions.ActOnCXXForRangeDecl(ThisDecl);
George Karpenkovec38cf72018-03-29 00:56:24 +00002048 } else {
2049 // Obj-C for loop
2050 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2051 VD->setObjCForDecl(true);
2052 }
Richard Smith02e85f32011-04-14 22:09:26 +00002053 Actions.FinalizeDeclaration(ThisDecl);
John McCallcf6e0c82012-01-27 01:29:43 +00002054 D.complete(ThisDecl);
Rafael Espindolaab417692013-07-09 12:05:01 +00002055 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
Richard Smith02e85f32011-04-14 22:09:26 +00002056 }
2057
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002058 SmallVector<Decl *, 8> DeclsInGroup;
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002059 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2060 D, ParsedTemplateInfo(), FRI);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002061 if (LateParsedAttrs.size() > 0)
2062 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
John McCall28a6aea2009-11-04 02:18:39 +00002063 D.complete(FirstDecl);
John McCall48871652010-08-21 09:40:31 +00002064 if (FirstDecl)
John McCalld5a36322009-11-03 19:26:08 +00002065 DeclsInGroup.push_back(FirstDecl);
2066
Faisal Vali421b2d12017-12-29 05:41:00 +00002067 bool ExpectSemi = Context != DeclaratorContext::ForContext;
Fangrui Song6907ce22018-07-30 19:24:48 +00002068
John McCalld5a36322009-11-03 19:26:08 +00002069 // If we don't have a comma, it is either the end of the list (a ';') or an
2070 // error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00002071 SourceLocation CommaLoc;
2072 while (TryConsumeToken(tok::comma, CommaLoc)) {
Richard Smith09f76ee2011-10-19 21:33:05 +00002073 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2074 // This comma was followed by a line-break and something which can't be
2075 // the start of a declarator. The comma was probably a typo for a
2076 // semicolon.
2077 Diag(CommaLoc, diag::err_expected_semi_declaration)
2078 << FixItHint::CreateReplacement(CommaLoc, ";");
2079 ExpectSemi = false;
2080 break;
2081 }
John McCalld5a36322009-11-03 19:26:08 +00002082
2083 // Parse the next declarator.
2084 D.clear();
Richard Smith8d06f422012-01-12 23:53:29 +00002085 D.setCommaLoc(CommaLoc);
John McCalld5a36322009-11-03 19:26:08 +00002086
2087 // Accept attributes in an init-declarator. In the first declarator in a
2088 // declaration, these would be part of the declspec. In subsequent
2089 // declarators, they become part of the declarator itself, so that they
2090 // don't apply to declarators after *this* one. Examples:
2091 // short __attribute__((common)) var; -> declspec
2092 // short var __attribute__((common)); -> declarator
2093 // short x, __attribute__((common)) var; -> declarator
John McCall53fa7142010-12-24 02:08:15 +00002094 MaybeParseGNUAttributes(D);
John McCalld5a36322009-11-03 19:26:08 +00002095
Nico Rieckeaaae272014-12-04 23:31:08 +00002096 // MSVC parses but ignores qualifiers after the comma as an extension.
2097 if (getLangOpts().MicrosoftExt)
2098 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2099
John McCalld5a36322009-11-03 19:26:08 +00002100 ParseDeclarator(D);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002101 if (!D.isInvalidType()) {
2102 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2103 D.complete(ThisDecl);
2104 if (ThisDecl)
Chad Rosierc1183952012-06-26 22:30:43 +00002105 DeclsInGroup.push_back(ThisDecl);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002106 }
John McCalld5a36322009-11-03 19:26:08 +00002107 }
2108
2109 if (DeclEnd)
2110 *DeclEnd = Tok.getLocation();
2111
Richard Smith09f76ee2011-10-19 21:33:05 +00002112 if (ExpectSemi &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002113 ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
Chris Lattner02f1b612012-04-28 16:12:17 +00002114 ? diag::err_invalid_token_after_toplevel_declarator
2115 : diag::err_expected_semi_declaration)) {
Chris Lattner13901342010-07-11 22:42:07 +00002116 // Okay, there was no semicolon and one was expected. If we see a
2117 // declaration specifier, just assume it was missing and continue parsing.
2118 // Otherwise things are very confused and we skip to recover.
2119 if (!isDeclarationSpecifier()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002120 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Alp Toker8fbec672013-12-17 23:29:36 +00002121 TryConsumeToken(tok::semi);
Chris Lattner13901342010-07-11 22:42:07 +00002122 }
John McCalld5a36322009-11-03 19:26:08 +00002123 }
2124
Rafael Espindolaab417692013-07-09 12:05:01 +00002125 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner53361ac2006-08-10 05:19:57 +00002126}
2127
Richard Smith02e85f32011-04-14 22:09:26 +00002128/// Parse an optional simple-asm-expr and attributes, and attach them to a
2129/// declarator. Returns true on an error.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002130bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
Richard Smith02e85f32011-04-14 22:09:26 +00002131 // If a simple-asm-expr is present, parse it.
2132 if (Tok.is(tok::kw_asm)) {
2133 SourceLocation Loc;
2134 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2135 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002136 SkipUntil(tok::semi, StopBeforeMatch);
Richard Smith02e85f32011-04-14 22:09:26 +00002137 return true;
2138 }
2139
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002140 D.setAsmLabel(AsmLabel.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002141 D.SetRangeEnd(Loc);
2142 }
2143
2144 MaybeParseGNUAttributes(D);
2145 return false;
2146}
2147
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002148/// Parse 'declaration' after parsing 'declaration-specifiers
Douglas Gregor23996282009-05-12 21:31:51 +00002149/// declarator'. This method parses the remainder of the declaration
2150/// (including any attributes or initializer, among other things) and
2151/// finalizes the declaration.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002152///
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002153/// init-declarator: [C99 6.7]
2154/// declarator
2155/// declarator '=' initializer
Chris Lattner6d7e6342006-08-15 03:41:14 +00002156/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2157/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002158/// [C++] declarator initializer[opt]
2159///
2160/// [C++] initializer:
2161/// [C++] '=' initializer-clause
2162/// [C++] '(' expression-list ')'
Sebastian Redlf769df52009-03-24 22:27:57 +00002163/// [C++0x] '=' 'default' [TODO]
2164/// [C++0x] '=' 'delete'
Sebastian Redl3da34892011-06-05 12:23:16 +00002165/// [C++0x] braced-init-list
Sebastian Redlf769df52009-03-24 22:27:57 +00002166///
2167/// According to the standard grammar, =default and =delete are function
2168/// definitions, but that definitely doesn't fit with the parser here.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002169///
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002170Decl *Parser::ParseDeclarationAfterDeclarator(
2171 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002172 if (ParseAsmAttributesAfterDeclarator(D))
Craig Topper161e4db2014-05-21 06:02:52 +00002173 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002174
Richard Smith02e85f32011-04-14 22:09:26 +00002175 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2176}
Mike Stump11289f42009-09-09 15:08:12 +00002177
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002178Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2179 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
Richard Smithc95d2c52017-09-22 04:25:05 +00002180 // RAII type used to track whether we're inside an initializer.
2181 struct InitializerScopeRAII {
2182 Parser &P;
2183 Declarator &D;
2184 Decl *ThisDecl;
2185
2186 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2187 : P(P), D(D), ThisDecl(ThisDecl) {
2188 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2189 Scope *S = nullptr;
2190 if (D.getCXXScopeSpec().isSet()) {
2191 P.EnterScope(0);
2192 S = P.getCurScope();
2193 }
2194 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2195 }
2196 }
2197 ~InitializerScopeRAII() { pop(); }
2198 void pop() {
2199 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2200 Scope *S = nullptr;
2201 if (D.getCXXScopeSpec().isSet())
2202 S = P.getCurScope();
2203 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2204 if (S)
2205 P.ExitScope();
2206 }
2207 ThisDecl = nullptr;
2208 }
2209 };
2210
Douglas Gregor23996282009-05-12 21:31:51 +00002211 // Inform the current actions module that we just parsed this declarator.
Craig Topper161e4db2014-05-21 06:02:52 +00002212 Decl *ThisDecl = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00002213 switch (TemplateInfo.Kind) {
2214 case ParsedTemplateInfo::NonTemplate:
Douglas Gregor0be31a22010-07-02 17:43:08 +00002215 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
Douglas Gregor450f00842009-09-25 18:43:00 +00002216 break;
Chad Rosierc1183952012-06-26 22:30:43 +00002217
Douglas Gregor450f00842009-09-25 18:43:00 +00002218 case ParsedTemplateInfo::Template:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002219 case ParsedTemplateInfo::ExplicitSpecialization: {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002220 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002221 *TemplateInfo.TemplateParams,
Douglas Gregor450f00842009-09-25 18:43:00 +00002222 D);
Larisse Voufo833b05a2013-08-06 07:33:00 +00002223 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002224 // Re-direct this decl to refer to the templated decl so that we can
2225 // initialize it.
2226 ThisDecl = VT->getTemplatedDecl();
2227 break;
2228 }
2229 case ParsedTemplateInfo::ExplicitInstantiation: {
2230 if (Tok.is(tok::semi)) {
2231 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2232 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2233 if (ThisRes.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002234 SkipUntil(tok::semi, StopBeforeMatch);
Craig Topper161e4db2014-05-21 06:02:52 +00002235 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002236 }
2237 ThisDecl = ThisRes.get();
2238 } else {
2239 // FIXME: This check should be for a variable template instantiation only.
2240
2241 // Check that this is a valid instantiation
Faisal Vali2ab8c152017-12-30 04:15:27 +00002242 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002243 // If the declarator-id is not a template-id, issue a diagnostic and
2244 // recover by ignoring the 'template' keyword.
2245 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2246 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2247 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2248 } else {
2249 SourceLocation LAngleLoc =
2250 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2251 Diag(D.getIdentifierLoc(),
2252 diag::err_explicit_instantiation_with_definition)
2253 << SourceRange(TemplateInfo.TemplateLoc)
2254 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2255
2256 // Recover as if it were an explicit specialization.
2257 TemplateParameterLists FakedParamLists;
2258 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00002259 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00002260 LAngleLoc, nullptr));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002261
2262 ThisDecl =
2263 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2264 }
2265 }
Douglas Gregor450f00842009-09-25 18:43:00 +00002266 break;
2267 }
2268 }
Mike Stump11289f42009-09-09 15:08:12 +00002269
Douglas Gregor23996282009-05-12 21:31:51 +00002270 // Parse declarator '=' initializer.
Richard Trieuc64d3232012-01-18 22:54:52 +00002271 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Trieu4972a6d2012-01-19 22:01:51 +00002272 if (isTokenEqualOrEqualTypo()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002273 SourceLocation EqualLoc = ConsumeToken();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002274
Anders Carlsson991285e2010-09-24 21:25:25 +00002275 if (Tok.is(tok::kw_delete)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002276 if (D.isFunctionDeclarator())
2277 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2278 << 1 /* delete */;
2279 else
2280 Diag(ConsumeToken(), diag::err_deleted_non_function);
Alexis Hunt5dafebc2011-05-06 01:42:00 +00002281 } else if (Tok.is(tok::kw_default)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002282 if (D.isFunctionDeclarator())
Sebastian Redl46afb552012-02-11 23:51:21 +00002283 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2284 << 0 /* default */;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002285 else
2286 Diag(ConsumeToken(), diag::err_default_special_members);
Douglas Gregor23996282009-05-12 21:31:51 +00002287 } else {
Richard Smithc95d2c52017-09-22 04:25:05 +00002288 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002289
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002290 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002291 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
Peter Collingbourne6b4fdc22012-07-27 12:56:09 +00002292 Actions.FinalizeDeclaration(ThisDecl);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002293 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +00002294 return nullptr;
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002295 }
Chad Rosierc1183952012-06-26 22:30:43 +00002296
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00002297 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2298 ExprResult Init = ParseInitializer();
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002299
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002300 // If this is the only decl in (possibly) range based for statement,
2301 // our best guess is that the user meant ':' instead of '='.
2302 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2303 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2304 << FixItHint::CreateReplacement(EqualLoc, ":");
2305 // We are trying to stop parser from looking for ';' in this for
2306 // statement, therefore preventing spurious errors to be issued.
2307 FRI->ColonLoc = EqualLoc;
2308 Init = ExprError();
2309 FRI->RangeExpr = Init;
2310 }
2311
Richard Smithc95d2c52017-09-22 04:25:05 +00002312 InitScope.pop();
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002313
Douglas Gregor23996282009-05-12 21:31:51 +00002314 if (Init.isInvalid()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002315 SmallVector<tok::TokenKind, 2> StopTokens;
2316 StopTokens.push_back(tok::comma);
Faisal Vali421b2d12017-12-29 05:41:00 +00002317 if (D.getContext() == DeclaratorContext::ForContext ||
2318 D.getContext() == DeclaratorContext::InitStmtContext)
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002319 StopTokens.push_back(tok::r_paren);
2320 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
Douglas Gregor604c3022010-03-01 18:27:54 +00002321 Actions.ActOnInitializerError(ThisDecl);
2322 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002323 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002324 /*DirectInit=*/false);
Douglas Gregor23996282009-05-12 21:31:51 +00002325 }
2326 } else if (Tok.is(tok::l_paren)) {
2327 // Parse C++ direct initializer: '(' expression-list ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002328 BalancedDelimiterTracker T(*this, tok::l_paren);
2329 T.consumeOpen();
2330
Benjamin Kramerf0623432012-08-23 22:51:59 +00002331 ExprVector Exprs;
Douglas Gregor23996282009-05-12 21:31:51 +00002332 CommaLocsTy CommaLocs;
2333
Richard Smithc95d2c52017-09-22 04:25:05 +00002334 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Douglas Gregor613bf102009-12-22 17:47:17 +00002335
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002336 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002337 auto RunSignatureHelp = [&]() {
Ilya Biryukov832c4af2018-09-07 14:04:39 +00002338 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002339 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
Ilya Biryukov2fab2352018-08-30 13:08:03 +00002340 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002341 CalledSignatureHelp = true;
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002342 return PreferredType;
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002343 };
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002344 auto SetPreferredType = [&] {
2345 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2346 };
2347
2348 llvm::function_ref<void()> ExpressionStarts;
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002349 if (ThisVarDecl) {
2350 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2351 // VarDecl. This is an error and it is reported in a call to
2352 // Actions.ActOnInitializerError(). However, we call
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002353 // ProduceConstructorSignatureHelp only on VarDecls.
2354 ExpressionStarts = SetPreferredType;
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002355 }
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002356 if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002357 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2358 Actions.ProduceConstructorSignatureHelp(
2359 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2360 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2361 CalledSignatureHelp = true;
2362 }
David Blaikieeae04112012-10-10 23:15:05 +00002363 Actions.ActOnInitializerError(ThisDecl);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002364 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor23996282009-05-12 21:31:51 +00002365 } else {
2366 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002367 T.consumeClose();
Douglas Gregor23996282009-05-12 21:31:51 +00002368
2369 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2370 "Unexpected number of commas!");
Douglas Gregor613bf102009-12-22 17:47:17 +00002371
Richard Smithc95d2c52017-09-22 04:25:05 +00002372 InitScope.pop();
Douglas Gregor613bf102009-12-22 17:47:17 +00002373
Sebastian Redla9351792012-02-11 23:51:47 +00002374 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2375 T.getCloseLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002376 Exprs);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002377 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002378 /*DirectInit=*/true);
Douglas Gregor23996282009-05-12 21:31:51 +00002379 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002380 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
Fariborz Jahanian8be1ecd2012-07-03 23:22:13 +00002381 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
Sebastian Redl3da34892011-06-05 12:23:16 +00002382 // Parse C++0x braced-init-list.
Richard Smith5d164bc2011-10-15 05:09:34 +00002383 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2384
Richard Smithc95d2c52017-09-22 04:25:05 +00002385 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Sebastian Redl3da34892011-06-05 12:23:16 +00002386
2387 ExprResult Init(ParseBraceInitializer());
2388
Richard Smithc95d2c52017-09-22 04:25:05 +00002389 InitScope.pop();
Sebastian Redl3da34892011-06-05 12:23:16 +00002390
2391 if (Init.isInvalid()) {
2392 Actions.ActOnInitializerError(ThisDecl);
2393 } else
Richard Smith3beb7c62017-01-12 02:27:38 +00002394 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
Sebastian Redl3da34892011-06-05 12:23:16 +00002395
Douglas Gregor23996282009-05-12 21:31:51 +00002396 } else {
Richard Smith3beb7c62017-01-12 02:27:38 +00002397 Actions.ActOnUninitializedDecl(ThisDecl);
Douglas Gregor23996282009-05-12 21:31:51 +00002398 }
2399
Richard Smithb2bc2e62011-02-21 20:05:19 +00002400 Actions.FinalizeDeclaration(ThisDecl);
2401
Douglas Gregor23996282009-05-12 21:31:51 +00002402 return ThisDecl;
2403}
2404
Chris Lattner1890ac82006-08-13 01:16:23 +00002405/// ParseSpecifierQualifierList
2406/// specifier-qualifier-list:
2407/// type-specifier specifier-qualifier-list[opt]
2408/// type-qualifier specifier-qualifier-list[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002409/// [GNU] attributes specifier-qualifier-list[opt]
Chris Lattner1890ac82006-08-13 01:16:23 +00002410///
Richard Smithc5b05522012-03-12 07:56:15 +00002411void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2412 DeclSpecContext DSC) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002413 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2414 /// parse declaration-specifiers and complain about extra stuff.
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002415 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
Faisal Valia534f072018-04-26 00:42:40 +00002416 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
Mike Stump11289f42009-09-09 15:08:12 +00002417
Chris Lattner1890ac82006-08-13 01:16:23 +00002418 // Validate declspec for type-name.
2419 unsigned Specs = DS.getParsedSpecifiers();
Richard Smith649c7b062014-01-08 00:56:48 +00002420 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
Richard Smithc5b05522012-03-12 07:56:15 +00002421 Diag(Tok, diag::err_expected_type);
2422 DS.SetTypeSpecError();
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00002423 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002424 Diag(Tok, diag::err_typename_requires_specqual);
Richard Smithc5b05522012-03-12 07:56:15 +00002425 if (!DS.hasTypeSpecifier())
2426 DS.SetTypeSpecError();
2427 }
Mike Stump11289f42009-09-09 15:08:12 +00002428
Chris Lattner1b22eed2006-11-28 05:12:07 +00002429 // Issue diagnostic and remove storage class if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002430 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
Chris Lattner1b22eed2006-11-28 05:12:07 +00002431 if (DS.getStorageClassSpecLoc().isValid())
2432 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2433 else
Richard Smithb4a9e862013-04-12 22:46:28 +00002434 Diag(DS.getThreadStorageClassSpecLoc(),
2435 diag::err_typename_invalid_storageclass);
Chris Lattnera925dc62006-11-28 04:33:46 +00002436 DS.ClearStorageClassSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002437 }
Mike Stump11289f42009-09-09 15:08:12 +00002438
Craig Topper3f13d4d22015-11-14 18:15:55 +00002439 // Issue diagnostic and remove function specifier if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002440 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
Douglas Gregor61956c42008-10-31 09:07:45 +00002441 if (DS.isInlineSpecified())
2442 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2443 if (DS.isVirtualSpecified())
2444 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
Nicolas Lesser5fe2ddb2019-05-04 00:09:00 +00002445 if (DS.hasExplicitSpecifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00002446 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
Chris Lattnera925dc62006-11-28 04:33:46 +00002447 DS.ClearFunctionSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002448 }
Richard Smithc5b05522012-03-12 07:56:15 +00002449
Nicolas Lesser5fe2ddb2019-05-04 00:09:00 +00002450 // Issue diagnostic and remove constexpr specifier if present.
Faisal Vali7db85c52017-12-31 00:06:40 +00002451 if (DS.isConstexprSpecified() && DSC != DeclSpecContext::DSC_condition) {
Richard Smithc5b05522012-03-12 07:56:15 +00002452 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2453 DS.ClearConstexprSpec();
2454 }
Chris Lattner1890ac82006-08-13 01:16:23 +00002455}
Chris Lattner53361ac2006-08-10 05:19:57 +00002456
Chris Lattner6cc055a2009-04-12 20:42:31 +00002457/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2458/// specified token is valid after the identifier in a declarator which
2459/// immediately follows the declspec. For example, these things are valid:
2460///
2461/// int x [ 4]; // direct-declarator
2462/// int x ( int y); // direct-declarator
2463/// int(int x ) // direct-declarator
2464/// int x ; // simple-declaration
2465/// int x = 17; // init-declarator-list
2466/// int x , y; // init-declarator-list
2467/// int x __asm__ ("foo"); // init-declarator-list
Chris Lattnera723ba92009-04-14 21:16:09 +00002468/// int x : 4; // struct-declarator
Chris Lattner2b988c12009-04-12 22:29:43 +00002469/// int x { 5}; // C++'0x unified initializers
Chris Lattner6cc055a2009-04-12 20:42:31 +00002470///
2471/// This is not, because 'x' does not immediately follow the declspec (though
2472/// ')' happens to be valid anyway).
2473/// int (x)
2474///
2475static bool isValidAfterIdentifierInDeclarator(const Token &T) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002476 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2477 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2478 tok::colon);
Chris Lattner6cc055a2009-04-12 20:42:31 +00002479}
2480
Chris Lattner20a0c612009-04-14 21:34:55 +00002481/// ParseImplicitInt - This method is called when we have an non-typename
2482/// identifier in a declspec (which normally terminates the decl spec) when
2483/// the declspec has no type specifier. In this case, the declspec is either
2484/// malformed or is "implicit int" (in K&R and C89).
2485///
2486/// This method handles diagnosing this prettily and returns false if the
2487/// declspec is done being processed. If it recovers and thinks there may be
2488/// other pieces of declspec after it, it returns true.
2489///
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002490bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002491 const ParsedTemplateInfo &TemplateInfo,
Richard Smitha0a5d502014-05-08 22:32:00 +00002492 AccessSpecifier AS, DeclSpecContext DSC,
Michael Han9407e502012-11-26 22:54:45 +00002493 ParsedAttributesWithRange &Attrs) {
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002494 assert(Tok.is(tok::identifier) && "should have identifier");
Mike Stump11289f42009-09-09 15:08:12 +00002495
Chris Lattner20a0c612009-04-14 21:34:55 +00002496 SourceLocation Loc = Tok.getLocation();
2497 // If we see an identifier that is not a type name, we normally would
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002498 // parse it as the identifier being declared. However, when a typename
Chris Lattner20a0c612009-04-14 21:34:55 +00002499 // is typo'd or the definition is not included, this will incorrectly
2500 // parse the typename as the identifier name and fall over misparsing
2501 // later parts of the diagnostic.
2502 //
2503 // As such, we try to do some look-ahead in cases where this would
2504 // otherwise be an "implicit-int" case to see if this is invalid. For
2505 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2506 // an identifier with implicit int, we'd get a parse error because the
2507 // next token is obviously invalid for a type. Parse these as a case
2508 // with an invalid type specifier.
2509 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
Mike Stump11289f42009-09-09 15:08:12 +00002510
Chris Lattner20a0c612009-04-14 21:34:55 +00002511 // Since we know that this either implicit int (which is rare) or an
Richard Smitha952ebb2012-05-15 21:01:51 +00002512 // error, do lookahead to try to do better recovery. This never applies
2513 // within a type specifier. Outside of C++, we allow this even if the
2514 // language doesn't "officially" support implicit int -- we support
Richard Smith3b870382013-04-30 22:43:51 +00002515 // implicit int as an extension in C99 and C11.
Richard Smith649c7b062014-01-08 00:56:48 +00002516 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
Richard Smithc5b05522012-03-12 07:56:15 +00002517 isValidAfterIdentifierInDeclarator(NextToken())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002518 // If this token is valid for implicit int, e.g. "static x = 4", then
2519 // we just avoid eating the identifier, so it will be parsed as the
2520 // identifier in the declarator.
2521 return false;
2522 }
Mike Stump11289f42009-09-09 15:08:12 +00002523
Richard Smitha952ebb2012-05-15 21:01:51 +00002524 if (getLangOpts().CPlusPlus &&
2525 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2526 // Don't require a type specifier if we have the 'auto' storage class
2527 // specifier in C++98 -- we'll promote it to a type specifier.
Richard Smithfb8b7b92013-10-15 00:00:26 +00002528 if (SS)
2529 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
Richard Smitha952ebb2012-05-15 21:01:51 +00002530 return false;
2531 }
2532
Reid Kleckner9a96e422016-05-24 21:23:54 +00002533 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2534 getLangOpts().MSVCCompat) {
2535 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2536 // Give Sema a chance to recover if we are in a template with dependent base
2537 // classes.
2538 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2539 *Tok.getIdentifierInfo(), Tok.getLocation(),
Faisal Vali7db85c52017-12-31 00:06:40 +00002540 DSC == DeclSpecContext::DSC_template_type_arg)) {
Reid Kleckner9a96e422016-05-24 21:23:54 +00002541 const char *PrevSpec;
2542 unsigned DiagID;
2543 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2544 Actions.getASTContext().getPrintingPolicy());
2545 DS.SetRangeEnd(Tok.getLocation());
2546 ConsumeToken();
2547 return false;
2548 }
2549 }
2550
Chris Lattner20a0c612009-04-14 21:34:55 +00002551 // Otherwise, if we don't consume this token, we are going to emit an
2552 // error anyway. Try to recover from various common problems. Check
2553 // to see if this was a reference to a tag name without a tag specified.
2554 // This is a common problem in C (saying 'foo' instead of 'struct foo').
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002555 //
2556 // C++ doesn't need this, and isTagName doesn't take SS.
Craig Topper161e4db2014-05-21 06:02:52 +00002557 if (SS == nullptr) {
2558 const char *TagName = nullptr, *FixitTagName = nullptr;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002559 tok::TokenKind TagKind = tok::unknown;
Mike Stump11289f42009-09-09 15:08:12 +00002560
Douglas Gregor0be31a22010-07-02 17:43:08 +00002561 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002562 default: break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002563 case DeclSpec::TST_enum:
2564 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2565 case DeclSpec::TST_union:
2566 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2567 case DeclSpec::TST_struct:
2568 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
Joao Matosdc86f942012-08-31 18:45:21 +00002569 case DeclSpec::TST_interface:
2570 TagName="__interface"; FixitTagName = "__interface ";
2571 TagKind=tok::kw___interface;break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002572 case DeclSpec::TST_class:
2573 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
Chris Lattner20a0c612009-04-14 21:34:55 +00002574 }
Mike Stump11289f42009-09-09 15:08:12 +00002575
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002576 if (TagName) {
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002577 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2578 LookupResult R(Actions, TokenName, SourceLocation(),
2579 Sema::LookupOrdinaryName);
2580
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002581 Diag(Loc, diag::err_use_of_tag_name_without_tag)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002582 << TokenName << TagName << getLangOpts().CPlusPlus
2583 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2584
2585 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2586 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2587 I != IEnd; ++I)
Kaelyn Uhrain3fe3f852012-04-27 18:26:49 +00002588 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002589 << TokenName << TagName;
2590 }
Mike Stump11289f42009-09-09 15:08:12 +00002591
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002592 // Parse this as a tag as if the missing tag were present.
2593 if (TagKind == tok::kw_enum)
Faisal Vali7db85c52017-12-31 00:06:40 +00002594 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2595 DeclSpecContext::DSC_normal);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002596 else
Richard Smithc5b05522012-03-12 07:56:15 +00002597 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
Faisal Vali7db85c52017-12-31 00:06:40 +00002598 /*EnteringContext*/ false,
2599 DeclSpecContext::DSC_normal, Attrs);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002600 return true;
2601 }
Chris Lattner20a0c612009-04-14 21:34:55 +00002602 }
Mike Stump11289f42009-09-09 15:08:12 +00002603
Richard Smithfe904f02012-05-15 21:29:55 +00002604 // Determine whether this identifier could plausibly be the name of something
Richard Smithedd124e2012-05-15 21:42:17 +00002605 // being declared (with a missing type).
Faisal Vali7db85c52017-12-31 00:06:40 +00002606 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2607 DSC == DeclSpecContext::DSC_class)) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002608 // Look ahead to the next token to try to figure out what this declaration
2609 // was supposed to be.
2610 switch (NextToken().getKind()) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002611 case tok::l_paren: {
2612 // static x(4); // 'x' is not a type
2613 // x(int n); // 'x' is not a type
2614 // x (*p)[]; // 'x' is a type
2615 //
Richard Smitha0a5d502014-05-08 22:32:00 +00002616 // Since we're in an error case, we can afford to perform a tentative
2617 // parse to determine which case we're in.
Richard Smitha952ebb2012-05-15 21:01:51 +00002618 TentativeParsingAction PA(*this);
2619 ConsumeToken();
2620 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2621 PA.Revert();
Richard Smithfb8b7b92013-10-15 00:00:26 +00002622
Richard Smithee390432014-05-16 01:56:53 +00002623 if (TPR != TPResult::False) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002624 // The identifier is followed by a parenthesized declarator.
2625 // It's supposed to be a type.
2626 break;
2627 }
2628
2629 // If we're in a context where we could be declaring a constructor,
2630 // check whether this is a constructor declaration with a bogus name.
Faisal Vali7db85c52017-12-31 00:06:40 +00002631 if (DSC == DeclSpecContext::DSC_class ||
2632 (DSC == DeclSpecContext::DSC_top_level && SS)) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002633 IdentifierInfo *II = Tok.getIdentifierInfo();
2634 if (Actions.isCurrentClassNameTypo(II, SS)) {
2635 Diag(Loc, diag::err_constructor_bad_name)
2636 << Tok.getIdentifierInfo() << II
2637 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2638 Tok.setIdentifierInfo(II);
2639 }
2640 }
2641 // Fall through.
Galina Kistanova77674252017-06-01 21:15:34 +00002642 LLVM_FALLTHROUGH;
Richard Smitha952ebb2012-05-15 21:01:51 +00002643 }
Richard Smithfb8b7b92013-10-15 00:00:26 +00002644 case tok::comma:
2645 case tok::equal:
2646 case tok::kw_asm:
2647 case tok::l_brace:
2648 case tok::l_square:
2649 case tok::semi:
2650 // This looks like a variable or function declaration. The type is
2651 // probably missing. We're done parsing decl-specifiers.
Nicolas Lesseree057172019-05-05 12:15:17 +00002652 // But only if we are not in a function prototype scope.
2653 if (getCurScope()->isFunctionPrototypeScope())
2654 break;
Richard Smithfb8b7b92013-10-15 00:00:26 +00002655 if (SS)
2656 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2657 return false;
Richard Smitha952ebb2012-05-15 21:01:51 +00002658
2659 default:
2660 // This is probably supposed to be a type. This includes cases like:
2661 // int f(itn);
2662 // struct S { unsinged : 4; };
2663 break;
2664 }
2665 }
2666
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002667 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2668 // and attempt to recover.
John McCallba7bf592010-08-24 05:47:05 +00002669 ParsedType T;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +00002670 IdentifierInfo *II = Tok.getIdentifierInfo();
Richard Smith52f8d192017-05-10 21:32:16 +00002671 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002672 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
Richard Smith52f8d192017-05-10 21:32:16 +00002673 IsTemplateName);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002674 if (T) {
2675 // The action has suggested that the type T could be used. Set that as
2676 // the type in the declaration specifiers, consume the would-be type
2677 // name token, and we're done.
2678 const char *PrevSpec;
2679 unsigned DiagID;
2680 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2681 Actions.getASTContext().getPrintingPolicy());
2682 DS.SetRangeEnd(Tok.getLocation());
2683 ConsumeToken();
2684 // There may be other declaration specifiers after this.
2685 return true;
2686 } else if (II != Tok.getIdentifierInfo()) {
2687 // If no type was suggested, the correction is to a keyword
2688 Tok.setKind(II->getTokenID());
2689 // There may be other declaration specifiers after this.
2690 return true;
Douglas Gregor15e56022009-10-13 23:27:22 +00002691 }
Mike Stump11289f42009-09-09 15:08:12 +00002692
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002693 // Otherwise, the action had no suggestion for us. Mark this as an error.
Richard Smithc5b05522012-03-12 07:56:15 +00002694 DS.SetTypeSpecError();
Chris Lattner20a0c612009-04-14 21:34:55 +00002695 DS.SetRangeEnd(Tok.getLocation());
2696 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002697
Richard Smith52f8d192017-05-10 21:32:16 +00002698 // Eat any following template arguments.
2699 if (IsTemplateName) {
2700 SourceLocation LAngle, RAngle;
2701 TemplateArgList Args;
2702 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2703 }
2704
Chris Lattner20a0c612009-04-14 21:34:55 +00002705 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2706 // avoid rippling error messages on subsequent uses of the same type,
2707 // could be useful if #include was forgotten.
2708 return false;
2709}
2710
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002711/// Determine the declaration specifier context from the declarator
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002712/// context.
2713///
2714/// \param Context the declarator context, which is one of the
Faisal Vali421b2d12017-12-29 05:41:00 +00002715/// DeclaratorContext enumerator values.
Chad Rosierc1183952012-06-26 22:30:43 +00002716Parser::DeclSpecContext
Faisal Vali421b2d12017-12-29 05:41:00 +00002717Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2718 if (Context == DeclaratorContext::MemberContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002719 return DeclSpecContext::DSC_class;
Faisal Vali421b2d12017-12-29 05:41:00 +00002720 if (Context == DeclaratorContext::FileContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002721 return DeclSpecContext::DSC_top_level;
Faisal Vali421b2d12017-12-29 05:41:00 +00002722 if (Context == DeclaratorContext::TemplateParamContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002723 return DeclSpecContext::DSC_template_param;
Richard Smith77a9c602018-02-28 03:02:23 +00002724 if (Context == DeclaratorContext::TemplateArgContext ||
2725 Context == DeclaratorContext::TemplateTypeArgContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002726 return DeclSpecContext::DSC_template_type_arg;
Richard Smithe303e352018-02-02 22:24:54 +00002727 if (Context == DeclaratorContext::TrailingReturnContext ||
2728 Context == DeclaratorContext::TrailingReturnVarContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002729 return DeclSpecContext::DSC_trailing;
Faisal Vali421b2d12017-12-29 05:41:00 +00002730 if (Context == DeclaratorContext::AliasDeclContext ||
2731 Context == DeclaratorContext::AliasTemplateContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002732 return DeclSpecContext::DSC_alias_declaration;
2733 return DeclSpecContext::DSC_normal;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002734}
2735
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002736/// ParseAlignArgument - Parse the argument to an alignment-specifier.
2737///
2738/// FIXME: Simply returns an alignof() expression if the argument is a
2739/// type. Ideally, the type should be propagated directly into Sema.
2740///
Benjamin Kramere56f3932011-12-23 17:00:35 +00002741/// [C11] type-id
2742/// [C11] constant-expression
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002743/// [C++0x] type-id ...[opt]
2744/// [C++0x] assignment-expression ...[opt]
2745ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2746 SourceLocation &EllipsisLoc) {
2747 ExprResult ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002748 if (isTypeIdInParens()) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002749 SourceLocation TypeLoc = Tok.getLocation();
2750 ParsedType Ty = ParseTypeName().get();
2751 SourceRange TypeRange(Start, Tok.getLocation());
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002752 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2753 Ty.getAsOpaquePtr(), TypeRange);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002754 } else
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002755 ER = ParseConstantExpression();
2756
Alp Toker8fbec672013-12-17 23:29:36 +00002757 if (getLangOpts().CPlusPlus11)
2758 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002759
2760 return ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002761}
2762
2763/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2764/// attribute to Attrs.
2765///
2766/// alignment-specifier:
Benjamin Kramere56f3932011-12-23 17:00:35 +00002767/// [C11] '_Alignas' '(' type-id ')'
2768/// [C11] '_Alignas' '(' constant-expression ')'
Richard Smithd11c7a12013-01-29 01:48:07 +00002769/// [C++11] 'alignas' '(' type-id ...[opt] ')'
2770/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002771void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
Richard Smith44c247f2013-02-22 08:32:16 +00002772 SourceLocation *EndLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002773 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002774 "Not an alignment-specifier!");
2775
Richard Smithd11c7a12013-01-29 01:48:07 +00002776 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2777 SourceLocation KWLoc = ConsumeToken();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002778
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002779 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002780 if (T.expectAndConsume())
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002781 return;
2782
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002783 SourceLocation EllipsisLoc;
2784 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002785 if (ArgExpr.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002786 T.skipToEnd();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002787 return;
2788 }
2789
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002790 T.consumeClose();
Richard Smith44c247f2013-02-22 08:32:16 +00002791 if (EndLoc)
2792 *EndLoc = T.getCloseLocation();
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002793
Aaron Ballman00e99962013-08-31 01:11:41 +00002794 ArgsVector ArgExprs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002795 ArgExprs.push_back(ArgExpr.get());
Craig Topper161e4db2014-05-21 06:02:52 +00002796 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
Erich Keanee891aa92018-07-13 15:07:47 +00002797 ParsedAttr::AS_Keyword, EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002798}
2799
Richard Smith404dfb42013-11-19 22:47:36 +00002800/// Determine whether we're looking at something that might be a declarator
2801/// in a simple-declaration. If it can't possibly be a declarator, maybe
2802/// diagnose a missing semicolon after a prior tag definition in the decl
2803/// specifier.
2804///
2805/// \return \c true if an error occurred and this can't be any kind of
2806/// declaration.
2807bool
2808Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2809 DeclSpecContext DSContext,
2810 LateParsedAttrList *LateAttrs) {
2811 assert(DS.hasTagDefinition() && "shouldn't call this");
2812
Faisal Vali7db85c52017-12-31 00:06:40 +00002813 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2814 DSContext == DeclSpecContext::DSC_top_level);
Richard Smith404dfb42013-11-19 22:47:36 +00002815
2816 if (getLangOpts().CPlusPlus &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002817 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2818 tok::annot_template_id) &&
Richard Smith404dfb42013-11-19 22:47:36 +00002819 TryAnnotateCXXScopeToken(EnteringContext)) {
2820 SkipMalformedDecl();
2821 return true;
2822 }
2823
Richard Smith698875a2013-11-20 23:40:57 +00002824 bool HasScope = Tok.is(tok::annot_cxxscope);
2825 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2826 Token AfterScope = HasScope ? NextToken() : Tok;
2827
Richard Smith404dfb42013-11-19 22:47:36 +00002828 // Determine whether the following tokens could possibly be a
2829 // declarator.
Richard Smith698875a2013-11-20 23:40:57 +00002830 bool MightBeDeclarator = true;
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002831 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
Richard Smith698875a2013-11-20 23:40:57 +00002832 // A declarator-id can't start with 'typename'.
2833 MightBeDeclarator = false;
2834 } else if (AfterScope.is(tok::annot_template_id)) {
2835 // If we have a type expressed as a template-id, this cannot be a
2836 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2837 TemplateIdAnnotation *Annot =
2838 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2839 if (Annot->Kind == TNK_Type_template)
2840 MightBeDeclarator = false;
2841 } else if (AfterScope.is(tok::identifier)) {
2842 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2843
Richard Smith404dfb42013-11-19 22:47:36 +00002844 // These tokens cannot come after the declarator-id in a
2845 // simple-declaration, and are likely to come after a type-specifier.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002846 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2847 tok::annot_cxxscope, tok::coloncolon)) {
Richard Smith698875a2013-11-20 23:40:57 +00002848 // Missing a semicolon.
2849 MightBeDeclarator = false;
2850 } else if (HasScope) {
2851 // If the declarator-id has a scope specifier, it must redeclare a
2852 // previously-declared entity. If that's a type (and this is not a
2853 // typedef), that's an error.
2854 CXXScopeSpec SS;
2855 Actions.RestoreNestedNameSpecifierAnnotation(
2856 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2857 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2858 Sema::NameClassification Classification = Actions.ClassifyName(
2859 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
Bruno Ricci70ad3962019-03-25 17:08:51 +00002860 /*IsAddressOfOperand=*/false, /*CCC=*/nullptr);
Richard Smith698875a2013-11-20 23:40:57 +00002861 switch (Classification.getKind()) {
2862 case Sema::NC_Error:
2863 SkipMalformedDecl();
2864 return true;
Richard Smith404dfb42013-11-19 22:47:36 +00002865
Richard Smith698875a2013-11-20 23:40:57 +00002866 case Sema::NC_Keyword:
2867 case Sema::NC_NestedNameSpecifier:
2868 llvm_unreachable("typo correction and nested name specifiers not "
2869 "possible here");
Richard Smith404dfb42013-11-19 22:47:36 +00002870
Richard Smith698875a2013-11-20 23:40:57 +00002871 case Sema::NC_Type:
2872 case Sema::NC_TypeTemplate:
2873 // Not a previously-declared non-type entity.
2874 MightBeDeclarator = false;
2875 break;
Richard Smith404dfb42013-11-19 22:47:36 +00002876
Richard Smith698875a2013-11-20 23:40:57 +00002877 case Sema::NC_Unknown:
2878 case Sema::NC_Expression:
2879 case Sema::NC_VarTemplate:
2880 case Sema::NC_FunctionTemplate:
2881 // Might be a redeclaration of a prior entity.
2882 break;
2883 }
Richard Smith404dfb42013-11-19 22:47:36 +00002884 }
Richard Smith404dfb42013-11-19 22:47:36 +00002885 }
2886
Richard Smith698875a2013-11-20 23:40:57 +00002887 if (MightBeDeclarator)
Richard Smith404dfb42013-11-19 22:47:36 +00002888 return false;
2889
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002890 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002891 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
Alp Toker383d2c42014-01-01 03:08:43 +00002892 diag::err_expected_after)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002893 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
Richard Smith404dfb42013-11-19 22:47:36 +00002894
2895 // Try to recover from the typo, by dropping the tag definition and parsing
2896 // the problematic tokens as a type.
2897 //
2898 // FIXME: Split the DeclSpec into pieces for the standalone
2899 // declaration and pieces for the following declaration, instead
2900 // of assuming that all the other pieces attach to new declaration,
2901 // and call ParsedFreeStandingDeclSpec as appropriate.
2902 DS.ClearTypeSpecType();
2903 ParsedTemplateInfo NotATemplate;
Faisal Valia534f072018-04-26 00:42:40 +00002904 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
Richard Smith404dfb42013-11-19 22:47:36 +00002905 return false;
2906}
2907
Leonard Chanab80f3c2018-06-14 14:53:51 +00002908// Choose the apprpriate diagnostic error for why fixed point types are
2909// disabled, set the previous specifier, and mark as invalid.
2910static void SetupFixedPointError(const LangOptions &LangOpts,
2911 const char *&PrevSpec, unsigned &DiagID,
2912 bool &isInvalid) {
2913 assert(!LangOpts.FixedPoint);
2914 DiagID = diag::err_fixed_point_not_enabled;
2915 PrevSpec = ""; // Not used by diagnostic
2916 isInvalid = true;
2917}
2918
Faisal Valia534f072018-04-26 00:42:40 +00002919/// ParseDeclarationSpecifiers
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002920/// declaration-specifiers: [C99 6.7]
Chris Lattner3b561a32006-08-13 00:12:11 +00002921/// storage-class-specifier declaration-specifiers[opt]
2922/// type-specifier declaration-specifiers[opt]
Chris Lattner3b561a32006-08-13 00:12:11 +00002923/// [C99] function-specifier declaration-specifiers[opt]
Benjamin Kramere56f3932011-12-23 17:00:35 +00002924/// [C11] alignment-specifier declaration-specifiers[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002925/// [GNU] attributes declaration-specifiers[opt]
Douglas Gregor26701a42011-09-09 02:06:17 +00002926/// [Clang] '__module_private__' declaration-specifiers[opt]
Douglas Gregorab209d82015-07-07 03:58:42 +00002927/// [ObjC1] '__kindof' declaration-specifiers[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002928///
Chris Lattnerf63f89a2006-08-05 03:28:50 +00002929/// storage-class-specifier: [C99 6.7.1]
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002930/// 'typedef'
2931/// 'extern'
2932/// 'static'
2933/// 'auto'
2934/// 'register'
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002935/// [C++] 'mutable'
Richard Smithb4a9e862013-04-12 22:46:28 +00002936/// [C++11] 'thread_local'
2937/// [C11] '_Thread_local'
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002938/// [GNU] '__thread'
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002939/// function-specifier: [C99 6.7.4]
Chris Lattner3b561a32006-08-13 00:12:11 +00002940/// [C99] 'inline'
Douglas Gregor61956c42008-10-31 09:07:45 +00002941/// [C++] 'virtual'
2942/// [C++] 'explicit'
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00002943/// [OpenCL] '__kernel'
Anders Carlssoncd8db412009-05-06 04:46:28 +00002944/// 'friend': [C++ dcl.friend]
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00002945/// 'constexpr': [C++0x dcl.constexpr]
Faisal Valia534f072018-04-26 00:42:40 +00002946void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002947 const ParsedTemplateInfo &TemplateInfo,
John McCall07e91c02009-08-06 02:15:43 +00002948 AccessSpecifier AS,
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002949 DeclSpecContext DSContext,
2950 LateParsedAttrList *LateAttrs) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002951 if (DS.getSourceRange().isInvalid()) {
David Majnemer24b28302014-07-26 05:41:31 +00002952 // Start the range at the current token but make the end of the range
2953 // invalid. This will make the entire range invalid unless we successfully
2954 // consume a token.
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002955 DS.SetRangeStart(Tok.getLocation());
David Majnemer24b28302014-07-26 05:41:31 +00002956 DS.SetRangeEnd(SourceLocation());
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002957 }
Chad Rosierc1183952012-06-26 22:30:43 +00002958
Faisal Vali7db85c52017-12-31 00:06:40 +00002959 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2960 DSContext == DeclSpecContext::DSC_top_level);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002961 bool AttrsLastTime = false;
2962 ParsedAttributesWithRange attrs(AttrFactory);
Benjamin Kramere4812142015-03-12 14:28:38 +00002963 // We use Sema's policy to get bool macros right.
Richard Smith301bc212016-05-19 01:39:10 +00002964 PrintingPolicy Policy = Actions.getPrintingPolicy();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002965 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00002966 bool isInvalid = false;
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00002967 bool isStorageClass = false;
Nicolas Lesser5fe2ddb2019-05-04 00:09:00 +00002968 bool isAlreadyConsumed = false;
Craig Topper161e4db2014-05-21 06:02:52 +00002969 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00002970 unsigned DiagID = 0;
2971
Nicolas Lesser5fe2ddb2019-05-04 00:09:00 +00002972 // This value need to be set when isAlreadyConsumed is set to true.
2973 SourceLocation RangeEnd;
2974
David Majnemer51fd8a02015-07-22 23:46:18 +00002975 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2976 // implementation for VS2013 uses _Atomic as an identifier for one of the
2977 // classes in <atomic>.
2978 //
2979 // A typedef declaration containing _Atomic<...> is among the places where
2980 // the class is used. If we are currently parsing such a declaration, treat
2981 // the token as an identifier.
2982 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2983 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2984 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2985 Tok.setKind(tok::identifier);
2986
Chris Lattner4d8f8732006-11-28 05:05:08 +00002987 SourceLocation Loc = Tok.getLocation();
Douglas Gregor450c75a2008-11-07 15:42:26 +00002988
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002989 switch (Tok.getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00002990 default:
Chris Lattner0974b232008-07-26 00:20:22 +00002991 DoneWithDeclSpec:
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002992 if (!AttrsLastTime)
2993 ProhibitAttributes(attrs);
Michael Han64536a62012-11-06 19:34:54 +00002994 else {
2995 // Reject C++11 attributes that appertain to decl specifiers as
2996 // we don't support any C++11 attributes that appertain to decl
2997 // specifiers. This also conforms to what g++ 4.8 is doing.
Richard Smith49cc1cc2016-08-18 21:59:42 +00002998 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
Michael Han64536a62012-11-06 19:34:54 +00002999
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003000 DS.takeAttributesFrom(attrs);
Michael Han64536a62012-11-06 19:34:54 +00003001 }
Peter Collingbourne70188b32011-09-29 18:03:57 +00003002
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003003 // If this is not a declaration specifier token, we're done reading decl
3004 // specifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00003005 DS.Finish(Actions, Policy);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003006 return;
Mike Stump11289f42009-09-09 15:08:12 +00003007
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003008 case tok::l_square:
3009 case tok::kw_alignas:
Aaron Ballman606093a2017-10-15 15:01:42 +00003010 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003011 goto DoneWithDeclSpec;
3012
3013 ProhibitAttributes(attrs);
3014 // FIXME: It would be good to recover by accepting the attributes,
3015 // but attempting to do that now would cause serious
3016 // madness in terms of diagnostics.
3017 attrs.clear();
3018 attrs.Range = SourceRange();
3019
3020 ParseCXX11Attributes(attrs);
3021 AttrsLastTime = true;
Chad Rosierc1183952012-06-26 22:30:43 +00003022 continue;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003023
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003024 case tok::code_completion: {
John McCallfaf5fb42010-08-26 23:41:50 +00003025 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003026 if (DS.hasTypeSpecifier()) {
3027 bool AllowNonIdentifiers
3028 = (getCurScope()->getFlags() & (Scope::ControlScope |
3029 Scope::BlockScope |
3030 Scope::TemplateParamScope |
3031 Scope::FunctionPrototypeScope |
3032 Scope::AtCatchScope)) == 0;
3033 bool AllowNestedNameSpecifiers
Faisal Vali7db85c52017-12-31 00:06:40 +00003034 = DSContext == DeclSpecContext::DSC_top_level ||
3035 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003036
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003037 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
Chad Rosierc1183952012-06-26 22:30:43 +00003038 AllowNonIdentifiers,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003039 AllowNestedNameSpecifiers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003040 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00003041 }
3042
Douglas Gregor80039242011-02-15 20:33:25 +00003043 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3044 CCC = Sema::PCC_LocalDeclarationSpecifiers;
3045 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
Faisal Vali7db85c52017-12-31 00:06:40 +00003046 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3047 : Sema::PCC_Template;
3048 else if (DSContext == DeclSpecContext::DSC_class)
John McCallfaf5fb42010-08-26 23:41:50 +00003049 CCC = Sema::PCC_Class;
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +00003050 else if (CurParsedObjCImpl)
John McCallfaf5fb42010-08-26 23:41:50 +00003051 CCC = Sema::PCC_ObjCImplementation;
Chad Rosierc1183952012-06-26 22:30:43 +00003052
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003053 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003054 return cutOffParsing();
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003055 }
3056
Chris Lattnerbd31aa32009-01-05 00:07:25 +00003057 case tok::coloncolon: // ::foo::bar
John McCall1f476a12010-02-26 08:45:28 +00003058 // C++ scope specifier. Annotate and loop, or bail out on error.
Eli Friedman2a1d9a92013-08-15 23:59:20 +00003059 if (TryAnnotateCXXScopeToken(EnteringContext)) {
John McCall1f476a12010-02-26 08:45:28 +00003060 if (!DS.hasTypeSpecifier())
3061 DS.SetTypeSpecError();
3062 goto DoneWithDeclSpec;
3063 }
John McCall8bc2a702010-03-01 18:20:46 +00003064 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3065 goto DoneWithDeclSpec;
John McCall1f476a12010-02-26 08:45:28 +00003066 continue;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003067
3068 case tok::annot_cxxscope: {
Richard Smith3092a3b2012-05-09 18:56:43 +00003069 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003070 goto DoneWithDeclSpec;
3071
John McCall9dab4e62009-12-12 11:40:51 +00003072 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00003073 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3074 Tok.getAnnotationRange(),
3075 SS);
John McCall9dab4e62009-12-12 11:40:51 +00003076
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003077 // We are looking for a qualified typename.
Douglas Gregor167fa622009-03-25 15:40:00 +00003078 Token Next = NextToken();
Mike Stump11289f42009-09-09 15:08:12 +00003079 if (Next.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003080 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
Douglas Gregorb67535d2009-03-31 00:43:58 +00003081 ->Kind == TNK_Type_template) {
Douglas Gregor167fa622009-03-25 15:40:00 +00003082 // We have a qualified template-id, e.g., N::A<int>
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003083
Richard Smith74f02342017-01-19 21:00:13 +00003084 // If this would be a valid constructor declaration with template
3085 // arguments, we will reject the attempt to form an invalid type-id
3086 // referring to the injected-class-name when we annotate the token,
3087 // per C++ [class.qual]p2.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003088 //
Richard Smith74f02342017-01-19 21:00:13 +00003089 // To improve diagnostics for this case, parse the declaration as a
3090 // constructor (and reject the extra template arguments later).
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003091 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
Faisal Vali7db85c52017-12-31 00:06:40 +00003092 if ((DSContext == DeclSpecContext::DSC_top_level ||
3093 DSContext == DeclSpecContext::DSC_class) &&
John McCall84821e72010-04-13 06:39:49 +00003094 TemplateId->Name &&
Richard Smith74f02342017-01-19 21:00:13 +00003095 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003096 isConstructorDeclarator(/*Unqualified*/ false)) {
Richard Smith74f02342017-01-19 21:00:13 +00003097 // The user meant this to be an out-of-line constructor
3098 // definition, but template arguments are not allowed
3099 // there. Just allow this as a constructor; we'll
3100 // complain about it later.
3101 goto DoneWithDeclSpec;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003102 }
3103
John McCall9dab4e62009-12-12 11:40:51 +00003104 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003105 ConsumeAnnotationToken(); // The C++ scope.
Mike Stump11289f42009-09-09 15:08:12 +00003106 assert(Tok.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003107 "ParseOptionalCXXScopeSpecifier not working");
Douglas Gregore7c20652011-03-02 00:47:37 +00003108 AnnotateTemplateIdTokenAsType();
Douglas Gregor167fa622009-03-25 15:40:00 +00003109 continue;
3110 }
3111
Douglas Gregorc5790df2009-09-28 07:26:33 +00003112 if (Next.is(tok::annot_typename)) {
John McCall9dab4e62009-12-12 11:40:51 +00003113 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003114 ConsumeAnnotationToken(); // The C++ scope.
John McCallba7bf592010-08-24 05:47:05 +00003115 if (Tok.getAnnotationValue()) {
3116 ParsedType T = getTypeAnnotation(Tok);
Nico Weber77430342010-11-22 10:30:56 +00003117 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
Chad Rosierc1183952012-06-26 22:30:43 +00003118 Tok.getAnnotationEndLoc(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003119 PrevSpec, DiagID, T, Policy);
Richard Smithda837032012-09-14 18:27:01 +00003120 if (isInvalid)
3121 break;
John McCallba7bf592010-08-24 05:47:05 +00003122 }
Douglas Gregorc5790df2009-09-28 07:26:33 +00003123 else
3124 DS.SetTypeSpecError();
3125 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003126 ConsumeAnnotationToken(); // The typename
Douglas Gregorc5790df2009-09-28 07:26:33 +00003127 }
3128
Douglas Gregor167fa622009-03-25 15:40:00 +00003129 if (Next.isNot(tok::identifier))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003130 goto DoneWithDeclSpec;
3131
Richard Smith74f02342017-01-19 21:00:13 +00003132 // Check whether this is a constructor declaration. If we're in a
3133 // context where the identifier could be a class name, and it has the
3134 // shape of a constructor declaration, process it as one.
Faisal Vali7db85c52017-12-31 00:06:40 +00003135 if ((DSContext == DeclSpecContext::DSC_top_level ||
3136 DSContext == DeclSpecContext::DSC_class) &&
Chad Rosierc1183952012-06-26 22:30:43 +00003137 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
Richard Smith74f02342017-01-19 21:00:13 +00003138 &SS) &&
3139 isConstructorDeclarator(/*Unqualified*/ false))
3140 goto DoneWithDeclSpec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003141
David Blaikieefdccaa2016-01-15 23:43:34 +00003142 ParsedType TypeRep =
3143 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3144 getCurScope(), &SS, false, false, nullptr,
3145 /*IsCtorOrDtorName=*/false,
Richard Smith600b5262017-01-26 20:40:47 +00003146 /*WantNonTrivialSourceInfo=*/true,
3147 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003148
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003149 // If the referenced identifier is not a type, then this declspec is
3150 // erroneous: We already checked about that it has no type specifier, and
3151 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
Mike Stump11289f42009-09-09 15:08:12 +00003152 // typename.
David Blaikie7d170102013-05-15 07:37:26 +00003153 if (!TypeRep) {
Richard Smithaf3b3252017-05-18 19:21:48 +00003154 // Eat the scope spec so the identifier is current.
3155 ConsumeAnnotationToken();
Michael Han9407e502012-11-26 22:54:45 +00003156 ParsedAttributesWithRange Attrs(AttrFactory);
3157 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3158 if (!Attrs.empty()) {
3159 AttrsLastTime = true;
3160 attrs.takeAllFrom(Attrs);
3161 }
3162 continue;
3163 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003164 goto DoneWithDeclSpec;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003165 }
Mike Stump11289f42009-09-09 15:08:12 +00003166
John McCall9dab4e62009-12-12 11:40:51 +00003167 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003168 ConsumeAnnotationToken(); // The C++ scope.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003169
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003170 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003171 DiagID, TypeRep, Policy);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003172 if (isInvalid)
3173 break;
Mike Stump11289f42009-09-09 15:08:12 +00003174
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003175 DS.SetRangeEnd(Tok.getLocation());
3176 ConsumeToken(); // The typename.
3177
3178 continue;
3179 }
Mike Stump11289f42009-09-09 15:08:12 +00003180
Chris Lattnere387d9e2009-01-21 19:48:37 +00003181 case tok::annot_typename: {
Richard Smith404dfb42013-11-19 22:47:36 +00003182 // If we've previously seen a tag definition, we were almost surely
3183 // missing a semicolon after it.
3184 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3185 goto DoneWithDeclSpec;
3186
John McCallba7bf592010-08-24 05:47:05 +00003187 if (Tok.getAnnotationValue()) {
3188 ParsedType T = getTypeAnnotation(Tok);
Nico Weber7f8bb362010-11-22 12:50:03 +00003189 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003190 DiagID, T, Policy);
John McCallba7bf592010-08-24 05:47:05 +00003191 } else
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003192 DS.SetTypeSpecError();
Chad Rosierc1183952012-06-26 22:30:43 +00003193
Chris Lattner005fc1b2010-04-05 18:18:31 +00003194 if (isInvalid)
3195 break;
3196
Chris Lattnere387d9e2009-01-21 19:48:37 +00003197 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003198 ConsumeAnnotationToken(); // The typename
Mike Stump11289f42009-09-09 15:08:12 +00003199
Chris Lattnere387d9e2009-01-21 19:48:37 +00003200 continue;
3201 }
Mike Stump11289f42009-09-09 15:08:12 +00003202
Douglas Gregor06873092011-04-28 15:48:45 +00003203 case tok::kw___is_signed:
3204 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3205 // typically treats it as a trait. If we see __is_signed as it appears
3206 // in libstdc++, e.g.,
3207 //
3208 // static const bool __is_signed;
3209 //
3210 // then treat __is_signed as an identifier rather than as a keyword.
Faisal Vali090da2d2018-01-01 18:23:28 +00003211 if (DS.getTypeSpecType() == TST_bool &&
Douglas Gregor06873092011-04-28 15:48:45 +00003212 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
Alp Toker47642d22013-12-03 06:13:01 +00003213 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3214 TryKeywordIdentFallback(true);
Douglas Gregor06873092011-04-28 15:48:45 +00003215
3216 // We're done with the declaration-specifiers.
3217 goto DoneWithDeclSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00003218
Chris Lattner16fac4f2008-07-26 01:18:38 +00003219 // typedef-name
Nikola Smiljanic67860242014-09-26 00:28:20 +00003220 case tok::kw___super:
David Blaikie15a430a2011-12-04 05:04:18 +00003221 case tok::kw_decltype:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003222 case tok::identifier: {
Reid Klecknerc582f012014-07-14 18:19:58 +00003223 // This identifier can only be a typedef name if we haven't already seen
3224 // a type-specifier. Without this check we misparse:
3225 // typedef int X; struct Y { short X; }; as 'short int'.
3226 if (DS.hasTypeSpecifier())
3227 goto DoneWithDeclSpec;
3228
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003229 // If the token is an identifier named "__declspec" and Microsoft
3230 // extensions are not enabled, it is likely that there will be cascading
3231 // parse errors if this really is a __declspec attribute. Attempt to
3232 // recognize that scenario and recover gracefully.
3233 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3234 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3235 Diag(Loc, diag::err_ms_attributes_not_enabled);
3236
3237 // The next token should be an open paren. If it is, eat the entire
3238 // attribute declaration and continue.
3239 if (NextToken().is(tok::l_paren)) {
3240 // Consume the __declspec identifier.
Richard Trieuba057372017-02-14 23:56:55 +00003241 ConsumeToken();
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003242
3243 // Eat the parens and everything between them.
3244 BalancedDelimiterTracker T(*this, tok::l_paren);
3245 if (T.consumeOpen()) {
3246 assert(false && "Not a left paren?");
3247 return;
3248 }
3249 T.skipToEnd();
3250 continue;
3251 }
3252 }
3253
Serge Pavlov458ea762014-07-16 05:16:52 +00003254 // In C++, check to see if this is a scope specifier like foo::bar::, if
3255 // so handle it as such. This is important for ctor parsing.
3256 if (getLangOpts().CPlusPlus) {
3257 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3258 DS.SetTypeSpecError();
3259 goto DoneWithDeclSpec;
3260 }
3261 if (!Tok.is(tok::identifier))
3262 continue;
3263 }
3264
John Thompson22334602010-02-05 00:12:22 +00003265 // Check for need to substitute AltiVec keyword tokens.
3266 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3267 break;
3268
Richard Smith3092a3b2012-05-09 18:56:43 +00003269 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3270 // allow the use of a typedef name as a type specifier.
3271 if (DS.isTypeAltiVecVector())
3272 goto DoneWithDeclSpec;
3273
Faisal Vali7db85c52017-12-31 00:06:40 +00003274 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3275 isObjCInstancetype()) {
Douglas Gregor5c0870a2015-06-19 23:18:00 +00003276 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3277 assert(TypeRep);
3278 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3279 DiagID, TypeRep, Policy);
3280 if (isInvalid)
3281 break;
3282
3283 DS.SetRangeEnd(Loc);
3284 ConsumeToken();
3285 continue;
3286 }
3287
Richard Smith715ee072018-06-20 21:58:20 +00003288 // If we're in a context where the identifier could be a class name,
3289 // check whether this is a constructor declaration.
3290 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3291 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3292 isConstructorDeclarator(/*Unqualified*/true))
3293 goto DoneWithDeclSpec;
3294
Richard Smith600b5262017-01-26 20:40:47 +00003295 ParsedType TypeRep = Actions.getTypeName(
3296 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3297 false, false, nullptr, false, false,
3298 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003299
Chris Lattner6cc055a2009-04-12 20:42:31 +00003300 // If this is not a typedef name, don't parse it as part of the declspec,
3301 // it must be an implicit int or an error.
John McCallba7bf592010-08-24 05:47:05 +00003302 if (!TypeRep) {
Michael Han9407e502012-11-26 22:54:45 +00003303 ParsedAttributesWithRange Attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +00003304 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
Michael Han9407e502012-11-26 22:54:45 +00003305 if (!Attrs.empty()) {
3306 AttrsLastTime = true;
3307 attrs.takeAllFrom(Attrs);
3308 }
3309 continue;
3310 }
Chris Lattner16fac4f2008-07-26 01:18:38 +00003311 goto DoneWithDeclSpec;
Chris Lattner6cc055a2009-04-12 20:42:31 +00003312 }
Douglas Gregor8bf42052009-02-09 18:46:07 +00003313
Richard Smith35845152017-02-07 01:37:30 +00003314 // Likewise, if this is a context where the identifier could be a template
3315 // name, check whether this is a deduction guide declaration.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003316 if (getLangOpts().CPlusPlus17 &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003317 (DSContext == DeclSpecContext::DSC_class ||
3318 DSContext == DeclSpecContext::DSC_top_level) &&
Richard Smith35845152017-02-07 01:37:30 +00003319 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3320 Tok.getLocation()) &&
3321 isConstructorDeclarator(/*Unqualified*/ true,
3322 /*DeductionGuide*/ true))
3323 goto DoneWithDeclSpec;
3324
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003325 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003326 DiagID, TypeRep, Policy);
Chris Lattner16fac4f2008-07-26 01:18:38 +00003327 if (isInvalid)
3328 break;
Mike Stump11289f42009-09-09 15:08:12 +00003329
Chris Lattner16fac4f2008-07-26 01:18:38 +00003330 DS.SetRangeEnd(Tok.getLocation());
3331 ConsumeToken(); // The identifier
3332
Douglas Gregore9d95f12015-07-07 03:57:35 +00003333 // Objective-C supports type arguments and protocol references
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003334 // following an Objective-C object or object pointer
3335 // type. Handle either one of them.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003336 if (Tok.is(tok::less) && getLangOpts().ObjC) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003337 SourceLocation NewEndLoc;
3338 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3339 Loc, TypeRep, /*consumeLastToken=*/true,
3340 NewEndLoc);
3341 if (NewTypeRep.isUsable()) {
3342 DS.UpdateTypeRep(NewTypeRep.get());
3343 DS.SetRangeEnd(NewEndLoc);
3344 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00003345 }
Chad Rosierc1183952012-06-26 22:30:43 +00003346
Steve Naroffcd5e7822008-09-22 10:28:57 +00003347 // Need to support trailing type qualifiers (e.g. "id<p> const").
3348 // If a type specifier follows, it will be diagnosed elsewhere.
3349 continue;
Chris Lattner16fac4f2008-07-26 01:18:38 +00003350 }
Douglas Gregor7f741122009-02-25 19:37:18 +00003351
3352 // type-name
3353 case tok::annot_template_id: {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003354 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorb67535d2009-03-31 00:43:58 +00003355 if (TemplateId->Kind != TNK_Type_template) {
Douglas Gregor7f741122009-02-25 19:37:18 +00003356 // This template-id does not refer to a type name, so we're
3357 // done with the type-specifiers.
3358 goto DoneWithDeclSpec;
3359 }
3360
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003361 // If we're in a context where the template-id could be a
3362 // constructor name or specialization, check whether this is a
3363 // constructor declaration.
Faisal Vali7db85c52017-12-31 00:06:40 +00003364 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00003365 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
Richard Smith446161b2014-03-03 21:12:53 +00003366 isConstructorDeclarator(TemplateId->SS.isEmpty()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003367 goto DoneWithDeclSpec;
3368
Douglas Gregor7f741122009-02-25 19:37:18 +00003369 // Turn the template-id annotation token into a type annotation
3370 // token, then try again to parse it as a type-specifier.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003371 AnnotateTemplateIdTokenAsType();
Douglas Gregor7f741122009-02-25 19:37:18 +00003372 continue;
3373 }
3374
Chris Lattnere37e2332006-08-15 04:50:22 +00003375 // GNU attributes support.
3376 case tok::kw___attribute:
Craig Topper161e4db2014-05-21 06:02:52 +00003377 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
Chris Lattnerb95cca02006-10-17 03:01:08 +00003378 continue;
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003379
3380 // Microsoft declspec support.
3381 case tok::kw___declspec:
Aaron Ballman068aa512015-05-20 20:58:33 +00003382 ParseMicrosoftDeclSpecs(DS.getAttributes());
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003383 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003384
Steve Naroff44ac7772008-12-25 14:16:32 +00003385 // Microsoft single token adornments.
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003386 case tok::kw___forceinline: {
Serge Pavlov750db652013-11-13 06:57:53 +00003387 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003388 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Richard Smithda837032012-09-14 18:27:01 +00003389 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00003390 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00003391 nullptr, 0, ParsedAttr::AS_Keyword);
Richard Smithda837032012-09-14 18:27:01 +00003392 break;
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003393 }
Eli Friedman53339e02009-06-08 23:27:34 +00003394
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003395 case tok::kw___unaligned:
3396 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3397 getLangOpts());
3398 break;
3399
Aaron Ballman317a77f2013-05-22 23:25:32 +00003400 case tok::kw___sptr:
3401 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00003402 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00003403 case tok::kw___ptr32:
Steve Narofff9c29d42008-12-25 14:41:26 +00003404 case tok::kw___w64:
Steve Naroff44ac7772008-12-25 14:16:32 +00003405 case tok::kw___cdecl:
3406 case tok::kw___stdcall:
3407 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00003408 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00003409 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00003410 case tok::kw___vectorcall:
John McCall53fa7142010-12-24 02:08:15 +00003411 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00003412 continue;
3413
Dawn Perchik335e16b2010-09-03 01:29:35 +00003414 // Borland single token adornments.
3415 case tok::kw___pascal:
John McCall53fa7142010-12-24 02:08:15 +00003416 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00003417 continue;
3418
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003419 // OpenCL single token adornments.
3420 case tok::kw___kernel:
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +00003421 ParseOpenCLKernelAttributes(DS.getAttributes());
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003422 continue;
3423
Douglas Gregor261a89b2015-06-19 17:51:05 +00003424 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00003425 case tok::kw__Nonnull:
3426 case tok::kw__Nullable:
3427 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00003428 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3429 continue;
3430
Douglas Gregorab209d82015-07-07 03:58:42 +00003431 // Objective-C 'kindof' types.
3432 case tok::kw___kindof:
3433 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00003434 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00003435 (void)ConsumeToken();
3436 continue;
3437
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003438 // storage-class-specifier
3439 case tok::kw_typedef:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003440 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003441 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003442 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003443 break;
3444 case tok::kw_extern:
Richard Smithb4a9e862013-04-12 22:46:28 +00003445 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003446 Diag(Tok, diag::ext_thread_before) << "extern";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003447 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003448 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003449 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003450 break;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003451 case tok::kw___private_extern__:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003452 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003453 Loc, PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003454 isStorageClass = true;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003455 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003456 case tok::kw_static:
Richard Smithb4a9e862013-04-12 22:46:28 +00003457 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003458 Diag(Tok, diag::ext_thread_before) << "static";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003459 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003460 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003461 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003462 break;
3463 case tok::kw_auto:
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003464 if (getLangOpts().CPlusPlus11) {
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003465 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003466 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003467 PrevSpec, DiagID, Policy);
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003468 if (!isInvalid)
Richard Smith58c74332011-09-04 19:54:14 +00003469 Diag(Tok, diag::ext_auto_storage_class)
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003470 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith58c74332011-09-04 19:54:14 +00003471 } else
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003472 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003473 DiagID, Policy);
Richard Smith58c74332011-09-04 19:54:14 +00003474 } else
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003475 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003476 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003477 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003478 break;
Richard Smithe301ba22015-11-11 02:02:15 +00003479 case tok::kw___auto_type:
3480 Diag(Tok, diag::ext_auto_type);
3481 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3482 DiagID, Policy);
3483 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003484 case tok::kw_register:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003485 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003486 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003487 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003488 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003489 case tok::kw_mutable:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003490 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003491 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003492 isStorageClass = true;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003493 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003494 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00003495 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3496 PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003497 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003498 break;
3499 case tok::kw_thread_local:
3500 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3501 PrevSpec, DiagID);
Sven van Haastregtc4100832018-04-24 14:47:29 +00003502 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003503 break;
3504 case tok::kw__Thread_local:
3505 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3506 Loc, PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003507 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003508 break;
Mike Stump11289f42009-09-09 15:08:12 +00003509
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003510 // function-specifier
3511 case tok::kw_inline:
Serge Pavlov750db652013-11-13 06:57:53 +00003512 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003513 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003514 case tok::kw_virtual:
Sven van Haastregt49ffffb2018-04-23 11:23:47 +00003515 // OpenCL C++ v1.0 s2.9: the virtual function qualifier is not supported.
3516 if (getLangOpts().OpenCLCPlusPlus) {
3517 DiagID = diag::err_openclcxx_virtual_function;
3518 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3519 isInvalid = true;
3520 }
3521 else {
3522 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3523 }
Douglas Gregor61956c42008-10-31 09:07:45 +00003524 break;
Nicolas Lesser5fe2ddb2019-05-04 00:09:00 +00003525 case tok::kw_explicit: {
3526 SourceLocation ExplicitLoc = Loc;
3527 SourceLocation CloseParenLoc;
3528 ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
3529 isAlreadyConsumed = true;
3530 RangeEnd = ExplicitLoc;
3531 ConsumeToken(); // kw_explicit
3532 if (Tok.is(tok::l_paren)) {
3533 if (getLangOpts().CPlusPlus2a) {
3534 ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3535 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3536 Tracker.consumeOpen();
3537 ExplicitExpr = ParseConstantExpression();
3538 RangeEnd = Tok.getLocation();
3539 if (ExplicitExpr.isUsable()) {
3540 CloseParenLoc = Tok.getLocation();
3541 Tracker.consumeClose();
3542 ExplicitSpec =
3543 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3544 } else
3545 Tracker.skipToEnd();
3546 } else
3547 Diag(Tok.getLocation(), diag::warn_cxx2a_compat_explicit_bool);
3548 }
3549 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3550 ExplicitSpec, CloseParenLoc);
Douglas Gregor61956c42008-10-31 09:07:45 +00003551 break;
Nicolas Lesser5fe2ddb2019-05-04 00:09:00 +00003552 }
Richard Smith0015f092013-01-17 22:16:11 +00003553 case tok::kw__Noreturn:
3554 if (!getLangOpts().C11)
3555 Diag(Loc, diag::ext_c11_noreturn);
Serge Pavlov750db652013-11-13 06:57:53 +00003556 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
Richard Smith0015f092013-01-17 22:16:11 +00003557 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003558
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003559 // alignment-specifier
3560 case tok::kw__Alignas:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003561 if (!getLangOpts().C11)
Jordan Rose58d54722012-06-30 21:33:57 +00003562 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003563 ParseAlignmentSpecifier(DS.getAttributes());
3564 continue;
3565
Anders Carlssoncd8db412009-05-06 04:46:28 +00003566 // friend
3567 case tok::kw_friend:
Faisal Vali7db85c52017-12-31 00:06:40 +00003568 if (DSContext == DeclSpecContext::DSC_class)
John McCall07e91c02009-08-06 02:15:43 +00003569 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3570 else {
3571 PrevSpec = ""; // not actually used by the diagnostic
3572 DiagID = diag::err_friend_invalid_in_context;
3573 isInvalid = true;
3574 }
Anders Carlssoncd8db412009-05-06 04:46:28 +00003575 break;
Mike Stump11289f42009-09-09 15:08:12 +00003576
Douglas Gregor26701a42011-09-09 02:06:17 +00003577 // Modules
3578 case tok::kw___module_private__:
3579 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3580 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003581
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00003582 // constexpr
3583 case tok::kw_constexpr:
3584 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3585 break;
3586
Chris Lattnere387d9e2009-01-21 19:48:37 +00003587 // type-specifier
3588 case tok::kw_short:
John McCall49bfce42009-08-03 20:12:06 +00003589 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, 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_long:
3593 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
John McCall49bfce42009-08-03 20:12:06 +00003594 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003595 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003596 else
John McCall49bfce42009-08-03 20:12:06 +00003597 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003598 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003599 break;
Francois Pichet84133e42011-04-28 01:59:37 +00003600 case tok::kw___int64:
3601 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003602 DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00003603 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003604 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00003605 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3606 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003607 break;
3608 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00003609 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3610 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003611 break;
3612 case tok::kw__Complex:
John McCall49bfce42009-08-03 20:12:06 +00003613 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3614 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003615 break;
3616 case tok::kw__Imaginary:
John McCall49bfce42009-08-03 20:12:06 +00003617 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3618 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003619 break;
3620 case tok::kw_void:
John McCall49bfce42009-08-03 20:12:06 +00003621 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003622 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003623 break;
3624 case tok::kw_char:
John McCall49bfce42009-08-03 20:12:06 +00003625 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003626 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003627 break;
3628 case tok::kw_int:
John McCall49bfce42009-08-03 20:12:06 +00003629 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003630 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003631 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00003632 case tok::kw___int128:
3633 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003634 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003635 break;
3636 case tok::kw_half:
3637 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003638 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003639 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003640 case tok::kw_float:
John McCall49bfce42009-08-03 20:12:06 +00003641 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003642 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003643 break;
3644 case tok::kw_double:
John McCall49bfce42009-08-03 20:12:06 +00003645 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003646 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003647 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00003648 case tok::kw__Float16:
3649 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3650 DiagID, Policy);
3651 break;
Leonard Chanf921d852018-06-04 16:07:52 +00003652 case tok::kw__Accum:
3653 if (!getLangOpts().FixedPoint) {
Leonard Chanab80f3c2018-06-14 14:53:51 +00003654 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
Leonard Chanf921d852018-06-04 16:07:52 +00003655 } else {
3656 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3657 DiagID, Policy);
3658 }
3659 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00003660 case tok::kw__Fract:
3661 if (!getLangOpts().FixedPoint) {
3662 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3663 } else {
3664 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3665 DiagID, Policy);
3666 }
3667 break;
3668 case tok::kw__Sat:
3669 if (!getLangOpts().FixedPoint) {
3670 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3671 } else {
3672 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3673 }
3674 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003675 case tok::kw___float128:
3676 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3677 DiagID, Policy);
3678 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003679 case tok::kw_wchar_t:
John McCall49bfce42009-08-03 20:12:06 +00003680 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003681 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003682 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00003683 case tok::kw_char8_t:
3684 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3685 DiagID, Policy);
3686 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003687 case tok::kw_char16_t:
John McCall49bfce42009-08-03 20:12:06 +00003688 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003689 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003690 break;
3691 case tok::kw_char32_t:
John McCall49bfce42009-08-03 20:12:06 +00003692 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003693 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003694 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003695 case tok::kw_bool:
3696 case tok::kw__Bool:
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003697 if (Tok.is(tok::kw_bool) &&
3698 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3699 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3700 PrevSpec = ""; // Not used by the diagnostic.
3701 DiagID = diag::err_bool_redeclaration;
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003702 // For better error recovery.
3703 Tok.setKind(tok::identifier);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003704 isInvalid = true;
3705 } else {
3706 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003707 DiagID, Policy);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003708 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003709 break;
3710 case tok::kw__Decimal32:
John McCall49bfce42009-08-03 20:12:06 +00003711 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003712 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003713 break;
3714 case tok::kw__Decimal64:
John McCall49bfce42009-08-03 20:12:06 +00003715 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003716 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003717 break;
3718 case tok::kw__Decimal128:
John McCall49bfce42009-08-03 20:12:06 +00003719 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003720 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003721 break;
John Thompson22334602010-02-05 00:12:22 +00003722 case tok::kw___vector:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003723 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003724 break;
3725 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003726 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003727 break;
Bill Seurercf2c96b2015-01-12 19:35:51 +00003728 case tok::kw___bool:
3729 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3730 break;
Xiuli Pan9c14e282016-01-09 12:53:17 +00003731 case tok::kw_pipe:
3732 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3733 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3734 // support the "pipe" word as identifier.
3735 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3736 goto DoneWithDeclSpec;
3737 }
3738 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3739 break;
Alexey Bader954ba212016-04-08 13:40:33 +00003740#define GENERIC_IMAGE_TYPE(ImgType, Id) \
3741 case tok::kw_##ImgType##_t: \
3742 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3743 DiagID, Policy); \
3744 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00003745#include "clang/Basic/OpenCLImageTypes.def"
John McCall39439732011-04-09 22:50:59 +00003746 case tok::kw___unknown_anytype:
Faisal Vali090da2d2018-01-01 18:23:28 +00003747 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003748 PrevSpec, DiagID, Policy);
John McCall39439732011-04-09 22:50:59 +00003749 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003750
3751 // class-specifier:
3752 case tok::kw_class:
3753 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00003754 case tok::kw___interface:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003755 case tok::kw_union: {
3756 tok::TokenKind Kind = Tok.getKind();
3757 ConsumeToken();
Michael Han9407e502012-11-26 22:54:45 +00003758
3759 // These are attributes following class specifiers.
3760 // To produce better diagnostic, we parse them when
3761 // parsing class specifier.
Bill Wendling44426052012-12-20 19:22:21 +00003762 ParsedAttributesWithRange Attributes(AttrFactory);
Richard Smithc5b05522012-03-12 07:56:15 +00003763 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
Bill Wendling44426052012-12-20 19:22:21 +00003764 EnteringContext, DSContext, Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003765
3766 // If there are attributes following class specifier,
3767 // take them over and handle them here.
Bill Wendling44426052012-12-20 19:22:21 +00003768 if (!Attributes.empty()) {
Michael Han9407e502012-11-26 22:54:45 +00003769 AttrsLastTime = true;
Bill Wendling44426052012-12-20 19:22:21 +00003770 attrs.takeAllFrom(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003771 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003772 continue;
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003773 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003774
3775 // enum-specifier:
3776 case tok::kw_enum:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003777 ConsumeToken();
Richard Smithc5b05522012-03-12 07:56:15 +00003778 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003779 continue;
Faisal Valia534f072018-04-26 00:42:40 +00003780
Chris Lattnere387d9e2009-01-21 19:48:37 +00003781 // cv-qualifier:
3782 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00003783 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003784 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003785 break;
3786 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00003787 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003788 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003789 break;
3790 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00003791 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003792 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003793 break;
3794
Douglas Gregor333489b2009-03-27 23:10:48 +00003795 // C++ typename-specifier:
3796 case tok::kw_typename:
John McCall1f476a12010-02-26 08:45:28 +00003797 if (TryAnnotateTypeOrScopeToken()) {
3798 DS.SetTypeSpecError();
3799 goto DoneWithDeclSpec;
3800 }
3801 if (!Tok.is(tok::kw_typename))
Douglas Gregor333489b2009-03-27 23:10:48 +00003802 continue;
3803 break;
3804
Chris Lattnere387d9e2009-01-21 19:48:37 +00003805 // GNU typeof support.
3806 case tok::kw_typeof:
3807 ParseTypeofSpecifier(DS);
3808 continue;
3809
David Blaikie15a430a2011-12-04 05:04:18 +00003810 case tok::annot_decltype:
Anders Carlsson74948d02009-06-24 17:47:40 +00003811 ParseDecltypeSpecifier(DS);
3812 continue;
3813
David Majnemer15b311c2016-06-14 03:20:28 +00003814 case tok::annot_pragma_pack:
3815 HandlePragmaPack();
3816 continue;
3817
3818 case tok::annot_pragma_ms_pragma:
3819 HandlePragmaMSPragma();
3820 continue;
3821
3822 case tok::annot_pragma_ms_vtordisp:
3823 HandlePragmaMSVtorDisp();
3824 continue;
3825
3826 case tok::annot_pragma_ms_pointers_to_members:
3827 HandlePragmaMSPointersToMembers();
3828 continue;
3829
Alexis Hunt4a257072011-05-19 05:37:45 +00003830 case tok::kw___underlying_type:
3831 ParseUnderlyingTypeSpecifier(DS);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003832 continue;
3833
3834 case tok::kw__Atomic:
Richard Smith8e1ac332013-03-28 01:55:44 +00003835 // C11 6.7.2.4/4:
3836 // If the _Atomic keyword is immediately followed by a left parenthesis,
3837 // it is interpreted as a type specifier (with a type name), not as a
3838 // type qualifier.
3839 if (NextToken().is(tok::l_paren)) {
3840 ParseAtomicSpecifier(DS);
3841 continue;
3842 }
3843 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3844 getLangOpts());
3845 break;
Alexis Hunt4a257072011-05-19 05:37:45 +00003846
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003847 // OpenCL address space qualifiers:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003848 case tok::kw___generic:
3849 // generic address space is introduced only in OpenCL v2.0
3850 // see OpenCL C Spec v2.0 s6.5.5
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003851 if (Actions.getLangOpts().OpenCLVersion < 200 &&
3852 !Actions.getLangOpts().OpenCLCPlusPlus) {
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003853 DiagID = diag::err_opencl_unknown_type_specifier;
3854 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3855 isInvalid = true;
3856 break;
3857 };
Galina Kistanova77674252017-06-01 21:15:34 +00003858 LLVM_FALLTHROUGH;
Anastasia Stulova948e37c2019-03-25 11:54:02 +00003859 case tok::kw_private:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003860 case tok::kw___private:
3861 case tok::kw___global:
3862 case tok::kw___local:
3863 case tok::kw___constant:
Anastasia Stulova2c4730d2019-02-15 12:07:57 +00003864 // OpenCL access qualifiers:
3865 case tok::kw___read_only:
3866 case tok::kw___write_only:
3867 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00003868 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003869 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003870
Steve Naroffcfdf6162008-06-05 00:02:44 +00003871 case tok::less:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003872 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
Chris Lattner0974b232008-07-26 00:20:22 +00003873 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3874 // but we support it.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003875 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
Chris Lattner0974b232008-07-26 00:20:22 +00003876 goto DoneWithDeclSpec;
Mike Stump11289f42009-09-09 15:08:12 +00003877
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003878 SourceLocation StartLoc = Tok.getLocation();
3879 SourceLocation EndLoc;
3880 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3881 if (Type.isUsable()) {
3882 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3883 PrevSpec, DiagID, Type.get(),
3884 Actions.getASTContext().getPrintingPolicy()))
3885 Diag(StartLoc, DiagID) << PrevSpec;
Fangrui Song6907ce22018-07-30 19:24:48 +00003886
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003887 DS.SetRangeEnd(EndLoc);
3888 } else {
3889 DS.SetTypeSpecError();
3890 }
Chad Rosierc1183952012-06-26 22:30:43 +00003891
Douglas Gregor06e41ae2010-10-21 23:17:00 +00003892 // Need to support trailing type qualifiers (e.g. "id<p> const").
3893 // If a type specifier follows, it will be diagnosed elsewhere.
3894 continue;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003895 }
Nicolas Lesser5fe2ddb2019-05-04 00:09:00 +00003896
Nicolas Lesser55dc7512019-05-04 11:28:11 +00003897 assert((!isAlreadyConsumed || RangeEnd != SourceLocation()) &&
Nicolas Lesser5fe2ddb2019-05-04 00:09:00 +00003898 "both or neither of isAlreadyConsumed and "
3899 "RangeEnd needs to be set");
3900 DS.SetRangeEnd(isAlreadyConsumed ? RangeEnd : Tok.getLocation());
3901
John McCall49bfce42009-08-03 20:12:06 +00003902 // If the specifier wasn't legal, issue a diagnostic.
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003903 if (isInvalid) {
3904 assert(PrevSpec && "Method did not return previous specifier!");
John McCall49bfce42009-08-03 20:12:06 +00003905 assert(DiagID);
Chad Rosierc1183952012-06-26 22:30:43 +00003906
Nick Desaulniers150ca532018-10-03 23:09:29 +00003907 if (DiagID == diag::ext_duplicate_declspec ||
Nicolas Lesser5fe2ddb2019-05-04 00:09:00 +00003908 DiagID == diag::ext_warn_duplicate_declspec ||
3909 DiagID == diag::err_duplicate_declspec)
3910 Diag(Loc, DiagID) << PrevSpec
3911 << FixItHint::CreateRemoval(
3912 SourceRange(Loc, DS.getEndLoc()));
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003913 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
Nicolas Lesser5fe2ddb2019-05-04 00:09:00 +00003914 Diag(Loc, DiagID) << getLangOpts().OpenCLCPlusPlus
3915 << getLangOpts().getOpenCLVersionTuple().getAsString()
3916 << PrevSpec << isStorageClass;
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003917 } else
Nicolas Lesser5fe2ddb2019-05-04 00:09:00 +00003918 Diag(Loc, DiagID) << PrevSpec;
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003919 }
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003920
Nicolas Lesser5fe2ddb2019-05-04 00:09:00 +00003921 if (DiagID != diag::err_bool_redeclaration && !isAlreadyConsumed)
Volodymyr Sapsai9f7b5cc2018-04-10 18:29:47 +00003922 // After an error the next token can be an annotation token.
3923 ConsumeAnyToken();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003924
3925 AttrsLastTime = false;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003926 }
3927}
Douglas Gregoreb31f392008-12-01 23:54:00 +00003928
Chris Lattner70ae4912007-10-29 04:42:53 +00003929/// ParseStructDeclaration - Parse a struct declaration without the terminating
3930/// semicolon.
3931///
Nico Weber98dd0852019-03-14 14:18:56 +00003932/// Note that a struct declaration refers to a declaration in a struct,
3933/// not to the declaration of a struct.
3934///
Chris Lattner90a26b02007-01-23 04:38:16 +00003935/// struct-declaration:
Aaron Ballman606093a2017-10-15 15:01:42 +00003936/// [C2x] attributes-specifier-seq[opt]
3937/// specifier-qualifier-list struct-declarator-list
Chris Lattner736ed5d2007-06-09 05:59:07 +00003938/// [GNU] __extension__ struct-declaration
Chris Lattner70ae4912007-10-29 04:42:53 +00003939/// [GNU] specifier-qualifier-list
Chris Lattner90a26b02007-01-23 04:38:16 +00003940/// struct-declarator-list:
3941/// struct-declarator
3942/// struct-declarator-list ',' struct-declarator
3943/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3944/// struct-declarator:
3945/// declarator
3946/// [GNU] declarator attributes[opt]
3947/// declarator[opt] ':' constant-expression
3948/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3949///
Benjamin Kramera39beb92014-09-03 11:06:10 +00003950void Parser::ParseStructDeclaration(
3951 ParsingDeclSpec &DS,
3952 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
Chad Rosierc1183952012-06-26 22:30:43 +00003953
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003954 if (Tok.is(tok::kw___extension__)) {
3955 // __extension__ silences extension warnings in the subexpression.
3956 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Steve Naroff97170802007-08-20 22:28:22 +00003957 ConsumeToken();
Benjamin Kramera39beb92014-09-03 11:06:10 +00003958 return ParseStructDeclaration(DS, FieldsCallback);
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003959 }
Mike Stump11289f42009-09-09 15:08:12 +00003960
Aaron Ballman606093a2017-10-15 15:01:42 +00003961 // Parse leading attributes.
3962 ParsedAttributesWithRange Attrs(AttrFactory);
3963 MaybeParseCXX11Attributes(Attrs);
3964 DS.takeAttributesFrom(Attrs);
3965
Steve Naroff97170802007-08-20 22:28:22 +00003966 // Parse the common specifier-qualifiers-list piece.
Steve Naroff97170802007-08-20 22:28:22 +00003967 ParseSpecifierQualifierList(DS);
Mike Stump11289f42009-09-09 15:08:12 +00003968
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003969 // If there are no declarators, this is a free-standing declaration
3970 // specifier. Let the actions module cope with it.
Chris Lattner76c72282007-10-09 17:33:22 +00003971 if (Tok.is(tok::semi)) {
Nico Weber7b837f52016-01-28 19:25:00 +00003972 RecordDecl *AnonRecord = nullptr;
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003973 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00003974 DS, AnonRecord);
3975 assert(!AnonRecord && "Did not expect anonymous struct or union here");
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003976 DS.complete(TheDecl);
Steve Naroff97170802007-08-20 22:28:22 +00003977 return;
3978 }
3979
3980 // Read struct-declarators until we find the semicolon.
John McCallcfefb6d2009-11-03 02:38:08 +00003981 bool FirstDeclarator = true;
Richard Smith8d06f422012-01-12 23:53:29 +00003982 SourceLocation CommaLoc;
Steve Naroff97170802007-08-20 22:28:22 +00003983 while (1) {
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003984 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
Richard Smith8d06f422012-01-12 23:53:29 +00003985 DeclaratorInfo.D.setCommaLoc(CommaLoc);
John McCallcfefb6d2009-11-03 02:38:08 +00003986
Bill Wendling44426052012-12-20 19:22:21 +00003987 // Attributes are only allowed here on successive declarators.
John McCall53fa7142010-12-24 02:08:15 +00003988 if (!FirstDeclarator)
3989 MaybeParseGNUAttributes(DeclaratorInfo.D);
Mike Stump11289f42009-09-09 15:08:12 +00003990
Steve Naroff97170802007-08-20 22:28:22 +00003991 /// struct-declarator: declarator
3992 /// struct-declarator: declarator[opt] ':' constant-expression
Chris Lattner17c3b1f2009-12-10 01:59:24 +00003993 if (Tok.isNot(tok::colon)) {
3994 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3995 ColonProtectionRAIIObject X(*this);
Chris Lattnera12405b2008-04-10 06:46:29 +00003996 ParseDeclarator(DeclaratorInfo.D);
Richard Smith3d1a94c2014-08-12 00:22:39 +00003997 } else
3998 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003999
Alp Toker8fbec672013-12-17 23:29:36 +00004000 if (TryConsumeToken(tok::colon)) {
John McCalldadc5752010-08-24 06:29:42 +00004001 ExprResult Res(ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004002 if (Res.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00004003 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner32295d32008-04-10 06:15:14 +00004004 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004005 DeclaratorInfo.BitfieldSize = Res.get();
Steve Naroff97170802007-08-20 22:28:22 +00004006 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004007
Steve Naroff97170802007-08-20 22:28:22 +00004008 // If attributes exist after the declarator, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004009 MaybeParseGNUAttributes(DeclaratorInfo.D);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004010
John McCallcfefb6d2009-11-03 02:38:08 +00004011 // We're done with this declarator; invoke the callback.
Benjamin Kramera39beb92014-09-03 11:06:10 +00004012 FieldsCallback(DeclaratorInfo);
John McCallcfefb6d2009-11-03 02:38:08 +00004013
Steve Naroff97170802007-08-20 22:28:22 +00004014 // If we don't have a comma, it is either the end of the list (a ';')
4015 // or an error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00004016 if (!TryConsumeToken(tok::comma, CommaLoc))
Chris Lattner70ae4912007-10-29 04:42:53 +00004017 return;
Sebastian Redlf6591ca2009-02-09 18:23:29 +00004018
John McCallcfefb6d2009-11-03 02:38:08 +00004019 FirstDeclarator = false;
Steve Naroff97170802007-08-20 22:28:22 +00004020 }
Steve Naroff97170802007-08-20 22:28:22 +00004021}
4022
4023/// ParseStructUnionBody
4024/// struct-contents:
4025/// struct-declaration-list
4026/// [EXT] empty
4027/// [GNU] "struct-declaration-list" without terminatoring ';'
4028/// struct-declaration-list:
4029/// struct-declaration
4030/// struct-declaration-list struct-declaration
Chris Lattner535b8302008-06-21 19:39:06 +00004031/// [OBC] '@' 'defs' '(' class-name ')'
Steve Naroff97170802007-08-20 22:28:22 +00004032///
Chris Lattner1300fb92007-01-23 23:42:53 +00004033void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00004034 unsigned TagType, Decl *TagDecl) {
Jordan Rose1e879d82018-03-23 00:07:18 +00004035 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00004036 "parsing struct/union body");
Andy Gibbs22e140b2013-04-03 09:31:19 +00004037 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
Mike Stump11289f42009-09-09 15:08:12 +00004038
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004039 BalancedDelimiterTracker T(*this, tok::l_brace);
4040 if (T.consumeOpen())
4041 return;
Mike Stump11289f42009-09-09 15:08:12 +00004042
Douglas Gregor658b9552009-01-09 22:42:13 +00004043 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004044 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004045
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004046 SmallVector<Decl *, 32> FieldDecls;
Chris Lattnera12405b2008-04-10 06:46:29 +00004047
Chris Lattner7b9ace62007-01-23 20:11:08 +00004048 // While we still have something to read, read the declarations in the struct.
Richard Smith752ada82015-11-17 23:32:01 +00004049 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4050 Tok.isNot(tok::eof)) {
Chris Lattner90a26b02007-01-23 04:38:16 +00004051 // Each iteration of this loop reads one struct-declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004052
Chris Lattner736ed5d2007-06-09 05:59:07 +00004053 // Check for extraneous top-level semicolon.
Chris Lattner76c72282007-10-09 17:33:22 +00004054 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004055 ConsumeExtraSemi(InsideStruct, TagType);
Chris Lattner36e46a22007-06-09 05:49:55 +00004056 continue;
4057 }
Chris Lattnera12405b2008-04-10 06:46:29 +00004058
Andy Gibbsc804e082013-04-03 09:46:04 +00004059 // Parse _Static_assert declaration.
4060 if (Tok.is(tok::kw__Static_assert)) {
4061 SourceLocation DeclEnd;
4062 ParseStaticAssertDeclaration(DeclEnd);
4063 continue;
4064 }
4065
Argyrios Kyrtzidis71c12fb2013-04-18 01:42:35 +00004066 if (Tok.is(tok::annot_pragma_pack)) {
4067 HandlePragmaPack();
4068 continue;
4069 }
4070
4071 if (Tok.is(tok::annot_pragma_align)) {
4072 HandlePragmaAlign();
4073 continue;
4074 }
4075
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004076 if (Tok.is(tok::annot_pragma_openmp)) {
Alexey Bataev587e1de2016-03-30 10:43:55 +00004077 // Result can be ignored, because it must be always empty.
4078 AccessSpecifier AS = AS_none;
4079 ParsedAttributesWithRange Attrs(AttrFactory);
4080 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004081 continue;
4082 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004083
John McCallcfefb6d2009-11-03 02:38:08 +00004084 if (!Tok.is(tok::at)) {
Benjamin Kramera39beb92014-09-03 11:06:10 +00004085 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4086 // Install the declarator into the current TagDecl.
4087 Decl *Field =
4088 Actions.ActOnField(getCurScope(), TagDecl,
4089 FD.D.getDeclSpec().getSourceRange().getBegin(),
4090 FD.D, FD.BitfieldSize);
4091 FieldDecls.push_back(Field);
4092 FD.complete(Field);
4093 };
John McCallcfefb6d2009-11-03 02:38:08 +00004094
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004095 // Parse all the comma separated declarators.
4096 ParsingDeclSpec DS(*this);
Benjamin Kramera39beb92014-09-03 11:06:10 +00004097 ParseStructDeclaration(DS, CFieldCallback);
Chris Lattner535b8302008-06-21 19:39:06 +00004098 } else { // Handle @defs
4099 ConsumeToken();
4100 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4101 Diag(Tok, diag::err_unexpected_at);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004102 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004103 continue;
4104 }
4105 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004106 ExpectAndConsume(tok::l_paren);
Chris Lattner535b8302008-06-21 19:39:06 +00004107 if (!Tok.is(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004108 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004109 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004110 continue;
4111 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004112 SmallVector<Decl *, 16> Fields;
Douglas Gregor0be31a22010-07-02 17:43:08 +00004113 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004114 Tok.getIdentifierInfo(), Fields);
Chris Lattner535b8302008-06-21 19:39:06 +00004115 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4116 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004117 ExpectAndConsume(tok::r_paren);
Mike Stump11289f42009-09-09 15:08:12 +00004118 }
Chris Lattner736ed5d2007-06-09 05:59:07 +00004119
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004120 if (TryConsumeToken(tok::semi))
4121 continue;
4122
4123 if (Tok.is(tok::r_brace)) {
Chris Lattner245c5332010-02-02 00:37:27 +00004124 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
Chris Lattner0c7e82d2007-06-09 05:54:40 +00004125 break;
Chris Lattner90a26b02007-01-23 04:38:16 +00004126 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004127
4128 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4129 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4130 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4131 // If we stopped at a ';', eat it.
4132 TryConsumeToken(tok::semi);
Chris Lattner90a26b02007-01-23 04:38:16 +00004133 }
Mike Stump11289f42009-09-09 15:08:12 +00004134
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004135 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +00004136
John McCall084e83d2011-03-24 11:26:52 +00004137 ParsedAttributes attrs(AttrFactory);
Chris Lattner90a26b02007-01-23 04:38:16 +00004138 // If attributes exist after struct contents, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004139 MaybeParseGNUAttributes(attrs);
Daniel Dunbar15619c72008-10-03 02:03:53 +00004140
Erich Keanec480f302018-07-12 21:09:05 +00004141 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4142 T.getOpenLocation(), T.getCloseLocation(), attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004143 StructScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004144 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
Chris Lattner90a26b02007-01-23 04:38:16 +00004145}
4146
Chris Lattner3b561a32006-08-13 00:12:11 +00004147/// ParseEnumSpecifier
Chris Lattner1890ac82006-08-13 01:16:23 +00004148/// enum-specifier: [C99 6.7.2.2]
Chris Lattner3b561a32006-08-13 00:12:11 +00004149/// 'enum' identifier[opt] '{' enumerator-list '}'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004150///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
Chris Lattnere37e2332006-08-15 04:50:22 +00004151/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4152/// '}' attributes[opt]
Aaron Ballman9ecff022012-03-01 04:09:28 +00004153/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4154/// '}'
Chris Lattner3b561a32006-08-13 00:12:11 +00004155/// 'enum' identifier
Chris Lattnere37e2332006-08-15 04:50:22 +00004156/// [GNU] 'enum' attributes[opt] identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004157///
Richard Smith7d137e32012-03-23 03:33:32 +00004158/// [C++11] enum-head '{' enumerator-list[opt] '}'
4159/// [C++11] enum-head '{' enumerator-list ',' '}'
Douglas Gregor0bf31402010-10-08 23:50:27 +00004160///
Richard Smith7d137e32012-03-23 03:33:32 +00004161/// enum-head: [C++11]
4162/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4163/// enum-key attribute-specifier-seq[opt] nested-name-specifier
4164/// identifier enum-base[opt]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004165///
Richard Smith7d137e32012-03-23 03:33:32 +00004166/// enum-key: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004167/// 'enum'
4168/// 'enum' 'class'
4169/// 'enum' 'struct'
4170///
Richard Smith7d137e32012-03-23 03:33:32 +00004171/// enum-base: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004172/// ':' type-specifier-seq
4173///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004174/// [C++] elaborated-type-specifier:
4175/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4176///
Chris Lattnerffaa0e62009-04-12 21:49:30 +00004177void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregordc70c3a2010-03-02 17:53:14 +00004178 const ParsedTemplateInfo &TemplateInfo,
Richard Smithc5b05522012-03-12 07:56:15 +00004179 AccessSpecifier AS, DeclSpecContext DSC) {
Chris Lattnerffbc2712007-01-25 06:05:38 +00004180 // Parse the tag portion of this.
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004181 if (Tok.is(tok::code_completion)) {
4182 // Code completion for an enum name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004183 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00004184 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004185 }
John McCallcb432fa2011-07-06 05:58:41 +00004186
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004187 // If attributes exist after tag, parse them.
4188 ParsedAttributesWithRange attrs(AttrFactory);
4189 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004190 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004191 MaybeParseMicrosoftDeclSpecs(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004192
Richard Smith0f8ee222012-01-10 01:33:14 +00004193 SourceLocation ScopedEnumKWLoc;
John McCallcb432fa2011-07-06 05:58:41 +00004194 bool IsScopedUsingClassTag = false;
4195
John McCallbeae29a2012-06-23 22:30:04 +00004196 // In C++11, recognize 'enum class' and 'enum struct'.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004197 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
Richard Trieud0d87b52013-04-23 02:47:36 +00004198 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4199 : diag::ext_scoped_enum);
John McCallcb432fa2011-07-06 05:58:41 +00004200 IsScopedUsingClassTag = Tok.is(tok::kw_class);
Richard Smith0f8ee222012-01-10 01:33:14 +00004201 ScopedEnumKWLoc = ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004202
Bill Wendling44426052012-12-20 19:22:21 +00004203 // Attributes are not allowed between these keywords. Diagnose,
John McCallbeae29a2012-06-23 22:30:04 +00004204 // but then just treat them like they appeared in the right place.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004205 ProhibitAttributes(attrs);
John McCallbeae29a2012-06-23 22:30:04 +00004206
4207 // They are allowed afterwards, though.
4208 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004209 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004210 MaybeParseMicrosoftDeclSpecs(attrs);
John McCallcb432fa2011-07-06 05:58:41 +00004211 }
Richard Smith7d137e32012-03-23 03:33:32 +00004212
John McCall6347b682012-05-07 06:16:58 +00004213 // C++11 [temp.explicit]p12:
4214 // The usual access controls do not apply to names used to specify
4215 // explicit instantiations.
4216 // We extend this to also cover explicit specializations. Note that
4217 // we don't suppress if this turns out to be an elaborated type
4218 // specifier.
4219 bool shouldDelayDiagsInTag =
4220 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4221 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4222 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Richard Smith7d137e32012-03-23 03:33:32 +00004223
Richard Smithbfdb1082012-03-12 08:56:40 +00004224 // Enum definitions should not be parsed in a trailing-return-type.
Faisal Vali7db85c52017-12-31 00:06:40 +00004225 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
Richard Smithbfdb1082012-03-12 08:56:40 +00004226
Abramo Bagnarad7548482010-05-19 21:37:53 +00004227 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004228 if (getLangOpts().CPlusPlus) {
John McCallcb432fa2011-07-06 05:58:41 +00004229 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4230 // if a fixed underlying type is allowed.
Erik Pilkington6f11db12018-09-28 20:24:58 +00004231 ColonProtectionRAIIObject X(*this, AllowDeclaration);
Chad Rosierc1183952012-06-26 22:30:43 +00004232
Nico Webercfaa4cd2015-02-15 07:26:13 +00004233 CXXScopeSpec Spec;
David Blaikieefdccaa2016-01-15 23:43:34 +00004234 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
Richard Smith1d4b2e12013-04-01 21:43:41 +00004235 /*EnteringContext=*/true))
John McCall1f476a12010-02-26 08:45:28 +00004236 return;
4237
Nico Webercfaa4cd2015-02-15 07:26:13 +00004238 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004239 Diag(Tok, diag::err_expected) << tok::identifier;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004240 if (Tok.isNot(tok::l_brace)) {
4241 // Has no name and is not a definition.
4242 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004243 SkipUntil(tok::comma, StopAtSemi);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004244 return;
4245 }
4246 }
Nico Webercfaa4cd2015-02-15 07:26:13 +00004247
4248 SS = Spec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004249 }
Mike Stump11289f42009-09-09 15:08:12 +00004250
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004251 // Must have either 'enum name' or 'enum {...}'.
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004252 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
Erik Pilkington6f11db12018-09-28 20:24:58 +00004253 !(AllowDeclaration && Tok.is(tok::colon))) {
Alp Tokerec543272013-12-24 09:48:30 +00004254 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
Mike Stump11289f42009-09-09 15:08:12 +00004255
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004256 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004257 SkipUntil(tok::comma, StopAtSemi);
Chris Lattner3b561a32006-08-13 00:12:11 +00004258 return;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004259 }
Mike Stump11289f42009-09-09 15:08:12 +00004260
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004261 // If an identifier is present, consume and remember it.
Craig Topper161e4db2014-05-21 06:02:52 +00004262 IdentifierInfo *Name = nullptr;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004263 SourceLocation NameLoc;
4264 if (Tok.is(tok::identifier)) {
4265 Name = Tok.getIdentifierInfo();
4266 NameLoc = ConsumeToken();
4267 }
Mike Stump11289f42009-09-09 15:08:12 +00004268
Richard Smith0f8ee222012-01-10 01:33:14 +00004269 if (!Name && ScopedEnumKWLoc.isValid()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00004270 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4271 // declaration of a scoped enumeration.
4272 Diag(Tok, diag::err_scoped_enum_missing_identifier);
Richard Smith0f8ee222012-01-10 01:33:14 +00004273 ScopedEnumKWLoc = SourceLocation();
Abramo Bagnara0e05e242010-12-03 18:54:17 +00004274 IsScopedUsingClassTag = false;
Douglas Gregor0bf31402010-10-08 23:50:27 +00004275 }
4276
John McCall6347b682012-05-07 06:16:58 +00004277 // Okay, end the suppression area. We'll decide whether to emit the
4278 // diagnostics in a second.
4279 if (shouldDelayDiagsInTag)
4280 diagsFromTag.done();
Richard Smith7d137e32012-03-23 03:33:32 +00004281
Douglas Gregor0bf31402010-10-08 23:50:27 +00004282 TypeResult BaseType;
4283
Douglas Gregord1f69f62010-12-01 17:42:47 +00004284 // Parse the fixed underlying type.
Richard Smith200f47c2012-07-02 19:14:01 +00004285 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
Erik Pilkington6f11db12018-09-28 20:24:58 +00004286 if (AllowDeclaration && Tok.is(tok::colon)) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004287 bool PossibleBitfield = false;
Richard Smith200f47c2012-07-02 19:14:01 +00004288 if (CanBeBitfield) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004289 // If we're in class scope, this can either be an enum declaration with
4290 // an underlying type, or a declaration of a bitfield member. We try to
4291 // use a simple disambiguation scheme first to catch the common cases
Chad Rosierc1183952012-06-26 22:30:43 +00004292 // (integer literal, sizeof); if it's still ambiguous, we then consider
4293 // anything that's a simple-type-specifier followed by '(' as an
4294 // expression. This suffices because function types are not valid
Douglas Gregord1f69f62010-12-01 17:42:47 +00004295 // underlying types anyway.
Faisal Valid143a0c2017-04-01 21:30:49 +00004296 EnterExpressionEvaluationContext Unevaluated(
4297 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregord1f69f62010-12-01 17:42:47 +00004298 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
Chad Rosierc1183952012-06-26 22:30:43 +00004299 // If the next token starts an expression, we know we're parsing a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004300 // bit-field. This is the common case.
Richard Smithee390432014-05-16 01:56:53 +00004301 if (TPR == TPResult::True)
Douglas Gregord1f69f62010-12-01 17:42:47 +00004302 PossibleBitfield = true;
4303 // If the next token starts a type-specifier-seq, it may be either a
4304 // a fixed underlying type or the start of a function-style cast in C++;
Chad Rosierc1183952012-06-26 22:30:43 +00004305 // lookahead one more token to see if it's obvious that we have a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004306 // fixed underlying type.
Richard Smithee390432014-05-16 01:56:53 +00004307 else if (TPR == TPResult::False &&
Douglas Gregord1f69f62010-12-01 17:42:47 +00004308 GetLookAheadToken(2).getKind() == tok::semi) {
4309 // Consume the ':'.
4310 ConsumeToken();
4311 } else {
4312 // We have the start of a type-specifier-seq, so we have to perform
4313 // tentative parsing to determine whether we have an expression or a
4314 // type.
4315 TentativeParsingAction TPA(*this);
4316
4317 // Consume the ':'.
4318 ConsumeToken();
Richard Smith1e3b0f02012-02-23 01:36:12 +00004319
4320 // If we see a type specifier followed by an open-brace, we have an
4321 // ambiguity between an underlying type and a C++11 braced
4322 // function-style cast. Resolve this by always treating it as an
4323 // underlying type.
4324 // FIXME: The standard is not entirely clear on how to disambiguate in
4325 // this case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004326 if ((getLangOpts().CPlusPlus &&
Richard Smithee390432014-05-16 01:56:53 +00004327 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00004328 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004329 // We'll parse this as a bitfield later.
4330 PossibleBitfield = true;
4331 TPA.Revert();
4332 } else {
4333 // We have a type-specifier-seq.
4334 TPA.Commit();
4335 }
4336 }
4337 } else {
4338 // Consume the ':'.
4339 ConsumeToken();
4340 }
4341
4342 if (!PossibleBitfield) {
4343 SourceRange Range;
4344 BaseType = ParseTypeName(&Range);
Chad Rosierc1183952012-06-26 22:30:43 +00004345
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004346 if (!getLangOpts().ObjC) {
Erik Pilkington6f11db12018-09-28 20:24:58 +00004347 if (getLangOpts().CPlusPlus11)
4348 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4349 else if (getLangOpts().CPlusPlus)
4350 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4351 else if (getLangOpts().MicrosoftExt)
4352 Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004353 else
Erik Pilkington6f11db12018-09-28 20:24:58 +00004354 Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004355 }
Douglas Gregord1f69f62010-12-01 17:42:47 +00004356 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004357 }
4358
Richard Smith0f8ee222012-01-10 01:33:14 +00004359 // There are four options here. If we have 'friend enum foo;' then this is a
4360 // friend declaration, and cannot have an accompanying definition. If we have
4361 // 'enum foo;', then this is a forward declaration. If we have
4362 // 'enum foo {...' then this is a definition. Otherwise we have something
4363 // like 'enum foo xyz', a reference.
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004364 //
4365 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4366 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4367 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4368 //
John McCallfaf5fb42010-08-26 23:41:50 +00004369 Sema::TagUseKind TUK;
John McCall6347b682012-05-07 06:16:58 +00004370 if (!AllowDeclaration) {
Richard Smithbfdb1082012-03-12 08:56:40 +00004371 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004372 } else if (Tok.is(tok::l_brace)) {
4373 if (DS.isFriendSpecified()) {
4374 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4375 << SourceRange(DS.getFriendSpecLoc());
4376 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004377 SkipUntil(tok::r_brace, StopAtSemi);
John McCall6347b682012-05-07 06:16:58 +00004378 TUK = Sema::TUK_Friend;
4379 } else {
4380 TUK = Sema::TUK_Definition;
4381 }
Richard Smith649c7b062014-01-08 00:56:48 +00004382 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00004383 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00004384 (Tok.isAtStartOfLine() &&
4385 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
Richard Smith369b9f92012-06-25 21:37:02 +00004386 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4387 if (Tok.isNot(tok::semi)) {
4388 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00004389 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004390 PP.EnterToken(Tok);
4391 Tok.setKind(tok::semi);
4392 }
John McCall6347b682012-05-07 06:16:58 +00004393 } else {
John McCallfaf5fb42010-08-26 23:41:50 +00004394 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004395 }
4396
4397 // If this is an elaborated type specifier, and we delayed
4398 // diagnostics before, just merge them into the current pool.
4399 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4400 diagsFromTag.redelay();
4401 }
Richard Smith7d137e32012-03-23 03:33:32 +00004402
4403 MultiTemplateParamsArg TParams;
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004404 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
John McCallfaf5fb42010-08-26 23:41:50 +00004405 TUK != Sema::TUK_Reference) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004406 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
Richard Smith7d137e32012-03-23 03:33:32 +00004407 // Skip the rest of this declarator, up until the comma or semicolon.
4408 Diag(Tok, diag::err_enum_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004409 SkipUntil(tok::comma, StopAtSemi);
Richard Smith7d137e32012-03-23 03:33:32 +00004410 return;
4411 }
4412
4413 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4414 // Enumerations can't be explicitly instantiated.
4415 DS.SetTypeSpecError();
4416 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4417 return;
4418 }
4419
4420 assert(TemplateInfo.TemplateParams && "no template parameters");
4421 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4422 TemplateInfo.TemplateParams->size());
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004423 }
Chad Rosierc1183952012-06-26 22:30:43 +00004424
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004425 if (TUK == Sema::TUK_Reference)
4426 ProhibitAttributes(attrs);
Richard Smith7d137e32012-03-23 03:33:32 +00004427
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004428 if (!Name && TUK != Sema::TUK_Definition) {
4429 Diag(Tok, diag::err_enumerator_unnamed_no_def);
Richard Smith7d137e32012-03-23 03:33:32 +00004430
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004431 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004432 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004433 return;
4434 }
Richard Smith7d137e32012-03-23 03:33:32 +00004435
Nico Weber32a0fc72016-09-03 03:01:32 +00004436 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00004437
Richard Smithd9ba2242015-05-07 03:54:19 +00004438 Sema::SkipBodyInfo SkipBody;
4439 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4440 NextToken().is(tok::identifier))
4441 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4442 NextToken().getIdentifierInfo(),
4443 NextToken().getLocation());
4444
Douglas Gregord6ab8742009-05-28 23:31:59 +00004445 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004446 bool IsDependent = false;
Craig Topper161e4db2014-05-21 06:02:52 +00004447 const char *PrevSpec = nullptr;
Douglas Gregorba41d012010-04-24 16:38:41 +00004448 unsigned DiagID;
Faisal Vali7db85c52017-12-31 00:06:40 +00004449 Decl *TagDecl = Actions.ActOnTag(
4450 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
Erich Keanec480f302018-07-12 21:09:05 +00004451 attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4452 ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
Faisal Vali7db85c52017-12-31 00:06:40 +00004453 DSC == DeclSpecContext::DSC_type_specifier,
4454 DSC == DeclSpecContext::DSC_template_param ||
4455 DSC == DeclSpecContext::DSC_template_type_arg,
4456 &SkipBody);
Richard Smithd9ba2242015-05-07 03:54:19 +00004457
4458 if (SkipBody.ShouldSkip) {
4459 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4460
4461 BalancedDelimiterTracker T(*this, tok::l_brace);
4462 T.consumeOpen();
4463 T.skipToEnd();
4464
4465 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4466 NameLoc.isValid() ? NameLoc : StartLoc,
4467 PrevSpec, DiagID, TagDecl, Owned,
4468 Actions.getASTContext().getPrintingPolicy()))
4469 Diag(StartLoc, DiagID) << PrevSpec;
4470 return;
4471 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004472
Douglas Gregorba41d012010-04-24 16:38:41 +00004473 if (IsDependent) {
Chad Rosierc1183952012-06-26 22:30:43 +00004474 // This enum has a dependent nested-name-specifier. Handle it as a
Douglas Gregorba41d012010-04-24 16:38:41 +00004475 // dependent tag.
4476 if (!Name) {
4477 DS.SetTypeSpecError();
4478 Diag(Tok, diag::err_expected_type_name_after_typename);
4479 return;
4480 }
Chad Rosierc1183952012-06-26 22:30:43 +00004481
Nico Weber83ea0122014-05-03 21:57:40 +00004482 TypeResult Type = Actions.ActOnDependentTag(
4483 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
Douglas Gregorba41d012010-04-24 16:38:41 +00004484 if (Type.isInvalid()) {
4485 DS.SetTypeSpecError();
4486 return;
4487 }
Chad Rosierc1183952012-06-26 22:30:43 +00004488
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004489 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4490 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004491 PrevSpec, DiagID, Type.get(),
4492 Actions.getASTContext().getPrintingPolicy()))
Douglas Gregorba41d012010-04-24 16:38:41 +00004493 Diag(StartLoc, DiagID) << PrevSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00004494
Douglas Gregorba41d012010-04-24 16:38:41 +00004495 return;
4496 }
Mike Stump11289f42009-09-09 15:08:12 +00004497
John McCall48871652010-08-21 09:40:31 +00004498 if (!TagDecl) {
Chad Rosierc1183952012-06-26 22:30:43 +00004499 // The action failed to produce an enumeration tag. If this is a
Douglas Gregorba41d012010-04-24 16:38:41 +00004500 // definition, consume the entire definition.
Richard Smithbfdb1082012-03-12 08:56:40 +00004501 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
Douglas Gregorba41d012010-04-24 16:38:41 +00004502 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004503 SkipUntil(tok::r_brace, StopAtSemi);
Douglas Gregorba41d012010-04-24 16:38:41 +00004504 }
Chad Rosierc1183952012-06-26 22:30:43 +00004505
Douglas Gregorba41d012010-04-24 16:38:41 +00004506 DS.SetTypeSpecError();
4507 return;
4508 }
Richard Smith0f8ee222012-01-10 01:33:14 +00004509
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004510 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4511 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4512 ParseEnumBody(StartLoc, D);
4513 if (SkipBody.CheckSameAsPrevious &&
4514 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4515 DS.SetTypeSpecError();
4516 return;
4517 }
4518 }
Mike Stump11289f42009-09-09 15:08:12 +00004519
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004520 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4521 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004522 PrevSpec, DiagID, TagDecl, Owned,
4523 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00004524 Diag(StartLoc, DiagID) << PrevSpec;
Chris Lattner3b561a32006-08-13 00:12:11 +00004525}
4526
Chris Lattnerc1915e22007-01-25 07:29:02 +00004527/// ParseEnumBody - Parse a {} enclosed enumerator-list.
4528/// enumerator-list:
4529/// enumerator
4530/// enumerator-list ',' enumerator
4531/// enumerator:
Aaron Ballman730476b2014-11-08 15:33:35 +00004532/// enumeration-constant attributes[opt]
4533/// enumeration-constant attributes[opt] '=' constant-expression
Chris Lattnerc1915e22007-01-25 07:29:02 +00004534/// enumeration-constant:
4535/// identifier
4536///
John McCall48871652010-08-21 09:40:31 +00004537void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004538 // Enter the scope of the enum body and start the definition.
Hans Wennborgfe781452014-06-17 00:00:18 +00004539 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004540 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
Douglas Gregor07665a62009-01-05 19:45:36 +00004541
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004542 BalancedDelimiterTracker T(*this, tok::l_brace);
4543 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00004544
Chris Lattner37256fb2007-08-27 17:24:30 +00004545 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
David Blaikiebbafb8a2012-03-11 07:00:24 +00004546 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
Richard Smithf8812672016-12-02 22:38:31 +00004547 Diag(Tok, diag::err_empty_enum);
Mike Stump11289f42009-09-09 15:08:12 +00004548
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004549 SmallVector<Decl *, 32> EnumConstantDecls;
Jordan Rose60ac3162015-04-30 17:20:30 +00004550 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
Chris Lattnerc1915e22007-01-25 07:29:02 +00004551
Craig Topper161e4db2014-05-21 06:02:52 +00004552 Decl *LastEnumConstDecl = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004553
Chris Lattnerc1915e22007-01-25 07:29:02 +00004554 // Parse the enumerator-list.
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004555 while (Tok.isNot(tok::r_brace)) {
4556 // Parse enumerator. If failed, try skipping till the start of the next
4557 // enumerator definition.
4558 if (Tok.isNot(tok::identifier)) {
4559 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4560 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4561 TryConsumeToken(tok::comma))
4562 continue;
4563 break;
4564 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004565 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4566 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00004567
John McCall811a0f52010-10-22 23:36:17 +00004568 // If attributes exist after the enumerator, parse them.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004569 ParsedAttributesWithRange attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004570 MaybeParseGNUAttributes(attrs);
Aaron Ballman730476b2014-11-08 15:33:35 +00004571 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
Aaron Ballman606093a2017-10-15 15:01:42 +00004572 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4573 if (getLangOpts().CPlusPlus)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004574 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Aaron Ballman606093a2017-10-15 15:01:42 +00004575 ? diag::warn_cxx14_compat_ns_enum_attribute
4576 : diag::ext_ns_enum_attribute)
4577 << 1 /*enumerator*/;
Aaron Ballman730476b2014-11-08 15:33:35 +00004578 ParseCXX11Attributes(attrs);
4579 }
John McCall811a0f52010-10-22 23:36:17 +00004580
Chris Lattnerc1915e22007-01-25 07:29:02 +00004581 SourceLocation EqualLoc;
John McCalldadc5752010-08-24 06:29:42 +00004582 ExprResult AssignedVal;
Jordan Rose60ac3162015-04-30 17:20:30 +00004583 EnumAvailabilityDiags.emplace_back(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00004584
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004585 if (TryConsumeToken(tok::equal, EqualLoc)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004586 AssignedVal = ParseConstantExpression();
4587 if (AssignedVal.isInvalid())
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004588 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
Chris Lattnerc1915e22007-01-25 07:29:02 +00004589 }
Mike Stump11289f42009-09-09 15:08:12 +00004590
Chris Lattnerc1915e22007-01-25 07:29:02 +00004591 // Install the enumerator constant into EnumDecl.
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004592 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
Erich Keanec480f302018-07-12 21:09:05 +00004593 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4594 EqualLoc, AssignedVal.get());
Jordan Rose60ac3162015-04-30 17:20:30 +00004595 EnumAvailabilityDiags.back().done();
Chad Rosierc1183952012-06-26 22:30:43 +00004596
Chris Lattner4ef40012007-06-11 01:28:17 +00004597 EnumConstantDecls.push_back(EnumConstDecl);
4598 LastEnumConstDecl = EnumConstDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004599
Douglas Gregorce66d022010-09-07 14:51:08 +00004600 if (Tok.is(tok::identifier)) {
4601 // We're missing a comma between enumerators.
Richard Smithbdb84f32016-07-22 23:36:59 +00004602 SourceLocation Loc = getEndOfPreviousToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004603 Diag(Loc, diag::err_enumerator_list_missing_comma)
Douglas Gregorce66d022010-09-07 14:51:08 +00004604 << FixItHint::CreateInsertion(Loc, ", ");
4605 continue;
4606 }
Chad Rosierc1183952012-06-26 22:30:43 +00004607
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004608 // Emumerator definition must be finished, only comma or r_brace are
4609 // allowed here.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004610 SourceLocation CommaLoc;
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004611 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4612 if (EqualLoc.isValid())
4613 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4614 << tok::comma;
4615 else
4616 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4617 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4618 if (TryConsumeToken(tok::comma, CommaLoc))
4619 continue;
4620 } else {
4621 break;
4622 }
4623 }
Mike Stump11289f42009-09-09 15:08:12 +00004624
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004625 // If comma is followed by r_brace, emit appropriate warning.
4626 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004627 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
Richard Smith87f5dc52012-07-23 05:45:25 +00004628 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4629 diag::ext_enumerator_list_comma_cxx :
4630 diag::ext_enumerator_list_comma_c)
Richard Smith5d164bc2011-10-15 05:09:34 +00004631 << FixItHint::CreateRemoval(CommaLoc);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004632 else if (getLangOpts().CPlusPlus11)
Richard Smith5d164bc2011-10-15 05:09:34 +00004633 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4634 << FixItHint::CreateRemoval(CommaLoc);
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004635 break;
Richard Smith5d164bc2011-10-15 05:09:34 +00004636 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004637 }
Mike Stump11289f42009-09-09 15:08:12 +00004638
Chris Lattnerc1915e22007-01-25 07:29:02 +00004639 // Eat the }.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004640 T.consumeClose();
Chris Lattnerc1915e22007-01-25 07:29:02 +00004641
Chris Lattnerc1915e22007-01-25 07:29:02 +00004642 // If attributes exist after the identifier list, parse them.
John McCall084e83d2011-03-24 11:26:52 +00004643 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004644 MaybeParseGNUAttributes(attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004645
Erich Keanec480f302018-07-12 21:09:05 +00004646 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4647 getCurScope(), attrs);
Mike Stump11289f42009-09-09 15:08:12 +00004648
Jordan Rose60ac3162015-04-30 17:20:30 +00004649 // Now handle enum constant availability diagnostics.
4650 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4651 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4652 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4653 EnumAvailabilityDiags[i].redelay();
4654 PD.complete(EnumConstantDecls[i]);
4655 }
4656
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004657 EnumScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004658 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
Richard Smith369b9f92012-06-25 21:37:02 +00004659
4660 // The next token must be valid after an enum definition. If not, a ';'
4661 // was probably forgotten.
Richard Smith200f47c2012-07-02 19:14:01 +00004662 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4663 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
Alp Toker383d2c42014-01-01 03:08:43 +00004664 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004665 // Push this token back into the preprocessor and change our current token
4666 // to ';' so that the rest of the code recovers as though there were an
4667 // ';' after the definition.
4668 PP.EnterToken(Tok);
4669 Tok.setKind(tok::semi);
4670 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004671}
Chris Lattner3b561a32006-08-13 00:12:11 +00004672
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004673/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4674/// is definitely a type-specifier. Return false if it isn't part of a type
4675/// specifier or if we're not sure.
4676bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4677 switch (Tok.getKind()) {
4678 default: return false;
4679 // type-specifiers
4680 case tok::kw_short:
4681 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004682 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004683 case tok::kw___int128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004684 case tok::kw_signed:
4685 case tok::kw_unsigned:
4686 case tok::kw__Complex:
4687 case tok::kw__Imaginary:
4688 case tok::kw_void:
4689 case tok::kw_char:
4690 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004691 case tok::kw_char8_t:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004692 case tok::kw_char16_t:
4693 case tok::kw_char32_t:
4694 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004695 case tok::kw_half:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004696 case tok::kw_float:
4697 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004698 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004699 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004700 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004701 case tok::kw___float128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004702 case tok::kw_bool:
4703 case tok::kw__Bool:
4704 case tok::kw__Decimal32:
4705 case tok::kw__Decimal64:
4706 case tok::kw__Decimal128:
4707 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004708#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004709#include "clang/Basic/OpenCLImageTypes.def"
Chad Rosierc1183952012-06-26 22:30:43 +00004710
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004711 // struct-or-union-specifier (C99) or class-specifier (C++)
4712 case tok::kw_class:
4713 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004714 case tok::kw___interface:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004715 case tok::kw_union:
4716 // enum-specifier
4717 case tok::kw_enum:
Chad Rosierc1183952012-06-26 22:30:43 +00004718
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004719 // typedef-name
4720 case tok::annot_typename:
4721 return true;
4722 }
4723}
4724
Steve Naroff69e8f9e2008-02-11 23:15:56 +00004725/// isTypeSpecifierQualifier - Return true if the current token could be the
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004726/// start of a specifier-qualifier-list.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004727bool Parser::isTypeSpecifierQualifier() {
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004728 switch (Tok.getKind()) {
4729 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004730
Chris Lattner020bab92009-01-04 23:41:41 +00004731 case tok::identifier: // foo::bar
John Thompson22334602010-02-05 00:12:22 +00004732 if (TryAltiVecVectorToken())
4733 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004734 LLVM_FALLTHROUGH;
Douglas Gregor333489b2009-03-27 23:10:48 +00004735 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004736 // Annotate typenames and C++ scope specifiers. If we get one, just
4737 // recurse to handle whatever we get.
4738 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004739 return true;
4740 if (Tok.is(tok::identifier))
4741 return false;
4742 return isTypeSpecifierQualifier();
Douglas Gregor333489b2009-03-27 23:10:48 +00004743
Chris Lattner020bab92009-01-04 23:41:41 +00004744 case tok::coloncolon: // ::foo::bar
4745 if (NextToken().is(tok::kw_new) || // ::new
4746 NextToken().is(tok::kw_delete)) // ::delete
4747 return false;
4748
Chris Lattner020bab92009-01-04 23:41:41 +00004749 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004750 return true;
4751 return isTypeSpecifierQualifier();
Mike Stump11289f42009-09-09 15:08:12 +00004752
Chris Lattnere37e2332006-08-15 04:50:22 +00004753 // GNU attributes support.
4754 case tok::kw___attribute:
Steve Naroffad373bd2007-07-31 12:34:36 +00004755 // GNU typeof support.
4756 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004757
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004758 // type-specifiers
4759 case tok::kw_short:
4760 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004761 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004762 case tok::kw___int128:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004763 case tok::kw_signed:
4764 case tok::kw_unsigned:
4765 case tok::kw__Complex:
4766 case tok::kw__Imaginary:
4767 case tok::kw_void:
4768 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004769 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004770 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004771 case tok::kw_char16_t:
4772 case tok::kw_char32_t:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004773 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004774 case tok::kw_half:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004775 case tok::kw_float:
4776 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004777 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004778 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004779 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004780 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004781 case tok::kw_bool:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004782 case tok::kw__Bool:
4783 case tok::kw__Decimal32:
4784 case tok::kw__Decimal64:
4785 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004786 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004787#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004788#include "clang/Basic/OpenCLImageTypes.def"
Mike Stump11289f42009-09-09 15:08:12 +00004789
Chris Lattner861a2262008-04-13 18:59:07 +00004790 // struct-or-union-specifier (C99) or class-specifier (C++)
4791 case tok::kw_class:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004792 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004793 case tok::kw___interface:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004794 case tok::kw_union:
4795 // enum-specifier
4796 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004797
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004798 // type-qualifier
4799 case tok::kw_const:
4800 case tok::kw_volatile:
4801 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004802 case tok::kw__Sat:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004803
John McCallea0a39e2012-11-14 00:49:39 +00004804 // Debugger support.
4805 case tok::kw___unknown_anytype:
4806
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004807 // typedef-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00004808 case tok::annot_typename:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004809 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004810
Chris Lattner409bf7d2008-10-20 00:25:30 +00004811 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4812 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004813 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00004814
Steve Naroff44ac7772008-12-25 14:16:32 +00004815 case tok::kw___cdecl:
4816 case tok::kw___stdcall:
4817 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004818 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004819 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004820 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004821 case tok::kw___w64:
4822 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004823 case tok::kw___ptr32:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004824 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004825 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004826
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004827 case tok::kw__Nonnull:
4828 case tok::kw__Nullable:
4829 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004830
Douglas Gregorab209d82015-07-07 03:58:42 +00004831 case tok::kw___kindof:
4832
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004833 case tok::kw___private:
4834 case tok::kw___local:
4835 case tok::kw___global:
4836 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004837 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004838 case tok::kw___read_only:
4839 case tok::kw___read_write:
4840 case tok::kw___write_only:
Eli Friedman53339e02009-06-08 23:27:34 +00004841 return true;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004842
Anastasia Stulova314fab62019-03-28 11:47:14 +00004843 case tok::kw_private:
4844 return getLangOpts().OpenCL;
4845
Richard Smith8e1ac332013-03-28 01:55:44 +00004846 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004847 case tok::kw__Atomic:
4848 return true;
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004849 }
4850}
4851
Chris Lattneracd58a32006-08-06 17:24:14 +00004852/// isDeclarationSpecifier() - Return true if the current token is part of a
4853/// declaration specifier.
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004854///
4855/// \param DisambiguatingWithExpression True to indicate that the purpose of
4856/// this check is to disambiguate between an expression and a declaration.
4857bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
Chris Lattneracd58a32006-08-06 17:24:14 +00004858 switch (Tok.getKind()) {
4859 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004860
Xiuli Pan9c14e282016-01-09 12:53:17 +00004861 case tok::kw_pipe:
4862 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4863
Chris Lattner020bab92009-01-04 23:41:41 +00004864 case tok::identifier: // foo::bar
Steve Naroff9527bbf2009-03-09 21:12:44 +00004865 // Unfortunate hack to support "Class.factoryMethod" notation.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004866 if (getLangOpts().ObjC && NextToken().is(tok::period))
Steve Naroff9527bbf2009-03-09 21:12:44 +00004867 return false;
John Thompson22334602010-02-05 00:12:22 +00004868 if (TryAltiVecVectorToken())
4869 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004870 LLVM_FALLTHROUGH;
David Blaikie15a430a2011-12-04 05:04:18 +00004871 case tok::kw_decltype: // decltype(T())::type
Douglas Gregor333489b2009-03-27 23:10:48 +00004872 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004873 // Annotate typenames and C++ scope specifiers. If we get one, just
4874 // recurse to handle whatever we get.
4875 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004876 return true;
4877 if (Tok.is(tok::identifier))
4878 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004879
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004880 // If we're in Objective-C and we have an Objective-C class type followed
Chad Rosierc1183952012-06-26 22:30:43 +00004881 // by an identifier and then either ':' or ']', in a place where an
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004882 // expression is permitted, then this is probably a class message send
4883 // missing the initial '['. In this case, we won't consider this to be
4884 // the start of a declaration.
Chad Rosierc1183952012-06-26 22:30:43 +00004885 if (DisambiguatingWithExpression &&
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004886 isStartOfObjCClassMessageMissingOpenBracket())
4887 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004888
John McCall1f476a12010-02-26 08:45:28 +00004889 return isDeclarationSpecifier();
4890
Chris Lattner020bab92009-01-04 23:41:41 +00004891 case tok::coloncolon: // ::foo::bar
4892 if (NextToken().is(tok::kw_new) || // ::new
4893 NextToken().is(tok::kw_delete)) // ::delete
4894 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004895
Chris Lattner020bab92009-01-04 23:41:41 +00004896 // Annotate typenames and C++ scope specifiers. If we get one, just
4897 // recurse to handle whatever we get.
4898 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004899 return true;
4900 return isDeclarationSpecifier();
Mike Stump11289f42009-09-09 15:08:12 +00004901
Chris Lattneracd58a32006-08-06 17:24:14 +00004902 // storage-class-specifier
4903 case tok::kw_typedef:
4904 case tok::kw_extern:
Steve Naroff2050b0d2007-12-18 00:16:02 +00004905 case tok::kw___private_extern__:
Chris Lattneracd58a32006-08-06 17:24:14 +00004906 case tok::kw_static:
4907 case tok::kw_auto:
Richard Smithe301ba22015-11-11 02:02:15 +00004908 case tok::kw___auto_type:
Chris Lattneracd58a32006-08-06 17:24:14 +00004909 case tok::kw_register:
4910 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00004911 case tok::kw_thread_local:
4912 case tok::kw__Thread_local:
Mike Stump11289f42009-09-09 15:08:12 +00004913
Douglas Gregor26701a42011-09-09 02:06:17 +00004914 // Modules
4915 case tok::kw___module_private__:
Chad Rosierc1183952012-06-26 22:30:43 +00004916
John McCallea0a39e2012-11-14 00:49:39 +00004917 // Debugger support
4918 case tok::kw___unknown_anytype:
4919
Chris Lattneracd58a32006-08-06 17:24:14 +00004920 // type-specifiers
4921 case tok::kw_short:
4922 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004923 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004924 case tok::kw___int128:
Chris Lattneracd58a32006-08-06 17:24:14 +00004925 case tok::kw_signed:
4926 case tok::kw_unsigned:
4927 case tok::kw__Complex:
4928 case tok::kw__Imaginary:
4929 case tok::kw_void:
4930 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004931 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004932 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004933 case tok::kw_char16_t:
4934 case tok::kw_char32_t:
4935
Chris Lattneracd58a32006-08-06 17:24:14 +00004936 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004937 case tok::kw_half:
Chris Lattneracd58a32006-08-06 17:24:14 +00004938 case tok::kw_float:
4939 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004940 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004941 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004942 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004943 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004944 case tok::kw_bool:
Chris Lattneracd58a32006-08-06 17:24:14 +00004945 case tok::kw__Bool:
4946 case tok::kw__Decimal32:
4947 case tok::kw__Decimal64:
4948 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004949 case tok::kw___vector:
Mike Stump11289f42009-09-09 15:08:12 +00004950
Chris Lattner861a2262008-04-13 18:59:07 +00004951 // struct-or-union-specifier (C99) or class-specifier (C++)
4952 case tok::kw_class:
Chris Lattneracd58a32006-08-06 17:24:14 +00004953 case tok::kw_struct:
4954 case tok::kw_union:
Joao Matosdc86f942012-08-31 18:45:21 +00004955 case tok::kw___interface:
Chris Lattneracd58a32006-08-06 17:24:14 +00004956 // enum-specifier
4957 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004958
Chris Lattneracd58a32006-08-06 17:24:14 +00004959 // type-qualifier
4960 case tok::kw_const:
4961 case tok::kw_volatile:
4962 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004963 case tok::kw__Sat:
Steve Naroffad373bd2007-07-31 12:34:36 +00004964
Chris Lattneracd58a32006-08-06 17:24:14 +00004965 // function-specifier
4966 case tok::kw_inline:
Douglas Gregor61956c42008-10-31 09:07:45 +00004967 case tok::kw_virtual:
4968 case tok::kw_explicit:
Richard Smith0015f092013-01-17 22:16:11 +00004969 case tok::kw__Noreturn:
Chris Lattner7b20dc72007-08-09 16:40:21 +00004970
Richard Smith1dba27c2013-01-29 09:02:09 +00004971 // alignment-specifier
4972 case tok::kw__Alignas:
4973
Richard Smithd16fe122012-10-25 00:00:53 +00004974 // friend keyword.
4975 case tok::kw_friend:
4976
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00004977 // static_assert-declaration
4978 case tok::kw__Static_assert:
4979
Chris Lattner599e47e2007-08-09 17:01:07 +00004980 // GNU typeof support.
4981 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004982
Chris Lattner599e47e2007-08-09 17:01:07 +00004983 // GNU attributes.
Chris Lattner7b20dc72007-08-09 16:40:21 +00004984 case tok::kw___attribute:
Mike Stump11289f42009-09-09 15:08:12 +00004985
Richard Smithd16fe122012-10-25 00:00:53 +00004986 // C++11 decltype and constexpr.
David Blaikie15a430a2011-12-04 05:04:18 +00004987 case tok::annot_decltype:
Richard Smithd16fe122012-10-25 00:00:53 +00004988 case tok::kw_constexpr:
Francois Pichete878cb62011-06-19 08:02:06 +00004989
Richard Smith8e1ac332013-03-28 01:55:44 +00004990 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004991 case tok::kw__Atomic:
4992 return true;
4993
Chris Lattner8b2ec162008-07-26 03:38:44 +00004994 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4995 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004996 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00004997
Douglas Gregor19b7acf2011-04-27 05:41:15 +00004998 // typedef-name
4999 case tok::annot_typename:
5000 return !DisambiguatingWithExpression ||
5001 !isStartOfObjCClassMessageMissingOpenBracket();
Chad Rosierc1183952012-06-26 22:30:43 +00005002
Steve Narofff192fab2009-01-06 19:34:12 +00005003 case tok::kw___declspec:
Steve Naroff44ac7772008-12-25 14:16:32 +00005004 case tok::kw___cdecl:
5005 case tok::kw___stdcall:
5006 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005007 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005008 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005009 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00005010 case tok::kw___w64:
Aaron Ballman317a77f2013-05-22 23:25:32 +00005011 case tok::kw___sptr:
5012 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005013 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005014 case tok::kw___ptr32:
Eli Friedman53339e02009-06-08 23:27:34 +00005015 case tok::kw___forceinline:
Dawn Perchik335e16b2010-09-03 01:29:35 +00005016 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00005017 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005018
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005019 case tok::kw__Nonnull:
5020 case tok::kw__Nullable:
5021 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005022
Douglas Gregorab209d82015-07-07 03:58:42 +00005023 case tok::kw___kindof:
5024
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005025 case tok::kw___private:
5026 case tok::kw___local:
5027 case tok::kw___global:
5028 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005029 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005030 case tok::kw___read_only:
5031 case tok::kw___read_write:
5032 case tok::kw___write_only:
Alexey Bader954ba212016-04-08 13:40:33 +00005033#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00005034#include "clang/Basic/OpenCLImageTypes.def"
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005035
Eli Friedman53339e02009-06-08 23:27:34 +00005036 return true;
Anastasia Stulova314fab62019-03-28 11:47:14 +00005037
5038 case tok::kw_private:
5039 return getLangOpts().OpenCL;
Chris Lattneracd58a32006-08-06 17:24:14 +00005040 }
5041}
5042
Richard Smith35845152017-02-07 01:37:30 +00005043bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005044 TentativeParsingAction TPA(*this);
5045
5046 // Parse the C++ scope specifier.
5047 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005048 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005049 /*EnteringContext=*/true)) {
John McCall1f476a12010-02-26 08:45:28 +00005050 TPA.Revert();
5051 return false;
5052 }
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005053
5054 // Parse the constructor name.
Richard Smithaf3b3252017-05-18 19:21:48 +00005055 if (Tok.is(tok::identifier)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005056 // We already know that we have a constructor name; just consume
5057 // the token.
5058 ConsumeToken();
Richard Smithaf3b3252017-05-18 19:21:48 +00005059 } else if (Tok.is(tok::annot_template_id)) {
5060 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005061 } else {
5062 TPA.Revert();
5063 return false;
5064 }
5065
Richard Smith8f8697f2017-02-08 01:16:55 +00005066 // There may be attributes here, appertaining to the constructor name or type
5067 // we just stepped past.
5068 SkipCXX11Attributes();
5069
Richard Smith43f340f2012-03-27 23:05:05 +00005070 // Current class name must be followed by a left parenthesis.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005071 if (Tok.isNot(tok::l_paren)) {
5072 TPA.Revert();
5073 return false;
5074 }
5075 ConsumeParen();
5076
Richard Smith43f340f2012-03-27 23:05:05 +00005077 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5078 // that we have a constructor.
5079 if (Tok.is(tok::r_paren) ||
5080 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005081 TPA.Revert();
5082 return true;
5083 }
5084
Richard Smithf2163662013-09-06 00:12:20 +00005085 // A C++11 attribute here signals that we have a constructor, and is an
5086 // attribute on the first constructor parameter.
5087 if (getLangOpts().CPlusPlus11 &&
5088 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5089 /*OuterMightBeMessageSend*/ true)) {
5090 TPA.Revert();
5091 return true;
5092 }
5093
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005094 // If we need to, enter the specified scope.
5095 DeclaratorScopeObj DeclScopeObj(*this, SS);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005096 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005097 DeclScopeObj.EnterDeclaratorScope();
5098
Francois Pichet79f3a872011-01-31 04:54:32 +00005099 // Optionally skip Microsoft attributes.
John McCall084e83d2011-03-24 11:26:52 +00005100 ParsedAttributes Attrs(AttrFactory);
Francois Pichet79f3a872011-01-31 04:54:32 +00005101 MaybeParseMicrosoftAttributes(Attrs);
5102
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005103 // Check whether the next token(s) are part of a declaration
5104 // specifier, in which case we have the start of a parameter and,
5105 // therefore, we know that this is a constructor.
Richard Smithefd009d2012-03-27 00:56:56 +00005106 bool IsConstructor = false;
5107 if (isDeclarationSpecifier())
5108 IsConstructor = true;
5109 else if (Tok.is(tok::identifier) ||
5110 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5111 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5112 // This might be a parenthesized member name, but is more likely to
5113 // be a constructor declaration with an invalid argument type. Keep
5114 // looking.
5115 if (Tok.is(tok::annot_cxxscope))
Richard Smithaf3b3252017-05-18 19:21:48 +00005116 ConsumeAnnotationToken();
Richard Smithefd009d2012-03-27 00:56:56 +00005117 ConsumeToken();
5118
5119 // If this is not a constructor, we must be parsing a declarator,
Richard Smith1453e312012-03-27 01:42:32 +00005120 // which must have one of the following syntactic forms (see the
5121 // grammar extract at the start of ParseDirectDeclarator):
Richard Smithefd009d2012-03-27 00:56:56 +00005122 switch (Tok.getKind()) {
5123 case tok::l_paren:
5124 // C(X ( int));
5125 case tok::l_square:
5126 // C(X [ 5]);
5127 // C(X [ [attribute]]);
5128 case tok::coloncolon:
5129 // C(X :: Y);
5130 // C(X :: *p);
Richard Smithefd009d2012-03-27 00:56:56 +00005131 // Assume this isn't a constructor, rather than assuming it's a
5132 // constructor with an unnamed parameter of an ill-formed type.
5133 break;
5134
Richard Smith446161b2014-03-03 21:12:53 +00005135 case tok::r_paren:
5136 // C(X )
Richard Smith8f8697f2017-02-08 01:16:55 +00005137
5138 // Skip past the right-paren and any following attributes to get to
5139 // the function body or trailing-return-type.
5140 ConsumeParen();
5141 SkipCXX11Attributes();
5142
Richard Smith35845152017-02-07 01:37:30 +00005143 if (DeductionGuide) {
5144 // C(X) -> ... is a deduction guide.
Richard Smith8f8697f2017-02-08 01:16:55 +00005145 IsConstructor = Tok.is(tok::arrow);
Richard Smith35845152017-02-07 01:37:30 +00005146 break;
5147 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005148 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
Richard Smith446161b2014-03-03 21:12:53 +00005149 // Assume these were meant to be constructors:
5150 // C(X) : (the name of a bit-field cannot be parenthesized).
5151 // C(X) try (this is otherwise ill-formed).
5152 IsConstructor = true;
5153 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005154 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
Richard Smith446161b2014-03-03 21:12:53 +00005155 // If we have a constructor name within the class definition,
5156 // assume these were meant to be constructors:
5157 // C(X) {
5158 // C(X) ;
5159 // ... because otherwise we would be declaring a non-static data
5160 // member that is ill-formed because it's of the same type as its
5161 // surrounding class.
5162 //
5163 // FIXME: We can actually do this whether or not the name is qualified,
5164 // because if it is qualified in this context it must be being used as
Richard Smith35845152017-02-07 01:37:30 +00005165 // a constructor name.
Richard Smith446161b2014-03-03 21:12:53 +00005166 // currently, so we're somewhat conservative here.
5167 IsConstructor = IsUnqualified;
5168 }
5169 break;
5170
Richard Smithefd009d2012-03-27 00:56:56 +00005171 default:
5172 IsConstructor = true;
5173 break;
5174 }
5175 }
5176
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005177 TPA.Revert();
5178 return IsConstructor;
5179}
Chris Lattnerb9093cd2006-08-04 04:39:53 +00005180
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005181/// ParseTypeQualifierListOpt
Dawn Perchik335e16b2010-09-03 01:29:35 +00005182/// type-qualifier-list: [C99 6.7.5]
5183/// type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005184/// [vendor] attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005185/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005186/// type-qualifier-list type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005187/// [vendor] type-qualifier-list attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005188/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005189/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
Aaron Ballman08b06592014-07-22 12:44:22 +00005190/// [ only if AttReqs & AR_CXX11AttributesParsed ]
5191/// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5192/// AttrRequirements bitmask values.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005193void Parser::ParseTypeQualifierListOpt(
5194 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5195 bool IdentifierRequired,
5196 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
Aaron Ballman606093a2017-10-15 15:01:42 +00005197 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005198 isCXX11AttributeSpecifier()) {
John McCall084e83d2011-03-24 11:26:52 +00005199 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith3dff2512012-04-10 03:25:07 +00005200 ParseCXX11Attributes(attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005201 DS.takeAttributesFrom(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005202 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005203
5204 SourceLocation EndLoc;
5205
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005206 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00005207 bool isInvalid = false;
Craig Topper161e4db2014-05-21 06:02:52 +00005208 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00005209 unsigned DiagID = 0;
Chris Lattner60809f52006-11-28 05:18:46 +00005210 SourceLocation Loc = Tok.getLocation();
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005211
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005212 switch (Tok.getKind()) {
Douglas Gregor28c78432010-08-27 17:35:51 +00005213 case tok::code_completion:
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005214 if (CodeCompletionHandler)
5215 (*CodeCompletionHandler)();
5216 else
5217 Actions.CodeCompleteTypeQualifiers(DS);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00005218 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00005219
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005220 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00005221 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005222 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005223 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005224 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00005225 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005226 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005227 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005228 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00005229 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005230 getLangOpts());
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005231 break;
Richard Smith8e1ac332013-03-28 01:55:44 +00005232 case tok::kw__Atomic:
5233 if (!AtomicAllowed)
5234 goto DoneWithTypeQuals;
5235 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5236 getLangOpts());
5237 break;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005238
5239 // OpenCL qualifiers:
Anastasia Stulova948e37c2019-03-25 11:54:02 +00005240 case tok::kw_private:
Anastasia Stulova314fab62019-03-28 11:47:14 +00005241 if (!getLangOpts().OpenCL)
5242 goto DoneWithTypeQuals;
5243 LLVM_FALLTHROUGH;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005244 case tok::kw___private:
5245 case tok::kw___global:
5246 case tok::kw___local:
5247 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005248 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005249 case tok::kw___read_only:
5250 case tok::kw___write_only:
5251 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00005252 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005253 break;
5254
Andrey Bokhanko45d41322016-05-11 18:38:21 +00005255 case tok::kw___unaligned:
5256 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5257 getLangOpts());
5258 break;
Aaron Ballman317a77f2013-05-22 23:25:32 +00005259 case tok::kw___uptr:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005260 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
Alp Toker62c5b572013-11-26 01:30:10 +00005261 // with the MS modifier keyword.
Aaron Ballman08b06592014-07-22 12:44:22 +00005262 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
Alp Toker47642d22013-12-03 06:13:01 +00005263 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5264 if (TryKeywordIdentFallback(false))
5265 continue;
Alp Toker62c5b572013-11-26 01:30:10 +00005266 }
Galina Kistanova77674252017-06-01 21:15:34 +00005267 LLVM_FALLTHROUGH;
Alp Toker62c5b572013-11-26 01:30:10 +00005268 case tok::kw___sptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005269 case tok::kw___w64:
Steve Narofff9c29d42008-12-25 14:41:26 +00005270 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005271 case tok::kw___ptr32:
Steve Naroff44ac7772008-12-25 14:16:32 +00005272 case tok::kw___cdecl:
5273 case tok::kw___stdcall:
5274 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005275 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005276 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005277 case tok::kw___vectorcall:
Aaron Ballman08b06592014-07-22 12:44:22 +00005278 if (AttrReqs & AR_DeclspecAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005279 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00005280 continue;
5281 }
5282 goto DoneWithTypeQuals;
Dawn Perchik335e16b2010-09-03 01:29:35 +00005283 case tok::kw___pascal:
Aaron Ballman08b06592014-07-22 12:44:22 +00005284 if (AttrReqs & AR_VendorAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005285 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00005286 continue;
5287 }
5288 goto DoneWithTypeQuals;
Douglas Gregor261a89b2015-06-19 17:51:05 +00005289
5290 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005291 case tok::kw__Nonnull:
5292 case tok::kw__Nullable:
5293 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005294 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5295 continue;
5296
Douglas Gregorab209d82015-07-07 03:58:42 +00005297 // Objective-C 'kindof' types.
5298 case tok::kw___kindof:
5299 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00005300 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00005301 (void)ConsumeToken();
5302 continue;
5303
Chris Lattnere37e2332006-08-15 04:50:22 +00005304 case tok::kw___attribute:
Aaron Ballman08b06592014-07-22 12:44:22 +00005305 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5306 // When GNU attributes are expressly forbidden, diagnose their usage.
5307 Diag(Tok, diag::err_attributes_not_allowed);
5308
5309 // Parse the attributes even if they are rejected to ensure that error
5310 // recovery is graceful.
5311 if (AttrReqs & AR_GNUAttributesParsed ||
5312 AttrReqs & AR_GNUAttributesParsedAndRejected) {
John McCall53fa7142010-12-24 02:08:15 +00005313 ParseGNUAttributes(DS.getAttributes());
Chris Lattnercf0bab22008-12-18 07:02:59 +00005314 continue; // do *not* consume the next token!
5315 }
5316 // otherwise, FALL THROUGH!
Galina Kistanova77674252017-06-01 21:15:34 +00005317 LLVM_FALLTHROUGH;
Chris Lattnercf0bab22008-12-18 07:02:59 +00005318 default:
Steve Naroff44ac7772008-12-25 14:16:32 +00005319 DoneWithTypeQuals:
Chris Lattnercf0bab22008-12-18 07:02:59 +00005320 // If this is not a type-qualifier token, we're done reading type
5321 // qualifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00005322 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005323 if (EndLoc.isValid())
5324 DS.SetRangeEnd(EndLoc);
Chris Lattnercf0bab22008-12-18 07:02:59 +00005325 return;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005326 }
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00005327
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005328 // If the specifier combination wasn't legal, issue a diagnostic.
5329 if (isInvalid) {
5330 assert(PrevSpec && "Method did not return previous specifier!");
Chris Lattner6d29c102008-11-18 07:48:38 +00005331 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005332 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005333 EndLoc = ConsumeToken();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005334 }
5335}
5336
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005337/// ParseDeclarator - Parse and verify a newly-initialized declarator.
5338///
5339void Parser::ParseDeclarator(Declarator &D) {
5340 /// This implements the 'declarator' production in the C grammar, then checks
5341 /// for well-formedness and issues diagnostics.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005342 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005343}
5344
Richard Smith0b350b92014-10-28 16:55:02 +00005345static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
Faisal Vali421b2d12017-12-29 05:41:00 +00005346 DeclaratorContext TheContext) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005347 if (Kind == tok::star || Kind == tok::caret)
5348 return true;
5349
Xiuli Pan9c14e282016-01-09 12:53:17 +00005350 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5351 return true;
5352
Richard Smith0efa75c2012-03-29 01:16:42 +00005353 if (!Lang.CPlusPlus)
5354 return false;
5355
Richard Smith0b350b92014-10-28 16:55:02 +00005356 if (Kind == tok::amp)
5357 return true;
5358
5359 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5360 // But we must not parse them in conversion-type-ids and new-type-ids, since
5361 // those can be legitimately followed by a && operator.
5362 // (The same thing can in theory happen after a trailing-return-type, but
5363 // since those are a C++11 feature, there is no rejects-valid issue there.)
5364 if (Kind == tok::ampamp)
Faisal Vali421b2d12017-12-29 05:41:00 +00005365 return Lang.CPlusPlus11 ||
5366 (TheContext != DeclaratorContext::ConversionIdContext &&
5367 TheContext != DeclaratorContext::CXXNewContext);
Richard Smith0b350b92014-10-28 16:55:02 +00005368
5369 return false;
Richard Smith0efa75c2012-03-29 01:16:42 +00005370}
5371
Xiuli Pan9c14e282016-01-09 12:53:17 +00005372// Indicates whether the given declarator is a pipe declarator.
5373static bool isPipeDeclerator(const Declarator &D) {
5374 const unsigned NumTypes = D.getNumTypeObjects();
5375
5376 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5377 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5378 return true;
5379
5380 return false;
5381}
5382
Sebastian Redlbd150f42008-11-21 19:14:01 +00005383/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5384/// is parsed by the function passed to it. Pass null, and the direct-declarator
5385/// isn't parsed at all, making this function effectively parse the C++
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005386/// ptr-operator production.
5387///
Richard Smith09f76ee2011-10-19 21:33:05 +00005388/// If the grammar of this construct is extended, matching changes must also be
Richard Smith1453e312012-03-27 01:42:32 +00005389/// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5390/// isConstructorDeclarator.
Richard Smith09f76ee2011-10-19 21:33:05 +00005391///
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005392/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5393/// [C] pointer[opt] direct-declarator
5394/// [C++] direct-declarator
5395/// [C++] ptr-operator declarator
Chris Lattner6c7416c2006-08-07 00:19:33 +00005396///
5397/// pointer: [C99 6.7.5]
5398/// '*' type-qualifier-list[opt]
5399/// '*' type-qualifier-list[opt] pointer
5400///
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005401/// ptr-operator:
5402/// '*' cv-qualifier-seq[opt]
5403/// '&'
Sebastian Redled0f3b02009-03-15 22:02:01 +00005404/// [C++0x] '&&'
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005405/// [GNU] '&' restrict[opt] attributes[opt]
Sebastian Redled0f3b02009-03-15 22:02:01 +00005406/// [GNU?] '&&' restrict[opt] attributes[opt]
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005407/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
Sebastian Redlbd150f42008-11-21 19:14:01 +00005408void Parser::ParseDeclaratorInternal(Declarator &D,
5409 DirectDeclParseFunction DirectDeclParser) {
Douglas Gregor66a985d2009-08-26 14:27:30 +00005410 if (Diags.hasAllExtensionsSilenced())
5411 D.setExtension();
Chad Rosierc1183952012-06-26 22:30:43 +00005412
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005413 // C++ member pointers start with a '::' or a nested-name.
5414 // Member pointers get special handling, since there's no place for the
5415 // scope spec in the generic path below.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005416 if (getLangOpts().CPlusPlus &&
Richard Smith83c2ecf2016-02-02 23:34:49 +00005417 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
Serge Pavlov458ea762014-07-16 05:16:52 +00005418 (Tok.is(tok::identifier) &&
5419 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
Chris Lattner803802d2009-03-24 17:04:48 +00005420 Tok.is(tok::annot_cxxscope))) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005421 bool EnteringContext =
5422 D.getContext() == DeclaratorContext::FileContext ||
5423 D.getContext() == DeclaratorContext::MemberContext;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005424 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005425 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005426
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +00005427 if (SS.isNotEmpty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005428 if (Tok.isNot(tok::star)) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005429 // The scope spec really belongs to the direct-declarator.
Richard Smith5f044ad2013-01-08 22:43:49 +00005430 if (D.mayHaveIdentifier())
5431 D.getCXXScopeSpec() = SS;
5432 else
5433 AnnotateScopeToken(SS, true);
5434
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005435 if (DirectDeclParser)
5436 (this->*DirectDeclParser)(D);
5437 return;
5438 }
5439
5440 SourceLocation Loc = ConsumeToken();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005441 D.SetRangeEnd(Loc);
John McCall084e83d2011-03-24 11:26:52 +00005442 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005443 ParseTypeQualifierListOpt(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005444 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005445
5446 // Recurse to parse whatever is left.
5447 ParseDeclaratorInternal(D, DirectDeclParser);
5448
5449 // Sema will have to catch (syntactically invalid) pointers into global
5450 // scope. It has to catch pointers into namespace scope anyway.
Erich Keanec480f302018-07-12 21:09:05 +00005451 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005452 SS, DS.getTypeQualifiers(), DS.getEndLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005453 std::move(DS.getAttributes()),
5454 /* Don't replace range end. */ SourceLocation());
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005455 return;
5456 }
5457 }
5458
5459 tok::TokenKind Kind = Tok.getKind();
Xiuli Pan9c14e282016-01-09 12:53:17 +00005460
5461 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
Xiuli Pan11e13f62016-02-26 03:13:03 +00005462 DeclSpec DS(AttrFactory);
5463 ParseTypeQualifierListOpt(DS);
Xiuli Pan9c14e282016-01-09 12:53:17 +00005464
5465 D.AddTypeInfo(
5466 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005467 std::move(DS.getAttributes()), SourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00005468 }
5469
Steve Naroffec33ed92008-08-27 16:04:49 +00005470 // Not a pointer, C++ reference, or block.
Richard Smith0b350b92014-10-28 16:55:02 +00005471 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00005472 if (DirectDeclParser)
5473 (this->*DirectDeclParser)(D);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005474 return;
5475 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005476
Sebastian Redled0f3b02009-03-15 22:02:01 +00005477 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5478 // '&&' -> rvalue reference
Sebastian Redl3b27be62009-03-23 00:00:23 +00005479 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005480 D.SetRangeEnd(Loc);
Bill Wendling3708c182007-05-27 10:15:43 +00005481
Chris Lattner9eac9312009-03-27 04:18:06 +00005482 if (Kind == tok::star || Kind == tok::caret) {
Chris Lattner788404f2008-02-21 01:32:26 +00005483 // Is a pointer.
John McCall084e83d2011-03-24 11:26:52 +00005484 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005485
Aaron Ballman08b06592014-07-22 12:44:22 +00005486 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5487 // C++11 attributes are allowed.
5488 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
Faisal Vali421b2d12017-12-29 05:41:00 +00005489 ((D.getContext() != DeclaratorContext::CXXNewContext)
5490 ? AR_GNUAttributesParsed
5491 : AR_GNUAttributesParsedAndRejected);
Aaron Ballman08b06592014-07-22 12:44:22 +00005492 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005493 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005494
Bill Wendling3708c182007-05-27 10:15:43 +00005495 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005496 ParseDeclaratorInternal(D, DirectDeclParser);
Steve Naroffec33ed92008-08-27 16:04:49 +00005497 if (Kind == tok::star)
5498 // Remember that we parsed a pointer type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005499 D.AddTypeInfo(DeclaratorChunk::getPointer(
5500 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5501 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5502 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5503 std::move(DS.getAttributes()), SourceLocation());
Steve Naroffec33ed92008-08-27 16:04:49 +00005504 else
5505 // Remember that we parsed a Block type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005506 D.AddTypeInfo(
5507 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5508 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005509 } else {
5510 // Is a reference
John McCall084e83d2011-03-24 11:26:52 +00005511 DeclSpec DS(AttrFactory);
Bill Wendling93efb222007-06-02 23:28:54 +00005512
Sebastian Redl3b27be62009-03-23 00:00:23 +00005513 // Complain about rvalue references in C++03, but then go on and build
5514 // the declarator.
Richard Smith5d164bc2011-10-15 05:09:34 +00005515 if (Kind == tok::ampamp)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005516 Diag(Loc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00005517 diag::warn_cxx98_compat_rvalue_reference :
5518 diag::ext_rvalue_reference);
Sebastian Redl3b27be62009-03-23 00:00:23 +00005519
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005520 // GNU-style and C++11 attributes are allowed here, as is restrict.
5521 ParseTypeQualifierListOpt(DS);
5522 D.ExtendWithDeclSpec(DS);
5523
Bill Wendling93efb222007-06-02 23:28:54 +00005524 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5525 // cv-qualifiers are introduced through the use of a typedef or of a
5526 // template type argument, in which case the cv-qualifiers are ignored.
Bill Wendling93efb222007-06-02 23:28:54 +00005527 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5528 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5529 Diag(DS.getConstSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005530 diag::err_invalid_reference_qualifier_application) << "const";
Bill Wendling93efb222007-06-02 23:28:54 +00005531 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5532 Diag(DS.getVolatileSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005533 diag::err_invalid_reference_qualifier_application) << "volatile";
Richard Smith8e1ac332013-03-28 01:55:44 +00005534 // 'restrict' is permitted as an extension.
5535 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5536 Diag(DS.getAtomicSpecLoc(),
5537 diag::err_invalid_reference_qualifier_application) << "_Atomic";
Bill Wendling93efb222007-06-02 23:28:54 +00005538 }
Bill Wendling3708c182007-05-27 10:15:43 +00005539
5540 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005541 ParseDeclaratorInternal(D, DirectDeclParser);
Bill Wendling3708c182007-05-27 10:15:43 +00005542
Douglas Gregor66583c52008-11-03 15:51:28 +00005543 if (D.getNumTypeObjects() > 0) {
5544 // C++ [dcl.ref]p4: There shall be no references to references.
5545 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5546 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
Chris Lattnerebad6a22008-11-19 07:37:42 +00005547 if (const IdentifierInfo *II = D.getIdentifier())
5548 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5549 << II;
5550 else
5551 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5552 << "type name";
Douglas Gregor66583c52008-11-03 15:51:28 +00005553
Sebastian Redlbd150f42008-11-21 19:14:01 +00005554 // Once we've complained about the reference-to-reference, we
Douglas Gregor66583c52008-11-03 15:51:28 +00005555 // can go ahead and build the (technically ill-formed)
5556 // declarator: reference collapsing will take care of it.
5557 }
5558 }
5559
Richard Smith8e1ac332013-03-28 01:55:44 +00005560 // Remember that we parsed a reference type.
Chris Lattner788404f2008-02-21 01:32:26 +00005561 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
Sebastian Redled0f3b02009-03-15 22:02:01 +00005562 Kind == tok::amp),
Erich Keanec480f302018-07-12 21:09:05 +00005563 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005564 }
Chris Lattner6c7416c2006-08-07 00:19:33 +00005565}
5566
Richard Trieuf4b81d02014-06-24 23:14:24 +00005567// When correcting from misplaced brackets before the identifier, the location
5568// is saved inside the declarator so that other diagnostic messages can use
5569// them. This extracts and returns that location, or returns the provided
5570// location if a stored location does not exist.
5571static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5572 SourceLocation Loc) {
5573 if (D.getName().StartLocation.isInvalid() &&
5574 D.getName().EndLocation.isValid())
5575 return D.getName().EndLocation;
5576
5577 return Loc;
5578}
5579
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005580/// ParseDirectDeclarator
5581/// direct-declarator: [C99 6.7.5]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005582/// [C99] identifier
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005583/// '(' declarator ')'
5584/// [GNU] '(' attributes declarator ')'
Chris Lattnere8074e62006-08-06 18:30:15 +00005585/// [C90] direct-declarator '[' constant-expression[opt] ']'
5586/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5587/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5588/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5589/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005590/// [C++11] direct-declarator '[' constant-expression[opt] ']'
5591/// attribute-specifier-seq[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005592/// direct-declarator '(' parameter-type-list ')'
5593/// direct-declarator '(' identifier-list[opt] ')'
5594/// [GNU] direct-declarator '(' parameter-forward-declarations
5595/// parameter-type-list[opt] ')'
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00005596/// [C++] direct-declarator '(' parameter-declaration-clause ')'
5597/// cv-qualifier-seq[opt] exception-specification[opt]
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005598/// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5599/// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5600/// ref-qualifier[opt] exception-specification[opt]
Douglas Gregor61956c42008-10-31 09:07:45 +00005601/// [C++] declarator-id
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005602/// [C++11] declarator-id attribute-specifier-seq[opt]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005603///
5604/// declarator-id: [C++ 8]
Douglas Gregor27b4c162010-12-23 22:44:42 +00005605/// '...'[opt] id-expression
Douglas Gregor831c93f2008-11-05 20:51:48 +00005606/// '::'[opt] nested-name-specifier[opt] type-name
5607///
5608/// id-expression: [C++ 5.1]
5609/// unqualified-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005610/// qualified-id
Douglas Gregor831c93f2008-11-05 20:51:48 +00005611///
5612/// unqualified-id: [C++ 5.1]
Mike Stump11289f42009-09-09 15:08:12 +00005613/// identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005614/// operator-function-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005615/// conversion-function-id
Mike Stump11289f42009-09-09 15:08:12 +00005616/// '~' class-name
Douglas Gregor7f741122009-02-25 19:37:18 +00005617/// template-id
Argyrios Kyrtzidise4426352008-11-07 22:02:30 +00005618///
Richard Smithbdb84f32016-07-22 23:36:59 +00005619/// C++17 adds the following, which we also handle here:
5620///
5621/// simple-declaration:
5622/// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5623///
Richard Smith1453e312012-03-27 01:42:32 +00005624/// Note, any additional constructs added here may need corresponding changes
5625/// in isConstructorDeclarator.
Chris Lattneracd58a32006-08-06 17:24:14 +00005626void Parser::ParseDirectDeclarator(Declarator &D) {
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005627 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005628
David Blaikiebbafb8a2012-03-11 07:00:24 +00005629 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
Richard Smithbdb84f32016-07-22 23:36:59 +00005630 // This might be a C++17 structured binding.
5631 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5632 D.getCXXScopeSpec().isEmpty())
5633 return ParseDecompositionDeclarator(D);
5634
Serge Pavlov458ea762014-07-16 05:16:52 +00005635 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5636 // this context it is a bitfield. Also in range-based for statement colon
5637 // may delimit for-range-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00005638 ColonProtectionRAIIObject X(
5639 *this, D.getContext() == DeclaratorContext::MemberContext ||
5640 (D.getContext() == DeclaratorContext::ForContext &&
5641 getLangOpts().CPlusPlus11));
Serge Pavlov458ea762014-07-16 05:16:52 +00005642
Douglas Gregor7861a802009-11-03 01:35:08 +00005643 // ParseDeclaratorInternal might already have parsed the scope.
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005644 if (D.getCXXScopeSpec().isEmpty()) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005645 bool EnteringContext =
5646 D.getContext() == DeclaratorContext::FileContext ||
5647 D.getContext() == DeclaratorContext::MemberContext;
David Blaikieefdccaa2016-01-15 23:43:34 +00005648 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005649 EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005650 }
5651
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005652 if (D.getCXXScopeSpec().isValid()) {
Richard Smith64e033f2015-01-15 00:48:52 +00005653 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5654 D.getCXXScopeSpec()))
John McCall2b058ef2009-12-11 20:04:54 +00005655 // Change the declaration context for name lookup, until this function
5656 // is exited (and the declarator has been parsed).
5657 DeclScopeObj.EnterDeclaratorScope();
Alex Lorenze151f0102016-12-07 10:24:44 +00005658 else if (getObjCDeclContext()) {
5659 // Ensure that we don't interpret the next token as an identifier when
5660 // dealing with declarations in an Objective-C container.
5661 D.SetIdentifier(nullptr, Tok.getLocation());
5662 D.setInvalidType(true);
5663 ConsumeToken();
5664 goto PastIdentifier;
5665 }
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005666 }
5667
Douglas Gregor27b4c162010-12-23 22:44:42 +00005668 // C++0x [dcl.fct]p14:
Faisal Vali8435a692014-12-04 12:40:21 +00005669 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5670 // parameter-declaration-clause without a preceding comma. In this case,
5671 // the ellipsis is parsed as part of the abstract-declarator if the type
5672 // of the parameter either names a template parameter pack that has not
5673 // been expanded or contains auto; otherwise, it is parsed as part of the
5674 // parameter-declaration-clause.
Richard Smith0efa75c2012-03-29 01:16:42 +00005675 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00005676 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5677 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5678 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
Douglas Gregor27b4c162010-12-23 22:44:42 +00005679 NextToken().is(tok::r_paren) &&
Richard Smithb19337f2013-02-20 20:19:27 +00005680 !D.hasGroupingParens() &&
Faisal Vali8435a692014-12-04 12:40:21 +00005681 !Actions.containsUnexpandedParameterPacks(D) &&
Faisal Vali090da2d2018-01-01 18:23:28 +00005682 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005683 SourceLocation EllipsisLoc = ConsumeToken();
Richard Smith0b350b92014-10-28 16:55:02 +00005684 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005685 // The ellipsis was put in the wrong place. Recover, and explain to
5686 // the user what they should have done.
5687 ParseDeclarator(D);
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00005688 if (EllipsisLoc.isValid())
5689 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00005690 return;
5691 } else
5692 D.setEllipsisLoc(EllipsisLoc);
5693
5694 // The ellipsis can't be followed by a parenthesized declarator. We
5695 // check for that in ParseParenDeclarator, after we have disambiguated
5696 // the l_paren token.
5697 }
5698
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005699 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5700 tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00005701 // We found something that indicates the start of an unqualified-id.
5702 // Parse that unqualified-id.
John McCall84821e72010-04-13 06:39:49 +00005703 bool AllowConstructorName;
Richard Smith35845152017-02-07 01:37:30 +00005704 bool AllowDeductionGuide;
5705 if (D.getDeclSpec().hasTypeSpecifier()) {
John McCall84821e72010-04-13 06:39:49 +00005706 AllowConstructorName = false;
Richard Smith35845152017-02-07 01:37:30 +00005707 AllowDeductionGuide = false;
5708 } else if (D.getCXXScopeSpec().isSet()) {
John McCall84821e72010-04-13 06:39:49 +00005709 AllowConstructorName =
Faisal Vali421b2d12017-12-29 05:41:00 +00005710 (D.getContext() == DeclaratorContext::FileContext ||
5711 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005712 AllowDeductionGuide = false;
5713 } else {
Faisal Vali421b2d12017-12-29 05:41:00 +00005714 AllowConstructorName =
5715 (D.getContext() == DeclaratorContext::MemberContext);
Fangrui Song6907ce22018-07-30 19:24:48 +00005716 AllowDeductionGuide =
Faisal Vali421b2d12017-12-29 05:41:00 +00005717 (D.getContext() == DeclaratorContext::FileContext ||
5718 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005719 }
John McCall84821e72010-04-13 06:39:49 +00005720
Richard Smith64e033f2015-01-15 00:48:52 +00005721 bool HadScope = D.getCXXScopeSpec().isValid();
Chad Rosierc1183952012-06-26 22:30:43 +00005722 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5723 /*EnteringContext=*/true,
David Blaikieefdccaa2016-01-15 23:43:34 +00005724 /*AllowDestructorName=*/true, AllowConstructorName,
Richard Smithc08b6932018-04-27 02:00:13 +00005725 AllowDeductionGuide, nullptr, nullptr,
Richard Smith35845152017-02-07 01:37:30 +00005726 D.getName()) ||
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005727 // Once we're past the identifier, if the scope was bad, mark the
5728 // whole declarator bad.
5729 D.getCXXScopeSpec().isInvalid()) {
Craig Topper161e4db2014-05-21 06:02:52 +00005730 D.SetIdentifier(nullptr, Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005731 D.setInvalidType(true);
Douglas Gregor7861a802009-11-03 01:35:08 +00005732 } else {
Richard Smith64e033f2015-01-15 00:48:52 +00005733 // ParseUnqualifiedId might have parsed a scope specifier during error
5734 // recovery. If it did so, enter that scope.
5735 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5736 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5737 D.getCXXScopeSpec()))
5738 DeclScopeObj.EnterDeclaratorScope();
5739
Douglas Gregor7861a802009-11-03 01:35:08 +00005740 // Parsed the unqualified-id; update range information and move along.
5741 if (D.getSourceRange().getBegin().isInvalid())
5742 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5743 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005744 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005745 goto PastIdentifier;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005746 }
Richard Smithd63db6e2015-12-19 02:40:19 +00005747
5748 if (D.getCXXScopeSpec().isNotEmpty()) {
5749 // We have a scope specifier but no following unqualified-id.
5750 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5751 diag::err_expected_unqualified_id)
5752 << /*C++*/1;
5753 D.SetIdentifier(nullptr, Tok.getLocation());
5754 goto PastIdentifier;
5755 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005756 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005757 assert(!getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005758 "There's a C++-specific check for tok::identifier above");
5759 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5760 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Richard Trieu2664dc12014-05-05 22:06:50 +00005761 D.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005762 ConsumeToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00005763 goto PastIdentifier;
Richard Smith74639b12017-05-19 01:54:59 +00005764 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5765 // We're not allowed an identifier here, but we got one. Try to figure out
5766 // if the user was trying to attach a name to the type, or whether the name
5767 // is some unrelated trailing syntax.
5768 bool DiagnoseIdentifier = false;
5769 if (D.hasGroupingParens())
5770 // An identifier within parens is unlikely to be intended to be anything
5771 // other than a name being "declared".
5772 DiagnoseIdentifier = true;
Richard Smith77a9c602018-02-28 03:02:23 +00005773 else if (D.getContext() == DeclaratorContext::TemplateArgContext)
Richard Smith74639b12017-05-19 01:54:59 +00005774 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5775 DiagnoseIdentifier =
5776 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali421b2d12017-12-29 05:41:00 +00005777 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5778 D.getContext() == DeclaratorContext::AliasTemplateContext)
Richard Smith74639b12017-05-19 01:54:59 +00005779 // The most likely error is that the ';' was forgotten.
5780 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
Richard Smithe303e352018-02-02 22:24:54 +00005781 else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5782 D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
Richard Smith74639b12017-05-19 01:54:59 +00005783 !isCXX11VirtSpecifier(Tok))
5784 DiagnoseIdentifier = NextToken().isOneOf(
5785 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5786 if (DiagnoseIdentifier) {
Richard Smithf39720b2013-10-13 22:12:28 +00005787 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5788 << FixItHint::CreateRemoval(Tok.getLocation());
Craig Topper161e4db2014-05-21 06:02:52 +00005789 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithf39720b2013-10-13 22:12:28 +00005790 ConsumeToken();
5791 goto PastIdentifier;
5792 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005793 }
Richard Smith0efa75c2012-03-29 01:16:42 +00005794
Douglas Gregor7861a802009-11-03 01:35:08 +00005795 if (Tok.is(tok::l_paren)) {
Richard Smithe303e352018-02-02 22:24:54 +00005796 // If this might be an abstract-declarator followed by a direct-initializer,
5797 // check whether this is a valid declarator chunk. If it can't be, assume
5798 // that it's an initializer instead.
5799 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5800 RevertingTentativeParsingAction PA(*this);
5801 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5802 TPResult::False) {
5803 D.SetIdentifier(nullptr, Tok.getLocation());
5804 goto PastIdentifier;
5805 }
5806 }
5807
Chris Lattneracd58a32006-08-06 17:24:14 +00005808 // direct-declarator: '(' declarator ')'
Chris Lattnere37e2332006-08-15 04:50:22 +00005809 // direct-declarator: '(' attributes declarator ')'
Chris Lattneracd58a32006-08-06 17:24:14 +00005810 // Example: 'char (*X)' or 'int (*XX)(void)'
5811 ParseParenDeclarator(D);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005812
5813 // If the declarator was parenthesized, we entered the declarator
5814 // scope when parsing the parenthesized declarator, then exited
5815 // the scope already. Re-enter the scope, if we need to.
5816 if (D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005817 // If there was an error parsing parenthesized declarator, declarator
Richard Smith0efa75c2012-03-29 01:16:42 +00005818 // scope may have been entered before. Don't do it again.
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005819 if (!D.isInvalidType() &&
Nico Weber6b05f382015-02-18 04:53:03 +00005820 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5821 D.getCXXScopeSpec()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005822 // Change the declaration context for name lookup, until this function
5823 // is exited (and the declarator has been parsed).
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005824 DeclScopeObj.EnterDeclaratorScope();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005825 }
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005826 } else if (D.mayOmitIdentifier()) {
Chris Lattneracd58a32006-08-06 17:24:14 +00005827 // This could be something simple like "int" (in which case the declarator
5828 // portion is empty), if an abstract-declarator is allowed.
Craig Topper161e4db2014-05-21 06:02:52 +00005829 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithb19337f2013-02-20 20:19:27 +00005830
5831 // The grammar for abstract-pack-declarator does not allow grouping parens.
5832 // FIXME: Revisit this once core issue 1488 is resolved.
5833 if (D.hasEllipsis() && D.hasGroupingParens())
5834 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5835 diag::ext_abstract_pack_declarator_parens);
Chris Lattneracd58a32006-08-06 17:24:14 +00005836 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00005837 if (Tok.getKind() == tok::annot_pragma_parser_crash)
David Blaikie5bd4c2a2012-08-21 18:56:49 +00005838 LLVM_BUILTIN_TRAP;
Richard Trieuf4b81d02014-06-24 23:14:24 +00005839 if (Tok.is(tok::l_square))
5840 return ParseMisplacedBracketDeclarator(D);
Faisal Vali421b2d12017-12-29 05:41:00 +00005841 if (D.getContext() == DeclaratorContext::MemberContext) {
Alex Lorenzf1278212017-04-11 15:01:53 +00005842 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5843 // treating these keyword as valid member names.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005844 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
Alex Lorenzf1278212017-04-11 15:01:53 +00005845 Tok.getIdentifierInfo() &&
5846 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5847 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5848 diag::err_expected_member_name_or_semi_objcxx_keyword)
5849 << Tok.getIdentifierInfo()
5850 << (D.getDeclSpec().isEmpty() ? SourceRange()
5851 : D.getDeclSpec().getSourceRange());
5852 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5853 D.SetRangeEnd(Tok.getLocation());
5854 ConsumeToken();
5855 goto PastIdentifier;
5856 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005857 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5858 diag::err_expected_member_name_or_semi)
Richard Trieua1342402014-05-02 23:40:32 +00005859 << (D.getDeclSpec().isEmpty() ? SourceRange()
5860 : D.getDeclSpec().getSourceRange());
Richard Trieuf4b81d02014-06-24 23:14:24 +00005861 } else if (getLangOpts().CPlusPlus) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005862 if (Tok.isOneOf(tok::period, tok::arrow))
Richard Trieu9c672672013-01-26 02:31:38 +00005863 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
Richard Trieu2f586962013-09-05 02:31:33 +00005864 else {
5865 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5866 if (Tok.isAtStartOfLine() && Loc.isValid())
5867 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5868 << getLangOpts().CPlusPlus;
5869 else
Richard Trieuf4b81d02014-06-24 23:14:24 +00005870 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5871 diag::err_expected_unqualified_id)
Richard Trieu2f586962013-09-05 02:31:33 +00005872 << getLangOpts().CPlusPlus;
5873 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005874 } else {
5875 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5876 diag::err_expected_either)
5877 << tok::identifier << tok::l_paren;
5878 }
Craig Topper161e4db2014-05-21 06:02:52 +00005879 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattner8c5dd732008-11-11 06:13:16 +00005880 D.setInvalidType(true);
Chris Lattneracd58a32006-08-06 17:24:14 +00005881 }
Mike Stump11289f42009-09-09 15:08:12 +00005882
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005883 PastIdentifier:
Chris Lattneracd58a32006-08-06 17:24:14 +00005884 assert(D.isPastIdentifier() &&
5885 "Haven't past the location of the identifier yet?");
Mike Stump11289f42009-09-09 15:08:12 +00005886
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005887 // Don't parse attributes unless we have parsed an unparenthesized name.
5888 if (D.hasName() && !D.getNumTypeObjects())
Richard Smith89645bc2013-01-02 12:01:23 +00005889 MaybeParseCXX11Attributes(D);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005890
Chris Lattneracd58a32006-08-06 17:24:14 +00005891 while (1) {
Chris Lattner76c72282007-10-09 17:33:22 +00005892 if (Tok.is(tok::l_paren)) {
David Blaikie15a430a2011-12-04 05:04:18 +00005893 // Enter function-declaration scope, limiting any declarators to the
5894 // function prototype scope, including parameter declarators.
5895 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00005896 Scope::FunctionPrototypeScope|Scope::DeclScope|
5897 (D.isFunctionDeclaratorAFunctionDeclaration()
5898 ? Scope::FunctionDeclarationScope : 0));
5899
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005900 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5901 // In such a case, check if we actually have a function declarator; if it
5902 // is not, the declarator has been fully parsed.
Richard Smith943c4402012-07-30 21:30:52 +00005903 bool IsAmbiguous = false;
Richard Smith4f605af2012-08-18 00:55:03 +00005904 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5905 // The name of the declarator, if any, is tentatively declared within
5906 // a possible direct initializer.
5907 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5908 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5909 TentativelyDeclaredIdentifiers.pop_back();
5910 if (!IsFunctionDecl)
5911 break;
5912 }
John McCall084e83d2011-03-24 11:26:52 +00005913 ParsedAttributes attrs(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005914 BalancedDelimiterTracker T(*this, tok::l_paren);
5915 T.consumeOpen();
Richard Smith943c4402012-07-30 21:30:52 +00005916 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
David Blaikie15a430a2011-12-04 05:04:18 +00005917 PrototypeScope.Exit();
Chris Lattner76c72282007-10-09 17:33:22 +00005918 } else if (Tok.is(tok::l_square)) {
Chris Lattnere8074e62006-08-06 18:30:15 +00005919 ParseBracketDeclarator(D);
Chris Lattneracd58a32006-08-06 17:24:14 +00005920 } else {
5921 break;
5922 }
5923 }
Chad Rosierc1183952012-06-26 22:30:43 +00005924}
Chris Lattneracd58a32006-08-06 17:24:14 +00005925
Richard Smithbdb84f32016-07-22 23:36:59 +00005926void Parser::ParseDecompositionDeclarator(Declarator &D) {
5927 assert(Tok.is(tok::l_square));
5928
5929 // If this doesn't look like a structured binding, maybe it's a misplaced
5930 // array declarator.
5931 // FIXME: Consume the l_square first so we don't need extra lookahead for
5932 // this.
5933 if (!(NextToken().is(tok::identifier) &&
5934 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5935 !(NextToken().is(tok::r_square) &&
5936 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5937 return ParseMisplacedBracketDeclarator(D);
5938
5939 BalancedDelimiterTracker T(*this, tok::l_square);
5940 T.consumeOpen();
5941
5942 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5943 while (Tok.isNot(tok::r_square)) {
5944 if (!Bindings.empty()) {
5945 if (Tok.is(tok::comma))
5946 ConsumeToken();
5947 else {
5948 if (Tok.is(tok::identifier)) {
5949 SourceLocation EndLoc = getEndOfPreviousToken();
5950 Diag(EndLoc, diag::err_expected)
5951 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5952 } else {
5953 Diag(Tok, diag::err_expected_comma_or_rsquare);
5954 }
5955
5956 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5957 StopAtSemi | StopBeforeMatch);
5958 if (Tok.is(tok::comma))
5959 ConsumeToken();
5960 else if (Tok.isNot(tok::identifier))
5961 break;
5962 }
5963 }
5964
5965 if (Tok.isNot(tok::identifier)) {
5966 Diag(Tok, diag::err_expected) << tok::identifier;
5967 break;
5968 }
5969
5970 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
5971 ConsumeToken();
5972 }
5973
5974 if (Tok.isNot(tok::r_square))
5975 // We've already diagnosed a problem here.
5976 T.skipToEnd();
5977 else {
5978 // C++17 does not allow the identifier-list in a structured binding
5979 // to be empty.
5980 if (Bindings.empty())
5981 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
5982
5983 T.consumeClose();
5984 }
5985
5986 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
5987 T.getCloseLocation());
5988}
5989
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005990/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5991/// only called before the identifier, so these are most likely just grouping
Mike Stump11289f42009-09-09 15:08:12 +00005992/// parens for precedence. If we find that these are actually function
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005993/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5994///
5995/// direct-declarator:
5996/// '(' declarator ')'
5997/// [GNU] '(' attributes declarator ')'
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005998/// direct-declarator '(' parameter-type-list ')'
5999/// direct-declarator '(' identifier-list[opt] ')'
6000/// [GNU] direct-declarator '(' parameter-forward-declarations
6001/// parameter-type-list[opt] ')'
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006002///
6003void Parser::ParseParenDeclarator(Declarator &D) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006004 BalancedDelimiterTracker T(*this, tok::l_paren);
6005 T.consumeOpen();
6006
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006007 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
Mike Stump11289f42009-09-09 15:08:12 +00006008
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006009 // Eat any attributes before we look at whether this is a grouping or function
6010 // declarator paren. If this is a grouping paren, the attribute applies to
6011 // the type being built up, for example:
6012 // int (__attribute__(()) *x)(long y)
6013 // If this ends up not being a grouping paren, the attribute applies to the
6014 // first argument, for example:
6015 // int (__attribute__(()) int x)
6016 // In either case, we need to eat any attributes to be able to determine what
6017 // sort of paren this is.
6018 //
John McCall084e83d2011-03-24 11:26:52 +00006019 ParsedAttributes attrs(AttrFactory);
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006020 bool RequiresArg = false;
6021 if (Tok.is(tok::kw___attribute)) {
John McCall53fa7142010-12-24 02:08:15 +00006022 ParseGNUAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006023
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006024 // We require that the argument list (if this is a non-grouping paren) be
6025 // present even if the attribute list was empty.
6026 RequiresArg = true;
6027 }
Chad Rosiereea9ca72012-12-21 21:22:20 +00006028
Steve Naroff44ac7772008-12-25 14:16:32 +00006029 // Eat any Microsoft extensions.
Chad Rosiereea9ca72012-12-21 21:22:20 +00006030 ParseMicrosoftTypeAttributes(attrs);
6031
Dawn Perchik335e16b2010-09-03 01:29:35 +00006032 // Eat any Borland extensions.
Ted Kremenek5eec2b02010-11-10 05:59:39 +00006033 if (Tok.is(tok::kw___pascal))
John McCall53fa7142010-12-24 02:08:15 +00006034 ParseBorlandTypeAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006035
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006036 // If we haven't past the identifier yet (or where the identifier would be
6037 // stored, if this is an abstract declarator), then this is probably just
6038 // grouping parens. However, if this could be an abstract-declarator, then
6039 // this could also be the start of function arguments (consider 'void()').
6040 bool isGrouping;
Mike Stump11289f42009-09-09 15:08:12 +00006041
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006042 if (!D.mayOmitIdentifier()) {
6043 // If this can't be an abstract-declarator, this *must* be a grouping
6044 // paren, because we haven't seen the identifier yet.
6045 isGrouping = true;
6046 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
Richard Smith43f340f2012-03-27 23:05:05 +00006047 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6048 NextToken().is(tok::r_paren)) || // C++ int(...)
Richard Smith2620cd92012-04-11 04:01:28 +00006049 isDeclarationSpecifier() || // 'int(int)' is a function.
6050 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006051 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6052 // considered to be a type, not a K&R identifier-list.
6053 isGrouping = false;
6054 } else {
6055 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6056 isGrouping = true;
6057 }
Mike Stump11289f42009-09-09 15:08:12 +00006058
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006059 // If this is a grouping paren, handle:
6060 // direct-declarator: '(' declarator ')'
6061 // direct-declarator: '(' attributes declarator ')'
6062 if (isGrouping) {
Richard Smith0efa75c2012-03-29 01:16:42 +00006063 SourceLocation EllipsisLoc = D.getEllipsisLoc();
6064 D.setEllipsisLoc(SourceLocation());
6065
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006066 bool hadGroupingParens = D.hasGroupingParens();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006067 D.setGroupingParens(true);
Sebastian Redlbd150f42008-11-21 19:14:01 +00006068 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006069 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006070 T.consumeClose();
Erich Keanec480f302018-07-12 21:09:05 +00006071 D.AddTypeInfo(
6072 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6073 std::move(attrs), T.getCloseLocation());
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006074
6075 D.setGroupingParens(hadGroupingParens);
Richard Smith0efa75c2012-03-29 01:16:42 +00006076
6077 // An ellipsis cannot be placed outside parentheses.
6078 if (EllipsisLoc.isValid())
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00006079 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00006080
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006081 return;
6082 }
Mike Stump11289f42009-09-09 15:08:12 +00006083
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006084 // Okay, if this wasn't a grouping paren, it must be the start of a function
6085 // argument list. Recognize that this declarator will never have an
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006086 // identifier (and remember where it would have been), then call into
6087 // ParseFunctionDeclarator to handle of argument list.
Craig Topper161e4db2014-05-21 06:02:52 +00006088 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006089
David Blaikie15a430a2011-12-04 05:04:18 +00006090 // Enter function-declaration scope, limiting any declarators to the
6091 // function prototype scope, including parameter declarators.
6092 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00006093 Scope::FunctionPrototypeScope | Scope::DeclScope |
6094 (D.isFunctionDeclaratorAFunctionDeclaration()
6095 ? Scope::FunctionDeclarationScope : 0));
Richard Smith943c4402012-07-30 21:30:52 +00006096 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
David Blaikie15a430a2011-12-04 05:04:18 +00006097 PrototypeScope.Exit();
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006098}
6099
6100/// ParseFunctionDeclarator - We are after the identifier and have parsed the
6101/// declarator D up to a paren, which indicates that we are parsing function
6102/// arguments.
Chris Lattneracd58a32006-08-06 17:24:14 +00006103///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006104/// If FirstArgAttrs is non-null, then the caller parsed those arguments
6105/// immediately after the open paren - they should be considered to be the
6106/// first argument of a parameter.
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006107///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006108/// If RequiresArg is true, then the first argument of the function is required
6109/// to be present and required to not be an identifier list.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006110///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006111/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6112/// (C++11) ref-qualifier[opt], exception-specification[opt],
6113/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
6114///
6115/// [C++11] exception-specification:
Douglas Gregor9e66af42011-07-05 16:44:18 +00006116/// dynamic-exception-specification
6117/// noexcept-specification
6118///
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006119void Parser::ParseFunctionDeclarator(Declarator &D,
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006120 ParsedAttributes &FirstArgAttrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006121 BalancedDelimiterTracker &Tracker,
Richard Smith943c4402012-07-30 21:30:52 +00006122 bool IsAmbiguous,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006123 bool RequiresArg) {
Chad Rosierc1183952012-06-26 22:30:43 +00006124 assert(getCurScope()->isFunctionPrototypeScope() &&
David Blaikie15a430a2011-12-04 05:04:18 +00006125 "Should call from a Function scope");
Douglas Gregor9e66af42011-07-05 16:44:18 +00006126 // lparen is already consumed!
6127 assert(D.isPastIdentifier() && "Should not call before identifier!");
6128
6129 // This should be true when the function has typed arguments.
6130 // Otherwise, it is treated as a K&R-style function.
6131 bool HasProto = false;
6132 // Build up an array of information about the parsed arguments.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006133 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006134 // Remember where we see an ellipsis, if any.
6135 SourceLocation EllipsisLoc;
6136
6137 DeclSpec DS(AttrFactory);
6138 bool RefQualifierIsLValueRef = true;
6139 SourceLocation RefQualifierLoc;
6140 ExceptionSpecificationType ESpecType = EST_None;
6141 SourceRange ESpecRange;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006142 SmallVector<ParsedType, 2> DynamicExceptions;
6143 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006144 ExprResult NoexceptExpr;
Hans Wennborgdcfba332015-10-06 23:40:43 +00006145 CachedTokens *ExceptionSpecTokens = nullptr;
Aaron Ballman606093a2017-10-15 15:01:42 +00006146 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith700537c2012-06-12 01:51:59 +00006147 TypeResult TrailingReturnType;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006148
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006149 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6150 EndLoc is the end location for the function declarator.
6151 They differ for trailing return types. */
6152 SourceLocation StartLoc, LocalEndLoc, EndLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006153 SourceLocation LParenLoc, RParenLoc;
6154 LParenLoc = Tracker.getOpenLocation();
6155 StartLoc = LParenLoc;
6156
Douglas Gregor9e66af42011-07-05 16:44:18 +00006157 if (isFunctionDeclaratorIdentifierList()) {
6158 if (RequiresArg)
6159 Diag(Tok, diag::err_argument_required_after_attribute);
6160
6161 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6162
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006163 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006164 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006165 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006166 EndLoc = RParenLoc;
Aaron Ballman606093a2017-10-15 15:01:42 +00006167
Fangrui Song6907ce22018-07-30 19:24:48 +00006168 // If there are attributes following the identifier list, parse them and
Aaron Ballman606093a2017-10-15 15:01:42 +00006169 // prohibit them.
6170 MaybeParseCXX11Attributes(FnAttrs);
6171 ProhibitAttributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006172 } else {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006173 if (Tok.isNot(tok::r_paren))
Fangrui Song6907ce22018-07-30 19:24:48 +00006174 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
Faisal Vali2b391ab2013-09-26 19:54:12 +00006175 EllipsisLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006176 else if (RequiresArg)
6177 Diag(Tok, diag::err_argument_required_after_attribute);
6178
Alexey Bader1f277942017-10-11 11:16:31 +00006179 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6180 || getLangOpts().OpenCL;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006181
6182 // If we have the closing ')', eat it.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006183 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006184 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006185 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006186 EndLoc = RParenLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006187
David Blaikiebbafb8a2012-03-11 07:00:24 +00006188 if (getLangOpts().CPlusPlus) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006189 // FIXME: Accept these components in any order, and produce fixits to
6190 // correct the order if the user gets it wrong. Ideally we should deal
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00006191 // with the pure-specifier in the same way.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006192
6193 // Parse cv-qualifier-seq[opt].
Aaron Ballman08b06592014-07-22 12:44:22 +00006194 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
Alex Lorenz8f4d3992017-02-13 23:19:40 +00006195 /*AtomicAllowed*/ false,
6196 /*IdentifierRequired=*/false,
6197 llvm::function_ref<void()>([&]() {
6198 Actions.CodeCompleteFunctionQualifiers(DS, D);
6199 }));
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006200 if (!DS.getSourceRange().getEnd().isInvalid()) {
6201 EndLoc = DS.getSourceRange().getEnd();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006202 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006203
6204 // Parse ref-qualifier[opt].
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006205 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
Douglas Gregor9e66af42011-07-05 16:44:18 +00006206 EndLoc = RefQualifierLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006207
Douglas Gregor3024f072012-04-16 07:05:22 +00006208 // C++11 [expr.prim.general]p3:
Chad Rosierc1183952012-06-26 22:30:43 +00006209 // If a declaration declares a member function or member function
6210 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00006211 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Chad Rosierc1183952012-06-26 22:30:43 +00006212 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00006213 // declarator.
Richard Smithad1bbb92013-03-15 00:41:52 +00006214 // FIXME: currently, "static" case isn't handled correctly.
Chad Rosierc1183952012-06-26 22:30:43 +00006215 bool IsCXX11MemberFunction =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006216 getLangOpts().CPlusPlus11 &&
Richard Smith990a6922014-01-17 21:01:18 +00006217 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
Faisal Vali421b2d12017-12-29 05:41:00 +00006218 (D.getContext() == DeclaratorContext::MemberContext
Richard Smithad1bbb92013-03-15 00:41:52 +00006219 ? !D.getDeclSpec().isFriendSpecified()
Faisal Vali421b2d12017-12-29 05:41:00 +00006220 : D.getContext() == DeclaratorContext::FileContext &&
Richard Smithad1bbb92013-03-15 00:41:52 +00006221 D.getCXXScopeSpec().isValid() &&
6222 Actions.CurContext->isRecord());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006223
6224 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6225 if (D.getDeclSpec().isConstexprSpecified() && !getLangOpts().CPlusPlus14)
6226 Q.addConst();
Anastasia Stulova5cffa452019-01-21 16:01:38 +00006227 // FIXME: Collect C++ address spaces.
6228 // If there are multiple different address spaces, the source is invalid.
6229 // Carry on using the first addr space for the qualifiers of 'this'.
6230 // The diagnostic will be given later while creating the function
6231 // prototype for the method.
6232 if (getLangOpts().OpenCLCPlusPlus) {
6233 for (ParsedAttr &attr : DS.getAttributes()) {
6234 LangAS ASIdx = attr.asOpenCLLangAS();
6235 if (ASIdx != LangAS::Default) {
6236 Q.addAddressSpace(ASIdx);
6237 break;
6238 }
6239 }
6240 }
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006241
6242 Sema::CXXThisScopeRAII ThisScope(
6243 Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6244 IsCXX11MemberFunction);
Richard Smith2331bbf2012-05-02 22:22:32 +00006245
Douglas Gregor9e66af42011-07-05 16:44:18 +00006246 // Parse exception-specification[opt].
Richard Smith0b3a4622014-11-13 20:01:57 +00006247 bool Delayed = D.isFirstDeclarationOfMember() &&
Richard Smith3ef3e892014-11-20 22:32:11 +00006248 D.isFunctionDeclaratorAFunctionDeclaration();
6249 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6250 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6251 GetLookAheadToken(1).is(tok::l_paren) &&
6252 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6253 GetLookAheadToken(3).is(tok::l_paren) &&
6254 GetLookAheadToken(4).is(tok::identifier) &&
6255 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6256 // HACK: We've got an exception-specification
6257 // noexcept(noexcept(swap(...)))
6258 // or
6259 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6260 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6261 // for 'swap' will only find the function we're currently declaring,
6262 // whereas it expects to find a non-member swap through ADL. Turn off
6263 // delayed parsing to give it a chance to find what it expects.
6264 Delayed = false;
6265 }
Richard Smith0b3a4622014-11-13 20:01:57 +00006266 ESpecType = tryParseExceptionSpecification(Delayed,
6267 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00006268 DynamicExceptions,
6269 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00006270 NoexceptExpr,
6271 ExceptionSpecTokens);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006272 if (ESpecType != EST_None)
6273 EndLoc = ESpecRange.getEnd();
6274
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006275 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6276 // after the exception-specification.
Richard Smith89645bc2013-01-02 12:01:23 +00006277 MaybeParseCXX11Attributes(FnAttrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006278
Douglas Gregor9e66af42011-07-05 16:44:18 +00006279 // Parse trailing-return-type[opt].
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006280 LocalEndLoc = EndLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006281 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00006282 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
Faisal Vali090da2d2018-01-01 18:23:28 +00006283 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006284 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006285 LocalEndLoc = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00006286 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00006287 TrailingReturnType =
6288 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006289 EndLoc = Range.getEnd();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006290 }
Aaron Ballman606093a2017-10-15 15:01:42 +00006291 } else if (standardAttributesAllowed()) {
6292 MaybeParseCXX11Attributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006293 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006294 }
6295
Reid Kleckner078aea92016-12-09 17:14:05 +00006296 // Collect non-parameter declarations from the prototype if this is a function
6297 // declaration. They will be moved into the scope of the function. Only do
6298 // this in C and not C++, where the decls will continue to live in the
6299 // surrounding context.
6300 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6301 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6302 !getLangOpts().CPlusPlus) {
6303 for (Decl *D : getCurScope()->decls()) {
6304 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6305 if (!ND || isa<ParmVarDecl>(ND))
6306 continue;
6307 DeclsInPrototype.push_back(ND);
6308 }
6309 }
6310
Douglas Gregor9e66af42011-07-05 16:44:18 +00006311 // Remember that we parsed a function type, and remember the attributes.
Erich Keanec480f302018-07-12 21:09:05 +00006312 D.AddTypeInfo(DeclaratorChunk::getFunction(
6313 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6314 ParamInfo.size(), EllipsisLoc, RParenLoc,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00006315 RefQualifierIsLValueRef, RefQualifierLoc,
6316 /*MutableLoc=*/SourceLocation(),
6317 ESpecType, ESpecRange, DynamicExceptions.data(),
6318 DynamicExceptionRanges.data(), DynamicExceptions.size(),
Erich Keanec480f302018-07-12 21:09:05 +00006319 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6320 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00006321 LocalEndLoc, D, TrailingReturnType, &DS),
Erich Keanec480f302018-07-12 21:09:05 +00006322 std::move(FnAttrs), EndLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006323}
6324
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006325/// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6326/// true if a ref-qualifier is found.
6327bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6328 SourceLocation &RefQualifierLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00006329 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006330 Diag(Tok, getLangOpts().CPlusPlus11 ?
6331 diag::warn_cxx98_compat_ref_qualifier :
6332 diag::ext_ref_qualifier);
6333
6334 RefQualifierIsLValueRef = Tok.is(tok::amp);
6335 RefQualifierLoc = ConsumeToken();
6336 return true;
6337 }
6338 return false;
6339}
6340
Douglas Gregor9e66af42011-07-05 16:44:18 +00006341/// isFunctionDeclaratorIdentifierList - This parameter list may have an
6342/// identifier list form for a K&R-style function: void foo(a,b,c)
6343///
6344/// Note that identifier-lists are only allowed for normal declarators, not for
6345/// abstract-declarators.
6346bool Parser::isFunctionDeclaratorIdentifierList() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006347 return !getLangOpts().CPlusPlus
Douglas Gregor9e66af42011-07-05 16:44:18 +00006348 && Tok.is(tok::identifier)
6349 && !TryAltiVecVectorToken()
6350 // K&R identifier lists can't have typedefs as identifiers, per C99
6351 // 6.7.5.3p11.
6352 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6353 // Identifier lists follow a really simple grammar: the identifiers can
6354 // be followed *only* by a ", identifier" or ")". However, K&R
6355 // identifier lists are really rare in the brave new modern world, and
6356 // it is very common for someone to typo a type in a non-K&R style
6357 // list. If we are presented with something like: "void foo(intptr x,
6358 // float y)", we don't want to start parsing the function declarator as
6359 // though it is a K&R style declarator just because intptr is an
6360 // invalid type.
6361 //
6362 // To handle this, we check to see if the token after the first
6363 // identifier is a "," or ")". Only then do we parse it as an
6364 // identifier list.
Bruno Cardoso Lopes218c8742016-09-13 20:04:35 +00006365 && (!Tok.is(tok::eof) &&
6366 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006367}
6368
6369/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6370/// we found a K&R-style identifier list instead of a typed parameter list.
6371///
6372/// After returning, ParamInfo will hold the parsed parameters.
6373///
6374/// identifier-list: [C99 6.7.5]
6375/// identifier
6376/// identifier-list ',' identifier
6377///
6378void Parser::ParseFunctionDeclaratorIdentifierList(
6379 Declarator &D,
Craig Topper5603df42013-07-05 19:34:19 +00006380 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006381 // If there was no identifier specified for the declarator, either we are in
6382 // an abstract-declarator, or we are in a parameter declarator which was found
6383 // to be abstract. In abstract-declarators, identifier lists are not valid:
6384 // diagnose this.
6385 if (!D.getIdentifier())
6386 Diag(Tok, diag::ext_ident_list_in_param);
6387
6388 // Maintain an efficient lookup of params we have seen so far.
6389 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6390
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006391 do {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006392 // If this isn't an identifier, report the error and skip until ')'.
6393 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00006394 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00006395 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006396 // Forget we parsed anything.
6397 ParamInfo.clear();
6398 return;
6399 }
6400
6401 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6402
6403 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6404 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6405 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6406
6407 // Verify that the argument identifier has not already been mentioned.
David Blaikie82e95a32014-11-19 07:49:47 +00006408 if (!ParamsSoFar.insert(ParmII).second) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006409 Diag(Tok, diag::err_param_redefinition) << ParmII;
6410 } else {
6411 // Remember this identifier in ParamInfo.
6412 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6413 Tok.getLocation(),
Craig Topper161e4db2014-05-21 06:02:52 +00006414 nullptr));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006415 }
6416
6417 // Eat the identifier.
6418 ConsumeToken();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006419 // The list continues if we see a comma.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006420 } while (TryConsumeToken(tok::comma));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006421}
6422
6423/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6424/// after the opening parenthesis. This function will not parse a K&R-style
6425/// identifier list.
6426///
Richard Smith2620cd92012-04-11 04:01:28 +00006427/// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6428/// caller parsed those arguments immediately after the open paren - they should
6429/// be considered to be part of the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006430///
6431/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6432/// be the location of the ellipsis, if any was parsed.
6433///
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006434/// parameter-type-list: [C99 6.7.5]
6435/// parameter-list
6436/// parameter-list ',' '...'
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006437/// [C++] parameter-list '...'
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006438///
6439/// parameter-list: [C99 6.7.5]
6440/// parameter-declaration
6441/// parameter-list ',' parameter-declaration
6442///
6443/// parameter-declaration: [C99 6.7.5]
6444/// declaration-specifiers declarator
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006445/// [C++] declaration-specifiers declarator '=' assignment-expression
Sebastian Redldb63af22012-03-14 15:54:00 +00006446/// [C++11] initializer-clause
Chris Lattnere37e2332006-08-15 04:50:22 +00006447/// [GNU] declaration-specifiers declarator attributes
Sebastian Redlf769df52009-03-24 22:27:57 +00006448/// declaration-specifiers abstract-declarator[opt]
6449/// [C++] declaration-specifiers abstract-declarator[opt]
Chris Lattner58258242008-04-10 02:22:51 +00006450/// '=' assignment-expression
Chris Lattnere37e2332006-08-15 04:50:22 +00006451/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
Richard Smith2620cd92012-04-11 04:01:28 +00006452/// [C++11] attribute-specifier-seq parameter-declaration
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006453///
Douglas Gregor9e66af42011-07-05 16:44:18 +00006454void Parser::ParseParameterDeclarationClause(
6455 Declarator &D,
Richard Smith2620cd92012-04-11 04:01:28 +00006456 ParsedAttributes &FirstArgAttrs,
Craig Topper5603df42013-07-05 19:34:19 +00006457 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006458 SourceLocation &EllipsisLoc) {
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006459 do {
6460 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6461 // before deciding this was a parameter-declaration-clause.
6462 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Chris Lattner371ed4e2008-04-06 06:57:35 +00006463 break;
Mike Stump11289f42009-09-09 15:08:12 +00006464
Chris Lattner371ed4e2008-04-06 06:57:35 +00006465 // Parse the declaration-specifiers.
John McCall28a6aea2009-11-04 02:18:39 +00006466 // Just use the ParsingDeclaration "scope" of the declarator.
John McCall084e83d2011-03-24 11:26:52 +00006467 DeclSpec DS(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006468
Richard Smith2620cd92012-04-11 04:01:28 +00006469 // Parse any C++11 attributes.
Richard Smith89645bc2013-01-02 12:01:23 +00006470 MaybeParseCXX11Attributes(DS.getAttributes());
Richard Smith2620cd92012-04-11 04:01:28 +00006471
John McCall53fa7142010-12-24 02:08:15 +00006472 // Skip any Microsoft attributes before a param.
Chad Rosierf8a2e702012-12-20 20:37:53 +00006473 MaybeParseMicrosoftAttributes(DS.getAttributes());
John McCall53fa7142010-12-24 02:08:15 +00006474
6475 SourceLocation DSStart = Tok.getLocation();
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006476
6477 // If the caller parsed attributes for the first argument, add them now.
John McCall53fa7142010-12-24 02:08:15 +00006478 // Take them so that we only apply the attributes to the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006479 // FIXME: If we can leave the attributes in the token stream somehow, we can
Richard Smith2620cd92012-04-11 04:01:28 +00006480 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6481 // too much hassle.
6482 DS.takeAttributesFrom(FirstArgAttrs);
John McCall53fa7142010-12-24 02:08:15 +00006483
Faisal Valia534f072018-04-26 00:42:40 +00006484 ParseDeclarationSpecifiers(DS);
Mike Stump11289f42009-09-09 15:08:12 +00006485
Faisal Vali2b391ab2013-09-26 19:54:12 +00006486
Fangrui Song6907ce22018-07-30 19:24:48 +00006487 // Parse the declarator. This is "PrototypeContext" or
6488 // "LambdaExprParameterContext", because we must accept either
Faisal Vali2b391ab2013-09-26 19:54:12 +00006489 // 'declarator' or 'abstract-declarator' here.
Faisal Vali421b2d12017-12-29 05:41:00 +00006490 Declarator ParmDeclarator(
6491 DS, D.getContext() == DeclaratorContext::LambdaExprContext
6492 ? DeclaratorContext::LambdaExprParameterContext
6493 : DeclaratorContext::PrototypeContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00006494 ParseDeclarator(ParmDeclarator);
Chris Lattner371ed4e2008-04-06 06:57:35 +00006495
6496 // Parse GNU attributes, if present.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006497 MaybeParseGNUAttributes(ParmDeclarator);
Mike Stump11289f42009-09-09 15:08:12 +00006498
Chris Lattner371ed4e2008-04-06 06:57:35 +00006499 // Remember this parsed parameter in ParamInfo.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006500 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
Mike Stump11289f42009-09-09 15:08:12 +00006501
Douglas Gregor4d87df52008-12-16 21:30:33 +00006502 // DefArgToks is used when the parsing of default arguments needs
6503 // to be delayed.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006504 std::unique_ptr<CachedTokens> DefArgToks;
Douglas Gregor4d87df52008-12-16 21:30:33 +00006505
Chris Lattner371ed4e2008-04-06 06:57:35 +00006506 // If no parameter was specified, verify that *something* was specified,
6507 // otherwise we have a missing type and identifier.
Craig Topper161e4db2014-05-21 06:02:52 +00006508 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
Faisal Vali2b391ab2013-09-26 19:54:12 +00006509 ParmDeclarator.getNumTypeObjects() == 0) {
Chris Lattner371ed4e2008-04-06 06:57:35 +00006510 // Completely missing, emit error.
6511 Diag(DSStart, diag::err_missing_param);
6512 } else {
6513 // Otherwise, we have something. Add it and let semantic analysis try
6514 // to grok it and add the result to the ParamInfo we are building.
Mike Stump11289f42009-09-09 15:08:12 +00006515
Richard Smith36ee9fb2014-08-11 23:30:23 +00006516 // Last chance to recover from a misplaced ellipsis in an attempted
6517 // parameter pack declaration.
6518 if (Tok.is(tok::ellipsis) &&
6519 (NextToken().isNot(tok::r_paren) ||
6520 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6521 !Actions.isUnexpandedParameterPackPermitted())) &&
6522 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6523 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6524
Chris Lattner371ed4e2008-04-06 06:57:35 +00006525 // Inform the actions module about the parameter declarator, so it gets
6526 // added to the current scope.
Richard Smith95e1fb02014-08-27 03:23:12 +00006527 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006528 // Parse the default argument, if any. We parse the default
6529 // arguments in all dialects; the semantic analysis in
6530 // ActOnParamDefaultArgument will reject the default argument in
6531 // C.
6532 if (Tok.is(tok::equal)) {
Douglas Gregor58354032008-12-24 00:01:03 +00006533 SourceLocation EqualLoc = Tok.getLocation();
6534
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006535 // Parse the default argument
Faisal Vali421b2d12017-12-29 05:41:00 +00006536 if (D.getContext() == DeclaratorContext::MemberContext) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006537 // If we're inside a class definition, cache the tokens
6538 // corresponding to the default argument. We'll actually parse
6539 // them when we see the end of the class definition.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006540 DefArgToks.reset(new CachedTokens);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006541
David Majnemer906ed272015-01-13 05:28:24 +00006542 SourceLocation ArgStartLoc = NextToken().getLocation();
Richard Smith1fff95c2013-09-12 23:28:08 +00006543 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006544 DefArgToks.reset();
Serge Pavlovb4b35782014-07-22 01:54:49 +00006545 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006546 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006547 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
David Majnemer906ed272015-01-13 05:28:24 +00006548 ArgStartLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006549 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006550 } else {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006551 // Consume the '='.
Douglas Gregor58354032008-12-24 00:01:03 +00006552 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00006553
Chad Rosierc1183952012-06-26 22:30:43 +00006554 // The argument isn't actually potentially evaluated unless it is
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006555 // used.
Faisal Valid143a0c2017-04-01 21:30:49 +00006556 EnterExpressionEvaluationContext Eval(
6557 Actions,
6558 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6559 Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006560
Sebastian Redldb63af22012-03-14 15:54:00 +00006561 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006562 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006563 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +00006564 DefArgResult = ParseBraceInitializer();
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006565 } else
Sebastian Redldb63af22012-03-14 15:54:00 +00006566 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +00006567 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006568 if (DefArgResult.isInvalid()) {
Serge Pavlovb4b35782014-07-22 01:54:49 +00006569 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Alexey Bataevee6507d2013-11-18 08:17:37 +00006570 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006571 } else {
6572 // Inform the actions module about the default argument
6573 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006574 DefArgResult.get());
Douglas Gregor4d87df52008-12-16 21:30:33 +00006575 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006576 }
6577 }
Mike Stump11289f42009-09-09 15:08:12 +00006578
6579 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
Fangrui Song6907ce22018-07-30 19:24:48 +00006580 ParmDeclarator.getIdentifierLoc(),
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006581 Param, std::move(DefArgToks)));
Chris Lattner371ed4e2008-04-06 06:57:35 +00006582 }
6583
Richard Smith36ee9fb2014-08-11 23:30:23 +00006584 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6585 if (!getLangOpts().CPlusPlus) {
6586 // We have ellipsis without a preceding ',', which is ill-formed
6587 // in C. Complain and provide the fix.
6588 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6589 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6590 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6591 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6592 // It looks like this was supposed to be a parameter pack. Warn and
6593 // point out where the ellipsis should have gone.
6594 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6595 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6596 << ParmEllipsis.isValid() << ParmEllipsis;
6597 if (ParmEllipsis.isValid()) {
6598 Diag(ParmEllipsis,
6599 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6600 } else {
6601 Diag(ParmDeclarator.getIdentifierLoc(),
6602 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6603 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6604 "...")
6605 << !ParmDeclarator.hasName();
6606 }
6607 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006608 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
Richard Smith36ee9fb2014-08-11 23:30:23 +00006609 }
6610
6611 // We can't have any more parameters after an ellipsis.
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006612 break;
6613 }
Mike Stump11289f42009-09-09 15:08:12 +00006614
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006615 // If the next token is a comma, consume it and keep reading arguments.
6616 } while (TryConsumeToken(tok::comma));
Chris Lattner6c940e62008-04-06 06:34:08 +00006617}
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006618
Chris Lattnere8074e62006-08-06 18:30:15 +00006619/// [C90] direct-declarator '[' constant-expression[opt] ']'
6620/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6621/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6622/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6623/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006624/// [C++11] direct-declarator '[' constant-expression[opt] ']'
6625/// attribute-specifier-seq[opt]
Chris Lattnere8074e62006-08-06 18:30:15 +00006626void Parser::ParseBracketDeclarator(Declarator &D) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006627 if (CheckProhibitedCXX11Attribute())
6628 return;
6629
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006630 BalancedDelimiterTracker T(*this, tok::l_square);
6631 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00006632
Chris Lattner84a11622008-12-18 07:27:21 +00006633 // C array syntax has many features, but by-far the most common is [] and [4].
6634 // This code does a fast path to handle some of the most obvious cases.
6635 if (Tok.getKind() == tok::r_square) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006636 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006637 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006638 MaybeParseCXX11Attributes(attrs);
Chad Rosierc1183952012-06-26 22:30:43 +00006639
Chris Lattner84a11622008-12-18 07:27:21 +00006640 // Remember that we parsed the empty array type.
Craig Topper161e4db2014-05-21 06:02:52 +00006641 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006642 T.getOpenLocation(),
6643 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006644 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006645 return;
6646 } else if (Tok.getKind() == tok::numeric_constant &&
6647 GetLookAheadToken(1).is(tok::r_square)) {
6648 // [4] is very common. Parse the numeric constant expression.
Richard Smithbcc22fc2012-03-09 08:00:36 +00006649 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
Chris Lattner84a11622008-12-18 07:27:21 +00006650 ConsumeToken();
6651
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006652 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006653 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006654 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006655
Chris Lattner84a11622008-12-18 07:27:21 +00006656 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006657 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006658 T.getOpenLocation(),
6659 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006660 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006661 return;
Benjamin Kramer72dae622016-02-18 15:30:24 +00006662 } else if (Tok.getKind() == tok::code_completion) {
6663 Actions.CodeCompleteBracketDeclarator(getCurScope());
6664 return cutOffParsing();
Chris Lattner84a11622008-12-18 07:27:21 +00006665 }
Mike Stump11289f42009-09-09 15:08:12 +00006666
Chris Lattnere8074e62006-08-06 18:30:15 +00006667 // If valid, this location is the position where we read the 'static' keyword.
6668 SourceLocation StaticLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006669 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006670
Chris Lattnere8074e62006-08-06 18:30:15 +00006671 // If there is a type-qualifier-list, read it now.
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006672 // Type qualifiers in an array subscript are a C99 feature.
John McCall084e83d2011-03-24 11:26:52 +00006673 DeclSpec DS(AttrFactory);
Aaron Ballman08b06592014-07-22 12:44:22 +00006674 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
Mike Stump11289f42009-09-09 15:08:12 +00006675
Chris Lattnere8074e62006-08-06 18:30:15 +00006676 // If we haven't already read 'static', check to see if there is one after the
6677 // type-qualifier-list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006678 if (!StaticLoc.isValid())
6679 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006680
Chris Lattnere8074e62006-08-06 18:30:15 +00006681 // Handle "direct-declarator [ type-qual-list[opt] * ]".
Chris Lattnere8074e62006-08-06 18:30:15 +00006682 bool isStar = false;
John McCalldadc5752010-08-24 06:29:42 +00006683 ExprResult NumElements;
Mike Stump11289f42009-09-09 15:08:12 +00006684
Chris Lattner521ff2b2008-04-06 05:26:30 +00006685 // Handle the case where we have '[*]' as the array size. However, a leading
6686 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
Sylvestre Ledru830885c2012-07-23 08:59:39 +00006687 // the token after the star is a ']'. Since stars in arrays are
Chris Lattner521ff2b2008-04-06 05:26:30 +00006688 // infrequent, use of lookahead is not costly here.
6689 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
Chris Lattnerc439f0d2008-04-06 05:27:21 +00006690 ConsumeToken(); // Eat the '*'.
Chris Lattner1906f802006-08-06 19:14:46 +00006691
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006692 if (StaticLoc.isValid()) {
Chris Lattner521ff2b2008-04-06 05:26:30 +00006693 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006694 StaticLoc = SourceLocation(); // Drop the static.
6695 }
Chris Lattner521ff2b2008-04-06 05:26:30 +00006696 isStar = true;
Chris Lattner76c72282007-10-09 17:33:22 +00006697 } else if (Tok.isNot(tok::r_square)) {
Chris Lattner84a11622008-12-18 07:27:21 +00006698 // Note, in C89, this production uses the constant-expr production instead
6699 // of assignment-expr. The only difference is that assignment-expr allows
6700 // things like '=' and '*='. Sema rejects these in C89 mode because they
6701 // are not i-c-e's, so we don't need to distinguish between the two here.
Mike Stump11289f42009-09-09 15:08:12 +00006702
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006703 // Parse the constant-expression or assignment-expression now (depending
6704 // on dialect).
David Blaikiebbafb8a2012-03-11 07:00:24 +00006705 if (getLangOpts().CPlusPlus) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006706 NumElements = ParseConstantExpression();
Eli Friedmane0afc982012-01-21 01:01:51 +00006707 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00006708 EnterExpressionEvaluationContext Unevaluated(
6709 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Kaelyn Takata15867822014-11-21 18:48:04 +00006710 NumElements =
6711 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Eli Friedmane0afc982012-01-21 01:01:51 +00006712 }
David Majnemerf9834d52014-08-08 07:21:18 +00006713 } else {
6714 if (StaticLoc.isValid()) {
6715 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6716 StaticLoc = SourceLocation(); // Drop the static.
6717 }
Chris Lattner62591722006-08-12 18:40:58 +00006718 }
Mike Stump11289f42009-09-09 15:08:12 +00006719
Chris Lattner62591722006-08-12 18:40:58 +00006720 // If there was an error parsing the assignment-expression, recover.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00006721 if (NumElements.isInvalid()) {
Chris Lattnercd2a8c52009-04-24 22:30:50 +00006722 D.setInvalidType(true);
Chris Lattner62591722006-08-12 18:40:58 +00006723 // If the expression was invalid, skip it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00006724 SkipUntil(tok::r_square, StopAtSemi);
Chris Lattner62591722006-08-12 18:40:58 +00006725 return;
Chris Lattnere8074e62006-08-06 18:30:15 +00006726 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006727
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006728 T.consumeClose();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006729
Jordan Rose303e2f12016-11-10 23:28:17 +00006730 MaybeParseCXX11Attributes(DS.getAttributes());
Alexis Hunt96d5c762009-11-21 08:43:09 +00006731
Chris Lattner84a11622008-12-18 07:27:21 +00006732 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006733 D.AddTypeInfo(
6734 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6735 isStar, NumElements.get(), T.getOpenLocation(),
6736 T.getCloseLocation()),
6737 std::move(DS.getAttributes()), T.getCloseLocation());
Chris Lattnere8074e62006-08-06 18:30:15 +00006738}
6739
Richard Trieuf4b81d02014-06-24 23:14:24 +00006740/// Diagnose brackets before an identifier.
6741void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6742 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6743 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6744
6745 SourceLocation StartBracketLoc = Tok.getLocation();
6746 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6747
6748 while (Tok.is(tok::l_square)) {
6749 ParseBracketDeclarator(TempDeclarator);
6750 }
6751
6752 // Stuff the location of the start of the brackets into the Declarator.
6753 // The diagnostics from ParseDirectDeclarator will make more sense if
6754 // they use this location instead.
6755 if (Tok.is(tok::semi))
6756 D.getName().EndLocation = StartBracketLoc;
6757
6758 SourceLocation SuggestParenLoc = Tok.getLocation();
6759
6760 // Now that the brackets are removed, try parsing the declarator again.
6761 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6762
6763 // Something went wrong parsing the brackets, in which case,
6764 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6765 // one here.
6766 if (TempDeclarator.getNumTypeObjects() == 0)
6767 return;
6768
6769 // Determine if parens will need to be suggested in the diagnostic.
6770 bool NeedParens = false;
6771 if (D.getNumTypeObjects() != 0) {
6772 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6773 case DeclaratorChunk::Pointer:
6774 case DeclaratorChunk::Reference:
6775 case DeclaratorChunk::BlockPointer:
6776 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00006777 case DeclaratorChunk::Pipe:
Richard Trieuf4b81d02014-06-24 23:14:24 +00006778 NeedParens = true;
6779 break;
6780 case DeclaratorChunk::Array:
6781 case DeclaratorChunk::Function:
6782 case DeclaratorChunk::Paren:
6783 break;
6784 }
6785 }
6786
6787 if (NeedParens) {
6788 // Create a DeclaratorChunk for the inserted parens.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006789 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Erich Keanec480f302018-07-12 21:09:05 +00006790 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
Richard Trieuf4b81d02014-06-24 23:14:24 +00006791 SourceLocation());
6792 }
6793
6794 // Adding back the bracket info to the end of the Declarator.
6795 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6796 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
Erich Keanec480f302018-07-12 21:09:05 +00006797 D.AddTypeInfo(Chunk, SourceLocation());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006798 }
6799
6800 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6801 // If parentheses are required, always suggest them.
6802 if (!D.getIdentifier() && !NeedParens)
6803 return;
6804
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006805 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
Richard Trieuf4b81d02014-06-24 23:14:24 +00006806
6807 // Generate the move bracket error message.
6808 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006809 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006810
6811 if (NeedParens) {
6812 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6813 << getLangOpts().CPlusPlus
6814 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6815 << FixItHint::CreateInsertion(EndLoc, ")")
6816 << FixItHint::CreateInsertionFromRange(
6817 EndLoc, CharSourceRange(BracketRange, true))
6818 << FixItHint::CreateRemoval(BracketRange);
6819 } else {
6820 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6821 << getLangOpts().CPlusPlus
6822 << FixItHint::CreateInsertionFromRange(
6823 EndLoc, CharSourceRange(BracketRange, true))
6824 << FixItHint::CreateRemoval(BracketRange);
6825 }
6826}
6827
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006828/// [GNU] typeof-specifier:
6829/// typeof ( expressions )
6830/// typeof ( type-name )
6831/// [GNU/C++] typeof unary-expression
Steve Naroffad373bd2007-07-31 12:34:36 +00006832///
6833void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
Chris Lattner76c72282007-10-09 17:33:22 +00006834 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006835 Token OpTok = Tok;
Steve Naroffad373bd2007-07-31 12:34:36 +00006836 SourceLocation StartLoc = ConsumeToken();
6837
John McCalle8595032010-01-13 20:03:27 +00006838 const bool hasParens = Tok.is(tok::l_paren);
6839
Faisal Valid143a0c2017-04-01 21:30:49 +00006840 EnterExpressionEvaluationContext Unevaluated(
6841 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6842 Sema::ReuseLambdaContextDecl);
Eli Friedmane0afc982012-01-21 01:01:51 +00006843
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006844 bool isCastExpr;
John McCallba7bf592010-08-24 05:47:05 +00006845 ParsedType CastTy;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006846 SourceRange CastRange;
Kaelyn Takata911260742014-12-19 01:28:40 +00006847 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6848 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
John McCalle8595032010-01-13 20:03:27 +00006849 if (hasParens)
6850 DS.setTypeofParensRange(CastRange);
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006851
6852 if (CastRange.getEnd().isInvalid())
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006853 // FIXME: Not accurate, the range gets one token more than it should.
6854 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006855 else
6856 DS.SetRangeEnd(CastRange.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +00006857
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006858 if (isCastExpr) {
6859 if (!CastTy) {
6860 DS.SetTypeSpecError();
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006861 return;
Douglas Gregor220cac52009-02-18 17:45:20 +00006862 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006863
Craig Topper161e4db2014-05-21 06:02:52 +00006864 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006865 unsigned DiagID;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006866 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6867 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006868 DiagID, CastTy,
6869 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006870 Diag(StartLoc, DiagID) << PrevSpec;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006871 return;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006872 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006873
Hiroshi Inoue533777f2017-07-02 06:12:49 +00006874 // If we get here, the operand to the typeof was an expression.
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006875 if (Operand.isInvalid()) {
6876 DS.SetTypeSpecError();
Steve Naroff4bd2f712007-08-02 02:53:48 +00006877 return;
Steve Naroffad373bd2007-07-31 12:34:36 +00006878 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006879
Eli Friedmane0afc982012-01-21 01:01:51 +00006880 // We might need to transform the operand if it is potentially evaluated.
6881 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6882 if (Operand.isInvalid()) {
6883 DS.SetTypeSpecError();
6884 return;
6885 }
6886
Craig Topper161e4db2014-05-21 06:02:52 +00006887 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006888 unsigned DiagID;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006889 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6890 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006891 DiagID, Operand.get(),
6892 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006893 Diag(StartLoc, DiagID) << PrevSpec;
Steve Naroffad373bd2007-07-31 12:34:36 +00006894}
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006895
Benjamin Kramere56f3932011-12-23 17:00:35 +00006896/// [C11] atomic-specifier:
Eli Friedman0dfb8892011-10-06 23:00:33 +00006897/// _Atomic ( type-name )
6898///
6899void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
Richard Smith8e1ac332013-03-28 01:55:44 +00006900 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6901 "Not an atomic specifier");
Eli Friedman0dfb8892011-10-06 23:00:33 +00006902
6903 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006904 BalancedDelimiterTracker T(*this, tok::l_paren);
Richard Smith8e1ac332013-03-28 01:55:44 +00006905 if (T.consumeOpen())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006906 return;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006907
6908 TypeResult Result = ParseTypeName();
6909 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00006910 SkipUntil(tok::r_paren, StopAtSemi);
Eli Friedman0dfb8892011-10-06 23:00:33 +00006911 return;
6912 }
6913
6914 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006915 T.consumeClose();
Eli Friedman0dfb8892011-10-06 23:00:33 +00006916
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006917 if (T.getCloseLocation().isInvalid())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006918 return;
6919
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006920 DS.setTypeofParensRange(T.getRange());
6921 DS.SetRangeEnd(T.getCloseLocation());
Eli Friedman0dfb8892011-10-06 23:00:33 +00006922
Craig Topper161e4db2014-05-21 06:02:52 +00006923 const char *PrevSpec = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006924 unsigned DiagID;
6925 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006926 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006927 Actions.getASTContext().getPrintingPolicy()))
Eli Friedman0dfb8892011-10-06 23:00:33 +00006928 Diag(StartLoc, DiagID) << PrevSpec;
6929}
6930
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006931/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6932/// from TryAltiVecVectorToken.
6933bool Parser::TryAltiVecVectorTokenOutOfLine() {
6934 Token Next = NextToken();
6935 switch (Next.getKind()) {
6936 default: return false;
6937 case tok::kw_short:
6938 case tok::kw_long:
6939 case tok::kw_signed:
6940 case tok::kw_unsigned:
6941 case tok::kw_void:
6942 case tok::kw_char:
6943 case tok::kw_int:
6944 case tok::kw_float:
6945 case tok::kw_double:
6946 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006947 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006948 case tok::kw___pixel:
6949 Tok.setKind(tok::kw___vector);
6950 return true;
6951 case tok::identifier:
6952 if (Next.getIdentifierInfo() == Ident_pixel) {
6953 Tok.setKind(tok::kw___vector);
6954 return true;
6955 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006956 if (Next.getIdentifierInfo() == Ident_bool) {
6957 Tok.setKind(tok::kw___vector);
6958 return true;
6959 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006960 return false;
6961 }
6962}
6963
6964bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6965 const char *&PrevSpec, unsigned &DiagID,
6966 bool &isInvalid) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006967 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006968 if (Tok.getIdentifierInfo() == Ident_vector) {
6969 Token Next = NextToken();
6970 switch (Next.getKind()) {
6971 case tok::kw_short:
6972 case tok::kw_long:
6973 case tok::kw_signed:
6974 case tok::kw_unsigned:
6975 case tok::kw_void:
6976 case tok::kw_char:
6977 case tok::kw_int:
6978 case tok::kw_float:
6979 case tok::kw_double:
6980 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006981 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006982 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006983 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006984 return true;
6985 case tok::identifier:
6986 if (Next.getIdentifierInfo() == Ident_pixel) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006987 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006988 return true;
6989 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006990 if (Next.getIdentifierInfo() == Ident_bool) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006991 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00006992 return true;
6993 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006994 break;
6995 default:
6996 break;
6997 }
Douglas Gregor9938e3b2010-06-16 15:28:57 +00006998 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006999 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007000 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007001 return true;
Bill Schmidt99a084b2013-07-03 20:54:09 +00007002 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
7003 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00007004 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00007005 return true;
Chris Lattner73a9c7d2010-02-28 18:33:55 +00007006 }
7007 return false;
7008}