blob: caf443de63e4623f8d4ee76f6c3e046591732f0e [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Declaration portions of the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000015#include "clang/Parse/RAIIObjectsForParser.h"
Erik Verbruggen888d52a2014-01-15 09:15:43 +000016#include "clang/AST/ASTContext.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000017#include "clang/AST/DeclTemplate.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000018#include "clang/AST/PrettyDeclStackTrace.h"
Benjamin Kramerd7d2b1f2012-12-01 16:35:25 +000019#include "clang/Basic/AddressSpaces.h"
Aaron Ballmanfdd783a2014-03-31 18:18:43 +000020#include "clang/Basic/Attributes.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000021#include "clang/Basic/CharInfo.h"
Aaron Ballmanfdd783a2014-03-31 18:18:43 +000022#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Parse/ParseDiagnostic.h"
Kaelyn Uhrain031643e2012-04-26 23:36:17 +000024#include "clang/Sema/Lookup.h"
John McCall8b0666c2010-08-20 18:27:03 +000025#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Scope.h"
Craig Topperabb83ae2015-11-14 19:31:56 +000027#include "clang/Sema/SemaDiagnostic.h"
George Burgess IVa19ea342016-11-10 20:43:52 +000028#include "llvm/ADT/Optional.h"
Chris Lattnerad9ac942007-01-23 01:14:52 +000029#include "llvm/ADT/SmallSet.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000030#include "llvm/ADT/SmallString.h"
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +000031#include "llvm/ADT/StringSwitch.h"
Hans Wennborgdcfba332015-10-06 23:40:43 +000032
Chris Lattnerc0acd3d2006-07-31 05:13:43 +000033using namespace clang;
34
35//===----------------------------------------------------------------------===//
36// C99 6.7: Declarations.
37//===----------------------------------------------------------------------===//
38
Chris Lattnerf5fbd792006-08-10 23:56:11 +000039/// ParseTypeName
40/// type-name: [C99 6.7.6]
41/// specifier-qualifier-list abstract-declarator[opt]
Sebastian Redlbd150f42008-11-21 19:14:01 +000042///
43/// Called type-id in C++.
Douglas Gregor205d5e32011-01-31 16:09:46 +000044TypeResult Parser::ParseTypeName(SourceRange *Range,
Faisal Vali421b2d12017-12-29 05:41:00 +000045 DeclaratorContext Context,
Richard Smithcd1c0552011-07-01 19:46:12 +000046 AccessSpecifier AS,
Richard Smith54ecd982013-02-20 19:22:51 +000047 Decl **OwnedType,
48 ParsedAttributes *Attrs) {
Richard Smith62dad822012-03-15 01:02:11 +000049 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
Faisal Vali7db85c52017-12-31 00:06:40 +000050 if (DSC == DeclSpecContext::DSC_normal)
51 DSC = DeclSpecContext::DSC_type_specifier;
Richard Smithbfdb1082012-03-12 08:56:40 +000052
Chris Lattnerf5fbd792006-08-10 23:56:11 +000053 // Parse the common declaration-specifiers piece.
John McCall084e83d2011-03-24 11:26:52 +000054 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +000055 if (Attrs)
Erich Keanec480f302018-07-12 21:09:05 +000056 DS.addAttributes(*Attrs);
Richard Smithbfdb1082012-03-12 08:56:40 +000057 ParseSpecifierQualifierList(DS, AS, DSC);
Richard Smithcd1c0552011-07-01 19:46:12 +000058 if (OwnedType)
Craig Topper161e4db2014-05-21 06:02:52 +000059 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
Sebastian Redld6434562009-05-29 18:02:33 +000060
Chris Lattnerf5fbd792006-08-10 23:56:11 +000061 // Parse the abstract-declarator, if present.
Douglas Gregor205d5e32011-01-31 16:09:46 +000062 Declarator DeclaratorInfo(DS, Context);
Chris Lattnerf5fbd792006-08-10 23:56:11 +000063 ParseDeclarator(DeclaratorInfo);
Sebastian Redld6434562009-05-29 18:02:33 +000064 if (Range)
65 *Range = DeclaratorInfo.getSourceRange();
66
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000067 if (DeclaratorInfo.isInvalidType())
Douglas Gregor220cac52009-02-18 17:45:20 +000068 return true;
69
Douglas Gregor0be31a22010-07-02 17:43:08 +000070 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Chris Lattnerf5fbd792006-08-10 23:56:11 +000071}
72
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000073/// Normalizes an attribute name by dropping prefixed and suffixed __.
George Burgess IV779af822017-06-30 22:33:24 +000074static StringRef normalizeAttrName(StringRef Name) {
75 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
76 return Name.drop_front(2).drop_back(2);
77 return Name;
78}
79
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000080/// isAttributeLateParsed - Return true if the attribute has arguments that
81/// require late parsing.
82static bool isAttributeLateParsed(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +000083#define CLANG_ATTR_LATE_PARSED_LIST
George Burgess IV779af822017-06-30 22:33:24 +000084 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +000085#include "clang/Parse/AttrParserStringSwitches.inc"
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000086 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +000087#undef CLANG_ATTR_LATE_PARSED_LIST
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000088}
89
Alexis Hunt96d5c762009-11-21 08:43:09 +000090/// ParseGNUAttributes - Parse a non-empty attributes list.
Chris Lattnerb8cd5c22006-08-15 04:10:46 +000091///
92/// [GNU] attributes:
93/// attribute
94/// attributes attribute
95///
96/// [GNU] attribute:
97/// '__attribute__' '(' '(' attribute-list ')' ')'
98///
99/// [GNU] attribute-list:
100/// attrib
101/// attribute_list ',' attrib
102///
103/// [GNU] attrib:
104/// empty
Steve Naroff0f2fe172007-06-01 17:11:19 +0000105/// attrib-name
106/// attrib-name '(' identifier ')'
107/// attrib-name '(' identifier ',' nonempty-expr-list ')'
108/// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
Chris Lattnerb8cd5c22006-08-15 04:10:46 +0000109///
Steve Naroff0f2fe172007-06-01 17:11:19 +0000110/// [GNU] attrib-name:
111/// identifier
112/// typespec
113/// typequal
114/// storageclass
Mike Stump11289f42009-09-09 15:08:12 +0000115///
Richard Smithf7ca0c02013-09-03 18:57:36 +0000116/// Whether an attribute takes an 'identifier' is determined by the
117/// attrib-name. GCC's behavior here is not worth imitating:
Steve Naroff0f2fe172007-06-01 17:11:19 +0000118///
Richard Smithf7ca0c02013-09-03 18:57:36 +0000119/// * In C mode, if the attribute argument list starts with an identifier
120/// followed by a ',' or an ')', and the identifier doesn't resolve to
121/// a type, it is parsed as an identifier. If the attribute actually
122/// wanted an expression, it's out of luck (but it turns out that no
123/// attributes work that way, because C constant expressions are very
124/// limited).
125/// * In C++ mode, if the attribute argument list starts with an identifier,
126/// and the attribute *wants* an identifier, it is parsed as an identifier.
127/// At block scope, any additional tokens between the identifier and the
128/// ',' or ')' are ignored, otherwise they produce a parse error.
Richard Smithb12bf692011-10-17 21:20:17 +0000129///
Richard Smithf7ca0c02013-09-03 18:57:36 +0000130/// We follow the C++ model, but don't allow junk after the identifier.
John McCall53fa7142010-12-24 02:08:15 +0000131void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000132 SourceLocation *endLoc,
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000133 LateParsedAttrList *LateAttrs,
134 Declarator *D) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000135 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
Mike Stump11289f42009-09-09 15:08:12 +0000136
Chris Lattner76c72282007-10-09 17:33:22 +0000137 while (Tok.is(tok::kw___attribute)) {
Steve Naroff0f2fe172007-06-01 17:11:19 +0000138 ConsumeToken();
139 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
140 "attribute")) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000141 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
John McCall53fa7142010-12-24 02:08:15 +0000142 return;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000143 }
144 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
Alexey Bataevee6507d2013-11-18 08:17:37 +0000145 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
John McCall53fa7142010-12-24 02:08:15 +0000146 return;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000147 }
148 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
Alp Toker094e5212014-01-05 03:27:11 +0000149 while (true) {
150 // Allow empty/non-empty attributes. ((__vector_size__(16),,,,))
151 if (TryConsumeToken(tok::comma))
Steve Naroff0f2fe172007-06-01 17:11:19 +0000152 continue;
Alp Toker094e5212014-01-05 03:27:11 +0000153
154 // Expect an identifier or declaration specifier (const, int, etc.)
David Majnemer22fe7712015-01-03 19:41:00 +0000155 if (Tok.isAnnotation())
156 break;
157 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
158 if (!AttrName)
Alp Toker094e5212014-01-05 03:27:11 +0000159 break;
160
Steve Naroff0f2fe172007-06-01 17:11:19 +0000161 SourceLocation AttrNameLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000162
Alp Toker094e5212014-01-05 03:27:11 +0000163 if (Tok.isNot(tok::l_paren)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000164 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000165 ParsedAttr::AS_GNU);
Alp Toker094e5212014-01-05 03:27:11 +0000166 continue;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000167 }
Alp Toker094e5212014-01-05 03:27:11 +0000168
169 // Handle "parameterized" attributes
170 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000171 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
Erich Keanee891aa92018-07-13 15:07:47 +0000172 SourceLocation(), ParsedAttr::AS_GNU, D);
Alp Toker094e5212014-01-05 03:27:11 +0000173 continue;
174 }
175
176 // Handle attributes with arguments that require late parsing.
177 LateParsedAttribute *LA =
178 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
179 LateAttrs->push_back(LA);
180
181 // Attributes in a class are parsed at the end of the class, along
182 // with other late-parsed declarations.
183 if (!ClassStack.empty() && !LateAttrs->parseSoon())
184 getCurrentClass().LateParsedDeclarations.push_back(LA);
185
George Burgess IVc8b95372017-01-04 22:43:01 +0000186 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
187 // recursively consumes balanced parens.
188 LA->Toks.push_back(Tok);
189 ConsumeParen();
190 // Consume everything up to and including the matching right parens.
191 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
Alp Toker094e5212014-01-05 03:27:11 +0000192
193 Token Eof;
194 Eof.startToken();
195 Eof.setLocation(Tok.getLocation());
196 LA->Toks.push_back(Eof);
Steve Naroff0f2fe172007-06-01 17:11:19 +0000197 }
Alp Toker094e5212014-01-05 03:27:11 +0000198
Alp Toker383d2c42014-01-01 03:08:43 +0000199 if (ExpectAndConsume(tok::r_paren))
Alexey Bataevee6507d2013-11-18 08:17:37 +0000200 SkipUntil(tok::r_paren, StopAtSemi);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000201 SourceLocation Loc = Tok.getLocation();
Alp Toker383d2c42014-01-01 03:08:43 +0000202 if (ExpectAndConsume(tok::r_paren))
Alexey Bataevee6507d2013-11-18 08:17:37 +0000203 SkipUntil(tok::r_paren, StopAtSemi);
John McCall53fa7142010-12-24 02:08:15 +0000204 if (endLoc)
205 *endLoc = Loc;
Steve Naroff0f2fe172007-06-01 17:11:19 +0000206 }
Steve Naroff0f2fe172007-06-01 17:11:19 +0000207}
Chris Lattnerf5fbd792006-08-10 23:56:11 +0000208
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000209/// Determine whether the given attribute has an identifier argument.
Aaron Ballman4768b312013-11-04 12:55:56 +0000210static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000211#define CLANG_ATTR_IDENTIFIER_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000212 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000213#include "clang/Parse/AttrParserStringSwitches.inc"
Douglas Gregord2472d42013-05-02 23:25:32 +0000214 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000215#undef CLANG_ATTR_IDENTIFIER_ARG_LIST
Douglas Gregord2472d42013-05-02 23:25:32 +0000216}
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000217
Erich Keane3efe0022018-07-20 14:13:28 +0000218/// Determine whether the given attribute has a variadic identifier argument.
219static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
220#define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
221 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
222#include "clang/Parse/AttrParserStringSwitches.inc"
223 .Default(false);
224#undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
225}
226
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000227/// Determine whether the given attribute parses a type argument.
Aaron Ballman4768b312013-11-04 12:55:56 +0000228static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000229#define CLANG_ATTR_TYPE_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000230 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000231#include "clang/Parse/AttrParserStringSwitches.inc"
Aaron Ballman4768b312013-11-04 12:55:56 +0000232 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000233#undef CLANG_ATTR_TYPE_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000234}
235
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000236/// Determine whether the given attribute requires parsing its arguments
Aaron Ballman15b27b92014-01-09 19:39:35 +0000237/// in an unevaluated context or not.
238static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000239#define CLANG_ATTR_ARG_CONTEXT_LIST
Aaron Ballman15b27b92014-01-09 19:39:35 +0000240 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000241#include "clang/Parse/AttrParserStringSwitches.inc"
Aaron Ballman15b27b92014-01-09 19:39:35 +0000242 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000243#undef CLANG_ATTR_ARG_CONTEXT_LIST
Aaron Ballman15b27b92014-01-09 19:39:35 +0000244}
245
Richard Smithfeefaf52013-09-03 18:01:40 +0000246IdentifierLoc *Parser::ParseIdentifierLoc() {
247 assert(Tok.is(tok::identifier) && "expected an identifier");
248 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
249 Tok.getLocation(),
250 Tok.getIdentifierInfo());
251 ConsumeToken();
252 return IL;
253}
254
Richard Smithb1f9a282013-10-31 01:56:18 +0000255void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
256 SourceLocation AttrNameLoc,
257 ParsedAttributes &Attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000258 SourceLocation *EndLoc,
259 IdentifierInfo *ScopeName,
260 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000261 ParsedAttr::Syntax Syntax) {
Richard Smithb1f9a282013-10-31 01:56:18 +0000262 BalancedDelimiterTracker Parens(*this, tok::l_paren);
263 Parens.consumeOpen();
264
265 TypeResult T;
266 if (Tok.isNot(tok::r_paren))
267 T = ParseTypeName();
268
269 if (Parens.consumeClose())
270 return;
271
272 if (T.isInvalid())
273 return;
274
275 if (T.isUsable())
276 Attrs.addNewTypeAttr(&AttrName,
Craig Topper161e4db2014-05-21 06:02:52 +0000277 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000278 ScopeName, ScopeLoc, T.get(), Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000279 else
280 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000281 ScopeName, ScopeLoc, nullptr, 0, Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000282}
283
Aaron Ballman35f94212014-04-14 16:03:22 +0000284unsigned Parser::ParseAttributeArgsCommon(
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000285 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
286 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +0000287 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000288 // Ignore the left paren location for now.
289 ConsumeParen();
290
291 ArgsVector ArgExprs;
292 if (Tok.is(tok::identifier)) {
293 // If this attribute wants an 'identifier' argument, make it so.
Erich Keane3efe0022018-07-20 14:13:28 +0000294 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
295 attributeHasVariadicIdentifierArg(*AttrName);
Erich Keanee891aa92018-07-13 15:07:47 +0000296 ParsedAttr::Kind AttrKind =
297 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000298
299 // If we don't know how to parse this attribute, but this is the only
300 // token in this argument, assume it's meant to be an identifier.
Erich Keanee891aa92018-07-13 15:07:47 +0000301 if (AttrKind == ParsedAttr::UnknownAttribute ||
302 AttrKind == ParsedAttr::IgnoredAttribute) {
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000303 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000304 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000305 }
306
307 if (IsIdentifierArg)
308 ArgExprs.push_back(ParseIdentifierLoc());
309 }
310
311 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
312 // Eat the comma.
313 if (!ArgExprs.empty())
314 ConsumeToken();
315
316 // Parse the non-empty comma-separated list of expressions.
317 do {
Erich Keane3efe0022018-07-20 14:13:28 +0000318 ExprResult ArgExpr;
319 if (Tok.is(tok::identifier) &&
320 attributeHasVariadicIdentifierArg(*AttrName)) {
321 ArgExprs.push_back(ParseIdentifierLoc());
322 } else {
323 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
324 EnterExpressionEvaluationContext Unevaluated(
325 Actions,
326 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
327 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000328
Erich Keane3efe0022018-07-20 14:13:28 +0000329 ExprResult ArgExpr(
330 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
331 if (ArgExpr.isInvalid()) {
332 SkipUntil(tok::r_paren, StopAtSemi);
333 return 0;
334 }
335 ArgExprs.push_back(ArgExpr.get());
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000336 }
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000337 // Eat the comma, move to the next argument
338 } while (TryConsumeToken(tok::comma));
339 }
340
341 SourceLocation RParen = Tok.getLocation();
342 if (!ExpectAndConsume(tok::r_paren)) {
343 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
344 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
345 ArgExprs.data(), ArgExprs.size(), Syntax);
346 }
347
348 if (EndLoc)
349 *EndLoc = RParen;
Aaron Ballman35f94212014-04-14 16:03:22 +0000350
351 return static_cast<unsigned>(ArgExprs.size());
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000352}
353
Michael Han23214e52012-10-03 01:56:22 +0000354/// Parse the arguments to a parameterized GNU attribute or
355/// a C++11 attribute in "gnu" namespace.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000356void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
357 SourceLocation AttrNameLoc,
358 ParsedAttributes &Attrs,
Michael Han23214e52012-10-03 01:56:22 +0000359 SourceLocation *EndLoc,
360 IdentifierInfo *ScopeName,
361 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000362 ParsedAttr::Syntax Syntax,
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000363 Declarator *D) {
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000364
365 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
366
Erich Keanee891aa92018-07-13 15:07:47 +0000367 ParsedAttr::Kind AttrKind =
368 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Richard Smith66e71682013-10-24 01:07:54 +0000369
Erich Keanee891aa92018-07-13 15:07:47 +0000370 if (AttrKind == ParsedAttr::AT_Availability) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000371 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
372 ScopeLoc, Syntax);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000373 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000374 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000375 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
376 ScopeName, ScopeLoc, Syntax);
377 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000378 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000379 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
380 ScopeName, ScopeLoc, Syntax);
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +0000381 return;
Erich Keanee891aa92018-07-13 15:07:47 +0000382 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000383 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
384 ScopeName, ScopeLoc, Syntax);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000385 return;
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000386 } else if (attributeIsTypeArgAttr(*AttrName)) {
387 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
388 ScopeLoc, Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000389 return;
390 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000391
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000392 // These may refer to the function arguments, but need to be parsed early to
393 // participate in determining whether it's a redeclaration.
George Burgess IVa19ea342016-11-10 20:43:52 +0000394 llvm::Optional<ParseScope> PrototypeScope;
Ulrich Weigandef5aa292015-07-13 14:13:01 +0000395 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
396 D && D->isFunctionDeclarator()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000397 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
George Burgess IVa19ea342016-11-10 20:43:52 +0000398 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
399 Scope::FunctionDeclarationScope |
400 Scope::DeclScope);
Alp Tokerc5350722014-02-26 22:27:52 +0000401 for (unsigned i = 0; i != FTI.NumParams; ++i) {
402 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000403 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
404 }
405 }
406
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000407 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
408 ScopeLoc, Syntax);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000409}
410
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000411unsigned Parser::ParseClangAttributeArgs(
412 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
413 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +0000414 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000415 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
416
Erich Keanee891aa92018-07-13 15:07:47 +0000417 ParsedAttr::Kind AttrKind =
418 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000419
Aaron Ballman38bbc162018-02-24 17:16:42 +0000420 switch (AttrKind) {
421 default:
422 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
423 ScopeName, ScopeLoc, Syntax);
Erich Keanee891aa92018-07-13 15:07:47 +0000424 case ParsedAttr::AT_ExternalSourceSymbol:
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000425 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
426 ScopeName, ScopeLoc, Syntax);
Aaron Ballman38bbc162018-02-24 17:16:42 +0000427 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000428 case ParsedAttr::AT_Availability:
Aaron Ballman38bbc162018-02-24 17:16:42 +0000429 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
430 ScopeLoc, Syntax);
431 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000432 case ParsedAttr::AT_ObjCBridgeRelated:
Aaron Ballmanc248b0f2018-02-24 17:37:37 +0000433 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
434 ScopeName, ScopeLoc, Syntax);
435 break;
Erich Keanee891aa92018-07-13 15:07:47 +0000436 case ParsedAttr::AT_TypeTagForDatatype:
Aaron Ballmana26d8ee2018-02-25 14:01:04 +0000437 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
438 ScopeName, ScopeLoc, Syntax);
439 break;
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000440 }
Erich Keanec480f302018-07-12 21:09:05 +0000441 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000442}
443
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000444bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
445 SourceLocation AttrNameLoc,
446 ParsedAttributes &Attrs) {
447 // If the attribute isn't known, we will not attempt to parse any
448 // arguments.
449 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
Bob Wilson7c730832015-07-20 22:57:31 +0000450 getTargetInfo(), getLangOpts())) {
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000451 // Eat the left paren, then skip to the ending right paren.
452 ConsumeParen();
453 SkipUntil(tok::r_paren);
454 return false;
Aaron Ballman478faed2012-06-19 22:09:27 +0000455 }
Aaron Ballman478faed2012-06-19 22:09:27 +0000456
Aaron Ballman95d57032014-04-14 16:44:26 +0000457 SourceLocation OpenParenLoc = Tok.getLocation();
458
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000459 if (AttrName->getName() == "property") {
Aaron Ballman478faed2012-06-19 22:09:27 +0000460 // The property declspec is more complex in that it can take one or two
Chad Rosierc1183952012-06-26 22:30:43 +0000461 // assignment expressions as a parameter, but the lhs of the assignment
Aaron Ballman478faed2012-06-19 22:09:27 +0000462 // must be named get or put.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000463
John McCall5e77d762013-04-16 07:28:30 +0000464 BalancedDelimiterTracker T(*this, tok::l_paren);
465 T.expectAndConsume(diag::err_expected_lparen_after,
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000466 AttrName->getNameStart(), tok::r_paren);
John McCall5e77d762013-04-16 07:28:30 +0000467
468 enum AccessorKind {
469 AK_Invalid = -1,
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000470 AK_Put = 0,
471 AK_Get = 1 // indices into AccessorNames
John McCall5e77d762013-04-16 07:28:30 +0000472 };
Craig Topper161e4db2014-05-21 06:02:52 +0000473 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
John McCall5e77d762013-04-16 07:28:30 +0000474 bool HasInvalidAccessor = false;
475
476 // Parse the accessor specifications.
477 while (true) {
478 // Stop if this doesn't look like an accessor spec.
479 if (!Tok.is(tok::identifier)) {
480 // If the user wrote a completely empty list, use a special diagnostic.
481 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
Craig Topper161e4db2014-05-21 06:02:52 +0000482 AccessorNames[AK_Put] == nullptr &&
483 AccessorNames[AK_Get] == nullptr) {
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000484 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
John McCall5e77d762013-04-16 07:28:30 +0000485 break;
486 }
487
488 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
489 break;
490 }
491
492 AccessorKind Kind;
493 SourceLocation KindLoc = Tok.getLocation();
494 StringRef KindStr = Tok.getIdentifierInfo()->getName();
495 if (KindStr == "get") {
496 Kind = AK_Get;
497 } else if (KindStr == "put") {
498 Kind = AK_Put;
499
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000500 // Recover from the common mistake of using 'set' instead of 'put'.
John McCall5e77d762013-04-16 07:28:30 +0000501 } else if (KindStr == "set") {
502 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000503 << FixItHint::CreateReplacement(KindLoc, "put");
John McCall5e77d762013-04-16 07:28:30 +0000504 Kind = AK_Put;
505
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000506 // Handle the mistake of forgetting the accessor kind by skipping
507 // this accessor.
John McCall5e77d762013-04-16 07:28:30 +0000508 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
509 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
510 ConsumeToken();
511 HasInvalidAccessor = true;
512 goto next_property_accessor;
513
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000514 // Otherwise, complain about the unknown accessor kind.
John McCall5e77d762013-04-16 07:28:30 +0000515 } else {
516 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
517 HasInvalidAccessor = true;
518 Kind = AK_Invalid;
519
520 // Try to keep parsing unless it doesn't look like an accessor spec.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000521 if (!NextToken().is(tok::equal))
522 break;
John McCall5e77d762013-04-16 07:28:30 +0000523 }
524
525 // Consume the identifier.
526 ConsumeToken();
527
528 // Consume the '='.
Alp Toker8fbec672013-12-17 23:29:36 +0000529 if (!TryConsumeToken(tok::equal)) {
John McCall5e77d762013-04-16 07:28:30 +0000530 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000531 << KindStr;
John McCall5e77d762013-04-16 07:28:30 +0000532 break;
533 }
534
535 // Expect the method name.
536 if (!Tok.is(tok::identifier)) {
537 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
538 break;
539 }
540
541 if (Kind == AK_Invalid) {
542 // Just drop invalid accessors.
Craig Topper161e4db2014-05-21 06:02:52 +0000543 } else if (AccessorNames[Kind] != nullptr) {
John McCall5e77d762013-04-16 07:28:30 +0000544 // Complain about the repeated accessor, ignore it, and keep parsing.
545 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
546 } else {
547 AccessorNames[Kind] = Tok.getIdentifierInfo();
548 }
549 ConsumeToken();
550
551 next_property_accessor:
552 // Keep processing accessors until we run out.
Alp Toker094e5212014-01-05 03:27:11 +0000553 if (TryConsumeToken(tok::comma))
John McCall5e77d762013-04-16 07:28:30 +0000554 continue;
555
556 // If we run into the ')', stop without consuming it.
Alp Toker094e5212014-01-05 03:27:11 +0000557 if (Tok.is(tok::r_paren))
John McCall5e77d762013-04-16 07:28:30 +0000558 break;
Alp Toker094e5212014-01-05 03:27:11 +0000559
560 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
561 break;
John McCall5e77d762013-04-16 07:28:30 +0000562 }
563
564 // Only add the property attribute if it was well-formed.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000565 if (!HasInvalidAccessor)
Craig Topper161e4db2014-05-21 06:02:52 +0000566 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
John McCall5e77d762013-04-16 07:28:30 +0000567 AccessorNames[AK_Get], AccessorNames[AK_Put],
Erich Keanee891aa92018-07-13 15:07:47 +0000568 ParsedAttr::AS_Declspec);
Aaron Ballman478faed2012-06-19 22:09:27 +0000569 T.skipToEnd();
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000570 return !HasInvalidAccessor;
Aaron Ballman478faed2012-06-19 22:09:27 +0000571 }
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000572
Aaron Ballman95d57032014-04-14 16:44:26 +0000573 unsigned NumArgs =
574 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
Erich Keanee891aa92018-07-13 15:07:47 +0000575 SourceLocation(), ParsedAttr::AS_Declspec);
Aaron Ballman95d57032014-04-14 16:44:26 +0000576
577 // If this attribute's args were parsed, and it was expected to have
578 // arguments but none were provided, emit a diagnostic.
Erich Keanec480f302018-07-12 21:09:05 +0000579 if (!Attrs.empty() && Attrs.begin()->getMaxArgs() && !NumArgs) {
Aaron Ballmanef5d94c2014-04-15 00:36:39 +0000580 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Aaron Ballman95d57032014-04-14 16:44:26 +0000581 return false;
582 }
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000583 return true;
Aaron Ballman478faed2012-06-19 22:09:27 +0000584}
585
Eli Friedman06de2b52009-06-08 07:21:15 +0000586/// [MS] decl-specifier:
587/// __declspec ( extended-decl-modifier-seq )
588///
589/// [MS] extended-decl-modifier-seq:
590/// extended-decl-modifier[opt]
591/// extended-decl-modifier extended-decl-modifier-seq
Aaron Ballman068aa512015-05-20 20:58:33 +0000592void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
593 SourceLocation *End) {
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +0000594 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
Steve Naroff3a9b7e02008-12-24 20:59:21 +0000595 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
Eli Friedman06de2b52009-06-08 07:21:15 +0000596
Aaron Ballman068aa512015-05-20 20:58:33 +0000597 while (Tok.is(tok::kw___declspec)) {
598 ConsumeToken();
599 BalancedDelimiterTracker T(*this, tok::l_paren);
600 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
601 tok::r_paren))
Aaron Ballman478faed2012-06-19 22:09:27 +0000602 return;
Aaron Ballman478faed2012-06-19 22:09:27 +0000603
Aaron Ballman068aa512015-05-20 20:58:33 +0000604 // An empty declspec is perfectly legal and should not warn. Additionally,
605 // you can specify multiple attributes per declspec.
606 while (Tok.isNot(tok::r_paren)) {
607 // Attribute not present.
608 if (TryConsumeToken(tok::comma))
609 continue;
610
611 // We expect either a well-known identifier or a generic string. Anything
612 // else is a malformed declspec.
613 bool IsString = Tok.getKind() == tok::string_literal;
614 if (!IsString && Tok.getKind() != tok::identifier &&
615 Tok.getKind() != tok::kw_restrict) {
616 Diag(Tok, diag::err_ms_declspec_type);
Aaron Ballman478faed2012-06-19 22:09:27 +0000617 T.skipToEnd();
618 return;
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000619 }
Aaron Ballman068aa512015-05-20 20:58:33 +0000620
621 IdentifierInfo *AttrName;
622 SourceLocation AttrNameLoc;
623 if (IsString) {
624 SmallString<8> StrBuffer;
625 bool Invalid = false;
626 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
627 if (Invalid) {
628 T.skipToEnd();
629 return;
630 }
631 AttrName = PP.getIdentifierInfo(Str);
632 AttrNameLoc = ConsumeStringToken();
633 } else {
634 AttrName = Tok.getIdentifierInfo();
635 AttrNameLoc = ConsumeToken();
636 }
637
638 bool AttrHandled = false;
639
640 // Parse attribute arguments.
641 if (Tok.is(tok::l_paren))
642 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
643 else if (AttrName->getName() == "property")
644 // The property attribute must have an argument list.
645 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
646 << AttrName->getName();
647
648 if (!AttrHandled)
649 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000650 ParsedAttr::AS_Declspec);
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000651 }
Aaron Ballman068aa512015-05-20 20:58:33 +0000652 T.consumeClose();
653 if (End)
654 *End = T.getCloseLocation();
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000655 }
Eli Friedman53339e02009-06-08 23:27:34 +0000656}
657
John McCall53fa7142010-12-24 02:08:15 +0000658void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
Eli Friedman53339e02009-06-08 23:27:34 +0000659 // Treat these like attributes
Reid Klecknerd7857f02014-10-24 17:42:17 +0000660 while (true) {
661 switch (Tok.getKind()) {
662 case tok::kw___fastcall:
663 case tok::kw___stdcall:
664 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +0000665 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +0000666 case tok::kw___cdecl:
667 case tok::kw___vectorcall:
668 case tok::kw___ptr64:
669 case tok::kw___w64:
670 case tok::kw___ptr32:
Reid Klecknerd7857f02014-10-24 17:42:17 +0000671 case tok::kw___sptr:
672 case tok::kw___uptr: {
673 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
674 SourceLocation AttrNameLoc = ConsumeToken();
675 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000676 ParsedAttr::AS_Keyword);
Reid Klecknerd7857f02014-10-24 17:42:17 +0000677 break;
678 }
679 default:
680 return;
681 }
Eli Friedman53339e02009-06-08 23:27:34 +0000682 }
Steve Naroff3a9b7e02008-12-24 20:59:21 +0000683}
684
Nico Rieckeaaae272014-12-04 23:31:08 +0000685void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
686 SourceLocation StartLoc = Tok.getLocation();
687 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
688
689 if (EndLoc.isValid()) {
690 SourceRange Range(StartLoc, EndLoc);
691 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
692 }
693}
694
695SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
696 SourceLocation EndLoc;
697
698 while (true) {
699 switch (Tok.getKind()) {
700 case tok::kw_const:
701 case tok::kw_volatile:
702 case tok::kw___fastcall:
703 case tok::kw___stdcall:
704 case tok::kw___thiscall:
705 case tok::kw___cdecl:
706 case tok::kw___vectorcall:
707 case tok::kw___ptr32:
708 case tok::kw___ptr64:
709 case tok::kw___w64:
710 case tok::kw___unaligned:
711 case tok::kw___sptr:
712 case tok::kw___uptr:
713 EndLoc = ConsumeToken();
714 break;
715 default:
716 return EndLoc;
717 }
718 }
719}
720
John McCall53fa7142010-12-24 02:08:15 +0000721void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
Dawn Perchik335e16b2010-09-03 01:29:35 +0000722 // Treat these like attributes
723 while (Tok.is(tok::kw___pascal)) {
724 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
725 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000726 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000727 ParsedAttr::AS_Keyword);
Dawn Perchik335e16b2010-09-03 01:29:35 +0000728 }
John McCall53fa7142010-12-24 02:08:15 +0000729}
730
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +0000731void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000732 // Treat these like attributes
733 while (Tok.is(tok::kw___kernel)) {
Richard Smith0cdcc982013-01-29 01:24:26 +0000734 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000735 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000736 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000737 ParsedAttr::AS_Keyword);
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000738 }
739}
740
Aaron Ballman05d76ea2014-01-14 01:29:54 +0000741void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
742 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
743 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +0000744 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000745 ParsedAttr::AS_Keyword);
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000746}
747
Douglas Gregor261a89b2015-06-19 17:51:05 +0000748void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
749 // Treat these like attributes, even though they're type specifiers.
750 while (true) {
751 switch (Tok.getKind()) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +0000752 case tok::kw__Nonnull:
753 case tok::kw__Nullable:
754 case tok::kw__Null_unspecified: {
Douglas Gregor261a89b2015-06-19 17:51:05 +0000755 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
756 SourceLocation AttrNameLoc = ConsumeToken();
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000757 if (!getLangOpts().ObjC)
Douglas Gregor261a89b2015-06-19 17:51:05 +0000758 Diag(AttrNameLoc, diag::ext_nullability)
759 << AttrName;
Fangrui Song6907ce22018-07-30 19:24:48 +0000760 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Erich Keanee891aa92018-07-13 15:07:47 +0000761 ParsedAttr::AS_Keyword);
Douglas Gregor261a89b2015-06-19 17:51:05 +0000762 break;
763 }
764 default:
765 return;
766 }
767 }
768}
769
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000770static bool VersionNumberSeparator(const char Separator) {
771 return (Separator == '.' || Separator == '_');
772}
773
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000774/// Parse a version number.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000775///
776/// version:
777/// simple-integer
Jan Korous23255692018-05-17 11:51:49 +0000778/// simple-integer '.' simple-integer
779/// simple-integer '_' simple-integer
780/// simple-integer '.' simple-integer '.' simple-integer
781/// simple-integer '_' simple-integer '_' simple-integer
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000782VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
Erik Pilkington29099de2016-07-16 00:35:23 +0000783 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000784
785 if (!Tok.is(tok::numeric_constant)) {
786 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000787 SkipUntil(tok::comma, tok::r_paren,
788 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000789 return VersionTuple();
790 }
791
792 // Parse the major (and possibly minor and subminor) versions, which
793 // are stored in the numeric constant. We utilize a quirk of the
794 // lexer, which is that it handles something like 1.2.3 as a single
795 // numeric constant, rather than two separate tokens.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000796 SmallString<512> Buffer;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000797 Buffer.resize(Tok.getLength()+1);
798 const char *ThisTokBegin = &Buffer[0];
799
800 // Get the spelling of the token, which eliminates trigraphs, etc.
801 bool Invalid = false;
802 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
803 if (Invalid)
804 return VersionTuple();
805
806 // Parse the major version.
807 unsigned AfterMajor = 0;
808 unsigned Major = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000809 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000810 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
811 ++AfterMajor;
812 }
813
814 if (AfterMajor == 0) {
815 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000816 SkipUntil(tok::comma, tok::r_paren,
817 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000818 return VersionTuple();
819 }
820
821 if (AfterMajor == ActualLength) {
822 ConsumeToken();
823
824 // We only had a single version component.
825 if (Major == 0) {
826 Diag(Tok, diag::err_zero_version);
827 return VersionTuple();
828 }
829
830 return VersionTuple(Major);
831 }
832
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000833 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
834 if (!VersionNumberSeparator(AfterMajorSeparator)
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000835 || (AfterMajor + 1 == ActualLength)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000836 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000837 SkipUntil(tok::comma, tok::r_paren,
838 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000839 return VersionTuple();
840 }
841
842 // Parse the minor version.
843 unsigned AfterMinor = AfterMajor + 1;
844 unsigned Minor = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000845 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000846 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
847 ++AfterMinor;
848 }
849
850 if (AfterMinor == ActualLength) {
851 ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +0000852
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000853 // We had major.minor.
854 if (Major == 0 && Minor == 0) {
855 Diag(Tok, diag::err_zero_version);
856 return VersionTuple();
857 }
858
Jan Korous23255692018-05-17 11:51:49 +0000859 return VersionTuple(Major, Minor);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000860 }
861
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000862 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000863 // If what follows is not a '.' or '_', we have a problem.
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000864 if (!VersionNumberSeparator(AfterMinorSeparator)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000865 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000866 SkipUntil(tok::comma, tok::r_paren,
867 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Chad Rosierc1183952012-06-26 22:30:43 +0000868 return VersionTuple();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000869 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000870
Fariborz Jahanianb6161612014-10-03 17:21:12 +0000871 // Warn if separators, be it '.' or '_', do not match.
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000872 if (AfterMajorSeparator != AfterMinorSeparator)
873 Diag(Tok, diag::warn_expected_consistent_version_separator);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000874
875 // Parse the subminor version.
876 unsigned AfterSubminor = AfterMinor + 1;
877 unsigned Subminor = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000878 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000879 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
880 ++AfterSubminor;
881 }
882
883 if (AfterSubminor != ActualLength) {
884 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000885 SkipUntil(tok::comma, tok::r_paren,
886 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000887 return VersionTuple();
888 }
889 ConsumeToken();
Jan Korous23255692018-05-17 11:51:49 +0000890 return VersionTuple(Major, Minor, Subminor);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000891}
892
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000893/// Parse the contents of the "availability" attribute.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000894///
895/// availability-attribute:
Manman Ren75bc6762016-03-21 17:30:55 +0000896/// 'availability' '(' platform ',' opt-strict version-arg-list,
897/// opt-replacement, opt-message')'
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000898///
899/// platform:
900/// identifier
901///
Manman Rend8039df2016-02-22 04:47:24 +0000902/// opt-strict:
903/// 'strict' ','
Manman Renb636b902016-02-17 22:05:48 +0000904///
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000905/// version-arg-list:
906/// version-arg
907/// version-arg ',' version-arg-list
908///
909/// version-arg:
910/// 'introduced' '=' version
911/// 'deprecated' '=' version
Douglas Gregorfdd417f2012-03-11 04:53:21 +0000912/// 'obsoleted' = version
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000913/// 'unavailable'
Manman Ren75bc6762016-03-21 17:30:55 +0000914/// opt-replacement:
915/// 'replacement' '=' <string>
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000916/// opt-message:
917/// 'message' '=' <string>
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000918void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
919 SourceLocation AvailabilityLoc,
920 ParsedAttributes &attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000921 SourceLocation *endLoc,
922 IdentifierInfo *ScopeName,
923 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +0000924 ParsedAttr::Syntax Syntax) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000925 enum { Introduced, Deprecated, Obsoleted, Unknown };
926 AvailabilityChange Changes[Unknown];
Manman Ren75bc6762016-03-21 17:30:55 +0000927 ExprResult MessageExpr, ReplacementExpr;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000928
929 // Opening '('.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000930 BalancedDelimiterTracker T(*this, tok::l_paren);
931 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000932 Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000933 return;
934 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000935
Manman Renb636b902016-02-17 22:05:48 +0000936 // Parse the platform name.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000937 if (Tok.isNot(tok::identifier)) {
938 Diag(Tok, diag::err_availability_expected_platform);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000939 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000940 return;
941 }
Richard Smithfeefaf52013-09-03 18:01:40 +0000942 IdentifierLoc *Platform = ParseIdentifierLoc();
Alex Lorenz0b1ce8b2017-08-15 14:42:01 +0000943 if (const IdentifierInfo *const Ident = Platform->Ident) {
944 // Canonicalize platform name from "macosx" to "macos".
945 if (Ident->getName() == "macosx")
946 Platform->Ident = PP.getIdentifierInfo("macos");
947 // Canonicalize platform name from "macosx_app_extension" to
948 // "macos_app_extension".
949 else if (Ident->getName() == "macosx_app_extension")
950 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
951 else
952 Platform->Ident = PP.getIdentifierInfo(
953 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
954 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000955
956 // Parse the ',' following the platform name.
Alp Toker383d2c42014-01-01 03:08:43 +0000957 if (ExpectAndConsume(tok::comma)) {
958 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000959 return;
Alp Toker383d2c42014-01-01 03:08:43 +0000960 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000961
962 // If we haven't grabbed the pointers for the identifiers
963 // "introduced", "deprecated", and "obsoleted", do so now.
964 if (!Ident_introduced) {
965 Ident_introduced = PP.getIdentifierInfo("introduced");
966 Ident_deprecated = PP.getIdentifierInfo("deprecated");
967 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000968 Ident_unavailable = PP.getIdentifierInfo("unavailable");
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000969 Ident_message = PP.getIdentifierInfo("message");
Manman Rend8039df2016-02-22 04:47:24 +0000970 Ident_strict = PP.getIdentifierInfo("strict");
Manman Ren75bc6762016-03-21 17:30:55 +0000971 Ident_replacement = PP.getIdentifierInfo("replacement");
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000972 }
973
Manman Ren75bc6762016-03-21 17:30:55 +0000974 // Parse the optional "strict", the optional "replacement" and the set of
Manman Renb636b902016-02-17 22:05:48 +0000975 // introductions/deprecations/removals.
Manman Rend8039df2016-02-22 04:47:24 +0000976 SourceLocation UnavailableLoc, StrictLoc;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000977 do {
978 if (Tok.isNot(tok::identifier)) {
979 Diag(Tok, diag::err_availability_expected_change);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000980 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000981 return;
982 }
983 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
984 SourceLocation KeywordLoc = ConsumeToken();
985
Manman Rend8039df2016-02-22 04:47:24 +0000986 if (Keyword == Ident_strict) {
987 if (StrictLoc.isValid()) {
Manman Renb636b902016-02-17 22:05:48 +0000988 Diag(KeywordLoc, diag::err_availability_redundant)
Manman Rend8039df2016-02-22 04:47:24 +0000989 << Keyword << SourceRange(StrictLoc);
Manman Renb636b902016-02-17 22:05:48 +0000990 }
Manman Rend8039df2016-02-22 04:47:24 +0000991 StrictLoc = KeywordLoc;
Manman Renb636b902016-02-17 22:05:48 +0000992 continue;
993 }
994
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000995 if (Keyword == Ident_unavailable) {
996 if (UnavailableLoc.isValid()) {
997 Diag(KeywordLoc, diag::err_availability_redundant)
998 << Keyword << SourceRange(UnavailableLoc);
Chad Rosierc1183952012-06-26 22:30:43 +0000999 }
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001000 UnavailableLoc = KeywordLoc;
Alp Toker97650562014-01-10 11:19:30 +00001001 continue;
Chad Rosierc1183952012-06-26 22:30:43 +00001002 }
1003
Michael Wu260e9622018-11-12 02:44:33 +00001004 if (Keyword == Ident_deprecated && Platform->Ident &&
1005 Platform->Ident->isStr("swift")) {
1006 // For swift, we deprecate for all versions.
1007 if (Changes[Deprecated].KeywordLoc.isValid()) {
1008 Diag(KeywordLoc, diag::err_availability_redundant)
1009 << Keyword
1010 << SourceRange(Changes[Deprecated].KeywordLoc);
1011 }
1012
1013 Changes[Deprecated].KeywordLoc = KeywordLoc;
1014 // Use a fake version here.
1015 Changes[Deprecated].Version = VersionTuple(1);
1016 continue;
1017 }
1018
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001019 if (Tok.isNot(tok::equal)) {
Alp Tokerec543272013-12-24 09:48:30 +00001020 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001021 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001022 return;
1023 }
1024 ConsumeToken();
Manman Ren75bc6762016-03-21 17:30:55 +00001025 if (Keyword == Ident_message || Keyword == Ident_replacement) {
David Majnemer2e498302014-07-18 05:43:12 +00001026 if (Tok.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001027 Diag(Tok, diag::err_expected_string_literal)
1028 << /*Source='availability attribute'*/2;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001029 SkipUntil(tok::r_paren, StopAtSemi);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001030 return;
1031 }
Manman Ren75bc6762016-03-21 17:30:55 +00001032 if (Keyword == Ident_message)
1033 MessageExpr = ParseStringLiteralExpression();
1034 else
1035 ReplacementExpr = ParseStringLiteralExpression();
David Majnemer2e498302014-07-18 05:43:12 +00001036 // Also reject wide string literals.
1037 if (StringLiteral *MessageStringLiteral =
1038 cast_or_null<StringLiteral>(MessageExpr.get())) {
1039 if (MessageStringLiteral->getCharByteWidth() != 1) {
1040 Diag(MessageStringLiteral->getSourceRange().getBegin(),
1041 diag::err_expected_string_literal)
1042 << /*Source='availability attribute'*/ 2;
1043 SkipUntil(tok::r_paren, StopAtSemi);
1044 return;
1045 }
1046 }
Manman Ren75bc6762016-03-21 17:30:55 +00001047 if (Keyword == Ident_message)
1048 break;
1049 else
1050 continue;
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001051 }
Chad Rosierc1183952012-06-26 22:30:43 +00001052
Fariborz Jahanian5a29e6a2014-11-05 23:58:55 +00001053 // Special handling of 'NA' only when applied to introduced or
1054 // deprecated.
1055 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1056 Tok.is(tok::identifier)) {
1057 IdentifierInfo *NA = Tok.getIdentifierInfo();
1058 if (NA->getName() == "NA") {
1059 ConsumeToken();
1060 if (Keyword == Ident_introduced)
1061 UnavailableLoc = KeywordLoc;
1062 continue;
1063 }
1064 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001065
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001066 SourceRange VersionRange;
1067 VersionTuple Version = ParseVersionTuple(VersionRange);
Chad Rosierc1183952012-06-26 22:30:43 +00001068
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001069 if (Version.empty()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001070 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001071 return;
1072 }
1073
1074 unsigned Index;
1075 if (Keyword == Ident_introduced)
1076 Index = Introduced;
1077 else if (Keyword == Ident_deprecated)
1078 Index = Deprecated;
1079 else if (Keyword == Ident_obsoleted)
1080 Index = Obsoleted;
Chad Rosierc1183952012-06-26 22:30:43 +00001081 else
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001082 Index = Unknown;
1083
1084 if (Index < Unknown) {
1085 if (!Changes[Index].KeywordLoc.isInvalid()) {
1086 Diag(KeywordLoc, diag::err_availability_redundant)
Chad Rosierc1183952012-06-26 22:30:43 +00001087 << Keyword
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001088 << SourceRange(Changes[Index].KeywordLoc,
1089 Changes[Index].VersionRange.getEnd());
1090 }
1091
1092 Changes[Index].KeywordLoc = KeywordLoc;
1093 Changes[Index].Version = Version;
1094 Changes[Index].VersionRange = VersionRange;
1095 } else {
1096 Diag(KeywordLoc, diag::err_availability_unknown_change)
1097 << Keyword << VersionRange;
1098 }
1099
Alp Toker97650562014-01-10 11:19:30 +00001100 } while (TryConsumeToken(tok::comma));
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001101
1102 // Closing ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001103 if (T.consumeClose())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001104 return;
1105
1106 if (endLoc)
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001107 *endLoc = T.getCloseLocation();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001108
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001109 // The 'unavailable' availability cannot be combined with any other
1110 // availability changes. Make sure that hasn't happened.
1111 if (UnavailableLoc.isValid()) {
1112 bool Complained = false;
1113 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1114 if (Changes[Index].KeywordLoc.isValid()) {
1115 if (!Complained) {
1116 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1117 << SourceRange(Changes[Index].KeywordLoc,
1118 Changes[Index].VersionRange.getEnd());
1119 Complained = true;
1120 }
1121
1122 // Clear out the availability.
1123 Changes[Index] = AvailabilityChange();
1124 }
1125 }
1126 }
1127
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001128 // Record this attribute
Chad Rosierc1183952012-06-26 22:30:43 +00001129 attrs.addNew(&Availability,
1130 SourceRange(AvailabilityLoc, T.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001131 ScopeName, ScopeLoc,
Aaron Ballman00e99962013-08-31 01:11:41 +00001132 Platform,
John McCall084e83d2011-03-24 11:26:52 +00001133 Changes[Introduced],
1134 Changes[Deprecated],
Chad Rosierc1183952012-06-26 22:30:43 +00001135 Changes[Obsoleted],
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001136 UnavailableLoc, MessageExpr.get(),
Manman Ren75bc6762016-03-21 17:30:55 +00001137 Syntax, StrictLoc, ReplacementExpr.get());
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001138}
1139
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001140/// Parse the contents of the "external_source_symbol" attribute.
Alex Lorenzd5d27e12017-03-01 18:06:25 +00001141///
1142/// external-source-symbol-attribute:
1143/// 'external_source_symbol' '(' keyword-arg-list ')'
1144///
1145/// keyword-arg-list:
1146/// keyword-arg
1147/// keyword-arg ',' keyword-arg-list
1148///
1149/// keyword-arg:
1150/// 'language' '=' <string>
1151/// 'defined_in' '=' <string>
1152/// 'generated_declaration'
1153void Parser::ParseExternalSourceSymbolAttribute(
1154 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1155 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +00001156 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00001157 // Opening '('.
1158 BalancedDelimiterTracker T(*this, tok::l_paren);
1159 if (T.expectAndConsume())
1160 return;
1161
1162 // Initialize the pointers for the keyword identifiers when required.
1163 if (!Ident_language) {
1164 Ident_language = PP.getIdentifierInfo("language");
1165 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1166 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1167 }
1168
1169 ExprResult Language;
1170 bool HasLanguage = false;
1171 ExprResult DefinedInExpr;
1172 bool HasDefinedIn = false;
1173 IdentifierLoc *GeneratedDeclaration = nullptr;
1174
1175 // Parse the language/defined_in/generated_declaration keywords
1176 do {
1177 if (Tok.isNot(tok::identifier)) {
1178 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1179 SkipUntil(tok::r_paren, StopAtSemi);
1180 return;
1181 }
1182
1183 SourceLocation KeywordLoc = Tok.getLocation();
1184 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1185 if (Keyword == Ident_generated_declaration) {
1186 if (GeneratedDeclaration) {
1187 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1188 SkipUntil(tok::r_paren, StopAtSemi);
1189 return;
1190 }
1191 GeneratedDeclaration = ParseIdentifierLoc();
1192 continue;
1193 }
1194
1195 if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1196 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1197 SkipUntil(tok::r_paren, StopAtSemi);
1198 return;
1199 }
1200
1201 ConsumeToken();
1202 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1203 Keyword->getName())) {
1204 SkipUntil(tok::r_paren, StopAtSemi);
1205 return;
1206 }
1207
1208 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1209 if (Keyword == Ident_language)
1210 HasLanguage = true;
1211 else
1212 HasDefinedIn = true;
1213
1214 if (Tok.isNot(tok::string_literal)) {
1215 Diag(Tok, diag::err_expected_string_literal)
1216 << /*Source='external_source_symbol attribute'*/ 3
1217 << /*language | source container*/ (Keyword != Ident_language);
1218 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1219 continue;
1220 }
1221 if (Keyword == Ident_language) {
1222 if (HadLanguage) {
1223 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1224 << Keyword;
1225 ParseStringLiteralExpression();
1226 continue;
1227 }
1228 Language = ParseStringLiteralExpression();
1229 } else {
1230 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1231 if (HadDefinedIn) {
1232 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1233 << Keyword;
1234 ParseStringLiteralExpression();
1235 continue;
1236 }
1237 DefinedInExpr = ParseStringLiteralExpression();
1238 }
1239 } while (TryConsumeToken(tok::comma));
1240
1241 // Closing ')'.
1242 if (T.consumeClose())
1243 return;
1244 if (EndLoc)
1245 *EndLoc = T.getCloseLocation();
1246
1247 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1248 GeneratedDeclaration};
1249 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1250 ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1251}
1252
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001253/// Parse the contents of the "objc_bridge_related" attribute.
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001254/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1255/// related_class:
1256/// Identifier
1257///
1258/// opt-class_method:
1259/// Identifier: | <empty>
1260///
1261/// opt-instance_method:
1262/// Identifier | <empty>
1263///
1264void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1265 SourceLocation ObjCBridgeRelatedLoc,
1266 ParsedAttributes &attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001267 SourceLocation *endLoc,
1268 IdentifierInfo *ScopeName,
1269 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001270 ParsedAttr::Syntax Syntax) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001271 // Opening '('.
1272 BalancedDelimiterTracker T(*this, tok::l_paren);
1273 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00001274 Diag(Tok, diag::err_expected) << tok::l_paren;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001275 return;
1276 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001277
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001278 // Parse the related class name.
1279 if (Tok.isNot(tok::identifier)) {
1280 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1281 SkipUntil(tok::r_paren, StopAtSemi);
1282 return;
1283 }
1284 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
Alp Toker97650562014-01-10 11:19:30 +00001285 if (ExpectAndConsume(tok::comma)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001286 SkipUntil(tok::r_paren, StopAtSemi);
1287 return;
1288 }
Alp Toker8fbec672013-12-17 23:29:36 +00001289
Aaron Ballman48a533d2018-02-27 23:49:28 +00001290 // Parse class method name. It's non-optional in the sense that a trailing
1291 // comma is required, but it can be the empty string, and then we record a
1292 // nullptr.
Craig Topper161e4db2014-05-21 06:02:52 +00001293 IdentifierLoc *ClassMethod = nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001294 if (Tok.is(tok::identifier)) {
1295 ClassMethod = ParseIdentifierLoc();
Alp Toker8fbec672013-12-17 23:29:36 +00001296 if (!TryConsumeToken(tok::colon)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001297 Diag(Tok, diag::err_objcbridge_related_selector_name);
1298 SkipUntil(tok::r_paren, StopAtSemi);
1299 return;
1300 }
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001301 }
Alp Toker8fbec672013-12-17 23:29:36 +00001302 if (!TryConsumeToken(tok::comma)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001303 if (Tok.is(tok::colon))
1304 Diag(Tok, diag::err_objcbridge_related_selector_name);
1305 else
Alp Tokerec543272013-12-24 09:48:30 +00001306 Diag(Tok, diag::err_expected) << tok::comma;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001307 SkipUntil(tok::r_paren, StopAtSemi);
1308 return;
1309 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001310
Aaron Ballman48a533d2018-02-27 23:49:28 +00001311 // Parse instance method name. Also non-optional but empty string is
1312 // permitted.
Craig Topper161e4db2014-05-21 06:02:52 +00001313 IdentifierLoc *InstanceMethod = nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001314 if (Tok.is(tok::identifier))
1315 InstanceMethod = ParseIdentifierLoc();
1316 else if (Tok.isNot(tok::r_paren)) {
Alp Tokerec543272013-12-24 09:48:30 +00001317 Diag(Tok, diag::err_expected) << tok::r_paren;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001318 SkipUntil(tok::r_paren, StopAtSemi);
1319 return;
1320 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001321
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001322 // Closing ')'.
1323 if (T.consumeClose())
1324 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001325
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001326 if (endLoc)
1327 *endLoc = T.getCloseLocation();
Fangrui Song6907ce22018-07-30 19:24:48 +00001328
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001329 // Record this attribute
1330 attrs.addNew(&ObjCBridgeRelated,
1331 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001332 ScopeName, ScopeLoc,
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001333 RelatedClass,
1334 ClassMethod,
1335 InstanceMethod,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001336 Syntax);
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001337}
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001338
Bill Wendling44426052012-12-20 19:22:21 +00001339// Late Parsed Attributes:
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001340// See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1341
1342void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1343
1344void Parser::LateParsedClass::ParseLexedAttributes() {
1345 Self->ParseLexedAttributes(*Class);
1346}
1347
1348void Parser::LateParsedAttribute::ParseLexedAttributes() {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001349 Self->ParseLexedAttribute(*this, true, false);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001350}
1351
1352/// Wrapper class which calls ParseLexedAttribute, after setting up the
1353/// scope appropriately.
1354void Parser::ParseLexedAttributes(ParsingClass &Class) {
1355 // Deal with templates
1356 // FIXME: Test cases to make sure this does the right thing for templates.
1357 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1358 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1359 HasTemplateScope);
1360 if (HasTemplateScope)
1361 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1362
Douglas Gregor3024f072012-04-16 07:05:22 +00001363 // Set or update the scope flags.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001364 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +00001365 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001366 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1367 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1368
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001369 // Enter the scope of nested classes
1370 if (!AlreadyHasClassScope)
1371 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1372 Class.TagOrTemplate);
Benjamin Kramer1d373c62012-05-17 12:01:52 +00001373 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001374 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1375 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1376 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001377 }
Chad Rosierc1183952012-06-26 22:30:43 +00001378
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001379 if (!AlreadyHasClassScope)
1380 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1381 Class.TagOrTemplate);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001382}
1383
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001384/// Parse all attributes in LAs, and attach them to Decl D.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001385void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1386 bool EnterScope, bool OnDefinition) {
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001387 assert(LAs.parseSoon() &&
1388 "Attribute list should be marked for immediate parsing.");
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001389 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
DeLesley Hutchins19c722d2012-08-15 22:41:04 +00001390 if (D)
1391 LAs[i]->addDecl(D);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001392 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
Benjamin Kramerbafc49a2012-04-14 12:44:47 +00001393 delete LAs[i];
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001394 }
1395 LAs.clear();
1396}
1397
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001398/// Finish parsing an attribute for which parsing was delayed.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001399/// This will be called at the end of parsing a class declaration
1400/// for each LateParsedAttribute. We consume the saved tokens and
Chad Rosierc1183952012-06-26 22:30:43 +00001401/// create an attribute with the arguments filled in. We add this
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001402/// to the Attribute list for the decl.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001403void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1404 bool EnterScope, bool OnDefinition) {
David Majnemerd5946f52015-01-13 08:35:24 +00001405 // Create a fake EOF so that attribute parsing won't go off the end of the
1406 // attribute.
1407 Token AttrEnd;
1408 AttrEnd.startToken();
1409 AttrEnd.setKind(tok::eof);
1410 AttrEnd.setLocation(Tok.getLocation());
1411 AttrEnd.setEofData(LA.Toks.data());
1412 LA.Toks.push_back(AttrEnd);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001413
1414 // Append the current token at the end of the new token stream so that it
1415 // doesn't get lost.
1416 LA.Toks.push_back(Tok);
David Blaikie2eabcc92016-02-09 18:52:09 +00001417 PP.EnterTokenStream(LA.Toks, true);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001418 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +00001419 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001420
1421 ParsedAttributes Attrs(AttrFactory);
1422 SourceLocation endLoc;
1423
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001424 if (LA.Decls.size() > 0) {
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001425 Decl *D = LA.Decls[0];
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001426 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1427 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001428
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001429 // Allow 'this' within late-parsed attributes.
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001430 Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
Richard Smithc3d2ebb2013-06-07 02:33:37 +00001431 ND && ND->isCXXInstanceMember());
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001432
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001433 if (LA.Decls.size() == 1) {
1434 // If the Decl is templatized, add template parameters to scope.
1435 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1436 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1437 if (HasTemplateScope)
1438 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001439
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001440 // If the Decl is on a function, add function parameters to the scope.
1441 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
Momchil Velikov57c681f2017-08-10 15:43:06 +00001442 ParseScope FnScope(
1443 this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
1444 HasFunScope);
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001445 if (HasFunScope)
1446 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001447
Michael Han23214e52012-10-03 01:56:22 +00001448 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001449 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
Craig Topper161e4db2014-05-21 06:02:52 +00001450 nullptr);
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001451
1452 if (HasFunScope) {
1453 Actions.ActOnExitFunctionContext();
1454 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1455 }
1456 if (HasTemplateScope) {
1457 TempScope.Exit();
1458 }
1459 } else {
1460 // If there are multiple decls, then the decl cannot be within the
1461 // function scope.
Michael Han23214e52012-10-03 01:56:22 +00001462 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001463 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
Craig Topper161e4db2014-05-21 06:02:52 +00001464 nullptr);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001465 }
DeLesley Hutchins71d61032012-03-02 22:29:50 +00001466 } else {
1467 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001468 }
1469
Erich Keanec480f302018-07-12 21:09:05 +00001470 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
1471 Attrs.begin()->isKnownToGCC())
Aaron Ballman9a99e0d2014-01-20 17:18:35 +00001472 Diag(Tok, diag::warn_attribute_on_function_definition)
1473 << &LA.AttrName;
1474
1475 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001476 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001477
David Majnemerd5946f52015-01-13 08:35:24 +00001478 // Due to a parsing error, we either went over the cached tokens or
1479 // there are still cached tokens left, so we skip the leftover tokens.
1480 while (Tok.isNot(tok::eof))
1481 ConsumeAnyToken();
1482
1483 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1484 ConsumeAnyToken();
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001485}
1486
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001487void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1488 SourceLocation AttrNameLoc,
1489 ParsedAttributes &Attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001490 SourceLocation *EndLoc,
1491 IdentifierInfo *ScopeName,
1492 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001493 ParsedAttr::Syntax Syntax) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001494 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1495
1496 BalancedDelimiterTracker T(*this, tok::l_paren);
1497 T.consumeOpen();
1498
1499 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001500 Diag(Tok, diag::err_expected) << tok::identifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001501 T.skipToEnd();
1502 return;
1503 }
Richard Smithfeefaf52013-09-03 18:01:40 +00001504 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001505
Alp Toker094e5212014-01-05 03:27:11 +00001506 if (ExpectAndConsume(tok::comma)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001507 T.skipToEnd();
1508 return;
1509 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001510
1511 SourceRange MatchingCTypeRange;
1512 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1513 if (MatchingCType.isInvalid()) {
1514 T.skipToEnd();
1515 return;
1516 }
1517
1518 bool LayoutCompatible = false;
1519 bool MustBeNull = false;
Alp Toker8fbec672013-12-17 23:29:36 +00001520 while (TryConsumeToken(tok::comma)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001521 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001522 Diag(Tok, diag::err_expected) << tok::identifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001523 T.skipToEnd();
1524 return;
1525 }
1526 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1527 if (Flag->isStr("layout_compatible"))
1528 LayoutCompatible = true;
1529 else if (Flag->isStr("must_be_null"))
1530 MustBeNull = true;
1531 else {
1532 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1533 T.skipToEnd();
1534 return;
1535 }
1536 ConsumeToken(); // consume flag
1537 }
1538
1539 if (!T.consumeClose()) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001540 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001541 ArgumentKind, MatchingCType.get(),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001542 LayoutCompatible, MustBeNull, Syntax);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001543 }
1544
1545 if (EndLoc)
1546 *EndLoc = T.getCloseLocation();
1547}
1548
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001549/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1550/// of a C++11 attribute-specifier in a location where an attribute is not
1551/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1552/// situation.
1553///
1554/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1555/// this doesn't appear to actually be an attribute-specifier, and the caller
1556/// should try to parse it.
1557bool Parser::DiagnoseProhibitedCXX11Attribute() {
1558 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1559
1560 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1561 case CAK_NotAttributeSpecifier:
1562 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1563 return false;
1564
1565 case CAK_InvalidAttributeSpecifier:
1566 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1567 return false;
1568
1569 case CAK_AttributeSpecifier:
1570 // Parse and discard the attributes.
1571 SourceLocation BeginLoc = ConsumeBracket();
1572 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001573 SkipUntil(tok::r_square);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001574 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1575 SourceLocation EndLoc = ConsumeBracket();
1576 Diag(BeginLoc, diag::err_attributes_not_allowed)
1577 << SourceRange(BeginLoc, EndLoc);
1578 return true;
1579 }
Chandler Carruthd8f7d382012-04-10 16:03:08 +00001580 llvm_unreachable("All cases handled above.");
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001581}
1582
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001583/// We have found the opening square brackets of a C++11
Richard Smith98155ad2013-02-20 01:17:14 +00001584/// attribute-specifier in a location where an attribute is not permitted, but
1585/// we know where the attributes ought to be written. Parse them anyway, and
1586/// provide a fixit moving them to the right place.
Richard Smith4c96e992013-02-19 23:47:15 +00001587void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1588 SourceLocation CorrectLocation) {
1589 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1590 Tok.is(tok::kw_alignas));
1591
1592 // Consume the attributes.
1593 SourceLocation Loc = Tok.getLocation();
1594 ParseCXX11Attributes(Attrs);
1595 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
Faisal Valic5089c02017-12-25 22:23:20 +00001596 // FIXME: use err_attributes_misplaced
Richard Smith4c96e992013-02-19 23:47:15 +00001597 Diag(Loc, diag::err_attributes_not_allowed)
1598 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1599 << FixItHint::CreateRemoval(AttrRange);
1600}
1601
Erich Keanec480f302018-07-12 21:09:05 +00001602void Parser::DiagnoseProhibitedAttributes(
1603 const SourceRange &Range, const SourceLocation CorrectLocation) {
Faisal Valic5089c02017-12-25 22:23:20 +00001604 if (CorrectLocation.isValid()) {
Erich Keanec480f302018-07-12 21:09:05 +00001605 CharSourceRange AttrRange(Range, true);
Faisal Valic5089c02017-12-25 22:23:20 +00001606 Diag(CorrectLocation, diag::err_attributes_misplaced)
1607 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1608 << FixItHint::CreateRemoval(AttrRange);
1609 } else
Erich Keanec480f302018-07-12 21:09:05 +00001610 Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
Dawn Perchik335e16b2010-09-03 01:29:35 +00001611}
1612
Richard Smith49cc1cc2016-08-18 21:59:42 +00001613void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1614 unsigned DiagID) {
Erich Keanee891aa92018-07-13 15:07:47 +00001615 for (const ParsedAttr &AL : Attrs) {
Erich Keanec480f302018-07-12 21:09:05 +00001616 if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
Richard Smith49cc1cc2016-08-18 21:59:42 +00001617 continue;
Erich Keanee891aa92018-07-13 15:07:47 +00001618 if (AL.getKind() == ParsedAttr::UnknownAttribute)
Erich Keanec480f302018-07-12 21:09:05 +00001619 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL.getName();
Richard Smith49cc1cc2016-08-18 21:59:42 +00001620 else {
Erich Keanec480f302018-07-12 21:09:05 +00001621 Diag(AL.getLoc(), DiagID) << AL.getName();
1622 AL.setInvalid();
Michael Han64536a62012-11-06 19:34:54 +00001623 }
Michael Han64536a62012-11-06 19:34:54 +00001624 }
1625}
1626
Nico Weber32a0fc72016-09-03 03:01:32 +00001627// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1628// applies to var, not the type Foo.
David Majnemer936b4112015-04-19 07:53:29 +00001629// As an exception to the rule, __declspec(align(...)) before the
1630// class-key affects the type instead of the variable.
Nico Weber32a0fc72016-09-03 03:01:32 +00001631// Also, Microsoft-style [attributes] seem to affect the type instead of the
1632// variable.
1633// This function moves attributes that should apply to the type off DS to Attrs.
1634void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1635 DeclSpec &DS,
1636 Sema::TagUseKind TUK) {
David Majnemer936b4112015-04-19 07:53:29 +00001637 if (TUK == Sema::TUK_Reference)
1638 return;
1639
Erich Keanee891aa92018-07-13 15:07:47 +00001640 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
David Majnemer936b4112015-04-19 07:53:29 +00001641
Erich Keanee891aa92018-07-13 15:07:47 +00001642 for (ParsedAttr &AL : DS.getAttributes()) {
1643 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
Erich Keanec480f302018-07-12 21:09:05 +00001644 AL.isDeclspecAttribute()) ||
1645 AL.isMicrosoftAttribute())
1646 ToBeMoved.push_back(&AL);
David Majnemer936b4112015-04-19 07:53:29 +00001647 }
Nico Weber88f5ed92016-09-13 18:55:26 +00001648
Erich Keanee891aa92018-07-13 15:07:47 +00001649 for (ParsedAttr *AL : ToBeMoved) {
Erich Keanec480f302018-07-12 21:09:05 +00001650 DS.getAttributes().remove(AL);
1651 Attrs.addAtEnd(AL);
1652 }
David Majnemer936b4112015-04-19 07:53:29 +00001653}
1654
Chris Lattner53361ac2006-08-10 05:19:57 +00001655/// ParseDeclaration - Parse a full 'declaration', which consists of
1656/// declaration-specifiers, some number of declarators, and a semicolon.
Faisal Vali421b2d12017-12-29 05:41:00 +00001657/// 'Context' should be a DeclaratorContext value. This returns the
Chris Lattner49836b42009-04-02 04:16:50 +00001658/// location of the semicolon in DeclEnd.
Chris Lattnera5235172007-08-25 06:57:03 +00001659///
1660/// declaration: [C99 6.7]
1661/// block-declaration ->
1662/// simple-declaration
1663/// others [FIXME]
Douglas Gregoreb31f392008-12-01 23:54:00 +00001664/// [C++] template-declaration
Chris Lattnera5235172007-08-25 06:57:03 +00001665/// [C++] namespace-definition
Douglas Gregord7c4d982008-12-30 03:27:21 +00001666/// [C++] using-directive
Douglas Gregor77b50e12009-06-22 23:06:13 +00001667/// [C++] using-declaration
Richard Smithc202b282012-04-14 00:33:13 +00001668/// [C++11/C11] static_assert-declaration
Chris Lattnera5235172007-08-25 06:57:03 +00001669/// others... [FIXME]
1670///
Faisal Vali421b2d12017-12-29 05:41:00 +00001671Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
Alexis Hunt96d5c762009-11-21 08:43:09 +00001672 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +00001673 ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +00001674 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Fariborz Jahanian59b75282011-08-30 17:10:52 +00001675 // Must temporarily exit the objective-c container scope for
1676 // parsing c none objective-c decls.
1677 ObjCDeclContextSwitch ObjCDC(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00001678
Craig Topper161e4db2014-05-21 06:02:52 +00001679 Decl *SingleDecl = nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +00001680 switch (Tok.getKind()) {
Douglas Gregoreb31f392008-12-01 23:54:00 +00001681 case tok::kw_template:
Douglas Gregor23996282009-05-12 21:31:51 +00001682 case tok::kw_export:
John McCall53fa7142010-12-24 02:08:15 +00001683 ProhibitAttributes(attrs);
Erich Keanec480f302018-07-12 21:09:05 +00001684 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001685 break;
Sebastian Redl67667942010-08-27 23:12:46 +00001686 case tok::kw_inline:
Sebastian Redl5a5f2c72010-08-31 00:36:45 +00001687 // Could be the start of an inline namespace. Allowed as an ext in C++03.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001688 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
John McCall53fa7142010-12-24 02:08:15 +00001689 ProhibitAttributes(attrs);
Sebastian Redl67667942010-08-27 23:12:46 +00001690 SourceLocation InlineLoc = ConsumeToken();
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00001691 return ParseNamespace(Context, DeclEnd, InlineLoc);
Sebastian Redl67667942010-08-27 23:12:46 +00001692 }
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001693 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
Fariborz Jahanian1db5c942010-09-28 20:42:35 +00001694 true);
Chris Lattnera5235172007-08-25 06:57:03 +00001695 case tok::kw_namespace:
John McCall53fa7142010-12-24 02:08:15 +00001696 ProhibitAttributes(attrs);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00001697 return ParseNamespace(Context, DeclEnd);
Douglas Gregord7c4d982008-12-30 03:27:21 +00001698 case tok::kw_using:
Richard Smith6f1daa42016-12-16 00:58:48 +00001699 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1700 DeclEnd, attrs);
Anders Carlssonf24fcff62009-03-11 16:27:10 +00001701 case tok::kw_static_assert:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00001702 case tok::kw__Static_assert:
John McCall53fa7142010-12-24 02:08:15 +00001703 ProhibitAttributes(attrs);
Chris Lattner49836b42009-04-02 04:16:50 +00001704 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001705 break;
Chris Lattnera5235172007-08-25 06:57:03 +00001706 default:
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001707 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
Chris Lattnera5235172007-08-25 06:57:03 +00001708 }
Chad Rosierc1183952012-06-26 22:30:43 +00001709
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001710 // This routine returns a DeclGroup, if the thing we parsed only contains a
Richard Smith6f1daa42016-12-16 00:58:48 +00001711 // single decl, convert it now.
1712 return Actions.ConvertDeclToDeclGroup(SingleDecl);
Chris Lattnera5235172007-08-25 06:57:03 +00001713}
1714
1715/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1716/// declaration-specifiers init-declarator-list[opt] ';'
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001717/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1718/// init-declarator-list ';'
Chris Lattnera5235172007-08-25 06:57:03 +00001719///[C90/C++]init-declarator-list ';' [TODO]
1720/// [OMP] threadprivate-directive [TODO]
Chris Lattner32dc41c2009-03-29 17:27:48 +00001721///
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001722/// for-range-declaration: [C++11 6.5p1: stmt.ranged]
Richard Smith02e85f32011-04-14 22:09:26 +00001723/// attribute-specifier-seq[opt] type-specifier-seq declarator
1724///
Chris Lattner32dc41c2009-03-29 17:27:48 +00001725/// If RequireSemi is false, this does not check for a ';' at the end of the
Chris Lattner005fc1b2010-04-05 18:18:31 +00001726/// declaration. If it is true, it checks for and eats it.
Richard Smith02e85f32011-04-14 22:09:26 +00001727///
1728/// If FRI is non-null, we might be parsing a for-range-declaration instead
1729/// of a simple-declaration. If we find that we are, we also parse the
1730/// for-range-initializer, and place it here.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001731Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +00001732Parser::ParseSimpleDeclaration(DeclaratorContext Context,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001733 SourceLocation &DeclEnd,
Richard Smith2386c8b2013-02-22 09:06:26 +00001734 ParsedAttributesWithRange &Attrs,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001735 bool RequireSemi, ForRangeInit *FRI) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001736 // Parse the common declaration-specifiers piece.
John McCall28a6aea2009-11-04 02:18:39 +00001737 ParsingDeclSpec DS(*this);
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001738
Richard Smith404dfb42013-11-19 22:47:36 +00001739 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
Faisal Valia534f072018-04-26 00:42:40 +00001740 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
Richard Smith404dfb42013-11-19 22:47:36 +00001741
1742 // If we had a free-standing type definition with a missing semicolon, we
1743 // may get this far before the problem becomes obvious.
1744 if (DS.hasTagDefinition() &&
1745 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
David Blaikie0403cb12016-01-15 23:43:25 +00001746 return nullptr;
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001747
Chris Lattner0e894622006-08-13 19:58:17 +00001748 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1749 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner76c72282007-10-09 17:33:22 +00001750 if (Tok.is(tok::semi)) {
Richard Smith2386c8b2013-02-22 09:06:26 +00001751 ProhibitAttributes(Attrs);
Argyrios Kyrtzidisfbb2bb52012-05-16 23:49:15 +00001752 DeclEnd = Tok.getLocation();
Chris Lattner005fc1b2010-04-05 18:18:31 +00001753 if (RequireSemi) ConsumeToken();
Nico Weber7b837f52016-01-28 19:25:00 +00001754 RecordDecl *AnonRecord = nullptr;
John McCall48871652010-08-21 09:40:31 +00001755 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00001756 DS, AnonRecord);
John McCall28a6aea2009-11-04 02:18:39 +00001757 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00001758 if (AnonRecord) {
1759 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00001760 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00001761 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001762 return Actions.ConvertDeclToDeclGroup(TheDecl);
Chris Lattner0e894622006-08-13 19:58:17 +00001763 }
Chad Rosierc1183952012-06-26 22:30:43 +00001764
Richard Smith2386c8b2013-02-22 09:06:26 +00001765 DS.takeAttributesFrom(Attrs);
Reid Klecknerd61a3112014-12-15 23:16:32 +00001766 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
John McCalld5a36322009-11-03 19:26:08 +00001767}
Mike Stump11289f42009-09-09 15:08:12 +00001768
Richard Smith09f76ee2011-10-19 21:33:05 +00001769/// Returns true if this might be the start of a declarator, or a common typo
1770/// for a declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001771bool Parser::MightBeDeclarator(DeclaratorContext Context) {
Richard Smith09f76ee2011-10-19 21:33:05 +00001772 switch (Tok.getKind()) {
1773 case tok::annot_cxxscope:
1774 case tok::annot_template_id:
1775 case tok::caret:
1776 case tok::code_completion:
1777 case tok::coloncolon:
1778 case tok::ellipsis:
1779 case tok::kw___attribute:
1780 case tok::kw_operator:
1781 case tok::l_paren:
1782 case tok::star:
1783 return true;
1784
1785 case tok::amp:
1786 case tok::ampamp:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001787 return getLangOpts().CPlusPlus;
Richard Smith09f76ee2011-10-19 21:33:05 +00001788
Richard Smithc8a79032012-01-09 22:31:44 +00001789 case tok::l_square: // Might be an attribute on an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001790 return Context == DeclaratorContext::MemberContext &&
1791 getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
Richard Smithc8a79032012-01-09 22:31:44 +00001792
1793 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001794 return Context == DeclaratorContext::MemberContext ||
1795 getLangOpts().CPlusPlus;
Richard Smithc8a79032012-01-09 22:31:44 +00001796
Richard Smith09f76ee2011-10-19 21:33:05 +00001797 case tok::identifier:
1798 switch (NextToken().getKind()) {
1799 case tok::code_completion:
1800 case tok::coloncolon:
1801 case tok::comma:
1802 case tok::equal:
1803 case tok::equalequal: // Might be a typo for '='.
1804 case tok::kw_alignas:
1805 case tok::kw_asm:
1806 case tok::kw___attribute:
1807 case tok::l_brace:
1808 case tok::l_paren:
1809 case tok::l_square:
1810 case tok::less:
1811 case tok::r_brace:
1812 case tok::r_paren:
1813 case tok::r_square:
1814 case tok::semi:
1815 return true;
1816
1817 case tok::colon:
1818 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
Richard Smithc8a79032012-01-09 22:31:44 +00001819 // and in block scope it's probably a label. Inside a class definition,
1820 // this is a bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001821 return Context == DeclaratorContext::MemberContext ||
1822 (getLangOpts().CPlusPlus &&
1823 Context == DeclaratorContext::FileContext);
Richard Smithc8a79032012-01-09 22:31:44 +00001824
1825 case tok::identifier: // Possible virt-specifier.
Richard Smith89645bc2013-01-02 12:01:23 +00001826 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
Richard Smith09f76ee2011-10-19 21:33:05 +00001827
1828 default:
1829 return false;
1830 }
1831
1832 default:
1833 return false;
1834 }
1835}
1836
Richard Smithb8caac82012-04-11 20:59:20 +00001837/// Skip until we reach something which seems like a sensible place to pick
1838/// up parsing after a malformed declaration. This will sometimes stop sooner
1839/// than SkipUntil(tok::r_brace) would, but will never stop later.
1840void Parser::SkipMalformedDecl() {
1841 while (true) {
1842 switch (Tok.getKind()) {
1843 case tok::l_brace:
1844 // Skip until matching }, then stop. We've probably skipped over
1845 // a malformed class or function definition or similar.
1846 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001847 SkipUntil(tok::r_brace);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001848 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
Richard Smithb8caac82012-04-11 20:59:20 +00001849 // This declaration isn't over yet. Keep skipping.
1850 continue;
1851 }
Alp Toker8fbec672013-12-17 23:29:36 +00001852 TryConsumeToken(tok::semi);
Richard Smithb8caac82012-04-11 20:59:20 +00001853 return;
1854
1855 case tok::l_square:
1856 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001857 SkipUntil(tok::r_square);
Richard Smithb8caac82012-04-11 20:59:20 +00001858 continue;
1859
1860 case tok::l_paren:
1861 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001862 SkipUntil(tok::r_paren);
Richard Smithb8caac82012-04-11 20:59:20 +00001863 continue;
1864
1865 case tok::r_brace:
1866 return;
1867
1868 case tok::semi:
1869 ConsumeToken();
1870 return;
1871
1872 case tok::kw_inline:
1873 // 'inline namespace' at the start of a line is almost certainly
Jordan Rose12e730c2012-07-09 16:54:53 +00001874 // a good place to pick back up parsing, except in an Objective-C
1875 // @interface context.
1876 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1877 (!ParsingInObjCContainer || CurParsedObjCImpl))
Richard Smithb8caac82012-04-11 20:59:20 +00001878 return;
1879 break;
1880
1881 case tok::kw_namespace:
1882 // 'namespace' at the start of a line is almost certainly a good
Jordan Rose12e730c2012-07-09 16:54:53 +00001883 // place to pick back up parsing, except in an Objective-C
1884 // @interface context.
1885 if (Tok.isAtStartOfLine() &&
1886 (!ParsingInObjCContainer || CurParsedObjCImpl))
1887 return;
1888 break;
1889
1890 case tok::at:
1891 // @end is very much like } in Objective-C contexts.
1892 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1893 ParsingInObjCContainer)
1894 return;
1895 break;
1896
1897 case tok::minus:
1898 case tok::plus:
1899 // - and + probably start new method declarations in Objective-C contexts.
1900 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
Richard Smithb8caac82012-04-11 20:59:20 +00001901 return;
1902 break;
1903
1904 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001905 case tok::annot_module_begin:
1906 case tok::annot_module_end:
1907 case tok::annot_module_include:
Richard Smithb8caac82012-04-11 20:59:20 +00001908 return;
1909
1910 default:
1911 break;
1912 }
1913
1914 ConsumeAnyToken();
1915 }
1916}
1917
John McCalld5a36322009-11-03 19:26:08 +00001918/// ParseDeclGroup - Having concluded that this is either a function
1919/// definition or a group of object declarations, actually parse the
1920/// result.
John McCall28a6aea2009-11-04 02:18:39 +00001921Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
Faisal Vali421b2d12017-12-29 05:41:00 +00001922 DeclaratorContext Context,
Richard Smith02e85f32011-04-14 22:09:26 +00001923 SourceLocation *DeclEnd,
1924 ForRangeInit *FRI) {
John McCalld5a36322009-11-03 19:26:08 +00001925 // Parse the first declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001926 ParsingDeclarator D(*this, DS, Context);
John McCalld5a36322009-11-03 19:26:08 +00001927 ParseDeclarator(D);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001928
John McCalld5a36322009-11-03 19:26:08 +00001929 // Bail out if the first declarator didn't seem well-formed.
1930 if (!D.hasName() && !D.mayOmitIdentifier()) {
Richard Smithb8caac82012-04-11 20:59:20 +00001931 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00001932 return nullptr;
Chris Lattnerefb0f112009-03-29 17:18:04 +00001933 }
Mike Stump11289f42009-09-09 15:08:12 +00001934
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001935 // Save late-parsed attributes for now; they need to be parsed in the
1936 // appropriate function scope after the function Decl has been constructed.
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001937 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1938 LateParsedAttrList LateParsedAttrs(true);
Richard Smith99c464c2014-11-10 21:10:32 +00001939 if (D.isFunctionDeclarator()) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001940 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1941
Richard Smith99c464c2014-11-10 21:10:32 +00001942 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1943 // attribute. If we find the keyword here, tell the user to put it
1944 // at the start instead.
1945 if (Tok.is(tok::kw__Noreturn)) {
1946 SourceLocation Loc = ConsumeToken();
1947 const char *PrevSpec;
1948 unsigned DiagID;
1949
1950 // We can offer a fixit if it's valid to mark this function as _Noreturn
1951 // and we don't have any other declarators in this declaration.
1952 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1953 MaybeParseGNUAttributes(D, &LateParsedAttrs);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001954 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
Richard Smith99c464c2014-11-10 21:10:32 +00001955
1956 Diag(Loc, diag::err_c11_noreturn_misplaced)
1957 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001958 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
Richard Smith99c464c2014-11-10 21:10:32 +00001959 : FixItHint());
1960 }
1961 }
1962
Chris Lattnerdbb1e932010-07-11 22:24:20 +00001963 // Check to see if we have a function *definition* which must have a body.
Douglas Gregor012efe22013-04-16 16:01:32 +00001964 if (D.isFunctionDeclarator() &&
Chris Lattnerdbb1e932010-07-11 22:24:20 +00001965 // Look at the next token to make sure that this isn't a function
1966 // declaration. We have to check this because __attribute__ might be the
1967 // start of a function definition in GCC-extended K&R C.
Fariborz Jahanian712bb812012-08-10 15:54:40 +00001968 !isDeclarationAfterDeclarator()) {
Chad Rosierc1183952012-06-26 22:30:43 +00001969
Reid Klecknerd61a3112014-12-15 23:16:32 +00001970 // Function definitions are only allowed at file scope and in C++ classes.
1971 // The C++ inline method definition case is handled elsewhere, so we only
1972 // need to handle the file scope definition case.
Faisal Vali421b2d12017-12-29 05:41:00 +00001973 if (Context == DeclaratorContext::FileContext) {
Douglas Gregor012efe22013-04-16 16:01:32 +00001974 if (isStartOfFunctionDefinition(D)) {
1975 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1976 Diag(Tok, diag::err_function_declared_typedef);
John McCalld5a36322009-11-03 19:26:08 +00001977
Douglas Gregor012efe22013-04-16 16:01:32 +00001978 // Recover by treating the 'typedef' as spurious.
1979 DS.ClearStorageClassSpecs();
1980 }
1981
1982 Decl *TheDecl =
1983 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1984 return Actions.ConvertDeclToDeclGroup(TheDecl);
John McCalld5a36322009-11-03 19:26:08 +00001985 }
1986
Douglas Gregor012efe22013-04-16 16:01:32 +00001987 if (isDeclarationSpecifier()) {
Nico Weber6b05f382015-02-18 04:53:03 +00001988 // If there is an invalid declaration specifier right after the
1989 // function prototype, then we must be in a missing semicolon case
1990 // where this isn't actually a body. Just fall through into the code
1991 // that handles it as a prototype, and let the top-level code handle
1992 // the erroneous declspec where it would otherwise expect a comma or
1993 // semicolon.
Douglas Gregor012efe22013-04-16 16:01:32 +00001994 } else {
1995 Diag(Tok, diag::err_expected_fn_body);
1996 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00001997 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00001998 }
John McCalld5a36322009-11-03 19:26:08 +00001999 } else {
Douglas Gregor012efe22013-04-16 16:01:32 +00002000 if (Tok.is(tok::l_brace)) {
2001 Diag(Tok, diag::err_function_definition_not_allowed);
Serge Pavlov1de51512013-12-09 05:25:47 +00002002 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00002003 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00002004 }
John McCalld5a36322009-11-03 19:26:08 +00002005 }
2006 }
2007
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002008 if (ParseAsmAttributesAfterDeclarator(D))
David Blaikie0403cb12016-01-15 23:43:25 +00002009 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00002010
2011 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2012 // must parse and analyze the for-range-initializer before the declaration is
2013 // analyzed.
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002014 //
2015 // Handle the Objective-C for-in loop variable similarly, although we
2016 // don't need to parse the container in advance.
2017 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2018 bool IsForRangeLoop = false;
Alp Toker8fbec672013-12-17 23:29:36 +00002019 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002020 IsForRangeLoop = true;
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002021 if (Tok.is(tok::l_brace))
2022 FRI->RangeExpr = ParseBraceInitializer();
2023 else
2024 FRI->RangeExpr = ParseExpression();
2025 }
2026
Richard Smith02e85f32011-04-14 22:09:26 +00002027 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
George Karpenkovec38cf72018-03-29 00:56:24 +00002028 if (IsForRangeLoop) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002029 Actions.ActOnCXXForRangeDecl(ThisDecl);
George Karpenkovec38cf72018-03-29 00:56:24 +00002030 } else {
2031 // Obj-C for loop
2032 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2033 VD->setObjCForDecl(true);
2034 }
Richard Smith02e85f32011-04-14 22:09:26 +00002035 Actions.FinalizeDeclaration(ThisDecl);
John McCallcf6e0c82012-01-27 01:29:43 +00002036 D.complete(ThisDecl);
Rafael Espindolaab417692013-07-09 12:05:01 +00002037 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
Richard Smith02e85f32011-04-14 22:09:26 +00002038 }
2039
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002040 SmallVector<Decl *, 8> DeclsInGroup;
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002041 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2042 D, ParsedTemplateInfo(), FRI);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002043 if (LateParsedAttrs.size() > 0)
2044 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
John McCall28a6aea2009-11-04 02:18:39 +00002045 D.complete(FirstDecl);
John McCall48871652010-08-21 09:40:31 +00002046 if (FirstDecl)
John McCalld5a36322009-11-03 19:26:08 +00002047 DeclsInGroup.push_back(FirstDecl);
2048
Faisal Vali421b2d12017-12-29 05:41:00 +00002049 bool ExpectSemi = Context != DeclaratorContext::ForContext;
Fangrui Song6907ce22018-07-30 19:24:48 +00002050
John McCalld5a36322009-11-03 19:26:08 +00002051 // If we don't have a comma, it is either the end of the list (a ';') or an
2052 // error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00002053 SourceLocation CommaLoc;
2054 while (TryConsumeToken(tok::comma, CommaLoc)) {
Richard Smith09f76ee2011-10-19 21:33:05 +00002055 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2056 // This comma was followed by a line-break and something which can't be
2057 // the start of a declarator. The comma was probably a typo for a
2058 // semicolon.
2059 Diag(CommaLoc, diag::err_expected_semi_declaration)
2060 << FixItHint::CreateReplacement(CommaLoc, ";");
2061 ExpectSemi = false;
2062 break;
2063 }
John McCalld5a36322009-11-03 19:26:08 +00002064
2065 // Parse the next declarator.
2066 D.clear();
Richard Smith8d06f422012-01-12 23:53:29 +00002067 D.setCommaLoc(CommaLoc);
John McCalld5a36322009-11-03 19:26:08 +00002068
2069 // Accept attributes in an init-declarator. In the first declarator in a
2070 // declaration, these would be part of the declspec. In subsequent
2071 // declarators, they become part of the declarator itself, so that they
2072 // don't apply to declarators after *this* one. Examples:
2073 // short __attribute__((common)) var; -> declspec
2074 // short var __attribute__((common)); -> declarator
2075 // short x, __attribute__((common)) var; -> declarator
John McCall53fa7142010-12-24 02:08:15 +00002076 MaybeParseGNUAttributes(D);
John McCalld5a36322009-11-03 19:26:08 +00002077
Nico Rieckeaaae272014-12-04 23:31:08 +00002078 // MSVC parses but ignores qualifiers after the comma as an extension.
2079 if (getLangOpts().MicrosoftExt)
2080 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2081
John McCalld5a36322009-11-03 19:26:08 +00002082 ParseDeclarator(D);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002083 if (!D.isInvalidType()) {
2084 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2085 D.complete(ThisDecl);
2086 if (ThisDecl)
Chad Rosierc1183952012-06-26 22:30:43 +00002087 DeclsInGroup.push_back(ThisDecl);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002088 }
John McCalld5a36322009-11-03 19:26:08 +00002089 }
2090
2091 if (DeclEnd)
2092 *DeclEnd = Tok.getLocation();
2093
Richard Smith09f76ee2011-10-19 21:33:05 +00002094 if (ExpectSemi &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002095 ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
Chris Lattner02f1b612012-04-28 16:12:17 +00002096 ? diag::err_invalid_token_after_toplevel_declarator
2097 : diag::err_expected_semi_declaration)) {
Chris Lattner13901342010-07-11 22:42:07 +00002098 // Okay, there was no semicolon and one was expected. If we see a
2099 // declaration specifier, just assume it was missing and continue parsing.
2100 // Otherwise things are very confused and we skip to recover.
2101 if (!isDeclarationSpecifier()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002102 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Alp Toker8fbec672013-12-17 23:29:36 +00002103 TryConsumeToken(tok::semi);
Chris Lattner13901342010-07-11 22:42:07 +00002104 }
John McCalld5a36322009-11-03 19:26:08 +00002105 }
2106
Rafael Espindolaab417692013-07-09 12:05:01 +00002107 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner53361ac2006-08-10 05:19:57 +00002108}
2109
Richard Smith02e85f32011-04-14 22:09:26 +00002110/// Parse an optional simple-asm-expr and attributes, and attach them to a
2111/// declarator. Returns true on an error.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002112bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
Richard Smith02e85f32011-04-14 22:09:26 +00002113 // If a simple-asm-expr is present, parse it.
2114 if (Tok.is(tok::kw_asm)) {
2115 SourceLocation Loc;
2116 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2117 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002118 SkipUntil(tok::semi, StopBeforeMatch);
Richard Smith02e85f32011-04-14 22:09:26 +00002119 return true;
2120 }
2121
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002122 D.setAsmLabel(AsmLabel.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002123 D.SetRangeEnd(Loc);
2124 }
2125
2126 MaybeParseGNUAttributes(D);
2127 return false;
2128}
2129
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002130/// Parse 'declaration' after parsing 'declaration-specifiers
Douglas Gregor23996282009-05-12 21:31:51 +00002131/// declarator'. This method parses the remainder of the declaration
2132/// (including any attributes or initializer, among other things) and
2133/// finalizes the declaration.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002134///
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002135/// init-declarator: [C99 6.7]
2136/// declarator
2137/// declarator '=' initializer
Chris Lattner6d7e6342006-08-15 03:41:14 +00002138/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2139/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002140/// [C++] declarator initializer[opt]
2141///
2142/// [C++] initializer:
2143/// [C++] '=' initializer-clause
2144/// [C++] '(' expression-list ')'
Sebastian Redlf769df52009-03-24 22:27:57 +00002145/// [C++0x] '=' 'default' [TODO]
2146/// [C++0x] '=' 'delete'
Sebastian Redl3da34892011-06-05 12:23:16 +00002147/// [C++0x] braced-init-list
Sebastian Redlf769df52009-03-24 22:27:57 +00002148///
2149/// According to the standard grammar, =default and =delete are function
2150/// definitions, but that definitely doesn't fit with the parser here.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002151///
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002152Decl *Parser::ParseDeclarationAfterDeclarator(
2153 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002154 if (ParseAsmAttributesAfterDeclarator(D))
Craig Topper161e4db2014-05-21 06:02:52 +00002155 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002156
Richard Smith02e85f32011-04-14 22:09:26 +00002157 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2158}
Mike Stump11289f42009-09-09 15:08:12 +00002159
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002160Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2161 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
Richard Smithc95d2c52017-09-22 04:25:05 +00002162 // RAII type used to track whether we're inside an initializer.
2163 struct InitializerScopeRAII {
2164 Parser &P;
2165 Declarator &D;
2166 Decl *ThisDecl;
2167
2168 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2169 : P(P), D(D), ThisDecl(ThisDecl) {
2170 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2171 Scope *S = nullptr;
2172 if (D.getCXXScopeSpec().isSet()) {
2173 P.EnterScope(0);
2174 S = P.getCurScope();
2175 }
2176 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2177 }
2178 }
2179 ~InitializerScopeRAII() { pop(); }
2180 void pop() {
2181 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2182 Scope *S = nullptr;
2183 if (D.getCXXScopeSpec().isSet())
2184 S = P.getCurScope();
2185 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2186 if (S)
2187 P.ExitScope();
2188 }
2189 ThisDecl = nullptr;
2190 }
2191 };
2192
Douglas Gregor23996282009-05-12 21:31:51 +00002193 // Inform the current actions module that we just parsed this declarator.
Craig Topper161e4db2014-05-21 06:02:52 +00002194 Decl *ThisDecl = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00002195 switch (TemplateInfo.Kind) {
2196 case ParsedTemplateInfo::NonTemplate:
Douglas Gregor0be31a22010-07-02 17:43:08 +00002197 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
Douglas Gregor450f00842009-09-25 18:43:00 +00002198 break;
Chad Rosierc1183952012-06-26 22:30:43 +00002199
Douglas Gregor450f00842009-09-25 18:43:00 +00002200 case ParsedTemplateInfo::Template:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002201 case ParsedTemplateInfo::ExplicitSpecialization: {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002202 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002203 *TemplateInfo.TemplateParams,
Douglas Gregor450f00842009-09-25 18:43:00 +00002204 D);
Larisse Voufo833b05a2013-08-06 07:33:00 +00002205 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002206 // Re-direct this decl to refer to the templated decl so that we can
2207 // initialize it.
2208 ThisDecl = VT->getTemplatedDecl();
2209 break;
2210 }
2211 case ParsedTemplateInfo::ExplicitInstantiation: {
2212 if (Tok.is(tok::semi)) {
2213 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2214 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2215 if (ThisRes.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002216 SkipUntil(tok::semi, StopBeforeMatch);
Craig Topper161e4db2014-05-21 06:02:52 +00002217 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002218 }
2219 ThisDecl = ThisRes.get();
2220 } else {
2221 // FIXME: This check should be for a variable template instantiation only.
2222
2223 // Check that this is a valid instantiation
Faisal Vali2ab8c152017-12-30 04:15:27 +00002224 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002225 // If the declarator-id is not a template-id, issue a diagnostic and
2226 // recover by ignoring the 'template' keyword.
2227 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2228 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2229 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2230 } else {
2231 SourceLocation LAngleLoc =
2232 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2233 Diag(D.getIdentifierLoc(),
2234 diag::err_explicit_instantiation_with_definition)
2235 << SourceRange(TemplateInfo.TemplateLoc)
2236 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2237
2238 // Recover as if it were an explicit specialization.
2239 TemplateParameterLists FakedParamLists;
2240 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00002241 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00002242 LAngleLoc, nullptr));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002243
2244 ThisDecl =
2245 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2246 }
2247 }
Douglas Gregor450f00842009-09-25 18:43:00 +00002248 break;
2249 }
2250 }
Mike Stump11289f42009-09-09 15:08:12 +00002251
Douglas Gregor23996282009-05-12 21:31:51 +00002252 // Parse declarator '=' initializer.
Richard Trieuc64d3232012-01-18 22:54:52 +00002253 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Trieu4972a6d2012-01-19 22:01:51 +00002254 if (isTokenEqualOrEqualTypo()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002255 SourceLocation EqualLoc = ConsumeToken();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002256
Anders Carlsson991285e2010-09-24 21:25:25 +00002257 if (Tok.is(tok::kw_delete)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002258 if (D.isFunctionDeclarator())
2259 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2260 << 1 /* delete */;
2261 else
2262 Diag(ConsumeToken(), diag::err_deleted_non_function);
Alexis Hunt5dafebc2011-05-06 01:42:00 +00002263 } else if (Tok.is(tok::kw_default)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002264 if (D.isFunctionDeclarator())
Sebastian Redl46afb552012-02-11 23:51:21 +00002265 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2266 << 0 /* default */;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002267 else
2268 Diag(ConsumeToken(), diag::err_default_special_members);
Douglas Gregor23996282009-05-12 21:31:51 +00002269 } else {
Richard Smithc95d2c52017-09-22 04:25:05 +00002270 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002271
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002272 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002273 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
Peter Collingbourne6b4fdc22012-07-27 12:56:09 +00002274 Actions.FinalizeDeclaration(ThisDecl);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002275 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +00002276 return nullptr;
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002277 }
Chad Rosierc1183952012-06-26 22:30:43 +00002278
John McCalldadc5752010-08-24 06:29:42 +00002279 ExprResult Init(ParseInitializer());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002280
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002281 // If this is the only decl in (possibly) range based for statement,
2282 // our best guess is that the user meant ':' instead of '='.
2283 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2284 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2285 << FixItHint::CreateReplacement(EqualLoc, ":");
2286 // We are trying to stop parser from looking for ';' in this for
2287 // statement, therefore preventing spurious errors to be issued.
2288 FRI->ColonLoc = EqualLoc;
2289 Init = ExprError();
2290 FRI->RangeExpr = Init;
2291 }
2292
Richard Smithc95d2c52017-09-22 04:25:05 +00002293 InitScope.pop();
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002294
Douglas Gregor23996282009-05-12 21:31:51 +00002295 if (Init.isInvalid()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002296 SmallVector<tok::TokenKind, 2> StopTokens;
2297 StopTokens.push_back(tok::comma);
Faisal Vali421b2d12017-12-29 05:41:00 +00002298 if (D.getContext() == DeclaratorContext::ForContext ||
2299 D.getContext() == DeclaratorContext::InitStmtContext)
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002300 StopTokens.push_back(tok::r_paren);
2301 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
Douglas Gregor604c3022010-03-01 18:27:54 +00002302 Actions.ActOnInitializerError(ThisDecl);
2303 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002304 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002305 /*DirectInit=*/false);
Douglas Gregor23996282009-05-12 21:31:51 +00002306 }
2307 } else if (Tok.is(tok::l_paren)) {
2308 // Parse C++ direct initializer: '(' expression-list ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002309 BalancedDelimiterTracker T(*this, tok::l_paren);
2310 T.consumeOpen();
2311
Benjamin Kramerf0623432012-08-23 22:51:59 +00002312 ExprVector Exprs;
Douglas Gregor23996282009-05-12 21:31:51 +00002313 CommaLocsTy CommaLocs;
2314
Richard Smithc95d2c52017-09-22 04:25:05 +00002315 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Douglas Gregor613bf102009-12-22 17:47:17 +00002316
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002317 llvm::function_ref<void()> ExprListCompleter;
2318 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2319 auto ConstructorCompleter = [&, ThisVarDecl] {
Ilya Biryukov832c4af2018-09-07 14:04:39 +00002320 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002321 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
Ilya Biryukov2fab2352018-08-30 13:08:03 +00002322 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002323 CalledSignatureHelp = true;
Ilya Biryukov832c4af2018-09-07 14:04:39 +00002324 Actions.CodeCompleteExpression(getCurScope(), PreferredType);
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002325 };
2326 if (ThisVarDecl) {
2327 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2328 // VarDecl. This is an error and it is reported in a call to
2329 // Actions.ActOnInitializerError(). However, we call
Ilya Biryukov832c4af2018-09-07 14:04:39 +00002330 // ProduceConstructorSignatureHelp only on VarDecls, falling back to
2331 // default completer in other cases.
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002332 ExprListCompleter = ConstructorCompleter;
2333 }
2334
2335 if (ParseExpressionList(Exprs, CommaLocs, ExprListCompleter)) {
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002336 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2337 Actions.ProduceConstructorSignatureHelp(
2338 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2339 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2340 CalledSignatureHelp = true;
2341 }
David Blaikieeae04112012-10-10 23:15:05 +00002342 Actions.ActOnInitializerError(ThisDecl);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002343 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor23996282009-05-12 21:31:51 +00002344 } else {
2345 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002346 T.consumeClose();
Douglas Gregor23996282009-05-12 21:31:51 +00002347
2348 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2349 "Unexpected number of commas!");
Douglas Gregor613bf102009-12-22 17:47:17 +00002350
Richard Smithc95d2c52017-09-22 04:25:05 +00002351 InitScope.pop();
Douglas Gregor613bf102009-12-22 17:47:17 +00002352
Sebastian Redla9351792012-02-11 23:51:47 +00002353 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2354 T.getCloseLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002355 Exprs);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002356 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002357 /*DirectInit=*/true);
Douglas Gregor23996282009-05-12 21:31:51 +00002358 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002359 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
Fariborz Jahanian8be1ecd2012-07-03 23:22:13 +00002360 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
Sebastian Redl3da34892011-06-05 12:23:16 +00002361 // Parse C++0x braced-init-list.
Richard Smith5d164bc2011-10-15 05:09:34 +00002362 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2363
Richard Smithc95d2c52017-09-22 04:25:05 +00002364 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Sebastian Redl3da34892011-06-05 12:23:16 +00002365
2366 ExprResult Init(ParseBraceInitializer());
2367
Richard Smithc95d2c52017-09-22 04:25:05 +00002368 InitScope.pop();
Sebastian Redl3da34892011-06-05 12:23:16 +00002369
2370 if (Init.isInvalid()) {
2371 Actions.ActOnInitializerError(ThisDecl);
2372 } else
Richard Smith3beb7c62017-01-12 02:27:38 +00002373 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
Sebastian Redl3da34892011-06-05 12:23:16 +00002374
Douglas Gregor23996282009-05-12 21:31:51 +00002375 } else {
Richard Smith3beb7c62017-01-12 02:27:38 +00002376 Actions.ActOnUninitializedDecl(ThisDecl);
Douglas Gregor23996282009-05-12 21:31:51 +00002377 }
2378
Richard Smithb2bc2e62011-02-21 20:05:19 +00002379 Actions.FinalizeDeclaration(ThisDecl);
2380
Douglas Gregor23996282009-05-12 21:31:51 +00002381 return ThisDecl;
2382}
2383
Chris Lattner1890ac82006-08-13 01:16:23 +00002384/// ParseSpecifierQualifierList
2385/// specifier-qualifier-list:
2386/// type-specifier specifier-qualifier-list[opt]
2387/// type-qualifier specifier-qualifier-list[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002388/// [GNU] attributes specifier-qualifier-list[opt]
Chris Lattner1890ac82006-08-13 01:16:23 +00002389///
Richard Smithc5b05522012-03-12 07:56:15 +00002390void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2391 DeclSpecContext DSC) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002392 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2393 /// parse declaration-specifiers and complain about extra stuff.
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002394 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
Faisal Valia534f072018-04-26 00:42:40 +00002395 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
Mike Stump11289f42009-09-09 15:08:12 +00002396
Chris Lattner1890ac82006-08-13 01:16:23 +00002397 // Validate declspec for type-name.
2398 unsigned Specs = DS.getParsedSpecifiers();
Richard Smith649c7b062014-01-08 00:56:48 +00002399 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
Richard Smithc5b05522012-03-12 07:56:15 +00002400 Diag(Tok, diag::err_expected_type);
2401 DS.SetTypeSpecError();
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00002402 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002403 Diag(Tok, diag::err_typename_requires_specqual);
Richard Smithc5b05522012-03-12 07:56:15 +00002404 if (!DS.hasTypeSpecifier())
2405 DS.SetTypeSpecError();
2406 }
Mike Stump11289f42009-09-09 15:08:12 +00002407
Chris Lattner1b22eed2006-11-28 05:12:07 +00002408 // Issue diagnostic and remove storage class if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002409 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
Chris Lattner1b22eed2006-11-28 05:12:07 +00002410 if (DS.getStorageClassSpecLoc().isValid())
2411 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2412 else
Richard Smithb4a9e862013-04-12 22:46:28 +00002413 Diag(DS.getThreadStorageClassSpecLoc(),
2414 diag::err_typename_invalid_storageclass);
Chris Lattnera925dc62006-11-28 04:33:46 +00002415 DS.ClearStorageClassSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002416 }
Mike Stump11289f42009-09-09 15:08:12 +00002417
Craig Topper3f13d4d22015-11-14 18:15:55 +00002418 // Issue diagnostic and remove function specifier if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002419 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
Douglas Gregor61956c42008-10-31 09:07:45 +00002420 if (DS.isInlineSpecified())
2421 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2422 if (DS.isVirtualSpecified())
2423 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2424 if (DS.isExplicitSpecified())
2425 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
Chris Lattnera925dc62006-11-28 04:33:46 +00002426 DS.ClearFunctionSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002427 }
Richard Smithc5b05522012-03-12 07:56:15 +00002428
2429 // Issue diagnostic and remove constexpr specfier if present.
Faisal Vali7db85c52017-12-31 00:06:40 +00002430 if (DS.isConstexprSpecified() && DSC != DeclSpecContext::DSC_condition) {
Richard Smithc5b05522012-03-12 07:56:15 +00002431 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2432 DS.ClearConstexprSpec();
2433 }
Chris Lattner1890ac82006-08-13 01:16:23 +00002434}
Chris Lattner53361ac2006-08-10 05:19:57 +00002435
Chris Lattner6cc055a2009-04-12 20:42:31 +00002436/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2437/// specified token is valid after the identifier in a declarator which
2438/// immediately follows the declspec. For example, these things are valid:
2439///
2440/// int x [ 4]; // direct-declarator
2441/// int x ( int y); // direct-declarator
2442/// int(int x ) // direct-declarator
2443/// int x ; // simple-declaration
2444/// int x = 17; // init-declarator-list
2445/// int x , y; // init-declarator-list
2446/// int x __asm__ ("foo"); // init-declarator-list
Chris Lattnera723ba92009-04-14 21:16:09 +00002447/// int x : 4; // struct-declarator
Chris Lattner2b988c12009-04-12 22:29:43 +00002448/// int x { 5}; // C++'0x unified initializers
Chris Lattner6cc055a2009-04-12 20:42:31 +00002449///
2450/// This is not, because 'x' does not immediately follow the declspec (though
2451/// ')' happens to be valid anyway).
2452/// int (x)
2453///
2454static bool isValidAfterIdentifierInDeclarator(const Token &T) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002455 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2456 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2457 tok::colon);
Chris Lattner6cc055a2009-04-12 20:42:31 +00002458}
2459
Chris Lattner20a0c612009-04-14 21:34:55 +00002460/// ParseImplicitInt - This method is called when we have an non-typename
2461/// identifier in a declspec (which normally terminates the decl spec) when
2462/// the declspec has no type specifier. In this case, the declspec is either
2463/// malformed or is "implicit int" (in K&R and C89).
2464///
2465/// This method handles diagnosing this prettily and returns false if the
2466/// declspec is done being processed. If it recovers and thinks there may be
2467/// other pieces of declspec after it, it returns true.
2468///
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002469bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002470 const ParsedTemplateInfo &TemplateInfo,
Richard Smitha0a5d502014-05-08 22:32:00 +00002471 AccessSpecifier AS, DeclSpecContext DSC,
Michael Han9407e502012-11-26 22:54:45 +00002472 ParsedAttributesWithRange &Attrs) {
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002473 assert(Tok.is(tok::identifier) && "should have identifier");
Mike Stump11289f42009-09-09 15:08:12 +00002474
Chris Lattner20a0c612009-04-14 21:34:55 +00002475 SourceLocation Loc = Tok.getLocation();
2476 // If we see an identifier that is not a type name, we normally would
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002477 // parse it as the identifier being declared. However, when a typename
Chris Lattner20a0c612009-04-14 21:34:55 +00002478 // is typo'd or the definition is not included, this will incorrectly
2479 // parse the typename as the identifier name and fall over misparsing
2480 // later parts of the diagnostic.
2481 //
2482 // As such, we try to do some look-ahead in cases where this would
2483 // otherwise be an "implicit-int" case to see if this is invalid. For
2484 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2485 // an identifier with implicit int, we'd get a parse error because the
2486 // next token is obviously invalid for a type. Parse these as a case
2487 // with an invalid type specifier.
2488 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
Mike Stump11289f42009-09-09 15:08:12 +00002489
Chris Lattner20a0c612009-04-14 21:34:55 +00002490 // Since we know that this either implicit int (which is rare) or an
Richard Smitha952ebb2012-05-15 21:01:51 +00002491 // error, do lookahead to try to do better recovery. This never applies
2492 // within a type specifier. Outside of C++, we allow this even if the
2493 // language doesn't "officially" support implicit int -- we support
Richard Smith3b870382013-04-30 22:43:51 +00002494 // implicit int as an extension in C99 and C11.
Richard Smith649c7b062014-01-08 00:56:48 +00002495 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
Richard Smithc5b05522012-03-12 07:56:15 +00002496 isValidAfterIdentifierInDeclarator(NextToken())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002497 // If this token is valid for implicit int, e.g. "static x = 4", then
2498 // we just avoid eating the identifier, so it will be parsed as the
2499 // identifier in the declarator.
2500 return false;
2501 }
Mike Stump11289f42009-09-09 15:08:12 +00002502
Richard Smitha952ebb2012-05-15 21:01:51 +00002503 if (getLangOpts().CPlusPlus &&
2504 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2505 // Don't require a type specifier if we have the 'auto' storage class
2506 // specifier in C++98 -- we'll promote it to a type specifier.
Richard Smithfb8b7b92013-10-15 00:00:26 +00002507 if (SS)
2508 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
Richard Smitha952ebb2012-05-15 21:01:51 +00002509 return false;
2510 }
2511
Reid Kleckner9a96e422016-05-24 21:23:54 +00002512 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2513 getLangOpts().MSVCCompat) {
2514 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2515 // Give Sema a chance to recover if we are in a template with dependent base
2516 // classes.
2517 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2518 *Tok.getIdentifierInfo(), Tok.getLocation(),
Faisal Vali7db85c52017-12-31 00:06:40 +00002519 DSC == DeclSpecContext::DSC_template_type_arg)) {
Reid Kleckner9a96e422016-05-24 21:23:54 +00002520 const char *PrevSpec;
2521 unsigned DiagID;
2522 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2523 Actions.getASTContext().getPrintingPolicy());
2524 DS.SetRangeEnd(Tok.getLocation());
2525 ConsumeToken();
2526 return false;
2527 }
2528 }
2529
Chris Lattner20a0c612009-04-14 21:34:55 +00002530 // Otherwise, if we don't consume this token, we are going to emit an
2531 // error anyway. Try to recover from various common problems. Check
2532 // to see if this was a reference to a tag name without a tag specified.
2533 // This is a common problem in C (saying 'foo' instead of 'struct foo').
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002534 //
2535 // C++ doesn't need this, and isTagName doesn't take SS.
Craig Topper161e4db2014-05-21 06:02:52 +00002536 if (SS == nullptr) {
2537 const char *TagName = nullptr, *FixitTagName = nullptr;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002538 tok::TokenKind TagKind = tok::unknown;
Mike Stump11289f42009-09-09 15:08:12 +00002539
Douglas Gregor0be31a22010-07-02 17:43:08 +00002540 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002541 default: break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002542 case DeclSpec::TST_enum:
2543 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2544 case DeclSpec::TST_union:
2545 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2546 case DeclSpec::TST_struct:
2547 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
Joao Matosdc86f942012-08-31 18:45:21 +00002548 case DeclSpec::TST_interface:
2549 TagName="__interface"; FixitTagName = "__interface ";
2550 TagKind=tok::kw___interface;break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002551 case DeclSpec::TST_class:
2552 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
Chris Lattner20a0c612009-04-14 21:34:55 +00002553 }
Mike Stump11289f42009-09-09 15:08:12 +00002554
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002555 if (TagName) {
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002556 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2557 LookupResult R(Actions, TokenName, SourceLocation(),
2558 Sema::LookupOrdinaryName);
2559
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002560 Diag(Loc, diag::err_use_of_tag_name_without_tag)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002561 << TokenName << TagName << getLangOpts().CPlusPlus
2562 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2563
2564 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2565 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2566 I != IEnd; ++I)
Kaelyn Uhrain3fe3f852012-04-27 18:26:49 +00002567 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002568 << TokenName << TagName;
2569 }
Mike Stump11289f42009-09-09 15:08:12 +00002570
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002571 // Parse this as a tag as if the missing tag were present.
2572 if (TagKind == tok::kw_enum)
Faisal Vali7db85c52017-12-31 00:06:40 +00002573 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2574 DeclSpecContext::DSC_normal);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002575 else
Richard Smithc5b05522012-03-12 07:56:15 +00002576 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
Faisal Vali7db85c52017-12-31 00:06:40 +00002577 /*EnteringContext*/ false,
2578 DeclSpecContext::DSC_normal, Attrs);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002579 return true;
2580 }
Chris Lattner20a0c612009-04-14 21:34:55 +00002581 }
Mike Stump11289f42009-09-09 15:08:12 +00002582
Richard Smithfe904f02012-05-15 21:29:55 +00002583 // Determine whether this identifier could plausibly be the name of something
Richard Smithedd124e2012-05-15 21:42:17 +00002584 // being declared (with a missing type).
Faisal Vali7db85c52017-12-31 00:06:40 +00002585 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2586 DSC == DeclSpecContext::DSC_class)) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002587 // Look ahead to the next token to try to figure out what this declaration
2588 // was supposed to be.
2589 switch (NextToken().getKind()) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002590 case tok::l_paren: {
2591 // static x(4); // 'x' is not a type
2592 // x(int n); // 'x' is not a type
2593 // x (*p)[]; // 'x' is a type
2594 //
Richard Smitha0a5d502014-05-08 22:32:00 +00002595 // Since we're in an error case, we can afford to perform a tentative
2596 // parse to determine which case we're in.
Richard Smitha952ebb2012-05-15 21:01:51 +00002597 TentativeParsingAction PA(*this);
2598 ConsumeToken();
2599 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2600 PA.Revert();
Richard Smithfb8b7b92013-10-15 00:00:26 +00002601
Richard Smithee390432014-05-16 01:56:53 +00002602 if (TPR != TPResult::False) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002603 // The identifier is followed by a parenthesized declarator.
2604 // It's supposed to be a type.
2605 break;
2606 }
2607
2608 // If we're in a context where we could be declaring a constructor,
2609 // check whether this is a constructor declaration with a bogus name.
Faisal Vali7db85c52017-12-31 00:06:40 +00002610 if (DSC == DeclSpecContext::DSC_class ||
2611 (DSC == DeclSpecContext::DSC_top_level && SS)) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002612 IdentifierInfo *II = Tok.getIdentifierInfo();
2613 if (Actions.isCurrentClassNameTypo(II, SS)) {
2614 Diag(Loc, diag::err_constructor_bad_name)
2615 << Tok.getIdentifierInfo() << II
2616 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2617 Tok.setIdentifierInfo(II);
2618 }
2619 }
2620 // Fall through.
Galina Kistanova77674252017-06-01 21:15:34 +00002621 LLVM_FALLTHROUGH;
Richard Smitha952ebb2012-05-15 21:01:51 +00002622 }
Richard Smithfb8b7b92013-10-15 00:00:26 +00002623 case tok::comma:
2624 case tok::equal:
2625 case tok::kw_asm:
2626 case tok::l_brace:
2627 case tok::l_square:
2628 case tok::semi:
2629 // This looks like a variable or function declaration. The type is
2630 // probably missing. We're done parsing decl-specifiers.
2631 if (SS)
2632 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2633 return false;
Richard Smitha952ebb2012-05-15 21:01:51 +00002634
2635 default:
2636 // This is probably supposed to be a type. This includes cases like:
2637 // int f(itn);
2638 // struct S { unsinged : 4; };
2639 break;
2640 }
2641 }
2642
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002643 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2644 // and attempt to recover.
John McCallba7bf592010-08-24 05:47:05 +00002645 ParsedType T;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +00002646 IdentifierInfo *II = Tok.getIdentifierInfo();
Richard Smith52f8d192017-05-10 21:32:16 +00002647 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002648 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
Richard Smith52f8d192017-05-10 21:32:16 +00002649 IsTemplateName);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002650 if (T) {
2651 // The action has suggested that the type T could be used. Set that as
2652 // the type in the declaration specifiers, consume the would-be type
2653 // name token, and we're done.
2654 const char *PrevSpec;
2655 unsigned DiagID;
2656 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2657 Actions.getASTContext().getPrintingPolicy());
2658 DS.SetRangeEnd(Tok.getLocation());
2659 ConsumeToken();
2660 // There may be other declaration specifiers after this.
2661 return true;
2662 } else if (II != Tok.getIdentifierInfo()) {
2663 // If no type was suggested, the correction is to a keyword
2664 Tok.setKind(II->getTokenID());
2665 // There may be other declaration specifiers after this.
2666 return true;
Douglas Gregor15e56022009-10-13 23:27:22 +00002667 }
Mike Stump11289f42009-09-09 15:08:12 +00002668
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002669 // Otherwise, the action had no suggestion for us. Mark this as an error.
Richard Smithc5b05522012-03-12 07:56:15 +00002670 DS.SetTypeSpecError();
Chris Lattner20a0c612009-04-14 21:34:55 +00002671 DS.SetRangeEnd(Tok.getLocation());
2672 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002673
Richard Smith52f8d192017-05-10 21:32:16 +00002674 // Eat any following template arguments.
2675 if (IsTemplateName) {
2676 SourceLocation LAngle, RAngle;
2677 TemplateArgList Args;
2678 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2679 }
2680
Chris Lattner20a0c612009-04-14 21:34:55 +00002681 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2682 // avoid rippling error messages on subsequent uses of the same type,
2683 // could be useful if #include was forgotten.
2684 return false;
2685}
2686
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002687/// Determine the declaration specifier context from the declarator
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002688/// context.
2689///
2690/// \param Context the declarator context, which is one of the
Faisal Vali421b2d12017-12-29 05:41:00 +00002691/// DeclaratorContext enumerator values.
Chad Rosierc1183952012-06-26 22:30:43 +00002692Parser::DeclSpecContext
Faisal Vali421b2d12017-12-29 05:41:00 +00002693Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2694 if (Context == DeclaratorContext::MemberContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002695 return DeclSpecContext::DSC_class;
Faisal Vali421b2d12017-12-29 05:41:00 +00002696 if (Context == DeclaratorContext::FileContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002697 return DeclSpecContext::DSC_top_level;
Faisal Vali421b2d12017-12-29 05:41:00 +00002698 if (Context == DeclaratorContext::TemplateParamContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002699 return DeclSpecContext::DSC_template_param;
Richard Smith77a9c602018-02-28 03:02:23 +00002700 if (Context == DeclaratorContext::TemplateArgContext ||
2701 Context == DeclaratorContext::TemplateTypeArgContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002702 return DeclSpecContext::DSC_template_type_arg;
Richard Smithe303e352018-02-02 22:24:54 +00002703 if (Context == DeclaratorContext::TrailingReturnContext ||
2704 Context == DeclaratorContext::TrailingReturnVarContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002705 return DeclSpecContext::DSC_trailing;
Faisal Vali421b2d12017-12-29 05:41:00 +00002706 if (Context == DeclaratorContext::AliasDeclContext ||
2707 Context == DeclaratorContext::AliasTemplateContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002708 return DeclSpecContext::DSC_alias_declaration;
2709 return DeclSpecContext::DSC_normal;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002710}
2711
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002712/// ParseAlignArgument - Parse the argument to an alignment-specifier.
2713///
2714/// FIXME: Simply returns an alignof() expression if the argument is a
2715/// type. Ideally, the type should be propagated directly into Sema.
2716///
Benjamin Kramere56f3932011-12-23 17:00:35 +00002717/// [C11] type-id
2718/// [C11] constant-expression
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002719/// [C++0x] type-id ...[opt]
2720/// [C++0x] assignment-expression ...[opt]
2721ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2722 SourceLocation &EllipsisLoc) {
2723 ExprResult ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002724 if (isTypeIdInParens()) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002725 SourceLocation TypeLoc = Tok.getLocation();
2726 ParsedType Ty = ParseTypeName().get();
2727 SourceRange TypeRange(Start, Tok.getLocation());
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002728 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2729 Ty.getAsOpaquePtr(), TypeRange);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002730 } else
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002731 ER = ParseConstantExpression();
2732
Alp Toker8fbec672013-12-17 23:29:36 +00002733 if (getLangOpts().CPlusPlus11)
2734 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002735
2736 return ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002737}
2738
2739/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2740/// attribute to Attrs.
2741///
2742/// alignment-specifier:
Benjamin Kramere56f3932011-12-23 17:00:35 +00002743/// [C11] '_Alignas' '(' type-id ')'
2744/// [C11] '_Alignas' '(' constant-expression ')'
Richard Smithd11c7a12013-01-29 01:48:07 +00002745/// [C++11] 'alignas' '(' type-id ...[opt] ')'
2746/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002747void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
Richard Smith44c247f2013-02-22 08:32:16 +00002748 SourceLocation *EndLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002749 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002750 "Not an alignment-specifier!");
2751
Richard Smithd11c7a12013-01-29 01:48:07 +00002752 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2753 SourceLocation KWLoc = ConsumeToken();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002754
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002755 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002756 if (T.expectAndConsume())
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002757 return;
2758
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002759 SourceLocation EllipsisLoc;
2760 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002761 if (ArgExpr.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002762 T.skipToEnd();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002763 return;
2764 }
2765
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002766 T.consumeClose();
Richard Smith44c247f2013-02-22 08:32:16 +00002767 if (EndLoc)
2768 *EndLoc = T.getCloseLocation();
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002769
Aaron Ballman00e99962013-08-31 01:11:41 +00002770 ArgsVector ArgExprs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002771 ArgExprs.push_back(ArgExpr.get());
Craig Topper161e4db2014-05-21 06:02:52 +00002772 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
Erich Keanee891aa92018-07-13 15:07:47 +00002773 ParsedAttr::AS_Keyword, EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002774}
2775
Richard Smith404dfb42013-11-19 22:47:36 +00002776/// Determine whether we're looking at something that might be a declarator
2777/// in a simple-declaration. If it can't possibly be a declarator, maybe
2778/// diagnose a missing semicolon after a prior tag definition in the decl
2779/// specifier.
2780///
2781/// \return \c true if an error occurred and this can't be any kind of
2782/// declaration.
2783bool
2784Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2785 DeclSpecContext DSContext,
2786 LateParsedAttrList *LateAttrs) {
2787 assert(DS.hasTagDefinition() && "shouldn't call this");
2788
Faisal Vali7db85c52017-12-31 00:06:40 +00002789 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2790 DSContext == DeclSpecContext::DSC_top_level);
Richard Smith404dfb42013-11-19 22:47:36 +00002791
2792 if (getLangOpts().CPlusPlus &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002793 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2794 tok::annot_template_id) &&
Richard Smith404dfb42013-11-19 22:47:36 +00002795 TryAnnotateCXXScopeToken(EnteringContext)) {
2796 SkipMalformedDecl();
2797 return true;
2798 }
2799
Richard Smith698875a2013-11-20 23:40:57 +00002800 bool HasScope = Tok.is(tok::annot_cxxscope);
2801 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2802 Token AfterScope = HasScope ? NextToken() : Tok;
2803
Richard Smith404dfb42013-11-19 22:47:36 +00002804 // Determine whether the following tokens could possibly be a
2805 // declarator.
Richard Smith698875a2013-11-20 23:40:57 +00002806 bool MightBeDeclarator = true;
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002807 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
Richard Smith698875a2013-11-20 23:40:57 +00002808 // A declarator-id can't start with 'typename'.
2809 MightBeDeclarator = false;
2810 } else if (AfterScope.is(tok::annot_template_id)) {
2811 // If we have a type expressed as a template-id, this cannot be a
2812 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2813 TemplateIdAnnotation *Annot =
2814 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2815 if (Annot->Kind == TNK_Type_template)
2816 MightBeDeclarator = false;
2817 } else if (AfterScope.is(tok::identifier)) {
2818 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2819
Richard Smith404dfb42013-11-19 22:47:36 +00002820 // These tokens cannot come after the declarator-id in a
2821 // simple-declaration, and are likely to come after a type-specifier.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002822 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2823 tok::annot_cxxscope, tok::coloncolon)) {
Richard Smith698875a2013-11-20 23:40:57 +00002824 // Missing a semicolon.
2825 MightBeDeclarator = false;
2826 } else if (HasScope) {
2827 // If the declarator-id has a scope specifier, it must redeclare a
2828 // previously-declared entity. If that's a type (and this is not a
2829 // typedef), that's an error.
2830 CXXScopeSpec SS;
2831 Actions.RestoreNestedNameSpecifierAnnotation(
2832 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2833 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2834 Sema::NameClassification Classification = Actions.ClassifyName(
2835 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2836 /*IsAddressOfOperand*/false);
2837 switch (Classification.getKind()) {
2838 case Sema::NC_Error:
2839 SkipMalformedDecl();
2840 return true;
Richard Smith404dfb42013-11-19 22:47:36 +00002841
Richard Smith698875a2013-11-20 23:40:57 +00002842 case Sema::NC_Keyword:
2843 case Sema::NC_NestedNameSpecifier:
2844 llvm_unreachable("typo correction and nested name specifiers not "
2845 "possible here");
Richard Smith404dfb42013-11-19 22:47:36 +00002846
Richard Smith698875a2013-11-20 23:40:57 +00002847 case Sema::NC_Type:
2848 case Sema::NC_TypeTemplate:
2849 // Not a previously-declared non-type entity.
2850 MightBeDeclarator = false;
2851 break;
Richard Smith404dfb42013-11-19 22:47:36 +00002852
Richard Smith698875a2013-11-20 23:40:57 +00002853 case Sema::NC_Unknown:
2854 case Sema::NC_Expression:
2855 case Sema::NC_VarTemplate:
2856 case Sema::NC_FunctionTemplate:
2857 // Might be a redeclaration of a prior entity.
2858 break;
2859 }
Richard Smith404dfb42013-11-19 22:47:36 +00002860 }
Richard Smith404dfb42013-11-19 22:47:36 +00002861 }
2862
Richard Smith698875a2013-11-20 23:40:57 +00002863 if (MightBeDeclarator)
Richard Smith404dfb42013-11-19 22:47:36 +00002864 return false;
2865
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002866 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002867 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
Alp Toker383d2c42014-01-01 03:08:43 +00002868 diag::err_expected_after)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002869 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
Richard Smith404dfb42013-11-19 22:47:36 +00002870
2871 // Try to recover from the typo, by dropping the tag definition and parsing
2872 // the problematic tokens as a type.
2873 //
2874 // FIXME: Split the DeclSpec into pieces for the standalone
2875 // declaration and pieces for the following declaration, instead
2876 // of assuming that all the other pieces attach to new declaration,
2877 // and call ParsedFreeStandingDeclSpec as appropriate.
2878 DS.ClearTypeSpecType();
2879 ParsedTemplateInfo NotATemplate;
Faisal Valia534f072018-04-26 00:42:40 +00002880 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
Richard Smith404dfb42013-11-19 22:47:36 +00002881 return false;
2882}
2883
Leonard Chanab80f3c2018-06-14 14:53:51 +00002884// Choose the apprpriate diagnostic error for why fixed point types are
2885// disabled, set the previous specifier, and mark as invalid.
2886static void SetupFixedPointError(const LangOptions &LangOpts,
2887 const char *&PrevSpec, unsigned &DiagID,
2888 bool &isInvalid) {
2889 assert(!LangOpts.FixedPoint);
2890 DiagID = diag::err_fixed_point_not_enabled;
2891 PrevSpec = ""; // Not used by diagnostic
2892 isInvalid = true;
2893}
2894
Faisal Valia534f072018-04-26 00:42:40 +00002895/// ParseDeclarationSpecifiers
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002896/// declaration-specifiers: [C99 6.7]
Chris Lattner3b561a32006-08-13 00:12:11 +00002897/// storage-class-specifier declaration-specifiers[opt]
2898/// type-specifier declaration-specifiers[opt]
Chris Lattner3b561a32006-08-13 00:12:11 +00002899/// [C99] function-specifier declaration-specifiers[opt]
Benjamin Kramere56f3932011-12-23 17:00:35 +00002900/// [C11] alignment-specifier declaration-specifiers[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002901/// [GNU] attributes declaration-specifiers[opt]
Douglas Gregor26701a42011-09-09 02:06:17 +00002902/// [Clang] '__module_private__' declaration-specifiers[opt]
Douglas Gregorab209d82015-07-07 03:58:42 +00002903/// [ObjC1] '__kindof' declaration-specifiers[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002904///
Chris Lattnerf63f89a2006-08-05 03:28:50 +00002905/// storage-class-specifier: [C99 6.7.1]
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002906/// 'typedef'
2907/// 'extern'
2908/// 'static'
2909/// 'auto'
2910/// 'register'
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002911/// [C++] 'mutable'
Richard Smithb4a9e862013-04-12 22:46:28 +00002912/// [C++11] 'thread_local'
2913/// [C11] '_Thread_local'
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002914/// [GNU] '__thread'
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002915/// function-specifier: [C99 6.7.4]
Chris Lattner3b561a32006-08-13 00:12:11 +00002916/// [C99] 'inline'
Douglas Gregor61956c42008-10-31 09:07:45 +00002917/// [C++] 'virtual'
2918/// [C++] 'explicit'
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00002919/// [OpenCL] '__kernel'
Anders Carlssoncd8db412009-05-06 04:46:28 +00002920/// 'friend': [C++ dcl.friend]
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00002921/// 'constexpr': [C++0x dcl.constexpr]
Faisal Valia534f072018-04-26 00:42:40 +00002922void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002923 const ParsedTemplateInfo &TemplateInfo,
John McCall07e91c02009-08-06 02:15:43 +00002924 AccessSpecifier AS,
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002925 DeclSpecContext DSContext,
2926 LateParsedAttrList *LateAttrs) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002927 if (DS.getSourceRange().isInvalid()) {
David Majnemer24b28302014-07-26 05:41:31 +00002928 // Start the range at the current token but make the end of the range
2929 // invalid. This will make the entire range invalid unless we successfully
2930 // consume a token.
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002931 DS.SetRangeStart(Tok.getLocation());
David Majnemer24b28302014-07-26 05:41:31 +00002932 DS.SetRangeEnd(SourceLocation());
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002933 }
Chad Rosierc1183952012-06-26 22:30:43 +00002934
Faisal Vali7db85c52017-12-31 00:06:40 +00002935 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2936 DSContext == DeclSpecContext::DSC_top_level);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002937 bool AttrsLastTime = false;
2938 ParsedAttributesWithRange attrs(AttrFactory);
Benjamin Kramere4812142015-03-12 14:28:38 +00002939 // We use Sema's policy to get bool macros right.
Richard Smith301bc212016-05-19 01:39:10 +00002940 PrintingPolicy Policy = Actions.getPrintingPolicy();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002941 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00002942 bool isInvalid = false;
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00002943 bool isStorageClass = false;
Craig Topper161e4db2014-05-21 06:02:52 +00002944 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00002945 unsigned DiagID = 0;
2946
David Majnemer51fd8a02015-07-22 23:46:18 +00002947 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2948 // implementation for VS2013 uses _Atomic as an identifier for one of the
2949 // classes in <atomic>.
2950 //
2951 // A typedef declaration containing _Atomic<...> is among the places where
2952 // the class is used. If we are currently parsing such a declaration, treat
2953 // the token as an identifier.
2954 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2955 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2956 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2957 Tok.setKind(tok::identifier);
2958
Chris Lattner4d8f8732006-11-28 05:05:08 +00002959 SourceLocation Loc = Tok.getLocation();
Douglas Gregor450c75a2008-11-07 15:42:26 +00002960
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002961 switch (Tok.getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00002962 default:
Chris Lattner0974b232008-07-26 00:20:22 +00002963 DoneWithDeclSpec:
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002964 if (!AttrsLastTime)
2965 ProhibitAttributes(attrs);
Michael Han64536a62012-11-06 19:34:54 +00002966 else {
2967 // Reject C++11 attributes that appertain to decl specifiers as
2968 // we don't support any C++11 attributes that appertain to decl
2969 // specifiers. This also conforms to what g++ 4.8 is doing.
Richard Smith49cc1cc2016-08-18 21:59:42 +00002970 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
Michael Han64536a62012-11-06 19:34:54 +00002971
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002972 DS.takeAttributesFrom(attrs);
Michael Han64536a62012-11-06 19:34:54 +00002973 }
Peter Collingbourne70188b32011-09-29 18:03:57 +00002974
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002975 // If this is not a declaration specifier token, we're done reading decl
2976 // specifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00002977 DS.Finish(Actions, Policy);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002978 return;
Mike Stump11289f42009-09-09 15:08:12 +00002979
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002980 case tok::l_square:
2981 case tok::kw_alignas:
Aaron Ballman606093a2017-10-15 15:01:42 +00002982 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002983 goto DoneWithDeclSpec;
2984
2985 ProhibitAttributes(attrs);
2986 // FIXME: It would be good to recover by accepting the attributes,
2987 // but attempting to do that now would cause serious
2988 // madness in terms of diagnostics.
2989 attrs.clear();
2990 attrs.Range = SourceRange();
2991
2992 ParseCXX11Attributes(attrs);
2993 AttrsLastTime = true;
Chad Rosierc1183952012-06-26 22:30:43 +00002994 continue;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002995
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002996 case tok::code_completion: {
John McCallfaf5fb42010-08-26 23:41:50 +00002997 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002998 if (DS.hasTypeSpecifier()) {
2999 bool AllowNonIdentifiers
3000 = (getCurScope()->getFlags() & (Scope::ControlScope |
3001 Scope::BlockScope |
3002 Scope::TemplateParamScope |
3003 Scope::FunctionPrototypeScope |
3004 Scope::AtCatchScope)) == 0;
3005 bool AllowNestedNameSpecifiers
Faisal Vali7db85c52017-12-31 00:06:40 +00003006 = DSContext == DeclSpecContext::DSC_top_level ||
3007 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003008
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003009 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
Chad Rosierc1183952012-06-26 22:30:43 +00003010 AllowNonIdentifiers,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003011 AllowNestedNameSpecifiers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003012 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00003013 }
3014
Douglas Gregor80039242011-02-15 20:33:25 +00003015 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3016 CCC = Sema::PCC_LocalDeclarationSpecifiers;
3017 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
Faisal Vali7db85c52017-12-31 00:06:40 +00003018 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3019 : Sema::PCC_Template;
3020 else if (DSContext == DeclSpecContext::DSC_class)
John McCallfaf5fb42010-08-26 23:41:50 +00003021 CCC = Sema::PCC_Class;
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +00003022 else if (CurParsedObjCImpl)
John McCallfaf5fb42010-08-26 23:41:50 +00003023 CCC = Sema::PCC_ObjCImplementation;
Chad Rosierc1183952012-06-26 22:30:43 +00003024
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003025 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003026 return cutOffParsing();
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003027 }
3028
Chris Lattnerbd31aa32009-01-05 00:07:25 +00003029 case tok::coloncolon: // ::foo::bar
John McCall1f476a12010-02-26 08:45:28 +00003030 // C++ scope specifier. Annotate and loop, or bail out on error.
Eli Friedman2a1d9a92013-08-15 23:59:20 +00003031 if (TryAnnotateCXXScopeToken(EnteringContext)) {
John McCall1f476a12010-02-26 08:45:28 +00003032 if (!DS.hasTypeSpecifier())
3033 DS.SetTypeSpecError();
3034 goto DoneWithDeclSpec;
3035 }
John McCall8bc2a702010-03-01 18:20:46 +00003036 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3037 goto DoneWithDeclSpec;
John McCall1f476a12010-02-26 08:45:28 +00003038 continue;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003039
3040 case tok::annot_cxxscope: {
Richard Smith3092a3b2012-05-09 18:56:43 +00003041 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003042 goto DoneWithDeclSpec;
3043
John McCall9dab4e62009-12-12 11:40:51 +00003044 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00003045 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3046 Tok.getAnnotationRange(),
3047 SS);
John McCall9dab4e62009-12-12 11:40:51 +00003048
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003049 // We are looking for a qualified typename.
Douglas Gregor167fa622009-03-25 15:40:00 +00003050 Token Next = NextToken();
Mike Stump11289f42009-09-09 15:08:12 +00003051 if (Next.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003052 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
Douglas Gregorb67535d2009-03-31 00:43:58 +00003053 ->Kind == TNK_Type_template) {
Douglas Gregor167fa622009-03-25 15:40:00 +00003054 // We have a qualified template-id, e.g., N::A<int>
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003055
Richard Smith74f02342017-01-19 21:00:13 +00003056 // If this would be a valid constructor declaration with template
3057 // arguments, we will reject the attempt to form an invalid type-id
3058 // referring to the injected-class-name when we annotate the token,
3059 // per C++ [class.qual]p2.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003060 //
Richard Smith74f02342017-01-19 21:00:13 +00003061 // To improve diagnostics for this case, parse the declaration as a
3062 // constructor (and reject the extra template arguments later).
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003063 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
Faisal Vali7db85c52017-12-31 00:06:40 +00003064 if ((DSContext == DeclSpecContext::DSC_top_level ||
3065 DSContext == DeclSpecContext::DSC_class) &&
John McCall84821e72010-04-13 06:39:49 +00003066 TemplateId->Name &&
Richard Smith74f02342017-01-19 21:00:13 +00003067 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003068 isConstructorDeclarator(/*Unqualified*/ false)) {
Richard Smith74f02342017-01-19 21:00:13 +00003069 // The user meant this to be an out-of-line constructor
3070 // definition, but template arguments are not allowed
3071 // there. Just allow this as a constructor; we'll
3072 // complain about it later.
3073 goto DoneWithDeclSpec;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003074 }
3075
John McCall9dab4e62009-12-12 11:40:51 +00003076 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003077 ConsumeAnnotationToken(); // The C++ scope.
Mike Stump11289f42009-09-09 15:08:12 +00003078 assert(Tok.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003079 "ParseOptionalCXXScopeSpecifier not working");
Douglas Gregore7c20652011-03-02 00:47:37 +00003080 AnnotateTemplateIdTokenAsType();
Douglas Gregor167fa622009-03-25 15:40:00 +00003081 continue;
3082 }
3083
Douglas Gregorc5790df2009-09-28 07:26:33 +00003084 if (Next.is(tok::annot_typename)) {
John McCall9dab4e62009-12-12 11:40:51 +00003085 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003086 ConsumeAnnotationToken(); // The C++ scope.
John McCallba7bf592010-08-24 05:47:05 +00003087 if (Tok.getAnnotationValue()) {
3088 ParsedType T = getTypeAnnotation(Tok);
Nico Weber77430342010-11-22 10:30:56 +00003089 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
Chad Rosierc1183952012-06-26 22:30:43 +00003090 Tok.getAnnotationEndLoc(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003091 PrevSpec, DiagID, T, Policy);
Richard Smithda837032012-09-14 18:27:01 +00003092 if (isInvalid)
3093 break;
John McCallba7bf592010-08-24 05:47:05 +00003094 }
Douglas Gregorc5790df2009-09-28 07:26:33 +00003095 else
3096 DS.SetTypeSpecError();
3097 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003098 ConsumeAnnotationToken(); // The typename
Douglas Gregorc5790df2009-09-28 07:26:33 +00003099 }
3100
Douglas Gregor167fa622009-03-25 15:40:00 +00003101 if (Next.isNot(tok::identifier))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003102 goto DoneWithDeclSpec;
3103
Richard Smith74f02342017-01-19 21:00:13 +00003104 // Check whether this is a constructor declaration. If we're in a
3105 // context where the identifier could be a class name, and it has the
3106 // shape of a constructor declaration, process it as one.
Faisal Vali7db85c52017-12-31 00:06:40 +00003107 if ((DSContext == DeclSpecContext::DSC_top_level ||
3108 DSContext == DeclSpecContext::DSC_class) &&
Chad Rosierc1183952012-06-26 22:30:43 +00003109 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
Richard Smith74f02342017-01-19 21:00:13 +00003110 &SS) &&
3111 isConstructorDeclarator(/*Unqualified*/ false))
3112 goto DoneWithDeclSpec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003113
David Blaikieefdccaa2016-01-15 23:43:34 +00003114 ParsedType TypeRep =
3115 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3116 getCurScope(), &SS, false, false, nullptr,
3117 /*IsCtorOrDtorName=*/false,
Richard Smith600b5262017-01-26 20:40:47 +00003118 /*WantNonTrivialSourceInfo=*/true,
3119 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003120
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003121 // If the referenced identifier is not a type, then this declspec is
3122 // erroneous: We already checked about that it has no type specifier, and
3123 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
Mike Stump11289f42009-09-09 15:08:12 +00003124 // typename.
David Blaikie7d170102013-05-15 07:37:26 +00003125 if (!TypeRep) {
Richard Smithaf3b3252017-05-18 19:21:48 +00003126 // Eat the scope spec so the identifier is current.
3127 ConsumeAnnotationToken();
Michael Han9407e502012-11-26 22:54:45 +00003128 ParsedAttributesWithRange Attrs(AttrFactory);
3129 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3130 if (!Attrs.empty()) {
3131 AttrsLastTime = true;
3132 attrs.takeAllFrom(Attrs);
3133 }
3134 continue;
3135 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003136 goto DoneWithDeclSpec;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003137 }
Mike Stump11289f42009-09-09 15:08:12 +00003138
John McCall9dab4e62009-12-12 11:40:51 +00003139 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003140 ConsumeAnnotationToken(); // The C++ scope.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003141
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003142 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003143 DiagID, TypeRep, Policy);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003144 if (isInvalid)
3145 break;
Mike Stump11289f42009-09-09 15:08:12 +00003146
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003147 DS.SetRangeEnd(Tok.getLocation());
3148 ConsumeToken(); // The typename.
3149
3150 continue;
3151 }
Mike Stump11289f42009-09-09 15:08:12 +00003152
Chris Lattnere387d9e2009-01-21 19:48:37 +00003153 case tok::annot_typename: {
Richard Smith404dfb42013-11-19 22:47:36 +00003154 // If we've previously seen a tag definition, we were almost surely
3155 // missing a semicolon after it.
3156 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3157 goto DoneWithDeclSpec;
3158
John McCallba7bf592010-08-24 05:47:05 +00003159 if (Tok.getAnnotationValue()) {
3160 ParsedType T = getTypeAnnotation(Tok);
Nico Weber7f8bb362010-11-22 12:50:03 +00003161 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003162 DiagID, T, Policy);
John McCallba7bf592010-08-24 05:47:05 +00003163 } else
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003164 DS.SetTypeSpecError();
Chad Rosierc1183952012-06-26 22:30:43 +00003165
Chris Lattner005fc1b2010-04-05 18:18:31 +00003166 if (isInvalid)
3167 break;
3168
Chris Lattnere387d9e2009-01-21 19:48:37 +00003169 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003170 ConsumeAnnotationToken(); // The typename
Mike Stump11289f42009-09-09 15:08:12 +00003171
Chris Lattnere387d9e2009-01-21 19:48:37 +00003172 continue;
3173 }
Mike Stump11289f42009-09-09 15:08:12 +00003174
Douglas Gregor06873092011-04-28 15:48:45 +00003175 case tok::kw___is_signed:
3176 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3177 // typically treats it as a trait. If we see __is_signed as it appears
3178 // in libstdc++, e.g.,
3179 //
3180 // static const bool __is_signed;
3181 //
3182 // then treat __is_signed as an identifier rather than as a keyword.
Faisal Vali090da2d2018-01-01 18:23:28 +00003183 if (DS.getTypeSpecType() == TST_bool &&
Douglas Gregor06873092011-04-28 15:48:45 +00003184 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
Alp Toker47642d22013-12-03 06:13:01 +00003185 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3186 TryKeywordIdentFallback(true);
Douglas Gregor06873092011-04-28 15:48:45 +00003187
3188 // We're done with the declaration-specifiers.
3189 goto DoneWithDeclSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00003190
Chris Lattner16fac4f2008-07-26 01:18:38 +00003191 // typedef-name
Nikola Smiljanic67860242014-09-26 00:28:20 +00003192 case tok::kw___super:
David Blaikie15a430a2011-12-04 05:04:18 +00003193 case tok::kw_decltype:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003194 case tok::identifier: {
Reid Klecknerc582f012014-07-14 18:19:58 +00003195 // This identifier can only be a typedef name if we haven't already seen
3196 // a type-specifier. Without this check we misparse:
3197 // typedef int X; struct Y { short X; }; as 'short int'.
3198 if (DS.hasTypeSpecifier())
3199 goto DoneWithDeclSpec;
3200
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003201 // If the token is an identifier named "__declspec" and Microsoft
3202 // extensions are not enabled, it is likely that there will be cascading
3203 // parse errors if this really is a __declspec attribute. Attempt to
3204 // recognize that scenario and recover gracefully.
3205 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3206 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3207 Diag(Loc, diag::err_ms_attributes_not_enabled);
3208
3209 // The next token should be an open paren. If it is, eat the entire
3210 // attribute declaration and continue.
3211 if (NextToken().is(tok::l_paren)) {
3212 // Consume the __declspec identifier.
Richard Trieuba057372017-02-14 23:56:55 +00003213 ConsumeToken();
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003214
3215 // Eat the parens and everything between them.
3216 BalancedDelimiterTracker T(*this, tok::l_paren);
3217 if (T.consumeOpen()) {
3218 assert(false && "Not a left paren?");
3219 return;
3220 }
3221 T.skipToEnd();
3222 continue;
3223 }
3224 }
3225
Serge Pavlov458ea762014-07-16 05:16:52 +00003226 // In C++, check to see if this is a scope specifier like foo::bar::, if
3227 // so handle it as such. This is important for ctor parsing.
3228 if (getLangOpts().CPlusPlus) {
3229 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3230 DS.SetTypeSpecError();
3231 goto DoneWithDeclSpec;
3232 }
3233 if (!Tok.is(tok::identifier))
3234 continue;
3235 }
3236
John Thompson22334602010-02-05 00:12:22 +00003237 // Check for need to substitute AltiVec keyword tokens.
3238 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3239 break;
3240
Richard Smith3092a3b2012-05-09 18:56:43 +00003241 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3242 // allow the use of a typedef name as a type specifier.
3243 if (DS.isTypeAltiVecVector())
3244 goto DoneWithDeclSpec;
3245
Faisal Vali7db85c52017-12-31 00:06:40 +00003246 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3247 isObjCInstancetype()) {
Douglas Gregor5c0870a2015-06-19 23:18:00 +00003248 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3249 assert(TypeRep);
3250 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3251 DiagID, TypeRep, Policy);
3252 if (isInvalid)
3253 break;
3254
3255 DS.SetRangeEnd(Loc);
3256 ConsumeToken();
3257 continue;
3258 }
3259
Richard Smith715ee072018-06-20 21:58:20 +00003260 // If we're in a context where the identifier could be a class name,
3261 // check whether this is a constructor declaration.
3262 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3263 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3264 isConstructorDeclarator(/*Unqualified*/true))
3265 goto DoneWithDeclSpec;
3266
Richard Smith600b5262017-01-26 20:40:47 +00003267 ParsedType TypeRep = Actions.getTypeName(
3268 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3269 false, false, nullptr, false, false,
3270 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003271
Chris Lattner6cc055a2009-04-12 20:42:31 +00003272 // If this is not a typedef name, don't parse it as part of the declspec,
3273 // it must be an implicit int or an error.
John McCallba7bf592010-08-24 05:47:05 +00003274 if (!TypeRep) {
Michael Han9407e502012-11-26 22:54:45 +00003275 ParsedAttributesWithRange Attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +00003276 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
Michael Han9407e502012-11-26 22:54:45 +00003277 if (!Attrs.empty()) {
3278 AttrsLastTime = true;
3279 attrs.takeAllFrom(Attrs);
3280 }
3281 continue;
3282 }
Chris Lattner16fac4f2008-07-26 01:18:38 +00003283 goto DoneWithDeclSpec;
Chris Lattner6cc055a2009-04-12 20:42:31 +00003284 }
Douglas Gregor8bf42052009-02-09 18:46:07 +00003285
Richard Smith35845152017-02-07 01:37:30 +00003286 // Likewise, if this is a context where the identifier could be a template
3287 // name, check whether this is a deduction guide declaration.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003288 if (getLangOpts().CPlusPlus17 &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003289 (DSContext == DeclSpecContext::DSC_class ||
3290 DSContext == DeclSpecContext::DSC_top_level) &&
Richard Smith35845152017-02-07 01:37:30 +00003291 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3292 Tok.getLocation()) &&
3293 isConstructorDeclarator(/*Unqualified*/ true,
3294 /*DeductionGuide*/ true))
3295 goto DoneWithDeclSpec;
3296
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003297 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003298 DiagID, TypeRep, Policy);
Chris Lattner16fac4f2008-07-26 01:18:38 +00003299 if (isInvalid)
3300 break;
Mike Stump11289f42009-09-09 15:08:12 +00003301
Chris Lattner16fac4f2008-07-26 01:18:38 +00003302 DS.SetRangeEnd(Tok.getLocation());
3303 ConsumeToken(); // The identifier
3304
Douglas Gregore9d95f12015-07-07 03:57:35 +00003305 // Objective-C supports type arguments and protocol references
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003306 // following an Objective-C object or object pointer
3307 // type. Handle either one of them.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003308 if (Tok.is(tok::less) && getLangOpts().ObjC) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003309 SourceLocation NewEndLoc;
3310 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3311 Loc, TypeRep, /*consumeLastToken=*/true,
3312 NewEndLoc);
3313 if (NewTypeRep.isUsable()) {
3314 DS.UpdateTypeRep(NewTypeRep.get());
3315 DS.SetRangeEnd(NewEndLoc);
3316 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00003317 }
Chad Rosierc1183952012-06-26 22:30:43 +00003318
Steve Naroffcd5e7822008-09-22 10:28:57 +00003319 // Need to support trailing type qualifiers (e.g. "id<p> const").
3320 // If a type specifier follows, it will be diagnosed elsewhere.
3321 continue;
Chris Lattner16fac4f2008-07-26 01:18:38 +00003322 }
Douglas Gregor7f741122009-02-25 19:37:18 +00003323
3324 // type-name
3325 case tok::annot_template_id: {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003326 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorb67535d2009-03-31 00:43:58 +00003327 if (TemplateId->Kind != TNK_Type_template) {
Douglas Gregor7f741122009-02-25 19:37:18 +00003328 // This template-id does not refer to a type name, so we're
3329 // done with the type-specifiers.
3330 goto DoneWithDeclSpec;
3331 }
3332
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003333 // If we're in a context where the template-id could be a
3334 // constructor name or specialization, check whether this is a
3335 // constructor declaration.
Faisal Vali7db85c52017-12-31 00:06:40 +00003336 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00003337 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
Richard Smith446161b2014-03-03 21:12:53 +00003338 isConstructorDeclarator(TemplateId->SS.isEmpty()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003339 goto DoneWithDeclSpec;
3340
Douglas Gregor7f741122009-02-25 19:37:18 +00003341 // Turn the template-id annotation token into a type annotation
3342 // token, then try again to parse it as a type-specifier.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003343 AnnotateTemplateIdTokenAsType();
Douglas Gregor7f741122009-02-25 19:37:18 +00003344 continue;
3345 }
3346
Chris Lattnere37e2332006-08-15 04:50:22 +00003347 // GNU attributes support.
3348 case tok::kw___attribute:
Craig Topper161e4db2014-05-21 06:02:52 +00003349 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
Chris Lattnerb95cca02006-10-17 03:01:08 +00003350 continue;
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003351
3352 // Microsoft declspec support.
3353 case tok::kw___declspec:
Aaron Ballman068aa512015-05-20 20:58:33 +00003354 ParseMicrosoftDeclSpecs(DS.getAttributes());
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003355 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003356
Steve Naroff44ac7772008-12-25 14:16:32 +00003357 // Microsoft single token adornments.
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003358 case tok::kw___forceinline: {
Serge Pavlov750db652013-11-13 06:57:53 +00003359 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003360 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Richard Smithda837032012-09-14 18:27:01 +00003361 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00003362 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00003363 nullptr, 0, ParsedAttr::AS_Keyword);
Richard Smithda837032012-09-14 18:27:01 +00003364 break;
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003365 }
Eli Friedman53339e02009-06-08 23:27:34 +00003366
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003367 case tok::kw___unaligned:
3368 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3369 getLangOpts());
3370 break;
3371
Aaron Ballman317a77f2013-05-22 23:25:32 +00003372 case tok::kw___sptr:
3373 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00003374 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00003375 case tok::kw___ptr32:
Steve Narofff9c29d42008-12-25 14:41:26 +00003376 case tok::kw___w64:
Steve Naroff44ac7772008-12-25 14:16:32 +00003377 case tok::kw___cdecl:
3378 case tok::kw___stdcall:
3379 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00003380 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00003381 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00003382 case tok::kw___vectorcall:
John McCall53fa7142010-12-24 02:08:15 +00003383 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00003384 continue;
3385
Dawn Perchik335e16b2010-09-03 01:29:35 +00003386 // Borland single token adornments.
3387 case tok::kw___pascal:
John McCall53fa7142010-12-24 02:08:15 +00003388 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00003389 continue;
3390
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003391 // OpenCL single token adornments.
3392 case tok::kw___kernel:
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +00003393 ParseOpenCLKernelAttributes(DS.getAttributes());
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003394 continue;
3395
Douglas Gregor261a89b2015-06-19 17:51:05 +00003396 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00003397 case tok::kw__Nonnull:
3398 case tok::kw__Nullable:
3399 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00003400 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3401 continue;
3402
Douglas Gregorab209d82015-07-07 03:58:42 +00003403 // Objective-C 'kindof' types.
3404 case tok::kw___kindof:
3405 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00003406 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00003407 (void)ConsumeToken();
3408 continue;
3409
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003410 // storage-class-specifier
3411 case tok::kw_typedef:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003412 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003413 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003414 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003415 break;
3416 case tok::kw_extern:
Richard Smithb4a9e862013-04-12 22:46:28 +00003417 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003418 Diag(Tok, diag::ext_thread_before) << "extern";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003419 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003420 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003421 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003422 break;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003423 case tok::kw___private_extern__:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003424 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003425 Loc, PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003426 isStorageClass = true;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003427 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003428 case tok::kw_static:
Richard Smithb4a9e862013-04-12 22:46:28 +00003429 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003430 Diag(Tok, diag::ext_thread_before) << "static";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003431 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003432 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003433 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003434 break;
3435 case tok::kw_auto:
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003436 if (getLangOpts().CPlusPlus11) {
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003437 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003438 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003439 PrevSpec, DiagID, Policy);
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003440 if (!isInvalid)
Richard Smith58c74332011-09-04 19:54:14 +00003441 Diag(Tok, diag::ext_auto_storage_class)
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003442 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith58c74332011-09-04 19:54:14 +00003443 } else
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003444 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003445 DiagID, Policy);
Richard Smith58c74332011-09-04 19:54:14 +00003446 } else
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003447 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003448 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003449 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003450 break;
Richard Smithe301ba22015-11-11 02:02:15 +00003451 case tok::kw___auto_type:
3452 Diag(Tok, diag::ext_auto_type);
3453 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3454 DiagID, Policy);
3455 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003456 case tok::kw_register:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003457 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003458 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003459 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003460 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003461 case tok::kw_mutable:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003462 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003463 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003464 isStorageClass = true;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003465 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003466 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00003467 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3468 PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003469 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003470 break;
3471 case tok::kw_thread_local:
3472 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3473 PrevSpec, DiagID);
Sven van Haastregtc4100832018-04-24 14:47:29 +00003474 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003475 break;
3476 case tok::kw__Thread_local:
3477 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3478 Loc, PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003479 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003480 break;
Mike Stump11289f42009-09-09 15:08:12 +00003481
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003482 // function-specifier
3483 case tok::kw_inline:
Serge Pavlov750db652013-11-13 06:57:53 +00003484 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003485 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003486 case tok::kw_virtual:
Sven van Haastregt49ffffb2018-04-23 11:23:47 +00003487 // OpenCL C++ v1.0 s2.9: the virtual function qualifier is not supported.
3488 if (getLangOpts().OpenCLCPlusPlus) {
3489 DiagID = diag::err_openclcxx_virtual_function;
3490 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3491 isInvalid = true;
3492 }
3493 else {
3494 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3495 }
Douglas Gregor61956c42008-10-31 09:07:45 +00003496 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003497 case tok::kw_explicit:
Serge Pavlov750db652013-11-13 06:57:53 +00003498 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
Douglas Gregor61956c42008-10-31 09:07:45 +00003499 break;
Richard Smith0015f092013-01-17 22:16:11 +00003500 case tok::kw__Noreturn:
3501 if (!getLangOpts().C11)
3502 Diag(Loc, diag::ext_c11_noreturn);
Serge Pavlov750db652013-11-13 06:57:53 +00003503 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
Richard Smith0015f092013-01-17 22:16:11 +00003504 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003505
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003506 // alignment-specifier
3507 case tok::kw__Alignas:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003508 if (!getLangOpts().C11)
Jordan Rose58d54722012-06-30 21:33:57 +00003509 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003510 ParseAlignmentSpecifier(DS.getAttributes());
3511 continue;
3512
Anders Carlssoncd8db412009-05-06 04:46:28 +00003513 // friend
3514 case tok::kw_friend:
Faisal Vali7db85c52017-12-31 00:06:40 +00003515 if (DSContext == DeclSpecContext::DSC_class)
John McCall07e91c02009-08-06 02:15:43 +00003516 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3517 else {
3518 PrevSpec = ""; // not actually used by the diagnostic
3519 DiagID = diag::err_friend_invalid_in_context;
3520 isInvalid = true;
3521 }
Anders Carlssoncd8db412009-05-06 04:46:28 +00003522 break;
Mike Stump11289f42009-09-09 15:08:12 +00003523
Douglas Gregor26701a42011-09-09 02:06:17 +00003524 // Modules
3525 case tok::kw___module_private__:
3526 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3527 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003528
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00003529 // constexpr
3530 case tok::kw_constexpr:
3531 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3532 break;
3533
Chris Lattnere387d9e2009-01-21 19:48:37 +00003534 // type-specifier
3535 case tok::kw_short:
John McCall49bfce42009-08-03 20:12:06 +00003536 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003537 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003538 break;
3539 case tok::kw_long:
3540 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
John McCall49bfce42009-08-03 20:12:06 +00003541 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003542 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003543 else
John McCall49bfce42009-08-03 20:12:06 +00003544 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003545 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003546 break;
Francois Pichet84133e42011-04-28 01:59:37 +00003547 case tok::kw___int64:
3548 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003549 DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00003550 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003551 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00003552 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3553 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003554 break;
3555 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00003556 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3557 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003558 break;
3559 case tok::kw__Complex:
John McCall49bfce42009-08-03 20:12:06 +00003560 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3561 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003562 break;
3563 case tok::kw__Imaginary:
John McCall49bfce42009-08-03 20:12:06 +00003564 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3565 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003566 break;
3567 case tok::kw_void:
John McCall49bfce42009-08-03 20:12:06 +00003568 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003569 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003570 break;
3571 case tok::kw_char:
John McCall49bfce42009-08-03 20:12:06 +00003572 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003573 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003574 break;
3575 case tok::kw_int:
John McCall49bfce42009-08-03 20:12:06 +00003576 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003577 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003578 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00003579 case tok::kw___int128:
3580 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003581 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003582 break;
3583 case tok::kw_half:
3584 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003585 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003586 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003587 case tok::kw_float:
John McCall49bfce42009-08-03 20:12:06 +00003588 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003589 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003590 break;
3591 case tok::kw_double:
John McCall49bfce42009-08-03 20:12:06 +00003592 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003593 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003594 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00003595 case tok::kw__Float16:
3596 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3597 DiagID, Policy);
3598 break;
Leonard Chanf921d852018-06-04 16:07:52 +00003599 case tok::kw__Accum:
3600 if (!getLangOpts().FixedPoint) {
Leonard Chanab80f3c2018-06-14 14:53:51 +00003601 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
Leonard Chanf921d852018-06-04 16:07:52 +00003602 } else {
3603 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3604 DiagID, Policy);
3605 }
3606 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00003607 case tok::kw__Fract:
3608 if (!getLangOpts().FixedPoint) {
3609 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3610 } else {
3611 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3612 DiagID, Policy);
3613 }
3614 break;
3615 case tok::kw__Sat:
3616 if (!getLangOpts().FixedPoint) {
3617 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3618 } else {
3619 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3620 }
3621 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003622 case tok::kw___float128:
3623 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3624 DiagID, Policy);
3625 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003626 case tok::kw_wchar_t:
John McCall49bfce42009-08-03 20:12:06 +00003627 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003628 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003629 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00003630 case tok::kw_char8_t:
3631 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3632 DiagID, Policy);
3633 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003634 case tok::kw_char16_t:
John McCall49bfce42009-08-03 20:12:06 +00003635 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003636 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003637 break;
3638 case tok::kw_char32_t:
John McCall49bfce42009-08-03 20:12:06 +00003639 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003640 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003641 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003642 case tok::kw_bool:
3643 case tok::kw__Bool:
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003644 if (Tok.is(tok::kw_bool) &&
3645 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3646 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3647 PrevSpec = ""; // Not used by the diagnostic.
3648 DiagID = diag::err_bool_redeclaration;
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003649 // For better error recovery.
3650 Tok.setKind(tok::identifier);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003651 isInvalid = true;
3652 } else {
3653 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003654 DiagID, Policy);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003655 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003656 break;
3657 case tok::kw__Decimal32:
John McCall49bfce42009-08-03 20:12:06 +00003658 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003659 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003660 break;
3661 case tok::kw__Decimal64:
John McCall49bfce42009-08-03 20:12:06 +00003662 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003663 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003664 break;
3665 case tok::kw__Decimal128:
John McCall49bfce42009-08-03 20:12:06 +00003666 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003667 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003668 break;
John Thompson22334602010-02-05 00:12:22 +00003669 case tok::kw___vector:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003670 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003671 break;
3672 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003673 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003674 break;
Bill Seurercf2c96b2015-01-12 19:35:51 +00003675 case tok::kw___bool:
3676 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3677 break;
Xiuli Pan9c14e282016-01-09 12:53:17 +00003678 case tok::kw_pipe:
3679 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3680 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3681 // support the "pipe" word as identifier.
3682 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3683 goto DoneWithDeclSpec;
3684 }
3685 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3686 break;
Alexey Bader954ba212016-04-08 13:40:33 +00003687#define GENERIC_IMAGE_TYPE(ImgType, Id) \
3688 case tok::kw_##ImgType##_t: \
3689 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3690 DiagID, Policy); \
3691 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00003692#include "clang/Basic/OpenCLImageTypes.def"
John McCall39439732011-04-09 22:50:59 +00003693 case tok::kw___unknown_anytype:
Faisal Vali090da2d2018-01-01 18:23:28 +00003694 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003695 PrevSpec, DiagID, Policy);
John McCall39439732011-04-09 22:50:59 +00003696 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003697
3698 // class-specifier:
3699 case tok::kw_class:
3700 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00003701 case tok::kw___interface:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003702 case tok::kw_union: {
3703 tok::TokenKind Kind = Tok.getKind();
3704 ConsumeToken();
Michael Han9407e502012-11-26 22:54:45 +00003705
3706 // These are attributes following class specifiers.
3707 // To produce better diagnostic, we parse them when
3708 // parsing class specifier.
Bill Wendling44426052012-12-20 19:22:21 +00003709 ParsedAttributesWithRange Attributes(AttrFactory);
Richard Smithc5b05522012-03-12 07:56:15 +00003710 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
Bill Wendling44426052012-12-20 19:22:21 +00003711 EnteringContext, DSContext, Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003712
3713 // If there are attributes following class specifier,
3714 // take them over and handle them here.
Bill Wendling44426052012-12-20 19:22:21 +00003715 if (!Attributes.empty()) {
Michael Han9407e502012-11-26 22:54:45 +00003716 AttrsLastTime = true;
Bill Wendling44426052012-12-20 19:22:21 +00003717 attrs.takeAllFrom(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003718 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003719 continue;
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003720 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003721
3722 // enum-specifier:
3723 case tok::kw_enum:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003724 ConsumeToken();
Richard Smithc5b05522012-03-12 07:56:15 +00003725 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003726 continue;
Faisal Valia534f072018-04-26 00:42:40 +00003727
Chris Lattnere387d9e2009-01-21 19:48:37 +00003728 // cv-qualifier:
3729 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00003730 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003731 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003732 break;
3733 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00003734 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003735 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003736 break;
3737 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00003738 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003739 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003740 break;
3741
Douglas Gregor333489b2009-03-27 23:10:48 +00003742 // C++ typename-specifier:
3743 case tok::kw_typename:
John McCall1f476a12010-02-26 08:45:28 +00003744 if (TryAnnotateTypeOrScopeToken()) {
3745 DS.SetTypeSpecError();
3746 goto DoneWithDeclSpec;
3747 }
3748 if (!Tok.is(tok::kw_typename))
Douglas Gregor333489b2009-03-27 23:10:48 +00003749 continue;
3750 break;
3751
Chris Lattnere387d9e2009-01-21 19:48:37 +00003752 // GNU typeof support.
3753 case tok::kw_typeof:
3754 ParseTypeofSpecifier(DS);
3755 continue;
3756
David Blaikie15a430a2011-12-04 05:04:18 +00003757 case tok::annot_decltype:
Anders Carlsson74948d02009-06-24 17:47:40 +00003758 ParseDecltypeSpecifier(DS);
3759 continue;
3760
David Majnemer15b311c2016-06-14 03:20:28 +00003761 case tok::annot_pragma_pack:
3762 HandlePragmaPack();
3763 continue;
3764
3765 case tok::annot_pragma_ms_pragma:
3766 HandlePragmaMSPragma();
3767 continue;
3768
3769 case tok::annot_pragma_ms_vtordisp:
3770 HandlePragmaMSVtorDisp();
3771 continue;
3772
3773 case tok::annot_pragma_ms_pointers_to_members:
3774 HandlePragmaMSPointersToMembers();
3775 continue;
3776
Alexis Hunt4a257072011-05-19 05:37:45 +00003777 case tok::kw___underlying_type:
3778 ParseUnderlyingTypeSpecifier(DS);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003779 continue;
3780
3781 case tok::kw__Atomic:
Richard Smith8e1ac332013-03-28 01:55:44 +00003782 // C11 6.7.2.4/4:
3783 // If the _Atomic keyword is immediately followed by a left parenthesis,
3784 // it is interpreted as a type specifier (with a type name), not as a
3785 // type qualifier.
3786 if (NextToken().is(tok::l_paren)) {
3787 ParseAtomicSpecifier(DS);
3788 continue;
3789 }
3790 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3791 getLangOpts());
3792 break;
Alexis Hunt4a257072011-05-19 05:37:45 +00003793
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003794 // OpenCL access qualifiers:
3795 case tok::kw___read_only:
3796 case tok::kw___write_only:
3797 case tok::kw___read_write:
3798 // OpenCL C++ 1.0 s2.2: access qualifiers are reserved keywords.
3799 if (Actions.getLangOpts().OpenCLCPlusPlus) {
3800 DiagID = diag::err_openclcxx_reserved;
3801 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3802 isInvalid = true;
3803 }
3804 ParseOpenCLQualifiers(DS.getAttributes());
3805 break;
3806
3807 // OpenCL address space qualifiers:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003808 case tok::kw___generic:
3809 // generic address space is introduced only in OpenCL v2.0
3810 // see OpenCL C Spec v2.0 s6.5.5
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003811 if (Actions.getLangOpts().OpenCLVersion < 200 &&
3812 !Actions.getLangOpts().OpenCLCPlusPlus) {
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003813 DiagID = diag::err_opencl_unknown_type_specifier;
3814 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3815 isInvalid = true;
3816 break;
3817 };
Galina Kistanova77674252017-06-01 21:15:34 +00003818 LLVM_FALLTHROUGH;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003819 case tok::kw___private:
3820 case tok::kw___global:
3821 case tok::kw___local:
3822 case tok::kw___constant:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00003823 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003824 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003825
Steve Naroffcfdf6162008-06-05 00:02:44 +00003826 case tok::less:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003827 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
Chris Lattner0974b232008-07-26 00:20:22 +00003828 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3829 // but we support it.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003830 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
Chris Lattner0974b232008-07-26 00:20:22 +00003831 goto DoneWithDeclSpec;
Mike Stump11289f42009-09-09 15:08:12 +00003832
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003833 SourceLocation StartLoc = Tok.getLocation();
3834 SourceLocation EndLoc;
3835 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3836 if (Type.isUsable()) {
3837 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3838 PrevSpec, DiagID, Type.get(),
3839 Actions.getASTContext().getPrintingPolicy()))
3840 Diag(StartLoc, DiagID) << PrevSpec;
Fangrui Song6907ce22018-07-30 19:24:48 +00003841
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003842 DS.SetRangeEnd(EndLoc);
3843 } else {
3844 DS.SetTypeSpecError();
3845 }
Chad Rosierc1183952012-06-26 22:30:43 +00003846
Douglas Gregor06e41ae2010-10-21 23:17:00 +00003847 // Need to support trailing type qualifiers (e.g. "id<p> const").
3848 // If a type specifier follows, it will be diagnosed elsewhere.
3849 continue;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003850 }
John McCall49bfce42009-08-03 20:12:06 +00003851 // If the specifier wasn't legal, issue a diagnostic.
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003852 if (isInvalid) {
3853 assert(PrevSpec && "Method did not return previous specifier!");
John McCall49bfce42009-08-03 20:12:06 +00003854 assert(DiagID);
Chad Rosierc1183952012-06-26 22:30:43 +00003855
Nick Desaulniers150ca532018-10-03 23:09:29 +00003856 if (DiagID == diag::ext_duplicate_declspec ||
3857 DiagID == diag::ext_warn_duplicate_declspec)
Douglas Gregora05f5ab2010-08-23 14:34:43 +00003858 Diag(Tok, DiagID)
3859 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003860 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003861 Diag(Tok, DiagID) << getLangOpts().OpenCLCPlusPlus
3862 << getLangOpts().getOpenCLVersionTuple().getAsString()
3863 << PrevSpec << isStorageClass;
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003864 } else
Douglas Gregora05f5ab2010-08-23 14:34:43 +00003865 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003866 }
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003867
Chris Lattner2e232092008-03-13 06:29:04 +00003868 DS.SetRangeEnd(Tok.getLocation());
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003869 if (DiagID != diag::err_bool_redeclaration)
Volodymyr Sapsai9f7b5cc2018-04-10 18:29:47 +00003870 // After an error the next token can be an annotation token.
3871 ConsumeAnyToken();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003872
3873 AttrsLastTime = false;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003874 }
3875}
Douglas Gregoreb31f392008-12-01 23:54:00 +00003876
Chris Lattner70ae4912007-10-29 04:42:53 +00003877/// ParseStructDeclaration - Parse a struct declaration without the terminating
3878/// semicolon.
3879///
Chris Lattner90a26b02007-01-23 04:38:16 +00003880/// struct-declaration:
Aaron Ballman606093a2017-10-15 15:01:42 +00003881/// [C2x] attributes-specifier-seq[opt]
3882/// specifier-qualifier-list struct-declarator-list
Chris Lattner736ed5d2007-06-09 05:59:07 +00003883/// [GNU] __extension__ struct-declaration
Chris Lattner70ae4912007-10-29 04:42:53 +00003884/// [GNU] specifier-qualifier-list
Chris Lattner90a26b02007-01-23 04:38:16 +00003885/// struct-declarator-list:
3886/// struct-declarator
3887/// struct-declarator-list ',' struct-declarator
3888/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3889/// struct-declarator:
3890/// declarator
3891/// [GNU] declarator attributes[opt]
3892/// declarator[opt] ':' constant-expression
3893/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3894///
Benjamin Kramera39beb92014-09-03 11:06:10 +00003895void Parser::ParseStructDeclaration(
3896 ParsingDeclSpec &DS,
3897 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
Chad Rosierc1183952012-06-26 22:30:43 +00003898
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003899 if (Tok.is(tok::kw___extension__)) {
3900 // __extension__ silences extension warnings in the subexpression.
3901 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Steve Naroff97170802007-08-20 22:28:22 +00003902 ConsumeToken();
Benjamin Kramera39beb92014-09-03 11:06:10 +00003903 return ParseStructDeclaration(DS, FieldsCallback);
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003904 }
Mike Stump11289f42009-09-09 15:08:12 +00003905
Aaron Ballman606093a2017-10-15 15:01:42 +00003906 // Parse leading attributes.
3907 ParsedAttributesWithRange Attrs(AttrFactory);
3908 MaybeParseCXX11Attributes(Attrs);
3909 DS.takeAttributesFrom(Attrs);
3910
Steve Naroff97170802007-08-20 22:28:22 +00003911 // Parse the common specifier-qualifiers-list piece.
Steve Naroff97170802007-08-20 22:28:22 +00003912 ParseSpecifierQualifierList(DS);
Mike Stump11289f42009-09-09 15:08:12 +00003913
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003914 // If there are no declarators, this is a free-standing declaration
3915 // specifier. Let the actions module cope with it.
Chris Lattner76c72282007-10-09 17:33:22 +00003916 if (Tok.is(tok::semi)) {
Nico Weber7b837f52016-01-28 19:25:00 +00003917 RecordDecl *AnonRecord = nullptr;
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003918 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00003919 DS, AnonRecord);
3920 assert(!AnonRecord && "Did not expect anonymous struct or union here");
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003921 DS.complete(TheDecl);
Steve Naroff97170802007-08-20 22:28:22 +00003922 return;
3923 }
3924
3925 // Read struct-declarators until we find the semicolon.
John McCallcfefb6d2009-11-03 02:38:08 +00003926 bool FirstDeclarator = true;
Richard Smith8d06f422012-01-12 23:53:29 +00003927 SourceLocation CommaLoc;
Steve Naroff97170802007-08-20 22:28:22 +00003928 while (1) {
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003929 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
Richard Smith8d06f422012-01-12 23:53:29 +00003930 DeclaratorInfo.D.setCommaLoc(CommaLoc);
John McCallcfefb6d2009-11-03 02:38:08 +00003931
Bill Wendling44426052012-12-20 19:22:21 +00003932 // Attributes are only allowed here on successive declarators.
John McCall53fa7142010-12-24 02:08:15 +00003933 if (!FirstDeclarator)
3934 MaybeParseGNUAttributes(DeclaratorInfo.D);
Mike Stump11289f42009-09-09 15:08:12 +00003935
Steve Naroff97170802007-08-20 22:28:22 +00003936 /// struct-declarator: declarator
3937 /// struct-declarator: declarator[opt] ':' constant-expression
Chris Lattner17c3b1f2009-12-10 01:59:24 +00003938 if (Tok.isNot(tok::colon)) {
3939 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3940 ColonProtectionRAIIObject X(*this);
Chris Lattnera12405b2008-04-10 06:46:29 +00003941 ParseDeclarator(DeclaratorInfo.D);
Richard Smith3d1a94c2014-08-12 00:22:39 +00003942 } else
3943 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003944
Alp Toker8fbec672013-12-17 23:29:36 +00003945 if (TryConsumeToken(tok::colon)) {
John McCalldadc5752010-08-24 06:29:42 +00003946 ExprResult Res(ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00003947 if (Res.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00003948 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner32295d32008-04-10 06:15:14 +00003949 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003950 DeclaratorInfo.BitfieldSize = Res.get();
Steve Naroff97170802007-08-20 22:28:22 +00003951 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003952
Steve Naroff97170802007-08-20 22:28:22 +00003953 // If attributes exist after the declarator, parse them.
John McCall53fa7142010-12-24 02:08:15 +00003954 MaybeParseGNUAttributes(DeclaratorInfo.D);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003955
John McCallcfefb6d2009-11-03 02:38:08 +00003956 // We're done with this declarator; invoke the callback.
Benjamin Kramera39beb92014-09-03 11:06:10 +00003957 FieldsCallback(DeclaratorInfo);
John McCallcfefb6d2009-11-03 02:38:08 +00003958
Steve Naroff97170802007-08-20 22:28:22 +00003959 // If we don't have a comma, it is either the end of the list (a ';')
3960 // or an error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00003961 if (!TryConsumeToken(tok::comma, CommaLoc))
Chris Lattner70ae4912007-10-29 04:42:53 +00003962 return;
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003963
John McCallcfefb6d2009-11-03 02:38:08 +00003964 FirstDeclarator = false;
Steve Naroff97170802007-08-20 22:28:22 +00003965 }
Steve Naroff97170802007-08-20 22:28:22 +00003966}
3967
3968/// ParseStructUnionBody
3969/// struct-contents:
3970/// struct-declaration-list
3971/// [EXT] empty
3972/// [GNU] "struct-declaration-list" without terminatoring ';'
3973/// struct-declaration-list:
3974/// struct-declaration
3975/// struct-declaration-list struct-declaration
Chris Lattner535b8302008-06-21 19:39:06 +00003976/// [OBC] '@' 'defs' '(' class-name ')'
Steve Naroff97170802007-08-20 22:28:22 +00003977///
Chris Lattner1300fb92007-01-23 23:42:53 +00003978void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00003979 unsigned TagType, Decl *TagDecl) {
Jordan Rose1e879d82018-03-23 00:07:18 +00003980 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003981 "parsing struct/union body");
Andy Gibbs22e140b2013-04-03 09:31:19 +00003982 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
Mike Stump11289f42009-09-09 15:08:12 +00003983
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003984 BalancedDelimiterTracker T(*this, tok::l_brace);
3985 if (T.consumeOpen())
3986 return;
Mike Stump11289f42009-09-09 15:08:12 +00003987
Douglas Gregor658b9552009-01-09 22:42:13 +00003988 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00003989 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003990
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003991 SmallVector<Decl *, 32> FieldDecls;
Chris Lattnera12405b2008-04-10 06:46:29 +00003992
Chris Lattner7b9ace62007-01-23 20:11:08 +00003993 // While we still have something to read, read the declarations in the struct.
Richard Smith752ada82015-11-17 23:32:01 +00003994 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3995 Tok.isNot(tok::eof)) {
Chris Lattner90a26b02007-01-23 04:38:16 +00003996 // Each iteration of this loop reads one struct-declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003997
Chris Lattner736ed5d2007-06-09 05:59:07 +00003998 // Check for extraneous top-level semicolon.
Chris Lattner76c72282007-10-09 17:33:22 +00003999 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00004000 ConsumeExtraSemi(InsideStruct, TagType);
Chris Lattner36e46a22007-06-09 05:49:55 +00004001 continue;
4002 }
Chris Lattnera12405b2008-04-10 06:46:29 +00004003
Andy Gibbsc804e082013-04-03 09:46:04 +00004004 // Parse _Static_assert declaration.
4005 if (Tok.is(tok::kw__Static_assert)) {
4006 SourceLocation DeclEnd;
4007 ParseStaticAssertDeclaration(DeclEnd);
4008 continue;
4009 }
4010
Argyrios Kyrtzidis71c12fb2013-04-18 01:42:35 +00004011 if (Tok.is(tok::annot_pragma_pack)) {
4012 HandlePragmaPack();
4013 continue;
4014 }
4015
4016 if (Tok.is(tok::annot_pragma_align)) {
4017 HandlePragmaAlign();
4018 continue;
4019 }
4020
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004021 if (Tok.is(tok::annot_pragma_openmp)) {
Alexey Bataev587e1de2016-03-30 10:43:55 +00004022 // Result can be ignored, because it must be always empty.
4023 AccessSpecifier AS = AS_none;
4024 ParsedAttributesWithRange Attrs(AttrFactory);
4025 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004026 continue;
4027 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004028
John McCallcfefb6d2009-11-03 02:38:08 +00004029 if (!Tok.is(tok::at)) {
Benjamin Kramera39beb92014-09-03 11:06:10 +00004030 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4031 // Install the declarator into the current TagDecl.
4032 Decl *Field =
4033 Actions.ActOnField(getCurScope(), TagDecl,
4034 FD.D.getDeclSpec().getSourceRange().getBegin(),
4035 FD.D, FD.BitfieldSize);
4036 FieldDecls.push_back(Field);
4037 FD.complete(Field);
4038 };
John McCallcfefb6d2009-11-03 02:38:08 +00004039
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004040 // Parse all the comma separated declarators.
4041 ParsingDeclSpec DS(*this);
Benjamin Kramera39beb92014-09-03 11:06:10 +00004042 ParseStructDeclaration(DS, CFieldCallback);
Chris Lattner535b8302008-06-21 19:39:06 +00004043 } else { // Handle @defs
4044 ConsumeToken();
4045 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4046 Diag(Tok, diag::err_unexpected_at);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004047 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004048 continue;
4049 }
4050 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004051 ExpectAndConsume(tok::l_paren);
Chris Lattner535b8302008-06-21 19:39:06 +00004052 if (!Tok.is(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004053 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004054 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004055 continue;
4056 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004057 SmallVector<Decl *, 16> Fields;
Douglas Gregor0be31a22010-07-02 17:43:08 +00004058 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004059 Tok.getIdentifierInfo(), Fields);
Chris Lattner535b8302008-06-21 19:39:06 +00004060 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4061 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004062 ExpectAndConsume(tok::r_paren);
Mike Stump11289f42009-09-09 15:08:12 +00004063 }
Chris Lattner736ed5d2007-06-09 05:59:07 +00004064
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004065 if (TryConsumeToken(tok::semi))
4066 continue;
4067
4068 if (Tok.is(tok::r_brace)) {
Chris Lattner245c5332010-02-02 00:37:27 +00004069 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
Chris Lattner0c7e82d2007-06-09 05:54:40 +00004070 break;
Chris Lattner90a26b02007-01-23 04:38:16 +00004071 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004072
4073 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4074 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4075 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4076 // If we stopped at a ';', eat it.
4077 TryConsumeToken(tok::semi);
Chris Lattner90a26b02007-01-23 04:38:16 +00004078 }
Mike Stump11289f42009-09-09 15:08:12 +00004079
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004080 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +00004081
John McCall084e83d2011-03-24 11:26:52 +00004082 ParsedAttributes attrs(AttrFactory);
Chris Lattner90a26b02007-01-23 04:38:16 +00004083 // If attributes exist after struct contents, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004084 MaybeParseGNUAttributes(attrs);
Daniel Dunbar15619c72008-10-03 02:03:53 +00004085
Erich Keanec480f302018-07-12 21:09:05 +00004086 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4087 T.getOpenLocation(), T.getCloseLocation(), attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004088 StructScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004089 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
Chris Lattner90a26b02007-01-23 04:38:16 +00004090}
4091
Chris Lattner3b561a32006-08-13 00:12:11 +00004092/// ParseEnumSpecifier
Chris Lattner1890ac82006-08-13 01:16:23 +00004093/// enum-specifier: [C99 6.7.2.2]
Chris Lattner3b561a32006-08-13 00:12:11 +00004094/// 'enum' identifier[opt] '{' enumerator-list '}'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004095///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
Chris Lattnere37e2332006-08-15 04:50:22 +00004096/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4097/// '}' attributes[opt]
Aaron Ballman9ecff022012-03-01 04:09:28 +00004098/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4099/// '}'
Chris Lattner3b561a32006-08-13 00:12:11 +00004100/// 'enum' identifier
Chris Lattnere37e2332006-08-15 04:50:22 +00004101/// [GNU] 'enum' attributes[opt] identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004102///
Richard Smith7d137e32012-03-23 03:33:32 +00004103/// [C++11] enum-head '{' enumerator-list[opt] '}'
4104/// [C++11] enum-head '{' enumerator-list ',' '}'
Douglas Gregor0bf31402010-10-08 23:50:27 +00004105///
Richard Smith7d137e32012-03-23 03:33:32 +00004106/// enum-head: [C++11]
4107/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4108/// enum-key attribute-specifier-seq[opt] nested-name-specifier
4109/// identifier enum-base[opt]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004110///
Richard Smith7d137e32012-03-23 03:33:32 +00004111/// enum-key: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004112/// 'enum'
4113/// 'enum' 'class'
4114/// 'enum' 'struct'
4115///
Richard Smith7d137e32012-03-23 03:33:32 +00004116/// enum-base: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004117/// ':' type-specifier-seq
4118///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004119/// [C++] elaborated-type-specifier:
4120/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4121///
Chris Lattnerffaa0e62009-04-12 21:49:30 +00004122void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregordc70c3a2010-03-02 17:53:14 +00004123 const ParsedTemplateInfo &TemplateInfo,
Richard Smithc5b05522012-03-12 07:56:15 +00004124 AccessSpecifier AS, DeclSpecContext DSC) {
Chris Lattnerffbc2712007-01-25 06:05:38 +00004125 // Parse the tag portion of this.
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004126 if (Tok.is(tok::code_completion)) {
4127 // Code completion for an enum name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004128 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00004129 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004130 }
John McCallcb432fa2011-07-06 05:58:41 +00004131
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004132 // If attributes exist after tag, parse them.
4133 ParsedAttributesWithRange attrs(AttrFactory);
4134 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004135 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004136 MaybeParseMicrosoftDeclSpecs(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004137
Richard Smith0f8ee222012-01-10 01:33:14 +00004138 SourceLocation ScopedEnumKWLoc;
John McCallcb432fa2011-07-06 05:58:41 +00004139 bool IsScopedUsingClassTag = false;
4140
John McCallbeae29a2012-06-23 22:30:04 +00004141 // In C++11, recognize 'enum class' and 'enum struct'.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004142 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
Richard Trieud0d87b52013-04-23 02:47:36 +00004143 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4144 : diag::ext_scoped_enum);
John McCallcb432fa2011-07-06 05:58:41 +00004145 IsScopedUsingClassTag = Tok.is(tok::kw_class);
Richard Smith0f8ee222012-01-10 01:33:14 +00004146 ScopedEnumKWLoc = ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004147
Bill Wendling44426052012-12-20 19:22:21 +00004148 // Attributes are not allowed between these keywords. Diagnose,
John McCallbeae29a2012-06-23 22:30:04 +00004149 // but then just treat them like they appeared in the right place.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004150 ProhibitAttributes(attrs);
John McCallbeae29a2012-06-23 22:30:04 +00004151
4152 // They are allowed afterwards, though.
4153 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004154 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004155 MaybeParseMicrosoftDeclSpecs(attrs);
John McCallcb432fa2011-07-06 05:58:41 +00004156 }
Richard Smith7d137e32012-03-23 03:33:32 +00004157
John McCall6347b682012-05-07 06:16:58 +00004158 // C++11 [temp.explicit]p12:
4159 // The usual access controls do not apply to names used to specify
4160 // explicit instantiations.
4161 // We extend this to also cover explicit specializations. Note that
4162 // we don't suppress if this turns out to be an elaborated type
4163 // specifier.
4164 bool shouldDelayDiagsInTag =
4165 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4166 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4167 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Richard Smith7d137e32012-03-23 03:33:32 +00004168
Richard Smithbfdb1082012-03-12 08:56:40 +00004169 // Enum definitions should not be parsed in a trailing-return-type.
Faisal Vali7db85c52017-12-31 00:06:40 +00004170 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
Richard Smithbfdb1082012-03-12 08:56:40 +00004171
Abramo Bagnarad7548482010-05-19 21:37:53 +00004172 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004173 if (getLangOpts().CPlusPlus) {
John McCallcb432fa2011-07-06 05:58:41 +00004174 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4175 // if a fixed underlying type is allowed.
Erik Pilkington6f11db12018-09-28 20:24:58 +00004176 ColonProtectionRAIIObject X(*this, AllowDeclaration);
Chad Rosierc1183952012-06-26 22:30:43 +00004177
Nico Webercfaa4cd2015-02-15 07:26:13 +00004178 CXXScopeSpec Spec;
David Blaikieefdccaa2016-01-15 23:43:34 +00004179 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
Richard Smith1d4b2e12013-04-01 21:43:41 +00004180 /*EnteringContext=*/true))
John McCall1f476a12010-02-26 08:45:28 +00004181 return;
4182
Nico Webercfaa4cd2015-02-15 07:26:13 +00004183 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004184 Diag(Tok, diag::err_expected) << tok::identifier;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004185 if (Tok.isNot(tok::l_brace)) {
4186 // Has no name and is not a definition.
4187 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004188 SkipUntil(tok::comma, StopAtSemi);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004189 return;
4190 }
4191 }
Nico Webercfaa4cd2015-02-15 07:26:13 +00004192
4193 SS = Spec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004194 }
Mike Stump11289f42009-09-09 15:08:12 +00004195
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004196 // Must have either 'enum name' or 'enum {...}'.
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004197 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
Erik Pilkington6f11db12018-09-28 20:24:58 +00004198 !(AllowDeclaration && Tok.is(tok::colon))) {
Alp Tokerec543272013-12-24 09:48:30 +00004199 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
Mike Stump11289f42009-09-09 15:08:12 +00004200
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004201 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004202 SkipUntil(tok::comma, StopAtSemi);
Chris Lattner3b561a32006-08-13 00:12:11 +00004203 return;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004204 }
Mike Stump11289f42009-09-09 15:08:12 +00004205
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004206 // If an identifier is present, consume and remember it.
Craig Topper161e4db2014-05-21 06:02:52 +00004207 IdentifierInfo *Name = nullptr;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004208 SourceLocation NameLoc;
4209 if (Tok.is(tok::identifier)) {
4210 Name = Tok.getIdentifierInfo();
4211 NameLoc = ConsumeToken();
4212 }
Mike Stump11289f42009-09-09 15:08:12 +00004213
Richard Smith0f8ee222012-01-10 01:33:14 +00004214 if (!Name && ScopedEnumKWLoc.isValid()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00004215 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4216 // declaration of a scoped enumeration.
4217 Diag(Tok, diag::err_scoped_enum_missing_identifier);
Richard Smith0f8ee222012-01-10 01:33:14 +00004218 ScopedEnumKWLoc = SourceLocation();
Abramo Bagnara0e05e242010-12-03 18:54:17 +00004219 IsScopedUsingClassTag = false;
Douglas Gregor0bf31402010-10-08 23:50:27 +00004220 }
4221
John McCall6347b682012-05-07 06:16:58 +00004222 // Okay, end the suppression area. We'll decide whether to emit the
4223 // diagnostics in a second.
4224 if (shouldDelayDiagsInTag)
4225 diagsFromTag.done();
Richard Smith7d137e32012-03-23 03:33:32 +00004226
Douglas Gregor0bf31402010-10-08 23:50:27 +00004227 TypeResult BaseType;
4228
Douglas Gregord1f69f62010-12-01 17:42:47 +00004229 // Parse the fixed underlying type.
Richard Smith200f47c2012-07-02 19:14:01 +00004230 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
Erik Pilkington6f11db12018-09-28 20:24:58 +00004231 if (AllowDeclaration && Tok.is(tok::colon)) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004232 bool PossibleBitfield = false;
Richard Smith200f47c2012-07-02 19:14:01 +00004233 if (CanBeBitfield) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004234 // If we're in class scope, this can either be an enum declaration with
4235 // an underlying type, or a declaration of a bitfield member. We try to
4236 // use a simple disambiguation scheme first to catch the common cases
Chad Rosierc1183952012-06-26 22:30:43 +00004237 // (integer literal, sizeof); if it's still ambiguous, we then consider
4238 // anything that's a simple-type-specifier followed by '(' as an
4239 // expression. This suffices because function types are not valid
Douglas Gregord1f69f62010-12-01 17:42:47 +00004240 // underlying types anyway.
Faisal Valid143a0c2017-04-01 21:30:49 +00004241 EnterExpressionEvaluationContext Unevaluated(
4242 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregord1f69f62010-12-01 17:42:47 +00004243 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
Chad Rosierc1183952012-06-26 22:30:43 +00004244 // If the next token starts an expression, we know we're parsing a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004245 // bit-field. This is the common case.
Richard Smithee390432014-05-16 01:56:53 +00004246 if (TPR == TPResult::True)
Douglas Gregord1f69f62010-12-01 17:42:47 +00004247 PossibleBitfield = true;
4248 // If the next token starts a type-specifier-seq, it may be either a
4249 // a fixed underlying type or the start of a function-style cast in C++;
Chad Rosierc1183952012-06-26 22:30:43 +00004250 // lookahead one more token to see if it's obvious that we have a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004251 // fixed underlying type.
Richard Smithee390432014-05-16 01:56:53 +00004252 else if (TPR == TPResult::False &&
Douglas Gregord1f69f62010-12-01 17:42:47 +00004253 GetLookAheadToken(2).getKind() == tok::semi) {
4254 // Consume the ':'.
4255 ConsumeToken();
4256 } else {
4257 // We have the start of a type-specifier-seq, so we have to perform
4258 // tentative parsing to determine whether we have an expression or a
4259 // type.
4260 TentativeParsingAction TPA(*this);
4261
4262 // Consume the ':'.
4263 ConsumeToken();
Richard Smith1e3b0f02012-02-23 01:36:12 +00004264
4265 // If we see a type specifier followed by an open-brace, we have an
4266 // ambiguity between an underlying type and a C++11 braced
4267 // function-style cast. Resolve this by always treating it as an
4268 // underlying type.
4269 // FIXME: The standard is not entirely clear on how to disambiguate in
4270 // this case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004271 if ((getLangOpts().CPlusPlus &&
Richard Smithee390432014-05-16 01:56:53 +00004272 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00004273 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004274 // We'll parse this as a bitfield later.
4275 PossibleBitfield = true;
4276 TPA.Revert();
4277 } else {
4278 // We have a type-specifier-seq.
4279 TPA.Commit();
4280 }
4281 }
4282 } else {
4283 // Consume the ':'.
4284 ConsumeToken();
4285 }
4286
4287 if (!PossibleBitfield) {
4288 SourceRange Range;
4289 BaseType = ParseTypeName(&Range);
Chad Rosierc1183952012-06-26 22:30:43 +00004290
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004291 if (!getLangOpts().ObjC) {
Erik Pilkington6f11db12018-09-28 20:24:58 +00004292 if (getLangOpts().CPlusPlus11)
4293 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4294 else if (getLangOpts().CPlusPlus)
4295 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4296 else if (getLangOpts().MicrosoftExt)
4297 Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004298 else
Erik Pilkington6f11db12018-09-28 20:24:58 +00004299 Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004300 }
Douglas Gregord1f69f62010-12-01 17:42:47 +00004301 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004302 }
4303
Richard Smith0f8ee222012-01-10 01:33:14 +00004304 // There are four options here. If we have 'friend enum foo;' then this is a
4305 // friend declaration, and cannot have an accompanying definition. If we have
4306 // 'enum foo;', then this is a forward declaration. If we have
4307 // 'enum foo {...' then this is a definition. Otherwise we have something
4308 // like 'enum foo xyz', a reference.
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004309 //
4310 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4311 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4312 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4313 //
John McCallfaf5fb42010-08-26 23:41:50 +00004314 Sema::TagUseKind TUK;
John McCall6347b682012-05-07 06:16:58 +00004315 if (!AllowDeclaration) {
Richard Smithbfdb1082012-03-12 08:56:40 +00004316 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004317 } else if (Tok.is(tok::l_brace)) {
4318 if (DS.isFriendSpecified()) {
4319 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4320 << SourceRange(DS.getFriendSpecLoc());
4321 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004322 SkipUntil(tok::r_brace, StopAtSemi);
John McCall6347b682012-05-07 06:16:58 +00004323 TUK = Sema::TUK_Friend;
4324 } else {
4325 TUK = Sema::TUK_Definition;
4326 }
Richard Smith649c7b062014-01-08 00:56:48 +00004327 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00004328 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00004329 (Tok.isAtStartOfLine() &&
4330 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
Richard Smith369b9f92012-06-25 21:37:02 +00004331 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4332 if (Tok.isNot(tok::semi)) {
4333 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00004334 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004335 PP.EnterToken(Tok);
4336 Tok.setKind(tok::semi);
4337 }
John McCall6347b682012-05-07 06:16:58 +00004338 } else {
John McCallfaf5fb42010-08-26 23:41:50 +00004339 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004340 }
4341
4342 // If this is an elaborated type specifier, and we delayed
4343 // diagnostics before, just merge them into the current pool.
4344 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4345 diagsFromTag.redelay();
4346 }
Richard Smith7d137e32012-03-23 03:33:32 +00004347
4348 MultiTemplateParamsArg TParams;
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004349 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
John McCallfaf5fb42010-08-26 23:41:50 +00004350 TUK != Sema::TUK_Reference) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004351 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
Richard Smith7d137e32012-03-23 03:33:32 +00004352 // Skip the rest of this declarator, up until the comma or semicolon.
4353 Diag(Tok, diag::err_enum_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004354 SkipUntil(tok::comma, StopAtSemi);
Richard Smith7d137e32012-03-23 03:33:32 +00004355 return;
4356 }
4357
4358 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4359 // Enumerations can't be explicitly instantiated.
4360 DS.SetTypeSpecError();
4361 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4362 return;
4363 }
4364
4365 assert(TemplateInfo.TemplateParams && "no template parameters");
4366 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4367 TemplateInfo.TemplateParams->size());
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004368 }
Chad Rosierc1183952012-06-26 22:30:43 +00004369
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004370 if (TUK == Sema::TUK_Reference)
4371 ProhibitAttributes(attrs);
Richard Smith7d137e32012-03-23 03:33:32 +00004372
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004373 if (!Name && TUK != Sema::TUK_Definition) {
4374 Diag(Tok, diag::err_enumerator_unnamed_no_def);
Richard Smith7d137e32012-03-23 03:33:32 +00004375
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004376 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004377 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004378 return;
4379 }
Richard Smith7d137e32012-03-23 03:33:32 +00004380
Nico Weber32a0fc72016-09-03 03:01:32 +00004381 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00004382
Richard Smithd9ba2242015-05-07 03:54:19 +00004383 Sema::SkipBodyInfo SkipBody;
4384 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4385 NextToken().is(tok::identifier))
4386 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4387 NextToken().getIdentifierInfo(),
4388 NextToken().getLocation());
4389
Douglas Gregord6ab8742009-05-28 23:31:59 +00004390 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004391 bool IsDependent = false;
Craig Topper161e4db2014-05-21 06:02:52 +00004392 const char *PrevSpec = nullptr;
Douglas Gregorba41d012010-04-24 16:38:41 +00004393 unsigned DiagID;
Faisal Vali7db85c52017-12-31 00:06:40 +00004394 Decl *TagDecl = Actions.ActOnTag(
4395 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
Erich Keanec480f302018-07-12 21:09:05 +00004396 attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4397 ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
Faisal Vali7db85c52017-12-31 00:06:40 +00004398 DSC == DeclSpecContext::DSC_type_specifier,
4399 DSC == DeclSpecContext::DSC_template_param ||
4400 DSC == DeclSpecContext::DSC_template_type_arg,
4401 &SkipBody);
Richard Smithd9ba2242015-05-07 03:54:19 +00004402
4403 if (SkipBody.ShouldSkip) {
4404 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4405
4406 BalancedDelimiterTracker T(*this, tok::l_brace);
4407 T.consumeOpen();
4408 T.skipToEnd();
4409
4410 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4411 NameLoc.isValid() ? NameLoc : StartLoc,
4412 PrevSpec, DiagID, TagDecl, Owned,
4413 Actions.getASTContext().getPrintingPolicy()))
4414 Diag(StartLoc, DiagID) << PrevSpec;
4415 return;
4416 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004417
Douglas Gregorba41d012010-04-24 16:38:41 +00004418 if (IsDependent) {
Chad Rosierc1183952012-06-26 22:30:43 +00004419 // This enum has a dependent nested-name-specifier. Handle it as a
Douglas Gregorba41d012010-04-24 16:38:41 +00004420 // dependent tag.
4421 if (!Name) {
4422 DS.SetTypeSpecError();
4423 Diag(Tok, diag::err_expected_type_name_after_typename);
4424 return;
4425 }
Chad Rosierc1183952012-06-26 22:30:43 +00004426
Nico Weber83ea0122014-05-03 21:57:40 +00004427 TypeResult Type = Actions.ActOnDependentTag(
4428 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
Douglas Gregorba41d012010-04-24 16:38:41 +00004429 if (Type.isInvalid()) {
4430 DS.SetTypeSpecError();
4431 return;
4432 }
Chad Rosierc1183952012-06-26 22:30:43 +00004433
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004434 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4435 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004436 PrevSpec, DiagID, Type.get(),
4437 Actions.getASTContext().getPrintingPolicy()))
Douglas Gregorba41d012010-04-24 16:38:41 +00004438 Diag(StartLoc, DiagID) << PrevSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00004439
Douglas Gregorba41d012010-04-24 16:38:41 +00004440 return;
4441 }
Mike Stump11289f42009-09-09 15:08:12 +00004442
John McCall48871652010-08-21 09:40:31 +00004443 if (!TagDecl) {
Chad Rosierc1183952012-06-26 22:30:43 +00004444 // The action failed to produce an enumeration tag. If this is a
Douglas Gregorba41d012010-04-24 16:38:41 +00004445 // definition, consume the entire definition.
Richard Smithbfdb1082012-03-12 08:56:40 +00004446 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
Douglas Gregorba41d012010-04-24 16:38:41 +00004447 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004448 SkipUntil(tok::r_brace, StopAtSemi);
Douglas Gregorba41d012010-04-24 16:38:41 +00004449 }
Chad Rosierc1183952012-06-26 22:30:43 +00004450
Douglas Gregorba41d012010-04-24 16:38:41 +00004451 DS.SetTypeSpecError();
4452 return;
4453 }
Richard Smith0f8ee222012-01-10 01:33:14 +00004454
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004455 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4456 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4457 ParseEnumBody(StartLoc, D);
4458 if (SkipBody.CheckSameAsPrevious &&
4459 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4460 DS.SetTypeSpecError();
4461 return;
4462 }
4463 }
Mike Stump11289f42009-09-09 15:08:12 +00004464
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004465 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4466 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004467 PrevSpec, DiagID, TagDecl, Owned,
4468 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00004469 Diag(StartLoc, DiagID) << PrevSpec;
Chris Lattner3b561a32006-08-13 00:12:11 +00004470}
4471
Chris Lattnerc1915e22007-01-25 07:29:02 +00004472/// ParseEnumBody - Parse a {} enclosed enumerator-list.
4473/// enumerator-list:
4474/// enumerator
4475/// enumerator-list ',' enumerator
4476/// enumerator:
Aaron Ballman730476b2014-11-08 15:33:35 +00004477/// enumeration-constant attributes[opt]
4478/// enumeration-constant attributes[opt] '=' constant-expression
Chris Lattnerc1915e22007-01-25 07:29:02 +00004479/// enumeration-constant:
4480/// identifier
4481///
John McCall48871652010-08-21 09:40:31 +00004482void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004483 // Enter the scope of the enum body and start the definition.
Hans Wennborgfe781452014-06-17 00:00:18 +00004484 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004485 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
Douglas Gregor07665a62009-01-05 19:45:36 +00004486
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004487 BalancedDelimiterTracker T(*this, tok::l_brace);
4488 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00004489
Chris Lattner37256fb2007-08-27 17:24:30 +00004490 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
David Blaikiebbafb8a2012-03-11 07:00:24 +00004491 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
Richard Smithf8812672016-12-02 22:38:31 +00004492 Diag(Tok, diag::err_empty_enum);
Mike Stump11289f42009-09-09 15:08:12 +00004493
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004494 SmallVector<Decl *, 32> EnumConstantDecls;
Jordan Rose60ac3162015-04-30 17:20:30 +00004495 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
Chris Lattnerc1915e22007-01-25 07:29:02 +00004496
Craig Topper161e4db2014-05-21 06:02:52 +00004497 Decl *LastEnumConstDecl = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004498
Chris Lattnerc1915e22007-01-25 07:29:02 +00004499 // Parse the enumerator-list.
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004500 while (Tok.isNot(tok::r_brace)) {
4501 // Parse enumerator. If failed, try skipping till the start of the next
4502 // enumerator definition.
4503 if (Tok.isNot(tok::identifier)) {
4504 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4505 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4506 TryConsumeToken(tok::comma))
4507 continue;
4508 break;
4509 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004510 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4511 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00004512
John McCall811a0f52010-10-22 23:36:17 +00004513 // If attributes exist after the enumerator, parse them.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004514 ParsedAttributesWithRange attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004515 MaybeParseGNUAttributes(attrs);
Aaron Ballman730476b2014-11-08 15:33:35 +00004516 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
Aaron Ballman606093a2017-10-15 15:01:42 +00004517 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4518 if (getLangOpts().CPlusPlus)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004519 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Aaron Ballman606093a2017-10-15 15:01:42 +00004520 ? diag::warn_cxx14_compat_ns_enum_attribute
4521 : diag::ext_ns_enum_attribute)
4522 << 1 /*enumerator*/;
Aaron Ballman730476b2014-11-08 15:33:35 +00004523 ParseCXX11Attributes(attrs);
4524 }
John McCall811a0f52010-10-22 23:36:17 +00004525
Chris Lattnerc1915e22007-01-25 07:29:02 +00004526 SourceLocation EqualLoc;
John McCalldadc5752010-08-24 06:29:42 +00004527 ExprResult AssignedVal;
Jordan Rose60ac3162015-04-30 17:20:30 +00004528 EnumAvailabilityDiags.emplace_back(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00004529
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004530 if (TryConsumeToken(tok::equal, EqualLoc)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004531 AssignedVal = ParseConstantExpression();
4532 if (AssignedVal.isInvalid())
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004533 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
Chris Lattnerc1915e22007-01-25 07:29:02 +00004534 }
Mike Stump11289f42009-09-09 15:08:12 +00004535
Chris Lattnerc1915e22007-01-25 07:29:02 +00004536 // Install the enumerator constant into EnumDecl.
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004537 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
Erich Keanec480f302018-07-12 21:09:05 +00004538 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4539 EqualLoc, AssignedVal.get());
Jordan Rose60ac3162015-04-30 17:20:30 +00004540 EnumAvailabilityDiags.back().done();
Chad Rosierc1183952012-06-26 22:30:43 +00004541
Chris Lattner4ef40012007-06-11 01:28:17 +00004542 EnumConstantDecls.push_back(EnumConstDecl);
4543 LastEnumConstDecl = EnumConstDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004544
Douglas Gregorce66d022010-09-07 14:51:08 +00004545 if (Tok.is(tok::identifier)) {
4546 // We're missing a comma between enumerators.
Richard Smithbdb84f32016-07-22 23:36:59 +00004547 SourceLocation Loc = getEndOfPreviousToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004548 Diag(Loc, diag::err_enumerator_list_missing_comma)
Douglas Gregorce66d022010-09-07 14:51:08 +00004549 << FixItHint::CreateInsertion(Loc, ", ");
4550 continue;
4551 }
Chad Rosierc1183952012-06-26 22:30:43 +00004552
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004553 // Emumerator definition must be finished, only comma or r_brace are
4554 // allowed here.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004555 SourceLocation CommaLoc;
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004556 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4557 if (EqualLoc.isValid())
4558 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4559 << tok::comma;
4560 else
4561 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4562 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4563 if (TryConsumeToken(tok::comma, CommaLoc))
4564 continue;
4565 } else {
4566 break;
4567 }
4568 }
Mike Stump11289f42009-09-09 15:08:12 +00004569
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004570 // If comma is followed by r_brace, emit appropriate warning.
4571 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004572 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
Richard Smith87f5dc52012-07-23 05:45:25 +00004573 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4574 diag::ext_enumerator_list_comma_cxx :
4575 diag::ext_enumerator_list_comma_c)
Richard Smith5d164bc2011-10-15 05:09:34 +00004576 << FixItHint::CreateRemoval(CommaLoc);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004577 else if (getLangOpts().CPlusPlus11)
Richard Smith5d164bc2011-10-15 05:09:34 +00004578 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4579 << FixItHint::CreateRemoval(CommaLoc);
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004580 break;
Richard Smith5d164bc2011-10-15 05:09:34 +00004581 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004582 }
Mike Stump11289f42009-09-09 15:08:12 +00004583
Chris Lattnerc1915e22007-01-25 07:29:02 +00004584 // Eat the }.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004585 T.consumeClose();
Chris Lattnerc1915e22007-01-25 07:29:02 +00004586
Chris Lattnerc1915e22007-01-25 07:29:02 +00004587 // If attributes exist after the identifier list, parse them.
John McCall084e83d2011-03-24 11:26:52 +00004588 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004589 MaybeParseGNUAttributes(attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004590
Erich Keanec480f302018-07-12 21:09:05 +00004591 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4592 getCurScope(), attrs);
Mike Stump11289f42009-09-09 15:08:12 +00004593
Jordan Rose60ac3162015-04-30 17:20:30 +00004594 // Now handle enum constant availability diagnostics.
4595 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4596 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4597 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4598 EnumAvailabilityDiags[i].redelay();
4599 PD.complete(EnumConstantDecls[i]);
4600 }
4601
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004602 EnumScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004603 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
Richard Smith369b9f92012-06-25 21:37:02 +00004604
4605 // The next token must be valid after an enum definition. If not, a ';'
4606 // was probably forgotten.
Richard Smith200f47c2012-07-02 19:14:01 +00004607 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4608 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
Alp Toker383d2c42014-01-01 03:08:43 +00004609 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004610 // Push this token back into the preprocessor and change our current token
4611 // to ';' so that the rest of the code recovers as though there were an
4612 // ';' after the definition.
4613 PP.EnterToken(Tok);
4614 Tok.setKind(tok::semi);
4615 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004616}
Chris Lattner3b561a32006-08-13 00:12:11 +00004617
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004618/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4619/// is definitely a type-specifier. Return false if it isn't part of a type
4620/// specifier or if we're not sure.
4621bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4622 switch (Tok.getKind()) {
4623 default: return false;
4624 // type-specifiers
4625 case tok::kw_short:
4626 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004627 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004628 case tok::kw___int128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004629 case tok::kw_signed:
4630 case tok::kw_unsigned:
4631 case tok::kw__Complex:
4632 case tok::kw__Imaginary:
4633 case tok::kw_void:
4634 case tok::kw_char:
4635 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004636 case tok::kw_char8_t:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004637 case tok::kw_char16_t:
4638 case tok::kw_char32_t:
4639 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004640 case tok::kw_half:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004641 case tok::kw_float:
4642 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004643 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004644 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004645 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004646 case tok::kw___float128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004647 case tok::kw_bool:
4648 case tok::kw__Bool:
4649 case tok::kw__Decimal32:
4650 case tok::kw__Decimal64:
4651 case tok::kw__Decimal128:
4652 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004653#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004654#include "clang/Basic/OpenCLImageTypes.def"
Chad Rosierc1183952012-06-26 22:30:43 +00004655
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004656 // struct-or-union-specifier (C99) or class-specifier (C++)
4657 case tok::kw_class:
4658 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004659 case tok::kw___interface:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004660 case tok::kw_union:
4661 // enum-specifier
4662 case tok::kw_enum:
Chad Rosierc1183952012-06-26 22:30:43 +00004663
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004664 // typedef-name
4665 case tok::annot_typename:
4666 return true;
4667 }
4668}
4669
Steve Naroff69e8f9e2008-02-11 23:15:56 +00004670/// isTypeSpecifierQualifier - Return true if the current token could be the
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004671/// start of a specifier-qualifier-list.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004672bool Parser::isTypeSpecifierQualifier() {
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004673 switch (Tok.getKind()) {
4674 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004675
Chris Lattner020bab92009-01-04 23:41:41 +00004676 case tok::identifier: // foo::bar
John Thompson22334602010-02-05 00:12:22 +00004677 if (TryAltiVecVectorToken())
4678 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004679 LLVM_FALLTHROUGH;
Douglas Gregor333489b2009-03-27 23:10:48 +00004680 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004681 // Annotate typenames and C++ scope specifiers. If we get one, just
4682 // recurse to handle whatever we get.
4683 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004684 return true;
4685 if (Tok.is(tok::identifier))
4686 return false;
4687 return isTypeSpecifierQualifier();
Douglas Gregor333489b2009-03-27 23:10:48 +00004688
Chris Lattner020bab92009-01-04 23:41:41 +00004689 case tok::coloncolon: // ::foo::bar
4690 if (NextToken().is(tok::kw_new) || // ::new
4691 NextToken().is(tok::kw_delete)) // ::delete
4692 return false;
4693
Chris Lattner020bab92009-01-04 23:41:41 +00004694 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004695 return true;
4696 return isTypeSpecifierQualifier();
Mike Stump11289f42009-09-09 15:08:12 +00004697
Chris Lattnere37e2332006-08-15 04:50:22 +00004698 // GNU attributes support.
4699 case tok::kw___attribute:
Steve Naroffad373bd2007-07-31 12:34:36 +00004700 // GNU typeof support.
4701 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004702
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004703 // type-specifiers
4704 case tok::kw_short:
4705 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004706 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004707 case tok::kw___int128:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004708 case tok::kw_signed:
4709 case tok::kw_unsigned:
4710 case tok::kw__Complex:
4711 case tok::kw__Imaginary:
4712 case tok::kw_void:
4713 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004714 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004715 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004716 case tok::kw_char16_t:
4717 case tok::kw_char32_t:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004718 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004719 case tok::kw_half:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004720 case tok::kw_float:
4721 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004722 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004723 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004724 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004725 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004726 case tok::kw_bool:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004727 case tok::kw__Bool:
4728 case tok::kw__Decimal32:
4729 case tok::kw__Decimal64:
4730 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004731 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004732#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004733#include "clang/Basic/OpenCLImageTypes.def"
Mike Stump11289f42009-09-09 15:08:12 +00004734
Chris Lattner861a2262008-04-13 18:59:07 +00004735 // struct-or-union-specifier (C99) or class-specifier (C++)
4736 case tok::kw_class:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004737 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004738 case tok::kw___interface:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004739 case tok::kw_union:
4740 // enum-specifier
4741 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004742
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004743 // type-qualifier
4744 case tok::kw_const:
4745 case tok::kw_volatile:
4746 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004747 case tok::kw__Sat:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004748
John McCallea0a39e2012-11-14 00:49:39 +00004749 // Debugger support.
4750 case tok::kw___unknown_anytype:
4751
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004752 // typedef-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00004753 case tok::annot_typename:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004754 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004755
Chris Lattner409bf7d2008-10-20 00:25:30 +00004756 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4757 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004758 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00004759
Steve Naroff44ac7772008-12-25 14:16:32 +00004760 case tok::kw___cdecl:
4761 case tok::kw___stdcall:
4762 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004763 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004764 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004765 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004766 case tok::kw___w64:
4767 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004768 case tok::kw___ptr32:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004769 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004770 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004771
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004772 case tok::kw__Nonnull:
4773 case tok::kw__Nullable:
4774 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004775
Douglas Gregorab209d82015-07-07 03:58:42 +00004776 case tok::kw___kindof:
4777
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004778 case tok::kw___private:
4779 case tok::kw___local:
4780 case tok::kw___global:
4781 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004782 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004783 case tok::kw___read_only:
4784 case tok::kw___read_write:
4785 case tok::kw___write_only:
4786
Eli Friedman53339e02009-06-08 23:27:34 +00004787 return true;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004788
Richard Smith8e1ac332013-03-28 01:55:44 +00004789 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004790 case tok::kw__Atomic:
4791 return true;
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004792 }
4793}
4794
Chris Lattneracd58a32006-08-06 17:24:14 +00004795/// isDeclarationSpecifier() - Return true if the current token is part of a
4796/// declaration specifier.
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004797///
4798/// \param DisambiguatingWithExpression True to indicate that the purpose of
4799/// this check is to disambiguate between an expression and a declaration.
4800bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
Chris Lattneracd58a32006-08-06 17:24:14 +00004801 switch (Tok.getKind()) {
4802 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004803
Xiuli Pan9c14e282016-01-09 12:53:17 +00004804 case tok::kw_pipe:
4805 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4806
Chris Lattner020bab92009-01-04 23:41:41 +00004807 case tok::identifier: // foo::bar
Steve Naroff9527bbf2009-03-09 21:12:44 +00004808 // Unfortunate hack to support "Class.factoryMethod" notation.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004809 if (getLangOpts().ObjC && NextToken().is(tok::period))
Steve Naroff9527bbf2009-03-09 21:12:44 +00004810 return false;
John Thompson22334602010-02-05 00:12:22 +00004811 if (TryAltiVecVectorToken())
4812 return true;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00004813 LLVM_FALLTHROUGH;
David Blaikie15a430a2011-12-04 05:04:18 +00004814 case tok::kw_decltype: // decltype(T())::type
Douglas Gregor333489b2009-03-27 23:10:48 +00004815 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004816 // Annotate typenames and C++ scope specifiers. If we get one, just
4817 // recurse to handle whatever we get.
4818 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004819 return true;
4820 if (Tok.is(tok::identifier))
4821 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004822
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004823 // If we're in Objective-C and we have an Objective-C class type followed
Chad Rosierc1183952012-06-26 22:30:43 +00004824 // by an identifier and then either ':' or ']', in a place where an
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004825 // expression is permitted, then this is probably a class message send
4826 // missing the initial '['. In this case, we won't consider this to be
4827 // the start of a declaration.
Chad Rosierc1183952012-06-26 22:30:43 +00004828 if (DisambiguatingWithExpression &&
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004829 isStartOfObjCClassMessageMissingOpenBracket())
4830 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004831
John McCall1f476a12010-02-26 08:45:28 +00004832 return isDeclarationSpecifier();
4833
Chris Lattner020bab92009-01-04 23:41:41 +00004834 case tok::coloncolon: // ::foo::bar
4835 if (NextToken().is(tok::kw_new) || // ::new
4836 NextToken().is(tok::kw_delete)) // ::delete
4837 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004838
Chris Lattner020bab92009-01-04 23:41:41 +00004839 // Annotate typenames and C++ scope specifiers. If we get one, just
4840 // recurse to handle whatever we get.
4841 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004842 return true;
4843 return isDeclarationSpecifier();
Mike Stump11289f42009-09-09 15:08:12 +00004844
Chris Lattneracd58a32006-08-06 17:24:14 +00004845 // storage-class-specifier
4846 case tok::kw_typedef:
4847 case tok::kw_extern:
Steve Naroff2050b0d2007-12-18 00:16:02 +00004848 case tok::kw___private_extern__:
Chris Lattneracd58a32006-08-06 17:24:14 +00004849 case tok::kw_static:
4850 case tok::kw_auto:
Richard Smithe301ba22015-11-11 02:02:15 +00004851 case tok::kw___auto_type:
Chris Lattneracd58a32006-08-06 17:24:14 +00004852 case tok::kw_register:
4853 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00004854 case tok::kw_thread_local:
4855 case tok::kw__Thread_local:
Mike Stump11289f42009-09-09 15:08:12 +00004856
Douglas Gregor26701a42011-09-09 02:06:17 +00004857 // Modules
4858 case tok::kw___module_private__:
Chad Rosierc1183952012-06-26 22:30:43 +00004859
John McCallea0a39e2012-11-14 00:49:39 +00004860 // Debugger support
4861 case tok::kw___unknown_anytype:
4862
Chris Lattneracd58a32006-08-06 17:24:14 +00004863 // type-specifiers
4864 case tok::kw_short:
4865 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004866 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004867 case tok::kw___int128:
Chris Lattneracd58a32006-08-06 17:24:14 +00004868 case tok::kw_signed:
4869 case tok::kw_unsigned:
4870 case tok::kw__Complex:
4871 case tok::kw__Imaginary:
4872 case tok::kw_void:
4873 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004874 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004875 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004876 case tok::kw_char16_t:
4877 case tok::kw_char32_t:
4878
Chris Lattneracd58a32006-08-06 17:24:14 +00004879 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004880 case tok::kw_half:
Chris Lattneracd58a32006-08-06 17:24:14 +00004881 case tok::kw_float:
4882 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004883 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004884 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004885 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004886 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004887 case tok::kw_bool:
Chris Lattneracd58a32006-08-06 17:24:14 +00004888 case tok::kw__Bool:
4889 case tok::kw__Decimal32:
4890 case tok::kw__Decimal64:
4891 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004892 case tok::kw___vector:
Mike Stump11289f42009-09-09 15:08:12 +00004893
Chris Lattner861a2262008-04-13 18:59:07 +00004894 // struct-or-union-specifier (C99) or class-specifier (C++)
4895 case tok::kw_class:
Chris Lattneracd58a32006-08-06 17:24:14 +00004896 case tok::kw_struct:
4897 case tok::kw_union:
Joao Matosdc86f942012-08-31 18:45:21 +00004898 case tok::kw___interface:
Chris Lattneracd58a32006-08-06 17:24:14 +00004899 // enum-specifier
4900 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004901
Chris Lattneracd58a32006-08-06 17:24:14 +00004902 // type-qualifier
4903 case tok::kw_const:
4904 case tok::kw_volatile:
4905 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004906 case tok::kw__Sat:
Steve Naroffad373bd2007-07-31 12:34:36 +00004907
Chris Lattneracd58a32006-08-06 17:24:14 +00004908 // function-specifier
4909 case tok::kw_inline:
Douglas Gregor61956c42008-10-31 09:07:45 +00004910 case tok::kw_virtual:
4911 case tok::kw_explicit:
Richard Smith0015f092013-01-17 22:16:11 +00004912 case tok::kw__Noreturn:
Chris Lattner7b20dc72007-08-09 16:40:21 +00004913
Richard Smith1dba27c2013-01-29 09:02:09 +00004914 // alignment-specifier
4915 case tok::kw__Alignas:
4916
Richard Smithd16fe122012-10-25 00:00:53 +00004917 // friend keyword.
4918 case tok::kw_friend:
4919
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00004920 // static_assert-declaration
4921 case tok::kw__Static_assert:
4922
Chris Lattner599e47e2007-08-09 17:01:07 +00004923 // GNU typeof support.
4924 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004925
Chris Lattner599e47e2007-08-09 17:01:07 +00004926 // GNU attributes.
Chris Lattner7b20dc72007-08-09 16:40:21 +00004927 case tok::kw___attribute:
Mike Stump11289f42009-09-09 15:08:12 +00004928
Richard Smithd16fe122012-10-25 00:00:53 +00004929 // C++11 decltype and constexpr.
David Blaikie15a430a2011-12-04 05:04:18 +00004930 case tok::annot_decltype:
Richard Smithd16fe122012-10-25 00:00:53 +00004931 case tok::kw_constexpr:
Francois Pichete878cb62011-06-19 08:02:06 +00004932
Richard Smith8e1ac332013-03-28 01:55:44 +00004933 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004934 case tok::kw__Atomic:
4935 return true;
4936
Chris Lattner8b2ec162008-07-26 03:38:44 +00004937 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4938 case tok::less:
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004939 return getLangOpts().ObjC;
Mike Stump11289f42009-09-09 15:08:12 +00004940
Douglas Gregor19b7acf2011-04-27 05:41:15 +00004941 // typedef-name
4942 case tok::annot_typename:
4943 return !DisambiguatingWithExpression ||
4944 !isStartOfObjCClassMessageMissingOpenBracket();
Chad Rosierc1183952012-06-26 22:30:43 +00004945
Steve Narofff192fab2009-01-06 19:34:12 +00004946 case tok::kw___declspec:
Steve Naroff44ac7772008-12-25 14:16:32 +00004947 case tok::kw___cdecl:
4948 case tok::kw___stdcall:
4949 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004950 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004951 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004952 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004953 case tok::kw___w64:
Aaron Ballman317a77f2013-05-22 23:25:32 +00004954 case tok::kw___sptr:
4955 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00004956 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004957 case tok::kw___ptr32:
Eli Friedman53339e02009-06-08 23:27:34 +00004958 case tok::kw___forceinline:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004959 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004960 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004961
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004962 case tok::kw__Nonnull:
4963 case tok::kw__Nullable:
4964 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004965
Douglas Gregorab209d82015-07-07 03:58:42 +00004966 case tok::kw___kindof:
4967
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004968 case tok::kw___private:
4969 case tok::kw___local:
4970 case tok::kw___global:
4971 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004972 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004973 case tok::kw___read_only:
4974 case tok::kw___read_write:
4975 case tok::kw___write_only:
Alexey Bader954ba212016-04-08 13:40:33 +00004976#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004977#include "clang/Basic/OpenCLImageTypes.def"
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004978
Eli Friedman53339e02009-06-08 23:27:34 +00004979 return true;
Chris Lattneracd58a32006-08-06 17:24:14 +00004980 }
4981}
4982
Richard Smith35845152017-02-07 01:37:30 +00004983bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004984 TentativeParsingAction TPA(*this);
4985
4986 // Parse the C++ scope specifier.
4987 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00004988 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00004989 /*EnteringContext=*/true)) {
John McCall1f476a12010-02-26 08:45:28 +00004990 TPA.Revert();
4991 return false;
4992 }
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004993
4994 // Parse the constructor name.
Richard Smithaf3b3252017-05-18 19:21:48 +00004995 if (Tok.is(tok::identifier)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004996 // We already know that we have a constructor name; just consume
4997 // the token.
4998 ConsumeToken();
Richard Smithaf3b3252017-05-18 19:21:48 +00004999 } else if (Tok.is(tok::annot_template_id)) {
5000 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005001 } else {
5002 TPA.Revert();
5003 return false;
5004 }
5005
Richard Smith8f8697f2017-02-08 01:16:55 +00005006 // There may be attributes here, appertaining to the constructor name or type
5007 // we just stepped past.
5008 SkipCXX11Attributes();
5009
Richard Smith43f340f2012-03-27 23:05:05 +00005010 // Current class name must be followed by a left parenthesis.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005011 if (Tok.isNot(tok::l_paren)) {
5012 TPA.Revert();
5013 return false;
5014 }
5015 ConsumeParen();
5016
Richard Smith43f340f2012-03-27 23:05:05 +00005017 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5018 // that we have a constructor.
5019 if (Tok.is(tok::r_paren) ||
5020 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005021 TPA.Revert();
5022 return true;
5023 }
5024
Richard Smithf2163662013-09-06 00:12:20 +00005025 // A C++11 attribute here signals that we have a constructor, and is an
5026 // attribute on the first constructor parameter.
5027 if (getLangOpts().CPlusPlus11 &&
5028 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5029 /*OuterMightBeMessageSend*/ true)) {
5030 TPA.Revert();
5031 return true;
5032 }
5033
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005034 // If we need to, enter the specified scope.
5035 DeclaratorScopeObj DeclScopeObj(*this, SS);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005036 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005037 DeclScopeObj.EnterDeclaratorScope();
5038
Francois Pichet79f3a872011-01-31 04:54:32 +00005039 // Optionally skip Microsoft attributes.
John McCall084e83d2011-03-24 11:26:52 +00005040 ParsedAttributes Attrs(AttrFactory);
Francois Pichet79f3a872011-01-31 04:54:32 +00005041 MaybeParseMicrosoftAttributes(Attrs);
5042
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005043 // Check whether the next token(s) are part of a declaration
5044 // specifier, in which case we have the start of a parameter and,
5045 // therefore, we know that this is a constructor.
Richard Smithefd009d2012-03-27 00:56:56 +00005046 bool IsConstructor = false;
5047 if (isDeclarationSpecifier())
5048 IsConstructor = true;
5049 else if (Tok.is(tok::identifier) ||
5050 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5051 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5052 // This might be a parenthesized member name, but is more likely to
5053 // be a constructor declaration with an invalid argument type. Keep
5054 // looking.
5055 if (Tok.is(tok::annot_cxxscope))
Richard Smithaf3b3252017-05-18 19:21:48 +00005056 ConsumeAnnotationToken();
Richard Smithefd009d2012-03-27 00:56:56 +00005057 ConsumeToken();
5058
5059 // If this is not a constructor, we must be parsing a declarator,
Richard Smith1453e312012-03-27 01:42:32 +00005060 // which must have one of the following syntactic forms (see the
5061 // grammar extract at the start of ParseDirectDeclarator):
Richard Smithefd009d2012-03-27 00:56:56 +00005062 switch (Tok.getKind()) {
5063 case tok::l_paren:
5064 // C(X ( int));
5065 case tok::l_square:
5066 // C(X [ 5]);
5067 // C(X [ [attribute]]);
5068 case tok::coloncolon:
5069 // C(X :: Y);
5070 // C(X :: *p);
Richard Smithefd009d2012-03-27 00:56:56 +00005071 // Assume this isn't a constructor, rather than assuming it's a
5072 // constructor with an unnamed parameter of an ill-formed type.
5073 break;
5074
Richard Smith446161b2014-03-03 21:12:53 +00005075 case tok::r_paren:
5076 // C(X )
Richard Smith8f8697f2017-02-08 01:16:55 +00005077
5078 // Skip past the right-paren and any following attributes to get to
5079 // the function body or trailing-return-type.
5080 ConsumeParen();
5081 SkipCXX11Attributes();
5082
Richard Smith35845152017-02-07 01:37:30 +00005083 if (DeductionGuide) {
5084 // C(X) -> ... is a deduction guide.
Richard Smith8f8697f2017-02-08 01:16:55 +00005085 IsConstructor = Tok.is(tok::arrow);
Richard Smith35845152017-02-07 01:37:30 +00005086 break;
5087 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005088 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
Richard Smith446161b2014-03-03 21:12:53 +00005089 // Assume these were meant to be constructors:
5090 // C(X) : (the name of a bit-field cannot be parenthesized).
5091 // C(X) try (this is otherwise ill-formed).
5092 IsConstructor = true;
5093 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005094 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
Richard Smith446161b2014-03-03 21:12:53 +00005095 // If we have a constructor name within the class definition,
5096 // assume these were meant to be constructors:
5097 // C(X) {
5098 // C(X) ;
5099 // ... because otherwise we would be declaring a non-static data
5100 // member that is ill-formed because it's of the same type as its
5101 // surrounding class.
5102 //
5103 // FIXME: We can actually do this whether or not the name is qualified,
5104 // because if it is qualified in this context it must be being used as
Richard Smith35845152017-02-07 01:37:30 +00005105 // a constructor name.
Richard Smith446161b2014-03-03 21:12:53 +00005106 // currently, so we're somewhat conservative here.
5107 IsConstructor = IsUnqualified;
5108 }
5109 break;
5110
Richard Smithefd009d2012-03-27 00:56:56 +00005111 default:
5112 IsConstructor = true;
5113 break;
5114 }
5115 }
5116
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005117 TPA.Revert();
5118 return IsConstructor;
5119}
Chris Lattnerb9093cd2006-08-04 04:39:53 +00005120
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005121/// ParseTypeQualifierListOpt
Dawn Perchik335e16b2010-09-03 01:29:35 +00005122/// type-qualifier-list: [C99 6.7.5]
5123/// type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005124/// [vendor] attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005125/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005126/// type-qualifier-list type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005127/// [vendor] type-qualifier-list attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005128/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005129/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
Aaron Ballman08b06592014-07-22 12:44:22 +00005130/// [ only if AttReqs & AR_CXX11AttributesParsed ]
5131/// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5132/// AttrRequirements bitmask values.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005133void Parser::ParseTypeQualifierListOpt(
5134 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5135 bool IdentifierRequired,
5136 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
Aaron Ballman606093a2017-10-15 15:01:42 +00005137 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005138 isCXX11AttributeSpecifier()) {
John McCall084e83d2011-03-24 11:26:52 +00005139 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith3dff2512012-04-10 03:25:07 +00005140 ParseCXX11Attributes(attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005141 DS.takeAttributesFrom(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005142 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005143
5144 SourceLocation EndLoc;
5145
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005146 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00005147 bool isInvalid = false;
Craig Topper161e4db2014-05-21 06:02:52 +00005148 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00005149 unsigned DiagID = 0;
Chris Lattner60809f52006-11-28 05:18:46 +00005150 SourceLocation Loc = Tok.getLocation();
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005151
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005152 switch (Tok.getKind()) {
Douglas Gregor28c78432010-08-27 17:35:51 +00005153 case tok::code_completion:
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005154 if (CodeCompletionHandler)
5155 (*CodeCompletionHandler)();
5156 else
5157 Actions.CodeCompleteTypeQualifiers(DS);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00005158 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00005159
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005160 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00005161 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005162 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005163 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005164 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00005165 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005166 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005167 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005168 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00005169 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005170 getLangOpts());
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005171 break;
Richard Smith8e1ac332013-03-28 01:55:44 +00005172 case tok::kw__Atomic:
5173 if (!AtomicAllowed)
5174 goto DoneWithTypeQuals;
5175 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5176 getLangOpts());
5177 break;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005178
5179 // OpenCL qualifiers:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005180 case tok::kw___private:
5181 case tok::kw___global:
5182 case tok::kw___local:
5183 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005184 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005185 case tok::kw___read_only:
5186 case tok::kw___write_only:
5187 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00005188 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005189 break;
5190
Andrey Bokhanko45d41322016-05-11 18:38:21 +00005191 case tok::kw___unaligned:
5192 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5193 getLangOpts());
5194 break;
Aaron Ballman317a77f2013-05-22 23:25:32 +00005195 case tok::kw___uptr:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005196 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
Alp Toker62c5b572013-11-26 01:30:10 +00005197 // with the MS modifier keyword.
Aaron Ballman08b06592014-07-22 12:44:22 +00005198 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
Alp Toker47642d22013-12-03 06:13:01 +00005199 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5200 if (TryKeywordIdentFallback(false))
5201 continue;
Alp Toker62c5b572013-11-26 01:30:10 +00005202 }
Galina Kistanova77674252017-06-01 21:15:34 +00005203 LLVM_FALLTHROUGH;
Alp Toker62c5b572013-11-26 01:30:10 +00005204 case tok::kw___sptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005205 case tok::kw___w64:
Steve Narofff9c29d42008-12-25 14:41:26 +00005206 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005207 case tok::kw___ptr32:
Steve Naroff44ac7772008-12-25 14:16:32 +00005208 case tok::kw___cdecl:
5209 case tok::kw___stdcall:
5210 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005211 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005212 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005213 case tok::kw___vectorcall:
Aaron Ballman08b06592014-07-22 12:44:22 +00005214 if (AttrReqs & AR_DeclspecAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005215 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00005216 continue;
5217 }
5218 goto DoneWithTypeQuals;
Dawn Perchik335e16b2010-09-03 01:29:35 +00005219 case tok::kw___pascal:
Aaron Ballman08b06592014-07-22 12:44:22 +00005220 if (AttrReqs & AR_VendorAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005221 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00005222 continue;
5223 }
5224 goto DoneWithTypeQuals;
Douglas Gregor261a89b2015-06-19 17:51:05 +00005225
5226 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005227 case tok::kw__Nonnull:
5228 case tok::kw__Nullable:
5229 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005230 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5231 continue;
5232
Douglas Gregorab209d82015-07-07 03:58:42 +00005233 // Objective-C 'kindof' types.
5234 case tok::kw___kindof:
5235 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00005236 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00005237 (void)ConsumeToken();
5238 continue;
5239
Chris Lattnere37e2332006-08-15 04:50:22 +00005240 case tok::kw___attribute:
Aaron Ballman08b06592014-07-22 12:44:22 +00005241 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5242 // When GNU attributes are expressly forbidden, diagnose their usage.
5243 Diag(Tok, diag::err_attributes_not_allowed);
5244
5245 // Parse the attributes even if they are rejected to ensure that error
5246 // recovery is graceful.
5247 if (AttrReqs & AR_GNUAttributesParsed ||
5248 AttrReqs & AR_GNUAttributesParsedAndRejected) {
John McCall53fa7142010-12-24 02:08:15 +00005249 ParseGNUAttributes(DS.getAttributes());
Chris Lattnercf0bab22008-12-18 07:02:59 +00005250 continue; // do *not* consume the next token!
5251 }
5252 // otherwise, FALL THROUGH!
Galina Kistanova77674252017-06-01 21:15:34 +00005253 LLVM_FALLTHROUGH;
Chris Lattnercf0bab22008-12-18 07:02:59 +00005254 default:
Steve Naroff44ac7772008-12-25 14:16:32 +00005255 DoneWithTypeQuals:
Chris Lattnercf0bab22008-12-18 07:02:59 +00005256 // If this is not a type-qualifier token, we're done reading type
5257 // qualifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00005258 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005259 if (EndLoc.isValid())
5260 DS.SetRangeEnd(EndLoc);
Chris Lattnercf0bab22008-12-18 07:02:59 +00005261 return;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005262 }
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00005263
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005264 // If the specifier combination wasn't legal, issue a diagnostic.
5265 if (isInvalid) {
5266 assert(PrevSpec && "Method did not return previous specifier!");
Chris Lattner6d29c102008-11-18 07:48:38 +00005267 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005268 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005269 EndLoc = ConsumeToken();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005270 }
5271}
5272
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005273/// ParseDeclarator - Parse and verify a newly-initialized declarator.
5274///
5275void Parser::ParseDeclarator(Declarator &D) {
5276 /// This implements the 'declarator' production in the C grammar, then checks
5277 /// for well-formedness and issues diagnostics.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005278 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005279}
5280
Richard Smith0b350b92014-10-28 16:55:02 +00005281static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
Faisal Vali421b2d12017-12-29 05:41:00 +00005282 DeclaratorContext TheContext) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005283 if (Kind == tok::star || Kind == tok::caret)
5284 return true;
5285
Xiuli Pan9c14e282016-01-09 12:53:17 +00005286 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5287 return true;
5288
Richard Smith0efa75c2012-03-29 01:16:42 +00005289 if (!Lang.CPlusPlus)
5290 return false;
5291
Richard Smith0b350b92014-10-28 16:55:02 +00005292 if (Kind == tok::amp)
5293 return true;
5294
5295 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5296 // But we must not parse them in conversion-type-ids and new-type-ids, since
5297 // those can be legitimately followed by a && operator.
5298 // (The same thing can in theory happen after a trailing-return-type, but
5299 // since those are a C++11 feature, there is no rejects-valid issue there.)
5300 if (Kind == tok::ampamp)
Faisal Vali421b2d12017-12-29 05:41:00 +00005301 return Lang.CPlusPlus11 ||
5302 (TheContext != DeclaratorContext::ConversionIdContext &&
5303 TheContext != DeclaratorContext::CXXNewContext);
Richard Smith0b350b92014-10-28 16:55:02 +00005304
5305 return false;
Richard Smith0efa75c2012-03-29 01:16:42 +00005306}
5307
Xiuli Pan9c14e282016-01-09 12:53:17 +00005308// Indicates whether the given declarator is a pipe declarator.
5309static bool isPipeDeclerator(const Declarator &D) {
5310 const unsigned NumTypes = D.getNumTypeObjects();
5311
5312 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5313 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5314 return true;
5315
5316 return false;
5317}
5318
Sebastian Redlbd150f42008-11-21 19:14:01 +00005319/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5320/// is parsed by the function passed to it. Pass null, and the direct-declarator
5321/// isn't parsed at all, making this function effectively parse the C++
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005322/// ptr-operator production.
5323///
Richard Smith09f76ee2011-10-19 21:33:05 +00005324/// If the grammar of this construct is extended, matching changes must also be
Richard Smith1453e312012-03-27 01:42:32 +00005325/// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5326/// isConstructorDeclarator.
Richard Smith09f76ee2011-10-19 21:33:05 +00005327///
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005328/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5329/// [C] pointer[opt] direct-declarator
5330/// [C++] direct-declarator
5331/// [C++] ptr-operator declarator
Chris Lattner6c7416c2006-08-07 00:19:33 +00005332///
5333/// pointer: [C99 6.7.5]
5334/// '*' type-qualifier-list[opt]
5335/// '*' type-qualifier-list[opt] pointer
5336///
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005337/// ptr-operator:
5338/// '*' cv-qualifier-seq[opt]
5339/// '&'
Sebastian Redled0f3b02009-03-15 22:02:01 +00005340/// [C++0x] '&&'
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005341/// [GNU] '&' restrict[opt] attributes[opt]
Sebastian Redled0f3b02009-03-15 22:02:01 +00005342/// [GNU?] '&&' restrict[opt] attributes[opt]
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005343/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
Sebastian Redlbd150f42008-11-21 19:14:01 +00005344void Parser::ParseDeclaratorInternal(Declarator &D,
5345 DirectDeclParseFunction DirectDeclParser) {
Douglas Gregor66a985d2009-08-26 14:27:30 +00005346 if (Diags.hasAllExtensionsSilenced())
5347 D.setExtension();
Chad Rosierc1183952012-06-26 22:30:43 +00005348
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005349 // C++ member pointers start with a '::' or a nested-name.
5350 // Member pointers get special handling, since there's no place for the
5351 // scope spec in the generic path below.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005352 if (getLangOpts().CPlusPlus &&
Richard Smith83c2ecf2016-02-02 23:34:49 +00005353 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
Serge Pavlov458ea762014-07-16 05:16:52 +00005354 (Tok.is(tok::identifier) &&
5355 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
Chris Lattner803802d2009-03-24 17:04:48 +00005356 Tok.is(tok::annot_cxxscope))) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005357 bool EnteringContext =
5358 D.getContext() == DeclaratorContext::FileContext ||
5359 D.getContext() == DeclaratorContext::MemberContext;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005360 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005361 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005362
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +00005363 if (SS.isNotEmpty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005364 if (Tok.isNot(tok::star)) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005365 // The scope spec really belongs to the direct-declarator.
Richard Smith5f044ad2013-01-08 22:43:49 +00005366 if (D.mayHaveIdentifier())
5367 D.getCXXScopeSpec() = SS;
5368 else
5369 AnnotateScopeToken(SS, true);
5370
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005371 if (DirectDeclParser)
5372 (this->*DirectDeclParser)(D);
5373 return;
5374 }
5375
5376 SourceLocation Loc = ConsumeToken();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005377 D.SetRangeEnd(Loc);
John McCall084e83d2011-03-24 11:26:52 +00005378 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005379 ParseTypeQualifierListOpt(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005380 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005381
5382 // Recurse to parse whatever is left.
5383 ParseDeclaratorInternal(D, DirectDeclParser);
5384
5385 // Sema will have to catch (syntactically invalid) pointers into global
5386 // scope. It has to catch pointers into namespace scope anyway.
Erich Keanec480f302018-07-12 21:09:05 +00005387 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005388 SS, DS.getTypeQualifiers(), DS.getEndLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005389 std::move(DS.getAttributes()),
5390 /* Don't replace range end. */ SourceLocation());
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005391 return;
5392 }
5393 }
5394
5395 tok::TokenKind Kind = Tok.getKind();
Xiuli Pan9c14e282016-01-09 12:53:17 +00005396
5397 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
Xiuli Pan11e13f62016-02-26 03:13:03 +00005398 DeclSpec DS(AttrFactory);
5399 ParseTypeQualifierListOpt(DS);
Xiuli Pan9c14e282016-01-09 12:53:17 +00005400
5401 D.AddTypeInfo(
5402 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005403 std::move(DS.getAttributes()), SourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00005404 }
5405
Steve Naroffec33ed92008-08-27 16:04:49 +00005406 // Not a pointer, C++ reference, or block.
Richard Smith0b350b92014-10-28 16:55:02 +00005407 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00005408 if (DirectDeclParser)
5409 (this->*DirectDeclParser)(D);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005410 return;
5411 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005412
Sebastian Redled0f3b02009-03-15 22:02:01 +00005413 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5414 // '&&' -> rvalue reference
Sebastian Redl3b27be62009-03-23 00:00:23 +00005415 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005416 D.SetRangeEnd(Loc);
Bill Wendling3708c182007-05-27 10:15:43 +00005417
Chris Lattner9eac9312009-03-27 04:18:06 +00005418 if (Kind == tok::star || Kind == tok::caret) {
Chris Lattner788404f2008-02-21 01:32:26 +00005419 // Is a pointer.
John McCall084e83d2011-03-24 11:26:52 +00005420 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005421
Aaron Ballman08b06592014-07-22 12:44:22 +00005422 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5423 // C++11 attributes are allowed.
5424 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
Faisal Vali421b2d12017-12-29 05:41:00 +00005425 ((D.getContext() != DeclaratorContext::CXXNewContext)
5426 ? AR_GNUAttributesParsed
5427 : AR_GNUAttributesParsedAndRejected);
Aaron Ballman08b06592014-07-22 12:44:22 +00005428 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005429 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005430
Bill Wendling3708c182007-05-27 10:15:43 +00005431 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005432 ParseDeclaratorInternal(D, DirectDeclParser);
Steve Naroffec33ed92008-08-27 16:04:49 +00005433 if (Kind == tok::star)
5434 // Remember that we parsed a pointer type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005435 D.AddTypeInfo(DeclaratorChunk::getPointer(
5436 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5437 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5438 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5439 std::move(DS.getAttributes()), SourceLocation());
Steve Naroffec33ed92008-08-27 16:04:49 +00005440 else
5441 // Remember that we parsed a Block type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005442 D.AddTypeInfo(
5443 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5444 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005445 } else {
5446 // Is a reference
John McCall084e83d2011-03-24 11:26:52 +00005447 DeclSpec DS(AttrFactory);
Bill Wendling93efb222007-06-02 23:28:54 +00005448
Sebastian Redl3b27be62009-03-23 00:00:23 +00005449 // Complain about rvalue references in C++03, but then go on and build
5450 // the declarator.
Richard Smith5d164bc2011-10-15 05:09:34 +00005451 if (Kind == tok::ampamp)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005452 Diag(Loc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00005453 diag::warn_cxx98_compat_rvalue_reference :
5454 diag::ext_rvalue_reference);
Sebastian Redl3b27be62009-03-23 00:00:23 +00005455
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005456 // GNU-style and C++11 attributes are allowed here, as is restrict.
5457 ParseTypeQualifierListOpt(DS);
5458 D.ExtendWithDeclSpec(DS);
5459
Bill Wendling93efb222007-06-02 23:28:54 +00005460 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5461 // cv-qualifiers are introduced through the use of a typedef or of a
5462 // template type argument, in which case the cv-qualifiers are ignored.
Bill Wendling93efb222007-06-02 23:28:54 +00005463 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5464 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5465 Diag(DS.getConstSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005466 diag::err_invalid_reference_qualifier_application) << "const";
Bill Wendling93efb222007-06-02 23:28:54 +00005467 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5468 Diag(DS.getVolatileSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005469 diag::err_invalid_reference_qualifier_application) << "volatile";
Richard Smith8e1ac332013-03-28 01:55:44 +00005470 // 'restrict' is permitted as an extension.
5471 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5472 Diag(DS.getAtomicSpecLoc(),
5473 diag::err_invalid_reference_qualifier_application) << "_Atomic";
Bill Wendling93efb222007-06-02 23:28:54 +00005474 }
Bill Wendling3708c182007-05-27 10:15:43 +00005475
5476 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005477 ParseDeclaratorInternal(D, DirectDeclParser);
Bill Wendling3708c182007-05-27 10:15:43 +00005478
Douglas Gregor66583c52008-11-03 15:51:28 +00005479 if (D.getNumTypeObjects() > 0) {
5480 // C++ [dcl.ref]p4: There shall be no references to references.
5481 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5482 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
Chris Lattnerebad6a22008-11-19 07:37:42 +00005483 if (const IdentifierInfo *II = D.getIdentifier())
5484 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5485 << II;
5486 else
5487 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5488 << "type name";
Douglas Gregor66583c52008-11-03 15:51:28 +00005489
Sebastian Redlbd150f42008-11-21 19:14:01 +00005490 // Once we've complained about the reference-to-reference, we
Douglas Gregor66583c52008-11-03 15:51:28 +00005491 // can go ahead and build the (technically ill-formed)
5492 // declarator: reference collapsing will take care of it.
5493 }
5494 }
5495
Richard Smith8e1ac332013-03-28 01:55:44 +00005496 // Remember that we parsed a reference type.
Chris Lattner788404f2008-02-21 01:32:26 +00005497 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
Sebastian Redled0f3b02009-03-15 22:02:01 +00005498 Kind == tok::amp),
Erich Keanec480f302018-07-12 21:09:05 +00005499 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005500 }
Chris Lattner6c7416c2006-08-07 00:19:33 +00005501}
5502
Richard Trieuf4b81d02014-06-24 23:14:24 +00005503// When correcting from misplaced brackets before the identifier, the location
5504// is saved inside the declarator so that other diagnostic messages can use
5505// them. This extracts and returns that location, or returns the provided
5506// location if a stored location does not exist.
5507static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5508 SourceLocation Loc) {
5509 if (D.getName().StartLocation.isInvalid() &&
5510 D.getName().EndLocation.isValid())
5511 return D.getName().EndLocation;
5512
5513 return Loc;
5514}
5515
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005516/// ParseDirectDeclarator
5517/// direct-declarator: [C99 6.7.5]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005518/// [C99] identifier
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005519/// '(' declarator ')'
5520/// [GNU] '(' attributes declarator ')'
Chris Lattnere8074e62006-08-06 18:30:15 +00005521/// [C90] direct-declarator '[' constant-expression[opt] ']'
5522/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5523/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5524/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5525/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005526/// [C++11] direct-declarator '[' constant-expression[opt] ']'
5527/// attribute-specifier-seq[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005528/// direct-declarator '(' parameter-type-list ')'
5529/// direct-declarator '(' identifier-list[opt] ')'
5530/// [GNU] direct-declarator '(' parameter-forward-declarations
5531/// parameter-type-list[opt] ')'
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00005532/// [C++] direct-declarator '(' parameter-declaration-clause ')'
5533/// cv-qualifier-seq[opt] exception-specification[opt]
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005534/// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5535/// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5536/// ref-qualifier[opt] exception-specification[opt]
Douglas Gregor61956c42008-10-31 09:07:45 +00005537/// [C++] declarator-id
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005538/// [C++11] declarator-id attribute-specifier-seq[opt]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005539///
5540/// declarator-id: [C++ 8]
Douglas Gregor27b4c162010-12-23 22:44:42 +00005541/// '...'[opt] id-expression
Douglas Gregor831c93f2008-11-05 20:51:48 +00005542/// '::'[opt] nested-name-specifier[opt] type-name
5543///
5544/// id-expression: [C++ 5.1]
5545/// unqualified-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005546/// qualified-id
Douglas Gregor831c93f2008-11-05 20:51:48 +00005547///
5548/// unqualified-id: [C++ 5.1]
Mike Stump11289f42009-09-09 15:08:12 +00005549/// identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005550/// operator-function-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005551/// conversion-function-id
Mike Stump11289f42009-09-09 15:08:12 +00005552/// '~' class-name
Douglas Gregor7f741122009-02-25 19:37:18 +00005553/// template-id
Argyrios Kyrtzidise4426352008-11-07 22:02:30 +00005554///
Richard Smithbdb84f32016-07-22 23:36:59 +00005555/// C++17 adds the following, which we also handle here:
5556///
5557/// simple-declaration:
5558/// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5559///
Richard Smith1453e312012-03-27 01:42:32 +00005560/// Note, any additional constructs added here may need corresponding changes
5561/// in isConstructorDeclarator.
Chris Lattneracd58a32006-08-06 17:24:14 +00005562void Parser::ParseDirectDeclarator(Declarator &D) {
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005563 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005564
David Blaikiebbafb8a2012-03-11 07:00:24 +00005565 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
Richard Smithbdb84f32016-07-22 23:36:59 +00005566 // This might be a C++17 structured binding.
5567 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5568 D.getCXXScopeSpec().isEmpty())
5569 return ParseDecompositionDeclarator(D);
5570
Serge Pavlov458ea762014-07-16 05:16:52 +00005571 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5572 // this context it is a bitfield. Also in range-based for statement colon
5573 // may delimit for-range-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00005574 ColonProtectionRAIIObject X(
5575 *this, D.getContext() == DeclaratorContext::MemberContext ||
5576 (D.getContext() == DeclaratorContext::ForContext &&
5577 getLangOpts().CPlusPlus11));
Serge Pavlov458ea762014-07-16 05:16:52 +00005578
Douglas Gregor7861a802009-11-03 01:35:08 +00005579 // ParseDeclaratorInternal might already have parsed the scope.
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005580 if (D.getCXXScopeSpec().isEmpty()) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005581 bool EnteringContext =
5582 D.getContext() == DeclaratorContext::FileContext ||
5583 D.getContext() == DeclaratorContext::MemberContext;
David Blaikieefdccaa2016-01-15 23:43:34 +00005584 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005585 EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005586 }
5587
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005588 if (D.getCXXScopeSpec().isValid()) {
Richard Smith64e033f2015-01-15 00:48:52 +00005589 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5590 D.getCXXScopeSpec()))
John McCall2b058ef2009-12-11 20:04:54 +00005591 // Change the declaration context for name lookup, until this function
5592 // is exited (and the declarator has been parsed).
5593 DeclScopeObj.EnterDeclaratorScope();
Alex Lorenze151f0102016-12-07 10:24:44 +00005594 else if (getObjCDeclContext()) {
5595 // Ensure that we don't interpret the next token as an identifier when
5596 // dealing with declarations in an Objective-C container.
5597 D.SetIdentifier(nullptr, Tok.getLocation());
5598 D.setInvalidType(true);
5599 ConsumeToken();
5600 goto PastIdentifier;
5601 }
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005602 }
5603
Douglas Gregor27b4c162010-12-23 22:44:42 +00005604 // C++0x [dcl.fct]p14:
Faisal Vali8435a692014-12-04 12:40:21 +00005605 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5606 // parameter-declaration-clause without a preceding comma. In this case,
5607 // the ellipsis is parsed as part of the abstract-declarator if the type
5608 // of the parameter either names a template parameter pack that has not
5609 // been expanded or contains auto; otherwise, it is parsed as part of the
5610 // parameter-declaration-clause.
Richard Smith0efa75c2012-03-29 01:16:42 +00005611 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00005612 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5613 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5614 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
Douglas Gregor27b4c162010-12-23 22:44:42 +00005615 NextToken().is(tok::r_paren) &&
Richard Smithb19337f2013-02-20 20:19:27 +00005616 !D.hasGroupingParens() &&
Faisal Vali8435a692014-12-04 12:40:21 +00005617 !Actions.containsUnexpandedParameterPacks(D) &&
Faisal Vali090da2d2018-01-01 18:23:28 +00005618 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005619 SourceLocation EllipsisLoc = ConsumeToken();
Richard Smith0b350b92014-10-28 16:55:02 +00005620 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005621 // The ellipsis was put in the wrong place. Recover, and explain to
5622 // the user what they should have done.
5623 ParseDeclarator(D);
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00005624 if (EllipsisLoc.isValid())
5625 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00005626 return;
5627 } else
5628 D.setEllipsisLoc(EllipsisLoc);
5629
5630 // The ellipsis can't be followed by a parenthesized declarator. We
5631 // check for that in ParseParenDeclarator, after we have disambiguated
5632 // the l_paren token.
5633 }
5634
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005635 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5636 tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00005637 // We found something that indicates the start of an unqualified-id.
5638 // Parse that unqualified-id.
John McCall84821e72010-04-13 06:39:49 +00005639 bool AllowConstructorName;
Richard Smith35845152017-02-07 01:37:30 +00005640 bool AllowDeductionGuide;
5641 if (D.getDeclSpec().hasTypeSpecifier()) {
John McCall84821e72010-04-13 06:39:49 +00005642 AllowConstructorName = false;
Richard Smith35845152017-02-07 01:37:30 +00005643 AllowDeductionGuide = false;
5644 } else if (D.getCXXScopeSpec().isSet()) {
John McCall84821e72010-04-13 06:39:49 +00005645 AllowConstructorName =
Faisal Vali421b2d12017-12-29 05:41:00 +00005646 (D.getContext() == DeclaratorContext::FileContext ||
5647 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005648 AllowDeductionGuide = false;
5649 } else {
Faisal Vali421b2d12017-12-29 05:41:00 +00005650 AllowConstructorName =
5651 (D.getContext() == DeclaratorContext::MemberContext);
Fangrui Song6907ce22018-07-30 19:24:48 +00005652 AllowDeductionGuide =
Faisal Vali421b2d12017-12-29 05:41:00 +00005653 (D.getContext() == DeclaratorContext::FileContext ||
5654 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005655 }
John McCall84821e72010-04-13 06:39:49 +00005656
Richard Smith64e033f2015-01-15 00:48:52 +00005657 bool HadScope = D.getCXXScopeSpec().isValid();
Chad Rosierc1183952012-06-26 22:30:43 +00005658 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5659 /*EnteringContext=*/true,
David Blaikieefdccaa2016-01-15 23:43:34 +00005660 /*AllowDestructorName=*/true, AllowConstructorName,
Richard Smithc08b6932018-04-27 02:00:13 +00005661 AllowDeductionGuide, nullptr, nullptr,
Richard Smith35845152017-02-07 01:37:30 +00005662 D.getName()) ||
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005663 // Once we're past the identifier, if the scope was bad, mark the
5664 // whole declarator bad.
5665 D.getCXXScopeSpec().isInvalid()) {
Craig Topper161e4db2014-05-21 06:02:52 +00005666 D.SetIdentifier(nullptr, Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005667 D.setInvalidType(true);
Douglas Gregor7861a802009-11-03 01:35:08 +00005668 } else {
Richard Smith64e033f2015-01-15 00:48:52 +00005669 // ParseUnqualifiedId might have parsed a scope specifier during error
5670 // recovery. If it did so, enter that scope.
5671 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5672 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5673 D.getCXXScopeSpec()))
5674 DeclScopeObj.EnterDeclaratorScope();
5675
Douglas Gregor7861a802009-11-03 01:35:08 +00005676 // Parsed the unqualified-id; update range information and move along.
5677 if (D.getSourceRange().getBegin().isInvalid())
5678 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5679 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005680 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005681 goto PastIdentifier;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005682 }
Richard Smithd63db6e2015-12-19 02:40:19 +00005683
5684 if (D.getCXXScopeSpec().isNotEmpty()) {
5685 // We have a scope specifier but no following unqualified-id.
5686 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5687 diag::err_expected_unqualified_id)
5688 << /*C++*/1;
5689 D.SetIdentifier(nullptr, Tok.getLocation());
5690 goto PastIdentifier;
5691 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005692 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005693 assert(!getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005694 "There's a C++-specific check for tok::identifier above");
5695 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5696 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Richard Trieu2664dc12014-05-05 22:06:50 +00005697 D.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005698 ConsumeToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00005699 goto PastIdentifier;
Richard Smith74639b12017-05-19 01:54:59 +00005700 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5701 // We're not allowed an identifier here, but we got one. Try to figure out
5702 // if the user was trying to attach a name to the type, or whether the name
5703 // is some unrelated trailing syntax.
5704 bool DiagnoseIdentifier = false;
5705 if (D.hasGroupingParens())
5706 // An identifier within parens is unlikely to be intended to be anything
5707 // other than a name being "declared".
5708 DiagnoseIdentifier = true;
Richard Smith77a9c602018-02-28 03:02:23 +00005709 else if (D.getContext() == DeclaratorContext::TemplateArgContext)
Richard Smith74639b12017-05-19 01:54:59 +00005710 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5711 DiagnoseIdentifier =
5712 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali421b2d12017-12-29 05:41:00 +00005713 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5714 D.getContext() == DeclaratorContext::AliasTemplateContext)
Richard Smith74639b12017-05-19 01:54:59 +00005715 // The most likely error is that the ';' was forgotten.
5716 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
Richard Smithe303e352018-02-02 22:24:54 +00005717 else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5718 D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
Richard Smith74639b12017-05-19 01:54:59 +00005719 !isCXX11VirtSpecifier(Tok))
5720 DiagnoseIdentifier = NextToken().isOneOf(
5721 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5722 if (DiagnoseIdentifier) {
Richard Smithf39720b2013-10-13 22:12:28 +00005723 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5724 << FixItHint::CreateRemoval(Tok.getLocation());
Craig Topper161e4db2014-05-21 06:02:52 +00005725 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithf39720b2013-10-13 22:12:28 +00005726 ConsumeToken();
5727 goto PastIdentifier;
5728 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005729 }
Richard Smith0efa75c2012-03-29 01:16:42 +00005730
Douglas Gregor7861a802009-11-03 01:35:08 +00005731 if (Tok.is(tok::l_paren)) {
Richard Smithe303e352018-02-02 22:24:54 +00005732 // If this might be an abstract-declarator followed by a direct-initializer,
5733 // check whether this is a valid declarator chunk. If it can't be, assume
5734 // that it's an initializer instead.
5735 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5736 RevertingTentativeParsingAction PA(*this);
5737 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5738 TPResult::False) {
5739 D.SetIdentifier(nullptr, Tok.getLocation());
5740 goto PastIdentifier;
5741 }
5742 }
5743
Chris Lattneracd58a32006-08-06 17:24:14 +00005744 // direct-declarator: '(' declarator ')'
Chris Lattnere37e2332006-08-15 04:50:22 +00005745 // direct-declarator: '(' attributes declarator ')'
Chris Lattneracd58a32006-08-06 17:24:14 +00005746 // Example: 'char (*X)' or 'int (*XX)(void)'
5747 ParseParenDeclarator(D);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005748
5749 // If the declarator was parenthesized, we entered the declarator
5750 // scope when parsing the parenthesized declarator, then exited
5751 // the scope already. Re-enter the scope, if we need to.
5752 if (D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005753 // If there was an error parsing parenthesized declarator, declarator
Richard Smith0efa75c2012-03-29 01:16:42 +00005754 // scope may have been entered before. Don't do it again.
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005755 if (!D.isInvalidType() &&
Nico Weber6b05f382015-02-18 04:53:03 +00005756 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5757 D.getCXXScopeSpec()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005758 // Change the declaration context for name lookup, until this function
5759 // is exited (and the declarator has been parsed).
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005760 DeclScopeObj.EnterDeclaratorScope();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005761 }
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005762 } else if (D.mayOmitIdentifier()) {
Chris Lattneracd58a32006-08-06 17:24:14 +00005763 // This could be something simple like "int" (in which case the declarator
5764 // portion is empty), if an abstract-declarator is allowed.
Craig Topper161e4db2014-05-21 06:02:52 +00005765 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithb19337f2013-02-20 20:19:27 +00005766
5767 // The grammar for abstract-pack-declarator does not allow grouping parens.
5768 // FIXME: Revisit this once core issue 1488 is resolved.
5769 if (D.hasEllipsis() && D.hasGroupingParens())
5770 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5771 diag::ext_abstract_pack_declarator_parens);
Chris Lattneracd58a32006-08-06 17:24:14 +00005772 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00005773 if (Tok.getKind() == tok::annot_pragma_parser_crash)
David Blaikie5bd4c2a2012-08-21 18:56:49 +00005774 LLVM_BUILTIN_TRAP;
Richard Trieuf4b81d02014-06-24 23:14:24 +00005775 if (Tok.is(tok::l_square))
5776 return ParseMisplacedBracketDeclarator(D);
Faisal Vali421b2d12017-12-29 05:41:00 +00005777 if (D.getContext() == DeclaratorContext::MemberContext) {
Alex Lorenzf1278212017-04-11 15:01:53 +00005778 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5779 // treating these keyword as valid member names.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005780 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
Alex Lorenzf1278212017-04-11 15:01:53 +00005781 Tok.getIdentifierInfo() &&
5782 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5783 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5784 diag::err_expected_member_name_or_semi_objcxx_keyword)
5785 << Tok.getIdentifierInfo()
5786 << (D.getDeclSpec().isEmpty() ? SourceRange()
5787 : D.getDeclSpec().getSourceRange());
5788 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5789 D.SetRangeEnd(Tok.getLocation());
5790 ConsumeToken();
5791 goto PastIdentifier;
5792 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005793 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5794 diag::err_expected_member_name_or_semi)
Richard Trieua1342402014-05-02 23:40:32 +00005795 << (D.getDeclSpec().isEmpty() ? SourceRange()
5796 : D.getDeclSpec().getSourceRange());
Richard Trieuf4b81d02014-06-24 23:14:24 +00005797 } else if (getLangOpts().CPlusPlus) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005798 if (Tok.isOneOf(tok::period, tok::arrow))
Richard Trieu9c672672013-01-26 02:31:38 +00005799 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
Richard Trieu2f586962013-09-05 02:31:33 +00005800 else {
5801 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5802 if (Tok.isAtStartOfLine() && Loc.isValid())
5803 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5804 << getLangOpts().CPlusPlus;
5805 else
Richard Trieuf4b81d02014-06-24 23:14:24 +00005806 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5807 diag::err_expected_unqualified_id)
Richard Trieu2f586962013-09-05 02:31:33 +00005808 << getLangOpts().CPlusPlus;
5809 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005810 } else {
5811 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5812 diag::err_expected_either)
5813 << tok::identifier << tok::l_paren;
5814 }
Craig Topper161e4db2014-05-21 06:02:52 +00005815 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattner8c5dd732008-11-11 06:13:16 +00005816 D.setInvalidType(true);
Chris Lattneracd58a32006-08-06 17:24:14 +00005817 }
Mike Stump11289f42009-09-09 15:08:12 +00005818
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005819 PastIdentifier:
Chris Lattneracd58a32006-08-06 17:24:14 +00005820 assert(D.isPastIdentifier() &&
5821 "Haven't past the location of the identifier yet?");
Mike Stump11289f42009-09-09 15:08:12 +00005822
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005823 // Don't parse attributes unless we have parsed an unparenthesized name.
5824 if (D.hasName() && !D.getNumTypeObjects())
Richard Smith89645bc2013-01-02 12:01:23 +00005825 MaybeParseCXX11Attributes(D);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005826
Chris Lattneracd58a32006-08-06 17:24:14 +00005827 while (1) {
Chris Lattner76c72282007-10-09 17:33:22 +00005828 if (Tok.is(tok::l_paren)) {
David Blaikie15a430a2011-12-04 05:04:18 +00005829 // Enter function-declaration scope, limiting any declarators to the
5830 // function prototype scope, including parameter declarators.
5831 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00005832 Scope::FunctionPrototypeScope|Scope::DeclScope|
5833 (D.isFunctionDeclaratorAFunctionDeclaration()
5834 ? Scope::FunctionDeclarationScope : 0));
5835
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005836 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5837 // In such a case, check if we actually have a function declarator; if it
5838 // is not, the declarator has been fully parsed.
Richard Smith943c4402012-07-30 21:30:52 +00005839 bool IsAmbiguous = false;
Richard Smith4f605af2012-08-18 00:55:03 +00005840 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5841 // The name of the declarator, if any, is tentatively declared within
5842 // a possible direct initializer.
5843 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5844 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5845 TentativelyDeclaredIdentifiers.pop_back();
5846 if (!IsFunctionDecl)
5847 break;
5848 }
John McCall084e83d2011-03-24 11:26:52 +00005849 ParsedAttributes attrs(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005850 BalancedDelimiterTracker T(*this, tok::l_paren);
5851 T.consumeOpen();
Richard Smith943c4402012-07-30 21:30:52 +00005852 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
David Blaikie15a430a2011-12-04 05:04:18 +00005853 PrototypeScope.Exit();
Chris Lattner76c72282007-10-09 17:33:22 +00005854 } else if (Tok.is(tok::l_square)) {
Chris Lattnere8074e62006-08-06 18:30:15 +00005855 ParseBracketDeclarator(D);
Chris Lattneracd58a32006-08-06 17:24:14 +00005856 } else {
5857 break;
5858 }
5859 }
Chad Rosierc1183952012-06-26 22:30:43 +00005860}
Chris Lattneracd58a32006-08-06 17:24:14 +00005861
Richard Smithbdb84f32016-07-22 23:36:59 +00005862void Parser::ParseDecompositionDeclarator(Declarator &D) {
5863 assert(Tok.is(tok::l_square));
5864
5865 // If this doesn't look like a structured binding, maybe it's a misplaced
5866 // array declarator.
5867 // FIXME: Consume the l_square first so we don't need extra lookahead for
5868 // this.
5869 if (!(NextToken().is(tok::identifier) &&
5870 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5871 !(NextToken().is(tok::r_square) &&
5872 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5873 return ParseMisplacedBracketDeclarator(D);
5874
5875 BalancedDelimiterTracker T(*this, tok::l_square);
5876 T.consumeOpen();
5877
5878 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5879 while (Tok.isNot(tok::r_square)) {
5880 if (!Bindings.empty()) {
5881 if (Tok.is(tok::comma))
5882 ConsumeToken();
5883 else {
5884 if (Tok.is(tok::identifier)) {
5885 SourceLocation EndLoc = getEndOfPreviousToken();
5886 Diag(EndLoc, diag::err_expected)
5887 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5888 } else {
5889 Diag(Tok, diag::err_expected_comma_or_rsquare);
5890 }
5891
5892 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5893 StopAtSemi | StopBeforeMatch);
5894 if (Tok.is(tok::comma))
5895 ConsumeToken();
5896 else if (Tok.isNot(tok::identifier))
5897 break;
5898 }
5899 }
5900
5901 if (Tok.isNot(tok::identifier)) {
5902 Diag(Tok, diag::err_expected) << tok::identifier;
5903 break;
5904 }
5905
5906 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
5907 ConsumeToken();
5908 }
5909
5910 if (Tok.isNot(tok::r_square))
5911 // We've already diagnosed a problem here.
5912 T.skipToEnd();
5913 else {
5914 // C++17 does not allow the identifier-list in a structured binding
5915 // to be empty.
5916 if (Bindings.empty())
5917 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
5918
5919 T.consumeClose();
5920 }
5921
5922 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
5923 T.getCloseLocation());
5924}
5925
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005926/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5927/// only called before the identifier, so these are most likely just grouping
Mike Stump11289f42009-09-09 15:08:12 +00005928/// parens for precedence. If we find that these are actually function
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005929/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5930///
5931/// direct-declarator:
5932/// '(' declarator ')'
5933/// [GNU] '(' attributes declarator ')'
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005934/// direct-declarator '(' parameter-type-list ')'
5935/// direct-declarator '(' identifier-list[opt] ')'
5936/// [GNU] direct-declarator '(' parameter-forward-declarations
5937/// parameter-type-list[opt] ')'
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005938///
5939void Parser::ParseParenDeclarator(Declarator &D) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005940 BalancedDelimiterTracker T(*this, tok::l_paren);
5941 T.consumeOpen();
5942
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005943 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
Mike Stump11289f42009-09-09 15:08:12 +00005944
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005945 // Eat any attributes before we look at whether this is a grouping or function
5946 // declarator paren. If this is a grouping paren, the attribute applies to
5947 // the type being built up, for example:
5948 // int (__attribute__(()) *x)(long y)
5949 // If this ends up not being a grouping paren, the attribute applies to the
5950 // first argument, for example:
5951 // int (__attribute__(()) int x)
5952 // In either case, we need to eat any attributes to be able to determine what
5953 // sort of paren this is.
5954 //
John McCall084e83d2011-03-24 11:26:52 +00005955 ParsedAttributes attrs(AttrFactory);
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005956 bool RequiresArg = false;
5957 if (Tok.is(tok::kw___attribute)) {
John McCall53fa7142010-12-24 02:08:15 +00005958 ParseGNUAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00005959
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005960 // We require that the argument list (if this is a non-grouping paren) be
5961 // present even if the attribute list was empty.
5962 RequiresArg = true;
5963 }
Chad Rosiereea9ca72012-12-21 21:22:20 +00005964
Steve Naroff44ac7772008-12-25 14:16:32 +00005965 // Eat any Microsoft extensions.
Chad Rosiereea9ca72012-12-21 21:22:20 +00005966 ParseMicrosoftTypeAttributes(attrs);
5967
Dawn Perchik335e16b2010-09-03 01:29:35 +00005968 // Eat any Borland extensions.
Ted Kremenek5eec2b02010-11-10 05:59:39 +00005969 if (Tok.is(tok::kw___pascal))
John McCall53fa7142010-12-24 02:08:15 +00005970 ParseBorlandTypeAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00005971
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005972 // If we haven't past the identifier yet (or where the identifier would be
5973 // stored, if this is an abstract declarator), then this is probably just
5974 // grouping parens. However, if this could be an abstract-declarator, then
5975 // this could also be the start of function arguments (consider 'void()').
5976 bool isGrouping;
Mike Stump11289f42009-09-09 15:08:12 +00005977
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005978 if (!D.mayOmitIdentifier()) {
5979 // If this can't be an abstract-declarator, this *must* be a grouping
5980 // paren, because we haven't seen the identifier yet.
5981 isGrouping = true;
5982 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
Richard Smith43f340f2012-03-27 23:05:05 +00005983 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5984 NextToken().is(tok::r_paren)) || // C++ int(...)
Richard Smith2620cd92012-04-11 04:01:28 +00005985 isDeclarationSpecifier() || // 'int(int)' is a function.
5986 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005987 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5988 // considered to be a type, not a K&R identifier-list.
5989 isGrouping = false;
5990 } else {
5991 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5992 isGrouping = true;
5993 }
Mike Stump11289f42009-09-09 15:08:12 +00005994
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005995 // If this is a grouping paren, handle:
5996 // direct-declarator: '(' declarator ')'
5997 // direct-declarator: '(' attributes declarator ')'
5998 if (isGrouping) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005999 SourceLocation EllipsisLoc = D.getEllipsisLoc();
6000 D.setEllipsisLoc(SourceLocation());
6001
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006002 bool hadGroupingParens = D.hasGroupingParens();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006003 D.setGroupingParens(true);
Sebastian Redlbd150f42008-11-21 19:14:01 +00006004 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006005 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006006 T.consumeClose();
Erich Keanec480f302018-07-12 21:09:05 +00006007 D.AddTypeInfo(
6008 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6009 std::move(attrs), T.getCloseLocation());
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006010
6011 D.setGroupingParens(hadGroupingParens);
Richard Smith0efa75c2012-03-29 01:16:42 +00006012
6013 // An ellipsis cannot be placed outside parentheses.
6014 if (EllipsisLoc.isValid())
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00006015 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00006016
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006017 return;
6018 }
Mike Stump11289f42009-09-09 15:08:12 +00006019
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006020 // Okay, if this wasn't a grouping paren, it must be the start of a function
6021 // argument list. Recognize that this declarator will never have an
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006022 // identifier (and remember where it would have been), then call into
6023 // ParseFunctionDeclarator to handle of argument list.
Craig Topper161e4db2014-05-21 06:02:52 +00006024 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006025
David Blaikie15a430a2011-12-04 05:04:18 +00006026 // Enter function-declaration scope, limiting any declarators to the
6027 // function prototype scope, including parameter declarators.
6028 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00006029 Scope::FunctionPrototypeScope | Scope::DeclScope |
6030 (D.isFunctionDeclaratorAFunctionDeclaration()
6031 ? Scope::FunctionDeclarationScope : 0));
Richard Smith943c4402012-07-30 21:30:52 +00006032 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
David Blaikie15a430a2011-12-04 05:04:18 +00006033 PrototypeScope.Exit();
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006034}
6035
6036/// ParseFunctionDeclarator - We are after the identifier and have parsed the
6037/// declarator D up to a paren, which indicates that we are parsing function
6038/// arguments.
Chris Lattneracd58a32006-08-06 17:24:14 +00006039///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006040/// If FirstArgAttrs is non-null, then the caller parsed those arguments
6041/// immediately after the open paren - they should be considered to be the
6042/// first argument of a parameter.
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006043///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006044/// If RequiresArg is true, then the first argument of the function is required
6045/// to be present and required to not be an identifier list.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006046///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006047/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6048/// (C++11) ref-qualifier[opt], exception-specification[opt],
6049/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
6050///
6051/// [C++11] exception-specification:
Douglas Gregor9e66af42011-07-05 16:44:18 +00006052/// dynamic-exception-specification
6053/// noexcept-specification
6054///
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006055void Parser::ParseFunctionDeclarator(Declarator &D,
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006056 ParsedAttributes &FirstArgAttrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006057 BalancedDelimiterTracker &Tracker,
Richard Smith943c4402012-07-30 21:30:52 +00006058 bool IsAmbiguous,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006059 bool RequiresArg) {
Chad Rosierc1183952012-06-26 22:30:43 +00006060 assert(getCurScope()->isFunctionPrototypeScope() &&
David Blaikie15a430a2011-12-04 05:04:18 +00006061 "Should call from a Function scope");
Douglas Gregor9e66af42011-07-05 16:44:18 +00006062 // lparen is already consumed!
6063 assert(D.isPastIdentifier() && "Should not call before identifier!");
6064
6065 // This should be true when the function has typed arguments.
6066 // Otherwise, it is treated as a K&R-style function.
6067 bool HasProto = false;
6068 // Build up an array of information about the parsed arguments.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006069 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006070 // Remember where we see an ellipsis, if any.
6071 SourceLocation EllipsisLoc;
6072
6073 DeclSpec DS(AttrFactory);
6074 bool RefQualifierIsLValueRef = true;
6075 SourceLocation RefQualifierLoc;
Douglas Gregore248eea2011-10-19 06:04:55 +00006076 SourceLocation ConstQualifierLoc;
6077 SourceLocation VolatileQualifierLoc;
Hal Finkel23a07392014-10-20 17:32:04 +00006078 SourceLocation RestrictQualifierLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006079 ExceptionSpecificationType ESpecType = EST_None;
6080 SourceRange ESpecRange;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006081 SmallVector<ParsedType, 2> DynamicExceptions;
6082 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006083 ExprResult NoexceptExpr;
Hans Wennborgdcfba332015-10-06 23:40:43 +00006084 CachedTokens *ExceptionSpecTokens = nullptr;
Aaron Ballman606093a2017-10-15 15:01:42 +00006085 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith700537c2012-06-12 01:51:59 +00006086 TypeResult TrailingReturnType;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006087
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006088 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6089 EndLoc is the end location for the function declarator.
6090 They differ for trailing return types. */
6091 SourceLocation StartLoc, LocalEndLoc, EndLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006092 SourceLocation LParenLoc, RParenLoc;
6093 LParenLoc = Tracker.getOpenLocation();
6094 StartLoc = LParenLoc;
6095
Douglas Gregor9e66af42011-07-05 16:44:18 +00006096 if (isFunctionDeclaratorIdentifierList()) {
6097 if (RequiresArg)
6098 Diag(Tok, diag::err_argument_required_after_attribute);
6099
6100 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6101
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006102 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006103 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006104 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006105 EndLoc = RParenLoc;
Aaron Ballman606093a2017-10-15 15:01:42 +00006106
Fangrui Song6907ce22018-07-30 19:24:48 +00006107 // If there are attributes following the identifier list, parse them and
Aaron Ballman606093a2017-10-15 15:01:42 +00006108 // prohibit them.
6109 MaybeParseCXX11Attributes(FnAttrs);
6110 ProhibitAttributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006111 } else {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006112 if (Tok.isNot(tok::r_paren))
Fangrui Song6907ce22018-07-30 19:24:48 +00006113 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
Faisal Vali2b391ab2013-09-26 19:54:12 +00006114 EllipsisLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006115 else if (RequiresArg)
6116 Diag(Tok, diag::err_argument_required_after_attribute);
6117
Alexey Bader1f277942017-10-11 11:16:31 +00006118 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6119 || getLangOpts().OpenCL;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006120
6121 // If we have the closing ')', eat it.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006122 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006123 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006124 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006125 EndLoc = RParenLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006126
David Blaikiebbafb8a2012-03-11 07:00:24 +00006127 if (getLangOpts().CPlusPlus) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006128 // FIXME: Accept these components in any order, and produce fixits to
6129 // correct the order if the user gets it wrong. Ideally we should deal
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00006130 // with the pure-specifier in the same way.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006131
6132 // Parse cv-qualifier-seq[opt].
Aaron Ballman08b06592014-07-22 12:44:22 +00006133 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
Alex Lorenz8f4d3992017-02-13 23:19:40 +00006134 /*AtomicAllowed*/ false,
6135 /*IdentifierRequired=*/false,
6136 llvm::function_ref<void()>([&]() {
6137 Actions.CodeCompleteFunctionQualifiers(DS, D);
6138 }));
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006139 if (!DS.getSourceRange().getEnd().isInvalid()) {
6140 EndLoc = DS.getSourceRange().getEnd();
6141 ConstQualifierLoc = DS.getConstSpecLoc();
6142 VolatileQualifierLoc = DS.getVolatileSpecLoc();
Hal Finkel23a07392014-10-20 17:32:04 +00006143 RestrictQualifierLoc = DS.getRestrictSpecLoc();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006144 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006145
6146 // Parse ref-qualifier[opt].
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006147 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
Douglas Gregor9e66af42011-07-05 16:44:18 +00006148 EndLoc = RefQualifierLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006149
Douglas Gregor3024f072012-04-16 07:05:22 +00006150 // C++11 [expr.prim.general]p3:
Chad Rosierc1183952012-06-26 22:30:43 +00006151 // If a declaration declares a member function or member function
6152 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00006153 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Chad Rosierc1183952012-06-26 22:30:43 +00006154 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00006155 // declarator.
Richard Smithad1bbb92013-03-15 00:41:52 +00006156 // FIXME: currently, "static" case isn't handled correctly.
Chad Rosierc1183952012-06-26 22:30:43 +00006157 bool IsCXX11MemberFunction =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006158 getLangOpts().CPlusPlus11 &&
Richard Smith990a6922014-01-17 21:01:18 +00006159 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
Faisal Vali421b2d12017-12-29 05:41:00 +00006160 (D.getContext() == DeclaratorContext::MemberContext
Richard Smithad1bbb92013-03-15 00:41:52 +00006161 ? !D.getDeclSpec().isFriendSpecified()
Faisal Vali421b2d12017-12-29 05:41:00 +00006162 : D.getContext() == DeclaratorContext::FileContext &&
Richard Smithad1bbb92013-03-15 00:41:52 +00006163 D.getCXXScopeSpec().isValid() &&
6164 Actions.CurContext->isRecord());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006165
6166 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6167 if (D.getDeclSpec().isConstexprSpecified() && !getLangOpts().CPlusPlus14)
6168 Q.addConst();
6169
6170 Sema::CXXThisScopeRAII ThisScope(
6171 Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6172 IsCXX11MemberFunction);
Richard Smith2331bbf2012-05-02 22:22:32 +00006173
Douglas Gregor9e66af42011-07-05 16:44:18 +00006174 // Parse exception-specification[opt].
Richard Smith0b3a4622014-11-13 20:01:57 +00006175 bool Delayed = D.isFirstDeclarationOfMember() &&
Richard Smith3ef3e892014-11-20 22:32:11 +00006176 D.isFunctionDeclaratorAFunctionDeclaration();
6177 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6178 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6179 GetLookAheadToken(1).is(tok::l_paren) &&
6180 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6181 GetLookAheadToken(3).is(tok::l_paren) &&
6182 GetLookAheadToken(4).is(tok::identifier) &&
6183 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6184 // HACK: We've got an exception-specification
6185 // noexcept(noexcept(swap(...)))
6186 // or
6187 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6188 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6189 // for 'swap' will only find the function we're currently declaring,
6190 // whereas it expects to find a non-member swap through ADL. Turn off
6191 // delayed parsing to give it a chance to find what it expects.
6192 Delayed = false;
6193 }
Richard Smith0b3a4622014-11-13 20:01:57 +00006194 ESpecType = tryParseExceptionSpecification(Delayed,
6195 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00006196 DynamicExceptions,
6197 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00006198 NoexceptExpr,
6199 ExceptionSpecTokens);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006200 if (ESpecType != EST_None)
6201 EndLoc = ESpecRange.getEnd();
6202
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006203 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6204 // after the exception-specification.
Richard Smith89645bc2013-01-02 12:01:23 +00006205 MaybeParseCXX11Attributes(FnAttrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006206
Douglas Gregor9e66af42011-07-05 16:44:18 +00006207 // Parse trailing-return-type[opt].
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006208 LocalEndLoc = EndLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006209 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00006210 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
Faisal Vali090da2d2018-01-01 18:23:28 +00006211 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006212 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006213 LocalEndLoc = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00006214 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00006215 TrailingReturnType =
6216 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006217 EndLoc = Range.getEnd();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006218 }
Aaron Ballman606093a2017-10-15 15:01:42 +00006219 } else if (standardAttributesAllowed()) {
6220 MaybeParseCXX11Attributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006221 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006222 }
6223
Reid Kleckner078aea92016-12-09 17:14:05 +00006224 // Collect non-parameter declarations from the prototype if this is a function
6225 // declaration. They will be moved into the scope of the function. Only do
6226 // this in C and not C++, where the decls will continue to live in the
6227 // surrounding context.
6228 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6229 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6230 !getLangOpts().CPlusPlus) {
6231 for (Decl *D : getCurScope()->decls()) {
6232 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6233 if (!ND || isa<ParmVarDecl>(ND))
6234 continue;
6235 DeclsInPrototype.push_back(ND);
6236 }
6237 }
6238
Douglas Gregor9e66af42011-07-05 16:44:18 +00006239 // Remember that we parsed a function type, and remember the attributes.
Erich Keanec480f302018-07-12 21:09:05 +00006240 D.AddTypeInfo(DeclaratorChunk::getFunction(
6241 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6242 ParamInfo.size(), EllipsisLoc, RParenLoc,
6243 DS.getTypeQualifiers(), RefQualifierIsLValueRef,
6244 RefQualifierLoc, ConstQualifierLoc, VolatileQualifierLoc,
6245 RestrictQualifierLoc,
6246 /*MutableLoc=*/SourceLocation(), ESpecType, ESpecRange,
6247 DynamicExceptions.data(), DynamicExceptionRanges.data(),
6248 DynamicExceptions.size(),
6249 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6250 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
6251 LocalEndLoc, D, TrailingReturnType),
6252 std::move(FnAttrs), EndLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006253}
6254
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006255/// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6256/// true if a ref-qualifier is found.
6257bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6258 SourceLocation &RefQualifierLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00006259 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006260 Diag(Tok, getLangOpts().CPlusPlus11 ?
6261 diag::warn_cxx98_compat_ref_qualifier :
6262 diag::ext_ref_qualifier);
6263
6264 RefQualifierIsLValueRef = Tok.is(tok::amp);
6265 RefQualifierLoc = ConsumeToken();
6266 return true;
6267 }
6268 return false;
6269}
6270
Douglas Gregor9e66af42011-07-05 16:44:18 +00006271/// isFunctionDeclaratorIdentifierList - This parameter list may have an
6272/// identifier list form for a K&R-style function: void foo(a,b,c)
6273///
6274/// Note that identifier-lists are only allowed for normal declarators, not for
6275/// abstract-declarators.
6276bool Parser::isFunctionDeclaratorIdentifierList() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006277 return !getLangOpts().CPlusPlus
Douglas Gregor9e66af42011-07-05 16:44:18 +00006278 && Tok.is(tok::identifier)
6279 && !TryAltiVecVectorToken()
6280 // K&R identifier lists can't have typedefs as identifiers, per C99
6281 // 6.7.5.3p11.
6282 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6283 // Identifier lists follow a really simple grammar: the identifiers can
6284 // be followed *only* by a ", identifier" or ")". However, K&R
6285 // identifier lists are really rare in the brave new modern world, and
6286 // it is very common for someone to typo a type in a non-K&R style
6287 // list. If we are presented with something like: "void foo(intptr x,
6288 // float y)", we don't want to start parsing the function declarator as
6289 // though it is a K&R style declarator just because intptr is an
6290 // invalid type.
6291 //
6292 // To handle this, we check to see if the token after the first
6293 // identifier is a "," or ")". Only then do we parse it as an
6294 // identifier list.
Bruno Cardoso Lopes218c8742016-09-13 20:04:35 +00006295 && (!Tok.is(tok::eof) &&
6296 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006297}
6298
6299/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6300/// we found a K&R-style identifier list instead of a typed parameter list.
6301///
6302/// After returning, ParamInfo will hold the parsed parameters.
6303///
6304/// identifier-list: [C99 6.7.5]
6305/// identifier
6306/// identifier-list ',' identifier
6307///
6308void Parser::ParseFunctionDeclaratorIdentifierList(
6309 Declarator &D,
Craig Topper5603df42013-07-05 19:34:19 +00006310 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006311 // If there was no identifier specified for the declarator, either we are in
6312 // an abstract-declarator, or we are in a parameter declarator which was found
6313 // to be abstract. In abstract-declarators, identifier lists are not valid:
6314 // diagnose this.
6315 if (!D.getIdentifier())
6316 Diag(Tok, diag::ext_ident_list_in_param);
6317
6318 // Maintain an efficient lookup of params we have seen so far.
6319 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6320
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006321 do {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006322 // If this isn't an identifier, report the error and skip until ')'.
6323 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00006324 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00006325 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006326 // Forget we parsed anything.
6327 ParamInfo.clear();
6328 return;
6329 }
6330
6331 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6332
6333 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6334 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6335 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6336
6337 // Verify that the argument identifier has not already been mentioned.
David Blaikie82e95a32014-11-19 07:49:47 +00006338 if (!ParamsSoFar.insert(ParmII).second) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006339 Diag(Tok, diag::err_param_redefinition) << ParmII;
6340 } else {
6341 // Remember this identifier in ParamInfo.
6342 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6343 Tok.getLocation(),
Craig Topper161e4db2014-05-21 06:02:52 +00006344 nullptr));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006345 }
6346
6347 // Eat the identifier.
6348 ConsumeToken();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006349 // The list continues if we see a comma.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006350 } while (TryConsumeToken(tok::comma));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006351}
6352
6353/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6354/// after the opening parenthesis. This function will not parse a K&R-style
6355/// identifier list.
6356///
Richard Smith2620cd92012-04-11 04:01:28 +00006357/// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6358/// caller parsed those arguments immediately after the open paren - they should
6359/// be considered to be part of the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006360///
6361/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6362/// be the location of the ellipsis, if any was parsed.
6363///
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006364/// parameter-type-list: [C99 6.7.5]
6365/// parameter-list
6366/// parameter-list ',' '...'
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006367/// [C++] parameter-list '...'
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006368///
6369/// parameter-list: [C99 6.7.5]
6370/// parameter-declaration
6371/// parameter-list ',' parameter-declaration
6372///
6373/// parameter-declaration: [C99 6.7.5]
6374/// declaration-specifiers declarator
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006375/// [C++] declaration-specifiers declarator '=' assignment-expression
Sebastian Redldb63af22012-03-14 15:54:00 +00006376/// [C++11] initializer-clause
Chris Lattnere37e2332006-08-15 04:50:22 +00006377/// [GNU] declaration-specifiers declarator attributes
Sebastian Redlf769df52009-03-24 22:27:57 +00006378/// declaration-specifiers abstract-declarator[opt]
6379/// [C++] declaration-specifiers abstract-declarator[opt]
Chris Lattner58258242008-04-10 02:22:51 +00006380/// '=' assignment-expression
Chris Lattnere37e2332006-08-15 04:50:22 +00006381/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
Richard Smith2620cd92012-04-11 04:01:28 +00006382/// [C++11] attribute-specifier-seq parameter-declaration
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006383///
Douglas Gregor9e66af42011-07-05 16:44:18 +00006384void Parser::ParseParameterDeclarationClause(
6385 Declarator &D,
Richard Smith2620cd92012-04-11 04:01:28 +00006386 ParsedAttributes &FirstArgAttrs,
Craig Topper5603df42013-07-05 19:34:19 +00006387 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006388 SourceLocation &EllipsisLoc) {
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006389 do {
6390 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6391 // before deciding this was a parameter-declaration-clause.
6392 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Chris Lattner371ed4e2008-04-06 06:57:35 +00006393 break;
Mike Stump11289f42009-09-09 15:08:12 +00006394
Chris Lattner371ed4e2008-04-06 06:57:35 +00006395 // Parse the declaration-specifiers.
John McCall28a6aea2009-11-04 02:18:39 +00006396 // Just use the ParsingDeclaration "scope" of the declarator.
John McCall084e83d2011-03-24 11:26:52 +00006397 DeclSpec DS(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006398
Richard Smith2620cd92012-04-11 04:01:28 +00006399 // Parse any C++11 attributes.
Richard Smith89645bc2013-01-02 12:01:23 +00006400 MaybeParseCXX11Attributes(DS.getAttributes());
Richard Smith2620cd92012-04-11 04:01:28 +00006401
John McCall53fa7142010-12-24 02:08:15 +00006402 // Skip any Microsoft attributes before a param.
Chad Rosierf8a2e702012-12-20 20:37:53 +00006403 MaybeParseMicrosoftAttributes(DS.getAttributes());
John McCall53fa7142010-12-24 02:08:15 +00006404
6405 SourceLocation DSStart = Tok.getLocation();
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006406
6407 // If the caller parsed attributes for the first argument, add them now.
John McCall53fa7142010-12-24 02:08:15 +00006408 // Take them so that we only apply the attributes to the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006409 // FIXME: If we can leave the attributes in the token stream somehow, we can
Richard Smith2620cd92012-04-11 04:01:28 +00006410 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6411 // too much hassle.
6412 DS.takeAttributesFrom(FirstArgAttrs);
John McCall53fa7142010-12-24 02:08:15 +00006413
Faisal Valia534f072018-04-26 00:42:40 +00006414 ParseDeclarationSpecifiers(DS);
Mike Stump11289f42009-09-09 15:08:12 +00006415
Faisal Vali2b391ab2013-09-26 19:54:12 +00006416
Fangrui Song6907ce22018-07-30 19:24:48 +00006417 // Parse the declarator. This is "PrototypeContext" or
6418 // "LambdaExprParameterContext", because we must accept either
Faisal Vali2b391ab2013-09-26 19:54:12 +00006419 // 'declarator' or 'abstract-declarator' here.
Faisal Vali421b2d12017-12-29 05:41:00 +00006420 Declarator ParmDeclarator(
6421 DS, D.getContext() == DeclaratorContext::LambdaExprContext
6422 ? DeclaratorContext::LambdaExprParameterContext
6423 : DeclaratorContext::PrototypeContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00006424 ParseDeclarator(ParmDeclarator);
Chris Lattner371ed4e2008-04-06 06:57:35 +00006425
6426 // Parse GNU attributes, if present.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006427 MaybeParseGNUAttributes(ParmDeclarator);
Mike Stump11289f42009-09-09 15:08:12 +00006428
Chris Lattner371ed4e2008-04-06 06:57:35 +00006429 // Remember this parsed parameter in ParamInfo.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006430 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
Mike Stump11289f42009-09-09 15:08:12 +00006431
Douglas Gregor4d87df52008-12-16 21:30:33 +00006432 // DefArgToks is used when the parsing of default arguments needs
6433 // to be delayed.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006434 std::unique_ptr<CachedTokens> DefArgToks;
Douglas Gregor4d87df52008-12-16 21:30:33 +00006435
Chris Lattner371ed4e2008-04-06 06:57:35 +00006436 // If no parameter was specified, verify that *something* was specified,
6437 // otherwise we have a missing type and identifier.
Craig Topper161e4db2014-05-21 06:02:52 +00006438 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
Faisal Vali2b391ab2013-09-26 19:54:12 +00006439 ParmDeclarator.getNumTypeObjects() == 0) {
Chris Lattner371ed4e2008-04-06 06:57:35 +00006440 // Completely missing, emit error.
6441 Diag(DSStart, diag::err_missing_param);
6442 } else {
6443 // Otherwise, we have something. Add it and let semantic analysis try
6444 // to grok it and add the result to the ParamInfo we are building.
Mike Stump11289f42009-09-09 15:08:12 +00006445
Richard Smith36ee9fb2014-08-11 23:30:23 +00006446 // Last chance to recover from a misplaced ellipsis in an attempted
6447 // parameter pack declaration.
6448 if (Tok.is(tok::ellipsis) &&
6449 (NextToken().isNot(tok::r_paren) ||
6450 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6451 !Actions.isUnexpandedParameterPackPermitted())) &&
6452 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6453 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6454
Chris Lattner371ed4e2008-04-06 06:57:35 +00006455 // Inform the actions module about the parameter declarator, so it gets
6456 // added to the current scope.
Richard Smith95e1fb02014-08-27 03:23:12 +00006457 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006458 // Parse the default argument, if any. We parse the default
6459 // arguments in all dialects; the semantic analysis in
6460 // ActOnParamDefaultArgument will reject the default argument in
6461 // C.
6462 if (Tok.is(tok::equal)) {
Douglas Gregor58354032008-12-24 00:01:03 +00006463 SourceLocation EqualLoc = Tok.getLocation();
6464
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006465 // Parse the default argument
Faisal Vali421b2d12017-12-29 05:41:00 +00006466 if (D.getContext() == DeclaratorContext::MemberContext) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006467 // If we're inside a class definition, cache the tokens
6468 // corresponding to the default argument. We'll actually parse
6469 // them when we see the end of the class definition.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006470 DefArgToks.reset(new CachedTokens);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006471
David Majnemer906ed272015-01-13 05:28:24 +00006472 SourceLocation ArgStartLoc = NextToken().getLocation();
Richard Smith1fff95c2013-09-12 23:28:08 +00006473 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006474 DefArgToks.reset();
Serge Pavlovb4b35782014-07-22 01:54:49 +00006475 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006476 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006477 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
David Majnemer906ed272015-01-13 05:28:24 +00006478 ArgStartLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006479 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006480 } else {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006481 // Consume the '='.
Douglas Gregor58354032008-12-24 00:01:03 +00006482 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00006483
Chad Rosierc1183952012-06-26 22:30:43 +00006484 // The argument isn't actually potentially evaluated unless it is
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006485 // used.
Faisal Valid143a0c2017-04-01 21:30:49 +00006486 EnterExpressionEvaluationContext Eval(
6487 Actions,
6488 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6489 Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006490
Sebastian Redldb63af22012-03-14 15:54:00 +00006491 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006492 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006493 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +00006494 DefArgResult = ParseBraceInitializer();
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006495 } else
Sebastian Redldb63af22012-03-14 15:54:00 +00006496 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +00006497 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006498 if (DefArgResult.isInvalid()) {
Serge Pavlovb4b35782014-07-22 01:54:49 +00006499 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Alexey Bataevee6507d2013-11-18 08:17:37 +00006500 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006501 } else {
6502 // Inform the actions module about the default argument
6503 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006504 DefArgResult.get());
Douglas Gregor4d87df52008-12-16 21:30:33 +00006505 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006506 }
6507 }
Mike Stump11289f42009-09-09 15:08:12 +00006508
6509 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
Fangrui Song6907ce22018-07-30 19:24:48 +00006510 ParmDeclarator.getIdentifierLoc(),
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006511 Param, std::move(DefArgToks)));
Chris Lattner371ed4e2008-04-06 06:57:35 +00006512 }
6513
Richard Smith36ee9fb2014-08-11 23:30:23 +00006514 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6515 if (!getLangOpts().CPlusPlus) {
6516 // We have ellipsis without a preceding ',', which is ill-formed
6517 // in C. Complain and provide the fix.
6518 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6519 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6520 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6521 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6522 // It looks like this was supposed to be a parameter pack. Warn and
6523 // point out where the ellipsis should have gone.
6524 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6525 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6526 << ParmEllipsis.isValid() << ParmEllipsis;
6527 if (ParmEllipsis.isValid()) {
6528 Diag(ParmEllipsis,
6529 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6530 } else {
6531 Diag(ParmDeclarator.getIdentifierLoc(),
6532 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6533 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6534 "...")
6535 << !ParmDeclarator.hasName();
6536 }
6537 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006538 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
Richard Smith36ee9fb2014-08-11 23:30:23 +00006539 }
6540
6541 // We can't have any more parameters after an ellipsis.
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006542 break;
6543 }
Mike Stump11289f42009-09-09 15:08:12 +00006544
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006545 // If the next token is a comma, consume it and keep reading arguments.
6546 } while (TryConsumeToken(tok::comma));
Chris Lattner6c940e62008-04-06 06:34:08 +00006547}
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006548
Chris Lattnere8074e62006-08-06 18:30:15 +00006549/// [C90] direct-declarator '[' constant-expression[opt] ']'
6550/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6551/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6552/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6553/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006554/// [C++11] direct-declarator '[' constant-expression[opt] ']'
6555/// attribute-specifier-seq[opt]
Chris Lattnere8074e62006-08-06 18:30:15 +00006556void Parser::ParseBracketDeclarator(Declarator &D) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006557 if (CheckProhibitedCXX11Attribute())
6558 return;
6559
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006560 BalancedDelimiterTracker T(*this, tok::l_square);
6561 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00006562
Chris Lattner84a11622008-12-18 07:27:21 +00006563 // C array syntax has many features, but by-far the most common is [] and [4].
6564 // This code does a fast path to handle some of the most obvious cases.
6565 if (Tok.getKind() == tok::r_square) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006566 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006567 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006568 MaybeParseCXX11Attributes(attrs);
Chad Rosierc1183952012-06-26 22:30:43 +00006569
Chris Lattner84a11622008-12-18 07:27:21 +00006570 // Remember that we parsed the empty array type.
Craig Topper161e4db2014-05-21 06:02:52 +00006571 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006572 T.getOpenLocation(),
6573 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006574 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006575 return;
6576 } else if (Tok.getKind() == tok::numeric_constant &&
6577 GetLookAheadToken(1).is(tok::r_square)) {
6578 // [4] is very common. Parse the numeric constant expression.
Richard Smithbcc22fc2012-03-09 08:00:36 +00006579 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
Chris Lattner84a11622008-12-18 07:27:21 +00006580 ConsumeToken();
6581
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006582 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006583 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006584 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006585
Chris Lattner84a11622008-12-18 07:27:21 +00006586 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006587 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006588 T.getOpenLocation(),
6589 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006590 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006591 return;
Benjamin Kramer72dae622016-02-18 15:30:24 +00006592 } else if (Tok.getKind() == tok::code_completion) {
6593 Actions.CodeCompleteBracketDeclarator(getCurScope());
6594 return cutOffParsing();
Chris Lattner84a11622008-12-18 07:27:21 +00006595 }
Mike Stump11289f42009-09-09 15:08:12 +00006596
Chris Lattnere8074e62006-08-06 18:30:15 +00006597 // If valid, this location is the position where we read the 'static' keyword.
6598 SourceLocation StaticLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006599 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006600
Chris Lattnere8074e62006-08-06 18:30:15 +00006601 // If there is a type-qualifier-list, read it now.
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006602 // Type qualifiers in an array subscript are a C99 feature.
John McCall084e83d2011-03-24 11:26:52 +00006603 DeclSpec DS(AttrFactory);
Aaron Ballman08b06592014-07-22 12:44:22 +00006604 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
Mike Stump11289f42009-09-09 15:08:12 +00006605
Chris Lattnere8074e62006-08-06 18:30:15 +00006606 // If we haven't already read 'static', check to see if there is one after the
6607 // type-qualifier-list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006608 if (!StaticLoc.isValid())
6609 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006610
Chris Lattnere8074e62006-08-06 18:30:15 +00006611 // Handle "direct-declarator [ type-qual-list[opt] * ]".
Chris Lattnere8074e62006-08-06 18:30:15 +00006612 bool isStar = false;
John McCalldadc5752010-08-24 06:29:42 +00006613 ExprResult NumElements;
Mike Stump11289f42009-09-09 15:08:12 +00006614
Chris Lattner521ff2b2008-04-06 05:26:30 +00006615 // Handle the case where we have '[*]' as the array size. However, a leading
6616 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
Sylvestre Ledru830885c2012-07-23 08:59:39 +00006617 // the token after the star is a ']'. Since stars in arrays are
Chris Lattner521ff2b2008-04-06 05:26:30 +00006618 // infrequent, use of lookahead is not costly here.
6619 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
Chris Lattnerc439f0d2008-04-06 05:27:21 +00006620 ConsumeToken(); // Eat the '*'.
Chris Lattner1906f802006-08-06 19:14:46 +00006621
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006622 if (StaticLoc.isValid()) {
Chris Lattner521ff2b2008-04-06 05:26:30 +00006623 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006624 StaticLoc = SourceLocation(); // Drop the static.
6625 }
Chris Lattner521ff2b2008-04-06 05:26:30 +00006626 isStar = true;
Chris Lattner76c72282007-10-09 17:33:22 +00006627 } else if (Tok.isNot(tok::r_square)) {
Chris Lattner84a11622008-12-18 07:27:21 +00006628 // Note, in C89, this production uses the constant-expr production instead
6629 // of assignment-expr. The only difference is that assignment-expr allows
6630 // things like '=' and '*='. Sema rejects these in C89 mode because they
6631 // are not i-c-e's, so we don't need to distinguish between the two here.
Mike Stump11289f42009-09-09 15:08:12 +00006632
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006633 // Parse the constant-expression or assignment-expression now (depending
6634 // on dialect).
David Blaikiebbafb8a2012-03-11 07:00:24 +00006635 if (getLangOpts().CPlusPlus) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006636 NumElements = ParseConstantExpression();
Eli Friedmane0afc982012-01-21 01:01:51 +00006637 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00006638 EnterExpressionEvaluationContext Unevaluated(
6639 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Kaelyn Takata15867822014-11-21 18:48:04 +00006640 NumElements =
6641 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Eli Friedmane0afc982012-01-21 01:01:51 +00006642 }
David Majnemerf9834d52014-08-08 07:21:18 +00006643 } else {
6644 if (StaticLoc.isValid()) {
6645 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6646 StaticLoc = SourceLocation(); // Drop the static.
6647 }
Chris Lattner62591722006-08-12 18:40:58 +00006648 }
Mike Stump11289f42009-09-09 15:08:12 +00006649
Chris Lattner62591722006-08-12 18:40:58 +00006650 // If there was an error parsing the assignment-expression, recover.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00006651 if (NumElements.isInvalid()) {
Chris Lattnercd2a8c52009-04-24 22:30:50 +00006652 D.setInvalidType(true);
Chris Lattner62591722006-08-12 18:40:58 +00006653 // If the expression was invalid, skip it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00006654 SkipUntil(tok::r_square, StopAtSemi);
Chris Lattner62591722006-08-12 18:40:58 +00006655 return;
Chris Lattnere8074e62006-08-06 18:30:15 +00006656 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006657
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006658 T.consumeClose();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006659
Jordan Rose303e2f12016-11-10 23:28:17 +00006660 MaybeParseCXX11Attributes(DS.getAttributes());
Alexis Hunt96d5c762009-11-21 08:43:09 +00006661
Chris Lattner84a11622008-12-18 07:27:21 +00006662 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006663 D.AddTypeInfo(
6664 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6665 isStar, NumElements.get(), T.getOpenLocation(),
6666 T.getCloseLocation()),
6667 std::move(DS.getAttributes()), T.getCloseLocation());
Chris Lattnere8074e62006-08-06 18:30:15 +00006668}
6669
Richard Trieuf4b81d02014-06-24 23:14:24 +00006670/// Diagnose brackets before an identifier.
6671void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6672 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6673 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6674
6675 SourceLocation StartBracketLoc = Tok.getLocation();
6676 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6677
6678 while (Tok.is(tok::l_square)) {
6679 ParseBracketDeclarator(TempDeclarator);
6680 }
6681
6682 // Stuff the location of the start of the brackets into the Declarator.
6683 // The diagnostics from ParseDirectDeclarator will make more sense if
6684 // they use this location instead.
6685 if (Tok.is(tok::semi))
6686 D.getName().EndLocation = StartBracketLoc;
6687
6688 SourceLocation SuggestParenLoc = Tok.getLocation();
6689
6690 // Now that the brackets are removed, try parsing the declarator again.
6691 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6692
6693 // Something went wrong parsing the brackets, in which case,
6694 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6695 // one here.
6696 if (TempDeclarator.getNumTypeObjects() == 0)
6697 return;
6698
6699 // Determine if parens will need to be suggested in the diagnostic.
6700 bool NeedParens = false;
6701 if (D.getNumTypeObjects() != 0) {
6702 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6703 case DeclaratorChunk::Pointer:
6704 case DeclaratorChunk::Reference:
6705 case DeclaratorChunk::BlockPointer:
6706 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00006707 case DeclaratorChunk::Pipe:
Richard Trieuf4b81d02014-06-24 23:14:24 +00006708 NeedParens = true;
6709 break;
6710 case DeclaratorChunk::Array:
6711 case DeclaratorChunk::Function:
6712 case DeclaratorChunk::Paren:
6713 break;
6714 }
6715 }
6716
6717 if (NeedParens) {
6718 // Create a DeclaratorChunk for the inserted parens.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006719 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Erich Keanec480f302018-07-12 21:09:05 +00006720 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
Richard Trieuf4b81d02014-06-24 23:14:24 +00006721 SourceLocation());
6722 }
6723
6724 // Adding back the bracket info to the end of the Declarator.
6725 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6726 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
Erich Keanec480f302018-07-12 21:09:05 +00006727 D.AddTypeInfo(Chunk, SourceLocation());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006728 }
6729
6730 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6731 // If parentheses are required, always suggest them.
6732 if (!D.getIdentifier() && !NeedParens)
6733 return;
6734
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006735 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
Richard Trieuf4b81d02014-06-24 23:14:24 +00006736
6737 // Generate the move bracket error message.
6738 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006739 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006740
6741 if (NeedParens) {
6742 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6743 << getLangOpts().CPlusPlus
6744 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6745 << FixItHint::CreateInsertion(EndLoc, ")")
6746 << FixItHint::CreateInsertionFromRange(
6747 EndLoc, CharSourceRange(BracketRange, true))
6748 << FixItHint::CreateRemoval(BracketRange);
6749 } else {
6750 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6751 << getLangOpts().CPlusPlus
6752 << FixItHint::CreateInsertionFromRange(
6753 EndLoc, CharSourceRange(BracketRange, true))
6754 << FixItHint::CreateRemoval(BracketRange);
6755 }
6756}
6757
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006758/// [GNU] typeof-specifier:
6759/// typeof ( expressions )
6760/// typeof ( type-name )
6761/// [GNU/C++] typeof unary-expression
Steve Naroffad373bd2007-07-31 12:34:36 +00006762///
6763void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
Chris Lattner76c72282007-10-09 17:33:22 +00006764 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006765 Token OpTok = Tok;
Steve Naroffad373bd2007-07-31 12:34:36 +00006766 SourceLocation StartLoc = ConsumeToken();
6767
John McCalle8595032010-01-13 20:03:27 +00006768 const bool hasParens = Tok.is(tok::l_paren);
6769
Faisal Valid143a0c2017-04-01 21:30:49 +00006770 EnterExpressionEvaluationContext Unevaluated(
6771 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6772 Sema::ReuseLambdaContextDecl);
Eli Friedmane0afc982012-01-21 01:01:51 +00006773
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006774 bool isCastExpr;
John McCallba7bf592010-08-24 05:47:05 +00006775 ParsedType CastTy;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006776 SourceRange CastRange;
Kaelyn Takata911260742014-12-19 01:28:40 +00006777 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6778 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
John McCalle8595032010-01-13 20:03:27 +00006779 if (hasParens)
6780 DS.setTypeofParensRange(CastRange);
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006781
6782 if (CastRange.getEnd().isInvalid())
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006783 // FIXME: Not accurate, the range gets one token more than it should.
6784 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006785 else
6786 DS.SetRangeEnd(CastRange.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +00006787
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006788 if (isCastExpr) {
6789 if (!CastTy) {
6790 DS.SetTypeSpecError();
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006791 return;
Douglas Gregor220cac52009-02-18 17:45:20 +00006792 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006793
Craig Topper161e4db2014-05-21 06:02:52 +00006794 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006795 unsigned DiagID;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006796 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6797 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006798 DiagID, CastTy,
6799 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006800 Diag(StartLoc, DiagID) << PrevSpec;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006801 return;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006802 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006803
Hiroshi Inoue533777f2017-07-02 06:12:49 +00006804 // If we get here, the operand to the typeof was an expression.
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006805 if (Operand.isInvalid()) {
6806 DS.SetTypeSpecError();
Steve Naroff4bd2f712007-08-02 02:53:48 +00006807 return;
Steve Naroffad373bd2007-07-31 12:34:36 +00006808 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006809
Eli Friedmane0afc982012-01-21 01:01:51 +00006810 // We might need to transform the operand if it is potentially evaluated.
6811 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6812 if (Operand.isInvalid()) {
6813 DS.SetTypeSpecError();
6814 return;
6815 }
6816
Craig Topper161e4db2014-05-21 06:02:52 +00006817 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006818 unsigned DiagID;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006819 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6820 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006821 DiagID, Operand.get(),
6822 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006823 Diag(StartLoc, DiagID) << PrevSpec;
Steve Naroffad373bd2007-07-31 12:34:36 +00006824}
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006825
Benjamin Kramere56f3932011-12-23 17:00:35 +00006826/// [C11] atomic-specifier:
Eli Friedman0dfb8892011-10-06 23:00:33 +00006827/// _Atomic ( type-name )
6828///
6829void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
Richard Smith8e1ac332013-03-28 01:55:44 +00006830 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6831 "Not an atomic specifier");
Eli Friedman0dfb8892011-10-06 23:00:33 +00006832
6833 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006834 BalancedDelimiterTracker T(*this, tok::l_paren);
Richard Smith8e1ac332013-03-28 01:55:44 +00006835 if (T.consumeOpen())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006836 return;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006837
6838 TypeResult Result = ParseTypeName();
6839 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00006840 SkipUntil(tok::r_paren, StopAtSemi);
Eli Friedman0dfb8892011-10-06 23:00:33 +00006841 return;
6842 }
6843
6844 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006845 T.consumeClose();
Eli Friedman0dfb8892011-10-06 23:00:33 +00006846
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006847 if (T.getCloseLocation().isInvalid())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006848 return;
6849
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006850 DS.setTypeofParensRange(T.getRange());
6851 DS.SetRangeEnd(T.getCloseLocation());
Eli Friedman0dfb8892011-10-06 23:00:33 +00006852
Craig Topper161e4db2014-05-21 06:02:52 +00006853 const char *PrevSpec = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006854 unsigned DiagID;
6855 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006856 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006857 Actions.getASTContext().getPrintingPolicy()))
Eli Friedman0dfb8892011-10-06 23:00:33 +00006858 Diag(StartLoc, DiagID) << PrevSpec;
6859}
6860
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006861/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6862/// from TryAltiVecVectorToken.
6863bool Parser::TryAltiVecVectorTokenOutOfLine() {
6864 Token Next = NextToken();
6865 switch (Next.getKind()) {
6866 default: return false;
6867 case tok::kw_short:
6868 case tok::kw_long:
6869 case tok::kw_signed:
6870 case tok::kw_unsigned:
6871 case tok::kw_void:
6872 case tok::kw_char:
6873 case tok::kw_int:
6874 case tok::kw_float:
6875 case tok::kw_double:
6876 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006877 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006878 case tok::kw___pixel:
6879 Tok.setKind(tok::kw___vector);
6880 return true;
6881 case tok::identifier:
6882 if (Next.getIdentifierInfo() == Ident_pixel) {
6883 Tok.setKind(tok::kw___vector);
6884 return true;
6885 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006886 if (Next.getIdentifierInfo() == Ident_bool) {
6887 Tok.setKind(tok::kw___vector);
6888 return true;
6889 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006890 return false;
6891 }
6892}
6893
6894bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6895 const char *&PrevSpec, unsigned &DiagID,
6896 bool &isInvalid) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006897 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006898 if (Tok.getIdentifierInfo() == Ident_vector) {
6899 Token Next = NextToken();
6900 switch (Next.getKind()) {
6901 case tok::kw_short:
6902 case tok::kw_long:
6903 case tok::kw_signed:
6904 case tok::kw_unsigned:
6905 case tok::kw_void:
6906 case tok::kw_char:
6907 case tok::kw_int:
6908 case tok::kw_float:
6909 case tok::kw_double:
6910 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006911 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006912 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006913 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006914 return true;
6915 case tok::identifier:
6916 if (Next.getIdentifierInfo() == Ident_pixel) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006917 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006918 return true;
6919 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006920 if (Next.getIdentifierInfo() == Ident_bool) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006921 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00006922 return true;
6923 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006924 break;
6925 default:
6926 break;
6927 }
Douglas Gregor9938e3b2010-06-16 15:28:57 +00006928 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006929 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006930 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006931 return true;
Bill Schmidt99a084b2013-07-03 20:54:09 +00006932 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6933 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006934 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00006935 return true;
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006936 }
6937 return false;
6938}