blob: a3080e64b001ce777cb1468df33c9feaa79136da [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Declaration portions of the Parser interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Parse/Parser.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000014#include "clang/Parse/RAIIObjectsForParser.h"
Erik Verbruggen888d52a2014-01-15 09:15:43 +000015#include "clang/AST/ASTContext.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000016#include "clang/AST/DeclTemplate.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000017#include "clang/AST/PrettyDeclStackTrace.h"
Benjamin Kramerd7d2b1f2012-12-01 16:35:25 +000018#include "clang/Basic/AddressSpaces.h"
Aaron Ballmanfdd783a2014-03-31 18:18:43 +000019#include "clang/Basic/Attributes.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000020#include "clang/Basic/CharInfo.h"
Aaron Ballmanfdd783a2014-03-31 18:18:43 +000021#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Parse/ParseDiagnostic.h"
Kaelyn Uhrain031643e2012-04-26 23:36:17 +000023#include "clang/Sema/Lookup.h"
John McCall8b0666c2010-08-20 18:27:03 +000024#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/Scope.h"
George Burgess IVa19ea342016-11-10 20:43:52 +000026#include "llvm/ADT/Optional.h"
Chris Lattnerad9ac942007-01-23 01:14:52 +000027#include "llvm/ADT/SmallSet.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000028#include "llvm/ADT/SmallString.h"
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +000029#include "llvm/ADT/StringSwitch.h"
Hans Wennborgdcfba332015-10-06 23:40:43 +000030
Chris Lattnerc0acd3d2006-07-31 05:13:43 +000031using namespace clang;
32
33//===----------------------------------------------------------------------===//
34// C99 6.7: Declarations.
35//===----------------------------------------------------------------------===//
36
Chris Lattnerf5fbd792006-08-10 23:56:11 +000037/// ParseTypeName
38/// type-name: [C99 6.7.6]
39/// specifier-qualifier-list abstract-declarator[opt]
Sebastian Redlbd150f42008-11-21 19:14:01 +000040///
41/// Called type-id in C++.
Douglas Gregor205d5e32011-01-31 16:09:46 +000042TypeResult Parser::ParseTypeName(SourceRange *Range,
Faisal Vali421b2d12017-12-29 05:41:00 +000043 DeclaratorContext Context,
Richard Smithcd1c0552011-07-01 19:46:12 +000044 AccessSpecifier AS,
Richard Smith54ecd982013-02-20 19:22:51 +000045 Decl **OwnedType,
46 ParsedAttributes *Attrs) {
Richard Smith62dad822012-03-15 01:02:11 +000047 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
Faisal Vali7db85c52017-12-31 00:06:40 +000048 if (DSC == DeclSpecContext::DSC_normal)
49 DSC = DeclSpecContext::DSC_type_specifier;
Richard Smithbfdb1082012-03-12 08:56:40 +000050
Chris Lattnerf5fbd792006-08-10 23:56:11 +000051 // Parse the common declaration-specifiers piece.
John McCall084e83d2011-03-24 11:26:52 +000052 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +000053 if (Attrs)
Erich Keanec480f302018-07-12 21:09:05 +000054 DS.addAttributes(*Attrs);
Richard Smithbfdb1082012-03-12 08:56:40 +000055 ParseSpecifierQualifierList(DS, AS, DSC);
Richard Smithcd1c0552011-07-01 19:46:12 +000056 if (OwnedType)
Craig Topper161e4db2014-05-21 06:02:52 +000057 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
Sebastian Redld6434562009-05-29 18:02:33 +000058
Chris Lattnerf5fbd792006-08-10 23:56:11 +000059 // Parse the abstract-declarator, if present.
Douglas Gregor205d5e32011-01-31 16:09:46 +000060 Declarator DeclaratorInfo(DS, Context);
Chris Lattnerf5fbd792006-08-10 23:56:11 +000061 ParseDeclarator(DeclaratorInfo);
Sebastian Redld6434562009-05-29 18:02:33 +000062 if (Range)
63 *Range = DeclaratorInfo.getSourceRange();
64
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000065 if (DeclaratorInfo.isInvalidType())
Douglas Gregor220cac52009-02-18 17:45:20 +000066 return true;
67
Douglas Gregor0be31a22010-07-02 17:43:08 +000068 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Chris Lattnerf5fbd792006-08-10 23:56:11 +000069}
70
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071/// Normalizes an attribute name by dropping prefixed and suffixed __.
George Burgess IV779af822017-06-30 22:33:24 +000072static StringRef normalizeAttrName(StringRef Name) {
73 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
74 return Name.drop_front(2).drop_back(2);
75 return Name;
76}
77
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000078/// isAttributeLateParsed - Return true if the attribute has arguments that
79/// require late parsing.
80static bool isAttributeLateParsed(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +000081#define CLANG_ATTR_LATE_PARSED_LIST
George Burgess IV779af822017-06-30 22:33:24 +000082 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +000083#include "clang/Parse/AttrParserStringSwitches.inc"
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000084 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +000085#undef CLANG_ATTR_LATE_PARSED_LIST
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000086}
87
Alexis Hunt96d5c762009-11-21 08:43:09 +000088/// ParseGNUAttributes - Parse a non-empty attributes list.
Chris Lattnerb8cd5c22006-08-15 04:10:46 +000089///
90/// [GNU] attributes:
91/// attribute
92/// attributes attribute
93///
94/// [GNU] attribute:
95/// '__attribute__' '(' '(' attribute-list ')' ')'
96///
97/// [GNU] attribute-list:
98/// attrib
99/// attribute_list ',' attrib
100///
101/// [GNU] attrib:
102/// empty
Steve Naroff0f2fe172007-06-01 17:11:19 +0000103/// attrib-name
104/// attrib-name '(' identifier ')'
105/// attrib-name '(' identifier ',' nonempty-expr-list ')'
106/// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
Chris Lattnerb8cd5c22006-08-15 04:10:46 +0000107///
Steve Naroff0f2fe172007-06-01 17:11:19 +0000108/// [GNU] attrib-name:
109/// identifier
110/// typespec
111/// typequal
112/// storageclass
Mike Stump11289f42009-09-09 15:08:12 +0000113///
Richard Smithf7ca0c02013-09-03 18:57:36 +0000114/// Whether an attribute takes an 'identifier' is determined by the
115/// attrib-name. GCC's behavior here is not worth imitating:
Steve Naroff0f2fe172007-06-01 17:11:19 +0000116///
Richard Smithf7ca0c02013-09-03 18:57:36 +0000117/// * In C mode, if the attribute argument list starts with an identifier
118/// followed by a ',' or an ')', and the identifier doesn't resolve to
119/// a type, it is parsed as an identifier. If the attribute actually
120/// wanted an expression, it's out of luck (but it turns out that no
121/// attributes work that way, because C constant expressions are very
122/// limited).
123/// * In C++ mode, if the attribute argument list starts with an identifier,
124/// and the attribute *wants* an identifier, it is parsed as an identifier.
125/// At block scope, any additional tokens between the identifier and the
126/// ',' or ')' are ignored, otherwise they produce a parse error.
Richard Smithb12bf692011-10-17 21:20:17 +0000127///
Richard Smithf7ca0c02013-09-03 18:57:36 +0000128/// We follow the C++ model, but don't allow junk after the identifier.
John McCall53fa7142010-12-24 02:08:15 +0000129void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000130 SourceLocation *endLoc,
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000131 LateParsedAttrList *LateAttrs,
132 Declarator *D) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000133 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
Mike Stump11289f42009-09-09 15:08:12 +0000134
Chris Lattner76c72282007-10-09 17:33:22 +0000135 while (Tok.is(tok::kw___attribute)) {
Steve Naroff0f2fe172007-06-01 17:11:19 +0000136 ConsumeToken();
137 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
138 "attribute")) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000139 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
John McCall53fa7142010-12-24 02:08:15 +0000140 return;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000141 }
142 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000143 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
John McCall53fa7142010-12-24 02:08:15 +0000144 return;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000145 }
146 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
Alp Toker094e5212014-01-05 03:27:11 +0000147 while (true) {
148 // Allow empty/non-empty attributes. ((__vector_size__(16),,,,))
149 if (TryConsumeToken(tok::comma))
Steve Naroff0f2fe172007-06-01 17:11:19 +0000150 continue;
Alp Toker094e5212014-01-05 03:27:11 +0000151
152 // Expect an identifier or declaration specifier (const, int, etc.)
David Majnemer22fe7712015-01-03 19:41:00 +0000153 if (Tok.isAnnotation())
154 break;
155 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
156 if (!AttrName)
Alp Toker094e5212014-01-05 03:27:11 +0000157 break;
158
Steve Naroff0f2fe172007-06-01 17:11:19 +0000159 SourceLocation AttrNameLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000160
Alp Toker094e5212014-01-05 03:27:11 +0000161 if (Tok.isNot(tok::l_paren)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000162 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000163 ParsedAttr::AS_GNU);
Alp Toker094e5212014-01-05 03:27:11 +0000164 continue;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000165 }
Alp Toker094e5212014-01-05 03:27:11 +0000166
167 // Handle "parameterized" attributes
168 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000169 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
Erich Keanee891aa92018-07-13 15:07:47 +0000170 SourceLocation(), ParsedAttr::AS_GNU, D);
Alp Toker094e5212014-01-05 03:27:11 +0000171 continue;
172 }
173
174 // Handle attributes with arguments that require late parsing.
175 LateParsedAttribute *LA =
176 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
177 LateAttrs->push_back(LA);
178
179 // Attributes in a class are parsed at the end of the class, along
180 // with other late-parsed declarations.
181 if (!ClassStack.empty() && !LateAttrs->parseSoon())
182 getCurrentClass().LateParsedDeclarations.push_back(LA);
183
George Burgess IVc8b95372017-01-04 22:43:01 +0000184 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
185 // recursively consumes balanced parens.
186 LA->Toks.push_back(Tok);
187 ConsumeParen();
188 // Consume everything up to and including the matching right parens.
189 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
Alp Toker094e5212014-01-05 03:27:11 +0000190
191 Token Eof;
192 Eof.startToken();
193 Eof.setLocation(Tok.getLocation());
194 LA->Toks.push_back(Eof);
Steve Naroff0f2fe172007-06-01 17:11:19 +0000195 }
Alp Toker094e5212014-01-05 03:27:11 +0000196
Alp Toker383d2c42014-01-01 03:08:43 +0000197 if (ExpectAndConsume(tok::r_paren))
Alexey Bataevee6507d2013-11-18 08:17:37 +0000198 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000199 SourceLocation Loc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000200 if (ExpectAndConsume(tok::r_paren))
Alexey Bataevee6507d2013-11-18 08:17:37 +0000201 SkipUntil(tok::r_paren, StopAtSemi);
John McCall53fa7142010-12-24 02:08:15 +0000202 if (endLoc)
203 *endLoc = Loc;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000204 }
Steve Naroff0f2fe172007-06-01 17:11:19 +0000205}
Chris Lattnerf5fbd792006-08-10 23:56:11 +0000206
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000207/// Determine whether the given attribute has an identifier argument.
Aaron Ballman4768b312013-11-04 12:55:56 +0000208static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000209#define CLANG_ATTR_IDENTIFIER_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000210 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000211#include "clang/Parse/AttrParserStringSwitches.inc"
Douglas Gregord2472d42013-05-02 23:25:32 +0000212 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000213#undef CLANG_ATTR_IDENTIFIER_ARG_LIST
Douglas Gregord2472d42013-05-02 23:25:32 +0000214}
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000215
Erich Keane3efe0022018-07-20 14:13:28 +0000216/// Determine whether the given attribute has a variadic identifier argument.
217static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
218#define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
219 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
220#include "clang/Parse/AttrParserStringSwitches.inc"
221 .Default(false);
222#undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
223}
224
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000225/// Determine whether the given attribute treats kw_this as an identifier.
226static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II) {
227#define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
228 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
229#include "clang/Parse/AttrParserStringSwitches.inc"
230 .Default(false);
231#undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
232}
233
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000234/// Determine whether the given attribute parses a type argument.
Aaron Ballman4768b312013-11-04 12:55:56 +0000235static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000236#define CLANG_ATTR_TYPE_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000237 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000238#include "clang/Parse/AttrParserStringSwitches.inc"
Aaron Ballman4768b312013-11-04 12:55:56 +0000239 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000240#undef CLANG_ATTR_TYPE_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000241}
242
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000243/// Determine whether the given attribute requires parsing its arguments
Aaron Ballman15b27b92014-01-09 19:39:35 +0000244/// in an unevaluated context or not.
245static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000246#define CLANG_ATTR_ARG_CONTEXT_LIST
Aaron Ballman15b27b92014-01-09 19:39:35 +0000247 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000248#include "clang/Parse/AttrParserStringSwitches.inc"
Aaron Ballman15b27b92014-01-09 19:39:35 +0000249 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000250#undef CLANG_ATTR_ARG_CONTEXT_LIST
Aaron Ballman15b27b92014-01-09 19:39:35 +0000251}
252
Richard Smithfeefaf52013-09-03 18:01:40 +0000253IdentifierLoc *Parser::ParseIdentifierLoc() {
254 assert(Tok.is(tok::identifier) && "expected an identifier");
255 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
256 Tok.getLocation(),
257 Tok.getIdentifierInfo());
258 ConsumeToken();
259 return IL;
260}
261
Richard Smithb1f9a282013-10-31 01:56:18 +0000262void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
263 SourceLocation AttrNameLoc,
264 ParsedAttributes &Attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000265 SourceLocation *EndLoc,
266 IdentifierInfo *ScopeName,
267 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000268 ParsedAttr::Syntax Syntax) {
Richard Smithb1f9a282013-10-31 01:56:18 +0000269 BalancedDelimiterTracker Parens(*this, tok::l_paren);
270 Parens.consumeOpen();
271
272 TypeResult T;
273 if (Tok.isNot(tok::r_paren))
274 T = ParseTypeName();
275
276 if (Parens.consumeClose())
277 return;
278
279 if (T.isInvalid())
280 return;
281
282 if (T.isUsable())
283 Attrs.addNewTypeAttr(&AttrName,
Craig Topper161e4db2014-05-21 06:02:52 +0000284 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000285 ScopeName, ScopeLoc, T.get(), Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000286 else
287 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000288 ScopeName, ScopeLoc, nullptr, 0, Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000289}
290
Aaron Ballman35f94212014-04-14 16:03:22 +0000291unsigned Parser::ParseAttributeArgsCommon(
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000292 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
293 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +0000294 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000295 // Ignore the left paren location for now.
296 ConsumeParen();
297
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000298 bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
299
300 // Interpret "kw_this" as an identifier if the attributed requests it.
301 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
302 Tok.setKind(tok::identifier);
303
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000304 ArgsVector ArgExprs;
305 if (Tok.is(tok::identifier)) {
306 // If this attribute wants an 'identifier' argument, make it so.
Erich Keane3efe0022018-07-20 14:13:28 +0000307 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
308 attributeHasVariadicIdentifierArg(*AttrName);
Erich Keanee891aa92018-07-13 15:07:47 +0000309 ParsedAttr::Kind AttrKind =
310 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000311
312 // If we don't know how to parse this attribute, but this is the only
313 // token in this argument, assume it's meant to be an identifier.
Erich Keanee891aa92018-07-13 15:07:47 +0000314 if (AttrKind == ParsedAttr::UnknownAttribute ||
315 AttrKind == ParsedAttr::IgnoredAttribute) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000316 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000317 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000318 }
319
320 if (IsIdentifierArg)
321 ArgExprs.push_back(ParseIdentifierLoc());
322 }
323
324 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
325 // Eat the comma.
326 if (!ArgExprs.empty())
327 ConsumeToken();
328
329 // Parse the non-empty comma-separated list of expressions.
330 do {
Johannes Doerfertac991bb2019-01-19 05:36:54 +0000331 // Interpret "kw_this" as an identifier if the attributed requests it.
332 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
333 Tok.setKind(tok::identifier);
334
Erich Keane3efe0022018-07-20 14:13:28 +0000335 ExprResult ArgExpr;
336 if (Tok.is(tok::identifier) &&
337 attributeHasVariadicIdentifierArg(*AttrName)) {
338 ArgExprs.push_back(ParseIdentifierLoc());
339 } else {
340 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
341 EnterExpressionEvaluationContext Unevaluated(
342 Actions,
343 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
344 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000345
Erich Keane3efe0022018-07-20 14:13:28 +0000346 ExprResult ArgExpr(
347 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
348 if (ArgExpr.isInvalid()) {
349 SkipUntil(tok::r_paren, StopAtSemi);
350 return 0;
351 }
352 ArgExprs.push_back(ArgExpr.get());
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000353 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000354 // Eat the comma, move to the next argument
355 } while (TryConsumeToken(tok::comma));
356 }
357
358 SourceLocation RParen = Tok.getLocation();
359 if (!ExpectAndConsume(tok::r_paren)) {
360 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
361 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
362 ArgExprs.data(), ArgExprs.size(), Syntax);
363 }
364
365 if (EndLoc)
366 *EndLoc = RParen;
Aaron Ballman35f94212014-04-14 16:03:22 +0000367
368 return static_cast<unsigned>(ArgExprs.size());
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000369}
370
Michael Han23214e52012-10-03 01:56:22 +0000371/// Parse the arguments to a parameterized GNU attribute or
372/// a C++11 attribute in "gnu" namespace.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000373void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
374 SourceLocation AttrNameLoc,
375 ParsedAttributes &Attrs,
Michael Han23214e52012-10-03 01:56:22 +0000376 SourceLocation *EndLoc,
377 IdentifierInfo *ScopeName,
378 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000379 ParsedAttr::Syntax Syntax,
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000380 Declarator *D) {
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000381
382 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
383
Erich Keanee891aa92018-07-13 15:07:47 +0000384 ParsedAttr::Kind AttrKind =
385 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Richard Smith66e71682013-10-24 01:07:54 +0000386
Erich Keanee891aa92018-07-13 15:07:47 +0000387 if (AttrKind == ParsedAttr::AT_Availability) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000388 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
389 ScopeLoc, Syntax);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000390 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000391 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000392 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
393 ScopeName, ScopeLoc, Syntax);
394 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000395 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000396 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
397 ScopeName, ScopeLoc, Syntax);
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +0000398 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000399 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000400 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
401 ScopeName, ScopeLoc, Syntax);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000402 return;
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000403 } else if (attributeIsTypeArgAttr(*AttrName)) {
404 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
405 ScopeLoc, Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000406 return;
407 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000408
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000409 // These may refer to the function arguments, but need to be parsed early to
410 // participate in determining whether it's a redeclaration.
George Burgess IVa19ea342016-11-10 20:43:52 +0000411 llvm::Optional<ParseScope> PrototypeScope;
Ulrich Weigandef5aa292015-07-13 14:13:01 +0000412 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
413 D && D->isFunctionDeclarator()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000414 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
George Burgess IVa19ea342016-11-10 20:43:52 +0000415 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
416 Scope::FunctionDeclarationScope |
417 Scope::DeclScope);
Alp Tokerc5350722014-02-26 22:27:52 +0000418 for (unsigned i = 0; i != FTI.NumParams; ++i) {
419 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000420 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
421 }
422 }
423
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000424 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
425 ScopeLoc, Syntax);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000426}
427
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000428unsigned Parser::ParseClangAttributeArgs(
429 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
430 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +0000431 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000432 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
433
Erich Keanee891aa92018-07-13 15:07:47 +0000434 ParsedAttr::Kind AttrKind =
435 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000436
Aaron Ballman38bbc162018-02-24 17:16:42 +0000437 switch (AttrKind) {
438 default:
439 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
440 ScopeName, ScopeLoc, Syntax);
Erich Keanee891aa92018-07-13 15:07:47 +0000441 case ParsedAttr::AT_ExternalSourceSymbol:
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000442 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
443 ScopeName, ScopeLoc, Syntax);
Aaron Ballman38bbc162018-02-24 17:16:42 +0000444 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000445 case ParsedAttr::AT_Availability:
Aaron Ballman38bbc162018-02-24 17:16:42 +0000446 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
447 ScopeLoc, Syntax);
448 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000449 case ParsedAttr::AT_ObjCBridgeRelated:
Aaron Ballmanc248b0f2018-02-24 17:37:37 +0000450 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
451 ScopeName, ScopeLoc, Syntax);
452 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000453 case ParsedAttr::AT_TypeTagForDatatype:
Aaron Ballmana26d8ee2018-02-25 14:01:04 +0000454 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
455 ScopeName, ScopeLoc, Syntax);
456 break;
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000457 }
Erich Keanec480f302018-07-12 21:09:05 +0000458 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000459}
460
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000461bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
462 SourceLocation AttrNameLoc,
463 ParsedAttributes &Attrs) {
464 // If the attribute isn't known, we will not attempt to parse any
465 // arguments.
466 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
Bob Wilson7c730832015-07-20 22:57:31 +0000467 getTargetInfo(), getLangOpts())) {
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000468 // Eat the left paren, then skip to the ending right paren.
469 ConsumeParen();
470 SkipUntil(tok::r_paren);
471 return false;
Aaron Ballman478faed2012-06-19 22:09:27 +0000472 }
Aaron Ballman478faed2012-06-19 22:09:27 +0000473
Aaron Ballman95d57032014-04-14 16:44:26 +0000474 SourceLocation OpenParenLoc = Tok.getLocation();
475
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000476 if (AttrName->getName() == "property") {
Aaron Ballman478faed2012-06-19 22:09:27 +0000477 // The property declspec is more complex in that it can take one or two
Chad Rosierc1183952012-06-26 22:30:43 +0000478 // assignment expressions as a parameter, but the lhs of the assignment
Aaron Ballman478faed2012-06-19 22:09:27 +0000479 // must be named get or put.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000480
John McCall5e77d762013-04-16 07:28:30 +0000481 BalancedDelimiterTracker T(*this, tok::l_paren);
482 T.expectAndConsume(diag::err_expected_lparen_after,
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000483 AttrName->getNameStart(), tok::r_paren);
John McCall5e77d762013-04-16 07:28:30 +0000484
485 enum AccessorKind {
486 AK_Invalid = -1,
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000487 AK_Put = 0,
488 AK_Get = 1 // indices into AccessorNames
John McCall5e77d762013-04-16 07:28:30 +0000489 };
Craig Topper161e4db2014-05-21 06:02:52 +0000490 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
John McCall5e77d762013-04-16 07:28:30 +0000491 bool HasInvalidAccessor = false;
492
493 // Parse the accessor specifications.
494 while (true) {
495 // Stop if this doesn't look like an accessor spec.
496 if (!Tok.is(tok::identifier)) {
497 // If the user wrote a completely empty list, use a special diagnostic.
498 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
Craig Topper161e4db2014-05-21 06:02:52 +0000499 AccessorNames[AK_Put] == nullptr &&
500 AccessorNames[AK_Get] == nullptr) {
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000501 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
John McCall5e77d762013-04-16 07:28:30 +0000502 break;
503 }
504
505 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
506 break;
507 }
508
509 AccessorKind Kind;
510 SourceLocation KindLoc = Tok.getLocation();
511 StringRef KindStr = Tok.getIdentifierInfo()->getName();
512 if (KindStr == "get") {
513 Kind = AK_Get;
514 } else if (KindStr == "put") {
515 Kind = AK_Put;
516
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000517 // Recover from the common mistake of using 'set' instead of 'put'.
John McCall5e77d762013-04-16 07:28:30 +0000518 } else if (KindStr == "set") {
519 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000520 << FixItHint::CreateReplacement(KindLoc, "put");
John McCall5e77d762013-04-16 07:28:30 +0000521 Kind = AK_Put;
522
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000523 // Handle the mistake of forgetting the accessor kind by skipping
524 // this accessor.
John McCall5e77d762013-04-16 07:28:30 +0000525 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
526 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
527 ConsumeToken();
528 HasInvalidAccessor = true;
529 goto next_property_accessor;
530
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000531 // Otherwise, complain about the unknown accessor kind.
John McCall5e77d762013-04-16 07:28:30 +0000532 } else {
533 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
534 HasInvalidAccessor = true;
535 Kind = AK_Invalid;
536
537 // Try to keep parsing unless it doesn't look like an accessor spec.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000538 if (!NextToken().is(tok::equal))
539 break;
John McCall5e77d762013-04-16 07:28:30 +0000540 }
541
542 // Consume the identifier.
543 ConsumeToken();
544
545 // Consume the '='.
Alp Toker8fbec672013-12-17 23:29:36 +0000546 if (!TryConsumeToken(tok::equal)) {
John McCall5e77d762013-04-16 07:28:30 +0000547 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000548 << KindStr;
John McCall5e77d762013-04-16 07:28:30 +0000549 break;
550 }
551
552 // Expect the method name.
553 if (!Tok.is(tok::identifier)) {
554 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
555 break;
556 }
557
558 if (Kind == AK_Invalid) {
559 // Just drop invalid accessors.
Craig Topper161e4db2014-05-21 06:02:52 +0000560 } else if (AccessorNames[Kind] != nullptr) {
John McCall5e77d762013-04-16 07:28:30 +0000561 // Complain about the repeated accessor, ignore it, and keep parsing.
562 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
563 } else {
564 AccessorNames[Kind] = Tok.getIdentifierInfo();
565 }
566 ConsumeToken();
567
568 next_property_accessor:
569 // Keep processing accessors until we run out.
Alp Toker094e5212014-01-05 03:27:11 +0000570 if (TryConsumeToken(tok::comma))
John McCall5e77d762013-04-16 07:28:30 +0000571 continue;
572
573 // If we run into the ')', stop without consuming it.
Alp Toker094e5212014-01-05 03:27:11 +0000574 if (Tok.is(tok::r_paren))
John McCall5e77d762013-04-16 07:28:30 +0000575 break;
Alp Toker094e5212014-01-05 03:27:11 +0000576
577 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
578 break;
John McCall5e77d762013-04-16 07:28:30 +0000579 }
580
581 // Only add the property attribute if it was well-formed.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000582 if (!HasInvalidAccessor)
Craig Topper161e4db2014-05-21 06:02:52 +0000583 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
John McCall5e77d762013-04-16 07:28:30 +0000584 AccessorNames[AK_Get], AccessorNames[AK_Put],
Erich Keanee891aa92018-07-13 15:07:47 +0000585 ParsedAttr::AS_Declspec);
Aaron Ballman478faed2012-06-19 22:09:27 +0000586 T.skipToEnd();
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000587 return !HasInvalidAccessor;
Aaron Ballman478faed2012-06-19 22:09:27 +0000588 }
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000589
Aaron Ballman95d57032014-04-14 16:44:26 +0000590 unsigned NumArgs =
591 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
Erich Keanee891aa92018-07-13 15:07:47 +0000592 SourceLocation(), ParsedAttr::AS_Declspec);
Aaron Ballman95d57032014-04-14 16:44:26 +0000593
594 // If this attribute's args were parsed, and it was expected to have
595 // arguments but none were provided, emit a diagnostic.
Erich Keanec480f302018-07-12 21:09:05 +0000596 if (!Attrs.empty() && Attrs.begin()->getMaxArgs() && !NumArgs) {
Aaron Ballmanef5d94c2014-04-15 00:36:39 +0000597 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Aaron Ballman95d57032014-04-14 16:44:26 +0000598 return false;
599 }
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000600 return true;
Aaron Ballman478faed2012-06-19 22:09:27 +0000601}
602
Eli Friedman06de2b52009-06-08 07:21:15 +0000603/// [MS] decl-specifier:
604/// __declspec ( extended-decl-modifier-seq )
605///
606/// [MS] extended-decl-modifier-seq:
607/// extended-decl-modifier[opt]
608/// extended-decl-modifier extended-decl-modifier-seq
Aaron Ballman068aa512015-05-20 20:58:33 +0000609void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
610 SourceLocation *End) {
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +0000611 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
Steve Naroff3a9b7e02008-12-24 20:59:21 +0000612 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
Eli Friedman06de2b52009-06-08 07:21:15 +0000613
Aaron Ballman068aa512015-05-20 20:58:33 +0000614 while (Tok.is(tok::kw___declspec)) {
615 ConsumeToken();
616 BalancedDelimiterTracker T(*this, tok::l_paren);
617 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
618 tok::r_paren))
Aaron Ballman478faed2012-06-19 22:09:27 +0000619 return;
Aaron Ballman478faed2012-06-19 22:09:27 +0000620
Aaron Ballman068aa512015-05-20 20:58:33 +0000621 // An empty declspec is perfectly legal and should not warn. Additionally,
622 // you can specify multiple attributes per declspec.
623 while (Tok.isNot(tok::r_paren)) {
624 // Attribute not present.
625 if (TryConsumeToken(tok::comma))
626 continue;
627
628 // We expect either a well-known identifier or a generic string. Anything
629 // else is a malformed declspec.
630 bool IsString = Tok.getKind() == tok::string_literal;
631 if (!IsString && Tok.getKind() != tok::identifier &&
632 Tok.getKind() != tok::kw_restrict) {
633 Diag(Tok, diag::err_ms_declspec_type);
Aaron Ballman478faed2012-06-19 22:09:27 +0000634 T.skipToEnd();
635 return;
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000636 }
Aaron Ballman068aa512015-05-20 20:58:33 +0000637
638 IdentifierInfo *AttrName;
639 SourceLocation AttrNameLoc;
640 if (IsString) {
641 SmallString<8> StrBuffer;
642 bool Invalid = false;
643 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
644 if (Invalid) {
645 T.skipToEnd();
646 return;
647 }
648 AttrName = PP.getIdentifierInfo(Str);
649 AttrNameLoc = ConsumeStringToken();
650 } else {
651 AttrName = Tok.getIdentifierInfo();
652 AttrNameLoc = ConsumeToken();
653 }
654
655 bool AttrHandled = false;
656
657 // Parse attribute arguments.
658 if (Tok.is(tok::l_paren))
659 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
660 else if (AttrName->getName() == "property")
661 // The property attribute must have an argument list.
662 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
663 << AttrName->getName();
664
665 if (!AttrHandled)
666 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000667 ParsedAttr::AS_Declspec);
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000668 }
Aaron Ballman068aa512015-05-20 20:58:33 +0000669 T.consumeClose();
670 if (End)
671 *End = T.getCloseLocation();
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000672 }
Eli Friedman53339e02009-06-08 23:27:34 +0000673}
674
John McCall53fa7142010-12-24 02:08:15 +0000675void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
Eli Friedman53339e02009-06-08 23:27:34 +0000676 // Treat these like attributes
Reid Klecknerd7857f02014-10-24 17:42:17 +0000677 while (true) {
678 switch (Tok.getKind()) {
679 case tok::kw___fastcall:
680 case tok::kw___stdcall:
681 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +0000682 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +0000683 case tok::kw___cdecl:
684 case tok::kw___vectorcall:
685 case tok::kw___ptr64:
686 case tok::kw___w64:
687 case tok::kw___ptr32:
Reid Klecknerd7857f02014-10-24 17:42:17 +0000688 case tok::kw___sptr:
689 case tok::kw___uptr: {
690 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
691 SourceLocation AttrNameLoc = ConsumeToken();
692 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000693 ParsedAttr::AS_Keyword);
Reid Klecknerd7857f02014-10-24 17:42:17 +0000694 break;
695 }
696 default:
697 return;
698 }
Eli Friedman53339e02009-06-08 23:27:34 +0000699 }
Steve Naroff3a9b7e02008-12-24 20:59:21 +0000700}
701
Nico Rieckeaaae272014-12-04 23:31:08 +0000702void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
703 SourceLocation StartLoc = Tok.getLocation();
704 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
705
706 if (EndLoc.isValid()) {
707 SourceRange Range(StartLoc, EndLoc);
708 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
709 }
710}
711
712SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
713 SourceLocation EndLoc;
714
715 while (true) {
716 switch (Tok.getKind()) {
717 case tok::kw_const:
718 case tok::kw_volatile:
719 case tok::kw___fastcall:
720 case tok::kw___stdcall:
721 case tok::kw___thiscall:
722 case tok::kw___cdecl:
723 case tok::kw___vectorcall:
724 case tok::kw___ptr32:
725 case tok::kw___ptr64:
726 case tok::kw___w64:
727 case tok::kw___unaligned:
728 case tok::kw___sptr:
729 case tok::kw___uptr:
730 EndLoc = ConsumeToken();
731 break;
732 default:
733 return EndLoc;
734 }
735 }
736}
737
John McCall53fa7142010-12-24 02:08:15 +0000738void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
Dawn Perchik335e16b2010-09-03 01:29:35 +0000739 // Treat these like attributes
740 while (Tok.is(tok::kw___pascal)) {
741 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
742 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000743 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000744 ParsedAttr::AS_Keyword);
Dawn Perchik335e16b2010-09-03 01:29:35 +0000745 }
John McCall53fa7142010-12-24 02:08:15 +0000746}
747
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +0000748void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000749 // Treat these like attributes
750 while (Tok.is(tok::kw___kernel)) {
Richard Smith0cdcc982013-01-29 01:24:26 +0000751 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000752 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000753 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000754 ParsedAttr::AS_Keyword);
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000755 }
756}
757
Aaron Ballman05d76ea2014-01-14 01:29:54 +0000758void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
759 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
760 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +0000761 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000762 ParsedAttr::AS_Keyword);
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000763}
764
Douglas Gregor261a89b2015-06-19 17:51:05 +0000765void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
766 // Treat these like attributes, even though they're type specifiers.
767 while (true) {
768 switch (Tok.getKind()) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +0000769 case tok::kw__Nonnull:
770 case tok::kw__Nullable:
771 case tok::kw__Null_unspecified: {
Douglas Gregor261a89b2015-06-19 17:51:05 +0000772 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
773 SourceLocation AttrNameLoc = ConsumeToken();
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000774 if (!getLangOpts().ObjC)
Douglas Gregor261a89b2015-06-19 17:51:05 +0000775 Diag(AttrNameLoc, diag::ext_nullability)
776 << AttrName;
Fangrui Song6907ce22018-07-30 19:24:48 +0000777 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000778 ParsedAttr::AS_Keyword);
Douglas Gregor261a89b2015-06-19 17:51:05 +0000779 break;
780 }
781 default:
782 return;
783 }
784 }
785}
786
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000787static bool VersionNumberSeparator(const char Separator) {
788 return (Separator == '.' || Separator == '_');
789}
790
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000791/// Parse a version number.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000792///
793/// version:
794/// simple-integer
Jan Korous23255692018-05-17 11:51:49 +0000795/// simple-integer '.' simple-integer
796/// simple-integer '_' simple-integer
797/// simple-integer '.' simple-integer '.' simple-integer
798/// simple-integer '_' simple-integer '_' simple-integer
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000799VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
Erik Pilkington29099de2016-07-16 00:35:23 +0000800 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000801
802 if (!Tok.is(tok::numeric_constant)) {
803 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000804 SkipUntil(tok::comma, tok::r_paren,
805 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000806 return VersionTuple();
807 }
808
809 // Parse the major (and possibly minor and subminor) versions, which
810 // are stored in the numeric constant. We utilize a quirk of the
811 // lexer, which is that it handles something like 1.2.3 as a single
812 // numeric constant, rather than two separate tokens.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000813 SmallString<512> Buffer;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000814 Buffer.resize(Tok.getLength()+1);
815 const char *ThisTokBegin = &Buffer[0];
816
817 // Get the spelling of the token, which eliminates trigraphs, etc.
818 bool Invalid = false;
819 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
820 if (Invalid)
821 return VersionTuple();
822
823 // Parse the major version.
824 unsigned AfterMajor = 0;
825 unsigned Major = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000826 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000827 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
828 ++AfterMajor;
829 }
830
831 if (AfterMajor == 0) {
832 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000833 SkipUntil(tok::comma, tok::r_paren,
834 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000835 return VersionTuple();
836 }
837
838 if (AfterMajor == ActualLength) {
839 ConsumeToken();
840
841 // We only had a single version component.
842 if (Major == 0) {
843 Diag(Tok, diag::err_zero_version);
844 return VersionTuple();
845 }
846
847 return VersionTuple(Major);
848 }
849
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000850 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
851 if (!VersionNumberSeparator(AfterMajorSeparator)
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000852 || (AfterMajor + 1 == ActualLength)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000853 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000854 SkipUntil(tok::comma, tok::r_paren,
855 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000856 return VersionTuple();
857 }
858
859 // Parse the minor version.
860 unsigned AfterMinor = AfterMajor + 1;
861 unsigned Minor = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000862 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000863 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
864 ++AfterMinor;
865 }
866
867 if (AfterMinor == ActualLength) {
868 ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +0000869
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000870 // We had major.minor.
871 if (Major == 0 && Minor == 0) {
872 Diag(Tok, diag::err_zero_version);
873 return VersionTuple();
874 }
875
Jan Korous23255692018-05-17 11:51:49 +0000876 return VersionTuple(Major, Minor);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000877 }
878
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000879 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000880 // If what follows is not a '.' or '_', we have a problem.
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000881 if (!VersionNumberSeparator(AfterMinorSeparator)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000882 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000883 SkipUntil(tok::comma, tok::r_paren,
884 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Chad Rosierc1183952012-06-26 22:30:43 +0000885 return VersionTuple();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000886 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000887
Fariborz Jahanianb6161612014-10-03 17:21:12 +0000888 // Warn if separators, be it '.' or '_', do not match.
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000889 if (AfterMajorSeparator != AfterMinorSeparator)
890 Diag(Tok, diag::warn_expected_consistent_version_separator);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000891
892 // Parse the subminor version.
893 unsigned AfterSubminor = AfterMinor + 1;
894 unsigned Subminor = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000895 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000896 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
897 ++AfterSubminor;
898 }
899
900 if (AfterSubminor != ActualLength) {
901 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000902 SkipUntil(tok::comma, tok::r_paren,
903 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000904 return VersionTuple();
905 }
906 ConsumeToken();
Jan Korous23255692018-05-17 11:51:49 +0000907 return VersionTuple(Major, Minor, Subminor);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000908}
909
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000910/// Parse the contents of the "availability" attribute.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000911///
912/// availability-attribute:
Manman Ren75bc6762016-03-21 17:30:55 +0000913/// 'availability' '(' platform ',' opt-strict version-arg-list,
914/// opt-replacement, opt-message')'
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000915///
916/// platform:
917/// identifier
918///
Manman Rend8039df2016-02-22 04:47:24 +0000919/// opt-strict:
920/// 'strict' ','
Manman Renb636b902016-02-17 22:05:48 +0000921///
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000922/// version-arg-list:
923/// version-arg
924/// version-arg ',' version-arg-list
925///
926/// version-arg:
927/// 'introduced' '=' version
928/// 'deprecated' '=' version
Douglas Gregorfdd417f2012-03-11 04:53:21 +0000929/// 'obsoleted' = version
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000930/// 'unavailable'
Manman Ren75bc6762016-03-21 17:30:55 +0000931/// opt-replacement:
932/// 'replacement' '=' <string>
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000933/// opt-message:
934/// 'message' '=' <string>
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000935void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
936 SourceLocation AvailabilityLoc,
937 ParsedAttributes &attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000938 SourceLocation *endLoc,
939 IdentifierInfo *ScopeName,
940 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000941 ParsedAttr::Syntax Syntax) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000942 enum { Introduced, Deprecated, Obsoleted, Unknown };
943 AvailabilityChange Changes[Unknown];
Manman Ren75bc6762016-03-21 17:30:55 +0000944 ExprResult MessageExpr, ReplacementExpr;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000945
946 // Opening '('.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000947 BalancedDelimiterTracker T(*this, tok::l_paren);
948 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000949 Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000950 return;
951 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000952
Manman Renb636b902016-02-17 22:05:48 +0000953 // Parse the platform name.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000954 if (Tok.isNot(tok::identifier)) {
955 Diag(Tok, diag::err_availability_expected_platform);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000956 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000957 return;
958 }
Richard Smithfeefaf52013-09-03 18:01:40 +0000959 IdentifierLoc *Platform = ParseIdentifierLoc();
Alex Lorenz0b1ce8b2017-08-15 14:42:01 +0000960 if (const IdentifierInfo *const Ident = Platform->Ident) {
961 // Canonicalize platform name from "macosx" to "macos".
962 if (Ident->getName() == "macosx")
963 Platform->Ident = PP.getIdentifierInfo("macos");
964 // Canonicalize platform name from "macosx_app_extension" to
965 // "macos_app_extension".
966 else if (Ident->getName() == "macosx_app_extension")
967 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
968 else
969 Platform->Ident = PP.getIdentifierInfo(
970 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
971 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000972
973 // Parse the ',' following the platform name.
Alp Toker383d2c42014-01-01 03:08:43 +0000974 if (ExpectAndConsume(tok::comma)) {
975 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000976 return;
Alp Toker383d2c42014-01-01 03:08:43 +0000977 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000978
979 // If we haven't grabbed the pointers for the identifiers
980 // "introduced", "deprecated", and "obsoleted", do so now.
981 if (!Ident_introduced) {
982 Ident_introduced = PP.getIdentifierInfo("introduced");
983 Ident_deprecated = PP.getIdentifierInfo("deprecated");
984 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000985 Ident_unavailable = PP.getIdentifierInfo("unavailable");
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000986 Ident_message = PP.getIdentifierInfo("message");
Manman Rend8039df2016-02-22 04:47:24 +0000987 Ident_strict = PP.getIdentifierInfo("strict");
Manman Ren75bc6762016-03-21 17:30:55 +0000988 Ident_replacement = PP.getIdentifierInfo("replacement");
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000989 }
990
Manman Ren75bc6762016-03-21 17:30:55 +0000991 // Parse the optional "strict", the optional "replacement" and the set of
Manman Renb636b902016-02-17 22:05:48 +0000992 // introductions/deprecations/removals.
Manman Rend8039df2016-02-22 04:47:24 +0000993 SourceLocation UnavailableLoc, StrictLoc;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000994 do {
995 if (Tok.isNot(tok::identifier)) {
996 Diag(Tok, diag::err_availability_expected_change);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000997 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000998 return;
999 }
1000 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1001 SourceLocation KeywordLoc = ConsumeToken();
1002
Manman Rend8039df2016-02-22 04:47:24 +00001003 if (Keyword == Ident_strict) {
1004 if (StrictLoc.isValid()) {
Manman Renb636b902016-02-17 22:05:48 +00001005 Diag(KeywordLoc, diag::err_availability_redundant)
Manman Rend8039df2016-02-22 04:47:24 +00001006 << Keyword << SourceRange(StrictLoc);
Manman Renb636b902016-02-17 22:05:48 +00001007 }
Manman Rend8039df2016-02-22 04:47:24 +00001008 StrictLoc = KeywordLoc;
Manman Renb636b902016-02-17 22:05:48 +00001009 continue;
1010 }
1011
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001012 if (Keyword == Ident_unavailable) {
1013 if (UnavailableLoc.isValid()) {
1014 Diag(KeywordLoc, diag::err_availability_redundant)
1015 << Keyword << SourceRange(UnavailableLoc);
Chad Rosierc1183952012-06-26 22:30:43 +00001016 }
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001017 UnavailableLoc = KeywordLoc;
Alp Toker97650562014-01-10 11:19:30 +00001018 continue;
Chad Rosierc1183952012-06-26 22:30:43 +00001019 }
1020
Michael Wu260e9622018-11-12 02:44:33 +00001021 if (Keyword == Ident_deprecated && Platform->Ident &&
1022 Platform->Ident->isStr("swift")) {
1023 // For swift, we deprecate for all versions.
1024 if (Changes[Deprecated].KeywordLoc.isValid()) {
1025 Diag(KeywordLoc, diag::err_availability_redundant)
1026 << Keyword
1027 << SourceRange(Changes[Deprecated].KeywordLoc);
1028 }
1029
1030 Changes[Deprecated].KeywordLoc = KeywordLoc;
1031 // Use a fake version here.
1032 Changes[Deprecated].Version = VersionTuple(1);
1033 continue;
1034 }
1035
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001036 if (Tok.isNot(tok::equal)) {
Alp Tokerec543272013-12-24 09:48:30 +00001037 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001038 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001039 return;
1040 }
1041 ConsumeToken();
Manman Ren75bc6762016-03-21 17:30:55 +00001042 if (Keyword == Ident_message || Keyword == Ident_replacement) {
David Majnemer2e498302014-07-18 05:43:12 +00001043 if (Tok.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001044 Diag(Tok, diag::err_expected_string_literal)
1045 << /*Source='availability attribute'*/2;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001046 SkipUntil(tok::r_paren, StopAtSemi);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001047 return;
1048 }
Manman Ren75bc6762016-03-21 17:30:55 +00001049 if (Keyword == Ident_message)
1050 MessageExpr = ParseStringLiteralExpression();
1051 else
1052 ReplacementExpr = ParseStringLiteralExpression();
David Majnemer2e498302014-07-18 05:43:12 +00001053 // Also reject wide string literals.
1054 if (StringLiteral *MessageStringLiteral =
1055 cast_or_null<StringLiteral>(MessageExpr.get())) {
1056 if (MessageStringLiteral->getCharByteWidth() != 1) {
1057 Diag(MessageStringLiteral->getSourceRange().getBegin(),
1058 diag::err_expected_string_literal)
1059 << /*Source='availability attribute'*/ 2;
1060 SkipUntil(tok::r_paren, StopAtSemi);
1061 return;
1062 }
1063 }
Manman Ren75bc6762016-03-21 17:30:55 +00001064 if (Keyword == Ident_message)
1065 break;
1066 else
1067 continue;
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001068 }
Chad Rosierc1183952012-06-26 22:30:43 +00001069
Fariborz Jahanian5a29e6a2014-11-05 23:58:55 +00001070 // Special handling of 'NA' only when applied to introduced or
1071 // deprecated.
1072 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1073 Tok.is(tok::identifier)) {
1074 IdentifierInfo *NA = Tok.getIdentifierInfo();
1075 if (NA->getName() == "NA") {
1076 ConsumeToken();
1077 if (Keyword == Ident_introduced)
1078 UnavailableLoc = KeywordLoc;
1079 continue;
1080 }
1081 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001082
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001083 SourceRange VersionRange;
1084 VersionTuple Version = ParseVersionTuple(VersionRange);
Chad Rosierc1183952012-06-26 22:30:43 +00001085
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001086 if (Version.empty()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001087 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001088 return;
1089 }
1090
1091 unsigned Index;
1092 if (Keyword == Ident_introduced)
1093 Index = Introduced;
1094 else if (Keyword == Ident_deprecated)
1095 Index = Deprecated;
1096 else if (Keyword == Ident_obsoleted)
1097 Index = Obsoleted;
Chad Rosierc1183952012-06-26 22:30:43 +00001098 else
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001099 Index = Unknown;
1100
1101 if (Index < Unknown) {
1102 if (!Changes[Index].KeywordLoc.isInvalid()) {
1103 Diag(KeywordLoc, diag::err_availability_redundant)
Chad Rosierc1183952012-06-26 22:30:43 +00001104 << Keyword
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001105 << SourceRange(Changes[Index].KeywordLoc,
1106 Changes[Index].VersionRange.getEnd());
1107 }
1108
1109 Changes[Index].KeywordLoc = KeywordLoc;
1110 Changes[Index].Version = Version;
1111 Changes[Index].VersionRange = VersionRange;
1112 } else {
1113 Diag(KeywordLoc, diag::err_availability_unknown_change)
1114 << Keyword << VersionRange;
1115 }
1116
Alp Toker97650562014-01-10 11:19:30 +00001117 } while (TryConsumeToken(tok::comma));
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001118
1119 // Closing ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001120 if (T.consumeClose())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001121 return;
1122
1123 if (endLoc)
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001124 *endLoc = T.getCloseLocation();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001125
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001126 // The 'unavailable' availability cannot be combined with any other
1127 // availability changes. Make sure that hasn't happened.
1128 if (UnavailableLoc.isValid()) {
1129 bool Complained = false;
1130 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1131 if (Changes[Index].KeywordLoc.isValid()) {
1132 if (!Complained) {
1133 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1134 << SourceRange(Changes[Index].KeywordLoc,
1135 Changes[Index].VersionRange.getEnd());
1136 Complained = true;
1137 }
1138
1139 // Clear out the availability.
1140 Changes[Index] = AvailabilityChange();
1141 }
1142 }
1143 }
1144
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001145 // Record this attribute
Chad Rosierc1183952012-06-26 22:30:43 +00001146 attrs.addNew(&Availability,
1147 SourceRange(AvailabilityLoc, T.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001148 ScopeName, ScopeLoc,
Aaron Ballman00e99962013-08-31 01:11:41 +00001149 Platform,
John McCall084e83d2011-03-24 11:26:52 +00001150 Changes[Introduced],
1151 Changes[Deprecated],
Chad Rosierc1183952012-06-26 22:30:43 +00001152 Changes[Obsoleted],
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001153 UnavailableLoc, MessageExpr.get(),
Manman Ren75bc6762016-03-21 17:30:55 +00001154 Syntax, StrictLoc, ReplacementExpr.get());
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001155}
1156
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001157/// Parse the contents of the "external_source_symbol" attribute.
Alex Lorenzd5d27e12017-03-01 18:06:25 +00001158///
1159/// external-source-symbol-attribute:
1160/// 'external_source_symbol' '(' keyword-arg-list ')'
1161///
1162/// keyword-arg-list:
1163/// keyword-arg
1164/// keyword-arg ',' keyword-arg-list
1165///
1166/// keyword-arg:
1167/// 'language' '=' <string>
1168/// 'defined_in' '=' <string>
1169/// 'generated_declaration'
1170void Parser::ParseExternalSourceSymbolAttribute(
1171 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1172 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +00001173 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00001174 // Opening '('.
1175 BalancedDelimiterTracker T(*this, tok::l_paren);
1176 if (T.expectAndConsume())
1177 return;
1178
1179 // Initialize the pointers for the keyword identifiers when required.
1180 if (!Ident_language) {
1181 Ident_language = PP.getIdentifierInfo("language");
1182 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1183 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1184 }
1185
1186 ExprResult Language;
1187 bool HasLanguage = false;
1188 ExprResult DefinedInExpr;
1189 bool HasDefinedIn = false;
1190 IdentifierLoc *GeneratedDeclaration = nullptr;
1191
1192 // Parse the language/defined_in/generated_declaration keywords
1193 do {
1194 if (Tok.isNot(tok::identifier)) {
1195 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1196 SkipUntil(tok::r_paren, StopAtSemi);
1197 return;
1198 }
1199
1200 SourceLocation KeywordLoc = Tok.getLocation();
1201 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1202 if (Keyword == Ident_generated_declaration) {
1203 if (GeneratedDeclaration) {
1204 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1205 SkipUntil(tok::r_paren, StopAtSemi);
1206 return;
1207 }
1208 GeneratedDeclaration = ParseIdentifierLoc();
1209 continue;
1210 }
1211
1212 if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1213 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1214 SkipUntil(tok::r_paren, StopAtSemi);
1215 return;
1216 }
1217
1218 ConsumeToken();
1219 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1220 Keyword->getName())) {
1221 SkipUntil(tok::r_paren, StopAtSemi);
1222 return;
1223 }
1224
1225 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1226 if (Keyword == Ident_language)
1227 HasLanguage = true;
1228 else
1229 HasDefinedIn = true;
1230
1231 if (Tok.isNot(tok::string_literal)) {
1232 Diag(Tok, diag::err_expected_string_literal)
1233 << /*Source='external_source_symbol attribute'*/ 3
1234 << /*language | source container*/ (Keyword != Ident_language);
1235 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1236 continue;
1237 }
1238 if (Keyword == Ident_language) {
1239 if (HadLanguage) {
1240 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1241 << Keyword;
1242 ParseStringLiteralExpression();
1243 continue;
1244 }
1245 Language = ParseStringLiteralExpression();
1246 } else {
1247 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1248 if (HadDefinedIn) {
1249 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1250 << Keyword;
1251 ParseStringLiteralExpression();
1252 continue;
1253 }
1254 DefinedInExpr = ParseStringLiteralExpression();
1255 }
1256 } while (TryConsumeToken(tok::comma));
1257
1258 // Closing ')'.
1259 if (T.consumeClose())
1260 return;
1261 if (EndLoc)
1262 *EndLoc = T.getCloseLocation();
1263
1264 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1265 GeneratedDeclaration};
1266 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1267 ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1268}
1269
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001270/// Parse the contents of the "objc_bridge_related" attribute.
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001271/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1272/// related_class:
1273/// Identifier
1274///
1275/// opt-class_method:
1276/// Identifier: | <empty>
1277///
1278/// opt-instance_method:
1279/// Identifier | <empty>
1280///
1281void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1282 SourceLocation ObjCBridgeRelatedLoc,
1283 ParsedAttributes &attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001284 SourceLocation *endLoc,
1285 IdentifierInfo *ScopeName,
1286 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001287 ParsedAttr::Syntax Syntax) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001288 // Opening '('.
1289 BalancedDelimiterTracker T(*this, tok::l_paren);
1290 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00001291 Diag(Tok, diag::err_expected) << tok::l_paren;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001292 return;
1293 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001294
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001295 // Parse the related class name.
1296 if (Tok.isNot(tok::identifier)) {
1297 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1298 SkipUntil(tok::r_paren, StopAtSemi);
1299 return;
1300 }
1301 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
Alp Toker97650562014-01-10 11:19:30 +00001302 if (ExpectAndConsume(tok::comma)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001303 SkipUntil(tok::r_paren, StopAtSemi);
1304 return;
1305 }
Alp Toker8fbec672013-12-17 23:29:36 +00001306
Aaron Ballman48a533d2018-02-27 23:49:28 +00001307 // Parse class method name. It's non-optional in the sense that a trailing
1308 // comma is required, but it can be the empty string, and then we record a
1309 // nullptr.
Craig Topper161e4db2014-05-21 06:02:52 +00001310 IdentifierLoc *ClassMethod = nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001311 if (Tok.is(tok::identifier)) {
1312 ClassMethod = ParseIdentifierLoc();
Alp Toker8fbec672013-12-17 23:29:36 +00001313 if (!TryConsumeToken(tok::colon)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001314 Diag(Tok, diag::err_objcbridge_related_selector_name);
1315 SkipUntil(tok::r_paren, StopAtSemi);
1316 return;
1317 }
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001318 }
Alp Toker8fbec672013-12-17 23:29:36 +00001319 if (!TryConsumeToken(tok::comma)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001320 if (Tok.is(tok::colon))
1321 Diag(Tok, diag::err_objcbridge_related_selector_name);
1322 else
Alp Tokerec543272013-12-24 09:48:30 +00001323 Diag(Tok, diag::err_expected) << tok::comma;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001324 SkipUntil(tok::r_paren, StopAtSemi);
1325 return;
1326 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001327
Aaron Ballman48a533d2018-02-27 23:49:28 +00001328 // Parse instance method name. Also non-optional but empty string is
1329 // permitted.
Craig Topper161e4db2014-05-21 06:02:52 +00001330 IdentifierLoc *InstanceMethod = nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001331 if (Tok.is(tok::identifier))
1332 InstanceMethod = ParseIdentifierLoc();
1333 else if (Tok.isNot(tok::r_paren)) {
Alp Tokerec543272013-12-24 09:48:30 +00001334 Diag(Tok, diag::err_expected) << tok::r_paren;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001335 SkipUntil(tok::r_paren, StopAtSemi);
1336 return;
1337 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001338
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001339 // Closing ')'.
1340 if (T.consumeClose())
1341 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001342
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001343 if (endLoc)
1344 *endLoc = T.getCloseLocation();
Fangrui Song6907ce22018-07-30 19:24:48 +00001345
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001346 // Record this attribute
1347 attrs.addNew(&ObjCBridgeRelated,
1348 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001349 ScopeName, ScopeLoc,
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001350 RelatedClass,
1351 ClassMethod,
1352 InstanceMethod,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001353 Syntax);
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001354}
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001355
Bill Wendling44426052012-12-20 19:22:21 +00001356// Late Parsed Attributes:
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001357// See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1358
1359void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1360
1361void Parser::LateParsedClass::ParseLexedAttributes() {
1362 Self->ParseLexedAttributes(*Class);
1363}
1364
1365void Parser::LateParsedAttribute::ParseLexedAttributes() {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001366 Self->ParseLexedAttribute(*this, true, false);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001367}
1368
1369/// Wrapper class which calls ParseLexedAttribute, after setting up the
1370/// scope appropriately.
1371void Parser::ParseLexedAttributes(ParsingClass &Class) {
1372 // Deal with templates
1373 // FIXME: Test cases to make sure this does the right thing for templates.
1374 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1375 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1376 HasTemplateScope);
1377 if (HasTemplateScope)
1378 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1379
Douglas Gregor3024f072012-04-16 07:05:22 +00001380 // Set or update the scope flags.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001381 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +00001382 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001383 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1384 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1385
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001386 // Enter the scope of nested classes
1387 if (!AlreadyHasClassScope)
1388 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1389 Class.TagOrTemplate);
Benjamin Kramer1d373c62012-05-17 12:01:52 +00001390 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001391 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1392 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1393 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001394 }
Chad Rosierc1183952012-06-26 22:30:43 +00001395
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001396 if (!AlreadyHasClassScope)
1397 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1398 Class.TagOrTemplate);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001399}
1400
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001401/// Parse all attributes in LAs, and attach them to Decl D.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001402void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1403 bool EnterScope, bool OnDefinition) {
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001404 assert(LAs.parseSoon() &&
1405 "Attribute list should be marked for immediate parsing.");
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001406 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
DeLesley Hutchins19c722d2012-08-15 22:41:04 +00001407 if (D)
1408 LAs[i]->addDecl(D);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001409 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
Benjamin Kramerbafc49a2012-04-14 12:44:47 +00001410 delete LAs[i];
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001411 }
1412 LAs.clear();
1413}
1414
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001415/// Finish parsing an attribute for which parsing was delayed.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001416/// This will be called at the end of parsing a class declaration
1417/// for each LateParsedAttribute. We consume the saved tokens and
Chad Rosierc1183952012-06-26 22:30:43 +00001418/// create an attribute with the arguments filled in. We add this
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001419/// to the Attribute list for the decl.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001420void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1421 bool EnterScope, bool OnDefinition) {
David Majnemerd5946f52015-01-13 08:35:24 +00001422 // Create a fake EOF so that attribute parsing won't go off the end of the
1423 // attribute.
1424 Token AttrEnd;
1425 AttrEnd.startToken();
1426 AttrEnd.setKind(tok::eof);
1427 AttrEnd.setLocation(Tok.getLocation());
1428 AttrEnd.setEofData(LA.Toks.data());
1429 LA.Toks.push_back(AttrEnd);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001430
1431 // Append the current token at the end of the new token stream so that it
1432 // doesn't get lost.
1433 LA.Toks.push_back(Tok);
David Blaikie2eabcc92016-02-09 18:52:09 +00001434 PP.EnterTokenStream(LA.Toks, true);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001435 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +00001436 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001437
1438 ParsedAttributes Attrs(AttrFactory);
1439 SourceLocation endLoc;
1440
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001441 if (LA.Decls.size() > 0) {
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001442 Decl *D = LA.Decls[0];
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001443 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1444 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001445
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001446 // Allow 'this' within late-parsed attributes.
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001447 Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
Richard Smithc3d2ebb2013-06-07 02:33:37 +00001448 ND && ND->isCXXInstanceMember());
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001449
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001450 if (LA.Decls.size() == 1) {
1451 // If the Decl is templatized, add template parameters to scope.
1452 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1453 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1454 if (HasTemplateScope)
1455 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001456
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001457 // If the Decl is on a function, add function parameters to the scope.
1458 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
Momchil Velikov57c681f2017-08-10 15:43:06 +00001459 ParseScope FnScope(
1460 this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
1461 HasFunScope);
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001462 if (HasFunScope)
1463 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001464
Michael Han23214e52012-10-03 01:56:22 +00001465 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001466 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
Craig Topper161e4db2014-05-21 06:02:52 +00001467 nullptr);
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001468
1469 if (HasFunScope) {
1470 Actions.ActOnExitFunctionContext();
1471 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1472 }
1473 if (HasTemplateScope) {
1474 TempScope.Exit();
1475 }
1476 } else {
1477 // If there are multiple decls, then the decl cannot be within the
1478 // function scope.
Michael Han23214e52012-10-03 01:56:22 +00001479 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001480 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
Craig Topper161e4db2014-05-21 06:02:52 +00001481 nullptr);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001482 }
DeLesley Hutchins71d61032012-03-02 22:29:50 +00001483 } else {
1484 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001485 }
1486
Erich Keanec480f302018-07-12 21:09:05 +00001487 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
1488 Attrs.begin()->isKnownToGCC())
Aaron Ballman9a99e0d2014-01-20 17:18:35 +00001489 Diag(Tok, diag::warn_attribute_on_function_definition)
1490 << &LA.AttrName;
1491
1492 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001493 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001494
David Majnemerd5946f52015-01-13 08:35:24 +00001495 // Due to a parsing error, we either went over the cached tokens or
1496 // there are still cached tokens left, so we skip the leftover tokens.
1497 while (Tok.isNot(tok::eof))
1498 ConsumeAnyToken();
1499
1500 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1501 ConsumeAnyToken();
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001502}
1503
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001504void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1505 SourceLocation AttrNameLoc,
1506 ParsedAttributes &Attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001507 SourceLocation *EndLoc,
1508 IdentifierInfo *ScopeName,
1509 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001510 ParsedAttr::Syntax Syntax) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001511 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1512
1513 BalancedDelimiterTracker T(*this, tok::l_paren);
1514 T.consumeOpen();
1515
1516 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001517 Diag(Tok, diag::err_expected) << tok::identifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001518 T.skipToEnd();
1519 return;
1520 }
Richard Smithfeefaf52013-09-03 18:01:40 +00001521 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001522
Alp Toker094e5212014-01-05 03:27:11 +00001523 if (ExpectAndConsume(tok::comma)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001524 T.skipToEnd();
1525 return;
1526 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001527
1528 SourceRange MatchingCTypeRange;
1529 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1530 if (MatchingCType.isInvalid()) {
1531 T.skipToEnd();
1532 return;
1533 }
1534
1535 bool LayoutCompatible = false;
1536 bool MustBeNull = false;
Alp Toker8fbec672013-12-17 23:29:36 +00001537 while (TryConsumeToken(tok::comma)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001538 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001539 Diag(Tok, diag::err_expected) << tok::identifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001540 T.skipToEnd();
1541 return;
1542 }
1543 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1544 if (Flag->isStr("layout_compatible"))
1545 LayoutCompatible = true;
1546 else if (Flag->isStr("must_be_null"))
1547 MustBeNull = true;
1548 else {
1549 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1550 T.skipToEnd();
1551 return;
1552 }
1553 ConsumeToken(); // consume flag
1554 }
1555
1556 if (!T.consumeClose()) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001557 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001558 ArgumentKind, MatchingCType.get(),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001559 LayoutCompatible, MustBeNull, Syntax);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001560 }
1561
1562 if (EndLoc)
1563 *EndLoc = T.getCloseLocation();
1564}
1565
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001566/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1567/// of a C++11 attribute-specifier in a location where an attribute is not
1568/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1569/// situation.
1570///
1571/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1572/// this doesn't appear to actually be an attribute-specifier, and the caller
1573/// should try to parse it.
1574bool Parser::DiagnoseProhibitedCXX11Attribute() {
1575 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1576
1577 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1578 case CAK_NotAttributeSpecifier:
1579 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1580 return false;
1581
1582 case CAK_InvalidAttributeSpecifier:
1583 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1584 return false;
1585
1586 case CAK_AttributeSpecifier:
1587 // Parse and discard the attributes.
1588 SourceLocation BeginLoc = ConsumeBracket();
1589 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001590 SkipUntil(tok::r_square);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001591 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1592 SourceLocation EndLoc = ConsumeBracket();
1593 Diag(BeginLoc, diag::err_attributes_not_allowed)
1594 << SourceRange(BeginLoc, EndLoc);
1595 return true;
1596 }
Chandler Carruthd8f7d382012-04-10 16:03:08 +00001597 llvm_unreachable("All cases handled above.");
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001598}
1599
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001600/// We have found the opening square brackets of a C++11
Richard Smith98155ad2013-02-20 01:17:14 +00001601/// attribute-specifier in a location where an attribute is not permitted, but
1602/// we know where the attributes ought to be written. Parse them anyway, and
1603/// provide a fixit moving them to the right place.
Richard Smith4c96e992013-02-19 23:47:15 +00001604void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1605 SourceLocation CorrectLocation) {
1606 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1607 Tok.is(tok::kw_alignas));
1608
1609 // Consume the attributes.
1610 SourceLocation Loc = Tok.getLocation();
1611 ParseCXX11Attributes(Attrs);
1612 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
Faisal Valic5089c02017-12-25 22:23:20 +00001613 // FIXME: use err_attributes_misplaced
Richard Smith4c96e992013-02-19 23:47:15 +00001614 Diag(Loc, diag::err_attributes_not_allowed)
1615 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1616 << FixItHint::CreateRemoval(AttrRange);
1617}
1618
Erich Keanec480f302018-07-12 21:09:05 +00001619void Parser::DiagnoseProhibitedAttributes(
1620 const SourceRange &Range, const SourceLocation CorrectLocation) {
Faisal Valic5089c02017-12-25 22:23:20 +00001621 if (CorrectLocation.isValid()) {
Erich Keanec480f302018-07-12 21:09:05 +00001622 CharSourceRange AttrRange(Range, true);
Faisal Valic5089c02017-12-25 22:23:20 +00001623 Diag(CorrectLocation, diag::err_attributes_misplaced)
1624 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1625 << FixItHint::CreateRemoval(AttrRange);
1626 } else
Erich Keanec480f302018-07-12 21:09:05 +00001627 Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
Dawn Perchik335e16b2010-09-03 01:29:35 +00001628}
1629
Richard Smith49cc1cc2016-08-18 21:59:42 +00001630void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1631 unsigned DiagID) {
Erich Keanee891aa92018-07-13 15:07:47 +00001632 for (const ParsedAttr &AL : Attrs) {
Erich Keanec480f302018-07-12 21:09:05 +00001633 if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
Richard Smith49cc1cc2016-08-18 21:59:42 +00001634 continue;
Erich Keanee891aa92018-07-13 15:07:47 +00001635 if (AL.getKind() == ParsedAttr::UnknownAttribute)
Erich Keanec480f302018-07-12 21:09:05 +00001636 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL.getName();
Richard Smith49cc1cc2016-08-18 21:59:42 +00001637 else {
Erich Keanec480f302018-07-12 21:09:05 +00001638 Diag(AL.getLoc(), DiagID) << AL.getName();
1639 AL.setInvalid();
Michael Han64536a62012-11-06 19:34:54 +00001640 }
Michael Han64536a62012-11-06 19:34:54 +00001641 }
1642}
1643
Nico Weber32a0fc72016-09-03 03:01:32 +00001644// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1645// applies to var, not the type Foo.
David Majnemer936b4112015-04-19 07:53:29 +00001646// As an exception to the rule, __declspec(align(...)) before the
1647// class-key affects the type instead of the variable.
Nico Weber32a0fc72016-09-03 03:01:32 +00001648// Also, Microsoft-style [attributes] seem to affect the type instead of the
1649// variable.
1650// This function moves attributes that should apply to the type off DS to Attrs.
1651void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1652 DeclSpec &DS,
1653 Sema::TagUseKind TUK) {
David Majnemer936b4112015-04-19 07:53:29 +00001654 if (TUK == Sema::TUK_Reference)
1655 return;
1656
Erich Keanee891aa92018-07-13 15:07:47 +00001657 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
David Majnemer936b4112015-04-19 07:53:29 +00001658
Erich Keanee891aa92018-07-13 15:07:47 +00001659 for (ParsedAttr &AL : DS.getAttributes()) {
1660 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
Erich Keanec480f302018-07-12 21:09:05 +00001661 AL.isDeclspecAttribute()) ||
1662 AL.isMicrosoftAttribute())
1663 ToBeMoved.push_back(&AL);
David Majnemer936b4112015-04-19 07:53:29 +00001664 }
Nico Weber88f5ed92016-09-13 18:55:26 +00001665
Erich Keanee891aa92018-07-13 15:07:47 +00001666 for (ParsedAttr *AL : ToBeMoved) {
Erich Keanec480f302018-07-12 21:09:05 +00001667 DS.getAttributes().remove(AL);
1668 Attrs.addAtEnd(AL);
1669 }
David Majnemer936b4112015-04-19 07:53:29 +00001670}
1671
Chris Lattner53361ac2006-08-10 05:19:57 +00001672/// ParseDeclaration - Parse a full 'declaration', which consists of
1673/// declaration-specifiers, some number of declarators, and a semicolon.
Faisal Vali421b2d12017-12-29 05:41:00 +00001674/// 'Context' should be a DeclaratorContext value. This returns the
Chris Lattner49836b42009-04-02 04:16:50 +00001675/// location of the semicolon in DeclEnd.
Chris Lattnera5235172007-08-25 06:57:03 +00001676///
1677/// declaration: [C99 6.7]
1678/// block-declaration ->
1679/// simple-declaration
1680/// others [FIXME]
Douglas Gregoreb31f392008-12-01 23:54:00 +00001681/// [C++] template-declaration
Chris Lattnera5235172007-08-25 06:57:03 +00001682/// [C++] namespace-definition
Douglas Gregord7c4d982008-12-30 03:27:21 +00001683/// [C++] using-directive
Douglas Gregor77b50e12009-06-22 23:06:13 +00001684/// [C++] using-declaration
Richard Smithc202b282012-04-14 00:33:13 +00001685/// [C++11/C11] static_assert-declaration
Chris Lattnera5235172007-08-25 06:57:03 +00001686/// others... [FIXME]
1687///
Faisal Vali421b2d12017-12-29 05:41:00 +00001688Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
Alexis Hunt96d5c762009-11-21 08:43:09 +00001689 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +00001690 ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +00001691 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Fariborz Jahanian59b75282011-08-30 17:10:52 +00001692 // Must temporarily exit the objective-c container scope for
1693 // parsing c none objective-c decls.
1694 ObjCDeclContextSwitch ObjCDC(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00001695
Craig Topper161e4db2014-05-21 06:02:52 +00001696 Decl *SingleDecl = nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +00001697 switch (Tok.getKind()) {
Douglas Gregoreb31f392008-12-01 23:54:00 +00001698 case tok::kw_template:
Douglas Gregor23996282009-05-12 21:31:51 +00001699 case tok::kw_export:
John McCall53fa7142010-12-24 02:08:15 +00001700 ProhibitAttributes(attrs);
Erich Keanec480f302018-07-12 21:09:05 +00001701 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001702 break;
Sebastian Redl67667942010-08-27 23:12:46 +00001703 case tok::kw_inline:
Sebastian Redl5a5f2c72010-08-31 00:36:45 +00001704 // Could be the start of an inline namespace. Allowed as an ext in C++03.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001705 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
John McCall53fa7142010-12-24 02:08:15 +00001706 ProhibitAttributes(attrs);
Sebastian Redl67667942010-08-27 23:12:46 +00001707 SourceLocation InlineLoc = ConsumeToken();
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00001708 return ParseNamespace(Context, DeclEnd, InlineLoc);
Sebastian Redl67667942010-08-27 23:12:46 +00001709 }
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001710 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
Fariborz Jahanian1db5c942010-09-28 20:42:35 +00001711 true);
Chris Lattnera5235172007-08-25 06:57:03 +00001712 case tok::kw_namespace:
John McCall53fa7142010-12-24 02:08:15 +00001713 ProhibitAttributes(attrs);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00001714 return ParseNamespace(Context, DeclEnd);
Douglas Gregord7c4d982008-12-30 03:27:21 +00001715 case tok::kw_using:
Richard Smith6f1daa42016-12-16 00:58:48 +00001716 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1717 DeclEnd, attrs);
Anders Carlssonf24fcff62009-03-11 16:27:10 +00001718 case tok::kw_static_assert:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00001719 case tok::kw__Static_assert:
John McCall53fa7142010-12-24 02:08:15 +00001720 ProhibitAttributes(attrs);
Chris Lattner49836b42009-04-02 04:16:50 +00001721 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001722 break;
Chris Lattnera5235172007-08-25 06:57:03 +00001723 default:
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001724 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
Chris Lattnera5235172007-08-25 06:57:03 +00001725 }
Chad Rosierc1183952012-06-26 22:30:43 +00001726
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001727 // This routine returns a DeclGroup, if the thing we parsed only contains a
Richard Smith6f1daa42016-12-16 00:58:48 +00001728 // single decl, convert it now.
1729 return Actions.ConvertDeclToDeclGroup(SingleDecl);
Chris Lattnera5235172007-08-25 06:57:03 +00001730}
1731
1732/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1733/// declaration-specifiers init-declarator-list[opt] ';'
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001734/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1735/// init-declarator-list ';'
Chris Lattnera5235172007-08-25 06:57:03 +00001736///[C90/C++]init-declarator-list ';' [TODO]
1737/// [OMP] threadprivate-directive [TODO]
Chris Lattner32dc41c2009-03-29 17:27:48 +00001738///
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001739/// for-range-declaration: [C++11 6.5p1: stmt.ranged]
Richard Smith02e85f32011-04-14 22:09:26 +00001740/// attribute-specifier-seq[opt] type-specifier-seq declarator
1741///
Chris Lattner32dc41c2009-03-29 17:27:48 +00001742/// If RequireSemi is false, this does not check for a ';' at the end of the
Chris Lattner005fc1b2010-04-05 18:18:31 +00001743/// declaration. If it is true, it checks for and eats it.
Richard Smith02e85f32011-04-14 22:09:26 +00001744///
1745/// If FRI is non-null, we might be parsing a for-range-declaration instead
1746/// of a simple-declaration. If we find that we are, we also parse the
1747/// for-range-initializer, and place it here.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001748Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +00001749Parser::ParseSimpleDeclaration(DeclaratorContext Context,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001750 SourceLocation &DeclEnd,
Richard Smith2386c8b2013-02-22 09:06:26 +00001751 ParsedAttributesWithRange &Attrs,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001752 bool RequireSemi, ForRangeInit *FRI) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001753 // Parse the common declaration-specifiers piece.
John McCall28a6aea2009-11-04 02:18:39 +00001754 ParsingDeclSpec DS(*this);
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001755
Richard Smith404dfb42013-11-19 22:47:36 +00001756 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
Faisal Valia534f072018-04-26 00:42:40 +00001757 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
Richard Smith404dfb42013-11-19 22:47:36 +00001758
1759 // If we had a free-standing type definition with a missing semicolon, we
1760 // may get this far before the problem becomes obvious.
1761 if (DS.hasTagDefinition() &&
1762 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
David Blaikie0403cb12016-01-15 23:43:25 +00001763 return nullptr;
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001764
Chris Lattner0e894622006-08-13 19:58:17 +00001765 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1766 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner76c72282007-10-09 17:33:22 +00001767 if (Tok.is(tok::semi)) {
Richard Smith2386c8b2013-02-22 09:06:26 +00001768 ProhibitAttributes(Attrs);
Argyrios Kyrtzidisfbb2bb52012-05-16 23:49:15 +00001769 DeclEnd = Tok.getLocation();
Chris Lattner005fc1b2010-04-05 18:18:31 +00001770 if (RequireSemi) ConsumeToken();
Nico Weber7b837f52016-01-28 19:25:00 +00001771 RecordDecl *AnonRecord = nullptr;
John McCall48871652010-08-21 09:40:31 +00001772 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00001773 DS, AnonRecord);
John McCall28a6aea2009-11-04 02:18:39 +00001774 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00001775 if (AnonRecord) {
1776 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00001777 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00001778 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001779 return Actions.ConvertDeclToDeclGroup(TheDecl);
Chris Lattner0e894622006-08-13 19:58:17 +00001780 }
Chad Rosierc1183952012-06-26 22:30:43 +00001781
Richard Smith2386c8b2013-02-22 09:06:26 +00001782 DS.takeAttributesFrom(Attrs);
Reid Klecknerd61a3112014-12-15 23:16:32 +00001783 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
John McCalld5a36322009-11-03 19:26:08 +00001784}
Mike Stump11289f42009-09-09 15:08:12 +00001785
Richard Smith09f76ee2011-10-19 21:33:05 +00001786/// Returns true if this might be the start of a declarator, or a common typo
1787/// for a declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001788bool Parser::MightBeDeclarator(DeclaratorContext Context) {
Richard Smith09f76ee2011-10-19 21:33:05 +00001789 switch (Tok.getKind()) {
1790 case tok::annot_cxxscope:
1791 case tok::annot_template_id:
1792 case tok::caret:
1793 case tok::code_completion:
1794 case tok::coloncolon:
1795 case tok::ellipsis:
1796 case tok::kw___attribute:
1797 case tok::kw_operator:
1798 case tok::l_paren:
1799 case tok::star:
1800 return true;
1801
1802 case tok::amp:
1803 case tok::ampamp:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001804 return getLangOpts().CPlusPlus;
Richard Smith09f76ee2011-10-19 21:33:05 +00001805
Richard Smithc8a79032012-01-09 22:31:44 +00001806 case tok::l_square: // Might be an attribute on an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001807 return Context == DeclaratorContext::MemberContext &&
1808 getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
Richard Smithc8a79032012-01-09 22:31:44 +00001809
1810 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001811 return Context == DeclaratorContext::MemberContext ||
1812 getLangOpts().CPlusPlus;
Richard Smithc8a79032012-01-09 22:31:44 +00001813
Richard Smith09f76ee2011-10-19 21:33:05 +00001814 case tok::identifier:
1815 switch (NextToken().getKind()) {
1816 case tok::code_completion:
1817 case tok::coloncolon:
1818 case tok::comma:
1819 case tok::equal:
1820 case tok::equalequal: // Might be a typo for '='.
1821 case tok::kw_alignas:
1822 case tok::kw_asm:
1823 case tok::kw___attribute:
1824 case tok::l_brace:
1825 case tok::l_paren:
1826 case tok::l_square:
1827 case tok::less:
1828 case tok::r_brace:
1829 case tok::r_paren:
1830 case tok::r_square:
1831 case tok::semi:
1832 return true;
1833
1834 case tok::colon:
1835 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
Richard Smithc8a79032012-01-09 22:31:44 +00001836 // and in block scope it's probably a label. Inside a class definition,
1837 // this is a bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001838 return Context == DeclaratorContext::MemberContext ||
1839 (getLangOpts().CPlusPlus &&
1840 Context == DeclaratorContext::FileContext);
Richard Smithc8a79032012-01-09 22:31:44 +00001841
1842 case tok::identifier: // Possible virt-specifier.
Richard Smith89645bc2013-01-02 12:01:23 +00001843 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
Richard Smith09f76ee2011-10-19 21:33:05 +00001844
1845 default:
1846 return false;
1847 }
1848
1849 default:
1850 return false;
1851 }
1852}
1853
Richard Smithb8caac82012-04-11 20:59:20 +00001854/// Skip until we reach something which seems like a sensible place to pick
1855/// up parsing after a malformed declaration. This will sometimes stop sooner
1856/// than SkipUntil(tok::r_brace) would, but will never stop later.
1857void Parser::SkipMalformedDecl() {
1858 while (true) {
1859 switch (Tok.getKind()) {
1860 case tok::l_brace:
1861 // Skip until matching }, then stop. We've probably skipped over
1862 // a malformed class or function definition or similar.
1863 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001864 SkipUntil(tok::r_brace);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001865 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
Richard Smithb8caac82012-04-11 20:59:20 +00001866 // This declaration isn't over yet. Keep skipping.
1867 continue;
1868 }
Alp Toker8fbec672013-12-17 23:29:36 +00001869 TryConsumeToken(tok::semi);
Richard Smithb8caac82012-04-11 20:59:20 +00001870 return;
1871
1872 case tok::l_square:
1873 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001874 SkipUntil(tok::r_square);
Richard Smithb8caac82012-04-11 20:59:20 +00001875 continue;
1876
1877 case tok::l_paren:
1878 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001879 SkipUntil(tok::r_paren);
Richard Smithb8caac82012-04-11 20:59:20 +00001880 continue;
1881
1882 case tok::r_brace:
1883 return;
1884
1885 case tok::semi:
1886 ConsumeToken();
1887 return;
1888
1889 case tok::kw_inline:
1890 // 'inline namespace' at the start of a line is almost certainly
Jordan Rose12e730c2012-07-09 16:54:53 +00001891 // a good place to pick back up parsing, except in an Objective-C
1892 // @interface context.
1893 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1894 (!ParsingInObjCContainer || CurParsedObjCImpl))
Richard Smithb8caac82012-04-11 20:59:20 +00001895 return;
1896 break;
1897
1898 case tok::kw_namespace:
1899 // 'namespace' at the start of a line is almost certainly a good
Jordan Rose12e730c2012-07-09 16:54:53 +00001900 // place to pick back up parsing, except in an Objective-C
1901 // @interface context.
1902 if (Tok.isAtStartOfLine() &&
1903 (!ParsingInObjCContainer || CurParsedObjCImpl))
1904 return;
1905 break;
1906
1907 case tok::at:
1908 // @end is very much like } in Objective-C contexts.
1909 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1910 ParsingInObjCContainer)
1911 return;
1912 break;
1913
1914 case tok::minus:
1915 case tok::plus:
1916 // - and + probably start new method declarations in Objective-C contexts.
1917 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
Richard Smithb8caac82012-04-11 20:59:20 +00001918 return;
1919 break;
1920
1921 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001922 case tok::annot_module_begin:
1923 case tok::annot_module_end:
1924 case tok::annot_module_include:
Richard Smithb8caac82012-04-11 20:59:20 +00001925 return;
1926
1927 default:
1928 break;
1929 }
1930
1931 ConsumeAnyToken();
1932 }
1933}
1934
John McCalld5a36322009-11-03 19:26:08 +00001935/// ParseDeclGroup - Having concluded that this is either a function
1936/// definition or a group of object declarations, actually parse the
1937/// result.
John McCall28a6aea2009-11-04 02:18:39 +00001938Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
Faisal Vali421b2d12017-12-29 05:41:00 +00001939 DeclaratorContext Context,
Richard Smith02e85f32011-04-14 22:09:26 +00001940 SourceLocation *DeclEnd,
1941 ForRangeInit *FRI) {
John McCalld5a36322009-11-03 19:26:08 +00001942 // Parse the first declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001943 ParsingDeclarator D(*this, DS, Context);
John McCalld5a36322009-11-03 19:26:08 +00001944 ParseDeclarator(D);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001945
John McCalld5a36322009-11-03 19:26:08 +00001946 // Bail out if the first declarator didn't seem well-formed.
1947 if (!D.hasName() && !D.mayOmitIdentifier()) {
Richard Smithb8caac82012-04-11 20:59:20 +00001948 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00001949 return nullptr;
Chris Lattnerefb0f112009-03-29 17:18:04 +00001950 }
Mike Stump11289f42009-09-09 15:08:12 +00001951
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001952 // Save late-parsed attributes for now; they need to be parsed in the
1953 // appropriate function scope after the function Decl has been constructed.
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001954 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1955 LateParsedAttrList LateParsedAttrs(true);
Richard Smith99c464c2014-11-10 21:10:32 +00001956 if (D.isFunctionDeclarator()) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001957 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1958
Richard Smith99c464c2014-11-10 21:10:32 +00001959 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1960 // attribute. If we find the keyword here, tell the user to put it
1961 // at the start instead.
1962 if (Tok.is(tok::kw__Noreturn)) {
1963 SourceLocation Loc = ConsumeToken();
1964 const char *PrevSpec;
1965 unsigned DiagID;
1966
1967 // We can offer a fixit if it's valid to mark this function as _Noreturn
1968 // and we don't have any other declarators in this declaration.
1969 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1970 MaybeParseGNUAttributes(D, &LateParsedAttrs);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001971 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
Richard Smith99c464c2014-11-10 21:10:32 +00001972
1973 Diag(Loc, diag::err_c11_noreturn_misplaced)
1974 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001975 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
Richard Smith99c464c2014-11-10 21:10:32 +00001976 : FixItHint());
1977 }
1978 }
1979
Chris Lattnerdbb1e932010-07-11 22:24:20 +00001980 // Check to see if we have a function *definition* which must have a body.
Douglas Gregor012efe22013-04-16 16:01:32 +00001981 if (D.isFunctionDeclarator() &&
Chris Lattnerdbb1e932010-07-11 22:24:20 +00001982 // Look at the next token to make sure that this isn't a function
1983 // declaration. We have to check this because __attribute__ might be the
1984 // start of a function definition in GCC-extended K&R C.
Fariborz Jahanian712bb812012-08-10 15:54:40 +00001985 !isDeclarationAfterDeclarator()) {
Chad Rosierc1183952012-06-26 22:30:43 +00001986
Reid Klecknerd61a3112014-12-15 23:16:32 +00001987 // Function definitions are only allowed at file scope and in C++ classes.
1988 // The C++ inline method definition case is handled elsewhere, so we only
1989 // need to handle the file scope definition case.
Faisal Vali421b2d12017-12-29 05:41:00 +00001990 if (Context == DeclaratorContext::FileContext) {
Douglas Gregor012efe22013-04-16 16:01:32 +00001991 if (isStartOfFunctionDefinition(D)) {
1992 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1993 Diag(Tok, diag::err_function_declared_typedef);
John McCalld5a36322009-11-03 19:26:08 +00001994
Douglas Gregor012efe22013-04-16 16:01:32 +00001995 // Recover by treating the 'typedef' as spurious.
1996 DS.ClearStorageClassSpecs();
1997 }
1998
1999 Decl *TheDecl =
2000 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
2001 return Actions.ConvertDeclToDeclGroup(TheDecl);
John McCalld5a36322009-11-03 19:26:08 +00002002 }
2003
Douglas Gregor012efe22013-04-16 16:01:32 +00002004 if (isDeclarationSpecifier()) {
Nico Weber6b05f382015-02-18 04:53:03 +00002005 // If there is an invalid declaration specifier right after the
2006 // function prototype, then we must be in a missing semicolon case
2007 // where this isn't actually a body. Just fall through into the code
2008 // that handles it as a prototype, and let the top-level code handle
2009 // the erroneous declspec where it would otherwise expect a comma or
2010 // semicolon.
Douglas Gregor012efe22013-04-16 16:01:32 +00002011 } else {
2012 Diag(Tok, diag::err_expected_fn_body);
2013 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002014 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00002015 }
John McCalld5a36322009-11-03 19:26:08 +00002016 } else {
Douglas Gregor012efe22013-04-16 16:01:32 +00002017 if (Tok.is(tok::l_brace)) {
2018 Diag(Tok, diag::err_function_definition_not_allowed);
Serge Pavlov1de51512013-12-09 05:25:47 +00002019 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00002020 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00002021 }
John McCalld5a36322009-11-03 19:26:08 +00002022 }
2023 }
2024
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002025 if (ParseAsmAttributesAfterDeclarator(D))
David Blaikie0403cb12016-01-15 23:43:25 +00002026 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00002027
2028 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2029 // must parse and analyze the for-range-initializer before the declaration is
2030 // analyzed.
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002031 //
2032 // Handle the Objective-C for-in loop variable similarly, although we
2033 // don't need to parse the container in advance.
2034 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2035 bool IsForRangeLoop = false;
Alp Toker8fbec672013-12-17 23:29:36 +00002036 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002037 IsForRangeLoop = true;
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002038 if (Tok.is(tok::l_brace))
2039 FRI->RangeExpr = ParseBraceInitializer();
2040 else
2041 FRI->RangeExpr = ParseExpression();
2042 }
2043
Richard Smith02e85f32011-04-14 22:09:26 +00002044 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
George Karpenkovec38cf72018-03-29 00:56:24 +00002045 if (IsForRangeLoop) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002046 Actions.ActOnCXXForRangeDecl(ThisDecl);
George Karpenkovec38cf72018-03-29 00:56:24 +00002047 } else {
2048 // Obj-C for loop
2049 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2050 VD->setObjCForDecl(true);
2051 }
Richard Smith02e85f32011-04-14 22:09:26 +00002052 Actions.FinalizeDeclaration(ThisDecl);
John McCallcf6e0c82012-01-27 01:29:43 +00002053 D.complete(ThisDecl);
Rafael Espindolaab417692013-07-09 12:05:01 +00002054 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
Richard Smith02e85f32011-04-14 22:09:26 +00002055 }
2056
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002057 SmallVector<Decl *, 8> DeclsInGroup;
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002058 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2059 D, ParsedTemplateInfo(), FRI);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002060 if (LateParsedAttrs.size() > 0)
2061 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
John McCall28a6aea2009-11-04 02:18:39 +00002062 D.complete(FirstDecl);
John McCall48871652010-08-21 09:40:31 +00002063 if (FirstDecl)
John McCalld5a36322009-11-03 19:26:08 +00002064 DeclsInGroup.push_back(FirstDecl);
2065
Faisal Vali421b2d12017-12-29 05:41:00 +00002066 bool ExpectSemi = Context != DeclaratorContext::ForContext;
Fangrui Song6907ce22018-07-30 19:24:48 +00002067
John McCalld5a36322009-11-03 19:26:08 +00002068 // If we don't have a comma, it is either the end of the list (a ';') or an
2069 // error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00002070 SourceLocation CommaLoc;
2071 while (TryConsumeToken(tok::comma, CommaLoc)) {
Richard Smith09f76ee2011-10-19 21:33:05 +00002072 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2073 // This comma was followed by a line-break and something which can't be
2074 // the start of a declarator. The comma was probably a typo for a
2075 // semicolon.
2076 Diag(CommaLoc, diag::err_expected_semi_declaration)
2077 << FixItHint::CreateReplacement(CommaLoc, ";");
2078 ExpectSemi = false;
2079 break;
2080 }
John McCalld5a36322009-11-03 19:26:08 +00002081
2082 // Parse the next declarator.
2083 D.clear();
Richard Smith8d06f422012-01-12 23:53:29 +00002084 D.setCommaLoc(CommaLoc);
John McCalld5a36322009-11-03 19:26:08 +00002085
2086 // Accept attributes in an init-declarator. In the first declarator in a
2087 // declaration, these would be part of the declspec. In subsequent
2088 // declarators, they become part of the declarator itself, so that they
2089 // don't apply to declarators after *this* one. Examples:
2090 // short __attribute__((common)) var; -> declspec
2091 // short var __attribute__((common)); -> declarator
2092 // short x, __attribute__((common)) var; -> declarator
John McCall53fa7142010-12-24 02:08:15 +00002093 MaybeParseGNUAttributes(D);
John McCalld5a36322009-11-03 19:26:08 +00002094
Nico Rieckeaaae272014-12-04 23:31:08 +00002095 // MSVC parses but ignores qualifiers after the comma as an extension.
2096 if (getLangOpts().MicrosoftExt)
2097 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2098
John McCalld5a36322009-11-03 19:26:08 +00002099 ParseDeclarator(D);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002100 if (!D.isInvalidType()) {
2101 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2102 D.complete(ThisDecl);
2103 if (ThisDecl)
Chad Rosierc1183952012-06-26 22:30:43 +00002104 DeclsInGroup.push_back(ThisDecl);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002105 }
John McCalld5a36322009-11-03 19:26:08 +00002106 }
2107
2108 if (DeclEnd)
2109 *DeclEnd = Tok.getLocation();
2110
Richard Smith09f76ee2011-10-19 21:33:05 +00002111 if (ExpectSemi &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002112 ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
Chris Lattner02f1b612012-04-28 16:12:17 +00002113 ? diag::err_invalid_token_after_toplevel_declarator
2114 : diag::err_expected_semi_declaration)) {
Chris Lattner13901342010-07-11 22:42:07 +00002115 // Okay, there was no semicolon and one was expected. If we see a
2116 // declaration specifier, just assume it was missing and continue parsing.
2117 // Otherwise things are very confused and we skip to recover.
2118 if (!isDeclarationSpecifier()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002119 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Alp Toker8fbec672013-12-17 23:29:36 +00002120 TryConsumeToken(tok::semi);
Chris Lattner13901342010-07-11 22:42:07 +00002121 }
John McCalld5a36322009-11-03 19:26:08 +00002122 }
2123
Rafael Espindolaab417692013-07-09 12:05:01 +00002124 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner53361ac2006-08-10 05:19:57 +00002125}
2126
Richard Smith02e85f32011-04-14 22:09:26 +00002127/// Parse an optional simple-asm-expr and attributes, and attach them to a
2128/// declarator. Returns true on an error.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002129bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
Richard Smith02e85f32011-04-14 22:09:26 +00002130 // If a simple-asm-expr is present, parse it.
2131 if (Tok.is(tok::kw_asm)) {
2132 SourceLocation Loc;
2133 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2134 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002135 SkipUntil(tok::semi, StopBeforeMatch);
Richard Smith02e85f32011-04-14 22:09:26 +00002136 return true;
2137 }
2138
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002139 D.setAsmLabel(AsmLabel.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002140 D.SetRangeEnd(Loc);
2141 }
2142
2143 MaybeParseGNUAttributes(D);
2144 return false;
2145}
2146
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002147/// Parse 'declaration' after parsing 'declaration-specifiers
Douglas Gregor23996282009-05-12 21:31:51 +00002148/// declarator'. This method parses the remainder of the declaration
2149/// (including any attributes or initializer, among other things) and
2150/// finalizes the declaration.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002151///
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002152/// init-declarator: [C99 6.7]
2153/// declarator
2154/// declarator '=' initializer
Chris Lattner6d7e6342006-08-15 03:41:14 +00002155/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2156/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002157/// [C++] declarator initializer[opt]
2158///
2159/// [C++] initializer:
2160/// [C++] '=' initializer-clause
2161/// [C++] '(' expression-list ')'
Sebastian Redlf769df52009-03-24 22:27:57 +00002162/// [C++0x] '=' 'default' [TODO]
2163/// [C++0x] '=' 'delete'
Sebastian Redl3da34892011-06-05 12:23:16 +00002164/// [C++0x] braced-init-list
Sebastian Redlf769df52009-03-24 22:27:57 +00002165///
2166/// According to the standard grammar, =default and =delete are function
2167/// definitions, but that definitely doesn't fit with the parser here.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002168///
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002169Decl *Parser::ParseDeclarationAfterDeclarator(
2170 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002171 if (ParseAsmAttributesAfterDeclarator(D))
Craig Topper161e4db2014-05-21 06:02:52 +00002172 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002173
Richard Smith02e85f32011-04-14 22:09:26 +00002174 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2175}
Mike Stump11289f42009-09-09 15:08:12 +00002176
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002177Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2178 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
Richard Smithc95d2c52017-09-22 04:25:05 +00002179 // RAII type used to track whether we're inside an initializer.
2180 struct InitializerScopeRAII {
2181 Parser &P;
2182 Declarator &D;
2183 Decl *ThisDecl;
2184
2185 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2186 : P(P), D(D), ThisDecl(ThisDecl) {
2187 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2188 Scope *S = nullptr;
2189 if (D.getCXXScopeSpec().isSet()) {
2190 P.EnterScope(0);
2191 S = P.getCurScope();
2192 }
2193 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2194 }
2195 }
2196 ~InitializerScopeRAII() { pop(); }
2197 void pop() {
2198 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2199 Scope *S = nullptr;
2200 if (D.getCXXScopeSpec().isSet())
2201 S = P.getCurScope();
2202 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2203 if (S)
2204 P.ExitScope();
2205 }
2206 ThisDecl = nullptr;
2207 }
2208 };
2209
Douglas Gregor23996282009-05-12 21:31:51 +00002210 // Inform the current actions module that we just parsed this declarator.
Craig Topper161e4db2014-05-21 06:02:52 +00002211 Decl *ThisDecl = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00002212 switch (TemplateInfo.Kind) {
2213 case ParsedTemplateInfo::NonTemplate:
Douglas Gregor0be31a22010-07-02 17:43:08 +00002214 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
Douglas Gregor450f00842009-09-25 18:43:00 +00002215 break;
Chad Rosierc1183952012-06-26 22:30:43 +00002216
Douglas Gregor450f00842009-09-25 18:43:00 +00002217 case ParsedTemplateInfo::Template:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002218 case ParsedTemplateInfo::ExplicitSpecialization: {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002219 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002220 *TemplateInfo.TemplateParams,
Douglas Gregor450f00842009-09-25 18:43:00 +00002221 D);
Larisse Voufo833b05a2013-08-06 07:33:00 +00002222 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002223 // Re-direct this decl to refer to the templated decl so that we can
2224 // initialize it.
2225 ThisDecl = VT->getTemplatedDecl();
2226 break;
2227 }
2228 case ParsedTemplateInfo::ExplicitInstantiation: {
2229 if (Tok.is(tok::semi)) {
2230 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2231 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2232 if (ThisRes.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002233 SkipUntil(tok::semi, StopBeforeMatch);
Craig Topper161e4db2014-05-21 06:02:52 +00002234 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002235 }
2236 ThisDecl = ThisRes.get();
2237 } else {
2238 // FIXME: This check should be for a variable template instantiation only.
2239
2240 // Check that this is a valid instantiation
Faisal Vali2ab8c152017-12-30 04:15:27 +00002241 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002242 // If the declarator-id is not a template-id, issue a diagnostic and
2243 // recover by ignoring the 'template' keyword.
2244 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2245 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2246 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2247 } else {
2248 SourceLocation LAngleLoc =
2249 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2250 Diag(D.getIdentifierLoc(),
2251 diag::err_explicit_instantiation_with_definition)
2252 << SourceRange(TemplateInfo.TemplateLoc)
2253 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2254
2255 // Recover as if it were an explicit specialization.
2256 TemplateParameterLists FakedParamLists;
2257 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00002258 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00002259 LAngleLoc, nullptr));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002260
2261 ThisDecl =
2262 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2263 }
2264 }
Douglas Gregor450f00842009-09-25 18:43:00 +00002265 break;
2266 }
2267 }
Mike Stump11289f42009-09-09 15:08:12 +00002268
Douglas Gregor23996282009-05-12 21:31:51 +00002269 // Parse declarator '=' initializer.
Richard Trieuc64d3232012-01-18 22:54:52 +00002270 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Trieu4972a6d2012-01-19 22:01:51 +00002271 if (isTokenEqualOrEqualTypo()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002272 SourceLocation EqualLoc = ConsumeToken();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002273
Anders Carlsson991285e2010-09-24 21:25:25 +00002274 if (Tok.is(tok::kw_delete)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002275 if (D.isFunctionDeclarator())
2276 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2277 << 1 /* delete */;
2278 else
2279 Diag(ConsumeToken(), diag::err_deleted_non_function);
Alexis Hunt5dafebc2011-05-06 01:42:00 +00002280 } else if (Tok.is(tok::kw_default)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002281 if (D.isFunctionDeclarator())
Sebastian Redl46afb552012-02-11 23:51:21 +00002282 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2283 << 0 /* default */;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002284 else
2285 Diag(ConsumeToken(), diag::err_default_special_members);
Douglas Gregor23996282009-05-12 21:31:51 +00002286 } else {
Richard Smithc95d2c52017-09-22 04:25:05 +00002287 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002288
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002289 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002290 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
Peter Collingbourne6b4fdc22012-07-27 12:56:09 +00002291 Actions.FinalizeDeclaration(ThisDecl);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002292 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +00002293 return nullptr;
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002294 }
Chad Rosierc1183952012-06-26 22:30:43 +00002295
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00002296 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2297 ExprResult Init = ParseInitializer();
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002298
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002299 // If this is the only decl in (possibly) range based for statement,
2300 // our best guess is that the user meant ':' instead of '='.
2301 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2302 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2303 << FixItHint::CreateReplacement(EqualLoc, ":");
2304 // We are trying to stop parser from looking for ';' in this for
2305 // statement, therefore preventing spurious errors to be issued.
2306 FRI->ColonLoc = EqualLoc;
2307 Init = ExprError();
2308 FRI->RangeExpr = Init;
2309 }
2310
Richard Smithc95d2c52017-09-22 04:25:05 +00002311 InitScope.pop();
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002312
Douglas Gregor23996282009-05-12 21:31:51 +00002313 if (Init.isInvalid()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002314 SmallVector<tok::TokenKind, 2> StopTokens;
2315 StopTokens.push_back(tok::comma);
Faisal Vali421b2d12017-12-29 05:41:00 +00002316 if (D.getContext() == DeclaratorContext::ForContext ||
2317 D.getContext() == DeclaratorContext::InitStmtContext)
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002318 StopTokens.push_back(tok::r_paren);
2319 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
Douglas Gregor604c3022010-03-01 18:27:54 +00002320 Actions.ActOnInitializerError(ThisDecl);
2321 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002322 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002323 /*DirectInit=*/false);
Douglas Gregor23996282009-05-12 21:31:51 +00002324 }
2325 } else if (Tok.is(tok::l_paren)) {
2326 // Parse C++ direct initializer: '(' expression-list ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002327 BalancedDelimiterTracker T(*this, tok::l_paren);
2328 T.consumeOpen();
2329
Benjamin Kramerf0623432012-08-23 22:51:59 +00002330 ExprVector Exprs;
Douglas Gregor23996282009-05-12 21:31:51 +00002331 CommaLocsTy CommaLocs;
2332
Richard Smithc95d2c52017-09-22 04:25:05 +00002333 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Douglas Gregor613bf102009-12-22 17:47:17 +00002334
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002335 llvm::function_ref<void()> ExprListCompleter;
2336 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2337 auto ConstructorCompleter = [&, ThisVarDecl] {
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 Biryukov832c4af2018-09-07 14:04:39 +00002342 Actions.CodeCompleteExpression(getCurScope(), PreferredType);
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002343 };
2344 if (ThisVarDecl) {
2345 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2346 // VarDecl. This is an error and it is reported in a call to
2347 // Actions.ActOnInitializerError(). However, we call
Ilya Biryukov832c4af2018-09-07 14:04:39 +00002348 // ProduceConstructorSignatureHelp only on VarDecls, falling back to
2349 // default completer in other cases.
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002350 ExprListCompleter = ConstructorCompleter;
2351 }
2352
2353 if (ParseExpressionList(Exprs, CommaLocs, ExprListCompleter)) {
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002354 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2355 Actions.ProduceConstructorSignatureHelp(
2356 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2357 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2358 CalledSignatureHelp = true;
2359 }
David Blaikieeae04112012-10-10 23:15:05 +00002360 Actions.ActOnInitializerError(ThisDecl);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002361 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor23996282009-05-12 21:31:51 +00002362 } else {
2363 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002364 T.consumeClose();
Douglas Gregor23996282009-05-12 21:31:51 +00002365
2366 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2367 "Unexpected number of commas!");
Douglas Gregor613bf102009-12-22 17:47:17 +00002368
Richard Smithc95d2c52017-09-22 04:25:05 +00002369 InitScope.pop();
Douglas Gregor613bf102009-12-22 17:47:17 +00002370
Sebastian Redla9351792012-02-11 23:51:47 +00002371 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2372 T.getCloseLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002373 Exprs);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002374 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002375 /*DirectInit=*/true);
Douglas Gregor23996282009-05-12 21:31:51 +00002376 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002377 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
Fariborz Jahanian8be1ecd2012-07-03 23:22:13 +00002378 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
Sebastian Redl3da34892011-06-05 12:23:16 +00002379 // Parse C++0x braced-init-list.
Richard Smith5d164bc2011-10-15 05:09:34 +00002380 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2381
Richard Smithc95d2c52017-09-22 04:25:05 +00002382 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Sebastian Redl3da34892011-06-05 12:23:16 +00002383
2384 ExprResult Init(ParseBraceInitializer());
2385
Richard Smithc95d2c52017-09-22 04:25:05 +00002386 InitScope.pop();
Sebastian Redl3da34892011-06-05 12:23:16 +00002387
2388 if (Init.isInvalid()) {
2389 Actions.ActOnInitializerError(ThisDecl);
2390 } else
Richard Smith3beb7c62017-01-12 02:27:38 +00002391 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
Sebastian Redl3da34892011-06-05 12:23:16 +00002392
Douglas Gregor23996282009-05-12 21:31:51 +00002393 } else {
Richard Smith3beb7c62017-01-12 02:27:38 +00002394 Actions.ActOnUninitializedDecl(ThisDecl);
Douglas Gregor23996282009-05-12 21:31:51 +00002395 }
2396
Richard Smithb2bc2e62011-02-21 20:05:19 +00002397 Actions.FinalizeDeclaration(ThisDecl);
2398
Douglas Gregor23996282009-05-12 21:31:51 +00002399 return ThisDecl;
2400}
2401
Chris Lattner1890ac82006-08-13 01:16:23 +00002402/// ParseSpecifierQualifierList
2403/// specifier-qualifier-list:
2404/// type-specifier specifier-qualifier-list[opt]
2405/// type-qualifier specifier-qualifier-list[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002406/// [GNU] attributes specifier-qualifier-list[opt]
Chris Lattner1890ac82006-08-13 01:16:23 +00002407///
Richard Smithc5b05522012-03-12 07:56:15 +00002408void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2409 DeclSpecContext DSC) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002410 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2411 /// parse declaration-specifiers and complain about extra stuff.
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002412 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
Faisal Valia534f072018-04-26 00:42:40 +00002413 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
Mike Stump11289f42009-09-09 15:08:12 +00002414
Chris Lattner1890ac82006-08-13 01:16:23 +00002415 // Validate declspec for type-name.
2416 unsigned Specs = DS.getParsedSpecifiers();
Richard Smith649c7b062014-01-08 00:56:48 +00002417 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
Richard Smithc5b05522012-03-12 07:56:15 +00002418 Diag(Tok, diag::err_expected_type);
2419 DS.SetTypeSpecError();
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00002420 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002421 Diag(Tok, diag::err_typename_requires_specqual);
Richard Smithc5b05522012-03-12 07:56:15 +00002422 if (!DS.hasTypeSpecifier())
2423 DS.SetTypeSpecError();
2424 }
Mike Stump11289f42009-09-09 15:08:12 +00002425
Chris Lattner1b22eed2006-11-28 05:12:07 +00002426 // Issue diagnostic and remove storage class if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002427 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
Chris Lattner1b22eed2006-11-28 05:12:07 +00002428 if (DS.getStorageClassSpecLoc().isValid())
2429 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2430 else
Richard Smithb4a9e862013-04-12 22:46:28 +00002431 Diag(DS.getThreadStorageClassSpecLoc(),
2432 diag::err_typename_invalid_storageclass);
Chris Lattnera925dc62006-11-28 04:33:46 +00002433 DS.ClearStorageClassSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002434 }
Mike Stump11289f42009-09-09 15:08:12 +00002435
Craig Topper3f13d4d22015-11-14 18:15:55 +00002436 // Issue diagnostic and remove function specifier if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002437 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
Douglas Gregor61956c42008-10-31 09:07:45 +00002438 if (DS.isInlineSpecified())
2439 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2440 if (DS.isVirtualSpecified())
2441 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2442 if (DS.isExplicitSpecified())
2443 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
Chris Lattnera925dc62006-11-28 04:33:46 +00002444 DS.ClearFunctionSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002445 }
Richard Smithc5b05522012-03-12 07:56:15 +00002446
2447 // Issue diagnostic and remove constexpr specfier if present.
Faisal Vali7db85c52017-12-31 00:06:40 +00002448 if (DS.isConstexprSpecified() && DSC != DeclSpecContext::DSC_condition) {
Richard Smithc5b05522012-03-12 07:56:15 +00002449 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2450 DS.ClearConstexprSpec();
2451 }
Chris Lattner1890ac82006-08-13 01:16:23 +00002452}
Chris Lattner53361ac2006-08-10 05:19:57 +00002453
Chris Lattner6cc055a2009-04-12 20:42:31 +00002454/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2455/// specified token is valid after the identifier in a declarator which
2456/// immediately follows the declspec. For example, these things are valid:
2457///
2458/// int x [ 4]; // direct-declarator
2459/// int x ( int y); // direct-declarator
2460/// int(int x ) // direct-declarator
2461/// int x ; // simple-declaration
2462/// int x = 17; // init-declarator-list
2463/// int x , y; // init-declarator-list
2464/// int x __asm__ ("foo"); // init-declarator-list
Chris Lattnera723ba92009-04-14 21:16:09 +00002465/// int x : 4; // struct-declarator
Chris Lattner2b988c12009-04-12 22:29:43 +00002466/// int x { 5}; // C++'0x unified initializers
Chris Lattner6cc055a2009-04-12 20:42:31 +00002467///
2468/// This is not, because 'x' does not immediately follow the declspec (though
2469/// ')' happens to be valid anyway).
2470/// int (x)
2471///
2472static bool isValidAfterIdentifierInDeclarator(const Token &T) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002473 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2474 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2475 tok::colon);
Chris Lattner6cc055a2009-04-12 20:42:31 +00002476}
2477
Chris Lattner20a0c612009-04-14 21:34:55 +00002478/// ParseImplicitInt - This method is called when we have an non-typename
2479/// identifier in a declspec (which normally terminates the decl spec) when
2480/// the declspec has no type specifier. In this case, the declspec is either
2481/// malformed or is "implicit int" (in K&R and C89).
2482///
2483/// This method handles diagnosing this prettily and returns false if the
2484/// declspec is done being processed. If it recovers and thinks there may be
2485/// other pieces of declspec after it, it returns true.
2486///
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002487bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002488 const ParsedTemplateInfo &TemplateInfo,
Richard Smitha0a5d502014-05-08 22:32:00 +00002489 AccessSpecifier AS, DeclSpecContext DSC,
Michael Han9407e502012-11-26 22:54:45 +00002490 ParsedAttributesWithRange &Attrs) {
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002491 assert(Tok.is(tok::identifier) && "should have identifier");
Mike Stump11289f42009-09-09 15:08:12 +00002492
Chris Lattner20a0c612009-04-14 21:34:55 +00002493 SourceLocation Loc = Tok.getLocation();
2494 // If we see an identifier that is not a type name, we normally would
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002495 // parse it as the identifier being declared. However, when a typename
Chris Lattner20a0c612009-04-14 21:34:55 +00002496 // is typo'd or the definition is not included, this will incorrectly
2497 // parse the typename as the identifier name and fall over misparsing
2498 // later parts of the diagnostic.
2499 //
2500 // As such, we try to do some look-ahead in cases where this would
2501 // otherwise be an "implicit-int" case to see if this is invalid. For
2502 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2503 // an identifier with implicit int, we'd get a parse error because the
2504 // next token is obviously invalid for a type. Parse these as a case
2505 // with an invalid type specifier.
2506 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
Mike Stump11289f42009-09-09 15:08:12 +00002507
Chris Lattner20a0c612009-04-14 21:34:55 +00002508 // Since we know that this either implicit int (which is rare) or an
Richard Smitha952ebb2012-05-15 21:01:51 +00002509 // error, do lookahead to try to do better recovery. This never applies
2510 // within a type specifier. Outside of C++, we allow this even if the
2511 // language doesn't "officially" support implicit int -- we support
Richard Smith3b870382013-04-30 22:43:51 +00002512 // implicit int as an extension in C99 and C11.
Richard Smith649c7b062014-01-08 00:56:48 +00002513 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
Richard Smithc5b05522012-03-12 07:56:15 +00002514 isValidAfterIdentifierInDeclarator(NextToken())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002515 // If this token is valid for implicit int, e.g. "static x = 4", then
2516 // we just avoid eating the identifier, so it will be parsed as the
2517 // identifier in the declarator.
2518 return false;
2519 }
Mike Stump11289f42009-09-09 15:08:12 +00002520
Richard Smitha952ebb2012-05-15 21:01:51 +00002521 if (getLangOpts().CPlusPlus &&
2522 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2523 // Don't require a type specifier if we have the 'auto' storage class
2524 // specifier in C++98 -- we'll promote it to a type specifier.
Richard Smithfb8b7b92013-10-15 00:00:26 +00002525 if (SS)
2526 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
Richard Smitha952ebb2012-05-15 21:01:51 +00002527 return false;
2528 }
2529
Reid Kleckner9a96e422016-05-24 21:23:54 +00002530 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2531 getLangOpts().MSVCCompat) {
2532 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2533 // Give Sema a chance to recover if we are in a template with dependent base
2534 // classes.
2535 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2536 *Tok.getIdentifierInfo(), Tok.getLocation(),
Faisal Vali7db85c52017-12-31 00:06:40 +00002537 DSC == DeclSpecContext::DSC_template_type_arg)) {
Reid Kleckner9a96e422016-05-24 21:23:54 +00002538 const char *PrevSpec;
2539 unsigned DiagID;
2540 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2541 Actions.getASTContext().getPrintingPolicy());
2542 DS.SetRangeEnd(Tok.getLocation());
2543 ConsumeToken();
2544 return false;
2545 }
2546 }
2547
Chris Lattner20a0c612009-04-14 21:34:55 +00002548 // Otherwise, if we don't consume this token, we are going to emit an
2549 // error anyway. Try to recover from various common problems. Check
2550 // to see if this was a reference to a tag name without a tag specified.
2551 // This is a common problem in C (saying 'foo' instead of 'struct foo').
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002552 //
2553 // C++ doesn't need this, and isTagName doesn't take SS.
Craig Topper161e4db2014-05-21 06:02:52 +00002554 if (SS == nullptr) {
2555 const char *TagName = nullptr, *FixitTagName = nullptr;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002556 tok::TokenKind TagKind = tok::unknown;
Mike Stump11289f42009-09-09 15:08:12 +00002557
Douglas Gregor0be31a22010-07-02 17:43:08 +00002558 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002559 default: break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002560 case DeclSpec::TST_enum:
2561 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2562 case DeclSpec::TST_union:
2563 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2564 case DeclSpec::TST_struct:
2565 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
Joao Matosdc86f942012-08-31 18:45:21 +00002566 case DeclSpec::TST_interface:
2567 TagName="__interface"; FixitTagName = "__interface ";
2568 TagKind=tok::kw___interface;break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002569 case DeclSpec::TST_class:
2570 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
Chris Lattner20a0c612009-04-14 21:34:55 +00002571 }
Mike Stump11289f42009-09-09 15:08:12 +00002572
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002573 if (TagName) {
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002574 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2575 LookupResult R(Actions, TokenName, SourceLocation(),
2576 Sema::LookupOrdinaryName);
2577
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002578 Diag(Loc, diag::err_use_of_tag_name_without_tag)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002579 << TokenName << TagName << getLangOpts().CPlusPlus
2580 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2581
2582 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2583 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2584 I != IEnd; ++I)
Kaelyn Uhrain3fe3f852012-04-27 18:26:49 +00002585 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002586 << TokenName << TagName;
2587 }
Mike Stump11289f42009-09-09 15:08:12 +00002588
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002589 // Parse this as a tag as if the missing tag were present.
2590 if (TagKind == tok::kw_enum)
Faisal Vali7db85c52017-12-31 00:06:40 +00002591 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2592 DeclSpecContext::DSC_normal);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002593 else
Richard Smithc5b05522012-03-12 07:56:15 +00002594 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
Faisal Vali7db85c52017-12-31 00:06:40 +00002595 /*EnteringContext*/ false,
2596 DeclSpecContext::DSC_normal, Attrs);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002597 return true;
2598 }
Chris Lattner20a0c612009-04-14 21:34:55 +00002599 }
Mike Stump11289f42009-09-09 15:08:12 +00002600
Richard Smithfe904f02012-05-15 21:29:55 +00002601 // Determine whether this identifier could plausibly be the name of something
Richard Smithedd124e2012-05-15 21:42:17 +00002602 // being declared (with a missing type).
Faisal Vali7db85c52017-12-31 00:06:40 +00002603 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2604 DSC == DeclSpecContext::DSC_class)) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002605 // Look ahead to the next token to try to figure out what this declaration
2606 // was supposed to be.
2607 switch (NextToken().getKind()) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002608 case tok::l_paren: {
2609 // static x(4); // 'x' is not a type
2610 // x(int n); // 'x' is not a type
2611 // x (*p)[]; // 'x' is a type
2612 //
Richard Smitha0a5d502014-05-08 22:32:00 +00002613 // Since we're in an error case, we can afford to perform a tentative
2614 // parse to determine which case we're in.
Richard Smitha952ebb2012-05-15 21:01:51 +00002615 TentativeParsingAction PA(*this);
2616 ConsumeToken();
2617 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2618 PA.Revert();
Richard Smithfb8b7b92013-10-15 00:00:26 +00002619
Richard Smithee390432014-05-16 01:56:53 +00002620 if (TPR != TPResult::False) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002621 // The identifier is followed by a parenthesized declarator.
2622 // It's supposed to be a type.
2623 break;
2624 }
2625
2626 // If we're in a context where we could be declaring a constructor,
2627 // check whether this is a constructor declaration with a bogus name.
Faisal Vali7db85c52017-12-31 00:06:40 +00002628 if (DSC == DeclSpecContext::DSC_class ||
2629 (DSC == DeclSpecContext::DSC_top_level && SS)) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002630 IdentifierInfo *II = Tok.getIdentifierInfo();
2631 if (Actions.isCurrentClassNameTypo(II, SS)) {
2632 Diag(Loc, diag::err_constructor_bad_name)
2633 << Tok.getIdentifierInfo() << II
2634 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2635 Tok.setIdentifierInfo(II);
2636 }
2637 }
2638 // Fall through.
Galina Kistanova77674252017-06-01 21:15:34 +00002639 LLVM_FALLTHROUGH;
Richard Smitha952ebb2012-05-15 21:01:51 +00002640 }
Richard Smithfb8b7b92013-10-15 00:00:26 +00002641 case tok::comma:
2642 case tok::equal:
2643 case tok::kw_asm:
2644 case tok::l_brace:
2645 case tok::l_square:
2646 case tok::semi:
2647 // This looks like a variable or function declaration. The type is
2648 // probably missing. We're done parsing decl-specifiers.
2649 if (SS)
2650 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2651 return false;
Richard Smitha952ebb2012-05-15 21:01:51 +00002652
2653 default:
2654 // This is probably supposed to be a type. This includes cases like:
2655 // int f(itn);
2656 // struct S { unsinged : 4; };
2657 break;
2658 }
2659 }
2660
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002661 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2662 // and attempt to recover.
John McCallba7bf592010-08-24 05:47:05 +00002663 ParsedType T;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +00002664 IdentifierInfo *II = Tok.getIdentifierInfo();
Richard Smith52f8d192017-05-10 21:32:16 +00002665 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002666 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
Richard Smith52f8d192017-05-10 21:32:16 +00002667 IsTemplateName);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002668 if (T) {
2669 // The action has suggested that the type T could be used. Set that as
2670 // the type in the declaration specifiers, consume the would-be type
2671 // name token, and we're done.
2672 const char *PrevSpec;
2673 unsigned DiagID;
2674 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2675 Actions.getASTContext().getPrintingPolicy());
2676 DS.SetRangeEnd(Tok.getLocation());
2677 ConsumeToken();
2678 // There may be other declaration specifiers after this.
2679 return true;
2680 } else if (II != Tok.getIdentifierInfo()) {
2681 // If no type was suggested, the correction is to a keyword
2682 Tok.setKind(II->getTokenID());
2683 // There may be other declaration specifiers after this.
2684 return true;
Douglas Gregor15e56022009-10-13 23:27:22 +00002685 }
Mike Stump11289f42009-09-09 15:08:12 +00002686
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002687 // Otherwise, the action had no suggestion for us. Mark this as an error.
Richard Smithc5b05522012-03-12 07:56:15 +00002688 DS.SetTypeSpecError();
Chris Lattner20a0c612009-04-14 21:34:55 +00002689 DS.SetRangeEnd(Tok.getLocation());
2690 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002691
Richard Smith52f8d192017-05-10 21:32:16 +00002692 // Eat any following template arguments.
2693 if (IsTemplateName) {
2694 SourceLocation LAngle, RAngle;
2695 TemplateArgList Args;
2696 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2697 }
2698
Chris Lattner20a0c612009-04-14 21:34:55 +00002699 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2700 // avoid rippling error messages on subsequent uses of the same type,
2701 // could be useful if #include was forgotten.
2702 return false;
2703}
2704
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002705/// Determine the declaration specifier context from the declarator
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002706/// context.
2707///
2708/// \param Context the declarator context, which is one of the
Faisal Vali421b2d12017-12-29 05:41:00 +00002709/// DeclaratorContext enumerator values.
Chad Rosierc1183952012-06-26 22:30:43 +00002710Parser::DeclSpecContext
Faisal Vali421b2d12017-12-29 05:41:00 +00002711Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2712 if (Context == DeclaratorContext::MemberContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002713 return DeclSpecContext::DSC_class;
Faisal Vali421b2d12017-12-29 05:41:00 +00002714 if (Context == DeclaratorContext::FileContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002715 return DeclSpecContext::DSC_top_level;
Faisal Vali421b2d12017-12-29 05:41:00 +00002716 if (Context == DeclaratorContext::TemplateParamContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002717 return DeclSpecContext::DSC_template_param;
Richard Smith77a9c602018-02-28 03:02:23 +00002718 if (Context == DeclaratorContext::TemplateArgContext ||
2719 Context == DeclaratorContext::TemplateTypeArgContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002720 return DeclSpecContext::DSC_template_type_arg;
Richard Smithe303e352018-02-02 22:24:54 +00002721 if (Context == DeclaratorContext::TrailingReturnContext ||
2722 Context == DeclaratorContext::TrailingReturnVarContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002723 return DeclSpecContext::DSC_trailing;
Faisal Vali421b2d12017-12-29 05:41:00 +00002724 if (Context == DeclaratorContext::AliasDeclContext ||
2725 Context == DeclaratorContext::AliasTemplateContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002726 return DeclSpecContext::DSC_alias_declaration;
2727 return DeclSpecContext::DSC_normal;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002728}
2729
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002730/// ParseAlignArgument - Parse the argument to an alignment-specifier.
2731///
2732/// FIXME: Simply returns an alignof() expression if the argument is a
2733/// type. Ideally, the type should be propagated directly into Sema.
2734///
Benjamin Kramere56f3932011-12-23 17:00:35 +00002735/// [C11] type-id
2736/// [C11] constant-expression
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002737/// [C++0x] type-id ...[opt]
2738/// [C++0x] assignment-expression ...[opt]
2739ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2740 SourceLocation &EllipsisLoc) {
2741 ExprResult ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002742 if (isTypeIdInParens()) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002743 SourceLocation TypeLoc = Tok.getLocation();
2744 ParsedType Ty = ParseTypeName().get();
2745 SourceRange TypeRange(Start, Tok.getLocation());
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002746 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2747 Ty.getAsOpaquePtr(), TypeRange);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002748 } else
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002749 ER = ParseConstantExpression();
2750
Alp Toker8fbec672013-12-17 23:29:36 +00002751 if (getLangOpts().CPlusPlus11)
2752 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002753
2754 return ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002755}
2756
2757/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2758/// attribute to Attrs.
2759///
2760/// alignment-specifier:
Benjamin Kramere56f3932011-12-23 17:00:35 +00002761/// [C11] '_Alignas' '(' type-id ')'
2762/// [C11] '_Alignas' '(' constant-expression ')'
Richard Smithd11c7a12013-01-29 01:48:07 +00002763/// [C++11] 'alignas' '(' type-id ...[opt] ')'
2764/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002765void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
Richard Smith44c247f2013-02-22 08:32:16 +00002766 SourceLocation *EndLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002767 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002768 "Not an alignment-specifier!");
2769
Richard Smithd11c7a12013-01-29 01:48:07 +00002770 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2771 SourceLocation KWLoc = ConsumeToken();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002772
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002773 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002774 if (T.expectAndConsume())
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002775 return;
2776
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002777 SourceLocation EllipsisLoc;
2778 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002779 if (ArgExpr.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002780 T.skipToEnd();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002781 return;
2782 }
2783
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002784 T.consumeClose();
Richard Smith44c247f2013-02-22 08:32:16 +00002785 if (EndLoc)
2786 *EndLoc = T.getCloseLocation();
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002787
Aaron Ballman00e99962013-08-31 01:11:41 +00002788 ArgsVector ArgExprs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002789 ArgExprs.push_back(ArgExpr.get());
Craig Topper161e4db2014-05-21 06:02:52 +00002790 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
Erich Keanee891aa92018-07-13 15:07:47 +00002791 ParsedAttr::AS_Keyword, EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002792}
2793
Richard Smith404dfb42013-11-19 22:47:36 +00002794/// Determine whether we're looking at something that might be a declarator
2795/// in a simple-declaration. If it can't possibly be a declarator, maybe
2796/// diagnose a missing semicolon after a prior tag definition in the decl
2797/// specifier.
2798///
2799/// \return \c true if an error occurred and this can't be any kind of
2800/// declaration.
2801bool
2802Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2803 DeclSpecContext DSContext,
2804 LateParsedAttrList *LateAttrs) {
2805 assert(DS.hasTagDefinition() && "shouldn't call this");
2806
Faisal Vali7db85c52017-12-31 00:06:40 +00002807 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2808 DSContext == DeclSpecContext::DSC_top_level);
Richard Smith404dfb42013-11-19 22:47:36 +00002809
2810 if (getLangOpts().CPlusPlus &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002811 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2812 tok::annot_template_id) &&
Richard Smith404dfb42013-11-19 22:47:36 +00002813 TryAnnotateCXXScopeToken(EnteringContext)) {
2814 SkipMalformedDecl();
2815 return true;
2816 }
2817
Richard Smith698875a2013-11-20 23:40:57 +00002818 bool HasScope = Tok.is(tok::annot_cxxscope);
2819 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2820 Token AfterScope = HasScope ? NextToken() : Tok;
2821
Richard Smith404dfb42013-11-19 22:47:36 +00002822 // Determine whether the following tokens could possibly be a
2823 // declarator.
Richard Smith698875a2013-11-20 23:40:57 +00002824 bool MightBeDeclarator = true;
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002825 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
Richard Smith698875a2013-11-20 23:40:57 +00002826 // A declarator-id can't start with 'typename'.
2827 MightBeDeclarator = false;
2828 } else if (AfterScope.is(tok::annot_template_id)) {
2829 // If we have a type expressed as a template-id, this cannot be a
2830 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2831 TemplateIdAnnotation *Annot =
2832 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2833 if (Annot->Kind == TNK_Type_template)
2834 MightBeDeclarator = false;
2835 } else if (AfterScope.is(tok::identifier)) {
2836 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2837
Richard Smith404dfb42013-11-19 22:47:36 +00002838 // These tokens cannot come after the declarator-id in a
2839 // simple-declaration, and are likely to come after a type-specifier.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002840 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2841 tok::annot_cxxscope, tok::coloncolon)) {
Richard Smith698875a2013-11-20 23:40:57 +00002842 // Missing a semicolon.
2843 MightBeDeclarator = false;
2844 } else if (HasScope) {
2845 // If the declarator-id has a scope specifier, it must redeclare a
2846 // previously-declared entity. If that's a type (and this is not a
2847 // typedef), that's an error.
2848 CXXScopeSpec SS;
2849 Actions.RestoreNestedNameSpecifierAnnotation(
2850 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2851 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2852 Sema::NameClassification Classification = Actions.ClassifyName(
2853 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2854 /*IsAddressOfOperand*/false);
2855 switch (Classification.getKind()) {
2856 case Sema::NC_Error:
2857 SkipMalformedDecl();
2858 return true;
Richard Smith404dfb42013-11-19 22:47:36 +00002859
Richard Smith698875a2013-11-20 23:40:57 +00002860 case Sema::NC_Keyword:
2861 case Sema::NC_NestedNameSpecifier:
2862 llvm_unreachable("typo correction and nested name specifiers not "
2863 "possible here");
Richard Smith404dfb42013-11-19 22:47:36 +00002864
Richard Smith698875a2013-11-20 23:40:57 +00002865 case Sema::NC_Type:
2866 case Sema::NC_TypeTemplate:
2867 // Not a previously-declared non-type entity.
2868 MightBeDeclarator = false;
2869 break;
Richard Smith404dfb42013-11-19 22:47:36 +00002870
Richard Smith698875a2013-11-20 23:40:57 +00002871 case Sema::NC_Unknown:
2872 case Sema::NC_Expression:
2873 case Sema::NC_VarTemplate:
2874 case Sema::NC_FunctionTemplate:
2875 // Might be a redeclaration of a prior entity.
2876 break;
2877 }
Richard Smith404dfb42013-11-19 22:47:36 +00002878 }
Richard Smith404dfb42013-11-19 22:47:36 +00002879 }
2880
Richard Smith698875a2013-11-20 23:40:57 +00002881 if (MightBeDeclarator)
Richard Smith404dfb42013-11-19 22:47:36 +00002882 return false;
2883
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002884 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002885 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
Alp Toker383d2c42014-01-01 03:08:43 +00002886 diag::err_expected_after)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002887 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
Richard Smith404dfb42013-11-19 22:47:36 +00002888
2889 // Try to recover from the typo, by dropping the tag definition and parsing
2890 // the problematic tokens as a type.
2891 //
2892 // FIXME: Split the DeclSpec into pieces for the standalone
2893 // declaration and pieces for the following declaration, instead
2894 // of assuming that all the other pieces attach to new declaration,
2895 // and call ParsedFreeStandingDeclSpec as appropriate.
2896 DS.ClearTypeSpecType();
2897 ParsedTemplateInfo NotATemplate;
Faisal Valia534f072018-04-26 00:42:40 +00002898 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
Richard Smith404dfb42013-11-19 22:47:36 +00002899 return false;
2900}
2901
Leonard Chanab80f3c2018-06-14 14:53:51 +00002902// Choose the apprpriate diagnostic error for why fixed point types are
2903// disabled, set the previous specifier, and mark as invalid.
2904static void SetupFixedPointError(const LangOptions &LangOpts,
2905 const char *&PrevSpec, unsigned &DiagID,
2906 bool &isInvalid) {
2907 assert(!LangOpts.FixedPoint);
2908 DiagID = diag::err_fixed_point_not_enabled;
2909 PrevSpec = ""; // Not used by diagnostic
2910 isInvalid = true;
2911}
2912
Faisal Valia534f072018-04-26 00:42:40 +00002913/// ParseDeclarationSpecifiers
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002914/// declaration-specifiers: [C99 6.7]
Chris Lattner3b561a32006-08-13 00:12:11 +00002915/// storage-class-specifier declaration-specifiers[opt]
2916/// type-specifier declaration-specifiers[opt]
Chris Lattner3b561a32006-08-13 00:12:11 +00002917/// [C99] function-specifier declaration-specifiers[opt]
Benjamin Kramere56f3932011-12-23 17:00:35 +00002918/// [C11] alignment-specifier declaration-specifiers[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002919/// [GNU] attributes declaration-specifiers[opt]
Douglas Gregor26701a42011-09-09 02:06:17 +00002920/// [Clang] '__module_private__' declaration-specifiers[opt]
Douglas Gregorab209d82015-07-07 03:58:42 +00002921/// [ObjC1] '__kindof' declaration-specifiers[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002922///
Chris Lattnerf63f89a2006-08-05 03:28:50 +00002923/// storage-class-specifier: [C99 6.7.1]
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002924/// 'typedef'
2925/// 'extern'
2926/// 'static'
2927/// 'auto'
2928/// 'register'
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002929/// [C++] 'mutable'
Richard Smithb4a9e862013-04-12 22:46:28 +00002930/// [C++11] 'thread_local'
2931/// [C11] '_Thread_local'
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002932/// [GNU] '__thread'
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002933/// function-specifier: [C99 6.7.4]
Chris Lattner3b561a32006-08-13 00:12:11 +00002934/// [C99] 'inline'
Douglas Gregor61956c42008-10-31 09:07:45 +00002935/// [C++] 'virtual'
2936/// [C++] 'explicit'
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00002937/// [OpenCL] '__kernel'
Anders Carlssoncd8db412009-05-06 04:46:28 +00002938/// 'friend': [C++ dcl.friend]
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00002939/// 'constexpr': [C++0x dcl.constexpr]
Faisal Valia534f072018-04-26 00:42:40 +00002940void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002941 const ParsedTemplateInfo &TemplateInfo,
John McCall07e91c02009-08-06 02:15:43 +00002942 AccessSpecifier AS,
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002943 DeclSpecContext DSContext,
2944 LateParsedAttrList *LateAttrs) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002945 if (DS.getSourceRange().isInvalid()) {
David Majnemer24b28302014-07-26 05:41:31 +00002946 // Start the range at the current token but make the end of the range
2947 // invalid. This will make the entire range invalid unless we successfully
2948 // consume a token.
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002949 DS.SetRangeStart(Tok.getLocation());
David Majnemer24b28302014-07-26 05:41:31 +00002950 DS.SetRangeEnd(SourceLocation());
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002951 }
Chad Rosierc1183952012-06-26 22:30:43 +00002952
Faisal Vali7db85c52017-12-31 00:06:40 +00002953 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2954 DSContext == DeclSpecContext::DSC_top_level);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002955 bool AttrsLastTime = false;
2956 ParsedAttributesWithRange attrs(AttrFactory);
Benjamin Kramere4812142015-03-12 14:28:38 +00002957 // We use Sema's policy to get bool macros right.
Richard Smith301bc212016-05-19 01:39:10 +00002958 PrintingPolicy Policy = Actions.getPrintingPolicy();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002959 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00002960 bool isInvalid = false;
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00002961 bool isStorageClass = false;
Craig Topper161e4db2014-05-21 06:02:52 +00002962 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00002963 unsigned DiagID = 0;
2964
David Majnemer51fd8a02015-07-22 23:46:18 +00002965 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2966 // implementation for VS2013 uses _Atomic as an identifier for one of the
2967 // classes in <atomic>.
2968 //
2969 // A typedef declaration containing _Atomic<...> is among the places where
2970 // the class is used. If we are currently parsing such a declaration, treat
2971 // the token as an identifier.
2972 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2973 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2974 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2975 Tok.setKind(tok::identifier);
2976
Chris Lattner4d8f8732006-11-28 05:05:08 +00002977 SourceLocation Loc = Tok.getLocation();
Douglas Gregor450c75a2008-11-07 15:42:26 +00002978
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002979 switch (Tok.getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00002980 default:
Chris Lattner0974b232008-07-26 00:20:22 +00002981 DoneWithDeclSpec:
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002982 if (!AttrsLastTime)
2983 ProhibitAttributes(attrs);
Michael Han64536a62012-11-06 19:34:54 +00002984 else {
2985 // Reject C++11 attributes that appertain to decl specifiers as
2986 // we don't support any C++11 attributes that appertain to decl
2987 // specifiers. This also conforms to what g++ 4.8 is doing.
Richard Smith49cc1cc2016-08-18 21:59:42 +00002988 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
Michael Han64536a62012-11-06 19:34:54 +00002989
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002990 DS.takeAttributesFrom(attrs);
Michael Han64536a62012-11-06 19:34:54 +00002991 }
Peter Collingbourne70188b32011-09-29 18:03:57 +00002992
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002993 // If this is not a declaration specifier token, we're done reading decl
2994 // specifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00002995 DS.Finish(Actions, Policy);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002996 return;
Mike Stump11289f42009-09-09 15:08:12 +00002997
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002998 case tok::l_square:
2999 case tok::kw_alignas:
Aaron Ballman606093a2017-10-15 15:01:42 +00003000 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003001 goto DoneWithDeclSpec;
3002
3003 ProhibitAttributes(attrs);
3004 // FIXME: It would be good to recover by accepting the attributes,
3005 // but attempting to do that now would cause serious
3006 // madness in terms of diagnostics.
3007 attrs.clear();
3008 attrs.Range = SourceRange();
3009
3010 ParseCXX11Attributes(attrs);
3011 AttrsLastTime = true;
Chad Rosierc1183952012-06-26 22:30:43 +00003012 continue;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003013
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003014 case tok::code_completion: {
John McCallfaf5fb42010-08-26 23:41:50 +00003015 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003016 if (DS.hasTypeSpecifier()) {
3017 bool AllowNonIdentifiers
3018 = (getCurScope()->getFlags() & (Scope::ControlScope |
3019 Scope::BlockScope |
3020 Scope::TemplateParamScope |
3021 Scope::FunctionPrototypeScope |
3022 Scope::AtCatchScope)) == 0;
3023 bool AllowNestedNameSpecifiers
Faisal Vali7db85c52017-12-31 00:06:40 +00003024 = DSContext == DeclSpecContext::DSC_top_level ||
3025 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003026
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003027 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
Chad Rosierc1183952012-06-26 22:30:43 +00003028 AllowNonIdentifiers,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003029 AllowNestedNameSpecifiers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003030 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00003031 }
3032
Douglas Gregor80039242011-02-15 20:33:25 +00003033 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3034 CCC = Sema::PCC_LocalDeclarationSpecifiers;
3035 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
Faisal Vali7db85c52017-12-31 00:06:40 +00003036 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3037 : Sema::PCC_Template;
3038 else if (DSContext == DeclSpecContext::DSC_class)
John McCallfaf5fb42010-08-26 23:41:50 +00003039 CCC = Sema::PCC_Class;
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +00003040 else if (CurParsedObjCImpl)
John McCallfaf5fb42010-08-26 23:41:50 +00003041 CCC = Sema::PCC_ObjCImplementation;
Chad Rosierc1183952012-06-26 22:30:43 +00003042
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003043 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003044 return cutOffParsing();
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003045 }
3046
Chris Lattnerbd31aa32009-01-05 00:07:25 +00003047 case tok::coloncolon: // ::foo::bar
John McCall1f476a12010-02-26 08:45:28 +00003048 // C++ scope specifier. Annotate and loop, or bail out on error.
Eli Friedman2a1d9a92013-08-15 23:59:20 +00003049 if (TryAnnotateCXXScopeToken(EnteringContext)) {
John McCall1f476a12010-02-26 08:45:28 +00003050 if (!DS.hasTypeSpecifier())
3051 DS.SetTypeSpecError();
3052 goto DoneWithDeclSpec;
3053 }
John McCall8bc2a702010-03-01 18:20:46 +00003054 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3055 goto DoneWithDeclSpec;
John McCall1f476a12010-02-26 08:45:28 +00003056 continue;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003057
3058 case tok::annot_cxxscope: {
Richard Smith3092a3b2012-05-09 18:56:43 +00003059 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003060 goto DoneWithDeclSpec;
3061
John McCall9dab4e62009-12-12 11:40:51 +00003062 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00003063 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3064 Tok.getAnnotationRange(),
3065 SS);
John McCall9dab4e62009-12-12 11:40:51 +00003066
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003067 // We are looking for a qualified typename.
Douglas Gregor167fa622009-03-25 15:40:00 +00003068 Token Next = NextToken();
Mike Stump11289f42009-09-09 15:08:12 +00003069 if (Next.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003070 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
Douglas Gregorb67535d2009-03-31 00:43:58 +00003071 ->Kind == TNK_Type_template) {
Douglas Gregor167fa622009-03-25 15:40:00 +00003072 // We have a qualified template-id, e.g., N::A<int>
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003073
Richard Smith74f02342017-01-19 21:00:13 +00003074 // If this would be a valid constructor declaration with template
3075 // arguments, we will reject the attempt to form an invalid type-id
3076 // referring to the injected-class-name when we annotate the token,
3077 // per C++ [class.qual]p2.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003078 //
Richard Smith74f02342017-01-19 21:00:13 +00003079 // To improve diagnostics for this case, parse the declaration as a
3080 // constructor (and reject the extra template arguments later).
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003081 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
Faisal Vali7db85c52017-12-31 00:06:40 +00003082 if ((DSContext == DeclSpecContext::DSC_top_level ||
3083 DSContext == DeclSpecContext::DSC_class) &&
John McCall84821e72010-04-13 06:39:49 +00003084 TemplateId->Name &&
Richard Smith74f02342017-01-19 21:00:13 +00003085 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003086 isConstructorDeclarator(/*Unqualified*/ false)) {
Richard Smith74f02342017-01-19 21:00:13 +00003087 // The user meant this to be an out-of-line constructor
3088 // definition, but template arguments are not allowed
3089 // there. Just allow this as a constructor; we'll
3090 // complain about it later.
3091 goto DoneWithDeclSpec;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003092 }
3093
John McCall9dab4e62009-12-12 11:40:51 +00003094 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003095 ConsumeAnnotationToken(); // The C++ scope.
Mike Stump11289f42009-09-09 15:08:12 +00003096 assert(Tok.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003097 "ParseOptionalCXXScopeSpecifier not working");
Douglas Gregore7c20652011-03-02 00:47:37 +00003098 AnnotateTemplateIdTokenAsType();
Douglas Gregor167fa622009-03-25 15:40:00 +00003099 continue;
3100 }
3101
Douglas Gregorc5790df2009-09-28 07:26:33 +00003102 if (Next.is(tok::annot_typename)) {
John McCall9dab4e62009-12-12 11:40:51 +00003103 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003104 ConsumeAnnotationToken(); // The C++ scope.
John McCallba7bf592010-08-24 05:47:05 +00003105 if (Tok.getAnnotationValue()) {
3106 ParsedType T = getTypeAnnotation(Tok);
Nico Weber77430342010-11-22 10:30:56 +00003107 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
Chad Rosierc1183952012-06-26 22:30:43 +00003108 Tok.getAnnotationEndLoc(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003109 PrevSpec, DiagID, T, Policy);
Richard Smithda837032012-09-14 18:27:01 +00003110 if (isInvalid)
3111 break;
John McCallba7bf592010-08-24 05:47:05 +00003112 }
Douglas Gregorc5790df2009-09-28 07:26:33 +00003113 else
3114 DS.SetTypeSpecError();
3115 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003116 ConsumeAnnotationToken(); // The typename
Douglas Gregorc5790df2009-09-28 07:26:33 +00003117 }
3118
Douglas Gregor167fa622009-03-25 15:40:00 +00003119 if (Next.isNot(tok::identifier))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003120 goto DoneWithDeclSpec;
3121
Richard Smith74f02342017-01-19 21:00:13 +00003122 // Check whether this is a constructor declaration. If we're in a
3123 // context where the identifier could be a class name, and it has the
3124 // shape of a constructor declaration, process it as one.
Faisal Vali7db85c52017-12-31 00:06:40 +00003125 if ((DSContext == DeclSpecContext::DSC_top_level ||
3126 DSContext == DeclSpecContext::DSC_class) &&
Chad Rosierc1183952012-06-26 22:30:43 +00003127 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
Richard Smith74f02342017-01-19 21:00:13 +00003128 &SS) &&
3129 isConstructorDeclarator(/*Unqualified*/ false))
3130 goto DoneWithDeclSpec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003131
David Blaikieefdccaa2016-01-15 23:43:34 +00003132 ParsedType TypeRep =
3133 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3134 getCurScope(), &SS, false, false, nullptr,
3135 /*IsCtorOrDtorName=*/false,
Richard Smith600b5262017-01-26 20:40:47 +00003136 /*WantNonTrivialSourceInfo=*/true,
3137 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003138
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003139 // If the referenced identifier is not a type, then this declspec is
3140 // erroneous: We already checked about that it has no type specifier, and
3141 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
Mike Stump11289f42009-09-09 15:08:12 +00003142 // typename.
David Blaikie7d170102013-05-15 07:37:26 +00003143 if (!TypeRep) {
Richard Smithaf3b3252017-05-18 19:21:48 +00003144 // Eat the scope spec so the identifier is current.
3145 ConsumeAnnotationToken();
Michael Han9407e502012-11-26 22:54:45 +00003146 ParsedAttributesWithRange Attrs(AttrFactory);
3147 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3148 if (!Attrs.empty()) {
3149 AttrsLastTime = true;
3150 attrs.takeAllFrom(Attrs);
3151 }
3152 continue;
3153 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003154 goto DoneWithDeclSpec;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003155 }
Mike Stump11289f42009-09-09 15:08:12 +00003156
John McCall9dab4e62009-12-12 11:40:51 +00003157 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003158 ConsumeAnnotationToken(); // The C++ scope.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003159
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003160 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003161 DiagID, TypeRep, Policy);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003162 if (isInvalid)
3163 break;
Mike Stump11289f42009-09-09 15:08:12 +00003164
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003165 DS.SetRangeEnd(Tok.getLocation());
3166 ConsumeToken(); // The typename.
3167
3168 continue;
3169 }
Mike Stump11289f42009-09-09 15:08:12 +00003170
Chris Lattnere387d9e2009-01-21 19:48:37 +00003171 case tok::annot_typename: {
Richard Smith404dfb42013-11-19 22:47:36 +00003172 // If we've previously seen a tag definition, we were almost surely
3173 // missing a semicolon after it.
3174 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3175 goto DoneWithDeclSpec;
3176
John McCallba7bf592010-08-24 05:47:05 +00003177 if (Tok.getAnnotationValue()) {
3178 ParsedType T = getTypeAnnotation(Tok);
Nico Weber7f8bb362010-11-22 12:50:03 +00003179 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003180 DiagID, T, Policy);
John McCallba7bf592010-08-24 05:47:05 +00003181 } else
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003182 DS.SetTypeSpecError();
Chad Rosierc1183952012-06-26 22:30:43 +00003183
Chris Lattner005fc1b2010-04-05 18:18:31 +00003184 if (isInvalid)
3185 break;
3186
Chris Lattnere387d9e2009-01-21 19:48:37 +00003187 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003188 ConsumeAnnotationToken(); // The typename
Mike Stump11289f42009-09-09 15:08:12 +00003189
Chris Lattnere387d9e2009-01-21 19:48:37 +00003190 continue;
3191 }
Mike Stump11289f42009-09-09 15:08:12 +00003192
Douglas Gregor06873092011-04-28 15:48:45 +00003193 case tok::kw___is_signed:
3194 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3195 // typically treats it as a trait. If we see __is_signed as it appears
3196 // in libstdc++, e.g.,
3197 //
3198 // static const bool __is_signed;
3199 //
3200 // then treat __is_signed as an identifier rather than as a keyword.
Faisal Vali090da2d2018-01-01 18:23:28 +00003201 if (DS.getTypeSpecType() == TST_bool &&
Douglas Gregor06873092011-04-28 15:48:45 +00003202 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
Alp Toker47642d22013-12-03 06:13:01 +00003203 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3204 TryKeywordIdentFallback(true);
Douglas Gregor06873092011-04-28 15:48:45 +00003205
3206 // We're done with the declaration-specifiers.
3207 goto DoneWithDeclSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00003208
Chris Lattner16fac4f2008-07-26 01:18:38 +00003209 // typedef-name
Nikola Smiljanic67860242014-09-26 00:28:20 +00003210 case tok::kw___super:
David Blaikie15a430a2011-12-04 05:04:18 +00003211 case tok::kw_decltype:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003212 case tok::identifier: {
Reid Klecknerc582f012014-07-14 18:19:58 +00003213 // This identifier can only be a typedef name if we haven't already seen
3214 // a type-specifier. Without this check we misparse:
3215 // typedef int X; struct Y { short X; }; as 'short int'.
3216 if (DS.hasTypeSpecifier())
3217 goto DoneWithDeclSpec;
3218
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003219 // If the token is an identifier named "__declspec" and Microsoft
3220 // extensions are not enabled, it is likely that there will be cascading
3221 // parse errors if this really is a __declspec attribute. Attempt to
3222 // recognize that scenario and recover gracefully.
3223 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3224 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3225 Diag(Loc, diag::err_ms_attributes_not_enabled);
3226
3227 // The next token should be an open paren. If it is, eat the entire
3228 // attribute declaration and continue.
3229 if (NextToken().is(tok::l_paren)) {
3230 // Consume the __declspec identifier.
Richard Trieuba057372017-02-14 23:56:55 +00003231 ConsumeToken();
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003232
3233 // Eat the parens and everything between them.
3234 BalancedDelimiterTracker T(*this, tok::l_paren);
3235 if (T.consumeOpen()) {
3236 assert(false && "Not a left paren?");
3237 return;
3238 }
3239 T.skipToEnd();
3240 continue;
3241 }
3242 }
3243
Serge Pavlov458ea762014-07-16 05:16:52 +00003244 // In C++, check to see if this is a scope specifier like foo::bar::, if
3245 // so handle it as such. This is important for ctor parsing.
3246 if (getLangOpts().CPlusPlus) {
3247 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3248 DS.SetTypeSpecError();
3249 goto DoneWithDeclSpec;
3250 }
3251 if (!Tok.is(tok::identifier))
3252 continue;
3253 }
3254
John Thompson22334602010-02-05 00:12:22 +00003255 // Check for need to substitute AltiVec keyword tokens.
3256 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3257 break;
3258
Richard Smith3092a3b2012-05-09 18:56:43 +00003259 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3260 // allow the use of a typedef name as a type specifier.
3261 if (DS.isTypeAltiVecVector())
3262 goto DoneWithDeclSpec;
3263
Faisal Vali7db85c52017-12-31 00:06:40 +00003264 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3265 isObjCInstancetype()) {
Douglas Gregor5c0870a2015-06-19 23:18:00 +00003266 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3267 assert(TypeRep);
3268 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3269 DiagID, TypeRep, Policy);
3270 if (isInvalid)
3271 break;
3272
3273 DS.SetRangeEnd(Loc);
3274 ConsumeToken();
3275 continue;
3276 }
3277
Richard Smith715ee072018-06-20 21:58:20 +00003278 // If we're in a context where the identifier could be a class name,
3279 // check whether this is a constructor declaration.
3280 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3281 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3282 isConstructorDeclarator(/*Unqualified*/true))
3283 goto DoneWithDeclSpec;
3284
Richard Smith600b5262017-01-26 20:40:47 +00003285 ParsedType TypeRep = Actions.getTypeName(
3286 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3287 false, false, nullptr, false, false,
3288 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003289
Chris Lattner6cc055a2009-04-12 20:42:31 +00003290 // If this is not a typedef name, don't parse it as part of the declspec,
3291 // it must be an implicit int or an error.
John McCallba7bf592010-08-24 05:47:05 +00003292 if (!TypeRep) {
Michael Han9407e502012-11-26 22:54:45 +00003293 ParsedAttributesWithRange Attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +00003294 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
Michael Han9407e502012-11-26 22:54:45 +00003295 if (!Attrs.empty()) {
3296 AttrsLastTime = true;
3297 attrs.takeAllFrom(Attrs);
3298 }
3299 continue;
3300 }
Chris Lattner16fac4f2008-07-26 01:18:38 +00003301 goto DoneWithDeclSpec;
Chris Lattner6cc055a2009-04-12 20:42:31 +00003302 }
Douglas Gregor8bf42052009-02-09 18:46:07 +00003303
Richard Smith35845152017-02-07 01:37:30 +00003304 // Likewise, if this is a context where the identifier could be a template
3305 // name, check whether this is a deduction guide declaration.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003306 if (getLangOpts().CPlusPlus17 &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003307 (DSContext == DeclSpecContext::DSC_class ||
3308 DSContext == DeclSpecContext::DSC_top_level) &&
Richard Smith35845152017-02-07 01:37:30 +00003309 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3310 Tok.getLocation()) &&
3311 isConstructorDeclarator(/*Unqualified*/ true,
3312 /*DeductionGuide*/ true))
3313 goto DoneWithDeclSpec;
3314
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003315 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003316 DiagID, TypeRep, Policy);
Chris Lattner16fac4f2008-07-26 01:18:38 +00003317 if (isInvalid)
3318 break;
Mike Stump11289f42009-09-09 15:08:12 +00003319
Chris Lattner16fac4f2008-07-26 01:18:38 +00003320 DS.SetRangeEnd(Tok.getLocation());
3321 ConsumeToken(); // The identifier
3322
Douglas Gregore9d95f12015-07-07 03:57:35 +00003323 // Objective-C supports type arguments and protocol references
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003324 // following an Objective-C object or object pointer
3325 // type. Handle either one of them.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003326 if (Tok.is(tok::less) && getLangOpts().ObjC) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003327 SourceLocation NewEndLoc;
3328 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3329 Loc, TypeRep, /*consumeLastToken=*/true,
3330 NewEndLoc);
3331 if (NewTypeRep.isUsable()) {
3332 DS.UpdateTypeRep(NewTypeRep.get());
3333 DS.SetRangeEnd(NewEndLoc);
3334 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00003335 }
Chad Rosierc1183952012-06-26 22:30:43 +00003336
Steve Naroffcd5e7822008-09-22 10:28:57 +00003337 // Need to support trailing type qualifiers (e.g. "id<p> const").
3338 // If a type specifier follows, it will be diagnosed elsewhere.
3339 continue;
Chris Lattner16fac4f2008-07-26 01:18:38 +00003340 }
Douglas Gregor7f741122009-02-25 19:37:18 +00003341
3342 // type-name
3343 case tok::annot_template_id: {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003344 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorb67535d2009-03-31 00:43:58 +00003345 if (TemplateId->Kind != TNK_Type_template) {
Douglas Gregor7f741122009-02-25 19:37:18 +00003346 // This template-id does not refer to a type name, so we're
3347 // done with the type-specifiers.
3348 goto DoneWithDeclSpec;
3349 }
3350
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003351 // If we're in a context where the template-id could be a
3352 // constructor name or specialization, check whether this is a
3353 // constructor declaration.
Faisal Vali7db85c52017-12-31 00:06:40 +00003354 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00003355 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
Richard Smith446161b2014-03-03 21:12:53 +00003356 isConstructorDeclarator(TemplateId->SS.isEmpty()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003357 goto DoneWithDeclSpec;
3358
Douglas Gregor7f741122009-02-25 19:37:18 +00003359 // Turn the template-id annotation token into a type annotation
3360 // token, then try again to parse it as a type-specifier.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003361 AnnotateTemplateIdTokenAsType();
Douglas Gregor7f741122009-02-25 19:37:18 +00003362 continue;
3363 }
3364
Chris Lattnere37e2332006-08-15 04:50:22 +00003365 // GNU attributes support.
3366 case tok::kw___attribute:
Craig Topper161e4db2014-05-21 06:02:52 +00003367 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
Chris Lattnerb95cca02006-10-17 03:01:08 +00003368 continue;
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003369
3370 // Microsoft declspec support.
3371 case tok::kw___declspec:
Aaron Ballman068aa512015-05-20 20:58:33 +00003372 ParseMicrosoftDeclSpecs(DS.getAttributes());
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003373 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003374
Steve Naroff44ac7772008-12-25 14:16:32 +00003375 // Microsoft single token adornments.
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003376 case tok::kw___forceinline: {
Serge Pavlov750db652013-11-13 06:57:53 +00003377 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003378 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Richard Smithda837032012-09-14 18:27:01 +00003379 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00003380 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00003381 nullptr, 0, ParsedAttr::AS_Keyword);
Richard Smithda837032012-09-14 18:27:01 +00003382 break;
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003383 }
Eli Friedman53339e02009-06-08 23:27:34 +00003384
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003385 case tok::kw___unaligned:
3386 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3387 getLangOpts());
3388 break;
3389
Aaron Ballman317a77f2013-05-22 23:25:32 +00003390 case tok::kw___sptr:
3391 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00003392 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00003393 case tok::kw___ptr32:
Steve Narofff9c29d42008-12-25 14:41:26 +00003394 case tok::kw___w64:
Steve Naroff44ac7772008-12-25 14:16:32 +00003395 case tok::kw___cdecl:
3396 case tok::kw___stdcall:
3397 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00003398 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00003399 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00003400 case tok::kw___vectorcall:
John McCall53fa7142010-12-24 02:08:15 +00003401 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00003402 continue;
3403
Dawn Perchik335e16b2010-09-03 01:29:35 +00003404 // Borland single token adornments.
3405 case tok::kw___pascal:
John McCall53fa7142010-12-24 02:08:15 +00003406 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00003407 continue;
3408
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003409 // OpenCL single token adornments.
3410 case tok::kw___kernel:
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +00003411 ParseOpenCLKernelAttributes(DS.getAttributes());
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003412 continue;
3413
Douglas Gregor261a89b2015-06-19 17:51:05 +00003414 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00003415 case tok::kw__Nonnull:
3416 case tok::kw__Nullable:
3417 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00003418 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3419 continue;
3420
Douglas Gregorab209d82015-07-07 03:58:42 +00003421 // Objective-C 'kindof' types.
3422 case tok::kw___kindof:
3423 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00003424 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00003425 (void)ConsumeToken();
3426 continue;
3427
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003428 // storage-class-specifier
3429 case tok::kw_typedef:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003430 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003431 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003432 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003433 break;
3434 case tok::kw_extern:
Richard Smithb4a9e862013-04-12 22:46:28 +00003435 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003436 Diag(Tok, diag::ext_thread_before) << "extern";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003437 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003438 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003439 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003440 break;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003441 case tok::kw___private_extern__:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003442 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003443 Loc, PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003444 isStorageClass = true;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003445 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003446 case tok::kw_static:
Richard Smithb4a9e862013-04-12 22:46:28 +00003447 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003448 Diag(Tok, diag::ext_thread_before) << "static";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003449 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003450 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003451 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003452 break;
3453 case tok::kw_auto:
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003454 if (getLangOpts().CPlusPlus11) {
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003455 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003456 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003457 PrevSpec, DiagID, Policy);
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003458 if (!isInvalid)
Richard Smith58c74332011-09-04 19:54:14 +00003459 Diag(Tok, diag::ext_auto_storage_class)
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003460 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith58c74332011-09-04 19:54:14 +00003461 } else
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003462 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003463 DiagID, Policy);
Richard Smith58c74332011-09-04 19:54:14 +00003464 } else
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003465 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003466 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003467 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003468 break;
Richard Smithe301ba22015-11-11 02:02:15 +00003469 case tok::kw___auto_type:
3470 Diag(Tok, diag::ext_auto_type);
3471 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3472 DiagID, Policy);
3473 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003474 case tok::kw_register:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003475 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, 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;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003479 case tok::kw_mutable:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003480 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003481 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003482 isStorageClass = true;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003483 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003484 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00003485 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3486 PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003487 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003488 break;
3489 case tok::kw_thread_local:
3490 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3491 PrevSpec, DiagID);
Sven van Haastregtc4100832018-04-24 14:47:29 +00003492 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003493 break;
3494 case tok::kw__Thread_local:
3495 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3496 Loc, PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003497 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003498 break;
Mike Stump11289f42009-09-09 15:08:12 +00003499
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003500 // function-specifier
3501 case tok::kw_inline:
Serge Pavlov750db652013-11-13 06:57:53 +00003502 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003503 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003504 case tok::kw_virtual:
Sven van Haastregt49ffffb2018-04-23 11:23:47 +00003505 // OpenCL C++ v1.0 s2.9: the virtual function qualifier is not supported.
3506 if (getLangOpts().OpenCLCPlusPlus) {
3507 DiagID = diag::err_openclcxx_virtual_function;
3508 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3509 isInvalid = true;
3510 }
3511 else {
3512 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3513 }
Douglas Gregor61956c42008-10-31 09:07:45 +00003514 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003515 case tok::kw_explicit:
Serge Pavlov750db652013-11-13 06:57:53 +00003516 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
Douglas Gregor61956c42008-10-31 09:07:45 +00003517 break;
Richard Smith0015f092013-01-17 22:16:11 +00003518 case tok::kw__Noreturn:
3519 if (!getLangOpts().C11)
3520 Diag(Loc, diag::ext_c11_noreturn);
Serge Pavlov750db652013-11-13 06:57:53 +00003521 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
Richard Smith0015f092013-01-17 22:16:11 +00003522 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003523
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003524 // alignment-specifier
3525 case tok::kw__Alignas:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003526 if (!getLangOpts().C11)
Jordan Rose58d54722012-06-30 21:33:57 +00003527 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003528 ParseAlignmentSpecifier(DS.getAttributes());
3529 continue;
3530
Anders Carlssoncd8db412009-05-06 04:46:28 +00003531 // friend
3532 case tok::kw_friend:
Faisal Vali7db85c52017-12-31 00:06:40 +00003533 if (DSContext == DeclSpecContext::DSC_class)
John McCall07e91c02009-08-06 02:15:43 +00003534 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3535 else {
3536 PrevSpec = ""; // not actually used by the diagnostic
3537 DiagID = diag::err_friend_invalid_in_context;
3538 isInvalid = true;
3539 }
Anders Carlssoncd8db412009-05-06 04:46:28 +00003540 break;
Mike Stump11289f42009-09-09 15:08:12 +00003541
Douglas Gregor26701a42011-09-09 02:06:17 +00003542 // Modules
3543 case tok::kw___module_private__:
3544 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3545 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003546
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00003547 // constexpr
3548 case tok::kw_constexpr:
3549 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3550 break;
3551
Chris Lattnere387d9e2009-01-21 19:48:37 +00003552 // type-specifier
3553 case tok::kw_short:
John McCall49bfce42009-08-03 20:12:06 +00003554 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003555 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003556 break;
3557 case tok::kw_long:
3558 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
John McCall49bfce42009-08-03 20:12:06 +00003559 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003560 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003561 else
John McCall49bfce42009-08-03 20:12:06 +00003562 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003563 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003564 break;
Francois Pichet84133e42011-04-28 01:59:37 +00003565 case tok::kw___int64:
3566 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003567 DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00003568 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003569 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00003570 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3571 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003572 break;
3573 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00003574 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3575 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003576 break;
3577 case tok::kw__Complex:
John McCall49bfce42009-08-03 20:12:06 +00003578 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3579 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003580 break;
3581 case tok::kw__Imaginary:
John McCall49bfce42009-08-03 20:12:06 +00003582 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3583 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003584 break;
3585 case tok::kw_void:
John McCall49bfce42009-08-03 20:12:06 +00003586 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003587 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003588 break;
3589 case tok::kw_char:
John McCall49bfce42009-08-03 20:12:06 +00003590 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003591 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003592 break;
3593 case tok::kw_int:
John McCall49bfce42009-08-03 20:12:06 +00003594 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003595 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003596 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00003597 case tok::kw___int128:
3598 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003599 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003600 break;
3601 case tok::kw_half:
3602 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003603 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003604 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003605 case tok::kw_float:
John McCall49bfce42009-08-03 20:12:06 +00003606 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003607 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003608 break;
3609 case tok::kw_double:
John McCall49bfce42009-08-03 20:12:06 +00003610 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003611 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003612 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00003613 case tok::kw__Float16:
3614 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3615 DiagID, Policy);
3616 break;
Leonard Chanf921d852018-06-04 16:07:52 +00003617 case tok::kw__Accum:
3618 if (!getLangOpts().FixedPoint) {
Leonard Chanab80f3c2018-06-14 14:53:51 +00003619 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
Leonard Chanf921d852018-06-04 16:07:52 +00003620 } else {
3621 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3622 DiagID, Policy);
3623 }
3624 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00003625 case tok::kw__Fract:
3626 if (!getLangOpts().FixedPoint) {
3627 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3628 } else {
3629 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3630 DiagID, Policy);
3631 }
3632 break;
3633 case tok::kw__Sat:
3634 if (!getLangOpts().FixedPoint) {
3635 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3636 } else {
3637 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3638 }
3639 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003640 case tok::kw___float128:
3641 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3642 DiagID, Policy);
3643 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003644 case tok::kw_wchar_t:
John McCall49bfce42009-08-03 20:12:06 +00003645 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003646 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003647 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00003648 case tok::kw_char8_t:
3649 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3650 DiagID, Policy);
3651 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003652 case tok::kw_char16_t:
John McCall49bfce42009-08-03 20:12:06 +00003653 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003654 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003655 break;
3656 case tok::kw_char32_t:
John McCall49bfce42009-08-03 20:12:06 +00003657 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003658 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003659 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003660 case tok::kw_bool:
3661 case tok::kw__Bool:
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003662 if (Tok.is(tok::kw_bool) &&
3663 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3664 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3665 PrevSpec = ""; // Not used by the diagnostic.
3666 DiagID = diag::err_bool_redeclaration;
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003667 // For better error recovery.
3668 Tok.setKind(tok::identifier);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003669 isInvalid = true;
3670 } else {
3671 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003672 DiagID, Policy);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003673 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003674 break;
3675 case tok::kw__Decimal32:
John McCall49bfce42009-08-03 20:12:06 +00003676 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003677 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003678 break;
3679 case tok::kw__Decimal64:
John McCall49bfce42009-08-03 20:12:06 +00003680 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003681 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003682 break;
3683 case tok::kw__Decimal128:
John McCall49bfce42009-08-03 20:12:06 +00003684 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003685 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003686 break;
John Thompson22334602010-02-05 00:12:22 +00003687 case tok::kw___vector:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003688 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003689 break;
3690 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003691 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003692 break;
Bill Seurercf2c96b2015-01-12 19:35:51 +00003693 case tok::kw___bool:
3694 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3695 break;
Xiuli Pan9c14e282016-01-09 12:53:17 +00003696 case tok::kw_pipe:
3697 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3698 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3699 // support the "pipe" word as identifier.
3700 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3701 goto DoneWithDeclSpec;
3702 }
3703 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3704 break;
Alexey Bader954ba212016-04-08 13:40:33 +00003705#define GENERIC_IMAGE_TYPE(ImgType, Id) \
3706 case tok::kw_##ImgType##_t: \
3707 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3708 DiagID, Policy); \
3709 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00003710#include "clang/Basic/OpenCLImageTypes.def"
John McCall39439732011-04-09 22:50:59 +00003711 case tok::kw___unknown_anytype:
Faisal Vali090da2d2018-01-01 18:23:28 +00003712 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003713 PrevSpec, DiagID, Policy);
John McCall39439732011-04-09 22:50:59 +00003714 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003715
3716 // class-specifier:
3717 case tok::kw_class:
3718 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00003719 case tok::kw___interface:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003720 case tok::kw_union: {
3721 tok::TokenKind Kind = Tok.getKind();
3722 ConsumeToken();
Michael Han9407e502012-11-26 22:54:45 +00003723
3724 // These are attributes following class specifiers.
3725 // To produce better diagnostic, we parse them when
3726 // parsing class specifier.
Bill Wendling44426052012-12-20 19:22:21 +00003727 ParsedAttributesWithRange Attributes(AttrFactory);
Richard Smithc5b05522012-03-12 07:56:15 +00003728 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
Bill Wendling44426052012-12-20 19:22:21 +00003729 EnteringContext, DSContext, Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003730
3731 // If there are attributes following class specifier,
3732 // take them over and handle them here.
Bill Wendling44426052012-12-20 19:22:21 +00003733 if (!Attributes.empty()) {
Michael Han9407e502012-11-26 22:54:45 +00003734 AttrsLastTime = true;
Bill Wendling44426052012-12-20 19:22:21 +00003735 attrs.takeAllFrom(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003736 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003737 continue;
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003738 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003739
3740 // enum-specifier:
3741 case tok::kw_enum:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003742 ConsumeToken();
Richard Smithc5b05522012-03-12 07:56:15 +00003743 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003744 continue;
Faisal Valia534f072018-04-26 00:42:40 +00003745
Chris Lattnere387d9e2009-01-21 19:48:37 +00003746 // cv-qualifier:
3747 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00003748 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003749 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003750 break;
3751 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00003752 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003753 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003754 break;
3755 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00003756 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003757 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003758 break;
3759
Douglas Gregor333489b2009-03-27 23:10:48 +00003760 // C++ typename-specifier:
3761 case tok::kw_typename:
John McCall1f476a12010-02-26 08:45:28 +00003762 if (TryAnnotateTypeOrScopeToken()) {
3763 DS.SetTypeSpecError();
3764 goto DoneWithDeclSpec;
3765 }
3766 if (!Tok.is(tok::kw_typename))
Douglas Gregor333489b2009-03-27 23:10:48 +00003767 continue;
3768 break;
3769
Chris Lattnere387d9e2009-01-21 19:48:37 +00003770 // GNU typeof support.
3771 case tok::kw_typeof:
3772 ParseTypeofSpecifier(DS);
3773 continue;
3774
David Blaikie15a430a2011-12-04 05:04:18 +00003775 case tok::annot_decltype:
Anders Carlsson74948d02009-06-24 17:47:40 +00003776 ParseDecltypeSpecifier(DS);
3777 continue;
3778
David Majnemer15b311c2016-06-14 03:20:28 +00003779 case tok::annot_pragma_pack:
3780 HandlePragmaPack();
3781 continue;
3782
3783 case tok::annot_pragma_ms_pragma:
3784 HandlePragmaMSPragma();
3785 continue;
3786
3787 case tok::annot_pragma_ms_vtordisp:
3788 HandlePragmaMSVtorDisp();
3789 continue;
3790
3791 case tok::annot_pragma_ms_pointers_to_members:
3792 HandlePragmaMSPointersToMembers();
3793 continue;
3794
Alexis Hunt4a257072011-05-19 05:37:45 +00003795 case tok::kw___underlying_type:
3796 ParseUnderlyingTypeSpecifier(DS);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003797 continue;
3798
3799 case tok::kw__Atomic:
Richard Smith8e1ac332013-03-28 01:55:44 +00003800 // C11 6.7.2.4/4:
3801 // If the _Atomic keyword is immediately followed by a left parenthesis,
3802 // it is interpreted as a type specifier (with a type name), not as a
3803 // type qualifier.
3804 if (NextToken().is(tok::l_paren)) {
3805 ParseAtomicSpecifier(DS);
3806 continue;
3807 }
3808 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3809 getLangOpts());
3810 break;
Alexis Hunt4a257072011-05-19 05:37:45 +00003811
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003812 // OpenCL access qualifiers:
3813 case tok::kw___read_only:
3814 case tok::kw___write_only:
3815 case tok::kw___read_write:
3816 // OpenCL C++ 1.0 s2.2: access qualifiers are reserved keywords.
3817 if (Actions.getLangOpts().OpenCLCPlusPlus) {
3818 DiagID = diag::err_openclcxx_reserved;
3819 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3820 isInvalid = true;
3821 }
3822 ParseOpenCLQualifiers(DS.getAttributes());
3823 break;
3824
3825 // OpenCL address space qualifiers:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003826 case tok::kw___generic:
3827 // generic address space is introduced only in OpenCL v2.0
3828 // see OpenCL C Spec v2.0 s6.5.5
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003829 if (Actions.getLangOpts().OpenCLVersion < 200 &&
3830 !Actions.getLangOpts().OpenCLCPlusPlus) {
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003831 DiagID = diag::err_opencl_unknown_type_specifier;
3832 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3833 isInvalid = true;
3834 break;
3835 };
Galina Kistanova77674252017-06-01 21:15:34 +00003836 LLVM_FALLTHROUGH;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003837 case tok::kw___private:
3838 case tok::kw___global:
3839 case tok::kw___local:
3840 case tok::kw___constant:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00003841 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003842 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003843
Steve Naroffcfdf6162008-06-05 00:02:44 +00003844 case tok::less:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003845 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
Chris Lattner0974b232008-07-26 00:20:22 +00003846 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3847 // but we support it.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003848 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
Chris Lattner0974b232008-07-26 00:20:22 +00003849 goto DoneWithDeclSpec;
Mike Stump11289f42009-09-09 15:08:12 +00003850
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003851 SourceLocation StartLoc = Tok.getLocation();
3852 SourceLocation EndLoc;
3853 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3854 if (Type.isUsable()) {
3855 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3856 PrevSpec, DiagID, Type.get(),
3857 Actions.getASTContext().getPrintingPolicy()))
3858 Diag(StartLoc, DiagID) << PrevSpec;
Fangrui Song6907ce22018-07-30 19:24:48 +00003859
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003860 DS.SetRangeEnd(EndLoc);
3861 } else {
3862 DS.SetTypeSpecError();
3863 }
Chad Rosierc1183952012-06-26 22:30:43 +00003864
Douglas Gregor06e41ae2010-10-21 23:17:00 +00003865 // Need to support trailing type qualifiers (e.g. "id<p> const").
3866 // If a type specifier follows, it will be diagnosed elsewhere.
3867 continue;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003868 }
John McCall49bfce42009-08-03 20:12:06 +00003869 // If the specifier wasn't legal, issue a diagnostic.
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003870 if (isInvalid) {
3871 assert(PrevSpec && "Method did not return previous specifier!");
John McCall49bfce42009-08-03 20:12:06 +00003872 assert(DiagID);
Chad Rosierc1183952012-06-26 22:30:43 +00003873
Nick Desaulniers150ca532018-10-03 23:09:29 +00003874 if (DiagID == diag::ext_duplicate_declspec ||
3875 DiagID == diag::ext_warn_duplicate_declspec)
Douglas Gregora05f5ab2010-08-23 14:34:43 +00003876 Diag(Tok, DiagID)
3877 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003878 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003879 Diag(Tok, DiagID) << getLangOpts().OpenCLCPlusPlus
3880 << getLangOpts().getOpenCLVersionTuple().getAsString()
3881 << PrevSpec << isStorageClass;
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003882 } else
Douglas Gregora05f5ab2010-08-23 14:34:43 +00003883 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003884 }
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003885
Chris Lattner2e232092008-03-13 06:29:04 +00003886 DS.SetRangeEnd(Tok.getLocation());
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003887 if (DiagID != diag::err_bool_redeclaration)
Volodymyr Sapsai9f7b5cc2018-04-10 18:29:47 +00003888 // After an error the next token can be an annotation token.
3889 ConsumeAnyToken();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003890
3891 AttrsLastTime = false;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003892 }
3893}
Douglas Gregoreb31f392008-12-01 23:54:00 +00003894
Chris Lattner70ae4912007-10-29 04:42:53 +00003895/// ParseStructDeclaration - Parse a struct declaration without the terminating
3896/// semicolon.
3897///
Chris Lattner90a26b02007-01-23 04:38:16 +00003898/// struct-declaration:
Aaron Ballman606093a2017-10-15 15:01:42 +00003899/// [C2x] attributes-specifier-seq[opt]
3900/// specifier-qualifier-list struct-declarator-list
Chris Lattner736ed5d2007-06-09 05:59:07 +00003901/// [GNU] __extension__ struct-declaration
Chris Lattner70ae4912007-10-29 04:42:53 +00003902/// [GNU] specifier-qualifier-list
Chris Lattner90a26b02007-01-23 04:38:16 +00003903/// struct-declarator-list:
3904/// struct-declarator
3905/// struct-declarator-list ',' struct-declarator
3906/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3907/// struct-declarator:
3908/// declarator
3909/// [GNU] declarator attributes[opt]
3910/// declarator[opt] ':' constant-expression
3911/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3912///
Benjamin Kramera39beb92014-09-03 11:06:10 +00003913void Parser::ParseStructDeclaration(
3914 ParsingDeclSpec &DS,
3915 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
Chad Rosierc1183952012-06-26 22:30:43 +00003916
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003917 if (Tok.is(tok::kw___extension__)) {
3918 // __extension__ silences extension warnings in the subexpression.
3919 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Steve Naroff97170802007-08-20 22:28:22 +00003920 ConsumeToken();
Benjamin Kramera39beb92014-09-03 11:06:10 +00003921 return ParseStructDeclaration(DS, FieldsCallback);
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003922 }
Mike Stump11289f42009-09-09 15:08:12 +00003923
Aaron Ballman606093a2017-10-15 15:01:42 +00003924 // Parse leading attributes.
3925 ParsedAttributesWithRange Attrs(AttrFactory);
3926 MaybeParseCXX11Attributes(Attrs);
3927 DS.takeAttributesFrom(Attrs);
3928
Steve Naroff97170802007-08-20 22:28:22 +00003929 // Parse the common specifier-qualifiers-list piece.
Steve Naroff97170802007-08-20 22:28:22 +00003930 ParseSpecifierQualifierList(DS);
Mike Stump11289f42009-09-09 15:08:12 +00003931
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003932 // If there are no declarators, this is a free-standing declaration
3933 // specifier. Let the actions module cope with it.
Chris Lattner76c72282007-10-09 17:33:22 +00003934 if (Tok.is(tok::semi)) {
Nico Weber7b837f52016-01-28 19:25:00 +00003935 RecordDecl *AnonRecord = nullptr;
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003936 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00003937 DS, AnonRecord);
3938 assert(!AnonRecord && "Did not expect anonymous struct or union here");
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003939 DS.complete(TheDecl);
Steve Naroff97170802007-08-20 22:28:22 +00003940 return;
3941 }
3942
3943 // Read struct-declarators until we find the semicolon.
John McCallcfefb6d2009-11-03 02:38:08 +00003944 bool FirstDeclarator = true;
Richard Smith8d06f422012-01-12 23:53:29 +00003945 SourceLocation CommaLoc;
Steve Naroff97170802007-08-20 22:28:22 +00003946 while (1) {
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003947 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
Richard Smith8d06f422012-01-12 23:53:29 +00003948 DeclaratorInfo.D.setCommaLoc(CommaLoc);
John McCallcfefb6d2009-11-03 02:38:08 +00003949
Bill Wendling44426052012-12-20 19:22:21 +00003950 // Attributes are only allowed here on successive declarators.
John McCall53fa7142010-12-24 02:08:15 +00003951 if (!FirstDeclarator)
3952 MaybeParseGNUAttributes(DeclaratorInfo.D);
Mike Stump11289f42009-09-09 15:08:12 +00003953
Steve Naroff97170802007-08-20 22:28:22 +00003954 /// struct-declarator: declarator
3955 /// struct-declarator: declarator[opt] ':' constant-expression
Chris Lattner17c3b1f2009-12-10 01:59:24 +00003956 if (Tok.isNot(tok::colon)) {
3957 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3958 ColonProtectionRAIIObject X(*this);
Chris Lattnera12405b2008-04-10 06:46:29 +00003959 ParseDeclarator(DeclaratorInfo.D);
Richard Smith3d1a94c2014-08-12 00:22:39 +00003960 } else
3961 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003962
Alp Toker8fbec672013-12-17 23:29:36 +00003963 if (TryConsumeToken(tok::colon)) {
John McCalldadc5752010-08-24 06:29:42 +00003964 ExprResult Res(ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00003965 if (Res.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00003966 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner32295d32008-04-10 06:15:14 +00003967 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003968 DeclaratorInfo.BitfieldSize = Res.get();
Steve Naroff97170802007-08-20 22:28:22 +00003969 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003970
Steve Naroff97170802007-08-20 22:28:22 +00003971 // If attributes exist after the declarator, parse them.
John McCall53fa7142010-12-24 02:08:15 +00003972 MaybeParseGNUAttributes(DeclaratorInfo.D);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003973
John McCallcfefb6d2009-11-03 02:38:08 +00003974 // We're done with this declarator; invoke the callback.
Benjamin Kramera39beb92014-09-03 11:06:10 +00003975 FieldsCallback(DeclaratorInfo);
John McCallcfefb6d2009-11-03 02:38:08 +00003976
Steve Naroff97170802007-08-20 22:28:22 +00003977 // If we don't have a comma, it is either the end of the list (a ';')
3978 // or an error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00003979 if (!TryConsumeToken(tok::comma, CommaLoc))
Chris Lattner70ae4912007-10-29 04:42:53 +00003980 return;
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003981
John McCallcfefb6d2009-11-03 02:38:08 +00003982 FirstDeclarator = false;
Steve Naroff97170802007-08-20 22:28:22 +00003983 }
Steve Naroff97170802007-08-20 22:28:22 +00003984}
3985
3986/// ParseStructUnionBody
3987/// struct-contents:
3988/// struct-declaration-list
3989/// [EXT] empty
3990/// [GNU] "struct-declaration-list" without terminatoring ';'
3991/// struct-declaration-list:
3992/// struct-declaration
3993/// struct-declaration-list struct-declaration
Chris Lattner535b8302008-06-21 19:39:06 +00003994/// [OBC] '@' 'defs' '(' class-name ')'
Steve Naroff97170802007-08-20 22:28:22 +00003995///
Chris Lattner1300fb92007-01-23 23:42:53 +00003996void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00003997 unsigned TagType, Decl *TagDecl) {
Jordan Rose1e879d82018-03-23 00:07:18 +00003998 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003999 "parsing struct/union body");
Andy Gibbs22e140b2013-04-03 09:31:19 +00004000 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
Mike Stump11289f42009-09-09 15:08:12 +00004001
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004002 BalancedDelimiterTracker T(*this, tok::l_brace);
4003 if (T.consumeOpen())
4004 return;
Mike Stump11289f42009-09-09 15:08:12 +00004005
Douglas Gregor658b9552009-01-09 22:42:13 +00004006 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004007 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004008
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004009 SmallVector<Decl *, 32> FieldDecls;
Chris Lattnera12405b2008-04-10 06:46:29 +00004010
Chris Lattner7b9ace62007-01-23 20:11:08 +00004011 // While we still have something to read, read the declarations in the struct.
Richard Smith752ada82015-11-17 23:32:01 +00004012 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4013 Tok.isNot(tok::eof)) {
Chris Lattner90a26b02007-01-23 04:38:16 +00004014 // Each iteration of this loop reads one struct-declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004015
Chris Lattner736ed5d2007-06-09 05:59:07 +00004016 // Check for extraneous top-level semicolon.
Chris Lattner76c72282007-10-09 17:33:22 +00004017 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004018 ConsumeExtraSemi(InsideStruct, TagType);
Chris Lattner36e46a22007-06-09 05:49:55 +00004019 continue;
4020 }
Chris Lattnera12405b2008-04-10 06:46:29 +00004021
Andy Gibbsc804e082013-04-03 09:46:04 +00004022 // Parse _Static_assert declaration.
4023 if (Tok.is(tok::kw__Static_assert)) {
4024 SourceLocation DeclEnd;
4025 ParseStaticAssertDeclaration(DeclEnd);
4026 continue;
4027 }
4028
Argyrios Kyrtzidis71c12fb2013-04-18 01:42:35 +00004029 if (Tok.is(tok::annot_pragma_pack)) {
4030 HandlePragmaPack();
4031 continue;
4032 }
4033
4034 if (Tok.is(tok::annot_pragma_align)) {
4035 HandlePragmaAlign();
4036 continue;
4037 }
4038
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004039 if (Tok.is(tok::annot_pragma_openmp)) {
Alexey Bataev587e1de2016-03-30 10:43:55 +00004040 // Result can be ignored, because it must be always empty.
4041 AccessSpecifier AS = AS_none;
4042 ParsedAttributesWithRange Attrs(AttrFactory);
4043 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004044 continue;
4045 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004046
John McCallcfefb6d2009-11-03 02:38:08 +00004047 if (!Tok.is(tok::at)) {
Benjamin Kramera39beb92014-09-03 11:06:10 +00004048 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4049 // Install the declarator into the current TagDecl.
4050 Decl *Field =
4051 Actions.ActOnField(getCurScope(), TagDecl,
4052 FD.D.getDeclSpec().getSourceRange().getBegin(),
4053 FD.D, FD.BitfieldSize);
4054 FieldDecls.push_back(Field);
4055 FD.complete(Field);
4056 };
John McCallcfefb6d2009-11-03 02:38:08 +00004057
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004058 // Parse all the comma separated declarators.
4059 ParsingDeclSpec DS(*this);
Benjamin Kramera39beb92014-09-03 11:06:10 +00004060 ParseStructDeclaration(DS, CFieldCallback);
Chris Lattner535b8302008-06-21 19:39:06 +00004061 } else { // Handle @defs
4062 ConsumeToken();
4063 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4064 Diag(Tok, diag::err_unexpected_at);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004065 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004066 continue;
4067 }
4068 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004069 ExpectAndConsume(tok::l_paren);
Chris Lattner535b8302008-06-21 19:39:06 +00004070 if (!Tok.is(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004071 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004072 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004073 continue;
4074 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004075 SmallVector<Decl *, 16> Fields;
Douglas Gregor0be31a22010-07-02 17:43:08 +00004076 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004077 Tok.getIdentifierInfo(), Fields);
Chris Lattner535b8302008-06-21 19:39:06 +00004078 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4079 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004080 ExpectAndConsume(tok::r_paren);
Mike Stump11289f42009-09-09 15:08:12 +00004081 }
Chris Lattner736ed5d2007-06-09 05:59:07 +00004082
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004083 if (TryConsumeToken(tok::semi))
4084 continue;
4085
4086 if (Tok.is(tok::r_brace)) {
Chris Lattner245c5332010-02-02 00:37:27 +00004087 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
Chris Lattner0c7e82d2007-06-09 05:54:40 +00004088 break;
Chris Lattner90a26b02007-01-23 04:38:16 +00004089 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004090
4091 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4092 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4093 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4094 // If we stopped at a ';', eat it.
4095 TryConsumeToken(tok::semi);
Chris Lattner90a26b02007-01-23 04:38:16 +00004096 }
Mike Stump11289f42009-09-09 15:08:12 +00004097
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004098 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +00004099
John McCall084e83d2011-03-24 11:26:52 +00004100 ParsedAttributes attrs(AttrFactory);
Chris Lattner90a26b02007-01-23 04:38:16 +00004101 // If attributes exist after struct contents, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004102 MaybeParseGNUAttributes(attrs);
Daniel Dunbar15619c72008-10-03 02:03:53 +00004103
Erich Keanec480f302018-07-12 21:09:05 +00004104 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4105 T.getOpenLocation(), T.getCloseLocation(), attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004106 StructScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004107 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
Chris Lattner90a26b02007-01-23 04:38:16 +00004108}
4109
Chris Lattner3b561a32006-08-13 00:12:11 +00004110/// ParseEnumSpecifier
Chris Lattner1890ac82006-08-13 01:16:23 +00004111/// enum-specifier: [C99 6.7.2.2]
Chris Lattner3b561a32006-08-13 00:12:11 +00004112/// 'enum' identifier[opt] '{' enumerator-list '}'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004113///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
Chris Lattnere37e2332006-08-15 04:50:22 +00004114/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4115/// '}' attributes[opt]
Aaron Ballman9ecff022012-03-01 04:09:28 +00004116/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4117/// '}'
Chris Lattner3b561a32006-08-13 00:12:11 +00004118/// 'enum' identifier
Chris Lattnere37e2332006-08-15 04:50:22 +00004119/// [GNU] 'enum' attributes[opt] identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004120///
Richard Smith7d137e32012-03-23 03:33:32 +00004121/// [C++11] enum-head '{' enumerator-list[opt] '}'
4122/// [C++11] enum-head '{' enumerator-list ',' '}'
Douglas Gregor0bf31402010-10-08 23:50:27 +00004123///
Richard Smith7d137e32012-03-23 03:33:32 +00004124/// enum-head: [C++11]
4125/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4126/// enum-key attribute-specifier-seq[opt] nested-name-specifier
4127/// identifier enum-base[opt]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004128///
Richard Smith7d137e32012-03-23 03:33:32 +00004129/// enum-key: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004130/// 'enum'
4131/// 'enum' 'class'
4132/// 'enum' 'struct'
4133///
Richard Smith7d137e32012-03-23 03:33:32 +00004134/// enum-base: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004135/// ':' type-specifier-seq
4136///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004137/// [C++] elaborated-type-specifier:
4138/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4139///
Chris Lattnerffaa0e62009-04-12 21:49:30 +00004140void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregordc70c3a2010-03-02 17:53:14 +00004141 const ParsedTemplateInfo &TemplateInfo,
Richard Smithc5b05522012-03-12 07:56:15 +00004142 AccessSpecifier AS, DeclSpecContext DSC) {
Chris Lattnerffbc2712007-01-25 06:05:38 +00004143 // Parse the tag portion of this.
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004144 if (Tok.is(tok::code_completion)) {
4145 // Code completion for an enum name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004146 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00004147 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004148 }
John McCallcb432fa2011-07-06 05:58:41 +00004149
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004150 // If attributes exist after tag, parse them.
4151 ParsedAttributesWithRange attrs(AttrFactory);
4152 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004153 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004154 MaybeParseMicrosoftDeclSpecs(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004155
Richard Smith0f8ee222012-01-10 01:33:14 +00004156 SourceLocation ScopedEnumKWLoc;
John McCallcb432fa2011-07-06 05:58:41 +00004157 bool IsScopedUsingClassTag = false;
4158
John McCallbeae29a2012-06-23 22:30:04 +00004159 // In C++11, recognize 'enum class' and 'enum struct'.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004160 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
Richard Trieud0d87b52013-04-23 02:47:36 +00004161 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4162 : diag::ext_scoped_enum);
John McCallcb432fa2011-07-06 05:58:41 +00004163 IsScopedUsingClassTag = Tok.is(tok::kw_class);
Richard Smith0f8ee222012-01-10 01:33:14 +00004164 ScopedEnumKWLoc = ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004165
Bill Wendling44426052012-12-20 19:22:21 +00004166 // Attributes are not allowed between these keywords. Diagnose,
John McCallbeae29a2012-06-23 22:30:04 +00004167 // but then just treat them like they appeared in the right place.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004168 ProhibitAttributes(attrs);
John McCallbeae29a2012-06-23 22:30:04 +00004169
4170 // They are allowed afterwards, though.
4171 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004172 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004173 MaybeParseMicrosoftDeclSpecs(attrs);
John McCallcb432fa2011-07-06 05:58:41 +00004174 }
Richard Smith7d137e32012-03-23 03:33:32 +00004175
John McCall6347b682012-05-07 06:16:58 +00004176 // C++11 [temp.explicit]p12:
4177 // The usual access controls do not apply to names used to specify
4178 // explicit instantiations.
4179 // We extend this to also cover explicit specializations. Note that
4180 // we don't suppress if this turns out to be an elaborated type
4181 // specifier.
4182 bool shouldDelayDiagsInTag =
4183 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4184 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4185 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Richard Smith7d137e32012-03-23 03:33:32 +00004186
Richard Smithbfdb1082012-03-12 08:56:40 +00004187 // Enum definitions should not be parsed in a trailing-return-type.
Faisal Vali7db85c52017-12-31 00:06:40 +00004188 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
Richard Smithbfdb1082012-03-12 08:56:40 +00004189
Abramo Bagnarad7548482010-05-19 21:37:53 +00004190 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004191 if (getLangOpts().CPlusPlus) {
John McCallcb432fa2011-07-06 05:58:41 +00004192 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4193 // if a fixed underlying type is allowed.
Erik Pilkington6f11db12018-09-28 20:24:58 +00004194 ColonProtectionRAIIObject X(*this, AllowDeclaration);
Chad Rosierc1183952012-06-26 22:30:43 +00004195
Nico Webercfaa4cd2015-02-15 07:26:13 +00004196 CXXScopeSpec Spec;
David Blaikieefdccaa2016-01-15 23:43:34 +00004197 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
Richard Smith1d4b2e12013-04-01 21:43:41 +00004198 /*EnteringContext=*/true))
John McCall1f476a12010-02-26 08:45:28 +00004199 return;
4200
Nico Webercfaa4cd2015-02-15 07:26:13 +00004201 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004202 Diag(Tok, diag::err_expected) << tok::identifier;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004203 if (Tok.isNot(tok::l_brace)) {
4204 // Has no name and is not a definition.
4205 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004206 SkipUntil(tok::comma, StopAtSemi);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004207 return;
4208 }
4209 }
Nico Webercfaa4cd2015-02-15 07:26:13 +00004210
4211 SS = Spec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004212 }
Mike Stump11289f42009-09-09 15:08:12 +00004213
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004214 // Must have either 'enum name' or 'enum {...}'.
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004215 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
Erik Pilkington6f11db12018-09-28 20:24:58 +00004216 !(AllowDeclaration && Tok.is(tok::colon))) {
Alp Tokerec543272013-12-24 09:48:30 +00004217 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
Mike Stump11289f42009-09-09 15:08:12 +00004218
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004219 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004220 SkipUntil(tok::comma, StopAtSemi);
Chris Lattner3b561a32006-08-13 00:12:11 +00004221 return;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004222 }
Mike Stump11289f42009-09-09 15:08:12 +00004223
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004224 // If an identifier is present, consume and remember it.
Craig Topper161e4db2014-05-21 06:02:52 +00004225 IdentifierInfo *Name = nullptr;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004226 SourceLocation NameLoc;
4227 if (Tok.is(tok::identifier)) {
4228 Name = Tok.getIdentifierInfo();
4229 NameLoc = ConsumeToken();
4230 }
Mike Stump11289f42009-09-09 15:08:12 +00004231
Richard Smith0f8ee222012-01-10 01:33:14 +00004232 if (!Name && ScopedEnumKWLoc.isValid()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00004233 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4234 // declaration of a scoped enumeration.
4235 Diag(Tok, diag::err_scoped_enum_missing_identifier);
Richard Smith0f8ee222012-01-10 01:33:14 +00004236 ScopedEnumKWLoc = SourceLocation();
Abramo Bagnara0e05e242010-12-03 18:54:17 +00004237 IsScopedUsingClassTag = false;
Douglas Gregor0bf31402010-10-08 23:50:27 +00004238 }
4239
John McCall6347b682012-05-07 06:16:58 +00004240 // Okay, end the suppression area. We'll decide whether to emit the
4241 // diagnostics in a second.
4242 if (shouldDelayDiagsInTag)
4243 diagsFromTag.done();
Richard Smith7d137e32012-03-23 03:33:32 +00004244
Douglas Gregor0bf31402010-10-08 23:50:27 +00004245 TypeResult BaseType;
4246
Douglas Gregord1f69f62010-12-01 17:42:47 +00004247 // Parse the fixed underlying type.
Richard Smith200f47c2012-07-02 19:14:01 +00004248 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
Erik Pilkington6f11db12018-09-28 20:24:58 +00004249 if (AllowDeclaration && Tok.is(tok::colon)) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004250 bool PossibleBitfield = false;
Richard Smith200f47c2012-07-02 19:14:01 +00004251 if (CanBeBitfield) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004252 // If we're in class scope, this can either be an enum declaration with
4253 // an underlying type, or a declaration of a bitfield member. We try to
4254 // use a simple disambiguation scheme first to catch the common cases
Chad Rosierc1183952012-06-26 22:30:43 +00004255 // (integer literal, sizeof); if it's still ambiguous, we then consider
4256 // anything that's a simple-type-specifier followed by '(' as an
4257 // expression. This suffices because function types are not valid
Douglas Gregord1f69f62010-12-01 17:42:47 +00004258 // underlying types anyway.
Faisal Valid143a0c2017-04-01 21:30:49 +00004259 EnterExpressionEvaluationContext Unevaluated(
4260 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregord1f69f62010-12-01 17:42:47 +00004261 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
Chad Rosierc1183952012-06-26 22:30:43 +00004262 // If the next token starts an expression, we know we're parsing a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004263 // bit-field. This is the common case.
Richard Smithee390432014-05-16 01:56:53 +00004264 if (TPR == TPResult::True)
Douglas Gregord1f69f62010-12-01 17:42:47 +00004265 PossibleBitfield = true;
4266 // If the next token starts a type-specifier-seq, it may be either a
4267 // a fixed underlying type or the start of a function-style cast in C++;
Chad Rosierc1183952012-06-26 22:30:43 +00004268 // lookahead one more token to see if it's obvious that we have a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004269 // fixed underlying type.
Richard Smithee390432014-05-16 01:56:53 +00004270 else if (TPR == TPResult::False &&
Douglas Gregord1f69f62010-12-01 17:42:47 +00004271 GetLookAheadToken(2).getKind() == tok::semi) {
4272 // Consume the ':'.
4273 ConsumeToken();
4274 } else {
4275 // We have the start of a type-specifier-seq, so we have to perform
4276 // tentative parsing to determine whether we have an expression or a
4277 // type.
4278 TentativeParsingAction TPA(*this);
4279
4280 // Consume the ':'.
4281 ConsumeToken();
Richard Smith1e3b0f02012-02-23 01:36:12 +00004282
4283 // If we see a type specifier followed by an open-brace, we have an
4284 // ambiguity between an underlying type and a C++11 braced
4285 // function-style cast. Resolve this by always treating it as an
4286 // underlying type.
4287 // FIXME: The standard is not entirely clear on how to disambiguate in
4288 // this case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004289 if ((getLangOpts().CPlusPlus &&
Richard Smithee390432014-05-16 01:56:53 +00004290 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00004291 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004292 // We'll parse this as a bitfield later.
4293 PossibleBitfield = true;
4294 TPA.Revert();
4295 } else {
4296 // We have a type-specifier-seq.
4297 TPA.Commit();
4298 }
4299 }
4300 } else {
4301 // Consume the ':'.
4302 ConsumeToken();
4303 }
4304
4305 if (!PossibleBitfield) {
4306 SourceRange Range;
4307 BaseType = ParseTypeName(&Range);
Chad Rosierc1183952012-06-26 22:30:43 +00004308
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004309 if (!getLangOpts().ObjC) {
Erik Pilkington6f11db12018-09-28 20:24:58 +00004310 if (getLangOpts().CPlusPlus11)
4311 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4312 else if (getLangOpts().CPlusPlus)
4313 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4314 else if (getLangOpts().MicrosoftExt)
4315 Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004316 else
Erik Pilkington6f11db12018-09-28 20:24:58 +00004317 Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004318 }
Douglas Gregord1f69f62010-12-01 17:42:47 +00004319 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004320 }
4321
Richard Smith0f8ee222012-01-10 01:33:14 +00004322 // There are four options here. If we have 'friend enum foo;' then this is a
4323 // friend declaration, and cannot have an accompanying definition. If we have
4324 // 'enum foo;', then this is a forward declaration. If we have
4325 // 'enum foo {...' then this is a definition. Otherwise we have something
4326 // like 'enum foo xyz', a reference.
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004327 //
4328 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4329 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4330 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4331 //
John McCallfaf5fb42010-08-26 23:41:50 +00004332 Sema::TagUseKind TUK;
John McCall6347b682012-05-07 06:16:58 +00004333 if (!AllowDeclaration) {
Richard Smithbfdb1082012-03-12 08:56:40 +00004334 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004335 } else if (Tok.is(tok::l_brace)) {
4336 if (DS.isFriendSpecified()) {
4337 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4338 << SourceRange(DS.getFriendSpecLoc());
4339 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004340 SkipUntil(tok::r_brace, StopAtSemi);
John McCall6347b682012-05-07 06:16:58 +00004341 TUK = Sema::TUK_Friend;
4342 } else {
4343 TUK = Sema::TUK_Definition;
4344 }
Richard Smith649c7b062014-01-08 00:56:48 +00004345 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00004346 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00004347 (Tok.isAtStartOfLine() &&
4348 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
Richard Smith369b9f92012-06-25 21:37:02 +00004349 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4350 if (Tok.isNot(tok::semi)) {
4351 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00004352 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004353 PP.EnterToken(Tok);
4354 Tok.setKind(tok::semi);
4355 }
John McCall6347b682012-05-07 06:16:58 +00004356 } else {
John McCallfaf5fb42010-08-26 23:41:50 +00004357 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004358 }
4359
4360 // If this is an elaborated type specifier, and we delayed
4361 // diagnostics before, just merge them into the current pool.
4362 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4363 diagsFromTag.redelay();
4364 }
Richard Smith7d137e32012-03-23 03:33:32 +00004365
4366 MultiTemplateParamsArg TParams;
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004367 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
John McCallfaf5fb42010-08-26 23:41:50 +00004368 TUK != Sema::TUK_Reference) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004369 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
Richard Smith7d137e32012-03-23 03:33:32 +00004370 // Skip the rest of this declarator, up until the comma or semicolon.
4371 Diag(Tok, diag::err_enum_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004372 SkipUntil(tok::comma, StopAtSemi);
Richard Smith7d137e32012-03-23 03:33:32 +00004373 return;
4374 }
4375
4376 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4377 // Enumerations can't be explicitly instantiated.
4378 DS.SetTypeSpecError();
4379 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4380 return;
4381 }
4382
4383 assert(TemplateInfo.TemplateParams && "no template parameters");
4384 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4385 TemplateInfo.TemplateParams->size());
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004386 }
Chad Rosierc1183952012-06-26 22:30:43 +00004387
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004388 if (TUK == Sema::TUK_Reference)
4389 ProhibitAttributes(attrs);
Richard Smith7d137e32012-03-23 03:33:32 +00004390
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004391 if (!Name && TUK != Sema::TUK_Definition) {
4392 Diag(Tok, diag::err_enumerator_unnamed_no_def);
Richard Smith7d137e32012-03-23 03:33:32 +00004393
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004394 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004395 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004396 return;
4397 }
Richard Smith7d137e32012-03-23 03:33:32 +00004398
Nico Weber32a0fc72016-09-03 03:01:32 +00004399 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00004400
Richard Smithd9ba2242015-05-07 03:54:19 +00004401 Sema::SkipBodyInfo SkipBody;
4402 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4403 NextToken().is(tok::identifier))
4404 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4405 NextToken().getIdentifierInfo(),
4406 NextToken().getLocation());
4407
Douglas Gregord6ab8742009-05-28 23:31:59 +00004408 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004409 bool IsDependent = false;
Craig Topper161e4db2014-05-21 06:02:52 +00004410 const char *PrevSpec = nullptr;
Douglas Gregorba41d012010-04-24 16:38:41 +00004411 unsigned DiagID;
Faisal Vali7db85c52017-12-31 00:06:40 +00004412 Decl *TagDecl = Actions.ActOnTag(
4413 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
Erich Keanec480f302018-07-12 21:09:05 +00004414 attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4415 ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
Faisal Vali7db85c52017-12-31 00:06:40 +00004416 DSC == DeclSpecContext::DSC_type_specifier,
4417 DSC == DeclSpecContext::DSC_template_param ||
4418 DSC == DeclSpecContext::DSC_template_type_arg,
4419 &SkipBody);
Richard Smithd9ba2242015-05-07 03:54:19 +00004420
4421 if (SkipBody.ShouldSkip) {
4422 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4423
4424 BalancedDelimiterTracker T(*this, tok::l_brace);
4425 T.consumeOpen();
4426 T.skipToEnd();
4427
4428 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4429 NameLoc.isValid() ? NameLoc : StartLoc,
4430 PrevSpec, DiagID, TagDecl, Owned,
4431 Actions.getASTContext().getPrintingPolicy()))
4432 Diag(StartLoc, DiagID) << PrevSpec;
4433 return;
4434 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004435
Douglas Gregorba41d012010-04-24 16:38:41 +00004436 if (IsDependent) {
Chad Rosierc1183952012-06-26 22:30:43 +00004437 // This enum has a dependent nested-name-specifier. Handle it as a
Douglas Gregorba41d012010-04-24 16:38:41 +00004438 // dependent tag.
4439 if (!Name) {
4440 DS.SetTypeSpecError();
4441 Diag(Tok, diag::err_expected_type_name_after_typename);
4442 return;
4443 }
Chad Rosierc1183952012-06-26 22:30:43 +00004444
Nico Weber83ea0122014-05-03 21:57:40 +00004445 TypeResult Type = Actions.ActOnDependentTag(
4446 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
Douglas Gregorba41d012010-04-24 16:38:41 +00004447 if (Type.isInvalid()) {
4448 DS.SetTypeSpecError();
4449 return;
4450 }
Chad Rosierc1183952012-06-26 22:30:43 +00004451
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004452 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4453 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004454 PrevSpec, DiagID, Type.get(),
4455 Actions.getASTContext().getPrintingPolicy()))
Douglas Gregorba41d012010-04-24 16:38:41 +00004456 Diag(StartLoc, DiagID) << PrevSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00004457
Douglas Gregorba41d012010-04-24 16:38:41 +00004458 return;
4459 }
Mike Stump11289f42009-09-09 15:08:12 +00004460
John McCall48871652010-08-21 09:40:31 +00004461 if (!TagDecl) {
Chad Rosierc1183952012-06-26 22:30:43 +00004462 // The action failed to produce an enumeration tag. If this is a
Douglas Gregorba41d012010-04-24 16:38:41 +00004463 // definition, consume the entire definition.
Richard Smithbfdb1082012-03-12 08:56:40 +00004464 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
Douglas Gregorba41d012010-04-24 16:38:41 +00004465 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004466 SkipUntil(tok::r_brace, StopAtSemi);
Douglas Gregorba41d012010-04-24 16:38:41 +00004467 }
Chad Rosierc1183952012-06-26 22:30:43 +00004468
Douglas Gregorba41d012010-04-24 16:38:41 +00004469 DS.SetTypeSpecError();
4470 return;
4471 }
Richard Smith0f8ee222012-01-10 01:33:14 +00004472
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004473 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4474 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4475 ParseEnumBody(StartLoc, D);
4476 if (SkipBody.CheckSameAsPrevious &&
4477 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4478 DS.SetTypeSpecError();
4479 return;
4480 }
4481 }
Mike Stump11289f42009-09-09 15:08:12 +00004482
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004483 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4484 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004485 PrevSpec, DiagID, TagDecl, Owned,
4486 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00004487 Diag(StartLoc, DiagID) << PrevSpec;
Chris Lattner3b561a32006-08-13 00:12:11 +00004488}
4489
Chris Lattnerc1915e22007-01-25 07:29:02 +00004490/// ParseEnumBody - Parse a {} enclosed enumerator-list.
4491/// enumerator-list:
4492/// enumerator
4493/// enumerator-list ',' enumerator
4494/// enumerator:
Aaron Ballman730476b2014-11-08 15:33:35 +00004495/// enumeration-constant attributes[opt]
4496/// enumeration-constant attributes[opt] '=' constant-expression
Chris Lattnerc1915e22007-01-25 07:29:02 +00004497/// enumeration-constant:
4498/// identifier
4499///
John McCall48871652010-08-21 09:40:31 +00004500void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004501 // Enter the scope of the enum body and start the definition.
Hans Wennborgfe781452014-06-17 00:00:18 +00004502 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004503 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
Douglas Gregor07665a62009-01-05 19:45:36 +00004504
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004505 BalancedDelimiterTracker T(*this, tok::l_brace);
4506 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00004507
Chris Lattner37256fb2007-08-27 17:24:30 +00004508 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
David Blaikiebbafb8a2012-03-11 07:00:24 +00004509 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
Richard Smithf8812672016-12-02 22:38:31 +00004510 Diag(Tok, diag::err_empty_enum);
Mike Stump11289f42009-09-09 15:08:12 +00004511
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004512 SmallVector<Decl *, 32> EnumConstantDecls;
Jordan Rose60ac3162015-04-30 17:20:30 +00004513 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
Chris Lattnerc1915e22007-01-25 07:29:02 +00004514
Craig Topper161e4db2014-05-21 06:02:52 +00004515 Decl *LastEnumConstDecl = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004516
Chris Lattnerc1915e22007-01-25 07:29:02 +00004517 // Parse the enumerator-list.
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004518 while (Tok.isNot(tok::r_brace)) {
4519 // Parse enumerator. If failed, try skipping till the start of the next
4520 // enumerator definition.
4521 if (Tok.isNot(tok::identifier)) {
4522 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4523 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4524 TryConsumeToken(tok::comma))
4525 continue;
4526 break;
4527 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004528 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4529 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00004530
John McCall811a0f52010-10-22 23:36:17 +00004531 // If attributes exist after the enumerator, parse them.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004532 ParsedAttributesWithRange attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004533 MaybeParseGNUAttributes(attrs);
Aaron Ballman730476b2014-11-08 15:33:35 +00004534 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
Aaron Ballman606093a2017-10-15 15:01:42 +00004535 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4536 if (getLangOpts().CPlusPlus)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004537 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Aaron Ballman606093a2017-10-15 15:01:42 +00004538 ? diag::warn_cxx14_compat_ns_enum_attribute
4539 : diag::ext_ns_enum_attribute)
4540 << 1 /*enumerator*/;
Aaron Ballman730476b2014-11-08 15:33:35 +00004541 ParseCXX11Attributes(attrs);
4542 }
John McCall811a0f52010-10-22 23:36:17 +00004543
Chris Lattnerc1915e22007-01-25 07:29:02 +00004544 SourceLocation EqualLoc;
John McCalldadc5752010-08-24 06:29:42 +00004545 ExprResult AssignedVal;
Jordan Rose60ac3162015-04-30 17:20:30 +00004546 EnumAvailabilityDiags.emplace_back(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00004547
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004548 if (TryConsumeToken(tok::equal, EqualLoc)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004549 AssignedVal = ParseConstantExpression();
4550 if (AssignedVal.isInvalid())
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004551 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
Chris Lattnerc1915e22007-01-25 07:29:02 +00004552 }
Mike Stump11289f42009-09-09 15:08:12 +00004553
Chris Lattnerc1915e22007-01-25 07:29:02 +00004554 // Install the enumerator constant into EnumDecl.
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004555 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
Erich Keanec480f302018-07-12 21:09:05 +00004556 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4557 EqualLoc, AssignedVal.get());
Jordan Rose60ac3162015-04-30 17:20:30 +00004558 EnumAvailabilityDiags.back().done();
Chad Rosierc1183952012-06-26 22:30:43 +00004559
Chris Lattner4ef40012007-06-11 01:28:17 +00004560 EnumConstantDecls.push_back(EnumConstDecl);
4561 LastEnumConstDecl = EnumConstDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004562
Douglas Gregorce66d022010-09-07 14:51:08 +00004563 if (Tok.is(tok::identifier)) {
4564 // We're missing a comma between enumerators.
Richard Smithbdb84f32016-07-22 23:36:59 +00004565 SourceLocation Loc = getEndOfPreviousToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004566 Diag(Loc, diag::err_enumerator_list_missing_comma)
Douglas Gregorce66d022010-09-07 14:51:08 +00004567 << FixItHint::CreateInsertion(Loc, ", ");
4568 continue;
4569 }
Chad Rosierc1183952012-06-26 22:30:43 +00004570
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004571 // Emumerator definition must be finished, only comma or r_brace are
4572 // allowed here.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004573 SourceLocation CommaLoc;
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004574 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4575 if (EqualLoc.isValid())
4576 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4577 << tok::comma;
4578 else
4579 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4580 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4581 if (TryConsumeToken(tok::comma, CommaLoc))
4582 continue;
4583 } else {
4584 break;
4585 }
4586 }
Mike Stump11289f42009-09-09 15:08:12 +00004587
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004588 // If comma is followed by r_brace, emit appropriate warning.
4589 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004590 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
Richard Smith87f5dc52012-07-23 05:45:25 +00004591 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4592 diag::ext_enumerator_list_comma_cxx :
4593 diag::ext_enumerator_list_comma_c)
Richard Smith5d164bc2011-10-15 05:09:34 +00004594 << FixItHint::CreateRemoval(CommaLoc);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004595 else if (getLangOpts().CPlusPlus11)
Richard Smith5d164bc2011-10-15 05:09:34 +00004596 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4597 << FixItHint::CreateRemoval(CommaLoc);
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004598 break;
Richard Smith5d164bc2011-10-15 05:09:34 +00004599 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004600 }
Mike Stump11289f42009-09-09 15:08:12 +00004601
Chris Lattnerc1915e22007-01-25 07:29:02 +00004602 // Eat the }.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004603 T.consumeClose();
Chris Lattnerc1915e22007-01-25 07:29:02 +00004604
Chris Lattnerc1915e22007-01-25 07:29:02 +00004605 // If attributes exist after the identifier list, parse them.
John McCall084e83d2011-03-24 11:26:52 +00004606 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004607 MaybeParseGNUAttributes(attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004608
Erich Keanec480f302018-07-12 21:09:05 +00004609 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4610 getCurScope(), attrs);
Mike Stump11289f42009-09-09 15:08:12 +00004611
Jordan Rose60ac3162015-04-30 17:20:30 +00004612 // Now handle enum constant availability diagnostics.
4613 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4614 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4615 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4616 EnumAvailabilityDiags[i].redelay();
4617 PD.complete(EnumConstantDecls[i]);
4618 }
4619
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004620 EnumScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004621 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
Richard Smith369b9f92012-06-25 21:37:02 +00004622
4623 // The next token must be valid after an enum definition. If not, a ';'
4624 // was probably forgotten.
Richard Smith200f47c2012-07-02 19:14:01 +00004625 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4626 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
Alp Toker383d2c42014-01-01 03:08:43 +00004627 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004628 // Push this token back into the preprocessor and change our current token
4629 // to ';' so that the rest of the code recovers as though there were an
4630 // ';' after the definition.
4631 PP.EnterToken(Tok);
4632 Tok.setKind(tok::semi);
4633 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004634}
Chris Lattner3b561a32006-08-13 00:12:11 +00004635
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004636/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4637/// is definitely a type-specifier. Return false if it isn't part of a type
4638/// specifier or if we're not sure.
4639bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4640 switch (Tok.getKind()) {
4641 default: return false;
4642 // type-specifiers
4643 case tok::kw_short:
4644 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004645 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004646 case tok::kw___int128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004647 case tok::kw_signed:
4648 case tok::kw_unsigned:
4649 case tok::kw__Complex:
4650 case tok::kw__Imaginary:
4651 case tok::kw_void:
4652 case tok::kw_char:
4653 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004654 case tok::kw_char8_t:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004655 case tok::kw_char16_t:
4656 case tok::kw_char32_t:
4657 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004658 case tok::kw_half:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004659 case tok::kw_float:
4660 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004661 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004662 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004663 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004664 case tok::kw___float128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004665 case tok::kw_bool:
4666 case tok::kw__Bool:
4667 case tok::kw__Decimal32:
4668 case tok::kw__Decimal64:
4669 case tok::kw__Decimal128:
4670 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004671#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004672#include "clang/Basic/OpenCLImageTypes.def"
Chad Rosierc1183952012-06-26 22:30:43 +00004673
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004674 // struct-or-union-specifier (C99) or class-specifier (C++)
4675 case tok::kw_class:
4676 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004677 case tok::kw___interface:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004678 case tok::kw_union:
4679 // enum-specifier
4680 case tok::kw_enum:
Chad Rosierc1183952012-06-26 22:30:43 +00004681
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004682 // typedef-name
4683 case tok::annot_typename:
4684 return true;
4685 }
4686}
4687
Steve Naroff69e8f9e2008-02-11 23:15:56 +00004688/// isTypeSpecifierQualifier - Return true if the current token could be the
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004689/// start of a specifier-qualifier-list.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004690bool Parser::isTypeSpecifierQualifier() {
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004691 switch (Tok.getKind()) {
4692 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004693
Chris Lattner020bab92009-01-04 23:41:41 +00004694 case tok::identifier: // foo::bar
John Thompson22334602010-02-05 00:12:22 +00004695 if (TryAltiVecVectorToken())
4696 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004697 LLVM_FALLTHROUGH;
Douglas Gregor333489b2009-03-27 23:10:48 +00004698 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004699 // Annotate typenames and C++ scope specifiers. If we get one, just
4700 // recurse to handle whatever we get.
4701 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004702 return true;
4703 if (Tok.is(tok::identifier))
4704 return false;
4705 return isTypeSpecifierQualifier();
Douglas Gregor333489b2009-03-27 23:10:48 +00004706
Chris Lattner020bab92009-01-04 23:41:41 +00004707 case tok::coloncolon: // ::foo::bar
4708 if (NextToken().is(tok::kw_new) || // ::new
4709 NextToken().is(tok::kw_delete)) // ::delete
4710 return false;
4711
Chris Lattner020bab92009-01-04 23:41:41 +00004712 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004713 return true;
4714 return isTypeSpecifierQualifier();
Mike Stump11289f42009-09-09 15:08:12 +00004715
Chris Lattnere37e2332006-08-15 04:50:22 +00004716 // GNU attributes support.
4717 case tok::kw___attribute:
Steve Naroffad373bd2007-07-31 12:34:36 +00004718 // GNU typeof support.
4719 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004720
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004721 // type-specifiers
4722 case tok::kw_short:
4723 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004724 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004725 case tok::kw___int128:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004726 case tok::kw_signed:
4727 case tok::kw_unsigned:
4728 case tok::kw__Complex:
4729 case tok::kw__Imaginary:
4730 case tok::kw_void:
4731 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004732 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004733 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004734 case tok::kw_char16_t:
4735 case tok::kw_char32_t:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004736 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004737 case tok::kw_half:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004738 case tok::kw_float:
4739 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004740 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004741 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004742 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004743 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004744 case tok::kw_bool:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004745 case tok::kw__Bool:
4746 case tok::kw__Decimal32:
4747 case tok::kw__Decimal64:
4748 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004749 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004750#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004751#include "clang/Basic/OpenCLImageTypes.def"
Mike Stump11289f42009-09-09 15:08:12 +00004752
Chris Lattner861a2262008-04-13 18:59:07 +00004753 // struct-or-union-specifier (C99) or class-specifier (C++)
4754 case tok::kw_class:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004755 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004756 case tok::kw___interface:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004757 case tok::kw_union:
4758 // enum-specifier
4759 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004760
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004761 // type-qualifier
4762 case tok::kw_const:
4763 case tok::kw_volatile:
4764 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004765 case tok::kw__Sat:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004766
John McCallea0a39e2012-11-14 00:49:39 +00004767 // Debugger support.
4768 case tok::kw___unknown_anytype:
4769
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004770 // typedef-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00004771 case tok::annot_typename:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004772 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004773
Chris Lattner409bf7d2008-10-20 00:25:30 +00004774 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4775 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004776 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00004777
Steve Naroff44ac7772008-12-25 14:16:32 +00004778 case tok::kw___cdecl:
4779 case tok::kw___stdcall:
4780 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004781 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004782 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004783 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004784 case tok::kw___w64:
4785 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004786 case tok::kw___ptr32:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004787 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004788 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004789
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004790 case tok::kw__Nonnull:
4791 case tok::kw__Nullable:
4792 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004793
Douglas Gregorab209d82015-07-07 03:58:42 +00004794 case tok::kw___kindof:
4795
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004796 case tok::kw___private:
4797 case tok::kw___local:
4798 case tok::kw___global:
4799 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004800 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004801 case tok::kw___read_only:
4802 case tok::kw___read_write:
4803 case tok::kw___write_only:
4804
Eli Friedman53339e02009-06-08 23:27:34 +00004805 return true;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004806
Richard Smith8e1ac332013-03-28 01:55:44 +00004807 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004808 case tok::kw__Atomic:
4809 return true;
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004810 }
4811}
4812
Chris Lattneracd58a32006-08-06 17:24:14 +00004813/// isDeclarationSpecifier() - Return true if the current token is part of a
4814/// declaration specifier.
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004815///
4816/// \param DisambiguatingWithExpression True to indicate that the purpose of
4817/// this check is to disambiguate between an expression and a declaration.
4818bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
Chris Lattneracd58a32006-08-06 17:24:14 +00004819 switch (Tok.getKind()) {
4820 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004821
Xiuli Pan9c14e282016-01-09 12:53:17 +00004822 case tok::kw_pipe:
4823 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4824
Chris Lattner020bab92009-01-04 23:41:41 +00004825 case tok::identifier: // foo::bar
Steve Naroff9527bbf2009-03-09 21:12:44 +00004826 // Unfortunate hack to support "Class.factoryMethod" notation.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004827 if (getLangOpts().ObjC && NextToken().is(tok::period))
Steve Naroff9527bbf2009-03-09 21:12:44 +00004828 return false;
John Thompson22334602010-02-05 00:12:22 +00004829 if (TryAltiVecVectorToken())
4830 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004831 LLVM_FALLTHROUGH;
David Blaikie15a430a2011-12-04 05:04:18 +00004832 case tok::kw_decltype: // decltype(T())::type
Douglas Gregor333489b2009-03-27 23:10:48 +00004833 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004834 // Annotate typenames and C++ scope specifiers. If we get one, just
4835 // recurse to handle whatever we get.
4836 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004837 return true;
4838 if (Tok.is(tok::identifier))
4839 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004840
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004841 // If we're in Objective-C and we have an Objective-C class type followed
Chad Rosierc1183952012-06-26 22:30:43 +00004842 // by an identifier and then either ':' or ']', in a place where an
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004843 // expression is permitted, then this is probably a class message send
4844 // missing the initial '['. In this case, we won't consider this to be
4845 // the start of a declaration.
Chad Rosierc1183952012-06-26 22:30:43 +00004846 if (DisambiguatingWithExpression &&
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004847 isStartOfObjCClassMessageMissingOpenBracket())
4848 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004849
John McCall1f476a12010-02-26 08:45:28 +00004850 return isDeclarationSpecifier();
4851
Chris Lattner020bab92009-01-04 23:41:41 +00004852 case tok::coloncolon: // ::foo::bar
4853 if (NextToken().is(tok::kw_new) || // ::new
4854 NextToken().is(tok::kw_delete)) // ::delete
4855 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004856
Chris Lattner020bab92009-01-04 23:41:41 +00004857 // Annotate typenames and C++ scope specifiers. If we get one, just
4858 // recurse to handle whatever we get.
4859 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004860 return true;
4861 return isDeclarationSpecifier();
Mike Stump11289f42009-09-09 15:08:12 +00004862
Chris Lattneracd58a32006-08-06 17:24:14 +00004863 // storage-class-specifier
4864 case tok::kw_typedef:
4865 case tok::kw_extern:
Steve Naroff2050b0d2007-12-18 00:16:02 +00004866 case tok::kw___private_extern__:
Chris Lattneracd58a32006-08-06 17:24:14 +00004867 case tok::kw_static:
4868 case tok::kw_auto:
Richard Smithe301ba22015-11-11 02:02:15 +00004869 case tok::kw___auto_type:
Chris Lattneracd58a32006-08-06 17:24:14 +00004870 case tok::kw_register:
4871 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00004872 case tok::kw_thread_local:
4873 case tok::kw__Thread_local:
Mike Stump11289f42009-09-09 15:08:12 +00004874
Douglas Gregor26701a42011-09-09 02:06:17 +00004875 // Modules
4876 case tok::kw___module_private__:
Chad Rosierc1183952012-06-26 22:30:43 +00004877
John McCallea0a39e2012-11-14 00:49:39 +00004878 // Debugger support
4879 case tok::kw___unknown_anytype:
4880
Chris Lattneracd58a32006-08-06 17:24:14 +00004881 // type-specifiers
4882 case tok::kw_short:
4883 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004884 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004885 case tok::kw___int128:
Chris Lattneracd58a32006-08-06 17:24:14 +00004886 case tok::kw_signed:
4887 case tok::kw_unsigned:
4888 case tok::kw__Complex:
4889 case tok::kw__Imaginary:
4890 case tok::kw_void:
4891 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004892 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004893 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004894 case tok::kw_char16_t:
4895 case tok::kw_char32_t:
4896
Chris Lattneracd58a32006-08-06 17:24:14 +00004897 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004898 case tok::kw_half:
Chris Lattneracd58a32006-08-06 17:24:14 +00004899 case tok::kw_float:
4900 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004901 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004902 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004903 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004904 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004905 case tok::kw_bool:
Chris Lattneracd58a32006-08-06 17:24:14 +00004906 case tok::kw__Bool:
4907 case tok::kw__Decimal32:
4908 case tok::kw__Decimal64:
4909 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004910 case tok::kw___vector:
Mike Stump11289f42009-09-09 15:08:12 +00004911
Chris Lattner861a2262008-04-13 18:59:07 +00004912 // struct-or-union-specifier (C99) or class-specifier (C++)
4913 case tok::kw_class:
Chris Lattneracd58a32006-08-06 17:24:14 +00004914 case tok::kw_struct:
4915 case tok::kw_union:
Joao Matosdc86f942012-08-31 18:45:21 +00004916 case tok::kw___interface:
Chris Lattneracd58a32006-08-06 17:24:14 +00004917 // enum-specifier
4918 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004919
Chris Lattneracd58a32006-08-06 17:24:14 +00004920 // type-qualifier
4921 case tok::kw_const:
4922 case tok::kw_volatile:
4923 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004924 case tok::kw__Sat:
Steve Naroffad373bd2007-07-31 12:34:36 +00004925
Chris Lattneracd58a32006-08-06 17:24:14 +00004926 // function-specifier
4927 case tok::kw_inline:
Douglas Gregor61956c42008-10-31 09:07:45 +00004928 case tok::kw_virtual:
4929 case tok::kw_explicit:
Richard Smith0015f092013-01-17 22:16:11 +00004930 case tok::kw__Noreturn:
Chris Lattner7b20dc72007-08-09 16:40:21 +00004931
Richard Smith1dba27c2013-01-29 09:02:09 +00004932 // alignment-specifier
4933 case tok::kw__Alignas:
4934
Richard Smithd16fe122012-10-25 00:00:53 +00004935 // friend keyword.
4936 case tok::kw_friend:
4937
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00004938 // static_assert-declaration
4939 case tok::kw__Static_assert:
4940
Chris Lattner599e47e2007-08-09 17:01:07 +00004941 // GNU typeof support.
4942 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004943
Chris Lattner599e47e2007-08-09 17:01:07 +00004944 // GNU attributes.
Chris Lattner7b20dc72007-08-09 16:40:21 +00004945 case tok::kw___attribute:
Mike Stump11289f42009-09-09 15:08:12 +00004946
Richard Smithd16fe122012-10-25 00:00:53 +00004947 // C++11 decltype and constexpr.
David Blaikie15a430a2011-12-04 05:04:18 +00004948 case tok::annot_decltype:
Richard Smithd16fe122012-10-25 00:00:53 +00004949 case tok::kw_constexpr:
Francois Pichete878cb62011-06-19 08:02:06 +00004950
Richard Smith8e1ac332013-03-28 01:55:44 +00004951 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004952 case tok::kw__Atomic:
4953 return true;
4954
Chris Lattner8b2ec162008-07-26 03:38:44 +00004955 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4956 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004957 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00004958
Douglas Gregor19b7acf2011-04-27 05:41:15 +00004959 // typedef-name
4960 case tok::annot_typename:
4961 return !DisambiguatingWithExpression ||
4962 !isStartOfObjCClassMessageMissingOpenBracket();
Chad Rosierc1183952012-06-26 22:30:43 +00004963
Steve Narofff192fab2009-01-06 19:34:12 +00004964 case tok::kw___declspec:
Steve Naroff44ac7772008-12-25 14:16:32 +00004965 case tok::kw___cdecl:
4966 case tok::kw___stdcall:
4967 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004968 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004969 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004970 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004971 case tok::kw___w64:
Aaron Ballman317a77f2013-05-22 23:25:32 +00004972 case tok::kw___sptr:
4973 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00004974 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004975 case tok::kw___ptr32:
Eli Friedman53339e02009-06-08 23:27:34 +00004976 case tok::kw___forceinline:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004977 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004978 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004979
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004980 case tok::kw__Nonnull:
4981 case tok::kw__Nullable:
4982 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004983
Douglas Gregorab209d82015-07-07 03:58:42 +00004984 case tok::kw___kindof:
4985
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004986 case tok::kw___private:
4987 case tok::kw___local:
4988 case tok::kw___global:
4989 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004990 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004991 case tok::kw___read_only:
4992 case tok::kw___read_write:
4993 case tok::kw___write_only:
Alexey Bader954ba212016-04-08 13:40:33 +00004994#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004995#include "clang/Basic/OpenCLImageTypes.def"
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004996
Eli Friedman53339e02009-06-08 23:27:34 +00004997 return true;
Chris Lattneracd58a32006-08-06 17:24:14 +00004998 }
4999}
5000
Richard Smith35845152017-02-07 01:37:30 +00005001bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005002 TentativeParsingAction TPA(*this);
5003
5004 // Parse the C++ scope specifier.
5005 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005006 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005007 /*EnteringContext=*/true)) {
John McCall1f476a12010-02-26 08:45:28 +00005008 TPA.Revert();
5009 return false;
5010 }
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005011
5012 // Parse the constructor name.
Richard Smithaf3b3252017-05-18 19:21:48 +00005013 if (Tok.is(tok::identifier)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005014 // We already know that we have a constructor name; just consume
5015 // the token.
5016 ConsumeToken();
Richard Smithaf3b3252017-05-18 19:21:48 +00005017 } else if (Tok.is(tok::annot_template_id)) {
5018 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005019 } else {
5020 TPA.Revert();
5021 return false;
5022 }
5023
Richard Smith8f8697f2017-02-08 01:16:55 +00005024 // There may be attributes here, appertaining to the constructor name or type
5025 // we just stepped past.
5026 SkipCXX11Attributes();
5027
Richard Smith43f340f2012-03-27 23:05:05 +00005028 // Current class name must be followed by a left parenthesis.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005029 if (Tok.isNot(tok::l_paren)) {
5030 TPA.Revert();
5031 return false;
5032 }
5033 ConsumeParen();
5034
Richard Smith43f340f2012-03-27 23:05:05 +00005035 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5036 // that we have a constructor.
5037 if (Tok.is(tok::r_paren) ||
5038 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005039 TPA.Revert();
5040 return true;
5041 }
5042
Richard Smithf2163662013-09-06 00:12:20 +00005043 // A C++11 attribute here signals that we have a constructor, and is an
5044 // attribute on the first constructor parameter.
5045 if (getLangOpts().CPlusPlus11 &&
5046 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5047 /*OuterMightBeMessageSend*/ true)) {
5048 TPA.Revert();
5049 return true;
5050 }
5051
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005052 // If we need to, enter the specified scope.
5053 DeclaratorScopeObj DeclScopeObj(*this, SS);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005054 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005055 DeclScopeObj.EnterDeclaratorScope();
5056
Francois Pichet79f3a872011-01-31 04:54:32 +00005057 // Optionally skip Microsoft attributes.
John McCall084e83d2011-03-24 11:26:52 +00005058 ParsedAttributes Attrs(AttrFactory);
Francois Pichet79f3a872011-01-31 04:54:32 +00005059 MaybeParseMicrosoftAttributes(Attrs);
5060
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005061 // Check whether the next token(s) are part of a declaration
5062 // specifier, in which case we have the start of a parameter and,
5063 // therefore, we know that this is a constructor.
Richard Smithefd009d2012-03-27 00:56:56 +00005064 bool IsConstructor = false;
5065 if (isDeclarationSpecifier())
5066 IsConstructor = true;
5067 else if (Tok.is(tok::identifier) ||
5068 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5069 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5070 // This might be a parenthesized member name, but is more likely to
5071 // be a constructor declaration with an invalid argument type. Keep
5072 // looking.
5073 if (Tok.is(tok::annot_cxxscope))
Richard Smithaf3b3252017-05-18 19:21:48 +00005074 ConsumeAnnotationToken();
Richard Smithefd009d2012-03-27 00:56:56 +00005075 ConsumeToken();
5076
5077 // If this is not a constructor, we must be parsing a declarator,
Richard Smith1453e312012-03-27 01:42:32 +00005078 // which must have one of the following syntactic forms (see the
5079 // grammar extract at the start of ParseDirectDeclarator):
Richard Smithefd009d2012-03-27 00:56:56 +00005080 switch (Tok.getKind()) {
5081 case tok::l_paren:
5082 // C(X ( int));
5083 case tok::l_square:
5084 // C(X [ 5]);
5085 // C(X [ [attribute]]);
5086 case tok::coloncolon:
5087 // C(X :: Y);
5088 // C(X :: *p);
Richard Smithefd009d2012-03-27 00:56:56 +00005089 // Assume this isn't a constructor, rather than assuming it's a
5090 // constructor with an unnamed parameter of an ill-formed type.
5091 break;
5092
Richard Smith446161b2014-03-03 21:12:53 +00005093 case tok::r_paren:
5094 // C(X )
Richard Smith8f8697f2017-02-08 01:16:55 +00005095
5096 // Skip past the right-paren and any following attributes to get to
5097 // the function body or trailing-return-type.
5098 ConsumeParen();
5099 SkipCXX11Attributes();
5100
Richard Smith35845152017-02-07 01:37:30 +00005101 if (DeductionGuide) {
5102 // C(X) -> ... is a deduction guide.
Richard Smith8f8697f2017-02-08 01:16:55 +00005103 IsConstructor = Tok.is(tok::arrow);
Richard Smith35845152017-02-07 01:37:30 +00005104 break;
5105 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005106 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
Richard Smith446161b2014-03-03 21:12:53 +00005107 // Assume these were meant to be constructors:
5108 // C(X) : (the name of a bit-field cannot be parenthesized).
5109 // C(X) try (this is otherwise ill-formed).
5110 IsConstructor = true;
5111 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005112 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
Richard Smith446161b2014-03-03 21:12:53 +00005113 // If we have a constructor name within the class definition,
5114 // assume these were meant to be constructors:
5115 // C(X) {
5116 // C(X) ;
5117 // ... because otherwise we would be declaring a non-static data
5118 // member that is ill-formed because it's of the same type as its
5119 // surrounding class.
5120 //
5121 // FIXME: We can actually do this whether or not the name is qualified,
5122 // because if it is qualified in this context it must be being used as
Richard Smith35845152017-02-07 01:37:30 +00005123 // a constructor name.
Richard Smith446161b2014-03-03 21:12:53 +00005124 // currently, so we're somewhat conservative here.
5125 IsConstructor = IsUnqualified;
5126 }
5127 break;
5128
Richard Smithefd009d2012-03-27 00:56:56 +00005129 default:
5130 IsConstructor = true;
5131 break;
5132 }
5133 }
5134
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005135 TPA.Revert();
5136 return IsConstructor;
5137}
Chris Lattnerb9093cd2006-08-04 04:39:53 +00005138
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005139/// ParseTypeQualifierListOpt
Dawn Perchik335e16b2010-09-03 01:29:35 +00005140/// type-qualifier-list: [C99 6.7.5]
5141/// type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005142/// [vendor] attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005143/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005144/// type-qualifier-list type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005145/// [vendor] type-qualifier-list attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005146/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005147/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
Aaron Ballman08b06592014-07-22 12:44:22 +00005148/// [ only if AttReqs & AR_CXX11AttributesParsed ]
5149/// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5150/// AttrRequirements bitmask values.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005151void Parser::ParseTypeQualifierListOpt(
5152 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5153 bool IdentifierRequired,
5154 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
Aaron Ballman606093a2017-10-15 15:01:42 +00005155 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005156 isCXX11AttributeSpecifier()) {
John McCall084e83d2011-03-24 11:26:52 +00005157 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith3dff2512012-04-10 03:25:07 +00005158 ParseCXX11Attributes(attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005159 DS.takeAttributesFrom(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005160 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005161
5162 SourceLocation EndLoc;
5163
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005164 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00005165 bool isInvalid = false;
Craig Topper161e4db2014-05-21 06:02:52 +00005166 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00005167 unsigned DiagID = 0;
Chris Lattner60809f52006-11-28 05:18:46 +00005168 SourceLocation Loc = Tok.getLocation();
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005169
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005170 switch (Tok.getKind()) {
Douglas Gregor28c78432010-08-27 17:35:51 +00005171 case tok::code_completion:
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005172 if (CodeCompletionHandler)
5173 (*CodeCompletionHandler)();
5174 else
5175 Actions.CodeCompleteTypeQualifiers(DS);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00005176 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00005177
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005178 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00005179 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005180 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005181 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005182 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00005183 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005184 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005185 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005186 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00005187 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005188 getLangOpts());
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005189 break;
Richard Smith8e1ac332013-03-28 01:55:44 +00005190 case tok::kw__Atomic:
5191 if (!AtomicAllowed)
5192 goto DoneWithTypeQuals;
5193 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5194 getLangOpts());
5195 break;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005196
5197 // OpenCL qualifiers:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005198 case tok::kw___private:
5199 case tok::kw___global:
5200 case tok::kw___local:
5201 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005202 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005203 case tok::kw___read_only:
5204 case tok::kw___write_only:
5205 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00005206 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005207 break;
5208
Andrey Bokhanko45d41322016-05-11 18:38:21 +00005209 case tok::kw___unaligned:
5210 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5211 getLangOpts());
5212 break;
Aaron Ballman317a77f2013-05-22 23:25:32 +00005213 case tok::kw___uptr:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005214 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
Alp Toker62c5b572013-11-26 01:30:10 +00005215 // with the MS modifier keyword.
Aaron Ballman08b06592014-07-22 12:44:22 +00005216 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
Alp Toker47642d22013-12-03 06:13:01 +00005217 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5218 if (TryKeywordIdentFallback(false))
5219 continue;
Alp Toker62c5b572013-11-26 01:30:10 +00005220 }
Galina Kistanova77674252017-06-01 21:15:34 +00005221 LLVM_FALLTHROUGH;
Alp Toker62c5b572013-11-26 01:30:10 +00005222 case tok::kw___sptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005223 case tok::kw___w64:
Steve Narofff9c29d42008-12-25 14:41:26 +00005224 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005225 case tok::kw___ptr32:
Steve Naroff44ac7772008-12-25 14:16:32 +00005226 case tok::kw___cdecl:
5227 case tok::kw___stdcall:
5228 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005229 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005230 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005231 case tok::kw___vectorcall:
Aaron Ballman08b06592014-07-22 12:44:22 +00005232 if (AttrReqs & AR_DeclspecAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005233 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00005234 continue;
5235 }
5236 goto DoneWithTypeQuals;
Dawn Perchik335e16b2010-09-03 01:29:35 +00005237 case tok::kw___pascal:
Aaron Ballman08b06592014-07-22 12:44:22 +00005238 if (AttrReqs & AR_VendorAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005239 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00005240 continue;
5241 }
5242 goto DoneWithTypeQuals;
Douglas Gregor261a89b2015-06-19 17:51:05 +00005243
5244 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005245 case tok::kw__Nonnull:
5246 case tok::kw__Nullable:
5247 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005248 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5249 continue;
5250
Douglas Gregorab209d82015-07-07 03:58:42 +00005251 // Objective-C 'kindof' types.
5252 case tok::kw___kindof:
5253 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00005254 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00005255 (void)ConsumeToken();
5256 continue;
5257
Chris Lattnere37e2332006-08-15 04:50:22 +00005258 case tok::kw___attribute:
Aaron Ballman08b06592014-07-22 12:44:22 +00005259 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5260 // When GNU attributes are expressly forbidden, diagnose their usage.
5261 Diag(Tok, diag::err_attributes_not_allowed);
5262
5263 // Parse the attributes even if they are rejected to ensure that error
5264 // recovery is graceful.
5265 if (AttrReqs & AR_GNUAttributesParsed ||
5266 AttrReqs & AR_GNUAttributesParsedAndRejected) {
John McCall53fa7142010-12-24 02:08:15 +00005267 ParseGNUAttributes(DS.getAttributes());
Chris Lattnercf0bab22008-12-18 07:02:59 +00005268 continue; // do *not* consume the next token!
5269 }
5270 // otherwise, FALL THROUGH!
Galina Kistanova77674252017-06-01 21:15:34 +00005271 LLVM_FALLTHROUGH;
Chris Lattnercf0bab22008-12-18 07:02:59 +00005272 default:
Steve Naroff44ac7772008-12-25 14:16:32 +00005273 DoneWithTypeQuals:
Chris Lattnercf0bab22008-12-18 07:02:59 +00005274 // If this is not a type-qualifier token, we're done reading type
5275 // qualifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00005276 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005277 if (EndLoc.isValid())
5278 DS.SetRangeEnd(EndLoc);
Chris Lattnercf0bab22008-12-18 07:02:59 +00005279 return;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005280 }
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00005281
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005282 // If the specifier combination wasn't legal, issue a diagnostic.
5283 if (isInvalid) {
5284 assert(PrevSpec && "Method did not return previous specifier!");
Chris Lattner6d29c102008-11-18 07:48:38 +00005285 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005286 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005287 EndLoc = ConsumeToken();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005288 }
5289}
5290
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005291/// ParseDeclarator - Parse and verify a newly-initialized declarator.
5292///
5293void Parser::ParseDeclarator(Declarator &D) {
5294 /// This implements the 'declarator' production in the C grammar, then checks
5295 /// for well-formedness and issues diagnostics.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005296 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005297}
5298
Richard Smith0b350b92014-10-28 16:55:02 +00005299static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
Faisal Vali421b2d12017-12-29 05:41:00 +00005300 DeclaratorContext TheContext) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005301 if (Kind == tok::star || Kind == tok::caret)
5302 return true;
5303
Xiuli Pan9c14e282016-01-09 12:53:17 +00005304 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5305 return true;
5306
Richard Smith0efa75c2012-03-29 01:16:42 +00005307 if (!Lang.CPlusPlus)
5308 return false;
5309
Richard Smith0b350b92014-10-28 16:55:02 +00005310 if (Kind == tok::amp)
5311 return true;
5312
5313 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5314 // But we must not parse them in conversion-type-ids and new-type-ids, since
5315 // those can be legitimately followed by a && operator.
5316 // (The same thing can in theory happen after a trailing-return-type, but
5317 // since those are a C++11 feature, there is no rejects-valid issue there.)
5318 if (Kind == tok::ampamp)
Faisal Vali421b2d12017-12-29 05:41:00 +00005319 return Lang.CPlusPlus11 ||
5320 (TheContext != DeclaratorContext::ConversionIdContext &&
5321 TheContext != DeclaratorContext::CXXNewContext);
Richard Smith0b350b92014-10-28 16:55:02 +00005322
5323 return false;
Richard Smith0efa75c2012-03-29 01:16:42 +00005324}
5325
Xiuli Pan9c14e282016-01-09 12:53:17 +00005326// Indicates whether the given declarator is a pipe declarator.
5327static bool isPipeDeclerator(const Declarator &D) {
5328 const unsigned NumTypes = D.getNumTypeObjects();
5329
5330 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5331 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5332 return true;
5333
5334 return false;
5335}
5336
Sebastian Redlbd150f42008-11-21 19:14:01 +00005337/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5338/// is parsed by the function passed to it. Pass null, and the direct-declarator
5339/// isn't parsed at all, making this function effectively parse the C++
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005340/// ptr-operator production.
5341///
Richard Smith09f76ee2011-10-19 21:33:05 +00005342/// If the grammar of this construct is extended, matching changes must also be
Richard Smith1453e312012-03-27 01:42:32 +00005343/// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5344/// isConstructorDeclarator.
Richard Smith09f76ee2011-10-19 21:33:05 +00005345///
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005346/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5347/// [C] pointer[opt] direct-declarator
5348/// [C++] direct-declarator
5349/// [C++] ptr-operator declarator
Chris Lattner6c7416c2006-08-07 00:19:33 +00005350///
5351/// pointer: [C99 6.7.5]
5352/// '*' type-qualifier-list[opt]
5353/// '*' type-qualifier-list[opt] pointer
5354///
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005355/// ptr-operator:
5356/// '*' cv-qualifier-seq[opt]
5357/// '&'
Sebastian Redled0f3b02009-03-15 22:02:01 +00005358/// [C++0x] '&&'
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005359/// [GNU] '&' restrict[opt] attributes[opt]
Sebastian Redled0f3b02009-03-15 22:02:01 +00005360/// [GNU?] '&&' restrict[opt] attributes[opt]
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005361/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
Sebastian Redlbd150f42008-11-21 19:14:01 +00005362void Parser::ParseDeclaratorInternal(Declarator &D,
5363 DirectDeclParseFunction DirectDeclParser) {
Douglas Gregor66a985d2009-08-26 14:27:30 +00005364 if (Diags.hasAllExtensionsSilenced())
5365 D.setExtension();
Chad Rosierc1183952012-06-26 22:30:43 +00005366
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005367 // C++ member pointers start with a '::' or a nested-name.
5368 // Member pointers get special handling, since there's no place for the
5369 // scope spec in the generic path below.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005370 if (getLangOpts().CPlusPlus &&
Richard Smith83c2ecf2016-02-02 23:34:49 +00005371 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
Serge Pavlov458ea762014-07-16 05:16:52 +00005372 (Tok.is(tok::identifier) &&
5373 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
Chris Lattner803802d2009-03-24 17:04:48 +00005374 Tok.is(tok::annot_cxxscope))) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005375 bool EnteringContext =
5376 D.getContext() == DeclaratorContext::FileContext ||
5377 D.getContext() == DeclaratorContext::MemberContext;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005378 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005379 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005380
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +00005381 if (SS.isNotEmpty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005382 if (Tok.isNot(tok::star)) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005383 // The scope spec really belongs to the direct-declarator.
Richard Smith5f044ad2013-01-08 22:43:49 +00005384 if (D.mayHaveIdentifier())
5385 D.getCXXScopeSpec() = SS;
5386 else
5387 AnnotateScopeToken(SS, true);
5388
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005389 if (DirectDeclParser)
5390 (this->*DirectDeclParser)(D);
5391 return;
5392 }
5393
5394 SourceLocation Loc = ConsumeToken();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005395 D.SetRangeEnd(Loc);
John McCall084e83d2011-03-24 11:26:52 +00005396 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005397 ParseTypeQualifierListOpt(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005398 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005399
5400 // Recurse to parse whatever is left.
5401 ParseDeclaratorInternal(D, DirectDeclParser);
5402
5403 // Sema will have to catch (syntactically invalid) pointers into global
5404 // scope. It has to catch pointers into namespace scope anyway.
Erich Keanec480f302018-07-12 21:09:05 +00005405 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005406 SS, DS.getTypeQualifiers(), DS.getEndLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005407 std::move(DS.getAttributes()),
5408 /* Don't replace range end. */ SourceLocation());
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005409 return;
5410 }
5411 }
5412
5413 tok::TokenKind Kind = Tok.getKind();
Xiuli Pan9c14e282016-01-09 12:53:17 +00005414
5415 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
Xiuli Pan11e13f62016-02-26 03:13:03 +00005416 DeclSpec DS(AttrFactory);
5417 ParseTypeQualifierListOpt(DS);
Xiuli Pan9c14e282016-01-09 12:53:17 +00005418
5419 D.AddTypeInfo(
5420 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005421 std::move(DS.getAttributes()), SourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00005422 }
5423
Steve Naroffec33ed92008-08-27 16:04:49 +00005424 // Not a pointer, C++ reference, or block.
Richard Smith0b350b92014-10-28 16:55:02 +00005425 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00005426 if (DirectDeclParser)
5427 (this->*DirectDeclParser)(D);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005428 return;
5429 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005430
Sebastian Redled0f3b02009-03-15 22:02:01 +00005431 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5432 // '&&' -> rvalue reference
Sebastian Redl3b27be62009-03-23 00:00:23 +00005433 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005434 D.SetRangeEnd(Loc);
Bill Wendling3708c182007-05-27 10:15:43 +00005435
Chris Lattner9eac9312009-03-27 04:18:06 +00005436 if (Kind == tok::star || Kind == tok::caret) {
Chris Lattner788404f2008-02-21 01:32:26 +00005437 // Is a pointer.
John McCall084e83d2011-03-24 11:26:52 +00005438 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005439
Aaron Ballman08b06592014-07-22 12:44:22 +00005440 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5441 // C++11 attributes are allowed.
5442 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
Faisal Vali421b2d12017-12-29 05:41:00 +00005443 ((D.getContext() != DeclaratorContext::CXXNewContext)
5444 ? AR_GNUAttributesParsed
5445 : AR_GNUAttributesParsedAndRejected);
Aaron Ballman08b06592014-07-22 12:44:22 +00005446 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005447 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005448
Bill Wendling3708c182007-05-27 10:15:43 +00005449 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005450 ParseDeclaratorInternal(D, DirectDeclParser);
Steve Naroffec33ed92008-08-27 16:04:49 +00005451 if (Kind == tok::star)
5452 // Remember that we parsed a pointer type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005453 D.AddTypeInfo(DeclaratorChunk::getPointer(
5454 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5455 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5456 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5457 std::move(DS.getAttributes()), SourceLocation());
Steve Naroffec33ed92008-08-27 16:04:49 +00005458 else
5459 // Remember that we parsed a Block type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005460 D.AddTypeInfo(
5461 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5462 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005463 } else {
5464 // Is a reference
John McCall084e83d2011-03-24 11:26:52 +00005465 DeclSpec DS(AttrFactory);
Bill Wendling93efb222007-06-02 23:28:54 +00005466
Sebastian Redl3b27be62009-03-23 00:00:23 +00005467 // Complain about rvalue references in C++03, but then go on and build
5468 // the declarator.
Richard Smith5d164bc2011-10-15 05:09:34 +00005469 if (Kind == tok::ampamp)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005470 Diag(Loc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00005471 diag::warn_cxx98_compat_rvalue_reference :
5472 diag::ext_rvalue_reference);
Sebastian Redl3b27be62009-03-23 00:00:23 +00005473
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005474 // GNU-style and C++11 attributes are allowed here, as is restrict.
5475 ParseTypeQualifierListOpt(DS);
5476 D.ExtendWithDeclSpec(DS);
5477
Bill Wendling93efb222007-06-02 23:28:54 +00005478 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5479 // cv-qualifiers are introduced through the use of a typedef or of a
5480 // template type argument, in which case the cv-qualifiers are ignored.
Bill Wendling93efb222007-06-02 23:28:54 +00005481 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5482 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5483 Diag(DS.getConstSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005484 diag::err_invalid_reference_qualifier_application) << "const";
Bill Wendling93efb222007-06-02 23:28:54 +00005485 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5486 Diag(DS.getVolatileSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005487 diag::err_invalid_reference_qualifier_application) << "volatile";
Richard Smith8e1ac332013-03-28 01:55:44 +00005488 // 'restrict' is permitted as an extension.
5489 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5490 Diag(DS.getAtomicSpecLoc(),
5491 diag::err_invalid_reference_qualifier_application) << "_Atomic";
Bill Wendling93efb222007-06-02 23:28:54 +00005492 }
Bill Wendling3708c182007-05-27 10:15:43 +00005493
5494 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005495 ParseDeclaratorInternal(D, DirectDeclParser);
Bill Wendling3708c182007-05-27 10:15:43 +00005496
Douglas Gregor66583c52008-11-03 15:51:28 +00005497 if (D.getNumTypeObjects() > 0) {
5498 // C++ [dcl.ref]p4: There shall be no references to references.
5499 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5500 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
Chris Lattnerebad6a22008-11-19 07:37:42 +00005501 if (const IdentifierInfo *II = D.getIdentifier())
5502 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5503 << II;
5504 else
5505 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5506 << "type name";
Douglas Gregor66583c52008-11-03 15:51:28 +00005507
Sebastian Redlbd150f42008-11-21 19:14:01 +00005508 // Once we've complained about the reference-to-reference, we
Douglas Gregor66583c52008-11-03 15:51:28 +00005509 // can go ahead and build the (technically ill-formed)
5510 // declarator: reference collapsing will take care of it.
5511 }
5512 }
5513
Richard Smith8e1ac332013-03-28 01:55:44 +00005514 // Remember that we parsed a reference type.
Chris Lattner788404f2008-02-21 01:32:26 +00005515 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
Sebastian Redled0f3b02009-03-15 22:02:01 +00005516 Kind == tok::amp),
Erich Keanec480f302018-07-12 21:09:05 +00005517 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005518 }
Chris Lattner6c7416c2006-08-07 00:19:33 +00005519}
5520
Richard Trieuf4b81d02014-06-24 23:14:24 +00005521// When correcting from misplaced brackets before the identifier, the location
5522// is saved inside the declarator so that other diagnostic messages can use
5523// them. This extracts and returns that location, or returns the provided
5524// location if a stored location does not exist.
5525static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5526 SourceLocation Loc) {
5527 if (D.getName().StartLocation.isInvalid() &&
5528 D.getName().EndLocation.isValid())
5529 return D.getName().EndLocation;
5530
5531 return Loc;
5532}
5533
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005534/// ParseDirectDeclarator
5535/// direct-declarator: [C99 6.7.5]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005536/// [C99] identifier
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005537/// '(' declarator ')'
5538/// [GNU] '(' attributes declarator ')'
Chris Lattnere8074e62006-08-06 18:30:15 +00005539/// [C90] direct-declarator '[' constant-expression[opt] ']'
5540/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5541/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5542/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5543/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005544/// [C++11] direct-declarator '[' constant-expression[opt] ']'
5545/// attribute-specifier-seq[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005546/// direct-declarator '(' parameter-type-list ')'
5547/// direct-declarator '(' identifier-list[opt] ')'
5548/// [GNU] direct-declarator '(' parameter-forward-declarations
5549/// parameter-type-list[opt] ')'
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00005550/// [C++] direct-declarator '(' parameter-declaration-clause ')'
5551/// cv-qualifier-seq[opt] exception-specification[opt]
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005552/// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5553/// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5554/// ref-qualifier[opt] exception-specification[opt]
Douglas Gregor61956c42008-10-31 09:07:45 +00005555/// [C++] declarator-id
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005556/// [C++11] declarator-id attribute-specifier-seq[opt]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005557///
5558/// declarator-id: [C++ 8]
Douglas Gregor27b4c162010-12-23 22:44:42 +00005559/// '...'[opt] id-expression
Douglas Gregor831c93f2008-11-05 20:51:48 +00005560/// '::'[opt] nested-name-specifier[opt] type-name
5561///
5562/// id-expression: [C++ 5.1]
5563/// unqualified-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005564/// qualified-id
Douglas Gregor831c93f2008-11-05 20:51:48 +00005565///
5566/// unqualified-id: [C++ 5.1]
Mike Stump11289f42009-09-09 15:08:12 +00005567/// identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005568/// operator-function-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005569/// conversion-function-id
Mike Stump11289f42009-09-09 15:08:12 +00005570/// '~' class-name
Douglas Gregor7f741122009-02-25 19:37:18 +00005571/// template-id
Argyrios Kyrtzidise4426352008-11-07 22:02:30 +00005572///
Richard Smithbdb84f32016-07-22 23:36:59 +00005573/// C++17 adds the following, which we also handle here:
5574///
5575/// simple-declaration:
5576/// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5577///
Richard Smith1453e312012-03-27 01:42:32 +00005578/// Note, any additional constructs added here may need corresponding changes
5579/// in isConstructorDeclarator.
Chris Lattneracd58a32006-08-06 17:24:14 +00005580void Parser::ParseDirectDeclarator(Declarator &D) {
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005581 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005582
David Blaikiebbafb8a2012-03-11 07:00:24 +00005583 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
Richard Smithbdb84f32016-07-22 23:36:59 +00005584 // This might be a C++17 structured binding.
5585 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5586 D.getCXXScopeSpec().isEmpty())
5587 return ParseDecompositionDeclarator(D);
5588
Serge Pavlov458ea762014-07-16 05:16:52 +00005589 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5590 // this context it is a bitfield. Also in range-based for statement colon
5591 // may delimit for-range-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00005592 ColonProtectionRAIIObject X(
5593 *this, D.getContext() == DeclaratorContext::MemberContext ||
5594 (D.getContext() == DeclaratorContext::ForContext &&
5595 getLangOpts().CPlusPlus11));
Serge Pavlov458ea762014-07-16 05:16:52 +00005596
Douglas Gregor7861a802009-11-03 01:35:08 +00005597 // ParseDeclaratorInternal might already have parsed the scope.
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005598 if (D.getCXXScopeSpec().isEmpty()) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005599 bool EnteringContext =
5600 D.getContext() == DeclaratorContext::FileContext ||
5601 D.getContext() == DeclaratorContext::MemberContext;
David Blaikieefdccaa2016-01-15 23:43:34 +00005602 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005603 EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005604 }
5605
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005606 if (D.getCXXScopeSpec().isValid()) {
Richard Smith64e033f2015-01-15 00:48:52 +00005607 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5608 D.getCXXScopeSpec()))
John McCall2b058ef2009-12-11 20:04:54 +00005609 // Change the declaration context for name lookup, until this function
5610 // is exited (and the declarator has been parsed).
5611 DeclScopeObj.EnterDeclaratorScope();
Alex Lorenze151f0102016-12-07 10:24:44 +00005612 else if (getObjCDeclContext()) {
5613 // Ensure that we don't interpret the next token as an identifier when
5614 // dealing with declarations in an Objective-C container.
5615 D.SetIdentifier(nullptr, Tok.getLocation());
5616 D.setInvalidType(true);
5617 ConsumeToken();
5618 goto PastIdentifier;
5619 }
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005620 }
5621
Douglas Gregor27b4c162010-12-23 22:44:42 +00005622 // C++0x [dcl.fct]p14:
Faisal Vali8435a692014-12-04 12:40:21 +00005623 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5624 // parameter-declaration-clause without a preceding comma. In this case,
5625 // the ellipsis is parsed as part of the abstract-declarator if the type
5626 // of the parameter either names a template parameter pack that has not
5627 // been expanded or contains auto; otherwise, it is parsed as part of the
5628 // parameter-declaration-clause.
Richard Smith0efa75c2012-03-29 01:16:42 +00005629 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00005630 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5631 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5632 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
Douglas Gregor27b4c162010-12-23 22:44:42 +00005633 NextToken().is(tok::r_paren) &&
Richard Smithb19337f2013-02-20 20:19:27 +00005634 !D.hasGroupingParens() &&
Faisal Vali8435a692014-12-04 12:40:21 +00005635 !Actions.containsUnexpandedParameterPacks(D) &&
Faisal Vali090da2d2018-01-01 18:23:28 +00005636 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005637 SourceLocation EllipsisLoc = ConsumeToken();
Richard Smith0b350b92014-10-28 16:55:02 +00005638 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005639 // The ellipsis was put in the wrong place. Recover, and explain to
5640 // the user what they should have done.
5641 ParseDeclarator(D);
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00005642 if (EllipsisLoc.isValid())
5643 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00005644 return;
5645 } else
5646 D.setEllipsisLoc(EllipsisLoc);
5647
5648 // The ellipsis can't be followed by a parenthesized declarator. We
5649 // check for that in ParseParenDeclarator, after we have disambiguated
5650 // the l_paren token.
5651 }
5652
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005653 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5654 tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00005655 // We found something that indicates the start of an unqualified-id.
5656 // Parse that unqualified-id.
John McCall84821e72010-04-13 06:39:49 +00005657 bool AllowConstructorName;
Richard Smith35845152017-02-07 01:37:30 +00005658 bool AllowDeductionGuide;
5659 if (D.getDeclSpec().hasTypeSpecifier()) {
John McCall84821e72010-04-13 06:39:49 +00005660 AllowConstructorName = false;
Richard Smith35845152017-02-07 01:37:30 +00005661 AllowDeductionGuide = false;
5662 } else if (D.getCXXScopeSpec().isSet()) {
John McCall84821e72010-04-13 06:39:49 +00005663 AllowConstructorName =
Faisal Vali421b2d12017-12-29 05:41:00 +00005664 (D.getContext() == DeclaratorContext::FileContext ||
5665 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005666 AllowDeductionGuide = false;
5667 } else {
Faisal Vali421b2d12017-12-29 05:41:00 +00005668 AllowConstructorName =
5669 (D.getContext() == DeclaratorContext::MemberContext);
Fangrui Song6907ce22018-07-30 19:24:48 +00005670 AllowDeductionGuide =
Faisal Vali421b2d12017-12-29 05:41:00 +00005671 (D.getContext() == DeclaratorContext::FileContext ||
5672 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005673 }
John McCall84821e72010-04-13 06:39:49 +00005674
Richard Smith64e033f2015-01-15 00:48:52 +00005675 bool HadScope = D.getCXXScopeSpec().isValid();
Chad Rosierc1183952012-06-26 22:30:43 +00005676 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5677 /*EnteringContext=*/true,
David Blaikieefdccaa2016-01-15 23:43:34 +00005678 /*AllowDestructorName=*/true, AllowConstructorName,
Richard Smithc08b6932018-04-27 02:00:13 +00005679 AllowDeductionGuide, nullptr, nullptr,
Richard Smith35845152017-02-07 01:37:30 +00005680 D.getName()) ||
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005681 // Once we're past the identifier, if the scope was bad, mark the
5682 // whole declarator bad.
5683 D.getCXXScopeSpec().isInvalid()) {
Craig Topper161e4db2014-05-21 06:02:52 +00005684 D.SetIdentifier(nullptr, Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005685 D.setInvalidType(true);
Douglas Gregor7861a802009-11-03 01:35:08 +00005686 } else {
Richard Smith64e033f2015-01-15 00:48:52 +00005687 // ParseUnqualifiedId might have parsed a scope specifier during error
5688 // recovery. If it did so, enter that scope.
5689 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5690 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5691 D.getCXXScopeSpec()))
5692 DeclScopeObj.EnterDeclaratorScope();
5693
Douglas Gregor7861a802009-11-03 01:35:08 +00005694 // Parsed the unqualified-id; update range information and move along.
5695 if (D.getSourceRange().getBegin().isInvalid())
5696 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5697 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005698 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005699 goto PastIdentifier;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005700 }
Richard Smithd63db6e2015-12-19 02:40:19 +00005701
5702 if (D.getCXXScopeSpec().isNotEmpty()) {
5703 // We have a scope specifier but no following unqualified-id.
5704 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5705 diag::err_expected_unqualified_id)
5706 << /*C++*/1;
5707 D.SetIdentifier(nullptr, Tok.getLocation());
5708 goto PastIdentifier;
5709 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005710 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005711 assert(!getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005712 "There's a C++-specific check for tok::identifier above");
5713 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5714 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Richard Trieu2664dc12014-05-05 22:06:50 +00005715 D.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005716 ConsumeToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00005717 goto PastIdentifier;
Richard Smith74639b12017-05-19 01:54:59 +00005718 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5719 // We're not allowed an identifier here, but we got one. Try to figure out
5720 // if the user was trying to attach a name to the type, or whether the name
5721 // is some unrelated trailing syntax.
5722 bool DiagnoseIdentifier = false;
5723 if (D.hasGroupingParens())
5724 // An identifier within parens is unlikely to be intended to be anything
5725 // other than a name being "declared".
5726 DiagnoseIdentifier = true;
Richard Smith77a9c602018-02-28 03:02:23 +00005727 else if (D.getContext() == DeclaratorContext::TemplateArgContext)
Richard Smith74639b12017-05-19 01:54:59 +00005728 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5729 DiagnoseIdentifier =
5730 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali421b2d12017-12-29 05:41:00 +00005731 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5732 D.getContext() == DeclaratorContext::AliasTemplateContext)
Richard Smith74639b12017-05-19 01:54:59 +00005733 // The most likely error is that the ';' was forgotten.
5734 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
Richard Smithe303e352018-02-02 22:24:54 +00005735 else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5736 D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
Richard Smith74639b12017-05-19 01:54:59 +00005737 !isCXX11VirtSpecifier(Tok))
5738 DiagnoseIdentifier = NextToken().isOneOf(
5739 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5740 if (DiagnoseIdentifier) {
Richard Smithf39720b2013-10-13 22:12:28 +00005741 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5742 << FixItHint::CreateRemoval(Tok.getLocation());
Craig Topper161e4db2014-05-21 06:02:52 +00005743 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithf39720b2013-10-13 22:12:28 +00005744 ConsumeToken();
5745 goto PastIdentifier;
5746 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005747 }
Richard Smith0efa75c2012-03-29 01:16:42 +00005748
Douglas Gregor7861a802009-11-03 01:35:08 +00005749 if (Tok.is(tok::l_paren)) {
Richard Smithe303e352018-02-02 22:24:54 +00005750 // If this might be an abstract-declarator followed by a direct-initializer,
5751 // check whether this is a valid declarator chunk. If it can't be, assume
5752 // that it's an initializer instead.
5753 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5754 RevertingTentativeParsingAction PA(*this);
5755 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5756 TPResult::False) {
5757 D.SetIdentifier(nullptr, Tok.getLocation());
5758 goto PastIdentifier;
5759 }
5760 }
5761
Chris Lattneracd58a32006-08-06 17:24:14 +00005762 // direct-declarator: '(' declarator ')'
Chris Lattnere37e2332006-08-15 04:50:22 +00005763 // direct-declarator: '(' attributes declarator ')'
Chris Lattneracd58a32006-08-06 17:24:14 +00005764 // Example: 'char (*X)' or 'int (*XX)(void)'
5765 ParseParenDeclarator(D);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005766
5767 // If the declarator was parenthesized, we entered the declarator
5768 // scope when parsing the parenthesized declarator, then exited
5769 // the scope already. Re-enter the scope, if we need to.
5770 if (D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005771 // If there was an error parsing parenthesized declarator, declarator
Richard Smith0efa75c2012-03-29 01:16:42 +00005772 // scope may have been entered before. Don't do it again.
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005773 if (!D.isInvalidType() &&
Nico Weber6b05f382015-02-18 04:53:03 +00005774 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5775 D.getCXXScopeSpec()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005776 // Change the declaration context for name lookup, until this function
5777 // is exited (and the declarator has been parsed).
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005778 DeclScopeObj.EnterDeclaratorScope();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005779 }
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005780 } else if (D.mayOmitIdentifier()) {
Chris Lattneracd58a32006-08-06 17:24:14 +00005781 // This could be something simple like "int" (in which case the declarator
5782 // portion is empty), if an abstract-declarator is allowed.
Craig Topper161e4db2014-05-21 06:02:52 +00005783 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithb19337f2013-02-20 20:19:27 +00005784
5785 // The grammar for abstract-pack-declarator does not allow grouping parens.
5786 // FIXME: Revisit this once core issue 1488 is resolved.
5787 if (D.hasEllipsis() && D.hasGroupingParens())
5788 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5789 diag::ext_abstract_pack_declarator_parens);
Chris Lattneracd58a32006-08-06 17:24:14 +00005790 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00005791 if (Tok.getKind() == tok::annot_pragma_parser_crash)
David Blaikie5bd4c2a2012-08-21 18:56:49 +00005792 LLVM_BUILTIN_TRAP;
Richard Trieuf4b81d02014-06-24 23:14:24 +00005793 if (Tok.is(tok::l_square))
5794 return ParseMisplacedBracketDeclarator(D);
Faisal Vali421b2d12017-12-29 05:41:00 +00005795 if (D.getContext() == DeclaratorContext::MemberContext) {
Alex Lorenzf1278212017-04-11 15:01:53 +00005796 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5797 // treating these keyword as valid member names.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005798 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
Alex Lorenzf1278212017-04-11 15:01:53 +00005799 Tok.getIdentifierInfo() &&
5800 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5801 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5802 diag::err_expected_member_name_or_semi_objcxx_keyword)
5803 << Tok.getIdentifierInfo()
5804 << (D.getDeclSpec().isEmpty() ? SourceRange()
5805 : D.getDeclSpec().getSourceRange());
5806 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5807 D.SetRangeEnd(Tok.getLocation());
5808 ConsumeToken();
5809 goto PastIdentifier;
5810 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005811 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5812 diag::err_expected_member_name_or_semi)
Richard Trieua1342402014-05-02 23:40:32 +00005813 << (D.getDeclSpec().isEmpty() ? SourceRange()
5814 : D.getDeclSpec().getSourceRange());
Richard Trieuf4b81d02014-06-24 23:14:24 +00005815 } else if (getLangOpts().CPlusPlus) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005816 if (Tok.isOneOf(tok::period, tok::arrow))
Richard Trieu9c672672013-01-26 02:31:38 +00005817 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
Richard Trieu2f586962013-09-05 02:31:33 +00005818 else {
5819 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5820 if (Tok.isAtStartOfLine() && Loc.isValid())
5821 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5822 << getLangOpts().CPlusPlus;
5823 else
Richard Trieuf4b81d02014-06-24 23:14:24 +00005824 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5825 diag::err_expected_unqualified_id)
Richard Trieu2f586962013-09-05 02:31:33 +00005826 << getLangOpts().CPlusPlus;
5827 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005828 } else {
5829 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5830 diag::err_expected_either)
5831 << tok::identifier << tok::l_paren;
5832 }
Craig Topper161e4db2014-05-21 06:02:52 +00005833 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattner8c5dd732008-11-11 06:13:16 +00005834 D.setInvalidType(true);
Chris Lattneracd58a32006-08-06 17:24:14 +00005835 }
Mike Stump11289f42009-09-09 15:08:12 +00005836
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005837 PastIdentifier:
Chris Lattneracd58a32006-08-06 17:24:14 +00005838 assert(D.isPastIdentifier() &&
5839 "Haven't past the location of the identifier yet?");
Mike Stump11289f42009-09-09 15:08:12 +00005840
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005841 // Don't parse attributes unless we have parsed an unparenthesized name.
5842 if (D.hasName() && !D.getNumTypeObjects())
Richard Smith89645bc2013-01-02 12:01:23 +00005843 MaybeParseCXX11Attributes(D);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005844
Chris Lattneracd58a32006-08-06 17:24:14 +00005845 while (1) {
Chris Lattner76c72282007-10-09 17:33:22 +00005846 if (Tok.is(tok::l_paren)) {
David Blaikie15a430a2011-12-04 05:04:18 +00005847 // Enter function-declaration scope, limiting any declarators to the
5848 // function prototype scope, including parameter declarators.
5849 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00005850 Scope::FunctionPrototypeScope|Scope::DeclScope|
5851 (D.isFunctionDeclaratorAFunctionDeclaration()
5852 ? Scope::FunctionDeclarationScope : 0));
5853
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005854 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5855 // In such a case, check if we actually have a function declarator; if it
5856 // is not, the declarator has been fully parsed.
Richard Smith943c4402012-07-30 21:30:52 +00005857 bool IsAmbiguous = false;
Richard Smith4f605af2012-08-18 00:55:03 +00005858 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5859 // The name of the declarator, if any, is tentatively declared within
5860 // a possible direct initializer.
5861 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5862 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5863 TentativelyDeclaredIdentifiers.pop_back();
5864 if (!IsFunctionDecl)
5865 break;
5866 }
John McCall084e83d2011-03-24 11:26:52 +00005867 ParsedAttributes attrs(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005868 BalancedDelimiterTracker T(*this, tok::l_paren);
5869 T.consumeOpen();
Richard Smith943c4402012-07-30 21:30:52 +00005870 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
David Blaikie15a430a2011-12-04 05:04:18 +00005871 PrototypeScope.Exit();
Chris Lattner76c72282007-10-09 17:33:22 +00005872 } else if (Tok.is(tok::l_square)) {
Chris Lattnere8074e62006-08-06 18:30:15 +00005873 ParseBracketDeclarator(D);
Chris Lattneracd58a32006-08-06 17:24:14 +00005874 } else {
5875 break;
5876 }
5877 }
Chad Rosierc1183952012-06-26 22:30:43 +00005878}
Chris Lattneracd58a32006-08-06 17:24:14 +00005879
Richard Smithbdb84f32016-07-22 23:36:59 +00005880void Parser::ParseDecompositionDeclarator(Declarator &D) {
5881 assert(Tok.is(tok::l_square));
5882
5883 // If this doesn't look like a structured binding, maybe it's a misplaced
5884 // array declarator.
5885 // FIXME: Consume the l_square first so we don't need extra lookahead for
5886 // this.
5887 if (!(NextToken().is(tok::identifier) &&
5888 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5889 !(NextToken().is(tok::r_square) &&
5890 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5891 return ParseMisplacedBracketDeclarator(D);
5892
5893 BalancedDelimiterTracker T(*this, tok::l_square);
5894 T.consumeOpen();
5895
5896 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5897 while (Tok.isNot(tok::r_square)) {
5898 if (!Bindings.empty()) {
5899 if (Tok.is(tok::comma))
5900 ConsumeToken();
5901 else {
5902 if (Tok.is(tok::identifier)) {
5903 SourceLocation EndLoc = getEndOfPreviousToken();
5904 Diag(EndLoc, diag::err_expected)
5905 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5906 } else {
5907 Diag(Tok, diag::err_expected_comma_or_rsquare);
5908 }
5909
5910 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5911 StopAtSemi | StopBeforeMatch);
5912 if (Tok.is(tok::comma))
5913 ConsumeToken();
5914 else if (Tok.isNot(tok::identifier))
5915 break;
5916 }
5917 }
5918
5919 if (Tok.isNot(tok::identifier)) {
5920 Diag(Tok, diag::err_expected) << tok::identifier;
5921 break;
5922 }
5923
5924 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
5925 ConsumeToken();
5926 }
5927
5928 if (Tok.isNot(tok::r_square))
5929 // We've already diagnosed a problem here.
5930 T.skipToEnd();
5931 else {
5932 // C++17 does not allow the identifier-list in a structured binding
5933 // to be empty.
5934 if (Bindings.empty())
5935 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
5936
5937 T.consumeClose();
5938 }
5939
5940 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
5941 T.getCloseLocation());
5942}
5943
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005944/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5945/// only called before the identifier, so these are most likely just grouping
Mike Stump11289f42009-09-09 15:08:12 +00005946/// parens for precedence. If we find that these are actually function
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005947/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5948///
5949/// direct-declarator:
5950/// '(' declarator ')'
5951/// [GNU] '(' attributes declarator ')'
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005952/// direct-declarator '(' parameter-type-list ')'
5953/// direct-declarator '(' identifier-list[opt] ')'
5954/// [GNU] direct-declarator '(' parameter-forward-declarations
5955/// parameter-type-list[opt] ')'
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005956///
5957void Parser::ParseParenDeclarator(Declarator &D) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005958 BalancedDelimiterTracker T(*this, tok::l_paren);
5959 T.consumeOpen();
5960
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005961 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
Mike Stump11289f42009-09-09 15:08:12 +00005962
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005963 // Eat any attributes before we look at whether this is a grouping or function
5964 // declarator paren. If this is a grouping paren, the attribute applies to
5965 // the type being built up, for example:
5966 // int (__attribute__(()) *x)(long y)
5967 // If this ends up not being a grouping paren, the attribute applies to the
5968 // first argument, for example:
5969 // int (__attribute__(()) int x)
5970 // In either case, we need to eat any attributes to be able to determine what
5971 // sort of paren this is.
5972 //
John McCall084e83d2011-03-24 11:26:52 +00005973 ParsedAttributes attrs(AttrFactory);
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005974 bool RequiresArg = false;
5975 if (Tok.is(tok::kw___attribute)) {
John McCall53fa7142010-12-24 02:08:15 +00005976 ParseGNUAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00005977
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005978 // We require that the argument list (if this is a non-grouping paren) be
5979 // present even if the attribute list was empty.
5980 RequiresArg = true;
5981 }
Chad Rosiereea9ca72012-12-21 21:22:20 +00005982
Steve Naroff44ac7772008-12-25 14:16:32 +00005983 // Eat any Microsoft extensions.
Chad Rosiereea9ca72012-12-21 21:22:20 +00005984 ParseMicrosoftTypeAttributes(attrs);
5985
Dawn Perchik335e16b2010-09-03 01:29:35 +00005986 // Eat any Borland extensions.
Ted Kremenek5eec2b02010-11-10 05:59:39 +00005987 if (Tok.is(tok::kw___pascal))
John McCall53fa7142010-12-24 02:08:15 +00005988 ParseBorlandTypeAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00005989
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005990 // If we haven't past the identifier yet (or where the identifier would be
5991 // stored, if this is an abstract declarator), then this is probably just
5992 // grouping parens. However, if this could be an abstract-declarator, then
5993 // this could also be the start of function arguments (consider 'void()').
5994 bool isGrouping;
Mike Stump11289f42009-09-09 15:08:12 +00005995
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005996 if (!D.mayOmitIdentifier()) {
5997 // If this can't be an abstract-declarator, this *must* be a grouping
5998 // paren, because we haven't seen the identifier yet.
5999 isGrouping = true;
6000 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
Richard Smith43f340f2012-03-27 23:05:05 +00006001 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6002 NextToken().is(tok::r_paren)) || // C++ int(...)
Richard Smith2620cd92012-04-11 04:01:28 +00006003 isDeclarationSpecifier() || // 'int(int)' is a function.
6004 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006005 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6006 // considered to be a type, not a K&R identifier-list.
6007 isGrouping = false;
6008 } else {
6009 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6010 isGrouping = true;
6011 }
Mike Stump11289f42009-09-09 15:08:12 +00006012
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006013 // If this is a grouping paren, handle:
6014 // direct-declarator: '(' declarator ')'
6015 // direct-declarator: '(' attributes declarator ')'
6016 if (isGrouping) {
Richard Smith0efa75c2012-03-29 01:16:42 +00006017 SourceLocation EllipsisLoc = D.getEllipsisLoc();
6018 D.setEllipsisLoc(SourceLocation());
6019
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006020 bool hadGroupingParens = D.hasGroupingParens();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006021 D.setGroupingParens(true);
Sebastian Redlbd150f42008-11-21 19:14:01 +00006022 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006023 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006024 T.consumeClose();
Erich Keanec480f302018-07-12 21:09:05 +00006025 D.AddTypeInfo(
6026 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6027 std::move(attrs), T.getCloseLocation());
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006028
6029 D.setGroupingParens(hadGroupingParens);
Richard Smith0efa75c2012-03-29 01:16:42 +00006030
6031 // An ellipsis cannot be placed outside parentheses.
6032 if (EllipsisLoc.isValid())
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00006033 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00006034
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006035 return;
6036 }
Mike Stump11289f42009-09-09 15:08:12 +00006037
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006038 // Okay, if this wasn't a grouping paren, it must be the start of a function
6039 // argument list. Recognize that this declarator will never have an
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006040 // identifier (and remember where it would have been), then call into
6041 // ParseFunctionDeclarator to handle of argument list.
Craig Topper161e4db2014-05-21 06:02:52 +00006042 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006043
David Blaikie15a430a2011-12-04 05:04:18 +00006044 // Enter function-declaration scope, limiting any declarators to the
6045 // function prototype scope, including parameter declarators.
6046 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00006047 Scope::FunctionPrototypeScope | Scope::DeclScope |
6048 (D.isFunctionDeclaratorAFunctionDeclaration()
6049 ? Scope::FunctionDeclarationScope : 0));
Richard Smith943c4402012-07-30 21:30:52 +00006050 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
David Blaikie15a430a2011-12-04 05:04:18 +00006051 PrototypeScope.Exit();
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006052}
6053
6054/// ParseFunctionDeclarator - We are after the identifier and have parsed the
6055/// declarator D up to a paren, which indicates that we are parsing function
6056/// arguments.
Chris Lattneracd58a32006-08-06 17:24:14 +00006057///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006058/// If FirstArgAttrs is non-null, then the caller parsed those arguments
6059/// immediately after the open paren - they should be considered to be the
6060/// first argument of a parameter.
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006061///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006062/// If RequiresArg is true, then the first argument of the function is required
6063/// to be present and required to not be an identifier list.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006064///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006065/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6066/// (C++11) ref-qualifier[opt], exception-specification[opt],
6067/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
6068///
6069/// [C++11] exception-specification:
Douglas Gregor9e66af42011-07-05 16:44:18 +00006070/// dynamic-exception-specification
6071/// noexcept-specification
6072///
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006073void Parser::ParseFunctionDeclarator(Declarator &D,
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006074 ParsedAttributes &FirstArgAttrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006075 BalancedDelimiterTracker &Tracker,
Richard Smith943c4402012-07-30 21:30:52 +00006076 bool IsAmbiguous,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006077 bool RequiresArg) {
Chad Rosierc1183952012-06-26 22:30:43 +00006078 assert(getCurScope()->isFunctionPrototypeScope() &&
David Blaikie15a430a2011-12-04 05:04:18 +00006079 "Should call from a Function scope");
Douglas Gregor9e66af42011-07-05 16:44:18 +00006080 // lparen is already consumed!
6081 assert(D.isPastIdentifier() && "Should not call before identifier!");
6082
6083 // This should be true when the function has typed arguments.
6084 // Otherwise, it is treated as a K&R-style function.
6085 bool HasProto = false;
6086 // Build up an array of information about the parsed arguments.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006087 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006088 // Remember where we see an ellipsis, if any.
6089 SourceLocation EllipsisLoc;
6090
6091 DeclSpec DS(AttrFactory);
6092 bool RefQualifierIsLValueRef = true;
6093 SourceLocation RefQualifierLoc;
6094 ExceptionSpecificationType ESpecType = EST_None;
6095 SourceRange ESpecRange;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006096 SmallVector<ParsedType, 2> DynamicExceptions;
6097 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006098 ExprResult NoexceptExpr;
Hans Wennborgdcfba332015-10-06 23:40:43 +00006099 CachedTokens *ExceptionSpecTokens = nullptr;
Aaron Ballman606093a2017-10-15 15:01:42 +00006100 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith700537c2012-06-12 01:51:59 +00006101 TypeResult TrailingReturnType;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006102
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006103 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6104 EndLoc is the end location for the function declarator.
6105 They differ for trailing return types. */
6106 SourceLocation StartLoc, LocalEndLoc, EndLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006107 SourceLocation LParenLoc, RParenLoc;
6108 LParenLoc = Tracker.getOpenLocation();
6109 StartLoc = LParenLoc;
6110
Douglas Gregor9e66af42011-07-05 16:44:18 +00006111 if (isFunctionDeclaratorIdentifierList()) {
6112 if (RequiresArg)
6113 Diag(Tok, diag::err_argument_required_after_attribute);
6114
6115 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6116
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006117 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006118 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006119 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006120 EndLoc = RParenLoc;
Aaron Ballman606093a2017-10-15 15:01:42 +00006121
Fangrui Song6907ce22018-07-30 19:24:48 +00006122 // If there are attributes following the identifier list, parse them and
Aaron Ballman606093a2017-10-15 15:01:42 +00006123 // prohibit them.
6124 MaybeParseCXX11Attributes(FnAttrs);
6125 ProhibitAttributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006126 } else {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006127 if (Tok.isNot(tok::r_paren))
Fangrui Song6907ce22018-07-30 19:24:48 +00006128 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
Faisal Vali2b391ab2013-09-26 19:54:12 +00006129 EllipsisLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006130 else if (RequiresArg)
6131 Diag(Tok, diag::err_argument_required_after_attribute);
6132
Alexey Bader1f277942017-10-11 11:16:31 +00006133 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6134 || getLangOpts().OpenCL;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006135
6136 // If we have the closing ')', eat it.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006137 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006138 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006139 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006140 EndLoc = RParenLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006141
David Blaikiebbafb8a2012-03-11 07:00:24 +00006142 if (getLangOpts().CPlusPlus) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006143 // FIXME: Accept these components in any order, and produce fixits to
6144 // correct the order if the user gets it wrong. Ideally we should deal
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00006145 // with the pure-specifier in the same way.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006146
6147 // Parse cv-qualifier-seq[opt].
Aaron Ballman08b06592014-07-22 12:44:22 +00006148 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
Alex Lorenz8f4d3992017-02-13 23:19:40 +00006149 /*AtomicAllowed*/ false,
6150 /*IdentifierRequired=*/false,
6151 llvm::function_ref<void()>([&]() {
6152 Actions.CodeCompleteFunctionQualifiers(DS, D);
6153 }));
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006154 if (!DS.getSourceRange().getEnd().isInvalid()) {
6155 EndLoc = DS.getSourceRange().getEnd();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006156 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006157
6158 // Parse ref-qualifier[opt].
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006159 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
Douglas Gregor9e66af42011-07-05 16:44:18 +00006160 EndLoc = RefQualifierLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006161
Douglas Gregor3024f072012-04-16 07:05:22 +00006162 // C++11 [expr.prim.general]p3:
Chad Rosierc1183952012-06-26 22:30:43 +00006163 // If a declaration declares a member function or member function
6164 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00006165 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Chad Rosierc1183952012-06-26 22:30:43 +00006166 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00006167 // declarator.
Richard Smithad1bbb92013-03-15 00:41:52 +00006168 // FIXME: currently, "static" case isn't handled correctly.
Chad Rosierc1183952012-06-26 22:30:43 +00006169 bool IsCXX11MemberFunction =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006170 getLangOpts().CPlusPlus11 &&
Richard Smith990a6922014-01-17 21:01:18 +00006171 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
Faisal Vali421b2d12017-12-29 05:41:00 +00006172 (D.getContext() == DeclaratorContext::MemberContext
Richard Smithad1bbb92013-03-15 00:41:52 +00006173 ? !D.getDeclSpec().isFriendSpecified()
Faisal Vali421b2d12017-12-29 05:41:00 +00006174 : D.getContext() == DeclaratorContext::FileContext &&
Richard Smithad1bbb92013-03-15 00:41:52 +00006175 D.getCXXScopeSpec().isValid() &&
6176 Actions.CurContext->isRecord());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006177
6178 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6179 if (D.getDeclSpec().isConstexprSpecified() && !getLangOpts().CPlusPlus14)
6180 Q.addConst();
Anastasia Stulova5cffa452019-01-21 16:01:38 +00006181 // FIXME: Collect C++ address spaces.
6182 // If there are multiple different address spaces, the source is invalid.
6183 // Carry on using the first addr space for the qualifiers of 'this'.
6184 // The diagnostic will be given later while creating the function
6185 // prototype for the method.
6186 if (getLangOpts().OpenCLCPlusPlus) {
6187 for (ParsedAttr &attr : DS.getAttributes()) {
6188 LangAS ASIdx = attr.asOpenCLLangAS();
6189 if (ASIdx != LangAS::Default) {
6190 Q.addAddressSpace(ASIdx);
6191 break;
6192 }
6193 }
6194 }
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006195
6196 Sema::CXXThisScopeRAII ThisScope(
6197 Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6198 IsCXX11MemberFunction);
Richard Smith2331bbf2012-05-02 22:22:32 +00006199
Douglas Gregor9e66af42011-07-05 16:44:18 +00006200 // Parse exception-specification[opt].
Richard Smith0b3a4622014-11-13 20:01:57 +00006201 bool Delayed = D.isFirstDeclarationOfMember() &&
Richard Smith3ef3e892014-11-20 22:32:11 +00006202 D.isFunctionDeclaratorAFunctionDeclaration();
6203 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6204 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6205 GetLookAheadToken(1).is(tok::l_paren) &&
6206 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6207 GetLookAheadToken(3).is(tok::l_paren) &&
6208 GetLookAheadToken(4).is(tok::identifier) &&
6209 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6210 // HACK: We've got an exception-specification
6211 // noexcept(noexcept(swap(...)))
6212 // or
6213 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6214 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6215 // for 'swap' will only find the function we're currently declaring,
6216 // whereas it expects to find a non-member swap through ADL. Turn off
6217 // delayed parsing to give it a chance to find what it expects.
6218 Delayed = false;
6219 }
Richard Smith0b3a4622014-11-13 20:01:57 +00006220 ESpecType = tryParseExceptionSpecification(Delayed,
6221 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00006222 DynamicExceptions,
6223 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00006224 NoexceptExpr,
6225 ExceptionSpecTokens);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006226 if (ESpecType != EST_None)
6227 EndLoc = ESpecRange.getEnd();
6228
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006229 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6230 // after the exception-specification.
Richard Smith89645bc2013-01-02 12:01:23 +00006231 MaybeParseCXX11Attributes(FnAttrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006232
Douglas Gregor9e66af42011-07-05 16:44:18 +00006233 // Parse trailing-return-type[opt].
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006234 LocalEndLoc = EndLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006235 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00006236 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
Faisal Vali090da2d2018-01-01 18:23:28 +00006237 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006238 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006239 LocalEndLoc = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00006240 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00006241 TrailingReturnType =
6242 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006243 EndLoc = Range.getEnd();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006244 }
Aaron Ballman606093a2017-10-15 15:01:42 +00006245 } else if (standardAttributesAllowed()) {
6246 MaybeParseCXX11Attributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006247 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006248 }
6249
Reid Kleckner078aea92016-12-09 17:14:05 +00006250 // Collect non-parameter declarations from the prototype if this is a function
6251 // declaration. They will be moved into the scope of the function. Only do
6252 // this in C and not C++, where the decls will continue to live in the
6253 // surrounding context.
6254 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6255 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6256 !getLangOpts().CPlusPlus) {
6257 for (Decl *D : getCurScope()->decls()) {
6258 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6259 if (!ND || isa<ParmVarDecl>(ND))
6260 continue;
6261 DeclsInPrototype.push_back(ND);
6262 }
6263 }
6264
Douglas Gregor9e66af42011-07-05 16:44:18 +00006265 // Remember that we parsed a function type, and remember the attributes.
Erich Keanec480f302018-07-12 21:09:05 +00006266 D.AddTypeInfo(DeclaratorChunk::getFunction(
6267 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6268 ParamInfo.size(), EllipsisLoc, RParenLoc,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00006269 RefQualifierIsLValueRef, RefQualifierLoc,
6270 /*MutableLoc=*/SourceLocation(),
6271 ESpecType, ESpecRange, DynamicExceptions.data(),
6272 DynamicExceptionRanges.data(), DynamicExceptions.size(),
Erich Keanec480f302018-07-12 21:09:05 +00006273 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6274 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00006275 LocalEndLoc, D, TrailingReturnType, &DS),
Erich Keanec480f302018-07-12 21:09:05 +00006276 std::move(FnAttrs), EndLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006277}
6278
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006279/// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6280/// true if a ref-qualifier is found.
6281bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6282 SourceLocation &RefQualifierLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00006283 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006284 Diag(Tok, getLangOpts().CPlusPlus11 ?
6285 diag::warn_cxx98_compat_ref_qualifier :
6286 diag::ext_ref_qualifier);
6287
6288 RefQualifierIsLValueRef = Tok.is(tok::amp);
6289 RefQualifierLoc = ConsumeToken();
6290 return true;
6291 }
6292 return false;
6293}
6294
Douglas Gregor9e66af42011-07-05 16:44:18 +00006295/// isFunctionDeclaratorIdentifierList - This parameter list may have an
6296/// identifier list form for a K&R-style function: void foo(a,b,c)
6297///
6298/// Note that identifier-lists are only allowed for normal declarators, not for
6299/// abstract-declarators.
6300bool Parser::isFunctionDeclaratorIdentifierList() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006301 return !getLangOpts().CPlusPlus
Douglas Gregor9e66af42011-07-05 16:44:18 +00006302 && Tok.is(tok::identifier)
6303 && !TryAltiVecVectorToken()
6304 // K&R identifier lists can't have typedefs as identifiers, per C99
6305 // 6.7.5.3p11.
6306 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6307 // Identifier lists follow a really simple grammar: the identifiers can
6308 // be followed *only* by a ", identifier" or ")". However, K&R
6309 // identifier lists are really rare in the brave new modern world, and
6310 // it is very common for someone to typo a type in a non-K&R style
6311 // list. If we are presented with something like: "void foo(intptr x,
6312 // float y)", we don't want to start parsing the function declarator as
6313 // though it is a K&R style declarator just because intptr is an
6314 // invalid type.
6315 //
6316 // To handle this, we check to see if the token after the first
6317 // identifier is a "," or ")". Only then do we parse it as an
6318 // identifier list.
Bruno Cardoso Lopes218c8742016-09-13 20:04:35 +00006319 && (!Tok.is(tok::eof) &&
6320 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006321}
6322
6323/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6324/// we found a K&R-style identifier list instead of a typed parameter list.
6325///
6326/// After returning, ParamInfo will hold the parsed parameters.
6327///
6328/// identifier-list: [C99 6.7.5]
6329/// identifier
6330/// identifier-list ',' identifier
6331///
6332void Parser::ParseFunctionDeclaratorIdentifierList(
6333 Declarator &D,
Craig Topper5603df42013-07-05 19:34:19 +00006334 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006335 // If there was no identifier specified for the declarator, either we are in
6336 // an abstract-declarator, or we are in a parameter declarator which was found
6337 // to be abstract. In abstract-declarators, identifier lists are not valid:
6338 // diagnose this.
6339 if (!D.getIdentifier())
6340 Diag(Tok, diag::ext_ident_list_in_param);
6341
6342 // Maintain an efficient lookup of params we have seen so far.
6343 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6344
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006345 do {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006346 // If this isn't an identifier, report the error and skip until ')'.
6347 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00006348 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00006349 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006350 // Forget we parsed anything.
6351 ParamInfo.clear();
6352 return;
6353 }
6354
6355 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6356
6357 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6358 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6359 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6360
6361 // Verify that the argument identifier has not already been mentioned.
David Blaikie82e95a32014-11-19 07:49:47 +00006362 if (!ParamsSoFar.insert(ParmII).second) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006363 Diag(Tok, diag::err_param_redefinition) << ParmII;
6364 } else {
6365 // Remember this identifier in ParamInfo.
6366 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6367 Tok.getLocation(),
Craig Topper161e4db2014-05-21 06:02:52 +00006368 nullptr));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006369 }
6370
6371 // Eat the identifier.
6372 ConsumeToken();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006373 // The list continues if we see a comma.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006374 } while (TryConsumeToken(tok::comma));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006375}
6376
6377/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6378/// after the opening parenthesis. This function will not parse a K&R-style
6379/// identifier list.
6380///
Richard Smith2620cd92012-04-11 04:01:28 +00006381/// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6382/// caller parsed those arguments immediately after the open paren - they should
6383/// be considered to be part of the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006384///
6385/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6386/// be the location of the ellipsis, if any was parsed.
6387///
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006388/// parameter-type-list: [C99 6.7.5]
6389/// parameter-list
6390/// parameter-list ',' '...'
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006391/// [C++] parameter-list '...'
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006392///
6393/// parameter-list: [C99 6.7.5]
6394/// parameter-declaration
6395/// parameter-list ',' parameter-declaration
6396///
6397/// parameter-declaration: [C99 6.7.5]
6398/// declaration-specifiers declarator
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006399/// [C++] declaration-specifiers declarator '=' assignment-expression
Sebastian Redldb63af22012-03-14 15:54:00 +00006400/// [C++11] initializer-clause
Chris Lattnere37e2332006-08-15 04:50:22 +00006401/// [GNU] declaration-specifiers declarator attributes
Sebastian Redlf769df52009-03-24 22:27:57 +00006402/// declaration-specifiers abstract-declarator[opt]
6403/// [C++] declaration-specifiers abstract-declarator[opt]
Chris Lattner58258242008-04-10 02:22:51 +00006404/// '=' assignment-expression
Chris Lattnere37e2332006-08-15 04:50:22 +00006405/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
Richard Smith2620cd92012-04-11 04:01:28 +00006406/// [C++11] attribute-specifier-seq parameter-declaration
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006407///
Douglas Gregor9e66af42011-07-05 16:44:18 +00006408void Parser::ParseParameterDeclarationClause(
6409 Declarator &D,
Richard Smith2620cd92012-04-11 04:01:28 +00006410 ParsedAttributes &FirstArgAttrs,
Craig Topper5603df42013-07-05 19:34:19 +00006411 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006412 SourceLocation &EllipsisLoc) {
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006413 do {
6414 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6415 // before deciding this was a parameter-declaration-clause.
6416 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Chris Lattner371ed4e2008-04-06 06:57:35 +00006417 break;
Mike Stump11289f42009-09-09 15:08:12 +00006418
Chris Lattner371ed4e2008-04-06 06:57:35 +00006419 // Parse the declaration-specifiers.
John McCall28a6aea2009-11-04 02:18:39 +00006420 // Just use the ParsingDeclaration "scope" of the declarator.
John McCall084e83d2011-03-24 11:26:52 +00006421 DeclSpec DS(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006422
Richard Smith2620cd92012-04-11 04:01:28 +00006423 // Parse any C++11 attributes.
Richard Smith89645bc2013-01-02 12:01:23 +00006424 MaybeParseCXX11Attributes(DS.getAttributes());
Richard Smith2620cd92012-04-11 04:01:28 +00006425
John McCall53fa7142010-12-24 02:08:15 +00006426 // Skip any Microsoft attributes before a param.
Chad Rosierf8a2e702012-12-20 20:37:53 +00006427 MaybeParseMicrosoftAttributes(DS.getAttributes());
John McCall53fa7142010-12-24 02:08:15 +00006428
6429 SourceLocation DSStart = Tok.getLocation();
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006430
6431 // If the caller parsed attributes for the first argument, add them now.
John McCall53fa7142010-12-24 02:08:15 +00006432 // Take them so that we only apply the attributes to the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006433 // FIXME: If we can leave the attributes in the token stream somehow, we can
Richard Smith2620cd92012-04-11 04:01:28 +00006434 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6435 // too much hassle.
6436 DS.takeAttributesFrom(FirstArgAttrs);
John McCall53fa7142010-12-24 02:08:15 +00006437
Faisal Valia534f072018-04-26 00:42:40 +00006438 ParseDeclarationSpecifiers(DS);
Mike Stump11289f42009-09-09 15:08:12 +00006439
Faisal Vali2b391ab2013-09-26 19:54:12 +00006440
Fangrui Song6907ce22018-07-30 19:24:48 +00006441 // Parse the declarator. This is "PrototypeContext" or
6442 // "LambdaExprParameterContext", because we must accept either
Faisal Vali2b391ab2013-09-26 19:54:12 +00006443 // 'declarator' or 'abstract-declarator' here.
Faisal Vali421b2d12017-12-29 05:41:00 +00006444 Declarator ParmDeclarator(
6445 DS, D.getContext() == DeclaratorContext::LambdaExprContext
6446 ? DeclaratorContext::LambdaExprParameterContext
6447 : DeclaratorContext::PrototypeContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00006448 ParseDeclarator(ParmDeclarator);
Chris Lattner371ed4e2008-04-06 06:57:35 +00006449
6450 // Parse GNU attributes, if present.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006451 MaybeParseGNUAttributes(ParmDeclarator);
Mike Stump11289f42009-09-09 15:08:12 +00006452
Chris Lattner371ed4e2008-04-06 06:57:35 +00006453 // Remember this parsed parameter in ParamInfo.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006454 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
Mike Stump11289f42009-09-09 15:08:12 +00006455
Douglas Gregor4d87df52008-12-16 21:30:33 +00006456 // DefArgToks is used when the parsing of default arguments needs
6457 // to be delayed.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006458 std::unique_ptr<CachedTokens> DefArgToks;
Douglas Gregor4d87df52008-12-16 21:30:33 +00006459
Chris Lattner371ed4e2008-04-06 06:57:35 +00006460 // If no parameter was specified, verify that *something* was specified,
6461 // otherwise we have a missing type and identifier.
Craig Topper161e4db2014-05-21 06:02:52 +00006462 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
Faisal Vali2b391ab2013-09-26 19:54:12 +00006463 ParmDeclarator.getNumTypeObjects() == 0) {
Chris Lattner371ed4e2008-04-06 06:57:35 +00006464 // Completely missing, emit error.
6465 Diag(DSStart, diag::err_missing_param);
6466 } else {
6467 // Otherwise, we have something. Add it and let semantic analysis try
6468 // to grok it and add the result to the ParamInfo we are building.
Mike Stump11289f42009-09-09 15:08:12 +00006469
Richard Smith36ee9fb2014-08-11 23:30:23 +00006470 // Last chance to recover from a misplaced ellipsis in an attempted
6471 // parameter pack declaration.
6472 if (Tok.is(tok::ellipsis) &&
6473 (NextToken().isNot(tok::r_paren) ||
6474 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6475 !Actions.isUnexpandedParameterPackPermitted())) &&
6476 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6477 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6478
Chris Lattner371ed4e2008-04-06 06:57:35 +00006479 // Inform the actions module about the parameter declarator, so it gets
6480 // added to the current scope.
Richard Smith95e1fb02014-08-27 03:23:12 +00006481 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006482 // Parse the default argument, if any. We parse the default
6483 // arguments in all dialects; the semantic analysis in
6484 // ActOnParamDefaultArgument will reject the default argument in
6485 // C.
6486 if (Tok.is(tok::equal)) {
Douglas Gregor58354032008-12-24 00:01:03 +00006487 SourceLocation EqualLoc = Tok.getLocation();
6488
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006489 // Parse the default argument
Faisal Vali421b2d12017-12-29 05:41:00 +00006490 if (D.getContext() == DeclaratorContext::MemberContext) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006491 // If we're inside a class definition, cache the tokens
6492 // corresponding to the default argument. We'll actually parse
6493 // them when we see the end of the class definition.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006494 DefArgToks.reset(new CachedTokens);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006495
David Majnemer906ed272015-01-13 05:28:24 +00006496 SourceLocation ArgStartLoc = NextToken().getLocation();
Richard Smith1fff95c2013-09-12 23:28:08 +00006497 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006498 DefArgToks.reset();
Serge Pavlovb4b35782014-07-22 01:54:49 +00006499 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006500 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006501 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
David Majnemer906ed272015-01-13 05:28:24 +00006502 ArgStartLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006503 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006504 } else {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006505 // Consume the '='.
Douglas Gregor58354032008-12-24 00:01:03 +00006506 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00006507
Chad Rosierc1183952012-06-26 22:30:43 +00006508 // The argument isn't actually potentially evaluated unless it is
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006509 // used.
Faisal Valid143a0c2017-04-01 21:30:49 +00006510 EnterExpressionEvaluationContext Eval(
6511 Actions,
6512 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6513 Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006514
Sebastian Redldb63af22012-03-14 15:54:00 +00006515 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006516 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006517 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +00006518 DefArgResult = ParseBraceInitializer();
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006519 } else
Sebastian Redldb63af22012-03-14 15:54:00 +00006520 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +00006521 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006522 if (DefArgResult.isInvalid()) {
Serge Pavlovb4b35782014-07-22 01:54:49 +00006523 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Alexey Bataevee6507d2013-11-18 08:17:37 +00006524 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006525 } else {
6526 // Inform the actions module about the default argument
6527 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006528 DefArgResult.get());
Douglas Gregor4d87df52008-12-16 21:30:33 +00006529 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006530 }
6531 }
Mike Stump11289f42009-09-09 15:08:12 +00006532
6533 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
Fangrui Song6907ce22018-07-30 19:24:48 +00006534 ParmDeclarator.getIdentifierLoc(),
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006535 Param, std::move(DefArgToks)));
Chris Lattner371ed4e2008-04-06 06:57:35 +00006536 }
6537
Richard Smith36ee9fb2014-08-11 23:30:23 +00006538 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6539 if (!getLangOpts().CPlusPlus) {
6540 // We have ellipsis without a preceding ',', which is ill-formed
6541 // in C. Complain and provide the fix.
6542 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6543 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6544 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6545 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6546 // It looks like this was supposed to be a parameter pack. Warn and
6547 // point out where the ellipsis should have gone.
6548 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6549 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6550 << ParmEllipsis.isValid() << ParmEllipsis;
6551 if (ParmEllipsis.isValid()) {
6552 Diag(ParmEllipsis,
6553 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6554 } else {
6555 Diag(ParmDeclarator.getIdentifierLoc(),
6556 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6557 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6558 "...")
6559 << !ParmDeclarator.hasName();
6560 }
6561 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006562 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
Richard Smith36ee9fb2014-08-11 23:30:23 +00006563 }
6564
6565 // We can't have any more parameters after an ellipsis.
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006566 break;
6567 }
Mike Stump11289f42009-09-09 15:08:12 +00006568
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006569 // If the next token is a comma, consume it and keep reading arguments.
6570 } while (TryConsumeToken(tok::comma));
Chris Lattner6c940e62008-04-06 06:34:08 +00006571}
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006572
Chris Lattnere8074e62006-08-06 18:30:15 +00006573/// [C90] direct-declarator '[' constant-expression[opt] ']'
6574/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6575/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6576/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6577/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006578/// [C++11] direct-declarator '[' constant-expression[opt] ']'
6579/// attribute-specifier-seq[opt]
Chris Lattnere8074e62006-08-06 18:30:15 +00006580void Parser::ParseBracketDeclarator(Declarator &D) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006581 if (CheckProhibitedCXX11Attribute())
6582 return;
6583
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006584 BalancedDelimiterTracker T(*this, tok::l_square);
6585 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00006586
Chris Lattner84a11622008-12-18 07:27:21 +00006587 // C array syntax has many features, but by-far the most common is [] and [4].
6588 // This code does a fast path to handle some of the most obvious cases.
6589 if (Tok.getKind() == tok::r_square) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006590 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006591 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006592 MaybeParseCXX11Attributes(attrs);
Chad Rosierc1183952012-06-26 22:30:43 +00006593
Chris Lattner84a11622008-12-18 07:27:21 +00006594 // Remember that we parsed the empty array type.
Craig Topper161e4db2014-05-21 06:02:52 +00006595 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006596 T.getOpenLocation(),
6597 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006598 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006599 return;
6600 } else if (Tok.getKind() == tok::numeric_constant &&
6601 GetLookAheadToken(1).is(tok::r_square)) {
6602 // [4] is very common. Parse the numeric constant expression.
Richard Smithbcc22fc2012-03-09 08:00:36 +00006603 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
Chris Lattner84a11622008-12-18 07:27:21 +00006604 ConsumeToken();
6605
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006606 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006607 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006608 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006609
Chris Lattner84a11622008-12-18 07:27:21 +00006610 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006611 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006612 T.getOpenLocation(),
6613 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006614 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006615 return;
Benjamin Kramer72dae622016-02-18 15:30:24 +00006616 } else if (Tok.getKind() == tok::code_completion) {
6617 Actions.CodeCompleteBracketDeclarator(getCurScope());
6618 return cutOffParsing();
Chris Lattner84a11622008-12-18 07:27:21 +00006619 }
Mike Stump11289f42009-09-09 15:08:12 +00006620
Chris Lattnere8074e62006-08-06 18:30:15 +00006621 // If valid, this location is the position where we read the 'static' keyword.
6622 SourceLocation StaticLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006623 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006624
Chris Lattnere8074e62006-08-06 18:30:15 +00006625 // If there is a type-qualifier-list, read it now.
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006626 // Type qualifiers in an array subscript are a C99 feature.
John McCall084e83d2011-03-24 11:26:52 +00006627 DeclSpec DS(AttrFactory);
Aaron Ballman08b06592014-07-22 12:44:22 +00006628 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
Mike Stump11289f42009-09-09 15:08:12 +00006629
Chris Lattnere8074e62006-08-06 18:30:15 +00006630 // If we haven't already read 'static', check to see if there is one after the
6631 // type-qualifier-list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006632 if (!StaticLoc.isValid())
6633 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006634
Chris Lattnere8074e62006-08-06 18:30:15 +00006635 // Handle "direct-declarator [ type-qual-list[opt] * ]".
Chris Lattnere8074e62006-08-06 18:30:15 +00006636 bool isStar = false;
John McCalldadc5752010-08-24 06:29:42 +00006637 ExprResult NumElements;
Mike Stump11289f42009-09-09 15:08:12 +00006638
Chris Lattner521ff2b2008-04-06 05:26:30 +00006639 // Handle the case where we have '[*]' as the array size. However, a leading
6640 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
Sylvestre Ledru830885c2012-07-23 08:59:39 +00006641 // the token after the star is a ']'. Since stars in arrays are
Chris Lattner521ff2b2008-04-06 05:26:30 +00006642 // infrequent, use of lookahead is not costly here.
6643 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
Chris Lattnerc439f0d2008-04-06 05:27:21 +00006644 ConsumeToken(); // Eat the '*'.
Chris Lattner1906f802006-08-06 19:14:46 +00006645
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006646 if (StaticLoc.isValid()) {
Chris Lattner521ff2b2008-04-06 05:26:30 +00006647 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006648 StaticLoc = SourceLocation(); // Drop the static.
6649 }
Chris Lattner521ff2b2008-04-06 05:26:30 +00006650 isStar = true;
Chris Lattner76c72282007-10-09 17:33:22 +00006651 } else if (Tok.isNot(tok::r_square)) {
Chris Lattner84a11622008-12-18 07:27:21 +00006652 // Note, in C89, this production uses the constant-expr production instead
6653 // of assignment-expr. The only difference is that assignment-expr allows
6654 // things like '=' and '*='. Sema rejects these in C89 mode because they
6655 // are not i-c-e's, so we don't need to distinguish between the two here.
Mike Stump11289f42009-09-09 15:08:12 +00006656
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006657 // Parse the constant-expression or assignment-expression now (depending
6658 // on dialect).
David Blaikiebbafb8a2012-03-11 07:00:24 +00006659 if (getLangOpts().CPlusPlus) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006660 NumElements = ParseConstantExpression();
Eli Friedmane0afc982012-01-21 01:01:51 +00006661 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00006662 EnterExpressionEvaluationContext Unevaluated(
6663 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Kaelyn Takata15867822014-11-21 18:48:04 +00006664 NumElements =
6665 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Eli Friedmane0afc982012-01-21 01:01:51 +00006666 }
David Majnemerf9834d52014-08-08 07:21:18 +00006667 } else {
6668 if (StaticLoc.isValid()) {
6669 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6670 StaticLoc = SourceLocation(); // Drop the static.
6671 }
Chris Lattner62591722006-08-12 18:40:58 +00006672 }
Mike Stump11289f42009-09-09 15:08:12 +00006673
Chris Lattner62591722006-08-12 18:40:58 +00006674 // If there was an error parsing the assignment-expression, recover.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00006675 if (NumElements.isInvalid()) {
Chris Lattnercd2a8c52009-04-24 22:30:50 +00006676 D.setInvalidType(true);
Chris Lattner62591722006-08-12 18:40:58 +00006677 // If the expression was invalid, skip it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00006678 SkipUntil(tok::r_square, StopAtSemi);
Chris Lattner62591722006-08-12 18:40:58 +00006679 return;
Chris Lattnere8074e62006-08-06 18:30:15 +00006680 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006681
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006682 T.consumeClose();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006683
Jordan Rose303e2f12016-11-10 23:28:17 +00006684 MaybeParseCXX11Attributes(DS.getAttributes());
Alexis Hunt96d5c762009-11-21 08:43:09 +00006685
Chris Lattner84a11622008-12-18 07:27:21 +00006686 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006687 D.AddTypeInfo(
6688 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6689 isStar, NumElements.get(), T.getOpenLocation(),
6690 T.getCloseLocation()),
6691 std::move(DS.getAttributes()), T.getCloseLocation());
Chris Lattnere8074e62006-08-06 18:30:15 +00006692}
6693
Richard Trieuf4b81d02014-06-24 23:14:24 +00006694/// Diagnose brackets before an identifier.
6695void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6696 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6697 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6698
6699 SourceLocation StartBracketLoc = Tok.getLocation();
6700 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6701
6702 while (Tok.is(tok::l_square)) {
6703 ParseBracketDeclarator(TempDeclarator);
6704 }
6705
6706 // Stuff the location of the start of the brackets into the Declarator.
6707 // The diagnostics from ParseDirectDeclarator will make more sense if
6708 // they use this location instead.
6709 if (Tok.is(tok::semi))
6710 D.getName().EndLocation = StartBracketLoc;
6711
6712 SourceLocation SuggestParenLoc = Tok.getLocation();
6713
6714 // Now that the brackets are removed, try parsing the declarator again.
6715 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6716
6717 // Something went wrong parsing the brackets, in which case,
6718 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6719 // one here.
6720 if (TempDeclarator.getNumTypeObjects() == 0)
6721 return;
6722
6723 // Determine if parens will need to be suggested in the diagnostic.
6724 bool NeedParens = false;
6725 if (D.getNumTypeObjects() != 0) {
6726 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6727 case DeclaratorChunk::Pointer:
6728 case DeclaratorChunk::Reference:
6729 case DeclaratorChunk::BlockPointer:
6730 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00006731 case DeclaratorChunk::Pipe:
Richard Trieuf4b81d02014-06-24 23:14:24 +00006732 NeedParens = true;
6733 break;
6734 case DeclaratorChunk::Array:
6735 case DeclaratorChunk::Function:
6736 case DeclaratorChunk::Paren:
6737 break;
6738 }
6739 }
6740
6741 if (NeedParens) {
6742 // Create a DeclaratorChunk for the inserted parens.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006743 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Erich Keanec480f302018-07-12 21:09:05 +00006744 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
Richard Trieuf4b81d02014-06-24 23:14:24 +00006745 SourceLocation());
6746 }
6747
6748 // Adding back the bracket info to the end of the Declarator.
6749 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6750 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
Erich Keanec480f302018-07-12 21:09:05 +00006751 D.AddTypeInfo(Chunk, SourceLocation());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006752 }
6753
6754 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6755 // If parentheses are required, always suggest them.
6756 if (!D.getIdentifier() && !NeedParens)
6757 return;
6758
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006759 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
Richard Trieuf4b81d02014-06-24 23:14:24 +00006760
6761 // Generate the move bracket error message.
6762 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006763 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006764
6765 if (NeedParens) {
6766 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6767 << getLangOpts().CPlusPlus
6768 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6769 << FixItHint::CreateInsertion(EndLoc, ")")
6770 << FixItHint::CreateInsertionFromRange(
6771 EndLoc, CharSourceRange(BracketRange, true))
6772 << FixItHint::CreateRemoval(BracketRange);
6773 } else {
6774 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6775 << getLangOpts().CPlusPlus
6776 << FixItHint::CreateInsertionFromRange(
6777 EndLoc, CharSourceRange(BracketRange, true))
6778 << FixItHint::CreateRemoval(BracketRange);
6779 }
6780}
6781
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006782/// [GNU] typeof-specifier:
6783/// typeof ( expressions )
6784/// typeof ( type-name )
6785/// [GNU/C++] typeof unary-expression
Steve Naroffad373bd2007-07-31 12:34:36 +00006786///
6787void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
Chris Lattner76c72282007-10-09 17:33:22 +00006788 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006789 Token OpTok = Tok;
Steve Naroffad373bd2007-07-31 12:34:36 +00006790 SourceLocation StartLoc = ConsumeToken();
6791
John McCalle8595032010-01-13 20:03:27 +00006792 const bool hasParens = Tok.is(tok::l_paren);
6793
Faisal Valid143a0c2017-04-01 21:30:49 +00006794 EnterExpressionEvaluationContext Unevaluated(
6795 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6796 Sema::ReuseLambdaContextDecl);
Eli Friedmane0afc982012-01-21 01:01:51 +00006797
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006798 bool isCastExpr;
John McCallba7bf592010-08-24 05:47:05 +00006799 ParsedType CastTy;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006800 SourceRange CastRange;
Kaelyn Takata911260742014-12-19 01:28:40 +00006801 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6802 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
John McCalle8595032010-01-13 20:03:27 +00006803 if (hasParens)
6804 DS.setTypeofParensRange(CastRange);
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006805
6806 if (CastRange.getEnd().isInvalid())
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006807 // FIXME: Not accurate, the range gets one token more than it should.
6808 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006809 else
6810 DS.SetRangeEnd(CastRange.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +00006811
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006812 if (isCastExpr) {
6813 if (!CastTy) {
6814 DS.SetTypeSpecError();
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006815 return;
Douglas Gregor220cac52009-02-18 17:45:20 +00006816 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006817
Craig Topper161e4db2014-05-21 06:02:52 +00006818 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006819 unsigned DiagID;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006820 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6821 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006822 DiagID, CastTy,
6823 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006824 Diag(StartLoc, DiagID) << PrevSpec;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006825 return;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006826 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006827
Hiroshi Inoue533777f2017-07-02 06:12:49 +00006828 // If we get here, the operand to the typeof was an expression.
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006829 if (Operand.isInvalid()) {
6830 DS.SetTypeSpecError();
Steve Naroff4bd2f712007-08-02 02:53:48 +00006831 return;
Steve Naroffad373bd2007-07-31 12:34:36 +00006832 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006833
Eli Friedmane0afc982012-01-21 01:01:51 +00006834 // We might need to transform the operand if it is potentially evaluated.
6835 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6836 if (Operand.isInvalid()) {
6837 DS.SetTypeSpecError();
6838 return;
6839 }
6840
Craig Topper161e4db2014-05-21 06:02:52 +00006841 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006842 unsigned DiagID;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006843 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6844 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006845 DiagID, Operand.get(),
6846 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006847 Diag(StartLoc, DiagID) << PrevSpec;
Steve Naroffad373bd2007-07-31 12:34:36 +00006848}
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006849
Benjamin Kramere56f3932011-12-23 17:00:35 +00006850/// [C11] atomic-specifier:
Eli Friedman0dfb8892011-10-06 23:00:33 +00006851/// _Atomic ( type-name )
6852///
6853void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
Richard Smith8e1ac332013-03-28 01:55:44 +00006854 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6855 "Not an atomic specifier");
Eli Friedman0dfb8892011-10-06 23:00:33 +00006856
6857 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006858 BalancedDelimiterTracker T(*this, tok::l_paren);
Richard Smith8e1ac332013-03-28 01:55:44 +00006859 if (T.consumeOpen())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006860 return;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006861
6862 TypeResult Result = ParseTypeName();
6863 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00006864 SkipUntil(tok::r_paren, StopAtSemi);
Eli Friedman0dfb8892011-10-06 23:00:33 +00006865 return;
6866 }
6867
6868 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006869 T.consumeClose();
Eli Friedman0dfb8892011-10-06 23:00:33 +00006870
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006871 if (T.getCloseLocation().isInvalid())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006872 return;
6873
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006874 DS.setTypeofParensRange(T.getRange());
6875 DS.SetRangeEnd(T.getCloseLocation());
Eli Friedman0dfb8892011-10-06 23:00:33 +00006876
Craig Topper161e4db2014-05-21 06:02:52 +00006877 const char *PrevSpec = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006878 unsigned DiagID;
6879 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006880 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006881 Actions.getASTContext().getPrintingPolicy()))
Eli Friedman0dfb8892011-10-06 23:00:33 +00006882 Diag(StartLoc, DiagID) << PrevSpec;
6883}
6884
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006885/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6886/// from TryAltiVecVectorToken.
6887bool Parser::TryAltiVecVectorTokenOutOfLine() {
6888 Token Next = NextToken();
6889 switch (Next.getKind()) {
6890 default: return false;
6891 case tok::kw_short:
6892 case tok::kw_long:
6893 case tok::kw_signed:
6894 case tok::kw_unsigned:
6895 case tok::kw_void:
6896 case tok::kw_char:
6897 case tok::kw_int:
6898 case tok::kw_float:
6899 case tok::kw_double:
6900 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006901 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006902 case tok::kw___pixel:
6903 Tok.setKind(tok::kw___vector);
6904 return true;
6905 case tok::identifier:
6906 if (Next.getIdentifierInfo() == Ident_pixel) {
6907 Tok.setKind(tok::kw___vector);
6908 return true;
6909 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006910 if (Next.getIdentifierInfo() == Ident_bool) {
6911 Tok.setKind(tok::kw___vector);
6912 return true;
6913 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006914 return false;
6915 }
6916}
6917
6918bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6919 const char *&PrevSpec, unsigned &DiagID,
6920 bool &isInvalid) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006921 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006922 if (Tok.getIdentifierInfo() == Ident_vector) {
6923 Token Next = NextToken();
6924 switch (Next.getKind()) {
6925 case tok::kw_short:
6926 case tok::kw_long:
6927 case tok::kw_signed:
6928 case tok::kw_unsigned:
6929 case tok::kw_void:
6930 case tok::kw_char:
6931 case tok::kw_int:
6932 case tok::kw_float:
6933 case tok::kw_double:
6934 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006935 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006936 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006937 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006938 return true;
6939 case tok::identifier:
6940 if (Next.getIdentifierInfo() == Ident_pixel) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006941 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006942 return true;
6943 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006944 if (Next.getIdentifierInfo() == Ident_bool) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006945 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00006946 return true;
6947 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006948 break;
6949 default:
6950 break;
6951 }
Douglas Gregor9938e3b2010-06-16 15:28:57 +00006952 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006953 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006954 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006955 return true;
Bill Schmidt99a084b2013-07-03 20:54:09 +00006956 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6957 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006958 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00006959 return true;
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006960 }
6961 return false;
6962}