blob: 04c0286ec6d6ab16dff12bf12b7b84e95a6d56ee [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();
757 if (!getLangOpts().ObjC1)
758 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
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001004 if (Tok.isNot(tok::equal)) {
Alp Tokerec543272013-12-24 09:48:30 +00001005 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001006 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001007 return;
1008 }
1009 ConsumeToken();
Manman Ren75bc6762016-03-21 17:30:55 +00001010 if (Keyword == Ident_message || Keyword == Ident_replacement) {
David Majnemer2e498302014-07-18 05:43:12 +00001011 if (Tok.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001012 Diag(Tok, diag::err_expected_string_literal)
1013 << /*Source='availability attribute'*/2;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001014 SkipUntil(tok::r_paren, StopAtSemi);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001015 return;
1016 }
Manman Ren75bc6762016-03-21 17:30:55 +00001017 if (Keyword == Ident_message)
1018 MessageExpr = ParseStringLiteralExpression();
1019 else
1020 ReplacementExpr = ParseStringLiteralExpression();
David Majnemer2e498302014-07-18 05:43:12 +00001021 // Also reject wide string literals.
1022 if (StringLiteral *MessageStringLiteral =
1023 cast_or_null<StringLiteral>(MessageExpr.get())) {
1024 if (MessageStringLiteral->getCharByteWidth() != 1) {
1025 Diag(MessageStringLiteral->getSourceRange().getBegin(),
1026 diag::err_expected_string_literal)
1027 << /*Source='availability attribute'*/ 2;
1028 SkipUntil(tok::r_paren, StopAtSemi);
1029 return;
1030 }
1031 }
Manman Ren75bc6762016-03-21 17:30:55 +00001032 if (Keyword == Ident_message)
1033 break;
1034 else
1035 continue;
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001036 }
Chad Rosierc1183952012-06-26 22:30:43 +00001037
Fariborz Jahanian5a29e6a2014-11-05 23:58:55 +00001038 // Special handling of 'NA' only when applied to introduced or
1039 // deprecated.
1040 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1041 Tok.is(tok::identifier)) {
1042 IdentifierInfo *NA = Tok.getIdentifierInfo();
1043 if (NA->getName() == "NA") {
1044 ConsumeToken();
1045 if (Keyword == Ident_introduced)
1046 UnavailableLoc = KeywordLoc;
1047 continue;
1048 }
1049 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001050
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001051 SourceRange VersionRange;
1052 VersionTuple Version = ParseVersionTuple(VersionRange);
Chad Rosierc1183952012-06-26 22:30:43 +00001053
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001054 if (Version.empty()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001055 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001056 return;
1057 }
1058
1059 unsigned Index;
1060 if (Keyword == Ident_introduced)
1061 Index = Introduced;
1062 else if (Keyword == Ident_deprecated)
1063 Index = Deprecated;
1064 else if (Keyword == Ident_obsoleted)
1065 Index = Obsoleted;
Chad Rosierc1183952012-06-26 22:30:43 +00001066 else
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001067 Index = Unknown;
1068
1069 if (Index < Unknown) {
1070 if (!Changes[Index].KeywordLoc.isInvalid()) {
1071 Diag(KeywordLoc, diag::err_availability_redundant)
Chad Rosierc1183952012-06-26 22:30:43 +00001072 << Keyword
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001073 << SourceRange(Changes[Index].KeywordLoc,
1074 Changes[Index].VersionRange.getEnd());
1075 }
1076
1077 Changes[Index].KeywordLoc = KeywordLoc;
1078 Changes[Index].Version = Version;
1079 Changes[Index].VersionRange = VersionRange;
1080 } else {
1081 Diag(KeywordLoc, diag::err_availability_unknown_change)
1082 << Keyword << VersionRange;
1083 }
1084
Alp Toker97650562014-01-10 11:19:30 +00001085 } while (TryConsumeToken(tok::comma));
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001086
1087 // Closing ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001088 if (T.consumeClose())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001089 return;
1090
1091 if (endLoc)
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001092 *endLoc = T.getCloseLocation();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001093
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001094 // The 'unavailable' availability cannot be combined with any other
1095 // availability changes. Make sure that hasn't happened.
1096 if (UnavailableLoc.isValid()) {
1097 bool Complained = false;
1098 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1099 if (Changes[Index].KeywordLoc.isValid()) {
1100 if (!Complained) {
1101 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1102 << SourceRange(Changes[Index].KeywordLoc,
1103 Changes[Index].VersionRange.getEnd());
1104 Complained = true;
1105 }
1106
1107 // Clear out the availability.
1108 Changes[Index] = AvailabilityChange();
1109 }
1110 }
1111 }
1112
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001113 // Record this attribute
Chad Rosierc1183952012-06-26 22:30:43 +00001114 attrs.addNew(&Availability,
1115 SourceRange(AvailabilityLoc, T.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001116 ScopeName, ScopeLoc,
Aaron Ballman00e99962013-08-31 01:11:41 +00001117 Platform,
John McCall084e83d2011-03-24 11:26:52 +00001118 Changes[Introduced],
1119 Changes[Deprecated],
Chad Rosierc1183952012-06-26 22:30:43 +00001120 Changes[Obsoleted],
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001121 UnavailableLoc, MessageExpr.get(),
Manman Ren75bc6762016-03-21 17:30:55 +00001122 Syntax, StrictLoc, ReplacementExpr.get());
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001123}
1124
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001125/// Parse the contents of the "external_source_symbol" attribute.
Alex Lorenzd5d27e12017-03-01 18:06:25 +00001126///
1127/// external-source-symbol-attribute:
1128/// 'external_source_symbol' '(' keyword-arg-list ')'
1129///
1130/// keyword-arg-list:
1131/// keyword-arg
1132/// keyword-arg ',' keyword-arg-list
1133///
1134/// keyword-arg:
1135/// 'language' '=' <string>
1136/// 'defined_in' '=' <string>
1137/// 'generated_declaration'
1138void Parser::ParseExternalSourceSymbolAttribute(
1139 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1140 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
Erich Keanee891aa92018-07-13 15:07:47 +00001141 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
Alex Lorenzd5d27e12017-03-01 18:06:25 +00001142 // Opening '('.
1143 BalancedDelimiterTracker T(*this, tok::l_paren);
1144 if (T.expectAndConsume())
1145 return;
1146
1147 // Initialize the pointers for the keyword identifiers when required.
1148 if (!Ident_language) {
1149 Ident_language = PP.getIdentifierInfo("language");
1150 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1151 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1152 }
1153
1154 ExprResult Language;
1155 bool HasLanguage = false;
1156 ExprResult DefinedInExpr;
1157 bool HasDefinedIn = false;
1158 IdentifierLoc *GeneratedDeclaration = nullptr;
1159
1160 // Parse the language/defined_in/generated_declaration keywords
1161 do {
1162 if (Tok.isNot(tok::identifier)) {
1163 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1164 SkipUntil(tok::r_paren, StopAtSemi);
1165 return;
1166 }
1167
1168 SourceLocation KeywordLoc = Tok.getLocation();
1169 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1170 if (Keyword == Ident_generated_declaration) {
1171 if (GeneratedDeclaration) {
1172 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1173 SkipUntil(tok::r_paren, StopAtSemi);
1174 return;
1175 }
1176 GeneratedDeclaration = ParseIdentifierLoc();
1177 continue;
1178 }
1179
1180 if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1181 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1182 SkipUntil(tok::r_paren, StopAtSemi);
1183 return;
1184 }
1185
1186 ConsumeToken();
1187 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1188 Keyword->getName())) {
1189 SkipUntil(tok::r_paren, StopAtSemi);
1190 return;
1191 }
1192
1193 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1194 if (Keyword == Ident_language)
1195 HasLanguage = true;
1196 else
1197 HasDefinedIn = true;
1198
1199 if (Tok.isNot(tok::string_literal)) {
1200 Diag(Tok, diag::err_expected_string_literal)
1201 << /*Source='external_source_symbol attribute'*/ 3
1202 << /*language | source container*/ (Keyword != Ident_language);
1203 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1204 continue;
1205 }
1206 if (Keyword == Ident_language) {
1207 if (HadLanguage) {
1208 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1209 << Keyword;
1210 ParseStringLiteralExpression();
1211 continue;
1212 }
1213 Language = ParseStringLiteralExpression();
1214 } else {
1215 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1216 if (HadDefinedIn) {
1217 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1218 << Keyword;
1219 ParseStringLiteralExpression();
1220 continue;
1221 }
1222 DefinedInExpr = ParseStringLiteralExpression();
1223 }
1224 } while (TryConsumeToken(tok::comma));
1225
1226 // Closing ')'.
1227 if (T.consumeClose())
1228 return;
1229 if (EndLoc)
1230 *EndLoc = T.getCloseLocation();
1231
1232 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1233 GeneratedDeclaration};
1234 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1235 ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1236}
1237
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001238/// Parse the contents of the "objc_bridge_related" attribute.
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001239/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1240/// related_class:
1241/// Identifier
1242///
1243/// opt-class_method:
1244/// Identifier: | <empty>
1245///
1246/// opt-instance_method:
1247/// Identifier | <empty>
1248///
1249void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1250 SourceLocation ObjCBridgeRelatedLoc,
1251 ParsedAttributes &attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001252 SourceLocation *endLoc,
1253 IdentifierInfo *ScopeName,
1254 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001255 ParsedAttr::Syntax Syntax) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001256 // Opening '('.
1257 BalancedDelimiterTracker T(*this, tok::l_paren);
1258 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00001259 Diag(Tok, diag::err_expected) << tok::l_paren;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001260 return;
1261 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001262
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001263 // Parse the related class name.
1264 if (Tok.isNot(tok::identifier)) {
1265 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1266 SkipUntil(tok::r_paren, StopAtSemi);
1267 return;
1268 }
1269 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
Alp Toker97650562014-01-10 11:19:30 +00001270 if (ExpectAndConsume(tok::comma)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001271 SkipUntil(tok::r_paren, StopAtSemi);
1272 return;
1273 }
Alp Toker8fbec672013-12-17 23:29:36 +00001274
Aaron Ballman48a533d2018-02-27 23:49:28 +00001275 // Parse class method name. It's non-optional in the sense that a trailing
1276 // comma is required, but it can be the empty string, and then we record a
1277 // nullptr.
Craig Topper161e4db2014-05-21 06:02:52 +00001278 IdentifierLoc *ClassMethod = nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001279 if (Tok.is(tok::identifier)) {
1280 ClassMethod = ParseIdentifierLoc();
Alp Toker8fbec672013-12-17 23:29:36 +00001281 if (!TryConsumeToken(tok::colon)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001282 Diag(Tok, diag::err_objcbridge_related_selector_name);
1283 SkipUntil(tok::r_paren, StopAtSemi);
1284 return;
1285 }
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001286 }
Alp Toker8fbec672013-12-17 23:29:36 +00001287 if (!TryConsumeToken(tok::comma)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001288 if (Tok.is(tok::colon))
1289 Diag(Tok, diag::err_objcbridge_related_selector_name);
1290 else
Alp Tokerec543272013-12-24 09:48:30 +00001291 Diag(Tok, diag::err_expected) << tok::comma;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001292 SkipUntil(tok::r_paren, StopAtSemi);
1293 return;
1294 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001295
Aaron Ballman48a533d2018-02-27 23:49:28 +00001296 // Parse instance method name. Also non-optional but empty string is
1297 // permitted.
Craig Topper161e4db2014-05-21 06:02:52 +00001298 IdentifierLoc *InstanceMethod = nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001299 if (Tok.is(tok::identifier))
1300 InstanceMethod = ParseIdentifierLoc();
1301 else if (Tok.isNot(tok::r_paren)) {
Alp Tokerec543272013-12-24 09:48:30 +00001302 Diag(Tok, diag::err_expected) << tok::r_paren;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001303 SkipUntil(tok::r_paren, StopAtSemi);
1304 return;
1305 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001306
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001307 // Closing ')'.
1308 if (T.consumeClose())
1309 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001310
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001311 if (endLoc)
1312 *endLoc = T.getCloseLocation();
Fangrui Song6907ce22018-07-30 19:24:48 +00001313
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001314 // Record this attribute
1315 attrs.addNew(&ObjCBridgeRelated,
1316 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001317 ScopeName, ScopeLoc,
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001318 RelatedClass,
1319 ClassMethod,
1320 InstanceMethod,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001321 Syntax);
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001322}
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001323
Bill Wendling44426052012-12-20 19:22:21 +00001324// Late Parsed Attributes:
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001325// See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1326
1327void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1328
1329void Parser::LateParsedClass::ParseLexedAttributes() {
1330 Self->ParseLexedAttributes(*Class);
1331}
1332
1333void Parser::LateParsedAttribute::ParseLexedAttributes() {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001334 Self->ParseLexedAttribute(*this, true, false);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001335}
1336
1337/// Wrapper class which calls ParseLexedAttribute, after setting up the
1338/// scope appropriately.
1339void Parser::ParseLexedAttributes(ParsingClass &Class) {
1340 // Deal with templates
1341 // FIXME: Test cases to make sure this does the right thing for templates.
1342 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1343 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1344 HasTemplateScope);
1345 if (HasTemplateScope)
1346 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1347
Douglas Gregor3024f072012-04-16 07:05:22 +00001348 // Set or update the scope flags.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001349 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +00001350 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001351 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1352 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1353
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001354 // Enter the scope of nested classes
1355 if (!AlreadyHasClassScope)
1356 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1357 Class.TagOrTemplate);
Benjamin Kramer1d373c62012-05-17 12:01:52 +00001358 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001359 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1360 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1361 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001362 }
Chad Rosierc1183952012-06-26 22:30:43 +00001363
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001364 if (!AlreadyHasClassScope)
1365 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1366 Class.TagOrTemplate);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001367}
1368
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001369/// Parse all attributes in LAs, and attach them to Decl D.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001370void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1371 bool EnterScope, bool OnDefinition) {
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001372 assert(LAs.parseSoon() &&
1373 "Attribute list should be marked for immediate parsing.");
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001374 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
DeLesley Hutchins19c722d2012-08-15 22:41:04 +00001375 if (D)
1376 LAs[i]->addDecl(D);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001377 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
Benjamin Kramerbafc49a2012-04-14 12:44:47 +00001378 delete LAs[i];
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001379 }
1380 LAs.clear();
1381}
1382
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001383/// Finish parsing an attribute for which parsing was delayed.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001384/// This will be called at the end of parsing a class declaration
1385/// for each LateParsedAttribute. We consume the saved tokens and
Chad Rosierc1183952012-06-26 22:30:43 +00001386/// create an attribute with the arguments filled in. We add this
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001387/// to the Attribute list for the decl.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001388void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1389 bool EnterScope, bool OnDefinition) {
David Majnemerd5946f52015-01-13 08:35:24 +00001390 // Create a fake EOF so that attribute parsing won't go off the end of the
1391 // attribute.
1392 Token AttrEnd;
1393 AttrEnd.startToken();
1394 AttrEnd.setKind(tok::eof);
1395 AttrEnd.setLocation(Tok.getLocation());
1396 AttrEnd.setEofData(LA.Toks.data());
1397 LA.Toks.push_back(AttrEnd);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001398
1399 // Append the current token at the end of the new token stream so that it
1400 // doesn't get lost.
1401 LA.Toks.push_back(Tok);
David Blaikie2eabcc92016-02-09 18:52:09 +00001402 PP.EnterTokenStream(LA.Toks, true);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001403 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +00001404 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001405
1406 ParsedAttributes Attrs(AttrFactory);
1407 SourceLocation endLoc;
1408
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001409 if (LA.Decls.size() > 0) {
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001410 Decl *D = LA.Decls[0];
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001411 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1412 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001413
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001414 // Allow 'this' within late-parsed attributes.
Richard Smithc3d2ebb2013-06-07 02:33:37 +00001415 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0,
1416 ND && ND->isCXXInstanceMember());
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001417
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001418 if (LA.Decls.size() == 1) {
1419 // If the Decl is templatized, add template parameters to scope.
1420 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1421 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1422 if (HasTemplateScope)
1423 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001424
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001425 // If the Decl is on a function, add function parameters to the scope.
1426 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
Momchil Velikov57c681f2017-08-10 15:43:06 +00001427 ParseScope FnScope(
1428 this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
1429 HasFunScope);
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001430 if (HasFunScope)
1431 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001432
Michael Han23214e52012-10-03 01:56:22 +00001433 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001434 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
Craig Topper161e4db2014-05-21 06:02:52 +00001435 nullptr);
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001436
1437 if (HasFunScope) {
1438 Actions.ActOnExitFunctionContext();
1439 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1440 }
1441 if (HasTemplateScope) {
1442 TempScope.Exit();
1443 }
1444 } else {
1445 // If there are multiple decls, then the decl cannot be within the
1446 // function scope.
Michael Han23214e52012-10-03 01:56:22 +00001447 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001448 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
Craig Topper161e4db2014-05-21 06:02:52 +00001449 nullptr);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001450 }
DeLesley Hutchins71d61032012-03-02 22:29:50 +00001451 } else {
1452 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001453 }
1454
Erich Keanec480f302018-07-12 21:09:05 +00001455 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
1456 Attrs.begin()->isKnownToGCC())
Aaron Ballman9a99e0d2014-01-20 17:18:35 +00001457 Diag(Tok, diag::warn_attribute_on_function_definition)
1458 << &LA.AttrName;
1459
1460 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001461 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001462
David Majnemerd5946f52015-01-13 08:35:24 +00001463 // Due to a parsing error, we either went over the cached tokens or
1464 // there are still cached tokens left, so we skip the leftover tokens.
1465 while (Tok.isNot(tok::eof))
1466 ConsumeAnyToken();
1467
1468 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1469 ConsumeAnyToken();
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001470}
1471
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001472void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1473 SourceLocation AttrNameLoc,
1474 ParsedAttributes &Attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001475 SourceLocation *EndLoc,
1476 IdentifierInfo *ScopeName,
1477 SourceLocation ScopeLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00001478 ParsedAttr::Syntax Syntax) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001479 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1480
1481 BalancedDelimiterTracker T(*this, tok::l_paren);
1482 T.consumeOpen();
1483
1484 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001485 Diag(Tok, diag::err_expected) << tok::identifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001486 T.skipToEnd();
1487 return;
1488 }
Richard Smithfeefaf52013-09-03 18:01:40 +00001489 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001490
Alp Toker094e5212014-01-05 03:27:11 +00001491 if (ExpectAndConsume(tok::comma)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001492 T.skipToEnd();
1493 return;
1494 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001495
1496 SourceRange MatchingCTypeRange;
1497 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1498 if (MatchingCType.isInvalid()) {
1499 T.skipToEnd();
1500 return;
1501 }
1502
1503 bool LayoutCompatible = false;
1504 bool MustBeNull = false;
Alp Toker8fbec672013-12-17 23:29:36 +00001505 while (TryConsumeToken(tok::comma)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001506 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001507 Diag(Tok, diag::err_expected) << tok::identifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001508 T.skipToEnd();
1509 return;
1510 }
1511 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1512 if (Flag->isStr("layout_compatible"))
1513 LayoutCompatible = true;
1514 else if (Flag->isStr("must_be_null"))
1515 MustBeNull = true;
1516 else {
1517 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1518 T.skipToEnd();
1519 return;
1520 }
1521 ConsumeToken(); // consume flag
1522 }
1523
1524 if (!T.consumeClose()) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001525 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001526 ArgumentKind, MatchingCType.get(),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001527 LayoutCompatible, MustBeNull, Syntax);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001528 }
1529
1530 if (EndLoc)
1531 *EndLoc = T.getCloseLocation();
1532}
1533
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001534/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1535/// of a C++11 attribute-specifier in a location where an attribute is not
1536/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1537/// situation.
1538///
1539/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1540/// this doesn't appear to actually be an attribute-specifier, and the caller
1541/// should try to parse it.
1542bool Parser::DiagnoseProhibitedCXX11Attribute() {
1543 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1544
1545 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1546 case CAK_NotAttributeSpecifier:
1547 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1548 return false;
1549
1550 case CAK_InvalidAttributeSpecifier:
1551 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1552 return false;
1553
1554 case CAK_AttributeSpecifier:
1555 // Parse and discard the attributes.
1556 SourceLocation BeginLoc = ConsumeBracket();
1557 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001558 SkipUntil(tok::r_square);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001559 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1560 SourceLocation EndLoc = ConsumeBracket();
1561 Diag(BeginLoc, diag::err_attributes_not_allowed)
1562 << SourceRange(BeginLoc, EndLoc);
1563 return true;
1564 }
Chandler Carruthd8f7d382012-04-10 16:03:08 +00001565 llvm_unreachable("All cases handled above.");
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001566}
1567
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001568/// We have found the opening square brackets of a C++11
Richard Smith98155ad2013-02-20 01:17:14 +00001569/// attribute-specifier in a location where an attribute is not permitted, but
1570/// we know where the attributes ought to be written. Parse them anyway, and
1571/// provide a fixit moving them to the right place.
Richard Smith4c96e992013-02-19 23:47:15 +00001572void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1573 SourceLocation CorrectLocation) {
1574 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1575 Tok.is(tok::kw_alignas));
1576
1577 // Consume the attributes.
1578 SourceLocation Loc = Tok.getLocation();
1579 ParseCXX11Attributes(Attrs);
1580 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
Faisal Valic5089c02017-12-25 22:23:20 +00001581 // FIXME: use err_attributes_misplaced
Richard Smith4c96e992013-02-19 23:47:15 +00001582 Diag(Loc, diag::err_attributes_not_allowed)
1583 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1584 << FixItHint::CreateRemoval(AttrRange);
1585}
1586
Erich Keanec480f302018-07-12 21:09:05 +00001587void Parser::DiagnoseProhibitedAttributes(
1588 const SourceRange &Range, const SourceLocation CorrectLocation) {
Faisal Valic5089c02017-12-25 22:23:20 +00001589 if (CorrectLocation.isValid()) {
Erich Keanec480f302018-07-12 21:09:05 +00001590 CharSourceRange AttrRange(Range, true);
Faisal Valic5089c02017-12-25 22:23:20 +00001591 Diag(CorrectLocation, diag::err_attributes_misplaced)
1592 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1593 << FixItHint::CreateRemoval(AttrRange);
1594 } else
Erich Keanec480f302018-07-12 21:09:05 +00001595 Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
Dawn Perchik335e16b2010-09-03 01:29:35 +00001596}
1597
Richard Smith49cc1cc2016-08-18 21:59:42 +00001598void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1599 unsigned DiagID) {
Erich Keanee891aa92018-07-13 15:07:47 +00001600 for (const ParsedAttr &AL : Attrs) {
Erich Keanec480f302018-07-12 21:09:05 +00001601 if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
Richard Smith49cc1cc2016-08-18 21:59:42 +00001602 continue;
Erich Keanee891aa92018-07-13 15:07:47 +00001603 if (AL.getKind() == ParsedAttr::UnknownAttribute)
Erich Keanec480f302018-07-12 21:09:05 +00001604 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL.getName();
Richard Smith49cc1cc2016-08-18 21:59:42 +00001605 else {
Erich Keanec480f302018-07-12 21:09:05 +00001606 Diag(AL.getLoc(), DiagID) << AL.getName();
1607 AL.setInvalid();
Michael Han64536a62012-11-06 19:34:54 +00001608 }
Michael Han64536a62012-11-06 19:34:54 +00001609 }
1610}
1611
Nico Weber32a0fc72016-09-03 03:01:32 +00001612// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1613// applies to var, not the type Foo.
David Majnemer936b4112015-04-19 07:53:29 +00001614// As an exception to the rule, __declspec(align(...)) before the
1615// class-key affects the type instead of the variable.
Nico Weber32a0fc72016-09-03 03:01:32 +00001616// Also, Microsoft-style [attributes] seem to affect the type instead of the
1617// variable.
1618// This function moves attributes that should apply to the type off DS to Attrs.
1619void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1620 DeclSpec &DS,
1621 Sema::TagUseKind TUK) {
David Majnemer936b4112015-04-19 07:53:29 +00001622 if (TUK == Sema::TUK_Reference)
1623 return;
1624
Erich Keanee891aa92018-07-13 15:07:47 +00001625 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
David Majnemer936b4112015-04-19 07:53:29 +00001626
Erich Keanee891aa92018-07-13 15:07:47 +00001627 for (ParsedAttr &AL : DS.getAttributes()) {
1628 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
Erich Keanec480f302018-07-12 21:09:05 +00001629 AL.isDeclspecAttribute()) ||
1630 AL.isMicrosoftAttribute())
1631 ToBeMoved.push_back(&AL);
David Majnemer936b4112015-04-19 07:53:29 +00001632 }
Nico Weber88f5ed92016-09-13 18:55:26 +00001633
Erich Keanee891aa92018-07-13 15:07:47 +00001634 for (ParsedAttr *AL : ToBeMoved) {
Erich Keanec480f302018-07-12 21:09:05 +00001635 DS.getAttributes().remove(AL);
1636 Attrs.addAtEnd(AL);
1637 }
David Majnemer936b4112015-04-19 07:53:29 +00001638}
1639
Chris Lattner53361ac2006-08-10 05:19:57 +00001640/// ParseDeclaration - Parse a full 'declaration', which consists of
1641/// declaration-specifiers, some number of declarators, and a semicolon.
Faisal Vali421b2d12017-12-29 05:41:00 +00001642/// 'Context' should be a DeclaratorContext value. This returns the
Chris Lattner49836b42009-04-02 04:16:50 +00001643/// location of the semicolon in DeclEnd.
Chris Lattnera5235172007-08-25 06:57:03 +00001644///
1645/// declaration: [C99 6.7]
1646/// block-declaration ->
1647/// simple-declaration
1648/// others [FIXME]
Douglas Gregoreb31f392008-12-01 23:54:00 +00001649/// [C++] template-declaration
Chris Lattnera5235172007-08-25 06:57:03 +00001650/// [C++] namespace-definition
Douglas Gregord7c4d982008-12-30 03:27:21 +00001651/// [C++] using-directive
Douglas Gregor77b50e12009-06-22 23:06:13 +00001652/// [C++] using-declaration
Richard Smithc202b282012-04-14 00:33:13 +00001653/// [C++11/C11] static_assert-declaration
Chris Lattnera5235172007-08-25 06:57:03 +00001654/// others... [FIXME]
1655///
Faisal Vali421b2d12017-12-29 05:41:00 +00001656Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
Alexis Hunt96d5c762009-11-21 08:43:09 +00001657 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +00001658 ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +00001659 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Fariborz Jahanian59b75282011-08-30 17:10:52 +00001660 // Must temporarily exit the objective-c container scope for
1661 // parsing c none objective-c decls.
1662 ObjCDeclContextSwitch ObjCDC(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00001663
Craig Topper161e4db2014-05-21 06:02:52 +00001664 Decl *SingleDecl = nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +00001665 switch (Tok.getKind()) {
Douglas Gregoreb31f392008-12-01 23:54:00 +00001666 case tok::kw_template:
Douglas Gregor23996282009-05-12 21:31:51 +00001667 case tok::kw_export:
John McCall53fa7142010-12-24 02:08:15 +00001668 ProhibitAttributes(attrs);
Erich Keanec480f302018-07-12 21:09:05 +00001669 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001670 break;
Sebastian Redl67667942010-08-27 23:12:46 +00001671 case tok::kw_inline:
Sebastian Redl5a5f2c72010-08-31 00:36:45 +00001672 // Could be the start of an inline namespace. Allowed as an ext in C++03.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001673 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
John McCall53fa7142010-12-24 02:08:15 +00001674 ProhibitAttributes(attrs);
Sebastian Redl67667942010-08-27 23:12:46 +00001675 SourceLocation InlineLoc = ConsumeToken();
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00001676 return ParseNamespace(Context, DeclEnd, InlineLoc);
Sebastian Redl67667942010-08-27 23:12:46 +00001677 }
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001678 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
Fariborz Jahanian1db5c942010-09-28 20:42:35 +00001679 true);
Chris Lattnera5235172007-08-25 06:57:03 +00001680 case tok::kw_namespace:
John McCall53fa7142010-12-24 02:08:15 +00001681 ProhibitAttributes(attrs);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00001682 return ParseNamespace(Context, DeclEnd);
Douglas Gregord7c4d982008-12-30 03:27:21 +00001683 case tok::kw_using:
Richard Smith6f1daa42016-12-16 00:58:48 +00001684 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1685 DeclEnd, attrs);
Anders Carlssonf24fcff62009-03-11 16:27:10 +00001686 case tok::kw_static_assert:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00001687 case tok::kw__Static_assert:
John McCall53fa7142010-12-24 02:08:15 +00001688 ProhibitAttributes(attrs);
Chris Lattner49836b42009-04-02 04:16:50 +00001689 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001690 break;
Chris Lattnera5235172007-08-25 06:57:03 +00001691 default:
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001692 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
Chris Lattnera5235172007-08-25 06:57:03 +00001693 }
Chad Rosierc1183952012-06-26 22:30:43 +00001694
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001695 // This routine returns a DeclGroup, if the thing we parsed only contains a
Richard Smith6f1daa42016-12-16 00:58:48 +00001696 // single decl, convert it now.
1697 return Actions.ConvertDeclToDeclGroup(SingleDecl);
Chris Lattnera5235172007-08-25 06:57:03 +00001698}
1699
1700/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1701/// declaration-specifiers init-declarator-list[opt] ';'
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001702/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1703/// init-declarator-list ';'
Chris Lattnera5235172007-08-25 06:57:03 +00001704///[C90/C++]init-declarator-list ';' [TODO]
1705/// [OMP] threadprivate-directive [TODO]
Chris Lattner32dc41c2009-03-29 17:27:48 +00001706///
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001707/// for-range-declaration: [C++11 6.5p1: stmt.ranged]
Richard Smith02e85f32011-04-14 22:09:26 +00001708/// attribute-specifier-seq[opt] type-specifier-seq declarator
1709///
Chris Lattner32dc41c2009-03-29 17:27:48 +00001710/// If RequireSemi is false, this does not check for a ';' at the end of the
Chris Lattner005fc1b2010-04-05 18:18:31 +00001711/// declaration. If it is true, it checks for and eats it.
Richard Smith02e85f32011-04-14 22:09:26 +00001712///
1713/// If FRI is non-null, we might be parsing a for-range-declaration instead
1714/// of a simple-declaration. If we find that we are, we also parse the
1715/// for-range-initializer, and place it here.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001716Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +00001717Parser::ParseSimpleDeclaration(DeclaratorContext Context,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001718 SourceLocation &DeclEnd,
Richard Smith2386c8b2013-02-22 09:06:26 +00001719 ParsedAttributesWithRange &Attrs,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001720 bool RequireSemi, ForRangeInit *FRI) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001721 // Parse the common declaration-specifiers piece.
John McCall28a6aea2009-11-04 02:18:39 +00001722 ParsingDeclSpec DS(*this);
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001723
Richard Smith404dfb42013-11-19 22:47:36 +00001724 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
Faisal Valia534f072018-04-26 00:42:40 +00001725 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
Richard Smith404dfb42013-11-19 22:47:36 +00001726
1727 // If we had a free-standing type definition with a missing semicolon, we
1728 // may get this far before the problem becomes obvious.
1729 if (DS.hasTagDefinition() &&
1730 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
David Blaikie0403cb12016-01-15 23:43:25 +00001731 return nullptr;
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001732
Chris Lattner0e894622006-08-13 19:58:17 +00001733 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1734 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner76c72282007-10-09 17:33:22 +00001735 if (Tok.is(tok::semi)) {
Richard Smith2386c8b2013-02-22 09:06:26 +00001736 ProhibitAttributes(Attrs);
Argyrios Kyrtzidisfbb2bb52012-05-16 23:49:15 +00001737 DeclEnd = Tok.getLocation();
Chris Lattner005fc1b2010-04-05 18:18:31 +00001738 if (RequireSemi) ConsumeToken();
Nico Weber7b837f52016-01-28 19:25:00 +00001739 RecordDecl *AnonRecord = nullptr;
John McCall48871652010-08-21 09:40:31 +00001740 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00001741 DS, AnonRecord);
John McCall28a6aea2009-11-04 02:18:39 +00001742 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00001743 if (AnonRecord) {
1744 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00001745 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00001746 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001747 return Actions.ConvertDeclToDeclGroup(TheDecl);
Chris Lattner0e894622006-08-13 19:58:17 +00001748 }
Chad Rosierc1183952012-06-26 22:30:43 +00001749
Richard Smith2386c8b2013-02-22 09:06:26 +00001750 DS.takeAttributesFrom(Attrs);
Reid Klecknerd61a3112014-12-15 23:16:32 +00001751 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
John McCalld5a36322009-11-03 19:26:08 +00001752}
Mike Stump11289f42009-09-09 15:08:12 +00001753
Richard Smith09f76ee2011-10-19 21:33:05 +00001754/// Returns true if this might be the start of a declarator, or a common typo
1755/// for a declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001756bool Parser::MightBeDeclarator(DeclaratorContext Context) {
Richard Smith09f76ee2011-10-19 21:33:05 +00001757 switch (Tok.getKind()) {
1758 case tok::annot_cxxscope:
1759 case tok::annot_template_id:
1760 case tok::caret:
1761 case tok::code_completion:
1762 case tok::coloncolon:
1763 case tok::ellipsis:
1764 case tok::kw___attribute:
1765 case tok::kw_operator:
1766 case tok::l_paren:
1767 case tok::star:
1768 return true;
1769
1770 case tok::amp:
1771 case tok::ampamp:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001772 return getLangOpts().CPlusPlus;
Richard Smith09f76ee2011-10-19 21:33:05 +00001773
Richard Smithc8a79032012-01-09 22:31:44 +00001774 case tok::l_square: // Might be an attribute on an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001775 return Context == DeclaratorContext::MemberContext &&
1776 getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
Richard Smithc8a79032012-01-09 22:31:44 +00001777
1778 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001779 return Context == DeclaratorContext::MemberContext ||
1780 getLangOpts().CPlusPlus;
Richard Smithc8a79032012-01-09 22:31:44 +00001781
Richard Smith09f76ee2011-10-19 21:33:05 +00001782 case tok::identifier:
1783 switch (NextToken().getKind()) {
1784 case tok::code_completion:
1785 case tok::coloncolon:
1786 case tok::comma:
1787 case tok::equal:
1788 case tok::equalequal: // Might be a typo for '='.
1789 case tok::kw_alignas:
1790 case tok::kw_asm:
1791 case tok::kw___attribute:
1792 case tok::l_brace:
1793 case tok::l_paren:
1794 case tok::l_square:
1795 case tok::less:
1796 case tok::r_brace:
1797 case tok::r_paren:
1798 case tok::r_square:
1799 case tok::semi:
1800 return true;
1801
1802 case tok::colon:
1803 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
Richard Smithc8a79032012-01-09 22:31:44 +00001804 // and in block scope it's probably a label. Inside a class definition,
1805 // this is a bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001806 return Context == DeclaratorContext::MemberContext ||
1807 (getLangOpts().CPlusPlus &&
1808 Context == DeclaratorContext::FileContext);
Richard Smithc8a79032012-01-09 22:31:44 +00001809
1810 case tok::identifier: // Possible virt-specifier.
Richard Smith89645bc2013-01-02 12:01:23 +00001811 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
Richard Smith09f76ee2011-10-19 21:33:05 +00001812
1813 default:
1814 return false;
1815 }
1816
1817 default:
1818 return false;
1819 }
1820}
1821
Richard Smithb8caac82012-04-11 20:59:20 +00001822/// Skip until we reach something which seems like a sensible place to pick
1823/// up parsing after a malformed declaration. This will sometimes stop sooner
1824/// than SkipUntil(tok::r_brace) would, but will never stop later.
1825void Parser::SkipMalformedDecl() {
1826 while (true) {
1827 switch (Tok.getKind()) {
1828 case tok::l_brace:
1829 // Skip until matching }, then stop. We've probably skipped over
1830 // a malformed class or function definition or similar.
1831 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001832 SkipUntil(tok::r_brace);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001833 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
Richard Smithb8caac82012-04-11 20:59:20 +00001834 // This declaration isn't over yet. Keep skipping.
1835 continue;
1836 }
Alp Toker8fbec672013-12-17 23:29:36 +00001837 TryConsumeToken(tok::semi);
Richard Smithb8caac82012-04-11 20:59:20 +00001838 return;
1839
1840 case tok::l_square:
1841 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001842 SkipUntil(tok::r_square);
Richard Smithb8caac82012-04-11 20:59:20 +00001843 continue;
1844
1845 case tok::l_paren:
1846 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001847 SkipUntil(tok::r_paren);
Richard Smithb8caac82012-04-11 20:59:20 +00001848 continue;
1849
1850 case tok::r_brace:
1851 return;
1852
1853 case tok::semi:
1854 ConsumeToken();
1855 return;
1856
1857 case tok::kw_inline:
1858 // 'inline namespace' at the start of a line is almost certainly
Jordan Rose12e730c2012-07-09 16:54:53 +00001859 // a good place to pick back up parsing, except in an Objective-C
1860 // @interface context.
1861 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1862 (!ParsingInObjCContainer || CurParsedObjCImpl))
Richard Smithb8caac82012-04-11 20:59:20 +00001863 return;
1864 break;
1865
1866 case tok::kw_namespace:
1867 // 'namespace' at the start of a line is almost certainly a good
Jordan Rose12e730c2012-07-09 16:54:53 +00001868 // place to pick back up parsing, except in an Objective-C
1869 // @interface context.
1870 if (Tok.isAtStartOfLine() &&
1871 (!ParsingInObjCContainer || CurParsedObjCImpl))
1872 return;
1873 break;
1874
1875 case tok::at:
1876 // @end is very much like } in Objective-C contexts.
1877 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1878 ParsingInObjCContainer)
1879 return;
1880 break;
1881
1882 case tok::minus:
1883 case tok::plus:
1884 // - and + probably start new method declarations in Objective-C contexts.
1885 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
Richard Smithb8caac82012-04-11 20:59:20 +00001886 return;
1887 break;
1888
1889 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001890 case tok::annot_module_begin:
1891 case tok::annot_module_end:
1892 case tok::annot_module_include:
Richard Smithb8caac82012-04-11 20:59:20 +00001893 return;
1894
1895 default:
1896 break;
1897 }
1898
1899 ConsumeAnyToken();
1900 }
1901}
1902
John McCalld5a36322009-11-03 19:26:08 +00001903/// ParseDeclGroup - Having concluded that this is either a function
1904/// definition or a group of object declarations, actually parse the
1905/// result.
John McCall28a6aea2009-11-04 02:18:39 +00001906Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
Faisal Vali421b2d12017-12-29 05:41:00 +00001907 DeclaratorContext Context,
Richard Smith02e85f32011-04-14 22:09:26 +00001908 SourceLocation *DeclEnd,
1909 ForRangeInit *FRI) {
John McCalld5a36322009-11-03 19:26:08 +00001910 // Parse the first declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001911 ParsingDeclarator D(*this, DS, Context);
John McCalld5a36322009-11-03 19:26:08 +00001912 ParseDeclarator(D);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001913
John McCalld5a36322009-11-03 19:26:08 +00001914 // Bail out if the first declarator didn't seem well-formed.
1915 if (!D.hasName() && !D.mayOmitIdentifier()) {
Richard Smithb8caac82012-04-11 20:59:20 +00001916 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00001917 return nullptr;
Chris Lattnerefb0f112009-03-29 17:18:04 +00001918 }
Mike Stump11289f42009-09-09 15:08:12 +00001919
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001920 // Save late-parsed attributes for now; they need to be parsed in the
1921 // appropriate function scope after the function Decl has been constructed.
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001922 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1923 LateParsedAttrList LateParsedAttrs(true);
Richard Smith99c464c2014-11-10 21:10:32 +00001924 if (D.isFunctionDeclarator()) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001925 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1926
Richard Smith99c464c2014-11-10 21:10:32 +00001927 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1928 // attribute. If we find the keyword here, tell the user to put it
1929 // at the start instead.
1930 if (Tok.is(tok::kw__Noreturn)) {
1931 SourceLocation Loc = ConsumeToken();
1932 const char *PrevSpec;
1933 unsigned DiagID;
1934
1935 // We can offer a fixit if it's valid to mark this function as _Noreturn
1936 // and we don't have any other declarators in this declaration.
1937 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1938 MaybeParseGNUAttributes(D, &LateParsedAttrs);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001939 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
Richard Smith99c464c2014-11-10 21:10:32 +00001940
1941 Diag(Loc, diag::err_c11_noreturn_misplaced)
1942 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001943 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
Richard Smith99c464c2014-11-10 21:10:32 +00001944 : FixItHint());
1945 }
1946 }
1947
Chris Lattnerdbb1e932010-07-11 22:24:20 +00001948 // Check to see if we have a function *definition* which must have a body.
Douglas Gregor012efe22013-04-16 16:01:32 +00001949 if (D.isFunctionDeclarator() &&
Chris Lattnerdbb1e932010-07-11 22:24:20 +00001950 // Look at the next token to make sure that this isn't a function
1951 // declaration. We have to check this because __attribute__ might be the
1952 // start of a function definition in GCC-extended K&R C.
Fariborz Jahanian712bb812012-08-10 15:54:40 +00001953 !isDeclarationAfterDeclarator()) {
Chad Rosierc1183952012-06-26 22:30:43 +00001954
Reid Klecknerd61a3112014-12-15 23:16:32 +00001955 // Function definitions are only allowed at file scope and in C++ classes.
1956 // The C++ inline method definition case is handled elsewhere, so we only
1957 // need to handle the file scope definition case.
Faisal Vali421b2d12017-12-29 05:41:00 +00001958 if (Context == DeclaratorContext::FileContext) {
Douglas Gregor012efe22013-04-16 16:01:32 +00001959 if (isStartOfFunctionDefinition(D)) {
1960 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1961 Diag(Tok, diag::err_function_declared_typedef);
John McCalld5a36322009-11-03 19:26:08 +00001962
Douglas Gregor012efe22013-04-16 16:01:32 +00001963 // Recover by treating the 'typedef' as spurious.
1964 DS.ClearStorageClassSpecs();
1965 }
1966
1967 Decl *TheDecl =
1968 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1969 return Actions.ConvertDeclToDeclGroup(TheDecl);
John McCalld5a36322009-11-03 19:26:08 +00001970 }
1971
Douglas Gregor012efe22013-04-16 16:01:32 +00001972 if (isDeclarationSpecifier()) {
Nico Weber6b05f382015-02-18 04:53:03 +00001973 // If there is an invalid declaration specifier right after the
1974 // function prototype, then we must be in a missing semicolon case
1975 // where this isn't actually a body. Just fall through into the code
1976 // that handles it as a prototype, and let the top-level code handle
1977 // the erroneous declspec where it would otherwise expect a comma or
1978 // semicolon.
Douglas Gregor012efe22013-04-16 16:01:32 +00001979 } else {
1980 Diag(Tok, diag::err_expected_fn_body);
1981 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00001982 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00001983 }
John McCalld5a36322009-11-03 19:26:08 +00001984 } else {
Douglas Gregor012efe22013-04-16 16:01:32 +00001985 if (Tok.is(tok::l_brace)) {
1986 Diag(Tok, diag::err_function_definition_not_allowed);
Serge Pavlov1de51512013-12-09 05:25:47 +00001987 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00001988 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00001989 }
John McCalld5a36322009-11-03 19:26:08 +00001990 }
1991 }
1992
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001993 if (ParseAsmAttributesAfterDeclarator(D))
David Blaikie0403cb12016-01-15 23:43:25 +00001994 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00001995
1996 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1997 // must parse and analyze the for-range-initializer before the declaration is
1998 // analyzed.
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001999 //
2000 // Handle the Objective-C for-in loop variable similarly, although we
2001 // don't need to parse the container in advance.
2002 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2003 bool IsForRangeLoop = false;
Alp Toker8fbec672013-12-17 23:29:36 +00002004 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002005 IsForRangeLoop = true;
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002006 if (Tok.is(tok::l_brace))
2007 FRI->RangeExpr = ParseBraceInitializer();
2008 else
2009 FRI->RangeExpr = ParseExpression();
2010 }
2011
Richard Smith02e85f32011-04-14 22:09:26 +00002012 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
George Karpenkovec38cf72018-03-29 00:56:24 +00002013 if (IsForRangeLoop) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002014 Actions.ActOnCXXForRangeDecl(ThisDecl);
George Karpenkovec38cf72018-03-29 00:56:24 +00002015 } else {
2016 // Obj-C for loop
2017 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2018 VD->setObjCForDecl(true);
2019 }
Richard Smith02e85f32011-04-14 22:09:26 +00002020 Actions.FinalizeDeclaration(ThisDecl);
John McCallcf6e0c82012-01-27 01:29:43 +00002021 D.complete(ThisDecl);
Rafael Espindolaab417692013-07-09 12:05:01 +00002022 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
Richard Smith02e85f32011-04-14 22:09:26 +00002023 }
2024
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002025 SmallVector<Decl *, 8> DeclsInGroup;
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002026 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2027 D, ParsedTemplateInfo(), FRI);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002028 if (LateParsedAttrs.size() > 0)
2029 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
John McCall28a6aea2009-11-04 02:18:39 +00002030 D.complete(FirstDecl);
John McCall48871652010-08-21 09:40:31 +00002031 if (FirstDecl)
John McCalld5a36322009-11-03 19:26:08 +00002032 DeclsInGroup.push_back(FirstDecl);
2033
Faisal Vali421b2d12017-12-29 05:41:00 +00002034 bool ExpectSemi = Context != DeclaratorContext::ForContext;
Fangrui Song6907ce22018-07-30 19:24:48 +00002035
John McCalld5a36322009-11-03 19:26:08 +00002036 // If we don't have a comma, it is either the end of the list (a ';') or an
2037 // error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00002038 SourceLocation CommaLoc;
2039 while (TryConsumeToken(tok::comma, CommaLoc)) {
Richard Smith09f76ee2011-10-19 21:33:05 +00002040 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2041 // This comma was followed by a line-break and something which can't be
2042 // the start of a declarator. The comma was probably a typo for a
2043 // semicolon.
2044 Diag(CommaLoc, diag::err_expected_semi_declaration)
2045 << FixItHint::CreateReplacement(CommaLoc, ";");
2046 ExpectSemi = false;
2047 break;
2048 }
John McCalld5a36322009-11-03 19:26:08 +00002049
2050 // Parse the next declarator.
2051 D.clear();
Richard Smith8d06f422012-01-12 23:53:29 +00002052 D.setCommaLoc(CommaLoc);
John McCalld5a36322009-11-03 19:26:08 +00002053
2054 // Accept attributes in an init-declarator. In the first declarator in a
2055 // declaration, these would be part of the declspec. In subsequent
2056 // declarators, they become part of the declarator itself, so that they
2057 // don't apply to declarators after *this* one. Examples:
2058 // short __attribute__((common)) var; -> declspec
2059 // short var __attribute__((common)); -> declarator
2060 // short x, __attribute__((common)) var; -> declarator
John McCall53fa7142010-12-24 02:08:15 +00002061 MaybeParseGNUAttributes(D);
John McCalld5a36322009-11-03 19:26:08 +00002062
Nico Rieckeaaae272014-12-04 23:31:08 +00002063 // MSVC parses but ignores qualifiers after the comma as an extension.
2064 if (getLangOpts().MicrosoftExt)
2065 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2066
John McCalld5a36322009-11-03 19:26:08 +00002067 ParseDeclarator(D);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002068 if (!D.isInvalidType()) {
2069 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2070 D.complete(ThisDecl);
2071 if (ThisDecl)
Chad Rosierc1183952012-06-26 22:30:43 +00002072 DeclsInGroup.push_back(ThisDecl);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002073 }
John McCalld5a36322009-11-03 19:26:08 +00002074 }
2075
2076 if (DeclEnd)
2077 *DeclEnd = Tok.getLocation();
2078
Richard Smith09f76ee2011-10-19 21:33:05 +00002079 if (ExpectSemi &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002080 ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
Chris Lattner02f1b612012-04-28 16:12:17 +00002081 ? diag::err_invalid_token_after_toplevel_declarator
2082 : diag::err_expected_semi_declaration)) {
Chris Lattner13901342010-07-11 22:42:07 +00002083 // Okay, there was no semicolon and one was expected. If we see a
2084 // declaration specifier, just assume it was missing and continue parsing.
2085 // Otherwise things are very confused and we skip to recover.
2086 if (!isDeclarationSpecifier()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002087 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Alp Toker8fbec672013-12-17 23:29:36 +00002088 TryConsumeToken(tok::semi);
Chris Lattner13901342010-07-11 22:42:07 +00002089 }
John McCalld5a36322009-11-03 19:26:08 +00002090 }
2091
Rafael Espindolaab417692013-07-09 12:05:01 +00002092 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner53361ac2006-08-10 05:19:57 +00002093}
2094
Richard Smith02e85f32011-04-14 22:09:26 +00002095/// Parse an optional simple-asm-expr and attributes, and attach them to a
2096/// declarator. Returns true on an error.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002097bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
Richard Smith02e85f32011-04-14 22:09:26 +00002098 // If a simple-asm-expr is present, parse it.
2099 if (Tok.is(tok::kw_asm)) {
2100 SourceLocation Loc;
2101 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2102 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002103 SkipUntil(tok::semi, StopBeforeMatch);
Richard Smith02e85f32011-04-14 22:09:26 +00002104 return true;
2105 }
2106
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002107 D.setAsmLabel(AsmLabel.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002108 D.SetRangeEnd(Loc);
2109 }
2110
2111 MaybeParseGNUAttributes(D);
2112 return false;
2113}
2114
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002115/// Parse 'declaration' after parsing 'declaration-specifiers
Douglas Gregor23996282009-05-12 21:31:51 +00002116/// declarator'. This method parses the remainder of the declaration
2117/// (including any attributes or initializer, among other things) and
2118/// finalizes the declaration.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002119///
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002120/// init-declarator: [C99 6.7]
2121/// declarator
2122/// declarator '=' initializer
Chris Lattner6d7e6342006-08-15 03:41:14 +00002123/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2124/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002125/// [C++] declarator initializer[opt]
2126///
2127/// [C++] initializer:
2128/// [C++] '=' initializer-clause
2129/// [C++] '(' expression-list ')'
Sebastian Redlf769df52009-03-24 22:27:57 +00002130/// [C++0x] '=' 'default' [TODO]
2131/// [C++0x] '=' 'delete'
Sebastian Redl3da34892011-06-05 12:23:16 +00002132/// [C++0x] braced-init-list
Sebastian Redlf769df52009-03-24 22:27:57 +00002133///
2134/// According to the standard grammar, =default and =delete are function
2135/// definitions, but that definitely doesn't fit with the parser here.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002136///
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002137Decl *Parser::ParseDeclarationAfterDeclarator(
2138 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002139 if (ParseAsmAttributesAfterDeclarator(D))
Craig Topper161e4db2014-05-21 06:02:52 +00002140 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002141
Richard Smith02e85f32011-04-14 22:09:26 +00002142 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2143}
Mike Stump11289f42009-09-09 15:08:12 +00002144
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002145Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2146 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
Richard Smithc95d2c52017-09-22 04:25:05 +00002147 // RAII type used to track whether we're inside an initializer.
2148 struct InitializerScopeRAII {
2149 Parser &P;
2150 Declarator &D;
2151 Decl *ThisDecl;
2152
2153 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2154 : P(P), D(D), ThisDecl(ThisDecl) {
2155 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2156 Scope *S = nullptr;
2157 if (D.getCXXScopeSpec().isSet()) {
2158 P.EnterScope(0);
2159 S = P.getCurScope();
2160 }
2161 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2162 }
2163 }
2164 ~InitializerScopeRAII() { pop(); }
2165 void pop() {
2166 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2167 Scope *S = nullptr;
2168 if (D.getCXXScopeSpec().isSet())
2169 S = P.getCurScope();
2170 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2171 if (S)
2172 P.ExitScope();
2173 }
2174 ThisDecl = nullptr;
2175 }
2176 };
2177
Douglas Gregor23996282009-05-12 21:31:51 +00002178 // Inform the current actions module that we just parsed this declarator.
Craig Topper161e4db2014-05-21 06:02:52 +00002179 Decl *ThisDecl = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00002180 switch (TemplateInfo.Kind) {
2181 case ParsedTemplateInfo::NonTemplate:
Douglas Gregor0be31a22010-07-02 17:43:08 +00002182 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
Douglas Gregor450f00842009-09-25 18:43:00 +00002183 break;
Chad Rosierc1183952012-06-26 22:30:43 +00002184
Douglas Gregor450f00842009-09-25 18:43:00 +00002185 case ParsedTemplateInfo::Template:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002186 case ParsedTemplateInfo::ExplicitSpecialization: {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002187 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002188 *TemplateInfo.TemplateParams,
Douglas Gregor450f00842009-09-25 18:43:00 +00002189 D);
Larisse Voufo833b05a2013-08-06 07:33:00 +00002190 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002191 // Re-direct this decl to refer to the templated decl so that we can
2192 // initialize it.
2193 ThisDecl = VT->getTemplatedDecl();
2194 break;
2195 }
2196 case ParsedTemplateInfo::ExplicitInstantiation: {
2197 if (Tok.is(tok::semi)) {
2198 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2199 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2200 if (ThisRes.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002201 SkipUntil(tok::semi, StopBeforeMatch);
Craig Topper161e4db2014-05-21 06:02:52 +00002202 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002203 }
2204 ThisDecl = ThisRes.get();
2205 } else {
2206 // FIXME: This check should be for a variable template instantiation only.
2207
2208 // Check that this is a valid instantiation
Faisal Vali2ab8c152017-12-30 04:15:27 +00002209 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002210 // If the declarator-id is not a template-id, issue a diagnostic and
2211 // recover by ignoring the 'template' keyword.
2212 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2213 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2214 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2215 } else {
2216 SourceLocation LAngleLoc =
2217 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2218 Diag(D.getIdentifierLoc(),
2219 diag::err_explicit_instantiation_with_definition)
2220 << SourceRange(TemplateInfo.TemplateLoc)
2221 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2222
2223 // Recover as if it were an explicit specialization.
2224 TemplateParameterLists FakedParamLists;
2225 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00002226 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00002227 LAngleLoc, nullptr));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002228
2229 ThisDecl =
2230 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2231 }
2232 }
Douglas Gregor450f00842009-09-25 18:43:00 +00002233 break;
2234 }
2235 }
Mike Stump11289f42009-09-09 15:08:12 +00002236
Douglas Gregor23996282009-05-12 21:31:51 +00002237 // Parse declarator '=' initializer.
Richard Trieuc64d3232012-01-18 22:54:52 +00002238 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Trieu4972a6d2012-01-19 22:01:51 +00002239 if (isTokenEqualOrEqualTypo()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002240 SourceLocation EqualLoc = ConsumeToken();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002241
Anders Carlsson991285e2010-09-24 21:25:25 +00002242 if (Tok.is(tok::kw_delete)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002243 if (D.isFunctionDeclarator())
2244 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2245 << 1 /* delete */;
2246 else
2247 Diag(ConsumeToken(), diag::err_deleted_non_function);
Alexis Hunt5dafebc2011-05-06 01:42:00 +00002248 } else if (Tok.is(tok::kw_default)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002249 if (D.isFunctionDeclarator())
Sebastian Redl46afb552012-02-11 23:51:21 +00002250 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2251 << 0 /* default */;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002252 else
2253 Diag(ConsumeToken(), diag::err_default_special_members);
Douglas Gregor23996282009-05-12 21:31:51 +00002254 } else {
Richard Smithc95d2c52017-09-22 04:25:05 +00002255 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002256
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002257 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002258 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
Peter Collingbourne6b4fdc22012-07-27 12:56:09 +00002259 Actions.FinalizeDeclaration(ThisDecl);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002260 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +00002261 return nullptr;
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002262 }
Chad Rosierc1183952012-06-26 22:30:43 +00002263
John McCalldadc5752010-08-24 06:29:42 +00002264 ExprResult Init(ParseInitializer());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002265
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002266 // If this is the only decl in (possibly) range based for statement,
2267 // our best guess is that the user meant ':' instead of '='.
2268 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2269 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2270 << FixItHint::CreateReplacement(EqualLoc, ":");
2271 // We are trying to stop parser from looking for ';' in this for
2272 // statement, therefore preventing spurious errors to be issued.
2273 FRI->ColonLoc = EqualLoc;
2274 Init = ExprError();
2275 FRI->RangeExpr = Init;
2276 }
2277
Richard Smithc95d2c52017-09-22 04:25:05 +00002278 InitScope.pop();
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002279
Douglas Gregor23996282009-05-12 21:31:51 +00002280 if (Init.isInvalid()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002281 SmallVector<tok::TokenKind, 2> StopTokens;
2282 StopTokens.push_back(tok::comma);
Faisal Vali421b2d12017-12-29 05:41:00 +00002283 if (D.getContext() == DeclaratorContext::ForContext ||
2284 D.getContext() == DeclaratorContext::InitStmtContext)
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002285 StopTokens.push_back(tok::r_paren);
2286 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
Douglas Gregor604c3022010-03-01 18:27:54 +00002287 Actions.ActOnInitializerError(ThisDecl);
2288 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002289 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002290 /*DirectInit=*/false);
Douglas Gregor23996282009-05-12 21:31:51 +00002291 }
2292 } else if (Tok.is(tok::l_paren)) {
2293 // Parse C++ direct initializer: '(' expression-list ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002294 BalancedDelimiterTracker T(*this, tok::l_paren);
2295 T.consumeOpen();
2296
Benjamin Kramerf0623432012-08-23 22:51:59 +00002297 ExprVector Exprs;
Douglas Gregor23996282009-05-12 21:31:51 +00002298 CommaLocsTy CommaLocs;
2299
Richard Smithc95d2c52017-09-22 04:25:05 +00002300 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Douglas Gregor613bf102009-12-22 17:47:17 +00002301
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002302 llvm::function_ref<void()> ExprListCompleter;
2303 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2304 auto ConstructorCompleter = [&, ThisVarDecl] {
2305 Actions.CodeCompleteConstructor(
2306 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2307 ThisDecl->getLocation(), Exprs);
2308 };
2309 if (ThisVarDecl) {
2310 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2311 // VarDecl. This is an error and it is reported in a call to
2312 // Actions.ActOnInitializerError(). However, we call
2313 // CodeCompleteConstructor only on VarDecls, falling back to default
2314 // completer in other cases.
2315 ExprListCompleter = ConstructorCompleter;
2316 }
2317
2318 if (ParseExpressionList(Exprs, CommaLocs, ExprListCompleter)) {
David Blaikieeae04112012-10-10 23:15:05 +00002319 Actions.ActOnInitializerError(ThisDecl);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002320 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor23996282009-05-12 21:31:51 +00002321 } else {
2322 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002323 T.consumeClose();
Douglas Gregor23996282009-05-12 21:31:51 +00002324
2325 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2326 "Unexpected number of commas!");
Douglas Gregor613bf102009-12-22 17:47:17 +00002327
Richard Smithc95d2c52017-09-22 04:25:05 +00002328 InitScope.pop();
Douglas Gregor613bf102009-12-22 17:47:17 +00002329
Sebastian Redla9351792012-02-11 23:51:47 +00002330 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2331 T.getCloseLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002332 Exprs);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002333 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002334 /*DirectInit=*/true);
Douglas Gregor23996282009-05-12 21:31:51 +00002335 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002336 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
Fariborz Jahanian8be1ecd2012-07-03 23:22:13 +00002337 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
Sebastian Redl3da34892011-06-05 12:23:16 +00002338 // Parse C++0x braced-init-list.
Richard Smith5d164bc2011-10-15 05:09:34 +00002339 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2340
Richard Smithc95d2c52017-09-22 04:25:05 +00002341 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Sebastian Redl3da34892011-06-05 12:23:16 +00002342
2343 ExprResult Init(ParseBraceInitializer());
2344
Richard Smithc95d2c52017-09-22 04:25:05 +00002345 InitScope.pop();
Sebastian Redl3da34892011-06-05 12:23:16 +00002346
2347 if (Init.isInvalid()) {
2348 Actions.ActOnInitializerError(ThisDecl);
2349 } else
Richard Smith3beb7c62017-01-12 02:27:38 +00002350 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
Sebastian Redl3da34892011-06-05 12:23:16 +00002351
Douglas Gregor23996282009-05-12 21:31:51 +00002352 } else {
Richard Smith3beb7c62017-01-12 02:27:38 +00002353 Actions.ActOnUninitializedDecl(ThisDecl);
Douglas Gregor23996282009-05-12 21:31:51 +00002354 }
2355
Richard Smithb2bc2e62011-02-21 20:05:19 +00002356 Actions.FinalizeDeclaration(ThisDecl);
2357
Douglas Gregor23996282009-05-12 21:31:51 +00002358 return ThisDecl;
2359}
2360
Chris Lattner1890ac82006-08-13 01:16:23 +00002361/// ParseSpecifierQualifierList
2362/// specifier-qualifier-list:
2363/// type-specifier specifier-qualifier-list[opt]
2364/// type-qualifier specifier-qualifier-list[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002365/// [GNU] attributes specifier-qualifier-list[opt]
Chris Lattner1890ac82006-08-13 01:16:23 +00002366///
Richard Smithc5b05522012-03-12 07:56:15 +00002367void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2368 DeclSpecContext DSC) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002369 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2370 /// parse declaration-specifiers and complain about extra stuff.
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002371 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
Faisal Valia534f072018-04-26 00:42:40 +00002372 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
Mike Stump11289f42009-09-09 15:08:12 +00002373
Chris Lattner1890ac82006-08-13 01:16:23 +00002374 // Validate declspec for type-name.
2375 unsigned Specs = DS.getParsedSpecifiers();
Richard Smith649c7b062014-01-08 00:56:48 +00002376 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
Richard Smithc5b05522012-03-12 07:56:15 +00002377 Diag(Tok, diag::err_expected_type);
2378 DS.SetTypeSpecError();
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00002379 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002380 Diag(Tok, diag::err_typename_requires_specqual);
Richard Smithc5b05522012-03-12 07:56:15 +00002381 if (!DS.hasTypeSpecifier())
2382 DS.SetTypeSpecError();
2383 }
Mike Stump11289f42009-09-09 15:08:12 +00002384
Chris Lattner1b22eed2006-11-28 05:12:07 +00002385 // Issue diagnostic and remove storage class if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002386 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
Chris Lattner1b22eed2006-11-28 05:12:07 +00002387 if (DS.getStorageClassSpecLoc().isValid())
2388 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2389 else
Richard Smithb4a9e862013-04-12 22:46:28 +00002390 Diag(DS.getThreadStorageClassSpecLoc(),
2391 diag::err_typename_invalid_storageclass);
Chris Lattnera925dc62006-11-28 04:33:46 +00002392 DS.ClearStorageClassSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002393 }
Mike Stump11289f42009-09-09 15:08:12 +00002394
Craig Topper3f13d4d22015-11-14 18:15:55 +00002395 // Issue diagnostic and remove function specifier if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002396 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
Douglas Gregor61956c42008-10-31 09:07:45 +00002397 if (DS.isInlineSpecified())
2398 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2399 if (DS.isVirtualSpecified())
2400 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2401 if (DS.isExplicitSpecified())
2402 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
Chris Lattnera925dc62006-11-28 04:33:46 +00002403 DS.ClearFunctionSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002404 }
Richard Smithc5b05522012-03-12 07:56:15 +00002405
2406 // Issue diagnostic and remove constexpr specfier if present.
Faisal Vali7db85c52017-12-31 00:06:40 +00002407 if (DS.isConstexprSpecified() && DSC != DeclSpecContext::DSC_condition) {
Richard Smithc5b05522012-03-12 07:56:15 +00002408 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2409 DS.ClearConstexprSpec();
2410 }
Chris Lattner1890ac82006-08-13 01:16:23 +00002411}
Chris Lattner53361ac2006-08-10 05:19:57 +00002412
Chris Lattner6cc055a2009-04-12 20:42:31 +00002413/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2414/// specified token is valid after the identifier in a declarator which
2415/// immediately follows the declspec. For example, these things are valid:
2416///
2417/// int x [ 4]; // direct-declarator
2418/// int x ( int y); // direct-declarator
2419/// int(int x ) // direct-declarator
2420/// int x ; // simple-declaration
2421/// int x = 17; // init-declarator-list
2422/// int x , y; // init-declarator-list
2423/// int x __asm__ ("foo"); // init-declarator-list
Chris Lattnera723ba92009-04-14 21:16:09 +00002424/// int x : 4; // struct-declarator
Chris Lattner2b988c12009-04-12 22:29:43 +00002425/// int x { 5}; // C++'0x unified initializers
Chris Lattner6cc055a2009-04-12 20:42:31 +00002426///
2427/// This is not, because 'x' does not immediately follow the declspec (though
2428/// ')' happens to be valid anyway).
2429/// int (x)
2430///
2431static bool isValidAfterIdentifierInDeclarator(const Token &T) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002432 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2433 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2434 tok::colon);
Chris Lattner6cc055a2009-04-12 20:42:31 +00002435}
2436
Chris Lattner20a0c612009-04-14 21:34:55 +00002437/// ParseImplicitInt - This method is called when we have an non-typename
2438/// identifier in a declspec (which normally terminates the decl spec) when
2439/// the declspec has no type specifier. In this case, the declspec is either
2440/// malformed or is "implicit int" (in K&R and C89).
2441///
2442/// This method handles diagnosing this prettily and returns false if the
2443/// declspec is done being processed. If it recovers and thinks there may be
2444/// other pieces of declspec after it, it returns true.
2445///
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002446bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002447 const ParsedTemplateInfo &TemplateInfo,
Richard Smitha0a5d502014-05-08 22:32:00 +00002448 AccessSpecifier AS, DeclSpecContext DSC,
Michael Han9407e502012-11-26 22:54:45 +00002449 ParsedAttributesWithRange &Attrs) {
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002450 assert(Tok.is(tok::identifier) && "should have identifier");
Mike Stump11289f42009-09-09 15:08:12 +00002451
Chris Lattner20a0c612009-04-14 21:34:55 +00002452 SourceLocation Loc = Tok.getLocation();
2453 // If we see an identifier that is not a type name, we normally would
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002454 // parse it as the identifier being declared. However, when a typename
Chris Lattner20a0c612009-04-14 21:34:55 +00002455 // is typo'd or the definition is not included, this will incorrectly
2456 // parse the typename as the identifier name and fall over misparsing
2457 // later parts of the diagnostic.
2458 //
2459 // As such, we try to do some look-ahead in cases where this would
2460 // otherwise be an "implicit-int" case to see if this is invalid. For
2461 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2462 // an identifier with implicit int, we'd get a parse error because the
2463 // next token is obviously invalid for a type. Parse these as a case
2464 // with an invalid type specifier.
2465 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
Mike Stump11289f42009-09-09 15:08:12 +00002466
Chris Lattner20a0c612009-04-14 21:34:55 +00002467 // Since we know that this either implicit int (which is rare) or an
Richard Smitha952ebb2012-05-15 21:01:51 +00002468 // error, do lookahead to try to do better recovery. This never applies
2469 // within a type specifier. Outside of C++, we allow this even if the
2470 // language doesn't "officially" support implicit int -- we support
Richard Smith3b870382013-04-30 22:43:51 +00002471 // implicit int as an extension in C99 and C11.
Richard Smith649c7b062014-01-08 00:56:48 +00002472 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
Richard Smithc5b05522012-03-12 07:56:15 +00002473 isValidAfterIdentifierInDeclarator(NextToken())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002474 // If this token is valid for implicit int, e.g. "static x = 4", then
2475 // we just avoid eating the identifier, so it will be parsed as the
2476 // identifier in the declarator.
2477 return false;
2478 }
Mike Stump11289f42009-09-09 15:08:12 +00002479
Richard Smitha952ebb2012-05-15 21:01:51 +00002480 if (getLangOpts().CPlusPlus &&
2481 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2482 // Don't require a type specifier if we have the 'auto' storage class
2483 // specifier in C++98 -- we'll promote it to a type specifier.
Richard Smithfb8b7b92013-10-15 00:00:26 +00002484 if (SS)
2485 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
Richard Smitha952ebb2012-05-15 21:01:51 +00002486 return false;
2487 }
2488
Reid Kleckner9a96e422016-05-24 21:23:54 +00002489 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2490 getLangOpts().MSVCCompat) {
2491 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2492 // Give Sema a chance to recover if we are in a template with dependent base
2493 // classes.
2494 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2495 *Tok.getIdentifierInfo(), Tok.getLocation(),
Faisal Vali7db85c52017-12-31 00:06:40 +00002496 DSC == DeclSpecContext::DSC_template_type_arg)) {
Reid Kleckner9a96e422016-05-24 21:23:54 +00002497 const char *PrevSpec;
2498 unsigned DiagID;
2499 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2500 Actions.getASTContext().getPrintingPolicy());
2501 DS.SetRangeEnd(Tok.getLocation());
2502 ConsumeToken();
2503 return false;
2504 }
2505 }
2506
Chris Lattner20a0c612009-04-14 21:34:55 +00002507 // Otherwise, if we don't consume this token, we are going to emit an
2508 // error anyway. Try to recover from various common problems. Check
2509 // to see if this was a reference to a tag name without a tag specified.
2510 // This is a common problem in C (saying 'foo' instead of 'struct foo').
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002511 //
2512 // C++ doesn't need this, and isTagName doesn't take SS.
Craig Topper161e4db2014-05-21 06:02:52 +00002513 if (SS == nullptr) {
2514 const char *TagName = nullptr, *FixitTagName = nullptr;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002515 tok::TokenKind TagKind = tok::unknown;
Mike Stump11289f42009-09-09 15:08:12 +00002516
Douglas Gregor0be31a22010-07-02 17:43:08 +00002517 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002518 default: break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002519 case DeclSpec::TST_enum:
2520 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2521 case DeclSpec::TST_union:
2522 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2523 case DeclSpec::TST_struct:
2524 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
Joao Matosdc86f942012-08-31 18:45:21 +00002525 case DeclSpec::TST_interface:
2526 TagName="__interface"; FixitTagName = "__interface ";
2527 TagKind=tok::kw___interface;break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002528 case DeclSpec::TST_class:
2529 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
Chris Lattner20a0c612009-04-14 21:34:55 +00002530 }
Mike Stump11289f42009-09-09 15:08:12 +00002531
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002532 if (TagName) {
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002533 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2534 LookupResult R(Actions, TokenName, SourceLocation(),
2535 Sema::LookupOrdinaryName);
2536
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002537 Diag(Loc, diag::err_use_of_tag_name_without_tag)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002538 << TokenName << TagName << getLangOpts().CPlusPlus
2539 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2540
2541 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2542 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2543 I != IEnd; ++I)
Kaelyn Uhrain3fe3f852012-04-27 18:26:49 +00002544 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002545 << TokenName << TagName;
2546 }
Mike Stump11289f42009-09-09 15:08:12 +00002547
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002548 // Parse this as a tag as if the missing tag were present.
2549 if (TagKind == tok::kw_enum)
Faisal Vali7db85c52017-12-31 00:06:40 +00002550 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2551 DeclSpecContext::DSC_normal);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002552 else
Richard Smithc5b05522012-03-12 07:56:15 +00002553 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
Faisal Vali7db85c52017-12-31 00:06:40 +00002554 /*EnteringContext*/ false,
2555 DeclSpecContext::DSC_normal, Attrs);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002556 return true;
2557 }
Chris Lattner20a0c612009-04-14 21:34:55 +00002558 }
Mike Stump11289f42009-09-09 15:08:12 +00002559
Richard Smithfe904f02012-05-15 21:29:55 +00002560 // Determine whether this identifier could plausibly be the name of something
Richard Smithedd124e2012-05-15 21:42:17 +00002561 // being declared (with a missing type).
Faisal Vali7db85c52017-12-31 00:06:40 +00002562 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2563 DSC == DeclSpecContext::DSC_class)) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002564 // Look ahead to the next token to try to figure out what this declaration
2565 // was supposed to be.
2566 switch (NextToken().getKind()) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002567 case tok::l_paren: {
2568 // static x(4); // 'x' is not a type
2569 // x(int n); // 'x' is not a type
2570 // x (*p)[]; // 'x' is a type
2571 //
Richard Smitha0a5d502014-05-08 22:32:00 +00002572 // Since we're in an error case, we can afford to perform a tentative
2573 // parse to determine which case we're in.
Richard Smitha952ebb2012-05-15 21:01:51 +00002574 TentativeParsingAction PA(*this);
2575 ConsumeToken();
2576 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2577 PA.Revert();
Richard Smithfb8b7b92013-10-15 00:00:26 +00002578
Richard Smithee390432014-05-16 01:56:53 +00002579 if (TPR != TPResult::False) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002580 // The identifier is followed by a parenthesized declarator.
2581 // It's supposed to be a type.
2582 break;
2583 }
2584
2585 // If we're in a context where we could be declaring a constructor,
2586 // check whether this is a constructor declaration with a bogus name.
Faisal Vali7db85c52017-12-31 00:06:40 +00002587 if (DSC == DeclSpecContext::DSC_class ||
2588 (DSC == DeclSpecContext::DSC_top_level && SS)) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002589 IdentifierInfo *II = Tok.getIdentifierInfo();
2590 if (Actions.isCurrentClassNameTypo(II, SS)) {
2591 Diag(Loc, diag::err_constructor_bad_name)
2592 << Tok.getIdentifierInfo() << II
2593 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2594 Tok.setIdentifierInfo(II);
2595 }
2596 }
2597 // Fall through.
Galina Kistanova77674252017-06-01 21:15:34 +00002598 LLVM_FALLTHROUGH;
Richard Smitha952ebb2012-05-15 21:01:51 +00002599 }
Richard Smithfb8b7b92013-10-15 00:00:26 +00002600 case tok::comma:
2601 case tok::equal:
2602 case tok::kw_asm:
2603 case tok::l_brace:
2604 case tok::l_square:
2605 case tok::semi:
2606 // This looks like a variable or function declaration. The type is
2607 // probably missing. We're done parsing decl-specifiers.
2608 if (SS)
2609 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2610 return false;
Richard Smitha952ebb2012-05-15 21:01:51 +00002611
2612 default:
2613 // This is probably supposed to be a type. This includes cases like:
2614 // int f(itn);
2615 // struct S { unsinged : 4; };
2616 break;
2617 }
2618 }
2619
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002620 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2621 // and attempt to recover.
John McCallba7bf592010-08-24 05:47:05 +00002622 ParsedType T;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +00002623 IdentifierInfo *II = Tok.getIdentifierInfo();
Richard Smith52f8d192017-05-10 21:32:16 +00002624 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002625 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
Richard Smith52f8d192017-05-10 21:32:16 +00002626 IsTemplateName);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002627 if (T) {
2628 // The action has suggested that the type T could be used. Set that as
2629 // the type in the declaration specifiers, consume the would-be type
2630 // name token, and we're done.
2631 const char *PrevSpec;
2632 unsigned DiagID;
2633 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2634 Actions.getASTContext().getPrintingPolicy());
2635 DS.SetRangeEnd(Tok.getLocation());
2636 ConsumeToken();
2637 // There may be other declaration specifiers after this.
2638 return true;
2639 } else if (II != Tok.getIdentifierInfo()) {
2640 // If no type was suggested, the correction is to a keyword
2641 Tok.setKind(II->getTokenID());
2642 // There may be other declaration specifiers after this.
2643 return true;
Douglas Gregor15e56022009-10-13 23:27:22 +00002644 }
Mike Stump11289f42009-09-09 15:08:12 +00002645
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002646 // Otherwise, the action had no suggestion for us. Mark this as an error.
Richard Smithc5b05522012-03-12 07:56:15 +00002647 DS.SetTypeSpecError();
Chris Lattner20a0c612009-04-14 21:34:55 +00002648 DS.SetRangeEnd(Tok.getLocation());
2649 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002650
Richard Smith52f8d192017-05-10 21:32:16 +00002651 // Eat any following template arguments.
2652 if (IsTemplateName) {
2653 SourceLocation LAngle, RAngle;
2654 TemplateArgList Args;
2655 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2656 }
2657
Chris Lattner20a0c612009-04-14 21:34:55 +00002658 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2659 // avoid rippling error messages on subsequent uses of the same type,
2660 // could be useful if #include was forgotten.
2661 return false;
2662}
2663
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002664/// Determine the declaration specifier context from the declarator
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002665/// context.
2666///
2667/// \param Context the declarator context, which is one of the
Faisal Vali421b2d12017-12-29 05:41:00 +00002668/// DeclaratorContext enumerator values.
Chad Rosierc1183952012-06-26 22:30:43 +00002669Parser::DeclSpecContext
Faisal Vali421b2d12017-12-29 05:41:00 +00002670Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2671 if (Context == DeclaratorContext::MemberContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002672 return DeclSpecContext::DSC_class;
Faisal Vali421b2d12017-12-29 05:41:00 +00002673 if (Context == DeclaratorContext::FileContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002674 return DeclSpecContext::DSC_top_level;
Faisal Vali421b2d12017-12-29 05:41:00 +00002675 if (Context == DeclaratorContext::TemplateParamContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002676 return DeclSpecContext::DSC_template_param;
Richard Smith77a9c602018-02-28 03:02:23 +00002677 if (Context == DeclaratorContext::TemplateArgContext ||
2678 Context == DeclaratorContext::TemplateTypeArgContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002679 return DeclSpecContext::DSC_template_type_arg;
Richard Smithe303e352018-02-02 22:24:54 +00002680 if (Context == DeclaratorContext::TrailingReturnContext ||
2681 Context == DeclaratorContext::TrailingReturnVarContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002682 return DeclSpecContext::DSC_trailing;
Faisal Vali421b2d12017-12-29 05:41:00 +00002683 if (Context == DeclaratorContext::AliasDeclContext ||
2684 Context == DeclaratorContext::AliasTemplateContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002685 return DeclSpecContext::DSC_alias_declaration;
2686 return DeclSpecContext::DSC_normal;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002687}
2688
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002689/// ParseAlignArgument - Parse the argument to an alignment-specifier.
2690///
2691/// FIXME: Simply returns an alignof() expression if the argument is a
2692/// type. Ideally, the type should be propagated directly into Sema.
2693///
Benjamin Kramere56f3932011-12-23 17:00:35 +00002694/// [C11] type-id
2695/// [C11] constant-expression
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002696/// [C++0x] type-id ...[opt]
2697/// [C++0x] assignment-expression ...[opt]
2698ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2699 SourceLocation &EllipsisLoc) {
2700 ExprResult ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002701 if (isTypeIdInParens()) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002702 SourceLocation TypeLoc = Tok.getLocation();
2703 ParsedType Ty = ParseTypeName().get();
2704 SourceRange TypeRange(Start, Tok.getLocation());
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002705 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2706 Ty.getAsOpaquePtr(), TypeRange);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002707 } else
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002708 ER = ParseConstantExpression();
2709
Alp Toker8fbec672013-12-17 23:29:36 +00002710 if (getLangOpts().CPlusPlus11)
2711 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002712
2713 return ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002714}
2715
2716/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2717/// attribute to Attrs.
2718///
2719/// alignment-specifier:
Benjamin Kramere56f3932011-12-23 17:00:35 +00002720/// [C11] '_Alignas' '(' type-id ')'
2721/// [C11] '_Alignas' '(' constant-expression ')'
Richard Smithd11c7a12013-01-29 01:48:07 +00002722/// [C++11] 'alignas' '(' type-id ...[opt] ')'
2723/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002724void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
Richard Smith44c247f2013-02-22 08:32:16 +00002725 SourceLocation *EndLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002726 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002727 "Not an alignment-specifier!");
2728
Richard Smithd11c7a12013-01-29 01:48:07 +00002729 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2730 SourceLocation KWLoc = ConsumeToken();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002731
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002732 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002733 if (T.expectAndConsume())
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002734 return;
2735
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002736 SourceLocation EllipsisLoc;
2737 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002738 if (ArgExpr.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002739 T.skipToEnd();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002740 return;
2741 }
2742
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002743 T.consumeClose();
Richard Smith44c247f2013-02-22 08:32:16 +00002744 if (EndLoc)
2745 *EndLoc = T.getCloseLocation();
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002746
Aaron Ballman00e99962013-08-31 01:11:41 +00002747 ArgsVector ArgExprs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002748 ArgExprs.push_back(ArgExpr.get());
Craig Topper161e4db2014-05-21 06:02:52 +00002749 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
Erich Keanee891aa92018-07-13 15:07:47 +00002750 ParsedAttr::AS_Keyword, EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002751}
2752
Richard Smith404dfb42013-11-19 22:47:36 +00002753/// Determine whether we're looking at something that might be a declarator
2754/// in a simple-declaration. If it can't possibly be a declarator, maybe
2755/// diagnose a missing semicolon after a prior tag definition in the decl
2756/// specifier.
2757///
2758/// \return \c true if an error occurred and this can't be any kind of
2759/// declaration.
2760bool
2761Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2762 DeclSpecContext DSContext,
2763 LateParsedAttrList *LateAttrs) {
2764 assert(DS.hasTagDefinition() && "shouldn't call this");
2765
Faisal Vali7db85c52017-12-31 00:06:40 +00002766 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2767 DSContext == DeclSpecContext::DSC_top_level);
Richard Smith404dfb42013-11-19 22:47:36 +00002768
2769 if (getLangOpts().CPlusPlus &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002770 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2771 tok::annot_template_id) &&
Richard Smith404dfb42013-11-19 22:47:36 +00002772 TryAnnotateCXXScopeToken(EnteringContext)) {
2773 SkipMalformedDecl();
2774 return true;
2775 }
2776
Richard Smith698875a2013-11-20 23:40:57 +00002777 bool HasScope = Tok.is(tok::annot_cxxscope);
2778 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2779 Token AfterScope = HasScope ? NextToken() : Tok;
2780
Richard Smith404dfb42013-11-19 22:47:36 +00002781 // Determine whether the following tokens could possibly be a
2782 // declarator.
Richard Smith698875a2013-11-20 23:40:57 +00002783 bool MightBeDeclarator = true;
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002784 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
Richard Smith698875a2013-11-20 23:40:57 +00002785 // A declarator-id can't start with 'typename'.
2786 MightBeDeclarator = false;
2787 } else if (AfterScope.is(tok::annot_template_id)) {
2788 // If we have a type expressed as a template-id, this cannot be a
2789 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2790 TemplateIdAnnotation *Annot =
2791 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2792 if (Annot->Kind == TNK_Type_template)
2793 MightBeDeclarator = false;
2794 } else if (AfterScope.is(tok::identifier)) {
2795 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2796
Richard Smith404dfb42013-11-19 22:47:36 +00002797 // These tokens cannot come after the declarator-id in a
2798 // simple-declaration, and are likely to come after a type-specifier.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002799 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2800 tok::annot_cxxscope, tok::coloncolon)) {
Richard Smith698875a2013-11-20 23:40:57 +00002801 // Missing a semicolon.
2802 MightBeDeclarator = false;
2803 } else if (HasScope) {
2804 // If the declarator-id has a scope specifier, it must redeclare a
2805 // previously-declared entity. If that's a type (and this is not a
2806 // typedef), that's an error.
2807 CXXScopeSpec SS;
2808 Actions.RestoreNestedNameSpecifierAnnotation(
2809 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2810 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2811 Sema::NameClassification Classification = Actions.ClassifyName(
2812 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2813 /*IsAddressOfOperand*/false);
2814 switch (Classification.getKind()) {
2815 case Sema::NC_Error:
2816 SkipMalformedDecl();
2817 return true;
Richard Smith404dfb42013-11-19 22:47:36 +00002818
Richard Smith698875a2013-11-20 23:40:57 +00002819 case Sema::NC_Keyword:
2820 case Sema::NC_NestedNameSpecifier:
2821 llvm_unreachable("typo correction and nested name specifiers not "
2822 "possible here");
Richard Smith404dfb42013-11-19 22:47:36 +00002823
Richard Smith698875a2013-11-20 23:40:57 +00002824 case Sema::NC_Type:
2825 case Sema::NC_TypeTemplate:
2826 // Not a previously-declared non-type entity.
2827 MightBeDeclarator = false;
2828 break;
Richard Smith404dfb42013-11-19 22:47:36 +00002829
Richard Smith698875a2013-11-20 23:40:57 +00002830 case Sema::NC_Unknown:
2831 case Sema::NC_Expression:
2832 case Sema::NC_VarTemplate:
2833 case Sema::NC_FunctionTemplate:
2834 // Might be a redeclaration of a prior entity.
2835 break;
2836 }
Richard Smith404dfb42013-11-19 22:47:36 +00002837 }
Richard Smith404dfb42013-11-19 22:47:36 +00002838 }
2839
Richard Smith698875a2013-11-20 23:40:57 +00002840 if (MightBeDeclarator)
Richard Smith404dfb42013-11-19 22:47:36 +00002841 return false;
2842
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002843 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002844 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
Alp Toker383d2c42014-01-01 03:08:43 +00002845 diag::err_expected_after)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002846 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
Richard Smith404dfb42013-11-19 22:47:36 +00002847
2848 // Try to recover from the typo, by dropping the tag definition and parsing
2849 // the problematic tokens as a type.
2850 //
2851 // FIXME: Split the DeclSpec into pieces for the standalone
2852 // declaration and pieces for the following declaration, instead
2853 // of assuming that all the other pieces attach to new declaration,
2854 // and call ParsedFreeStandingDeclSpec as appropriate.
2855 DS.ClearTypeSpecType();
2856 ParsedTemplateInfo NotATemplate;
Faisal Valia534f072018-04-26 00:42:40 +00002857 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
Richard Smith404dfb42013-11-19 22:47:36 +00002858 return false;
2859}
2860
Leonard Chanab80f3c2018-06-14 14:53:51 +00002861// Choose the apprpriate diagnostic error for why fixed point types are
2862// disabled, set the previous specifier, and mark as invalid.
2863static void SetupFixedPointError(const LangOptions &LangOpts,
2864 const char *&PrevSpec, unsigned &DiagID,
2865 bool &isInvalid) {
2866 assert(!LangOpts.FixedPoint);
2867 DiagID = diag::err_fixed_point_not_enabled;
2868 PrevSpec = ""; // Not used by diagnostic
2869 isInvalid = true;
2870}
2871
Faisal Valia534f072018-04-26 00:42:40 +00002872/// ParseDeclarationSpecifiers
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002873/// declaration-specifiers: [C99 6.7]
Chris Lattner3b561a32006-08-13 00:12:11 +00002874/// storage-class-specifier declaration-specifiers[opt]
2875/// type-specifier declaration-specifiers[opt]
Chris Lattner3b561a32006-08-13 00:12:11 +00002876/// [C99] function-specifier declaration-specifiers[opt]
Benjamin Kramere56f3932011-12-23 17:00:35 +00002877/// [C11] alignment-specifier declaration-specifiers[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002878/// [GNU] attributes declaration-specifiers[opt]
Douglas Gregor26701a42011-09-09 02:06:17 +00002879/// [Clang] '__module_private__' declaration-specifiers[opt]
Douglas Gregorab209d82015-07-07 03:58:42 +00002880/// [ObjC1] '__kindof' declaration-specifiers[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002881///
Chris Lattnerf63f89a2006-08-05 03:28:50 +00002882/// storage-class-specifier: [C99 6.7.1]
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002883/// 'typedef'
2884/// 'extern'
2885/// 'static'
2886/// 'auto'
2887/// 'register'
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002888/// [C++] 'mutable'
Richard Smithb4a9e862013-04-12 22:46:28 +00002889/// [C++11] 'thread_local'
2890/// [C11] '_Thread_local'
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002891/// [GNU] '__thread'
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002892/// function-specifier: [C99 6.7.4]
Chris Lattner3b561a32006-08-13 00:12:11 +00002893/// [C99] 'inline'
Douglas Gregor61956c42008-10-31 09:07:45 +00002894/// [C++] 'virtual'
2895/// [C++] 'explicit'
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00002896/// [OpenCL] '__kernel'
Anders Carlssoncd8db412009-05-06 04:46:28 +00002897/// 'friend': [C++ dcl.friend]
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00002898/// 'constexpr': [C++0x dcl.constexpr]
Faisal Valia534f072018-04-26 00:42:40 +00002899void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002900 const ParsedTemplateInfo &TemplateInfo,
John McCall07e91c02009-08-06 02:15:43 +00002901 AccessSpecifier AS,
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002902 DeclSpecContext DSContext,
2903 LateParsedAttrList *LateAttrs) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002904 if (DS.getSourceRange().isInvalid()) {
David Majnemer24b28302014-07-26 05:41:31 +00002905 // Start the range at the current token but make the end of the range
2906 // invalid. This will make the entire range invalid unless we successfully
2907 // consume a token.
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002908 DS.SetRangeStart(Tok.getLocation());
David Majnemer24b28302014-07-26 05:41:31 +00002909 DS.SetRangeEnd(SourceLocation());
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002910 }
Chad Rosierc1183952012-06-26 22:30:43 +00002911
Faisal Vali7db85c52017-12-31 00:06:40 +00002912 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2913 DSContext == DeclSpecContext::DSC_top_level);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002914 bool AttrsLastTime = false;
2915 ParsedAttributesWithRange attrs(AttrFactory);
Benjamin Kramere4812142015-03-12 14:28:38 +00002916 // We use Sema's policy to get bool macros right.
Richard Smith301bc212016-05-19 01:39:10 +00002917 PrintingPolicy Policy = Actions.getPrintingPolicy();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002918 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00002919 bool isInvalid = false;
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00002920 bool isStorageClass = false;
Craig Topper161e4db2014-05-21 06:02:52 +00002921 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00002922 unsigned DiagID = 0;
2923
David Majnemer51fd8a02015-07-22 23:46:18 +00002924 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2925 // implementation for VS2013 uses _Atomic as an identifier for one of the
2926 // classes in <atomic>.
2927 //
2928 // A typedef declaration containing _Atomic<...> is among the places where
2929 // the class is used. If we are currently parsing such a declaration, treat
2930 // the token as an identifier.
2931 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2932 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2933 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2934 Tok.setKind(tok::identifier);
2935
Chris Lattner4d8f8732006-11-28 05:05:08 +00002936 SourceLocation Loc = Tok.getLocation();
Douglas Gregor450c75a2008-11-07 15:42:26 +00002937
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002938 switch (Tok.getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00002939 default:
Chris Lattner0974b232008-07-26 00:20:22 +00002940 DoneWithDeclSpec:
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002941 if (!AttrsLastTime)
2942 ProhibitAttributes(attrs);
Michael Han64536a62012-11-06 19:34:54 +00002943 else {
2944 // Reject C++11 attributes that appertain to decl specifiers as
2945 // we don't support any C++11 attributes that appertain to decl
2946 // specifiers. This also conforms to what g++ 4.8 is doing.
Richard Smith49cc1cc2016-08-18 21:59:42 +00002947 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
Michael Han64536a62012-11-06 19:34:54 +00002948
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002949 DS.takeAttributesFrom(attrs);
Michael Han64536a62012-11-06 19:34:54 +00002950 }
Peter Collingbourne70188b32011-09-29 18:03:57 +00002951
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002952 // If this is not a declaration specifier token, we're done reading decl
2953 // specifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00002954 DS.Finish(Actions, Policy);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002955 return;
Mike Stump11289f42009-09-09 15:08:12 +00002956
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002957 case tok::l_square:
2958 case tok::kw_alignas:
Aaron Ballman606093a2017-10-15 15:01:42 +00002959 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002960 goto DoneWithDeclSpec;
2961
2962 ProhibitAttributes(attrs);
2963 // FIXME: It would be good to recover by accepting the attributes,
2964 // but attempting to do that now would cause serious
2965 // madness in terms of diagnostics.
2966 attrs.clear();
2967 attrs.Range = SourceRange();
2968
2969 ParseCXX11Attributes(attrs);
2970 AttrsLastTime = true;
Chad Rosierc1183952012-06-26 22:30:43 +00002971 continue;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002972
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002973 case tok::code_completion: {
John McCallfaf5fb42010-08-26 23:41:50 +00002974 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002975 if (DS.hasTypeSpecifier()) {
2976 bool AllowNonIdentifiers
2977 = (getCurScope()->getFlags() & (Scope::ControlScope |
2978 Scope::BlockScope |
2979 Scope::TemplateParamScope |
2980 Scope::FunctionPrototypeScope |
2981 Scope::AtCatchScope)) == 0;
2982 bool AllowNestedNameSpecifiers
Faisal Vali7db85c52017-12-31 00:06:40 +00002983 = DSContext == DeclSpecContext::DSC_top_level ||
2984 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002985
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00002986 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
Chad Rosierc1183952012-06-26 22:30:43 +00002987 AllowNonIdentifiers,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00002988 AllowNestedNameSpecifiers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002989 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00002990 }
2991
Douglas Gregor80039242011-02-15 20:33:25 +00002992 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2993 CCC = Sema::PCC_LocalDeclarationSpecifiers;
2994 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
Faisal Vali7db85c52017-12-31 00:06:40 +00002995 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
2996 : Sema::PCC_Template;
2997 else if (DSContext == DeclSpecContext::DSC_class)
John McCallfaf5fb42010-08-26 23:41:50 +00002998 CCC = Sema::PCC_Class;
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +00002999 else if (CurParsedObjCImpl)
John McCallfaf5fb42010-08-26 23:41:50 +00003000 CCC = Sema::PCC_ObjCImplementation;
Chad Rosierc1183952012-06-26 22:30:43 +00003001
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003002 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003003 return cutOffParsing();
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003004 }
3005
Chris Lattnerbd31aa32009-01-05 00:07:25 +00003006 case tok::coloncolon: // ::foo::bar
John McCall1f476a12010-02-26 08:45:28 +00003007 // C++ scope specifier. Annotate and loop, or bail out on error.
Eli Friedman2a1d9a92013-08-15 23:59:20 +00003008 if (TryAnnotateCXXScopeToken(EnteringContext)) {
John McCall1f476a12010-02-26 08:45:28 +00003009 if (!DS.hasTypeSpecifier())
3010 DS.SetTypeSpecError();
3011 goto DoneWithDeclSpec;
3012 }
John McCall8bc2a702010-03-01 18:20:46 +00003013 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3014 goto DoneWithDeclSpec;
John McCall1f476a12010-02-26 08:45:28 +00003015 continue;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003016
3017 case tok::annot_cxxscope: {
Richard Smith3092a3b2012-05-09 18:56:43 +00003018 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003019 goto DoneWithDeclSpec;
3020
John McCall9dab4e62009-12-12 11:40:51 +00003021 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00003022 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3023 Tok.getAnnotationRange(),
3024 SS);
John McCall9dab4e62009-12-12 11:40:51 +00003025
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003026 // We are looking for a qualified typename.
Douglas Gregor167fa622009-03-25 15:40:00 +00003027 Token Next = NextToken();
Mike Stump11289f42009-09-09 15:08:12 +00003028 if (Next.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003029 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
Douglas Gregorb67535d2009-03-31 00:43:58 +00003030 ->Kind == TNK_Type_template) {
Douglas Gregor167fa622009-03-25 15:40:00 +00003031 // We have a qualified template-id, e.g., N::A<int>
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003032
Richard Smith74f02342017-01-19 21:00:13 +00003033 // If this would be a valid constructor declaration with template
3034 // arguments, we will reject the attempt to form an invalid type-id
3035 // referring to the injected-class-name when we annotate the token,
3036 // per C++ [class.qual]p2.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003037 //
Richard Smith74f02342017-01-19 21:00:13 +00003038 // To improve diagnostics for this case, parse the declaration as a
3039 // constructor (and reject the extra template arguments later).
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003040 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
Faisal Vali7db85c52017-12-31 00:06:40 +00003041 if ((DSContext == DeclSpecContext::DSC_top_level ||
3042 DSContext == DeclSpecContext::DSC_class) &&
John McCall84821e72010-04-13 06:39:49 +00003043 TemplateId->Name &&
Richard Smith74f02342017-01-19 21:00:13 +00003044 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003045 isConstructorDeclarator(/*Unqualified*/ false)) {
Richard Smith74f02342017-01-19 21:00:13 +00003046 // The user meant this to be an out-of-line constructor
3047 // definition, but template arguments are not allowed
3048 // there. Just allow this as a constructor; we'll
3049 // complain about it later.
3050 goto DoneWithDeclSpec;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003051 }
3052
John McCall9dab4e62009-12-12 11:40:51 +00003053 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003054 ConsumeAnnotationToken(); // The C++ scope.
Mike Stump11289f42009-09-09 15:08:12 +00003055 assert(Tok.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003056 "ParseOptionalCXXScopeSpecifier not working");
Douglas Gregore7c20652011-03-02 00:47:37 +00003057 AnnotateTemplateIdTokenAsType();
Douglas Gregor167fa622009-03-25 15:40:00 +00003058 continue;
3059 }
3060
Douglas Gregorc5790df2009-09-28 07:26:33 +00003061 if (Next.is(tok::annot_typename)) {
John McCall9dab4e62009-12-12 11:40:51 +00003062 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003063 ConsumeAnnotationToken(); // The C++ scope.
John McCallba7bf592010-08-24 05:47:05 +00003064 if (Tok.getAnnotationValue()) {
3065 ParsedType T = getTypeAnnotation(Tok);
Nico Weber77430342010-11-22 10:30:56 +00003066 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
Chad Rosierc1183952012-06-26 22:30:43 +00003067 Tok.getAnnotationEndLoc(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003068 PrevSpec, DiagID, T, Policy);
Richard Smithda837032012-09-14 18:27:01 +00003069 if (isInvalid)
3070 break;
John McCallba7bf592010-08-24 05:47:05 +00003071 }
Douglas Gregorc5790df2009-09-28 07:26:33 +00003072 else
3073 DS.SetTypeSpecError();
3074 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003075 ConsumeAnnotationToken(); // The typename
Douglas Gregorc5790df2009-09-28 07:26:33 +00003076 }
3077
Douglas Gregor167fa622009-03-25 15:40:00 +00003078 if (Next.isNot(tok::identifier))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003079 goto DoneWithDeclSpec;
3080
Richard Smith74f02342017-01-19 21:00:13 +00003081 // Check whether this is a constructor declaration. If we're in a
3082 // context where the identifier could be a class name, and it has the
3083 // shape of a constructor declaration, process it as one.
Faisal Vali7db85c52017-12-31 00:06:40 +00003084 if ((DSContext == DeclSpecContext::DSC_top_level ||
3085 DSContext == DeclSpecContext::DSC_class) &&
Chad Rosierc1183952012-06-26 22:30:43 +00003086 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
Richard Smith74f02342017-01-19 21:00:13 +00003087 &SS) &&
3088 isConstructorDeclarator(/*Unqualified*/ false))
3089 goto DoneWithDeclSpec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003090
David Blaikieefdccaa2016-01-15 23:43:34 +00003091 ParsedType TypeRep =
3092 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3093 getCurScope(), &SS, false, false, nullptr,
3094 /*IsCtorOrDtorName=*/false,
Richard Smith600b5262017-01-26 20:40:47 +00003095 /*WantNonTrivialSourceInfo=*/true,
3096 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003097
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003098 // If the referenced identifier is not a type, then this declspec is
3099 // erroneous: We already checked about that it has no type specifier, and
3100 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
Mike Stump11289f42009-09-09 15:08:12 +00003101 // typename.
David Blaikie7d170102013-05-15 07:37:26 +00003102 if (!TypeRep) {
Richard Smithaf3b3252017-05-18 19:21:48 +00003103 // Eat the scope spec so the identifier is current.
3104 ConsumeAnnotationToken();
Michael Han9407e502012-11-26 22:54:45 +00003105 ParsedAttributesWithRange Attrs(AttrFactory);
3106 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3107 if (!Attrs.empty()) {
3108 AttrsLastTime = true;
3109 attrs.takeAllFrom(Attrs);
3110 }
3111 continue;
3112 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003113 goto DoneWithDeclSpec;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003114 }
Mike Stump11289f42009-09-09 15:08:12 +00003115
John McCall9dab4e62009-12-12 11:40:51 +00003116 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003117 ConsumeAnnotationToken(); // The C++ scope.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003118
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003119 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003120 DiagID, TypeRep, Policy);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003121 if (isInvalid)
3122 break;
Mike Stump11289f42009-09-09 15:08:12 +00003123
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003124 DS.SetRangeEnd(Tok.getLocation());
3125 ConsumeToken(); // The typename.
3126
3127 continue;
3128 }
Mike Stump11289f42009-09-09 15:08:12 +00003129
Chris Lattnere387d9e2009-01-21 19:48:37 +00003130 case tok::annot_typename: {
Richard Smith404dfb42013-11-19 22:47:36 +00003131 // If we've previously seen a tag definition, we were almost surely
3132 // missing a semicolon after it.
3133 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3134 goto DoneWithDeclSpec;
3135
John McCallba7bf592010-08-24 05:47:05 +00003136 if (Tok.getAnnotationValue()) {
3137 ParsedType T = getTypeAnnotation(Tok);
Nico Weber7f8bb362010-11-22 12:50:03 +00003138 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003139 DiagID, T, Policy);
John McCallba7bf592010-08-24 05:47:05 +00003140 } else
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003141 DS.SetTypeSpecError();
Chad Rosierc1183952012-06-26 22:30:43 +00003142
Chris Lattner005fc1b2010-04-05 18:18:31 +00003143 if (isInvalid)
3144 break;
3145
Chris Lattnere387d9e2009-01-21 19:48:37 +00003146 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003147 ConsumeAnnotationToken(); // The typename
Mike Stump11289f42009-09-09 15:08:12 +00003148
Chris Lattnere387d9e2009-01-21 19:48:37 +00003149 continue;
3150 }
Mike Stump11289f42009-09-09 15:08:12 +00003151
Douglas Gregor06873092011-04-28 15:48:45 +00003152 case tok::kw___is_signed:
3153 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3154 // typically treats it as a trait. If we see __is_signed as it appears
3155 // in libstdc++, e.g.,
3156 //
3157 // static const bool __is_signed;
3158 //
3159 // then treat __is_signed as an identifier rather than as a keyword.
Faisal Vali090da2d2018-01-01 18:23:28 +00003160 if (DS.getTypeSpecType() == TST_bool &&
Douglas Gregor06873092011-04-28 15:48:45 +00003161 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
Alp Toker47642d22013-12-03 06:13:01 +00003162 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3163 TryKeywordIdentFallback(true);
Douglas Gregor06873092011-04-28 15:48:45 +00003164
3165 // We're done with the declaration-specifiers.
3166 goto DoneWithDeclSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00003167
Chris Lattner16fac4f2008-07-26 01:18:38 +00003168 // typedef-name
Nikola Smiljanic67860242014-09-26 00:28:20 +00003169 case tok::kw___super:
David Blaikie15a430a2011-12-04 05:04:18 +00003170 case tok::kw_decltype:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003171 case tok::identifier: {
Reid Klecknerc582f012014-07-14 18:19:58 +00003172 // This identifier can only be a typedef name if we haven't already seen
3173 // a type-specifier. Without this check we misparse:
3174 // typedef int X; struct Y { short X; }; as 'short int'.
3175 if (DS.hasTypeSpecifier())
3176 goto DoneWithDeclSpec;
3177
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003178 // If the token is an identifier named "__declspec" and Microsoft
3179 // extensions are not enabled, it is likely that there will be cascading
3180 // parse errors if this really is a __declspec attribute. Attempt to
3181 // recognize that scenario and recover gracefully.
3182 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3183 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3184 Diag(Loc, diag::err_ms_attributes_not_enabled);
3185
3186 // The next token should be an open paren. If it is, eat the entire
3187 // attribute declaration and continue.
3188 if (NextToken().is(tok::l_paren)) {
3189 // Consume the __declspec identifier.
Richard Trieuba057372017-02-14 23:56:55 +00003190 ConsumeToken();
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003191
3192 // Eat the parens and everything between them.
3193 BalancedDelimiterTracker T(*this, tok::l_paren);
3194 if (T.consumeOpen()) {
3195 assert(false && "Not a left paren?");
3196 return;
3197 }
3198 T.skipToEnd();
3199 continue;
3200 }
3201 }
3202
Serge Pavlov458ea762014-07-16 05:16:52 +00003203 // In C++, check to see if this is a scope specifier like foo::bar::, if
3204 // so handle it as such. This is important for ctor parsing.
3205 if (getLangOpts().CPlusPlus) {
3206 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3207 DS.SetTypeSpecError();
3208 goto DoneWithDeclSpec;
3209 }
3210 if (!Tok.is(tok::identifier))
3211 continue;
3212 }
3213
John Thompson22334602010-02-05 00:12:22 +00003214 // Check for need to substitute AltiVec keyword tokens.
3215 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3216 break;
3217
Richard Smith3092a3b2012-05-09 18:56:43 +00003218 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3219 // allow the use of a typedef name as a type specifier.
3220 if (DS.isTypeAltiVecVector())
3221 goto DoneWithDeclSpec;
3222
Faisal Vali7db85c52017-12-31 00:06:40 +00003223 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3224 isObjCInstancetype()) {
Douglas Gregor5c0870a2015-06-19 23:18:00 +00003225 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3226 assert(TypeRep);
3227 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3228 DiagID, TypeRep, Policy);
3229 if (isInvalid)
3230 break;
3231
3232 DS.SetRangeEnd(Loc);
3233 ConsumeToken();
3234 continue;
3235 }
3236
Richard Smith715ee072018-06-20 21:58:20 +00003237 // If we're in a context where the identifier could be a class name,
3238 // check whether this is a constructor declaration.
3239 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3240 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3241 isConstructorDeclarator(/*Unqualified*/true))
3242 goto DoneWithDeclSpec;
3243
Richard Smith600b5262017-01-26 20:40:47 +00003244 ParsedType TypeRep = Actions.getTypeName(
3245 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3246 false, false, nullptr, false, false,
3247 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003248
Chris Lattner6cc055a2009-04-12 20:42:31 +00003249 // If this is not a typedef name, don't parse it as part of the declspec,
3250 // it must be an implicit int or an error.
John McCallba7bf592010-08-24 05:47:05 +00003251 if (!TypeRep) {
Michael Han9407e502012-11-26 22:54:45 +00003252 ParsedAttributesWithRange Attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +00003253 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
Michael Han9407e502012-11-26 22:54:45 +00003254 if (!Attrs.empty()) {
3255 AttrsLastTime = true;
3256 attrs.takeAllFrom(Attrs);
3257 }
3258 continue;
3259 }
Chris Lattner16fac4f2008-07-26 01:18:38 +00003260 goto DoneWithDeclSpec;
Chris Lattner6cc055a2009-04-12 20:42:31 +00003261 }
Douglas Gregor8bf42052009-02-09 18:46:07 +00003262
Richard Smith35845152017-02-07 01:37:30 +00003263 // Likewise, if this is a context where the identifier could be a template
3264 // name, check whether this is a deduction guide declaration.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003265 if (getLangOpts().CPlusPlus17 &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003266 (DSContext == DeclSpecContext::DSC_class ||
3267 DSContext == DeclSpecContext::DSC_top_level) &&
Richard Smith35845152017-02-07 01:37:30 +00003268 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3269 Tok.getLocation()) &&
3270 isConstructorDeclarator(/*Unqualified*/ true,
3271 /*DeductionGuide*/ true))
3272 goto DoneWithDeclSpec;
3273
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003274 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003275 DiagID, TypeRep, Policy);
Chris Lattner16fac4f2008-07-26 01:18:38 +00003276 if (isInvalid)
3277 break;
Mike Stump11289f42009-09-09 15:08:12 +00003278
Chris Lattner16fac4f2008-07-26 01:18:38 +00003279 DS.SetRangeEnd(Tok.getLocation());
3280 ConsumeToken(); // The identifier
3281
Douglas Gregore9d95f12015-07-07 03:57:35 +00003282 // Objective-C supports type arguments and protocol references
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003283 // following an Objective-C object or object pointer
3284 // type. Handle either one of them.
Douglas Gregore9d95f12015-07-07 03:57:35 +00003285 if (Tok.is(tok::less) && getLangOpts().ObjC1) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003286 SourceLocation NewEndLoc;
3287 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3288 Loc, TypeRep, /*consumeLastToken=*/true,
3289 NewEndLoc);
3290 if (NewTypeRep.isUsable()) {
3291 DS.UpdateTypeRep(NewTypeRep.get());
3292 DS.SetRangeEnd(NewEndLoc);
3293 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00003294 }
Chad Rosierc1183952012-06-26 22:30:43 +00003295
Steve Naroffcd5e7822008-09-22 10:28:57 +00003296 // Need to support trailing type qualifiers (e.g. "id<p> const").
3297 // If a type specifier follows, it will be diagnosed elsewhere.
3298 continue;
Chris Lattner16fac4f2008-07-26 01:18:38 +00003299 }
Douglas Gregor7f741122009-02-25 19:37:18 +00003300
3301 // type-name
3302 case tok::annot_template_id: {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003303 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorb67535d2009-03-31 00:43:58 +00003304 if (TemplateId->Kind != TNK_Type_template) {
Douglas Gregor7f741122009-02-25 19:37:18 +00003305 // This template-id does not refer to a type name, so we're
3306 // done with the type-specifiers.
3307 goto DoneWithDeclSpec;
3308 }
3309
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003310 // If we're in a context where the template-id could be a
3311 // constructor name or specialization, check whether this is a
3312 // constructor declaration.
Faisal Vali7db85c52017-12-31 00:06:40 +00003313 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00003314 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
Richard Smith446161b2014-03-03 21:12:53 +00003315 isConstructorDeclarator(TemplateId->SS.isEmpty()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003316 goto DoneWithDeclSpec;
3317
Douglas Gregor7f741122009-02-25 19:37:18 +00003318 // Turn the template-id annotation token into a type annotation
3319 // token, then try again to parse it as a type-specifier.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003320 AnnotateTemplateIdTokenAsType();
Douglas Gregor7f741122009-02-25 19:37:18 +00003321 continue;
3322 }
3323
Chris Lattnere37e2332006-08-15 04:50:22 +00003324 // GNU attributes support.
3325 case tok::kw___attribute:
Craig Topper161e4db2014-05-21 06:02:52 +00003326 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
Chris Lattnerb95cca02006-10-17 03:01:08 +00003327 continue;
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003328
3329 // Microsoft declspec support.
3330 case tok::kw___declspec:
Aaron Ballman068aa512015-05-20 20:58:33 +00003331 ParseMicrosoftDeclSpecs(DS.getAttributes());
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003332 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003333
Steve Naroff44ac7772008-12-25 14:16:32 +00003334 // Microsoft single token adornments.
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003335 case tok::kw___forceinline: {
Serge Pavlov750db652013-11-13 06:57:53 +00003336 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003337 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Richard Smithda837032012-09-14 18:27:01 +00003338 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00003339 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
Erich Keanee891aa92018-07-13 15:07:47 +00003340 nullptr, 0, ParsedAttr::AS_Keyword);
Richard Smithda837032012-09-14 18:27:01 +00003341 break;
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003342 }
Eli Friedman53339e02009-06-08 23:27:34 +00003343
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003344 case tok::kw___unaligned:
3345 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3346 getLangOpts());
3347 break;
3348
Aaron Ballman317a77f2013-05-22 23:25:32 +00003349 case tok::kw___sptr:
3350 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00003351 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00003352 case tok::kw___ptr32:
Steve Narofff9c29d42008-12-25 14:41:26 +00003353 case tok::kw___w64:
Steve Naroff44ac7772008-12-25 14:16:32 +00003354 case tok::kw___cdecl:
3355 case tok::kw___stdcall:
3356 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00003357 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00003358 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00003359 case tok::kw___vectorcall:
John McCall53fa7142010-12-24 02:08:15 +00003360 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00003361 continue;
3362
Dawn Perchik335e16b2010-09-03 01:29:35 +00003363 // Borland single token adornments.
3364 case tok::kw___pascal:
John McCall53fa7142010-12-24 02:08:15 +00003365 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00003366 continue;
3367
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003368 // OpenCL single token adornments.
3369 case tok::kw___kernel:
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +00003370 ParseOpenCLKernelAttributes(DS.getAttributes());
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003371 continue;
3372
Douglas Gregor261a89b2015-06-19 17:51:05 +00003373 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00003374 case tok::kw__Nonnull:
3375 case tok::kw__Nullable:
3376 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00003377 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3378 continue;
3379
Douglas Gregorab209d82015-07-07 03:58:42 +00003380 // Objective-C 'kindof' types.
3381 case tok::kw___kindof:
3382 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00003383 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00003384 (void)ConsumeToken();
3385 continue;
3386
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003387 // storage-class-specifier
3388 case tok::kw_typedef:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003389 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003390 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003391 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003392 break;
3393 case tok::kw_extern:
Richard Smithb4a9e862013-04-12 22:46:28 +00003394 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003395 Diag(Tok, diag::ext_thread_before) << "extern";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003396 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003397 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003398 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003399 break;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003400 case tok::kw___private_extern__:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003401 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003402 Loc, PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003403 isStorageClass = true;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003404 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003405 case tok::kw_static:
Richard Smithb4a9e862013-04-12 22:46:28 +00003406 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003407 Diag(Tok, diag::ext_thread_before) << "static";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003408 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003409 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003410 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003411 break;
3412 case tok::kw_auto:
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003413 if (getLangOpts().CPlusPlus11) {
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003414 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003415 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003416 PrevSpec, DiagID, Policy);
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003417 if (!isInvalid)
Richard Smith58c74332011-09-04 19:54:14 +00003418 Diag(Tok, diag::ext_auto_storage_class)
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003419 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith58c74332011-09-04 19:54:14 +00003420 } else
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003421 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003422 DiagID, Policy);
Richard Smith58c74332011-09-04 19:54:14 +00003423 } else
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003424 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003425 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003426 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003427 break;
Richard Smithe301ba22015-11-11 02:02:15 +00003428 case tok::kw___auto_type:
3429 Diag(Tok, diag::ext_auto_type);
3430 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3431 DiagID, Policy);
3432 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003433 case tok::kw_register:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003434 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003435 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003436 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003437 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003438 case tok::kw_mutable:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003439 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003440 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003441 isStorageClass = true;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003442 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003443 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00003444 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3445 PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003446 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003447 break;
3448 case tok::kw_thread_local:
3449 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3450 PrevSpec, DiagID);
Sven van Haastregtc4100832018-04-24 14:47:29 +00003451 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003452 break;
3453 case tok::kw__Thread_local:
3454 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3455 Loc, PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003456 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003457 break;
Mike Stump11289f42009-09-09 15:08:12 +00003458
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003459 // function-specifier
3460 case tok::kw_inline:
Serge Pavlov750db652013-11-13 06:57:53 +00003461 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003462 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003463 case tok::kw_virtual:
Sven van Haastregt49ffffb2018-04-23 11:23:47 +00003464 // OpenCL C++ v1.0 s2.9: the virtual function qualifier is not supported.
3465 if (getLangOpts().OpenCLCPlusPlus) {
3466 DiagID = diag::err_openclcxx_virtual_function;
3467 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3468 isInvalid = true;
3469 }
3470 else {
3471 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3472 }
Douglas Gregor61956c42008-10-31 09:07:45 +00003473 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003474 case tok::kw_explicit:
Serge Pavlov750db652013-11-13 06:57:53 +00003475 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
Douglas Gregor61956c42008-10-31 09:07:45 +00003476 break;
Richard Smith0015f092013-01-17 22:16:11 +00003477 case tok::kw__Noreturn:
3478 if (!getLangOpts().C11)
3479 Diag(Loc, diag::ext_c11_noreturn);
Serge Pavlov750db652013-11-13 06:57:53 +00003480 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
Richard Smith0015f092013-01-17 22:16:11 +00003481 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003482
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003483 // alignment-specifier
3484 case tok::kw__Alignas:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003485 if (!getLangOpts().C11)
Jordan Rose58d54722012-06-30 21:33:57 +00003486 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003487 ParseAlignmentSpecifier(DS.getAttributes());
3488 continue;
3489
Anders Carlssoncd8db412009-05-06 04:46:28 +00003490 // friend
3491 case tok::kw_friend:
Faisal Vali7db85c52017-12-31 00:06:40 +00003492 if (DSContext == DeclSpecContext::DSC_class)
John McCall07e91c02009-08-06 02:15:43 +00003493 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3494 else {
3495 PrevSpec = ""; // not actually used by the diagnostic
3496 DiagID = diag::err_friend_invalid_in_context;
3497 isInvalid = true;
3498 }
Anders Carlssoncd8db412009-05-06 04:46:28 +00003499 break;
Mike Stump11289f42009-09-09 15:08:12 +00003500
Douglas Gregor26701a42011-09-09 02:06:17 +00003501 // Modules
3502 case tok::kw___module_private__:
3503 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3504 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003505
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00003506 // constexpr
3507 case tok::kw_constexpr:
3508 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3509 break;
3510
Chris Lattnere387d9e2009-01-21 19:48:37 +00003511 // type-specifier
3512 case tok::kw_short:
John McCall49bfce42009-08-03 20:12:06 +00003513 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003514 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003515 break;
3516 case tok::kw_long:
3517 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
John McCall49bfce42009-08-03 20:12:06 +00003518 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003519 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003520 else
John McCall49bfce42009-08-03 20:12:06 +00003521 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003522 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003523 break;
Francois Pichet84133e42011-04-28 01:59:37 +00003524 case tok::kw___int64:
3525 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003526 DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00003527 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003528 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00003529 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3530 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003531 break;
3532 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00003533 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3534 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003535 break;
3536 case tok::kw__Complex:
John McCall49bfce42009-08-03 20:12:06 +00003537 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3538 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003539 break;
3540 case tok::kw__Imaginary:
John McCall49bfce42009-08-03 20:12:06 +00003541 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3542 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003543 break;
3544 case tok::kw_void:
John McCall49bfce42009-08-03 20:12:06 +00003545 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003546 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003547 break;
3548 case tok::kw_char:
John McCall49bfce42009-08-03 20:12:06 +00003549 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003550 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003551 break;
3552 case tok::kw_int:
John McCall49bfce42009-08-03 20:12:06 +00003553 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003554 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003555 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00003556 case tok::kw___int128:
3557 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003558 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003559 break;
3560 case tok::kw_half:
3561 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003562 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003563 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003564 case tok::kw_float:
John McCall49bfce42009-08-03 20:12:06 +00003565 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003566 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003567 break;
3568 case tok::kw_double:
John McCall49bfce42009-08-03 20:12:06 +00003569 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003570 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003571 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00003572 case tok::kw__Float16:
3573 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3574 DiagID, Policy);
3575 break;
Leonard Chanf921d852018-06-04 16:07:52 +00003576 case tok::kw__Accum:
3577 if (!getLangOpts().FixedPoint) {
Leonard Chanab80f3c2018-06-14 14:53:51 +00003578 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
Leonard Chanf921d852018-06-04 16:07:52 +00003579 } else {
3580 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3581 DiagID, Policy);
3582 }
3583 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00003584 case tok::kw__Fract:
3585 if (!getLangOpts().FixedPoint) {
3586 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3587 } else {
3588 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3589 DiagID, Policy);
3590 }
3591 break;
3592 case tok::kw__Sat:
3593 if (!getLangOpts().FixedPoint) {
3594 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3595 } else {
3596 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3597 }
3598 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003599 case tok::kw___float128:
3600 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3601 DiagID, Policy);
3602 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003603 case tok::kw_wchar_t:
John McCall49bfce42009-08-03 20:12:06 +00003604 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003605 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003606 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00003607 case tok::kw_char8_t:
3608 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3609 DiagID, Policy);
3610 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003611 case tok::kw_char16_t:
John McCall49bfce42009-08-03 20:12:06 +00003612 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003613 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003614 break;
3615 case tok::kw_char32_t:
John McCall49bfce42009-08-03 20:12:06 +00003616 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003617 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003618 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003619 case tok::kw_bool:
3620 case tok::kw__Bool:
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003621 if (Tok.is(tok::kw_bool) &&
3622 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3623 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3624 PrevSpec = ""; // Not used by the diagnostic.
3625 DiagID = diag::err_bool_redeclaration;
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003626 // For better error recovery.
3627 Tok.setKind(tok::identifier);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003628 isInvalid = true;
3629 } else {
3630 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003631 DiagID, Policy);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003632 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003633 break;
3634 case tok::kw__Decimal32:
John McCall49bfce42009-08-03 20:12:06 +00003635 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003636 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003637 break;
3638 case tok::kw__Decimal64:
John McCall49bfce42009-08-03 20:12:06 +00003639 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003640 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003641 break;
3642 case tok::kw__Decimal128:
John McCall49bfce42009-08-03 20:12:06 +00003643 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003644 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003645 break;
John Thompson22334602010-02-05 00:12:22 +00003646 case tok::kw___vector:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003647 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003648 break;
3649 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003650 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003651 break;
Bill Seurercf2c96b2015-01-12 19:35:51 +00003652 case tok::kw___bool:
3653 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3654 break;
Xiuli Pan9c14e282016-01-09 12:53:17 +00003655 case tok::kw_pipe:
3656 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3657 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3658 // support the "pipe" word as identifier.
3659 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3660 goto DoneWithDeclSpec;
3661 }
3662 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3663 break;
Alexey Bader954ba212016-04-08 13:40:33 +00003664#define GENERIC_IMAGE_TYPE(ImgType, Id) \
3665 case tok::kw_##ImgType##_t: \
3666 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3667 DiagID, Policy); \
3668 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00003669#include "clang/Basic/OpenCLImageTypes.def"
John McCall39439732011-04-09 22:50:59 +00003670 case tok::kw___unknown_anytype:
Faisal Vali090da2d2018-01-01 18:23:28 +00003671 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003672 PrevSpec, DiagID, Policy);
John McCall39439732011-04-09 22:50:59 +00003673 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003674
3675 // class-specifier:
3676 case tok::kw_class:
3677 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00003678 case tok::kw___interface:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003679 case tok::kw_union: {
3680 tok::TokenKind Kind = Tok.getKind();
3681 ConsumeToken();
Michael Han9407e502012-11-26 22:54:45 +00003682
3683 // These are attributes following class specifiers.
3684 // To produce better diagnostic, we parse them when
3685 // parsing class specifier.
Bill Wendling44426052012-12-20 19:22:21 +00003686 ParsedAttributesWithRange Attributes(AttrFactory);
Richard Smithc5b05522012-03-12 07:56:15 +00003687 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
Bill Wendling44426052012-12-20 19:22:21 +00003688 EnteringContext, DSContext, Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003689
3690 // If there are attributes following class specifier,
3691 // take them over and handle them here.
Bill Wendling44426052012-12-20 19:22:21 +00003692 if (!Attributes.empty()) {
Michael Han9407e502012-11-26 22:54:45 +00003693 AttrsLastTime = true;
Bill Wendling44426052012-12-20 19:22:21 +00003694 attrs.takeAllFrom(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003695 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003696 continue;
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003697 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003698
3699 // enum-specifier:
3700 case tok::kw_enum:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003701 ConsumeToken();
Richard Smithc5b05522012-03-12 07:56:15 +00003702 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003703 continue;
Faisal Valia534f072018-04-26 00:42:40 +00003704
Chris Lattnere387d9e2009-01-21 19:48:37 +00003705 // cv-qualifier:
3706 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00003707 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003708 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003709 break;
3710 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00003711 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003712 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003713 break;
3714 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00003715 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003716 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003717 break;
3718
Douglas Gregor333489b2009-03-27 23:10:48 +00003719 // C++ typename-specifier:
3720 case tok::kw_typename:
John McCall1f476a12010-02-26 08:45:28 +00003721 if (TryAnnotateTypeOrScopeToken()) {
3722 DS.SetTypeSpecError();
3723 goto DoneWithDeclSpec;
3724 }
3725 if (!Tok.is(tok::kw_typename))
Douglas Gregor333489b2009-03-27 23:10:48 +00003726 continue;
3727 break;
3728
Chris Lattnere387d9e2009-01-21 19:48:37 +00003729 // GNU typeof support.
3730 case tok::kw_typeof:
3731 ParseTypeofSpecifier(DS);
3732 continue;
3733
David Blaikie15a430a2011-12-04 05:04:18 +00003734 case tok::annot_decltype:
Anders Carlsson74948d02009-06-24 17:47:40 +00003735 ParseDecltypeSpecifier(DS);
3736 continue;
3737
David Majnemer15b311c2016-06-14 03:20:28 +00003738 case tok::annot_pragma_pack:
3739 HandlePragmaPack();
3740 continue;
3741
3742 case tok::annot_pragma_ms_pragma:
3743 HandlePragmaMSPragma();
3744 continue;
3745
3746 case tok::annot_pragma_ms_vtordisp:
3747 HandlePragmaMSVtorDisp();
3748 continue;
3749
3750 case tok::annot_pragma_ms_pointers_to_members:
3751 HandlePragmaMSPointersToMembers();
3752 continue;
3753
Alexis Hunt4a257072011-05-19 05:37:45 +00003754 case tok::kw___underlying_type:
3755 ParseUnderlyingTypeSpecifier(DS);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003756 continue;
3757
3758 case tok::kw__Atomic:
Richard Smith8e1ac332013-03-28 01:55:44 +00003759 // C11 6.7.2.4/4:
3760 // If the _Atomic keyword is immediately followed by a left parenthesis,
3761 // it is interpreted as a type specifier (with a type name), not as a
3762 // type qualifier.
3763 if (NextToken().is(tok::l_paren)) {
3764 ParseAtomicSpecifier(DS);
3765 continue;
3766 }
3767 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3768 getLangOpts());
3769 break;
Alexis Hunt4a257072011-05-19 05:37:45 +00003770
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003771 // OpenCL access qualifiers:
3772 case tok::kw___read_only:
3773 case tok::kw___write_only:
3774 case tok::kw___read_write:
3775 // OpenCL C++ 1.0 s2.2: access qualifiers are reserved keywords.
3776 if (Actions.getLangOpts().OpenCLCPlusPlus) {
3777 DiagID = diag::err_openclcxx_reserved;
3778 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3779 isInvalid = true;
3780 }
3781 ParseOpenCLQualifiers(DS.getAttributes());
3782 break;
3783
3784 // OpenCL address space qualifiers:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003785 case tok::kw___generic:
3786 // generic address space is introduced only in OpenCL v2.0
3787 // see OpenCL C Spec v2.0 s6.5.5
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003788 if (Actions.getLangOpts().OpenCLVersion < 200 &&
3789 !Actions.getLangOpts().OpenCLCPlusPlus) {
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003790 DiagID = diag::err_opencl_unknown_type_specifier;
3791 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3792 isInvalid = true;
3793 break;
3794 };
Galina Kistanova77674252017-06-01 21:15:34 +00003795 LLVM_FALLTHROUGH;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003796 case tok::kw___private:
3797 case tok::kw___global:
3798 case tok::kw___local:
3799 case tok::kw___constant:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00003800 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003801 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003802
Steve Naroffcfdf6162008-06-05 00:02:44 +00003803 case tok::less:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003804 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
Chris Lattner0974b232008-07-26 00:20:22 +00003805 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3806 // but we support it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003807 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
Chris Lattner0974b232008-07-26 00:20:22 +00003808 goto DoneWithDeclSpec;
Mike Stump11289f42009-09-09 15:08:12 +00003809
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003810 SourceLocation StartLoc = Tok.getLocation();
3811 SourceLocation EndLoc;
3812 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3813 if (Type.isUsable()) {
3814 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3815 PrevSpec, DiagID, Type.get(),
3816 Actions.getASTContext().getPrintingPolicy()))
3817 Diag(StartLoc, DiagID) << PrevSpec;
Fangrui Song6907ce22018-07-30 19:24:48 +00003818
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003819 DS.SetRangeEnd(EndLoc);
3820 } else {
3821 DS.SetTypeSpecError();
3822 }
Chad Rosierc1183952012-06-26 22:30:43 +00003823
Douglas Gregor06e41ae2010-10-21 23:17:00 +00003824 // Need to support trailing type qualifiers (e.g. "id<p> const").
3825 // If a type specifier follows, it will be diagnosed elsewhere.
3826 continue;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003827 }
John McCall49bfce42009-08-03 20:12:06 +00003828 // If the specifier wasn't legal, issue a diagnostic.
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003829 if (isInvalid) {
3830 assert(PrevSpec && "Method did not return previous specifier!");
John McCall49bfce42009-08-03 20:12:06 +00003831 assert(DiagID);
Chad Rosierc1183952012-06-26 22:30:43 +00003832
Douglas Gregora05f5ab2010-08-23 14:34:43 +00003833 if (DiagID == diag::ext_duplicate_declspec)
3834 Diag(Tok, DiagID)
3835 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003836 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003837 Diag(Tok, DiagID) << getLangOpts().OpenCLCPlusPlus
3838 << getLangOpts().getOpenCLVersionTuple().getAsString()
3839 << PrevSpec << isStorageClass;
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003840 } else
Douglas Gregora05f5ab2010-08-23 14:34:43 +00003841 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003842 }
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003843
Chris Lattner2e232092008-03-13 06:29:04 +00003844 DS.SetRangeEnd(Tok.getLocation());
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003845 if (DiagID != diag::err_bool_redeclaration)
Volodymyr Sapsai9f7b5cc2018-04-10 18:29:47 +00003846 // After an error the next token can be an annotation token.
3847 ConsumeAnyToken();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003848
3849 AttrsLastTime = false;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003850 }
3851}
Douglas Gregoreb31f392008-12-01 23:54:00 +00003852
Chris Lattner70ae4912007-10-29 04:42:53 +00003853/// ParseStructDeclaration - Parse a struct declaration without the terminating
3854/// semicolon.
3855///
Chris Lattner90a26b02007-01-23 04:38:16 +00003856/// struct-declaration:
Aaron Ballman606093a2017-10-15 15:01:42 +00003857/// [C2x] attributes-specifier-seq[opt]
3858/// specifier-qualifier-list struct-declarator-list
Chris Lattner736ed5d2007-06-09 05:59:07 +00003859/// [GNU] __extension__ struct-declaration
Chris Lattner70ae4912007-10-29 04:42:53 +00003860/// [GNU] specifier-qualifier-list
Chris Lattner90a26b02007-01-23 04:38:16 +00003861/// struct-declarator-list:
3862/// struct-declarator
3863/// struct-declarator-list ',' struct-declarator
3864/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3865/// struct-declarator:
3866/// declarator
3867/// [GNU] declarator attributes[opt]
3868/// declarator[opt] ':' constant-expression
3869/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3870///
Benjamin Kramera39beb92014-09-03 11:06:10 +00003871void Parser::ParseStructDeclaration(
3872 ParsingDeclSpec &DS,
3873 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
Chad Rosierc1183952012-06-26 22:30:43 +00003874
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003875 if (Tok.is(tok::kw___extension__)) {
3876 // __extension__ silences extension warnings in the subexpression.
3877 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Steve Naroff97170802007-08-20 22:28:22 +00003878 ConsumeToken();
Benjamin Kramera39beb92014-09-03 11:06:10 +00003879 return ParseStructDeclaration(DS, FieldsCallback);
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003880 }
Mike Stump11289f42009-09-09 15:08:12 +00003881
Aaron Ballman606093a2017-10-15 15:01:42 +00003882 // Parse leading attributes.
3883 ParsedAttributesWithRange Attrs(AttrFactory);
3884 MaybeParseCXX11Attributes(Attrs);
3885 DS.takeAttributesFrom(Attrs);
3886
Steve Naroff97170802007-08-20 22:28:22 +00003887 // Parse the common specifier-qualifiers-list piece.
Steve Naroff97170802007-08-20 22:28:22 +00003888 ParseSpecifierQualifierList(DS);
Mike Stump11289f42009-09-09 15:08:12 +00003889
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003890 // If there are no declarators, this is a free-standing declaration
3891 // specifier. Let the actions module cope with it.
Chris Lattner76c72282007-10-09 17:33:22 +00003892 if (Tok.is(tok::semi)) {
Nico Weber7b837f52016-01-28 19:25:00 +00003893 RecordDecl *AnonRecord = nullptr;
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003894 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00003895 DS, AnonRecord);
3896 assert(!AnonRecord && "Did not expect anonymous struct or union here");
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003897 DS.complete(TheDecl);
Steve Naroff97170802007-08-20 22:28:22 +00003898 return;
3899 }
3900
3901 // Read struct-declarators until we find the semicolon.
John McCallcfefb6d2009-11-03 02:38:08 +00003902 bool FirstDeclarator = true;
Richard Smith8d06f422012-01-12 23:53:29 +00003903 SourceLocation CommaLoc;
Steve Naroff97170802007-08-20 22:28:22 +00003904 while (1) {
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003905 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
Richard Smith8d06f422012-01-12 23:53:29 +00003906 DeclaratorInfo.D.setCommaLoc(CommaLoc);
John McCallcfefb6d2009-11-03 02:38:08 +00003907
Bill Wendling44426052012-12-20 19:22:21 +00003908 // Attributes are only allowed here on successive declarators.
John McCall53fa7142010-12-24 02:08:15 +00003909 if (!FirstDeclarator)
3910 MaybeParseGNUAttributes(DeclaratorInfo.D);
Mike Stump11289f42009-09-09 15:08:12 +00003911
Steve Naroff97170802007-08-20 22:28:22 +00003912 /// struct-declarator: declarator
3913 /// struct-declarator: declarator[opt] ':' constant-expression
Chris Lattner17c3b1f2009-12-10 01:59:24 +00003914 if (Tok.isNot(tok::colon)) {
3915 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3916 ColonProtectionRAIIObject X(*this);
Chris Lattnera12405b2008-04-10 06:46:29 +00003917 ParseDeclarator(DeclaratorInfo.D);
Richard Smith3d1a94c2014-08-12 00:22:39 +00003918 } else
3919 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003920
Alp Toker8fbec672013-12-17 23:29:36 +00003921 if (TryConsumeToken(tok::colon)) {
John McCalldadc5752010-08-24 06:29:42 +00003922 ExprResult Res(ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00003923 if (Res.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00003924 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner32295d32008-04-10 06:15:14 +00003925 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003926 DeclaratorInfo.BitfieldSize = Res.get();
Steve Naroff97170802007-08-20 22:28:22 +00003927 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003928
Steve Naroff97170802007-08-20 22:28:22 +00003929 // If attributes exist after the declarator, parse them.
John McCall53fa7142010-12-24 02:08:15 +00003930 MaybeParseGNUAttributes(DeclaratorInfo.D);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003931
John McCallcfefb6d2009-11-03 02:38:08 +00003932 // We're done with this declarator; invoke the callback.
Benjamin Kramera39beb92014-09-03 11:06:10 +00003933 FieldsCallback(DeclaratorInfo);
John McCallcfefb6d2009-11-03 02:38:08 +00003934
Steve Naroff97170802007-08-20 22:28:22 +00003935 // If we don't have a comma, it is either the end of the list (a ';')
3936 // or an error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00003937 if (!TryConsumeToken(tok::comma, CommaLoc))
Chris Lattner70ae4912007-10-29 04:42:53 +00003938 return;
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003939
John McCallcfefb6d2009-11-03 02:38:08 +00003940 FirstDeclarator = false;
Steve Naroff97170802007-08-20 22:28:22 +00003941 }
Steve Naroff97170802007-08-20 22:28:22 +00003942}
3943
3944/// ParseStructUnionBody
3945/// struct-contents:
3946/// struct-declaration-list
3947/// [EXT] empty
3948/// [GNU] "struct-declaration-list" without terminatoring ';'
3949/// struct-declaration-list:
3950/// struct-declaration
3951/// struct-declaration-list struct-declaration
Chris Lattner535b8302008-06-21 19:39:06 +00003952/// [OBC] '@' 'defs' '(' class-name ')'
Steve Naroff97170802007-08-20 22:28:22 +00003953///
Chris Lattner1300fb92007-01-23 23:42:53 +00003954void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00003955 unsigned TagType, Decl *TagDecl) {
Jordan Rose1e879d82018-03-23 00:07:18 +00003956 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003957 "parsing struct/union body");
Andy Gibbs22e140b2013-04-03 09:31:19 +00003958 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
Mike Stump11289f42009-09-09 15:08:12 +00003959
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003960 BalancedDelimiterTracker T(*this, tok::l_brace);
3961 if (T.consumeOpen())
3962 return;
Mike Stump11289f42009-09-09 15:08:12 +00003963
Douglas Gregor658b9552009-01-09 22:42:13 +00003964 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00003965 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003966
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003967 SmallVector<Decl *, 32> FieldDecls;
Chris Lattnera12405b2008-04-10 06:46:29 +00003968
Chris Lattner7b9ace62007-01-23 20:11:08 +00003969 // While we still have something to read, read the declarations in the struct.
Richard Smith752ada82015-11-17 23:32:01 +00003970 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3971 Tok.isNot(tok::eof)) {
Chris Lattner90a26b02007-01-23 04:38:16 +00003972 // Each iteration of this loop reads one struct-declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003973
Chris Lattner736ed5d2007-06-09 05:59:07 +00003974 // Check for extraneous top-level semicolon.
Chris Lattner76c72282007-10-09 17:33:22 +00003975 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00003976 ConsumeExtraSemi(InsideStruct, TagType);
Chris Lattner36e46a22007-06-09 05:49:55 +00003977 continue;
3978 }
Chris Lattnera12405b2008-04-10 06:46:29 +00003979
Andy Gibbsc804e082013-04-03 09:46:04 +00003980 // Parse _Static_assert declaration.
3981 if (Tok.is(tok::kw__Static_assert)) {
3982 SourceLocation DeclEnd;
3983 ParseStaticAssertDeclaration(DeclEnd);
3984 continue;
3985 }
3986
Argyrios Kyrtzidis71c12fb2013-04-18 01:42:35 +00003987 if (Tok.is(tok::annot_pragma_pack)) {
3988 HandlePragmaPack();
3989 continue;
3990 }
3991
3992 if (Tok.is(tok::annot_pragma_align)) {
3993 HandlePragmaAlign();
3994 continue;
3995 }
3996
Alexey Bataev4652e4b2015-08-12 07:10:54 +00003997 if (Tok.is(tok::annot_pragma_openmp)) {
Alexey Bataev587e1de2016-03-30 10:43:55 +00003998 // Result can be ignored, because it must be always empty.
3999 AccessSpecifier AS = AS_none;
4000 ParsedAttributesWithRange Attrs(AttrFactory);
4001 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004002 continue;
4003 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004004
John McCallcfefb6d2009-11-03 02:38:08 +00004005 if (!Tok.is(tok::at)) {
Benjamin Kramera39beb92014-09-03 11:06:10 +00004006 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4007 // Install the declarator into the current TagDecl.
4008 Decl *Field =
4009 Actions.ActOnField(getCurScope(), TagDecl,
4010 FD.D.getDeclSpec().getSourceRange().getBegin(),
4011 FD.D, FD.BitfieldSize);
4012 FieldDecls.push_back(Field);
4013 FD.complete(Field);
4014 };
John McCallcfefb6d2009-11-03 02:38:08 +00004015
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004016 // Parse all the comma separated declarators.
4017 ParsingDeclSpec DS(*this);
Benjamin Kramera39beb92014-09-03 11:06:10 +00004018 ParseStructDeclaration(DS, CFieldCallback);
Chris Lattner535b8302008-06-21 19:39:06 +00004019 } else { // Handle @defs
4020 ConsumeToken();
4021 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4022 Diag(Tok, diag::err_unexpected_at);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004023 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004024 continue;
4025 }
4026 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004027 ExpectAndConsume(tok::l_paren);
Chris Lattner535b8302008-06-21 19:39:06 +00004028 if (!Tok.is(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004029 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004030 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004031 continue;
4032 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004033 SmallVector<Decl *, 16> Fields;
Douglas Gregor0be31a22010-07-02 17:43:08 +00004034 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004035 Tok.getIdentifierInfo(), Fields);
Chris Lattner535b8302008-06-21 19:39:06 +00004036 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4037 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004038 ExpectAndConsume(tok::r_paren);
Mike Stump11289f42009-09-09 15:08:12 +00004039 }
Chris Lattner736ed5d2007-06-09 05:59:07 +00004040
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004041 if (TryConsumeToken(tok::semi))
4042 continue;
4043
4044 if (Tok.is(tok::r_brace)) {
Chris Lattner245c5332010-02-02 00:37:27 +00004045 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
Chris Lattner0c7e82d2007-06-09 05:54:40 +00004046 break;
Chris Lattner90a26b02007-01-23 04:38:16 +00004047 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004048
4049 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4050 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4051 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4052 // If we stopped at a ';', eat it.
4053 TryConsumeToken(tok::semi);
Chris Lattner90a26b02007-01-23 04:38:16 +00004054 }
Mike Stump11289f42009-09-09 15:08:12 +00004055
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004056 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +00004057
John McCall084e83d2011-03-24 11:26:52 +00004058 ParsedAttributes attrs(AttrFactory);
Chris Lattner90a26b02007-01-23 04:38:16 +00004059 // If attributes exist after struct contents, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004060 MaybeParseGNUAttributes(attrs);
Daniel Dunbar15619c72008-10-03 02:03:53 +00004061
Erich Keanec480f302018-07-12 21:09:05 +00004062 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4063 T.getOpenLocation(), T.getCloseLocation(), attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004064 StructScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004065 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
Chris Lattner90a26b02007-01-23 04:38:16 +00004066}
4067
Chris Lattner3b561a32006-08-13 00:12:11 +00004068/// ParseEnumSpecifier
Chris Lattner1890ac82006-08-13 01:16:23 +00004069/// enum-specifier: [C99 6.7.2.2]
Chris Lattner3b561a32006-08-13 00:12:11 +00004070/// 'enum' identifier[opt] '{' enumerator-list '}'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004071///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
Chris Lattnere37e2332006-08-15 04:50:22 +00004072/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4073/// '}' attributes[opt]
Aaron Ballman9ecff022012-03-01 04:09:28 +00004074/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4075/// '}'
Chris Lattner3b561a32006-08-13 00:12:11 +00004076/// 'enum' identifier
Chris Lattnere37e2332006-08-15 04:50:22 +00004077/// [GNU] 'enum' attributes[opt] identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004078///
Richard Smith7d137e32012-03-23 03:33:32 +00004079/// [C++11] enum-head '{' enumerator-list[opt] '}'
4080/// [C++11] enum-head '{' enumerator-list ',' '}'
Douglas Gregor0bf31402010-10-08 23:50:27 +00004081///
Richard Smith7d137e32012-03-23 03:33:32 +00004082/// enum-head: [C++11]
4083/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4084/// enum-key attribute-specifier-seq[opt] nested-name-specifier
4085/// identifier enum-base[opt]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004086///
Richard Smith7d137e32012-03-23 03:33:32 +00004087/// enum-key: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004088/// 'enum'
4089/// 'enum' 'class'
4090/// 'enum' 'struct'
4091///
Richard Smith7d137e32012-03-23 03:33:32 +00004092/// enum-base: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004093/// ':' type-specifier-seq
4094///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004095/// [C++] elaborated-type-specifier:
4096/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4097///
Chris Lattnerffaa0e62009-04-12 21:49:30 +00004098void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregordc70c3a2010-03-02 17:53:14 +00004099 const ParsedTemplateInfo &TemplateInfo,
Richard Smithc5b05522012-03-12 07:56:15 +00004100 AccessSpecifier AS, DeclSpecContext DSC) {
Chris Lattnerffbc2712007-01-25 06:05:38 +00004101 // Parse the tag portion of this.
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004102 if (Tok.is(tok::code_completion)) {
4103 // Code completion for an enum name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004104 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00004105 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004106 }
John McCallcb432fa2011-07-06 05:58:41 +00004107
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004108 // If attributes exist after tag, parse them.
4109 ParsedAttributesWithRange attrs(AttrFactory);
4110 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004111 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004112 MaybeParseMicrosoftDeclSpecs(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004113
Richard Smith0f8ee222012-01-10 01:33:14 +00004114 SourceLocation ScopedEnumKWLoc;
John McCallcb432fa2011-07-06 05:58:41 +00004115 bool IsScopedUsingClassTag = false;
4116
John McCallbeae29a2012-06-23 22:30:04 +00004117 // In C++11, recognize 'enum class' and 'enum struct'.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004118 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
Richard Trieud0d87b52013-04-23 02:47:36 +00004119 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4120 : diag::ext_scoped_enum);
John McCallcb432fa2011-07-06 05:58:41 +00004121 IsScopedUsingClassTag = Tok.is(tok::kw_class);
Richard Smith0f8ee222012-01-10 01:33:14 +00004122 ScopedEnumKWLoc = ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004123
Bill Wendling44426052012-12-20 19:22:21 +00004124 // Attributes are not allowed between these keywords. Diagnose,
John McCallbeae29a2012-06-23 22:30:04 +00004125 // but then just treat them like they appeared in the right place.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004126 ProhibitAttributes(attrs);
John McCallbeae29a2012-06-23 22:30:04 +00004127
4128 // They are allowed afterwards, though.
4129 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004130 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004131 MaybeParseMicrosoftDeclSpecs(attrs);
John McCallcb432fa2011-07-06 05:58:41 +00004132 }
Richard Smith7d137e32012-03-23 03:33:32 +00004133
John McCall6347b682012-05-07 06:16:58 +00004134 // C++11 [temp.explicit]p12:
4135 // The usual access controls do not apply to names used to specify
4136 // explicit instantiations.
4137 // We extend this to also cover explicit specializations. Note that
4138 // we don't suppress if this turns out to be an elaborated type
4139 // specifier.
4140 bool shouldDelayDiagsInTag =
4141 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4142 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4143 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Richard Smith7d137e32012-03-23 03:33:32 +00004144
Richard Smithbfdb1082012-03-12 08:56:40 +00004145 // Enum definitions should not be parsed in a trailing-return-type.
Faisal Vali7db85c52017-12-31 00:06:40 +00004146 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
Richard Smithbfdb1082012-03-12 08:56:40 +00004147
4148 bool AllowFixedUnderlyingType = AllowDeclaration &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004149 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
Richard Smithbfdb1082012-03-12 08:56:40 +00004150 getLangOpts().ObjC2);
John McCallcb432fa2011-07-06 05:58:41 +00004151
Abramo Bagnarad7548482010-05-19 21:37:53 +00004152 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004153 if (getLangOpts().CPlusPlus) {
John McCallcb432fa2011-07-06 05:58:41 +00004154 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4155 // if a fixed underlying type is allowed.
4156 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
Chad Rosierc1183952012-06-26 22:30:43 +00004157
Nico Webercfaa4cd2015-02-15 07:26:13 +00004158 CXXScopeSpec Spec;
David Blaikieefdccaa2016-01-15 23:43:34 +00004159 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
Richard Smith1d4b2e12013-04-01 21:43:41 +00004160 /*EnteringContext=*/true))
John McCall1f476a12010-02-26 08:45:28 +00004161 return;
4162
Nico Webercfaa4cd2015-02-15 07:26:13 +00004163 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004164 Diag(Tok, diag::err_expected) << tok::identifier;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004165 if (Tok.isNot(tok::l_brace)) {
4166 // Has no name and is not a definition.
4167 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004168 SkipUntil(tok::comma, StopAtSemi);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004169 return;
4170 }
4171 }
Nico Webercfaa4cd2015-02-15 07:26:13 +00004172
4173 SS = Spec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004174 }
Mike Stump11289f42009-09-09 15:08:12 +00004175
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004176 // Must have either 'enum name' or 'enum {...}'.
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004177 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
Richard Smithbfdb1082012-03-12 08:56:40 +00004178 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
Alp Tokerec543272013-12-24 09:48:30 +00004179 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
Mike Stump11289f42009-09-09 15:08:12 +00004180
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004181 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004182 SkipUntil(tok::comma, StopAtSemi);
Chris Lattner3b561a32006-08-13 00:12:11 +00004183 return;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004184 }
Mike Stump11289f42009-09-09 15:08:12 +00004185
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004186 // If an identifier is present, consume and remember it.
Craig Topper161e4db2014-05-21 06:02:52 +00004187 IdentifierInfo *Name = nullptr;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004188 SourceLocation NameLoc;
4189 if (Tok.is(tok::identifier)) {
4190 Name = Tok.getIdentifierInfo();
4191 NameLoc = ConsumeToken();
4192 }
Mike Stump11289f42009-09-09 15:08:12 +00004193
Richard Smith0f8ee222012-01-10 01:33:14 +00004194 if (!Name && ScopedEnumKWLoc.isValid()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00004195 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4196 // declaration of a scoped enumeration.
4197 Diag(Tok, diag::err_scoped_enum_missing_identifier);
Richard Smith0f8ee222012-01-10 01:33:14 +00004198 ScopedEnumKWLoc = SourceLocation();
Abramo Bagnara0e05e242010-12-03 18:54:17 +00004199 IsScopedUsingClassTag = false;
Douglas Gregor0bf31402010-10-08 23:50:27 +00004200 }
4201
John McCall6347b682012-05-07 06:16:58 +00004202 // Okay, end the suppression area. We'll decide whether to emit the
4203 // diagnostics in a second.
4204 if (shouldDelayDiagsInTag)
4205 diagsFromTag.done();
Richard Smith7d137e32012-03-23 03:33:32 +00004206
Douglas Gregor0bf31402010-10-08 23:50:27 +00004207 TypeResult BaseType;
4208
Douglas Gregord1f69f62010-12-01 17:42:47 +00004209 // Parse the fixed underlying type.
Richard Smith200f47c2012-07-02 19:14:01 +00004210 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004211 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004212 bool PossibleBitfield = false;
Richard Smith200f47c2012-07-02 19:14:01 +00004213 if (CanBeBitfield) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004214 // If we're in class scope, this can either be an enum declaration with
4215 // an underlying type, or a declaration of a bitfield member. We try to
4216 // use a simple disambiguation scheme first to catch the common cases
Chad Rosierc1183952012-06-26 22:30:43 +00004217 // (integer literal, sizeof); if it's still ambiguous, we then consider
4218 // anything that's a simple-type-specifier followed by '(' as an
4219 // expression. This suffices because function types are not valid
Douglas Gregord1f69f62010-12-01 17:42:47 +00004220 // underlying types anyway.
Faisal Valid143a0c2017-04-01 21:30:49 +00004221 EnterExpressionEvaluationContext Unevaluated(
4222 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregord1f69f62010-12-01 17:42:47 +00004223 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
Chad Rosierc1183952012-06-26 22:30:43 +00004224 // If the next token starts an expression, we know we're parsing a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004225 // bit-field. This is the common case.
Richard Smithee390432014-05-16 01:56:53 +00004226 if (TPR == TPResult::True)
Douglas Gregord1f69f62010-12-01 17:42:47 +00004227 PossibleBitfield = true;
4228 // If the next token starts a type-specifier-seq, it may be either a
4229 // a fixed underlying type or the start of a function-style cast in C++;
Chad Rosierc1183952012-06-26 22:30:43 +00004230 // lookahead one more token to see if it's obvious that we have a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004231 // fixed underlying type.
Richard Smithee390432014-05-16 01:56:53 +00004232 else if (TPR == TPResult::False &&
Douglas Gregord1f69f62010-12-01 17:42:47 +00004233 GetLookAheadToken(2).getKind() == tok::semi) {
4234 // Consume the ':'.
4235 ConsumeToken();
4236 } else {
4237 // We have the start of a type-specifier-seq, so we have to perform
4238 // tentative parsing to determine whether we have an expression or a
4239 // type.
4240 TentativeParsingAction TPA(*this);
4241
4242 // Consume the ':'.
4243 ConsumeToken();
Richard Smith1e3b0f02012-02-23 01:36:12 +00004244
4245 // If we see a type specifier followed by an open-brace, we have an
4246 // ambiguity between an underlying type and a C++11 braced
4247 // function-style cast. Resolve this by always treating it as an
4248 // underlying type.
4249 // FIXME: The standard is not entirely clear on how to disambiguate in
4250 // this case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004251 if ((getLangOpts().CPlusPlus &&
Richard Smithee390432014-05-16 01:56:53 +00004252 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00004253 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004254 // We'll parse this as a bitfield later.
4255 PossibleBitfield = true;
4256 TPA.Revert();
4257 } else {
4258 // We have a type-specifier-seq.
4259 TPA.Commit();
4260 }
4261 }
4262 } else {
4263 // Consume the ':'.
4264 ConsumeToken();
4265 }
4266
4267 if (!PossibleBitfield) {
4268 SourceRange Range;
4269 BaseType = ParseTypeName(&Range);
Chad Rosierc1183952012-06-26 22:30:43 +00004270
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004271 if (getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00004272 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004273 } else if (!getLangOpts().ObjC2) {
4274 if (getLangOpts().CPlusPlus)
4275 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
4276 else
4277 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
4278 }
Douglas Gregord1f69f62010-12-01 17:42:47 +00004279 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004280 }
4281
Richard Smith0f8ee222012-01-10 01:33:14 +00004282 // There are four options here. If we have 'friend enum foo;' then this is a
4283 // friend declaration, and cannot have an accompanying definition. If we have
4284 // 'enum foo;', then this is a forward declaration. If we have
4285 // 'enum foo {...' then this is a definition. Otherwise we have something
4286 // like 'enum foo xyz', a reference.
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004287 //
4288 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4289 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4290 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4291 //
John McCallfaf5fb42010-08-26 23:41:50 +00004292 Sema::TagUseKind TUK;
John McCall6347b682012-05-07 06:16:58 +00004293 if (!AllowDeclaration) {
Richard Smithbfdb1082012-03-12 08:56:40 +00004294 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004295 } else if (Tok.is(tok::l_brace)) {
4296 if (DS.isFriendSpecified()) {
4297 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4298 << SourceRange(DS.getFriendSpecLoc());
4299 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004300 SkipUntil(tok::r_brace, StopAtSemi);
John McCall6347b682012-05-07 06:16:58 +00004301 TUK = Sema::TUK_Friend;
4302 } else {
4303 TUK = Sema::TUK_Definition;
4304 }
Richard Smith649c7b062014-01-08 00:56:48 +00004305 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00004306 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00004307 (Tok.isAtStartOfLine() &&
4308 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
Richard Smith369b9f92012-06-25 21:37:02 +00004309 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4310 if (Tok.isNot(tok::semi)) {
4311 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00004312 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004313 PP.EnterToken(Tok);
4314 Tok.setKind(tok::semi);
4315 }
John McCall6347b682012-05-07 06:16:58 +00004316 } else {
John McCallfaf5fb42010-08-26 23:41:50 +00004317 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004318 }
4319
4320 // If this is an elaborated type specifier, and we delayed
4321 // diagnostics before, just merge them into the current pool.
4322 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4323 diagsFromTag.redelay();
4324 }
Richard Smith7d137e32012-03-23 03:33:32 +00004325
4326 MultiTemplateParamsArg TParams;
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004327 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
John McCallfaf5fb42010-08-26 23:41:50 +00004328 TUK != Sema::TUK_Reference) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004329 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
Richard Smith7d137e32012-03-23 03:33:32 +00004330 // Skip the rest of this declarator, up until the comma or semicolon.
4331 Diag(Tok, diag::err_enum_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004332 SkipUntil(tok::comma, StopAtSemi);
Richard Smith7d137e32012-03-23 03:33:32 +00004333 return;
4334 }
4335
4336 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4337 // Enumerations can't be explicitly instantiated.
4338 DS.SetTypeSpecError();
4339 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4340 return;
4341 }
4342
4343 assert(TemplateInfo.TemplateParams && "no template parameters");
4344 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4345 TemplateInfo.TemplateParams->size());
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004346 }
Chad Rosierc1183952012-06-26 22:30:43 +00004347
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004348 if (TUK == Sema::TUK_Reference)
4349 ProhibitAttributes(attrs);
Richard Smith7d137e32012-03-23 03:33:32 +00004350
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004351 if (!Name && TUK != Sema::TUK_Definition) {
4352 Diag(Tok, diag::err_enumerator_unnamed_no_def);
Richard Smith7d137e32012-03-23 03:33:32 +00004353
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004354 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004355 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004356 return;
4357 }
Richard Smith7d137e32012-03-23 03:33:32 +00004358
Nico Weber32a0fc72016-09-03 03:01:32 +00004359 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00004360
Richard Smithd9ba2242015-05-07 03:54:19 +00004361 Sema::SkipBodyInfo SkipBody;
4362 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4363 NextToken().is(tok::identifier))
4364 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4365 NextToken().getIdentifierInfo(),
4366 NextToken().getLocation());
4367
Douglas Gregord6ab8742009-05-28 23:31:59 +00004368 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004369 bool IsDependent = false;
Craig Topper161e4db2014-05-21 06:02:52 +00004370 const char *PrevSpec = nullptr;
Douglas Gregorba41d012010-04-24 16:38:41 +00004371 unsigned DiagID;
Faisal Vali7db85c52017-12-31 00:06:40 +00004372 Decl *TagDecl = Actions.ActOnTag(
4373 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
Erich Keanec480f302018-07-12 21:09:05 +00004374 attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4375 ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
Faisal Vali7db85c52017-12-31 00:06:40 +00004376 DSC == DeclSpecContext::DSC_type_specifier,
4377 DSC == DeclSpecContext::DSC_template_param ||
4378 DSC == DeclSpecContext::DSC_template_type_arg,
4379 &SkipBody);
Richard Smithd9ba2242015-05-07 03:54:19 +00004380
4381 if (SkipBody.ShouldSkip) {
4382 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4383
4384 BalancedDelimiterTracker T(*this, tok::l_brace);
4385 T.consumeOpen();
4386 T.skipToEnd();
4387
4388 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4389 NameLoc.isValid() ? NameLoc : StartLoc,
4390 PrevSpec, DiagID, TagDecl, Owned,
4391 Actions.getASTContext().getPrintingPolicy()))
4392 Diag(StartLoc, DiagID) << PrevSpec;
4393 return;
4394 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004395
Douglas Gregorba41d012010-04-24 16:38:41 +00004396 if (IsDependent) {
Chad Rosierc1183952012-06-26 22:30:43 +00004397 // This enum has a dependent nested-name-specifier. Handle it as a
Douglas Gregorba41d012010-04-24 16:38:41 +00004398 // dependent tag.
4399 if (!Name) {
4400 DS.SetTypeSpecError();
4401 Diag(Tok, diag::err_expected_type_name_after_typename);
4402 return;
4403 }
Chad Rosierc1183952012-06-26 22:30:43 +00004404
Nico Weber83ea0122014-05-03 21:57:40 +00004405 TypeResult Type = Actions.ActOnDependentTag(
4406 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
Douglas Gregorba41d012010-04-24 16:38:41 +00004407 if (Type.isInvalid()) {
4408 DS.SetTypeSpecError();
4409 return;
4410 }
Chad Rosierc1183952012-06-26 22:30:43 +00004411
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004412 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4413 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004414 PrevSpec, DiagID, Type.get(),
4415 Actions.getASTContext().getPrintingPolicy()))
Douglas Gregorba41d012010-04-24 16:38:41 +00004416 Diag(StartLoc, DiagID) << PrevSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00004417
Douglas Gregorba41d012010-04-24 16:38:41 +00004418 return;
4419 }
Mike Stump11289f42009-09-09 15:08:12 +00004420
John McCall48871652010-08-21 09:40:31 +00004421 if (!TagDecl) {
Chad Rosierc1183952012-06-26 22:30:43 +00004422 // The action failed to produce an enumeration tag. If this is a
Douglas Gregorba41d012010-04-24 16:38:41 +00004423 // definition, consume the entire definition.
Richard Smithbfdb1082012-03-12 08:56:40 +00004424 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
Douglas Gregorba41d012010-04-24 16:38:41 +00004425 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004426 SkipUntil(tok::r_brace, StopAtSemi);
Douglas Gregorba41d012010-04-24 16:38:41 +00004427 }
Chad Rosierc1183952012-06-26 22:30:43 +00004428
Douglas Gregorba41d012010-04-24 16:38:41 +00004429 DS.SetTypeSpecError();
4430 return;
4431 }
Richard Smith0f8ee222012-01-10 01:33:14 +00004432
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004433 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4434 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4435 ParseEnumBody(StartLoc, D);
4436 if (SkipBody.CheckSameAsPrevious &&
4437 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4438 DS.SetTypeSpecError();
4439 return;
4440 }
4441 }
Mike Stump11289f42009-09-09 15:08:12 +00004442
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004443 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4444 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004445 PrevSpec, DiagID, TagDecl, Owned,
4446 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00004447 Diag(StartLoc, DiagID) << PrevSpec;
Chris Lattner3b561a32006-08-13 00:12:11 +00004448}
4449
Chris Lattnerc1915e22007-01-25 07:29:02 +00004450/// ParseEnumBody - Parse a {} enclosed enumerator-list.
4451/// enumerator-list:
4452/// enumerator
4453/// enumerator-list ',' enumerator
4454/// enumerator:
Aaron Ballman730476b2014-11-08 15:33:35 +00004455/// enumeration-constant attributes[opt]
4456/// enumeration-constant attributes[opt] '=' constant-expression
Chris Lattnerc1915e22007-01-25 07:29:02 +00004457/// enumeration-constant:
4458/// identifier
4459///
John McCall48871652010-08-21 09:40:31 +00004460void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004461 // Enter the scope of the enum body and start the definition.
Hans Wennborgfe781452014-06-17 00:00:18 +00004462 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004463 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
Douglas Gregor07665a62009-01-05 19:45:36 +00004464
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004465 BalancedDelimiterTracker T(*this, tok::l_brace);
4466 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00004467
Chris Lattner37256fb2007-08-27 17:24:30 +00004468 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
David Blaikiebbafb8a2012-03-11 07:00:24 +00004469 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
Richard Smithf8812672016-12-02 22:38:31 +00004470 Diag(Tok, diag::err_empty_enum);
Mike Stump11289f42009-09-09 15:08:12 +00004471
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004472 SmallVector<Decl *, 32> EnumConstantDecls;
Jordan Rose60ac3162015-04-30 17:20:30 +00004473 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
Chris Lattnerc1915e22007-01-25 07:29:02 +00004474
Craig Topper161e4db2014-05-21 06:02:52 +00004475 Decl *LastEnumConstDecl = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004476
Chris Lattnerc1915e22007-01-25 07:29:02 +00004477 // Parse the enumerator-list.
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004478 while (Tok.isNot(tok::r_brace)) {
4479 // Parse enumerator. If failed, try skipping till the start of the next
4480 // enumerator definition.
4481 if (Tok.isNot(tok::identifier)) {
4482 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4483 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4484 TryConsumeToken(tok::comma))
4485 continue;
4486 break;
4487 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004488 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4489 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00004490
John McCall811a0f52010-10-22 23:36:17 +00004491 // If attributes exist after the enumerator, parse them.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004492 ParsedAttributesWithRange attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004493 MaybeParseGNUAttributes(attrs);
Aaron Ballman730476b2014-11-08 15:33:35 +00004494 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
Aaron Ballman606093a2017-10-15 15:01:42 +00004495 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4496 if (getLangOpts().CPlusPlus)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004497 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Aaron Ballman606093a2017-10-15 15:01:42 +00004498 ? diag::warn_cxx14_compat_ns_enum_attribute
4499 : diag::ext_ns_enum_attribute)
4500 << 1 /*enumerator*/;
Aaron Ballman730476b2014-11-08 15:33:35 +00004501 ParseCXX11Attributes(attrs);
4502 }
John McCall811a0f52010-10-22 23:36:17 +00004503
Chris Lattnerc1915e22007-01-25 07:29:02 +00004504 SourceLocation EqualLoc;
John McCalldadc5752010-08-24 06:29:42 +00004505 ExprResult AssignedVal;
Jordan Rose60ac3162015-04-30 17:20:30 +00004506 EnumAvailabilityDiags.emplace_back(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00004507
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004508 if (TryConsumeToken(tok::equal, EqualLoc)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004509 AssignedVal = ParseConstantExpression();
4510 if (AssignedVal.isInvalid())
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004511 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
Chris Lattnerc1915e22007-01-25 07:29:02 +00004512 }
Mike Stump11289f42009-09-09 15:08:12 +00004513
Chris Lattnerc1915e22007-01-25 07:29:02 +00004514 // Install the enumerator constant into EnumDecl.
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004515 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
Erich Keanec480f302018-07-12 21:09:05 +00004516 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4517 EqualLoc, AssignedVal.get());
Jordan Rose60ac3162015-04-30 17:20:30 +00004518 EnumAvailabilityDiags.back().done();
Chad Rosierc1183952012-06-26 22:30:43 +00004519
Chris Lattner4ef40012007-06-11 01:28:17 +00004520 EnumConstantDecls.push_back(EnumConstDecl);
4521 LastEnumConstDecl = EnumConstDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004522
Douglas Gregorce66d022010-09-07 14:51:08 +00004523 if (Tok.is(tok::identifier)) {
4524 // We're missing a comma between enumerators.
Richard Smithbdb84f32016-07-22 23:36:59 +00004525 SourceLocation Loc = getEndOfPreviousToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004526 Diag(Loc, diag::err_enumerator_list_missing_comma)
Douglas Gregorce66d022010-09-07 14:51:08 +00004527 << FixItHint::CreateInsertion(Loc, ", ");
4528 continue;
4529 }
Chad Rosierc1183952012-06-26 22:30:43 +00004530
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004531 // Emumerator definition must be finished, only comma or r_brace are
4532 // allowed here.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004533 SourceLocation CommaLoc;
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004534 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4535 if (EqualLoc.isValid())
4536 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4537 << tok::comma;
4538 else
4539 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4540 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4541 if (TryConsumeToken(tok::comma, CommaLoc))
4542 continue;
4543 } else {
4544 break;
4545 }
4546 }
Mike Stump11289f42009-09-09 15:08:12 +00004547
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004548 // If comma is followed by r_brace, emit appropriate warning.
4549 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004550 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
Richard Smith87f5dc52012-07-23 05:45:25 +00004551 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4552 diag::ext_enumerator_list_comma_cxx :
4553 diag::ext_enumerator_list_comma_c)
Richard Smith5d164bc2011-10-15 05:09:34 +00004554 << FixItHint::CreateRemoval(CommaLoc);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004555 else if (getLangOpts().CPlusPlus11)
Richard Smith5d164bc2011-10-15 05:09:34 +00004556 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4557 << FixItHint::CreateRemoval(CommaLoc);
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004558 break;
Richard Smith5d164bc2011-10-15 05:09:34 +00004559 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004560 }
Mike Stump11289f42009-09-09 15:08:12 +00004561
Chris Lattnerc1915e22007-01-25 07:29:02 +00004562 // Eat the }.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004563 T.consumeClose();
Chris Lattnerc1915e22007-01-25 07:29:02 +00004564
Chris Lattnerc1915e22007-01-25 07:29:02 +00004565 // If attributes exist after the identifier list, parse them.
John McCall084e83d2011-03-24 11:26:52 +00004566 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004567 MaybeParseGNUAttributes(attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004568
Erich Keanec480f302018-07-12 21:09:05 +00004569 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4570 getCurScope(), attrs);
Mike Stump11289f42009-09-09 15:08:12 +00004571
Jordan Rose60ac3162015-04-30 17:20:30 +00004572 // Now handle enum constant availability diagnostics.
4573 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4574 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4575 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4576 EnumAvailabilityDiags[i].redelay();
4577 PD.complete(EnumConstantDecls[i]);
4578 }
4579
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004580 EnumScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004581 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
Richard Smith369b9f92012-06-25 21:37:02 +00004582
4583 // The next token must be valid after an enum definition. If not, a ';'
4584 // was probably forgotten.
Richard Smith200f47c2012-07-02 19:14:01 +00004585 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4586 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
Alp Toker383d2c42014-01-01 03:08:43 +00004587 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004588 // Push this token back into the preprocessor and change our current token
4589 // to ';' so that the rest of the code recovers as though there were an
4590 // ';' after the definition.
4591 PP.EnterToken(Tok);
4592 Tok.setKind(tok::semi);
4593 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004594}
Chris Lattner3b561a32006-08-13 00:12:11 +00004595
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004596/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4597/// is definitely a type-specifier. Return false if it isn't part of a type
4598/// specifier or if we're not sure.
4599bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4600 switch (Tok.getKind()) {
4601 default: return false;
4602 // type-specifiers
4603 case tok::kw_short:
4604 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004605 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004606 case tok::kw___int128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004607 case tok::kw_signed:
4608 case tok::kw_unsigned:
4609 case tok::kw__Complex:
4610 case tok::kw__Imaginary:
4611 case tok::kw_void:
4612 case tok::kw_char:
4613 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004614 case tok::kw_char8_t:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004615 case tok::kw_char16_t:
4616 case tok::kw_char32_t:
4617 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004618 case tok::kw_half:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004619 case tok::kw_float:
4620 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004621 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004622 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004623 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004624 case tok::kw___float128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004625 case tok::kw_bool:
4626 case tok::kw__Bool:
4627 case tok::kw__Decimal32:
4628 case tok::kw__Decimal64:
4629 case tok::kw__Decimal128:
4630 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004631#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004632#include "clang/Basic/OpenCLImageTypes.def"
Chad Rosierc1183952012-06-26 22:30:43 +00004633
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004634 // struct-or-union-specifier (C99) or class-specifier (C++)
4635 case tok::kw_class:
4636 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004637 case tok::kw___interface:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004638 case tok::kw_union:
4639 // enum-specifier
4640 case tok::kw_enum:
Chad Rosierc1183952012-06-26 22:30:43 +00004641
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004642 // typedef-name
4643 case tok::annot_typename:
4644 return true;
4645 }
4646}
4647
Steve Naroff69e8f9e2008-02-11 23:15:56 +00004648/// isTypeSpecifierQualifier - Return true if the current token could be the
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004649/// start of a specifier-qualifier-list.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004650bool Parser::isTypeSpecifierQualifier() {
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004651 switch (Tok.getKind()) {
4652 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004653
Chris Lattner020bab92009-01-04 23:41:41 +00004654 case tok::identifier: // foo::bar
John Thompson22334602010-02-05 00:12:22 +00004655 if (TryAltiVecVectorToken())
4656 return true;
4657 // Fall through.
Douglas Gregor333489b2009-03-27 23:10:48 +00004658 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004659 // Annotate typenames and C++ scope specifiers. If we get one, just
4660 // recurse to handle whatever we get.
4661 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004662 return true;
4663 if (Tok.is(tok::identifier))
4664 return false;
4665 return isTypeSpecifierQualifier();
Douglas Gregor333489b2009-03-27 23:10:48 +00004666
Chris Lattner020bab92009-01-04 23:41:41 +00004667 case tok::coloncolon: // ::foo::bar
4668 if (NextToken().is(tok::kw_new) || // ::new
4669 NextToken().is(tok::kw_delete)) // ::delete
4670 return false;
4671
Chris Lattner020bab92009-01-04 23:41:41 +00004672 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004673 return true;
4674 return isTypeSpecifierQualifier();
Mike Stump11289f42009-09-09 15:08:12 +00004675
Chris Lattnere37e2332006-08-15 04:50:22 +00004676 // GNU attributes support.
4677 case tok::kw___attribute:
Steve Naroffad373bd2007-07-31 12:34:36 +00004678 // GNU typeof support.
4679 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004680
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004681 // type-specifiers
4682 case tok::kw_short:
4683 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004684 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004685 case tok::kw___int128:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004686 case tok::kw_signed:
4687 case tok::kw_unsigned:
4688 case tok::kw__Complex:
4689 case tok::kw__Imaginary:
4690 case tok::kw_void:
4691 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004692 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004693 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004694 case tok::kw_char16_t:
4695 case tok::kw_char32_t:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004696 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004697 case tok::kw_half:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004698 case tok::kw_float:
4699 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004700 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004701 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004702 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004703 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004704 case tok::kw_bool:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004705 case tok::kw__Bool:
4706 case tok::kw__Decimal32:
4707 case tok::kw__Decimal64:
4708 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004709 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004710#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004711#include "clang/Basic/OpenCLImageTypes.def"
Mike Stump11289f42009-09-09 15:08:12 +00004712
Chris Lattner861a2262008-04-13 18:59:07 +00004713 // struct-or-union-specifier (C99) or class-specifier (C++)
4714 case tok::kw_class:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004715 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004716 case tok::kw___interface:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004717 case tok::kw_union:
4718 // enum-specifier
4719 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004720
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004721 // type-qualifier
4722 case tok::kw_const:
4723 case tok::kw_volatile:
4724 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004725 case tok::kw__Sat:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004726
John McCallea0a39e2012-11-14 00:49:39 +00004727 // Debugger support.
4728 case tok::kw___unknown_anytype:
4729
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004730 // typedef-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00004731 case tok::annot_typename:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004732 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004733
Chris Lattner409bf7d2008-10-20 00:25:30 +00004734 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4735 case tok::less:
David Blaikiebbafb8a2012-03-11 07:00:24 +00004736 return getLangOpts().ObjC1;
Mike Stump11289f42009-09-09 15:08:12 +00004737
Steve Naroff44ac7772008-12-25 14:16:32 +00004738 case tok::kw___cdecl:
4739 case tok::kw___stdcall:
4740 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004741 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004742 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004743 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004744 case tok::kw___w64:
4745 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004746 case tok::kw___ptr32:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004747 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004748 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004749
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004750 case tok::kw__Nonnull:
4751 case tok::kw__Nullable:
4752 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004753
Douglas Gregorab209d82015-07-07 03:58:42 +00004754 case tok::kw___kindof:
4755
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004756 case tok::kw___private:
4757 case tok::kw___local:
4758 case tok::kw___global:
4759 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004760 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004761 case tok::kw___read_only:
4762 case tok::kw___read_write:
4763 case tok::kw___write_only:
4764
Eli Friedman53339e02009-06-08 23:27:34 +00004765 return true;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004766
Richard Smith8e1ac332013-03-28 01:55:44 +00004767 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004768 case tok::kw__Atomic:
4769 return true;
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004770 }
4771}
4772
Chris Lattneracd58a32006-08-06 17:24:14 +00004773/// isDeclarationSpecifier() - Return true if the current token is part of a
4774/// declaration specifier.
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004775///
4776/// \param DisambiguatingWithExpression True to indicate that the purpose of
4777/// this check is to disambiguate between an expression and a declaration.
4778bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
Chris Lattneracd58a32006-08-06 17:24:14 +00004779 switch (Tok.getKind()) {
4780 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004781
Xiuli Pan9c14e282016-01-09 12:53:17 +00004782 case tok::kw_pipe:
4783 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4784
Chris Lattner020bab92009-01-04 23:41:41 +00004785 case tok::identifier: // foo::bar
Steve Naroff9527bbf2009-03-09 21:12:44 +00004786 // Unfortunate hack to support "Class.factoryMethod" notation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004787 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
Steve Naroff9527bbf2009-03-09 21:12:44 +00004788 return false;
John Thompson22334602010-02-05 00:12:22 +00004789 if (TryAltiVecVectorToken())
4790 return true;
4791 // Fall through.
David Blaikie15a430a2011-12-04 05:04:18 +00004792 case tok::kw_decltype: // decltype(T())::type
Douglas Gregor333489b2009-03-27 23:10:48 +00004793 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004794 // Annotate typenames and C++ scope specifiers. If we get one, just
4795 // recurse to handle whatever we get.
4796 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004797 return true;
4798 if (Tok.is(tok::identifier))
4799 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004800
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004801 // If we're in Objective-C and we have an Objective-C class type followed
Chad Rosierc1183952012-06-26 22:30:43 +00004802 // by an identifier and then either ':' or ']', in a place where an
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004803 // expression is permitted, then this is probably a class message send
4804 // missing the initial '['. In this case, we won't consider this to be
4805 // the start of a declaration.
Chad Rosierc1183952012-06-26 22:30:43 +00004806 if (DisambiguatingWithExpression &&
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004807 isStartOfObjCClassMessageMissingOpenBracket())
4808 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004809
John McCall1f476a12010-02-26 08:45:28 +00004810 return isDeclarationSpecifier();
4811
Chris Lattner020bab92009-01-04 23:41:41 +00004812 case tok::coloncolon: // ::foo::bar
4813 if (NextToken().is(tok::kw_new) || // ::new
4814 NextToken().is(tok::kw_delete)) // ::delete
4815 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004816
Chris Lattner020bab92009-01-04 23:41:41 +00004817 // Annotate typenames and C++ scope specifiers. If we get one, just
4818 // recurse to handle whatever we get.
4819 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004820 return true;
4821 return isDeclarationSpecifier();
Mike Stump11289f42009-09-09 15:08:12 +00004822
Chris Lattneracd58a32006-08-06 17:24:14 +00004823 // storage-class-specifier
4824 case tok::kw_typedef:
4825 case tok::kw_extern:
Steve Naroff2050b0d2007-12-18 00:16:02 +00004826 case tok::kw___private_extern__:
Chris Lattneracd58a32006-08-06 17:24:14 +00004827 case tok::kw_static:
4828 case tok::kw_auto:
Richard Smithe301ba22015-11-11 02:02:15 +00004829 case tok::kw___auto_type:
Chris Lattneracd58a32006-08-06 17:24:14 +00004830 case tok::kw_register:
4831 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00004832 case tok::kw_thread_local:
4833 case tok::kw__Thread_local:
Mike Stump11289f42009-09-09 15:08:12 +00004834
Douglas Gregor26701a42011-09-09 02:06:17 +00004835 // Modules
4836 case tok::kw___module_private__:
Chad Rosierc1183952012-06-26 22:30:43 +00004837
John McCallea0a39e2012-11-14 00:49:39 +00004838 // Debugger support
4839 case tok::kw___unknown_anytype:
4840
Chris Lattneracd58a32006-08-06 17:24:14 +00004841 // type-specifiers
4842 case tok::kw_short:
4843 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004844 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004845 case tok::kw___int128:
Chris Lattneracd58a32006-08-06 17:24:14 +00004846 case tok::kw_signed:
4847 case tok::kw_unsigned:
4848 case tok::kw__Complex:
4849 case tok::kw__Imaginary:
4850 case tok::kw_void:
4851 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004852 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004853 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004854 case tok::kw_char16_t:
4855 case tok::kw_char32_t:
4856
Chris Lattneracd58a32006-08-06 17:24:14 +00004857 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004858 case tok::kw_half:
Chris Lattneracd58a32006-08-06 17:24:14 +00004859 case tok::kw_float:
4860 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004861 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004862 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004863 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004864 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004865 case tok::kw_bool:
Chris Lattneracd58a32006-08-06 17:24:14 +00004866 case tok::kw__Bool:
4867 case tok::kw__Decimal32:
4868 case tok::kw__Decimal64:
4869 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004870 case tok::kw___vector:
Mike Stump11289f42009-09-09 15:08:12 +00004871
Chris Lattner861a2262008-04-13 18:59:07 +00004872 // struct-or-union-specifier (C99) or class-specifier (C++)
4873 case tok::kw_class:
Chris Lattneracd58a32006-08-06 17:24:14 +00004874 case tok::kw_struct:
4875 case tok::kw_union:
Joao Matosdc86f942012-08-31 18:45:21 +00004876 case tok::kw___interface:
Chris Lattneracd58a32006-08-06 17:24:14 +00004877 // enum-specifier
4878 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004879
Chris Lattneracd58a32006-08-06 17:24:14 +00004880 // type-qualifier
4881 case tok::kw_const:
4882 case tok::kw_volatile:
4883 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004884 case tok::kw__Sat:
Steve Naroffad373bd2007-07-31 12:34:36 +00004885
Chris Lattneracd58a32006-08-06 17:24:14 +00004886 // function-specifier
4887 case tok::kw_inline:
Douglas Gregor61956c42008-10-31 09:07:45 +00004888 case tok::kw_virtual:
4889 case tok::kw_explicit:
Richard Smith0015f092013-01-17 22:16:11 +00004890 case tok::kw__Noreturn:
Chris Lattner7b20dc72007-08-09 16:40:21 +00004891
Richard Smith1dba27c2013-01-29 09:02:09 +00004892 // alignment-specifier
4893 case tok::kw__Alignas:
4894
Richard Smithd16fe122012-10-25 00:00:53 +00004895 // friend keyword.
4896 case tok::kw_friend:
4897
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00004898 // static_assert-declaration
4899 case tok::kw__Static_assert:
4900
Chris Lattner599e47e2007-08-09 17:01:07 +00004901 // GNU typeof support.
4902 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004903
Chris Lattner599e47e2007-08-09 17:01:07 +00004904 // GNU attributes.
Chris Lattner7b20dc72007-08-09 16:40:21 +00004905 case tok::kw___attribute:
Mike Stump11289f42009-09-09 15:08:12 +00004906
Richard Smithd16fe122012-10-25 00:00:53 +00004907 // C++11 decltype and constexpr.
David Blaikie15a430a2011-12-04 05:04:18 +00004908 case tok::annot_decltype:
Richard Smithd16fe122012-10-25 00:00:53 +00004909 case tok::kw_constexpr:
Francois Pichete878cb62011-06-19 08:02:06 +00004910
Richard Smith8e1ac332013-03-28 01:55:44 +00004911 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004912 case tok::kw__Atomic:
4913 return true;
4914
Chris Lattner8b2ec162008-07-26 03:38:44 +00004915 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4916 case tok::less:
David Blaikiebbafb8a2012-03-11 07:00:24 +00004917 return getLangOpts().ObjC1;
Mike Stump11289f42009-09-09 15:08:12 +00004918
Douglas Gregor19b7acf2011-04-27 05:41:15 +00004919 // typedef-name
4920 case tok::annot_typename:
4921 return !DisambiguatingWithExpression ||
4922 !isStartOfObjCClassMessageMissingOpenBracket();
Chad Rosierc1183952012-06-26 22:30:43 +00004923
Steve Narofff192fab2009-01-06 19:34:12 +00004924 case tok::kw___declspec:
Steve Naroff44ac7772008-12-25 14:16:32 +00004925 case tok::kw___cdecl:
4926 case tok::kw___stdcall:
4927 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004928 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004929 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004930 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004931 case tok::kw___w64:
Aaron Ballman317a77f2013-05-22 23:25:32 +00004932 case tok::kw___sptr:
4933 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00004934 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004935 case tok::kw___ptr32:
Eli Friedman53339e02009-06-08 23:27:34 +00004936 case tok::kw___forceinline:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004937 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004938 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004939
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004940 case tok::kw__Nonnull:
4941 case tok::kw__Nullable:
4942 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004943
Douglas Gregorab209d82015-07-07 03:58:42 +00004944 case tok::kw___kindof:
4945
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004946 case tok::kw___private:
4947 case tok::kw___local:
4948 case tok::kw___global:
4949 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004950 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004951 case tok::kw___read_only:
4952 case tok::kw___read_write:
4953 case tok::kw___write_only:
Alexey Bader954ba212016-04-08 13:40:33 +00004954#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004955#include "clang/Basic/OpenCLImageTypes.def"
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004956
Eli Friedman53339e02009-06-08 23:27:34 +00004957 return true;
Chris Lattneracd58a32006-08-06 17:24:14 +00004958 }
4959}
4960
Richard Smith35845152017-02-07 01:37:30 +00004961bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004962 TentativeParsingAction TPA(*this);
4963
4964 // Parse the C++ scope specifier.
4965 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00004966 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00004967 /*EnteringContext=*/true)) {
John McCall1f476a12010-02-26 08:45:28 +00004968 TPA.Revert();
4969 return false;
4970 }
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004971
4972 // Parse the constructor name.
Richard Smithaf3b3252017-05-18 19:21:48 +00004973 if (Tok.is(tok::identifier)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004974 // We already know that we have a constructor name; just consume
4975 // the token.
4976 ConsumeToken();
Richard Smithaf3b3252017-05-18 19:21:48 +00004977 } else if (Tok.is(tok::annot_template_id)) {
4978 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004979 } else {
4980 TPA.Revert();
4981 return false;
4982 }
4983
Richard Smith8f8697f2017-02-08 01:16:55 +00004984 // There may be attributes here, appertaining to the constructor name or type
4985 // we just stepped past.
4986 SkipCXX11Attributes();
4987
Richard Smith43f340f2012-03-27 23:05:05 +00004988 // Current class name must be followed by a left parenthesis.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004989 if (Tok.isNot(tok::l_paren)) {
4990 TPA.Revert();
4991 return false;
4992 }
4993 ConsumeParen();
4994
Richard Smith43f340f2012-03-27 23:05:05 +00004995 // A right parenthesis, or ellipsis followed by a right parenthesis signals
4996 // that we have a constructor.
4997 if (Tok.is(tok::r_paren) ||
4998 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004999 TPA.Revert();
5000 return true;
5001 }
5002
Richard Smithf2163662013-09-06 00:12:20 +00005003 // A C++11 attribute here signals that we have a constructor, and is an
5004 // attribute on the first constructor parameter.
5005 if (getLangOpts().CPlusPlus11 &&
5006 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5007 /*OuterMightBeMessageSend*/ true)) {
5008 TPA.Revert();
5009 return true;
5010 }
5011
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005012 // If we need to, enter the specified scope.
5013 DeclaratorScopeObj DeclScopeObj(*this, SS);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005014 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005015 DeclScopeObj.EnterDeclaratorScope();
5016
Francois Pichet79f3a872011-01-31 04:54:32 +00005017 // Optionally skip Microsoft attributes.
John McCall084e83d2011-03-24 11:26:52 +00005018 ParsedAttributes Attrs(AttrFactory);
Francois Pichet79f3a872011-01-31 04:54:32 +00005019 MaybeParseMicrosoftAttributes(Attrs);
5020
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005021 // Check whether the next token(s) are part of a declaration
5022 // specifier, in which case we have the start of a parameter and,
5023 // therefore, we know that this is a constructor.
Richard Smithefd009d2012-03-27 00:56:56 +00005024 bool IsConstructor = false;
5025 if (isDeclarationSpecifier())
5026 IsConstructor = true;
5027 else if (Tok.is(tok::identifier) ||
5028 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5029 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5030 // This might be a parenthesized member name, but is more likely to
5031 // be a constructor declaration with an invalid argument type. Keep
5032 // looking.
5033 if (Tok.is(tok::annot_cxxscope))
Richard Smithaf3b3252017-05-18 19:21:48 +00005034 ConsumeAnnotationToken();
Richard Smithefd009d2012-03-27 00:56:56 +00005035 ConsumeToken();
5036
5037 // If this is not a constructor, we must be parsing a declarator,
Richard Smith1453e312012-03-27 01:42:32 +00005038 // which must have one of the following syntactic forms (see the
5039 // grammar extract at the start of ParseDirectDeclarator):
Richard Smithefd009d2012-03-27 00:56:56 +00005040 switch (Tok.getKind()) {
5041 case tok::l_paren:
5042 // C(X ( int));
5043 case tok::l_square:
5044 // C(X [ 5]);
5045 // C(X [ [attribute]]);
5046 case tok::coloncolon:
5047 // C(X :: Y);
5048 // C(X :: *p);
Richard Smithefd009d2012-03-27 00:56:56 +00005049 // Assume this isn't a constructor, rather than assuming it's a
5050 // constructor with an unnamed parameter of an ill-formed type.
5051 break;
5052
Richard Smith446161b2014-03-03 21:12:53 +00005053 case tok::r_paren:
5054 // C(X )
Richard Smith8f8697f2017-02-08 01:16:55 +00005055
5056 // Skip past the right-paren and any following attributes to get to
5057 // the function body or trailing-return-type.
5058 ConsumeParen();
5059 SkipCXX11Attributes();
5060
Richard Smith35845152017-02-07 01:37:30 +00005061 if (DeductionGuide) {
5062 // C(X) -> ... is a deduction guide.
Richard Smith8f8697f2017-02-08 01:16:55 +00005063 IsConstructor = Tok.is(tok::arrow);
Richard Smith35845152017-02-07 01:37:30 +00005064 break;
5065 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005066 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
Richard Smith446161b2014-03-03 21:12:53 +00005067 // Assume these were meant to be constructors:
5068 // C(X) : (the name of a bit-field cannot be parenthesized).
5069 // C(X) try (this is otherwise ill-formed).
5070 IsConstructor = true;
5071 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005072 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
Richard Smith446161b2014-03-03 21:12:53 +00005073 // If we have a constructor name within the class definition,
5074 // assume these were meant to be constructors:
5075 // C(X) {
5076 // C(X) ;
5077 // ... because otherwise we would be declaring a non-static data
5078 // member that is ill-formed because it's of the same type as its
5079 // surrounding class.
5080 //
5081 // FIXME: We can actually do this whether or not the name is qualified,
5082 // because if it is qualified in this context it must be being used as
Richard Smith35845152017-02-07 01:37:30 +00005083 // a constructor name.
Richard Smith446161b2014-03-03 21:12:53 +00005084 // currently, so we're somewhat conservative here.
5085 IsConstructor = IsUnqualified;
5086 }
5087 break;
5088
Richard Smithefd009d2012-03-27 00:56:56 +00005089 default:
5090 IsConstructor = true;
5091 break;
5092 }
5093 }
5094
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005095 TPA.Revert();
5096 return IsConstructor;
5097}
Chris Lattnerb9093cd2006-08-04 04:39:53 +00005098
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005099/// ParseTypeQualifierListOpt
Dawn Perchik335e16b2010-09-03 01:29:35 +00005100/// type-qualifier-list: [C99 6.7.5]
5101/// type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005102/// [vendor] attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005103/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005104/// type-qualifier-list type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005105/// [vendor] type-qualifier-list attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005106/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005107/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
Aaron Ballman08b06592014-07-22 12:44:22 +00005108/// [ only if AttReqs & AR_CXX11AttributesParsed ]
5109/// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5110/// AttrRequirements bitmask values.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005111void Parser::ParseTypeQualifierListOpt(
5112 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5113 bool IdentifierRequired,
5114 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
Aaron Ballman606093a2017-10-15 15:01:42 +00005115 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005116 isCXX11AttributeSpecifier()) {
John McCall084e83d2011-03-24 11:26:52 +00005117 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith3dff2512012-04-10 03:25:07 +00005118 ParseCXX11Attributes(attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005119 DS.takeAttributesFrom(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005120 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005121
5122 SourceLocation EndLoc;
5123
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005124 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00005125 bool isInvalid = false;
Craig Topper161e4db2014-05-21 06:02:52 +00005126 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00005127 unsigned DiagID = 0;
Chris Lattner60809f52006-11-28 05:18:46 +00005128 SourceLocation Loc = Tok.getLocation();
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005129
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005130 switch (Tok.getKind()) {
Douglas Gregor28c78432010-08-27 17:35:51 +00005131 case tok::code_completion:
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005132 if (CodeCompletionHandler)
5133 (*CodeCompletionHandler)();
5134 else
5135 Actions.CodeCompleteTypeQualifiers(DS);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00005136 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00005137
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005138 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00005139 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005140 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005141 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005142 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00005143 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005144 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005145 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005146 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00005147 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005148 getLangOpts());
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005149 break;
Richard Smith8e1ac332013-03-28 01:55:44 +00005150 case tok::kw__Atomic:
5151 if (!AtomicAllowed)
5152 goto DoneWithTypeQuals;
5153 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5154 getLangOpts());
5155 break;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005156
5157 // OpenCL qualifiers:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005158 case tok::kw___private:
5159 case tok::kw___global:
5160 case tok::kw___local:
5161 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005162 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005163 case tok::kw___read_only:
5164 case tok::kw___write_only:
5165 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00005166 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005167 break;
5168
Andrey Bokhanko45d41322016-05-11 18:38:21 +00005169 case tok::kw___unaligned:
5170 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5171 getLangOpts());
5172 break;
Aaron Ballman317a77f2013-05-22 23:25:32 +00005173 case tok::kw___uptr:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005174 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
Alp Toker62c5b572013-11-26 01:30:10 +00005175 // with the MS modifier keyword.
Aaron Ballman08b06592014-07-22 12:44:22 +00005176 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
Alp Toker47642d22013-12-03 06:13:01 +00005177 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5178 if (TryKeywordIdentFallback(false))
5179 continue;
Alp Toker62c5b572013-11-26 01:30:10 +00005180 }
Galina Kistanova77674252017-06-01 21:15:34 +00005181 LLVM_FALLTHROUGH;
Alp Toker62c5b572013-11-26 01:30:10 +00005182 case tok::kw___sptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005183 case tok::kw___w64:
Steve Narofff9c29d42008-12-25 14:41:26 +00005184 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005185 case tok::kw___ptr32:
Steve Naroff44ac7772008-12-25 14:16:32 +00005186 case tok::kw___cdecl:
5187 case tok::kw___stdcall:
5188 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005189 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005190 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005191 case tok::kw___vectorcall:
Aaron Ballman08b06592014-07-22 12:44:22 +00005192 if (AttrReqs & AR_DeclspecAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005193 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00005194 continue;
5195 }
5196 goto DoneWithTypeQuals;
Dawn Perchik335e16b2010-09-03 01:29:35 +00005197 case tok::kw___pascal:
Aaron Ballman08b06592014-07-22 12:44:22 +00005198 if (AttrReqs & AR_VendorAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005199 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00005200 continue;
5201 }
5202 goto DoneWithTypeQuals;
Douglas Gregor261a89b2015-06-19 17:51:05 +00005203
5204 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005205 case tok::kw__Nonnull:
5206 case tok::kw__Nullable:
5207 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005208 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5209 continue;
5210
Douglas Gregorab209d82015-07-07 03:58:42 +00005211 // Objective-C 'kindof' types.
5212 case tok::kw___kindof:
5213 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
Erich Keanee891aa92018-07-13 15:07:47 +00005214 nullptr, 0, ParsedAttr::AS_Keyword);
Douglas Gregorab209d82015-07-07 03:58:42 +00005215 (void)ConsumeToken();
5216 continue;
5217
Chris Lattnere37e2332006-08-15 04:50:22 +00005218 case tok::kw___attribute:
Aaron Ballman08b06592014-07-22 12:44:22 +00005219 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5220 // When GNU attributes are expressly forbidden, diagnose their usage.
5221 Diag(Tok, diag::err_attributes_not_allowed);
5222
5223 // Parse the attributes even if they are rejected to ensure that error
5224 // recovery is graceful.
5225 if (AttrReqs & AR_GNUAttributesParsed ||
5226 AttrReqs & AR_GNUAttributesParsedAndRejected) {
John McCall53fa7142010-12-24 02:08:15 +00005227 ParseGNUAttributes(DS.getAttributes());
Chris Lattnercf0bab22008-12-18 07:02:59 +00005228 continue; // do *not* consume the next token!
5229 }
5230 // otherwise, FALL THROUGH!
Galina Kistanova77674252017-06-01 21:15:34 +00005231 LLVM_FALLTHROUGH;
Chris Lattnercf0bab22008-12-18 07:02:59 +00005232 default:
Steve Naroff44ac7772008-12-25 14:16:32 +00005233 DoneWithTypeQuals:
Chris Lattnercf0bab22008-12-18 07:02:59 +00005234 // If this is not a type-qualifier token, we're done reading type
5235 // qualifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00005236 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005237 if (EndLoc.isValid())
5238 DS.SetRangeEnd(EndLoc);
Chris Lattnercf0bab22008-12-18 07:02:59 +00005239 return;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005240 }
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00005241
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005242 // If the specifier combination wasn't legal, issue a diagnostic.
5243 if (isInvalid) {
5244 assert(PrevSpec && "Method did not return previous specifier!");
Chris Lattner6d29c102008-11-18 07:48:38 +00005245 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005246 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005247 EndLoc = ConsumeToken();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005248 }
5249}
5250
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005251/// ParseDeclarator - Parse and verify a newly-initialized declarator.
5252///
5253void Parser::ParseDeclarator(Declarator &D) {
5254 /// This implements the 'declarator' production in the C grammar, then checks
5255 /// for well-formedness and issues diagnostics.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005256 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005257}
5258
Richard Smith0b350b92014-10-28 16:55:02 +00005259static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
Faisal Vali421b2d12017-12-29 05:41:00 +00005260 DeclaratorContext TheContext) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005261 if (Kind == tok::star || Kind == tok::caret)
5262 return true;
5263
Xiuli Pan9c14e282016-01-09 12:53:17 +00005264 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5265 return true;
5266
Richard Smith0efa75c2012-03-29 01:16:42 +00005267 if (!Lang.CPlusPlus)
5268 return false;
5269
Richard Smith0b350b92014-10-28 16:55:02 +00005270 if (Kind == tok::amp)
5271 return true;
5272
5273 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5274 // But we must not parse them in conversion-type-ids and new-type-ids, since
5275 // those can be legitimately followed by a && operator.
5276 // (The same thing can in theory happen after a trailing-return-type, but
5277 // since those are a C++11 feature, there is no rejects-valid issue there.)
5278 if (Kind == tok::ampamp)
Faisal Vali421b2d12017-12-29 05:41:00 +00005279 return Lang.CPlusPlus11 ||
5280 (TheContext != DeclaratorContext::ConversionIdContext &&
5281 TheContext != DeclaratorContext::CXXNewContext);
Richard Smith0b350b92014-10-28 16:55:02 +00005282
5283 return false;
Richard Smith0efa75c2012-03-29 01:16:42 +00005284}
5285
Xiuli Pan9c14e282016-01-09 12:53:17 +00005286// Indicates whether the given declarator is a pipe declarator.
5287static bool isPipeDeclerator(const Declarator &D) {
5288 const unsigned NumTypes = D.getNumTypeObjects();
5289
5290 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5291 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5292 return true;
5293
5294 return false;
5295}
5296
Sebastian Redlbd150f42008-11-21 19:14:01 +00005297/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5298/// is parsed by the function passed to it. Pass null, and the direct-declarator
5299/// isn't parsed at all, making this function effectively parse the C++
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005300/// ptr-operator production.
5301///
Richard Smith09f76ee2011-10-19 21:33:05 +00005302/// If the grammar of this construct is extended, matching changes must also be
Richard Smith1453e312012-03-27 01:42:32 +00005303/// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5304/// isConstructorDeclarator.
Richard Smith09f76ee2011-10-19 21:33:05 +00005305///
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005306/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5307/// [C] pointer[opt] direct-declarator
5308/// [C++] direct-declarator
5309/// [C++] ptr-operator declarator
Chris Lattner6c7416c2006-08-07 00:19:33 +00005310///
5311/// pointer: [C99 6.7.5]
5312/// '*' type-qualifier-list[opt]
5313/// '*' type-qualifier-list[opt] pointer
5314///
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005315/// ptr-operator:
5316/// '*' cv-qualifier-seq[opt]
5317/// '&'
Sebastian Redled0f3b02009-03-15 22:02:01 +00005318/// [C++0x] '&&'
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005319/// [GNU] '&' restrict[opt] attributes[opt]
Sebastian Redled0f3b02009-03-15 22:02:01 +00005320/// [GNU?] '&&' restrict[opt] attributes[opt]
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005321/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
Sebastian Redlbd150f42008-11-21 19:14:01 +00005322void Parser::ParseDeclaratorInternal(Declarator &D,
5323 DirectDeclParseFunction DirectDeclParser) {
Douglas Gregor66a985d2009-08-26 14:27:30 +00005324 if (Diags.hasAllExtensionsSilenced())
5325 D.setExtension();
Chad Rosierc1183952012-06-26 22:30:43 +00005326
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005327 // C++ member pointers start with a '::' or a nested-name.
5328 // Member pointers get special handling, since there's no place for the
5329 // scope spec in the generic path below.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005330 if (getLangOpts().CPlusPlus &&
Richard Smith83c2ecf2016-02-02 23:34:49 +00005331 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
Serge Pavlov458ea762014-07-16 05:16:52 +00005332 (Tok.is(tok::identifier) &&
5333 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
Chris Lattner803802d2009-03-24 17:04:48 +00005334 Tok.is(tok::annot_cxxscope))) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005335 bool EnteringContext =
5336 D.getContext() == DeclaratorContext::FileContext ||
5337 D.getContext() == DeclaratorContext::MemberContext;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005338 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005339 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005340
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +00005341 if (SS.isNotEmpty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005342 if (Tok.isNot(tok::star)) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005343 // The scope spec really belongs to the direct-declarator.
Richard Smith5f044ad2013-01-08 22:43:49 +00005344 if (D.mayHaveIdentifier())
5345 D.getCXXScopeSpec() = SS;
5346 else
5347 AnnotateScopeToken(SS, true);
5348
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005349 if (DirectDeclParser)
5350 (this->*DirectDeclParser)(D);
5351 return;
5352 }
5353
5354 SourceLocation Loc = ConsumeToken();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005355 D.SetRangeEnd(Loc);
John McCall084e83d2011-03-24 11:26:52 +00005356 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005357 ParseTypeQualifierListOpt(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005358 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005359
5360 // Recurse to parse whatever is left.
5361 ParseDeclaratorInternal(D, DirectDeclParser);
5362
5363 // Sema will have to catch (syntactically invalid) pointers into global
5364 // scope. It has to catch pointers into namespace scope anyway.
Erich Keanec480f302018-07-12 21:09:05 +00005365 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005366 SS, DS.getTypeQualifiers(), DS.getEndLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005367 std::move(DS.getAttributes()),
5368 /* Don't replace range end. */ SourceLocation());
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005369 return;
5370 }
5371 }
5372
5373 tok::TokenKind Kind = Tok.getKind();
Xiuli Pan9c14e282016-01-09 12:53:17 +00005374
5375 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
Xiuli Pan11e13f62016-02-26 03:13:03 +00005376 DeclSpec DS(AttrFactory);
5377 ParseTypeQualifierListOpt(DS);
Xiuli Pan9c14e282016-01-09 12:53:17 +00005378
5379 D.AddTypeInfo(
5380 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
Erich Keanec480f302018-07-12 21:09:05 +00005381 std::move(DS.getAttributes()), SourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00005382 }
5383
Steve Naroffec33ed92008-08-27 16:04:49 +00005384 // Not a pointer, C++ reference, or block.
Richard Smith0b350b92014-10-28 16:55:02 +00005385 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00005386 if (DirectDeclParser)
5387 (this->*DirectDeclParser)(D);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005388 return;
5389 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005390
Sebastian Redled0f3b02009-03-15 22:02:01 +00005391 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5392 // '&&' -> rvalue reference
Sebastian Redl3b27be62009-03-23 00:00:23 +00005393 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005394 D.SetRangeEnd(Loc);
Bill Wendling3708c182007-05-27 10:15:43 +00005395
Chris Lattner9eac9312009-03-27 04:18:06 +00005396 if (Kind == tok::star || Kind == tok::caret) {
Chris Lattner788404f2008-02-21 01:32:26 +00005397 // Is a pointer.
John McCall084e83d2011-03-24 11:26:52 +00005398 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005399
Aaron Ballman08b06592014-07-22 12:44:22 +00005400 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5401 // C++11 attributes are allowed.
5402 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
Faisal Vali421b2d12017-12-29 05:41:00 +00005403 ((D.getContext() != DeclaratorContext::CXXNewContext)
5404 ? AR_GNUAttributesParsed
5405 : AR_GNUAttributesParsedAndRejected);
Aaron Ballman08b06592014-07-22 12:44:22 +00005406 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005407 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005408
Bill Wendling3708c182007-05-27 10:15:43 +00005409 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005410 ParseDeclaratorInternal(D, DirectDeclParser);
Steve Naroffec33ed92008-08-27 16:04:49 +00005411 if (Kind == tok::star)
5412 // Remember that we parsed a pointer type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005413 D.AddTypeInfo(DeclaratorChunk::getPointer(
5414 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5415 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5416 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5417 std::move(DS.getAttributes()), SourceLocation());
Steve Naroffec33ed92008-08-27 16:04:49 +00005418 else
5419 // Remember that we parsed a Block type, and remember the type-quals.
Erich Keanec480f302018-07-12 21:09:05 +00005420 D.AddTypeInfo(
5421 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5422 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005423 } else {
5424 // Is a reference
John McCall084e83d2011-03-24 11:26:52 +00005425 DeclSpec DS(AttrFactory);
Bill Wendling93efb222007-06-02 23:28:54 +00005426
Sebastian Redl3b27be62009-03-23 00:00:23 +00005427 // Complain about rvalue references in C++03, but then go on and build
5428 // the declarator.
Richard Smith5d164bc2011-10-15 05:09:34 +00005429 if (Kind == tok::ampamp)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005430 Diag(Loc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00005431 diag::warn_cxx98_compat_rvalue_reference :
5432 diag::ext_rvalue_reference);
Sebastian Redl3b27be62009-03-23 00:00:23 +00005433
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005434 // GNU-style and C++11 attributes are allowed here, as is restrict.
5435 ParseTypeQualifierListOpt(DS);
5436 D.ExtendWithDeclSpec(DS);
5437
Bill Wendling93efb222007-06-02 23:28:54 +00005438 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5439 // cv-qualifiers are introduced through the use of a typedef or of a
5440 // template type argument, in which case the cv-qualifiers are ignored.
Bill Wendling93efb222007-06-02 23:28:54 +00005441 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5442 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5443 Diag(DS.getConstSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005444 diag::err_invalid_reference_qualifier_application) << "const";
Bill Wendling93efb222007-06-02 23:28:54 +00005445 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5446 Diag(DS.getVolatileSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005447 diag::err_invalid_reference_qualifier_application) << "volatile";
Richard Smith8e1ac332013-03-28 01:55:44 +00005448 // 'restrict' is permitted as an extension.
5449 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5450 Diag(DS.getAtomicSpecLoc(),
5451 diag::err_invalid_reference_qualifier_application) << "_Atomic";
Bill Wendling93efb222007-06-02 23:28:54 +00005452 }
Bill Wendling3708c182007-05-27 10:15:43 +00005453
5454 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005455 ParseDeclaratorInternal(D, DirectDeclParser);
Bill Wendling3708c182007-05-27 10:15:43 +00005456
Douglas Gregor66583c52008-11-03 15:51:28 +00005457 if (D.getNumTypeObjects() > 0) {
5458 // C++ [dcl.ref]p4: There shall be no references to references.
5459 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5460 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
Chris Lattnerebad6a22008-11-19 07:37:42 +00005461 if (const IdentifierInfo *II = D.getIdentifier())
5462 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5463 << II;
5464 else
5465 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5466 << "type name";
Douglas Gregor66583c52008-11-03 15:51:28 +00005467
Sebastian Redlbd150f42008-11-21 19:14:01 +00005468 // Once we've complained about the reference-to-reference, we
Douglas Gregor66583c52008-11-03 15:51:28 +00005469 // can go ahead and build the (technically ill-formed)
5470 // declarator: reference collapsing will take care of it.
5471 }
5472 }
5473
Richard Smith8e1ac332013-03-28 01:55:44 +00005474 // Remember that we parsed a reference type.
Chris Lattner788404f2008-02-21 01:32:26 +00005475 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
Sebastian Redled0f3b02009-03-15 22:02:01 +00005476 Kind == tok::amp),
Erich Keanec480f302018-07-12 21:09:05 +00005477 std::move(DS.getAttributes()), SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005478 }
Chris Lattner6c7416c2006-08-07 00:19:33 +00005479}
5480
Richard Trieuf4b81d02014-06-24 23:14:24 +00005481// When correcting from misplaced brackets before the identifier, the location
5482// is saved inside the declarator so that other diagnostic messages can use
5483// them. This extracts and returns that location, or returns the provided
5484// location if a stored location does not exist.
5485static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5486 SourceLocation Loc) {
5487 if (D.getName().StartLocation.isInvalid() &&
5488 D.getName().EndLocation.isValid())
5489 return D.getName().EndLocation;
5490
5491 return Loc;
5492}
5493
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005494/// ParseDirectDeclarator
5495/// direct-declarator: [C99 6.7.5]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005496/// [C99] identifier
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005497/// '(' declarator ')'
5498/// [GNU] '(' attributes declarator ')'
Chris Lattnere8074e62006-08-06 18:30:15 +00005499/// [C90] direct-declarator '[' constant-expression[opt] ']'
5500/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5501/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5502/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5503/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005504/// [C++11] direct-declarator '[' constant-expression[opt] ']'
5505/// attribute-specifier-seq[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005506/// direct-declarator '(' parameter-type-list ')'
5507/// direct-declarator '(' identifier-list[opt] ')'
5508/// [GNU] direct-declarator '(' parameter-forward-declarations
5509/// parameter-type-list[opt] ')'
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00005510/// [C++] direct-declarator '(' parameter-declaration-clause ')'
5511/// cv-qualifier-seq[opt] exception-specification[opt]
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005512/// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5513/// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5514/// ref-qualifier[opt] exception-specification[opt]
Douglas Gregor61956c42008-10-31 09:07:45 +00005515/// [C++] declarator-id
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005516/// [C++11] declarator-id attribute-specifier-seq[opt]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005517///
5518/// declarator-id: [C++ 8]
Douglas Gregor27b4c162010-12-23 22:44:42 +00005519/// '...'[opt] id-expression
Douglas Gregor831c93f2008-11-05 20:51:48 +00005520/// '::'[opt] nested-name-specifier[opt] type-name
5521///
5522/// id-expression: [C++ 5.1]
5523/// unqualified-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005524/// qualified-id
Douglas Gregor831c93f2008-11-05 20:51:48 +00005525///
5526/// unqualified-id: [C++ 5.1]
Mike Stump11289f42009-09-09 15:08:12 +00005527/// identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005528/// operator-function-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005529/// conversion-function-id
Mike Stump11289f42009-09-09 15:08:12 +00005530/// '~' class-name
Douglas Gregor7f741122009-02-25 19:37:18 +00005531/// template-id
Argyrios Kyrtzidise4426352008-11-07 22:02:30 +00005532///
Richard Smithbdb84f32016-07-22 23:36:59 +00005533/// C++17 adds the following, which we also handle here:
5534///
5535/// simple-declaration:
5536/// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5537///
Richard Smith1453e312012-03-27 01:42:32 +00005538/// Note, any additional constructs added here may need corresponding changes
5539/// in isConstructorDeclarator.
Chris Lattneracd58a32006-08-06 17:24:14 +00005540void Parser::ParseDirectDeclarator(Declarator &D) {
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005541 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005542
David Blaikiebbafb8a2012-03-11 07:00:24 +00005543 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
Richard Smithbdb84f32016-07-22 23:36:59 +00005544 // This might be a C++17 structured binding.
5545 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5546 D.getCXXScopeSpec().isEmpty())
5547 return ParseDecompositionDeclarator(D);
5548
Serge Pavlov458ea762014-07-16 05:16:52 +00005549 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5550 // this context it is a bitfield. Also in range-based for statement colon
5551 // may delimit for-range-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00005552 ColonProtectionRAIIObject X(
5553 *this, D.getContext() == DeclaratorContext::MemberContext ||
5554 (D.getContext() == DeclaratorContext::ForContext &&
5555 getLangOpts().CPlusPlus11));
Serge Pavlov458ea762014-07-16 05:16:52 +00005556
Douglas Gregor7861a802009-11-03 01:35:08 +00005557 // ParseDeclaratorInternal might already have parsed the scope.
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005558 if (D.getCXXScopeSpec().isEmpty()) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005559 bool EnteringContext =
5560 D.getContext() == DeclaratorContext::FileContext ||
5561 D.getContext() == DeclaratorContext::MemberContext;
David Blaikieefdccaa2016-01-15 23:43:34 +00005562 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005563 EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005564 }
5565
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005566 if (D.getCXXScopeSpec().isValid()) {
Richard Smith64e033f2015-01-15 00:48:52 +00005567 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5568 D.getCXXScopeSpec()))
John McCall2b058ef2009-12-11 20:04:54 +00005569 // Change the declaration context for name lookup, until this function
5570 // is exited (and the declarator has been parsed).
5571 DeclScopeObj.EnterDeclaratorScope();
Alex Lorenze151f0102016-12-07 10:24:44 +00005572 else if (getObjCDeclContext()) {
5573 // Ensure that we don't interpret the next token as an identifier when
5574 // dealing with declarations in an Objective-C container.
5575 D.SetIdentifier(nullptr, Tok.getLocation());
5576 D.setInvalidType(true);
5577 ConsumeToken();
5578 goto PastIdentifier;
5579 }
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005580 }
5581
Douglas Gregor27b4c162010-12-23 22:44:42 +00005582 // C++0x [dcl.fct]p14:
Faisal Vali8435a692014-12-04 12:40:21 +00005583 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5584 // parameter-declaration-clause without a preceding comma. In this case,
5585 // the ellipsis is parsed as part of the abstract-declarator if the type
5586 // of the parameter either names a template parameter pack that has not
5587 // been expanded or contains auto; otherwise, it is parsed as part of the
5588 // parameter-declaration-clause.
Richard Smith0efa75c2012-03-29 01:16:42 +00005589 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00005590 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5591 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5592 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
Douglas Gregor27b4c162010-12-23 22:44:42 +00005593 NextToken().is(tok::r_paren) &&
Richard Smithb19337f2013-02-20 20:19:27 +00005594 !D.hasGroupingParens() &&
Faisal Vali8435a692014-12-04 12:40:21 +00005595 !Actions.containsUnexpandedParameterPacks(D) &&
Faisal Vali090da2d2018-01-01 18:23:28 +00005596 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005597 SourceLocation EllipsisLoc = ConsumeToken();
Richard Smith0b350b92014-10-28 16:55:02 +00005598 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005599 // The ellipsis was put in the wrong place. Recover, and explain to
5600 // the user what they should have done.
5601 ParseDeclarator(D);
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00005602 if (EllipsisLoc.isValid())
5603 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00005604 return;
5605 } else
5606 D.setEllipsisLoc(EllipsisLoc);
5607
5608 // The ellipsis can't be followed by a parenthesized declarator. We
5609 // check for that in ParseParenDeclarator, after we have disambiguated
5610 // the l_paren token.
5611 }
5612
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005613 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5614 tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00005615 // We found something that indicates the start of an unqualified-id.
5616 // Parse that unqualified-id.
John McCall84821e72010-04-13 06:39:49 +00005617 bool AllowConstructorName;
Richard Smith35845152017-02-07 01:37:30 +00005618 bool AllowDeductionGuide;
5619 if (D.getDeclSpec().hasTypeSpecifier()) {
John McCall84821e72010-04-13 06:39:49 +00005620 AllowConstructorName = false;
Richard Smith35845152017-02-07 01:37:30 +00005621 AllowDeductionGuide = false;
5622 } else if (D.getCXXScopeSpec().isSet()) {
John McCall84821e72010-04-13 06:39:49 +00005623 AllowConstructorName =
Faisal Vali421b2d12017-12-29 05:41:00 +00005624 (D.getContext() == DeclaratorContext::FileContext ||
5625 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005626 AllowDeductionGuide = false;
5627 } else {
Faisal Vali421b2d12017-12-29 05:41:00 +00005628 AllowConstructorName =
5629 (D.getContext() == DeclaratorContext::MemberContext);
Fangrui Song6907ce22018-07-30 19:24:48 +00005630 AllowDeductionGuide =
Faisal Vali421b2d12017-12-29 05:41:00 +00005631 (D.getContext() == DeclaratorContext::FileContext ||
5632 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005633 }
John McCall84821e72010-04-13 06:39:49 +00005634
Richard Smith64e033f2015-01-15 00:48:52 +00005635 bool HadScope = D.getCXXScopeSpec().isValid();
Chad Rosierc1183952012-06-26 22:30:43 +00005636 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5637 /*EnteringContext=*/true,
David Blaikieefdccaa2016-01-15 23:43:34 +00005638 /*AllowDestructorName=*/true, AllowConstructorName,
Richard Smithc08b6932018-04-27 02:00:13 +00005639 AllowDeductionGuide, nullptr, nullptr,
Richard Smith35845152017-02-07 01:37:30 +00005640 D.getName()) ||
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005641 // Once we're past the identifier, if the scope was bad, mark the
5642 // whole declarator bad.
5643 D.getCXXScopeSpec().isInvalid()) {
Craig Topper161e4db2014-05-21 06:02:52 +00005644 D.SetIdentifier(nullptr, Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005645 D.setInvalidType(true);
Douglas Gregor7861a802009-11-03 01:35:08 +00005646 } else {
Richard Smith64e033f2015-01-15 00:48:52 +00005647 // ParseUnqualifiedId might have parsed a scope specifier during error
5648 // recovery. If it did so, enter that scope.
5649 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5650 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5651 D.getCXXScopeSpec()))
5652 DeclScopeObj.EnterDeclaratorScope();
5653
Douglas Gregor7861a802009-11-03 01:35:08 +00005654 // Parsed the unqualified-id; update range information and move along.
5655 if (D.getSourceRange().getBegin().isInvalid())
5656 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5657 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005658 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005659 goto PastIdentifier;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005660 }
Richard Smithd63db6e2015-12-19 02:40:19 +00005661
5662 if (D.getCXXScopeSpec().isNotEmpty()) {
5663 // We have a scope specifier but no following unqualified-id.
5664 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5665 diag::err_expected_unqualified_id)
5666 << /*C++*/1;
5667 D.SetIdentifier(nullptr, Tok.getLocation());
5668 goto PastIdentifier;
5669 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005670 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005671 assert(!getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005672 "There's a C++-specific check for tok::identifier above");
5673 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5674 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Richard Trieu2664dc12014-05-05 22:06:50 +00005675 D.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005676 ConsumeToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00005677 goto PastIdentifier;
Richard Smith74639b12017-05-19 01:54:59 +00005678 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5679 // We're not allowed an identifier here, but we got one. Try to figure out
5680 // if the user was trying to attach a name to the type, or whether the name
5681 // is some unrelated trailing syntax.
5682 bool DiagnoseIdentifier = false;
5683 if (D.hasGroupingParens())
5684 // An identifier within parens is unlikely to be intended to be anything
5685 // other than a name being "declared".
5686 DiagnoseIdentifier = true;
Richard Smith77a9c602018-02-28 03:02:23 +00005687 else if (D.getContext() == DeclaratorContext::TemplateArgContext)
Richard Smith74639b12017-05-19 01:54:59 +00005688 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5689 DiagnoseIdentifier =
5690 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali421b2d12017-12-29 05:41:00 +00005691 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5692 D.getContext() == DeclaratorContext::AliasTemplateContext)
Richard Smith74639b12017-05-19 01:54:59 +00005693 // The most likely error is that the ';' was forgotten.
5694 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
Richard Smithe303e352018-02-02 22:24:54 +00005695 else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5696 D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
Richard Smith74639b12017-05-19 01:54:59 +00005697 !isCXX11VirtSpecifier(Tok))
5698 DiagnoseIdentifier = NextToken().isOneOf(
5699 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5700 if (DiagnoseIdentifier) {
Richard Smithf39720b2013-10-13 22:12:28 +00005701 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5702 << FixItHint::CreateRemoval(Tok.getLocation());
Craig Topper161e4db2014-05-21 06:02:52 +00005703 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithf39720b2013-10-13 22:12:28 +00005704 ConsumeToken();
5705 goto PastIdentifier;
5706 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005707 }
Richard Smith0efa75c2012-03-29 01:16:42 +00005708
Douglas Gregor7861a802009-11-03 01:35:08 +00005709 if (Tok.is(tok::l_paren)) {
Richard Smithe303e352018-02-02 22:24:54 +00005710 // If this might be an abstract-declarator followed by a direct-initializer,
5711 // check whether this is a valid declarator chunk. If it can't be, assume
5712 // that it's an initializer instead.
5713 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5714 RevertingTentativeParsingAction PA(*this);
5715 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5716 TPResult::False) {
5717 D.SetIdentifier(nullptr, Tok.getLocation());
5718 goto PastIdentifier;
5719 }
5720 }
5721
Chris Lattneracd58a32006-08-06 17:24:14 +00005722 // direct-declarator: '(' declarator ')'
Chris Lattnere37e2332006-08-15 04:50:22 +00005723 // direct-declarator: '(' attributes declarator ')'
Chris Lattneracd58a32006-08-06 17:24:14 +00005724 // Example: 'char (*X)' or 'int (*XX)(void)'
5725 ParseParenDeclarator(D);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005726
5727 // If the declarator was parenthesized, we entered the declarator
5728 // scope when parsing the parenthesized declarator, then exited
5729 // the scope already. Re-enter the scope, if we need to.
5730 if (D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005731 // If there was an error parsing parenthesized declarator, declarator
Richard Smith0efa75c2012-03-29 01:16:42 +00005732 // scope may have been entered before. Don't do it again.
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005733 if (!D.isInvalidType() &&
Nico Weber6b05f382015-02-18 04:53:03 +00005734 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5735 D.getCXXScopeSpec()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005736 // Change the declaration context for name lookup, until this function
5737 // is exited (and the declarator has been parsed).
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005738 DeclScopeObj.EnterDeclaratorScope();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005739 }
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005740 } else if (D.mayOmitIdentifier()) {
Chris Lattneracd58a32006-08-06 17:24:14 +00005741 // This could be something simple like "int" (in which case the declarator
5742 // portion is empty), if an abstract-declarator is allowed.
Craig Topper161e4db2014-05-21 06:02:52 +00005743 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithb19337f2013-02-20 20:19:27 +00005744
5745 // The grammar for abstract-pack-declarator does not allow grouping parens.
5746 // FIXME: Revisit this once core issue 1488 is resolved.
5747 if (D.hasEllipsis() && D.hasGroupingParens())
5748 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5749 diag::ext_abstract_pack_declarator_parens);
Chris Lattneracd58a32006-08-06 17:24:14 +00005750 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00005751 if (Tok.getKind() == tok::annot_pragma_parser_crash)
David Blaikie5bd4c2a2012-08-21 18:56:49 +00005752 LLVM_BUILTIN_TRAP;
Richard Trieuf4b81d02014-06-24 23:14:24 +00005753 if (Tok.is(tok::l_square))
5754 return ParseMisplacedBracketDeclarator(D);
Faisal Vali421b2d12017-12-29 05:41:00 +00005755 if (D.getContext() == DeclaratorContext::MemberContext) {
Alex Lorenzf1278212017-04-11 15:01:53 +00005756 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5757 // treating these keyword as valid member names.
5758 if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus &&
5759 Tok.getIdentifierInfo() &&
5760 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5761 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5762 diag::err_expected_member_name_or_semi_objcxx_keyword)
5763 << Tok.getIdentifierInfo()
5764 << (D.getDeclSpec().isEmpty() ? SourceRange()
5765 : D.getDeclSpec().getSourceRange());
5766 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5767 D.SetRangeEnd(Tok.getLocation());
5768 ConsumeToken();
5769 goto PastIdentifier;
5770 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005771 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5772 diag::err_expected_member_name_or_semi)
Richard Trieua1342402014-05-02 23:40:32 +00005773 << (D.getDeclSpec().isEmpty() ? SourceRange()
5774 : D.getDeclSpec().getSourceRange());
Richard Trieuf4b81d02014-06-24 23:14:24 +00005775 } else if (getLangOpts().CPlusPlus) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005776 if (Tok.isOneOf(tok::period, tok::arrow))
Richard Trieu9c672672013-01-26 02:31:38 +00005777 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
Richard Trieu2f586962013-09-05 02:31:33 +00005778 else {
5779 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5780 if (Tok.isAtStartOfLine() && Loc.isValid())
5781 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5782 << getLangOpts().CPlusPlus;
5783 else
Richard Trieuf4b81d02014-06-24 23:14:24 +00005784 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5785 diag::err_expected_unqualified_id)
Richard Trieu2f586962013-09-05 02:31:33 +00005786 << getLangOpts().CPlusPlus;
5787 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005788 } else {
5789 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5790 diag::err_expected_either)
5791 << tok::identifier << tok::l_paren;
5792 }
Craig Topper161e4db2014-05-21 06:02:52 +00005793 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattner8c5dd732008-11-11 06:13:16 +00005794 D.setInvalidType(true);
Chris Lattneracd58a32006-08-06 17:24:14 +00005795 }
Mike Stump11289f42009-09-09 15:08:12 +00005796
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005797 PastIdentifier:
Chris Lattneracd58a32006-08-06 17:24:14 +00005798 assert(D.isPastIdentifier() &&
5799 "Haven't past the location of the identifier yet?");
Mike Stump11289f42009-09-09 15:08:12 +00005800
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005801 // Don't parse attributes unless we have parsed an unparenthesized name.
5802 if (D.hasName() && !D.getNumTypeObjects())
Richard Smith89645bc2013-01-02 12:01:23 +00005803 MaybeParseCXX11Attributes(D);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005804
Chris Lattneracd58a32006-08-06 17:24:14 +00005805 while (1) {
Chris Lattner76c72282007-10-09 17:33:22 +00005806 if (Tok.is(tok::l_paren)) {
David Blaikie15a430a2011-12-04 05:04:18 +00005807 // Enter function-declaration scope, limiting any declarators to the
5808 // function prototype scope, including parameter declarators.
5809 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00005810 Scope::FunctionPrototypeScope|Scope::DeclScope|
5811 (D.isFunctionDeclaratorAFunctionDeclaration()
5812 ? Scope::FunctionDeclarationScope : 0));
5813
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005814 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5815 // In such a case, check if we actually have a function declarator; if it
5816 // is not, the declarator has been fully parsed.
Richard Smith943c4402012-07-30 21:30:52 +00005817 bool IsAmbiguous = false;
Richard Smith4f605af2012-08-18 00:55:03 +00005818 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5819 // The name of the declarator, if any, is tentatively declared within
5820 // a possible direct initializer.
5821 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5822 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5823 TentativelyDeclaredIdentifiers.pop_back();
5824 if (!IsFunctionDecl)
5825 break;
5826 }
John McCall084e83d2011-03-24 11:26:52 +00005827 ParsedAttributes attrs(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005828 BalancedDelimiterTracker T(*this, tok::l_paren);
5829 T.consumeOpen();
Richard Smith943c4402012-07-30 21:30:52 +00005830 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
David Blaikie15a430a2011-12-04 05:04:18 +00005831 PrototypeScope.Exit();
Chris Lattner76c72282007-10-09 17:33:22 +00005832 } else if (Tok.is(tok::l_square)) {
Chris Lattnere8074e62006-08-06 18:30:15 +00005833 ParseBracketDeclarator(D);
Chris Lattneracd58a32006-08-06 17:24:14 +00005834 } else {
5835 break;
5836 }
5837 }
Chad Rosierc1183952012-06-26 22:30:43 +00005838}
Chris Lattneracd58a32006-08-06 17:24:14 +00005839
Richard Smithbdb84f32016-07-22 23:36:59 +00005840void Parser::ParseDecompositionDeclarator(Declarator &D) {
5841 assert(Tok.is(tok::l_square));
5842
5843 // If this doesn't look like a structured binding, maybe it's a misplaced
5844 // array declarator.
5845 // FIXME: Consume the l_square first so we don't need extra lookahead for
5846 // this.
5847 if (!(NextToken().is(tok::identifier) &&
5848 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5849 !(NextToken().is(tok::r_square) &&
5850 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5851 return ParseMisplacedBracketDeclarator(D);
5852
5853 BalancedDelimiterTracker T(*this, tok::l_square);
5854 T.consumeOpen();
5855
5856 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5857 while (Tok.isNot(tok::r_square)) {
5858 if (!Bindings.empty()) {
5859 if (Tok.is(tok::comma))
5860 ConsumeToken();
5861 else {
5862 if (Tok.is(tok::identifier)) {
5863 SourceLocation EndLoc = getEndOfPreviousToken();
5864 Diag(EndLoc, diag::err_expected)
5865 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5866 } else {
5867 Diag(Tok, diag::err_expected_comma_or_rsquare);
5868 }
5869
5870 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5871 StopAtSemi | StopBeforeMatch);
5872 if (Tok.is(tok::comma))
5873 ConsumeToken();
5874 else if (Tok.isNot(tok::identifier))
5875 break;
5876 }
5877 }
5878
5879 if (Tok.isNot(tok::identifier)) {
5880 Diag(Tok, diag::err_expected) << tok::identifier;
5881 break;
5882 }
5883
5884 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
5885 ConsumeToken();
5886 }
5887
5888 if (Tok.isNot(tok::r_square))
5889 // We've already diagnosed a problem here.
5890 T.skipToEnd();
5891 else {
5892 // C++17 does not allow the identifier-list in a structured binding
5893 // to be empty.
5894 if (Bindings.empty())
5895 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
5896
5897 T.consumeClose();
5898 }
5899
5900 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
5901 T.getCloseLocation());
5902}
5903
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005904/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5905/// only called before the identifier, so these are most likely just grouping
Mike Stump11289f42009-09-09 15:08:12 +00005906/// parens for precedence. If we find that these are actually function
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005907/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5908///
5909/// direct-declarator:
5910/// '(' declarator ')'
5911/// [GNU] '(' attributes declarator ')'
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005912/// direct-declarator '(' parameter-type-list ')'
5913/// direct-declarator '(' identifier-list[opt] ')'
5914/// [GNU] direct-declarator '(' parameter-forward-declarations
5915/// parameter-type-list[opt] ')'
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005916///
5917void Parser::ParseParenDeclarator(Declarator &D) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005918 BalancedDelimiterTracker T(*this, tok::l_paren);
5919 T.consumeOpen();
5920
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005921 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
Mike Stump11289f42009-09-09 15:08:12 +00005922
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005923 // Eat any attributes before we look at whether this is a grouping or function
5924 // declarator paren. If this is a grouping paren, the attribute applies to
5925 // the type being built up, for example:
5926 // int (__attribute__(()) *x)(long y)
5927 // If this ends up not being a grouping paren, the attribute applies to the
5928 // first argument, for example:
5929 // int (__attribute__(()) int x)
5930 // In either case, we need to eat any attributes to be able to determine what
5931 // sort of paren this is.
5932 //
John McCall084e83d2011-03-24 11:26:52 +00005933 ParsedAttributes attrs(AttrFactory);
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005934 bool RequiresArg = false;
5935 if (Tok.is(tok::kw___attribute)) {
John McCall53fa7142010-12-24 02:08:15 +00005936 ParseGNUAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00005937
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005938 // We require that the argument list (if this is a non-grouping paren) be
5939 // present even if the attribute list was empty.
5940 RequiresArg = true;
5941 }
Chad Rosiereea9ca72012-12-21 21:22:20 +00005942
Steve Naroff44ac7772008-12-25 14:16:32 +00005943 // Eat any Microsoft extensions.
Chad Rosiereea9ca72012-12-21 21:22:20 +00005944 ParseMicrosoftTypeAttributes(attrs);
5945
Dawn Perchik335e16b2010-09-03 01:29:35 +00005946 // Eat any Borland extensions.
Ted Kremenek5eec2b02010-11-10 05:59:39 +00005947 if (Tok.is(tok::kw___pascal))
John McCall53fa7142010-12-24 02:08:15 +00005948 ParseBorlandTypeAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00005949
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005950 // If we haven't past the identifier yet (or where the identifier would be
5951 // stored, if this is an abstract declarator), then this is probably just
5952 // grouping parens. However, if this could be an abstract-declarator, then
5953 // this could also be the start of function arguments (consider 'void()').
5954 bool isGrouping;
Mike Stump11289f42009-09-09 15:08:12 +00005955
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005956 if (!D.mayOmitIdentifier()) {
5957 // If this can't be an abstract-declarator, this *must* be a grouping
5958 // paren, because we haven't seen the identifier yet.
5959 isGrouping = true;
5960 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
Richard Smith43f340f2012-03-27 23:05:05 +00005961 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5962 NextToken().is(tok::r_paren)) || // C++ int(...)
Richard Smith2620cd92012-04-11 04:01:28 +00005963 isDeclarationSpecifier() || // 'int(int)' is a function.
5964 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005965 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5966 // considered to be a type, not a K&R identifier-list.
5967 isGrouping = false;
5968 } else {
5969 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5970 isGrouping = true;
5971 }
Mike Stump11289f42009-09-09 15:08:12 +00005972
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005973 // If this is a grouping paren, handle:
5974 // direct-declarator: '(' declarator ')'
5975 // direct-declarator: '(' attributes declarator ')'
5976 if (isGrouping) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005977 SourceLocation EllipsisLoc = D.getEllipsisLoc();
5978 D.setEllipsisLoc(SourceLocation());
5979
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00005980 bool hadGroupingParens = D.hasGroupingParens();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005981 D.setGroupingParens(true);
Sebastian Redlbd150f42008-11-21 19:14:01 +00005982 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005983 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005984 T.consumeClose();
Erich Keanec480f302018-07-12 21:09:05 +00005985 D.AddTypeInfo(
5986 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
5987 std::move(attrs), T.getCloseLocation());
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00005988
5989 D.setGroupingParens(hadGroupingParens);
Richard Smith0efa75c2012-03-29 01:16:42 +00005990
5991 // An ellipsis cannot be placed outside parentheses.
5992 if (EllipsisLoc.isValid())
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00005993 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00005994
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005995 return;
5996 }
Mike Stump11289f42009-09-09 15:08:12 +00005997
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005998 // Okay, if this wasn't a grouping paren, it must be the start of a function
5999 // argument list. Recognize that this declarator will never have an
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006000 // identifier (and remember where it would have been), then call into
6001 // ParseFunctionDeclarator to handle of argument list.
Craig Topper161e4db2014-05-21 06:02:52 +00006002 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006003
David Blaikie15a430a2011-12-04 05:04:18 +00006004 // Enter function-declaration scope, limiting any declarators to the
6005 // function prototype scope, including parameter declarators.
6006 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00006007 Scope::FunctionPrototypeScope | Scope::DeclScope |
6008 (D.isFunctionDeclaratorAFunctionDeclaration()
6009 ? Scope::FunctionDeclarationScope : 0));
Richard Smith943c4402012-07-30 21:30:52 +00006010 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
David Blaikie15a430a2011-12-04 05:04:18 +00006011 PrototypeScope.Exit();
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006012}
6013
6014/// ParseFunctionDeclarator - We are after the identifier and have parsed the
6015/// declarator D up to a paren, which indicates that we are parsing function
6016/// arguments.
Chris Lattneracd58a32006-08-06 17:24:14 +00006017///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006018/// If FirstArgAttrs is non-null, then the caller parsed those arguments
6019/// immediately after the open paren - they should be considered to be the
6020/// first argument of a parameter.
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006021///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006022/// If RequiresArg is true, then the first argument of the function is required
6023/// to be present and required to not be an identifier list.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006024///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006025/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6026/// (C++11) ref-qualifier[opt], exception-specification[opt],
6027/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
6028///
6029/// [C++11] exception-specification:
Douglas Gregor9e66af42011-07-05 16:44:18 +00006030/// dynamic-exception-specification
6031/// noexcept-specification
6032///
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006033void Parser::ParseFunctionDeclarator(Declarator &D,
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006034 ParsedAttributes &FirstArgAttrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006035 BalancedDelimiterTracker &Tracker,
Richard Smith943c4402012-07-30 21:30:52 +00006036 bool IsAmbiguous,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006037 bool RequiresArg) {
Chad Rosierc1183952012-06-26 22:30:43 +00006038 assert(getCurScope()->isFunctionPrototypeScope() &&
David Blaikie15a430a2011-12-04 05:04:18 +00006039 "Should call from a Function scope");
Douglas Gregor9e66af42011-07-05 16:44:18 +00006040 // lparen is already consumed!
6041 assert(D.isPastIdentifier() && "Should not call before identifier!");
6042
6043 // This should be true when the function has typed arguments.
6044 // Otherwise, it is treated as a K&R-style function.
6045 bool HasProto = false;
6046 // Build up an array of information about the parsed arguments.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006047 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006048 // Remember where we see an ellipsis, if any.
6049 SourceLocation EllipsisLoc;
6050
6051 DeclSpec DS(AttrFactory);
6052 bool RefQualifierIsLValueRef = true;
6053 SourceLocation RefQualifierLoc;
Douglas Gregore248eea2011-10-19 06:04:55 +00006054 SourceLocation ConstQualifierLoc;
6055 SourceLocation VolatileQualifierLoc;
Hal Finkel23a07392014-10-20 17:32:04 +00006056 SourceLocation RestrictQualifierLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006057 ExceptionSpecificationType ESpecType = EST_None;
6058 SourceRange ESpecRange;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006059 SmallVector<ParsedType, 2> DynamicExceptions;
6060 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006061 ExprResult NoexceptExpr;
Hans Wennborgdcfba332015-10-06 23:40:43 +00006062 CachedTokens *ExceptionSpecTokens = nullptr;
Aaron Ballman606093a2017-10-15 15:01:42 +00006063 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith700537c2012-06-12 01:51:59 +00006064 TypeResult TrailingReturnType;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006065
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006066 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6067 EndLoc is the end location for the function declarator.
6068 They differ for trailing return types. */
6069 SourceLocation StartLoc, LocalEndLoc, EndLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006070 SourceLocation LParenLoc, RParenLoc;
6071 LParenLoc = Tracker.getOpenLocation();
6072 StartLoc = LParenLoc;
6073
Douglas Gregor9e66af42011-07-05 16:44:18 +00006074 if (isFunctionDeclaratorIdentifierList()) {
6075 if (RequiresArg)
6076 Diag(Tok, diag::err_argument_required_after_attribute);
6077
6078 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6079
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006080 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006081 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006082 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006083 EndLoc = RParenLoc;
Aaron Ballman606093a2017-10-15 15:01:42 +00006084
Fangrui Song6907ce22018-07-30 19:24:48 +00006085 // If there are attributes following the identifier list, parse them and
Aaron Ballman606093a2017-10-15 15:01:42 +00006086 // prohibit them.
6087 MaybeParseCXX11Attributes(FnAttrs);
6088 ProhibitAttributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006089 } else {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006090 if (Tok.isNot(tok::r_paren))
Fangrui Song6907ce22018-07-30 19:24:48 +00006091 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
Faisal Vali2b391ab2013-09-26 19:54:12 +00006092 EllipsisLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006093 else if (RequiresArg)
6094 Diag(Tok, diag::err_argument_required_after_attribute);
6095
Alexey Bader1f277942017-10-11 11:16:31 +00006096 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6097 || getLangOpts().OpenCL;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006098
6099 // If we have the closing ')', eat it.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006100 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006101 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006102 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006103 EndLoc = RParenLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006104
David Blaikiebbafb8a2012-03-11 07:00:24 +00006105 if (getLangOpts().CPlusPlus) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006106 // FIXME: Accept these components in any order, and produce fixits to
6107 // correct the order if the user gets it wrong. Ideally we should deal
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00006108 // with the pure-specifier in the same way.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006109
6110 // Parse cv-qualifier-seq[opt].
Aaron Ballman08b06592014-07-22 12:44:22 +00006111 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
Alex Lorenz8f4d3992017-02-13 23:19:40 +00006112 /*AtomicAllowed*/ false,
6113 /*IdentifierRequired=*/false,
6114 llvm::function_ref<void()>([&]() {
6115 Actions.CodeCompleteFunctionQualifiers(DS, D);
6116 }));
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006117 if (!DS.getSourceRange().getEnd().isInvalid()) {
6118 EndLoc = DS.getSourceRange().getEnd();
6119 ConstQualifierLoc = DS.getConstSpecLoc();
6120 VolatileQualifierLoc = DS.getVolatileSpecLoc();
Hal Finkel23a07392014-10-20 17:32:04 +00006121 RestrictQualifierLoc = DS.getRestrictSpecLoc();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006122 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006123
6124 // Parse ref-qualifier[opt].
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006125 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
Douglas Gregor9e66af42011-07-05 16:44:18 +00006126 EndLoc = RefQualifierLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006127
Douglas Gregor3024f072012-04-16 07:05:22 +00006128 // C++11 [expr.prim.general]p3:
Chad Rosierc1183952012-06-26 22:30:43 +00006129 // If a declaration declares a member function or member function
6130 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00006131 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Chad Rosierc1183952012-06-26 22:30:43 +00006132 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00006133 // declarator.
Richard Smithad1bbb92013-03-15 00:41:52 +00006134 // FIXME: currently, "static" case isn't handled correctly.
Chad Rosierc1183952012-06-26 22:30:43 +00006135 bool IsCXX11MemberFunction =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006136 getLangOpts().CPlusPlus11 &&
Richard Smith990a6922014-01-17 21:01:18 +00006137 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
Faisal Vali421b2d12017-12-29 05:41:00 +00006138 (D.getContext() == DeclaratorContext::MemberContext
Richard Smithad1bbb92013-03-15 00:41:52 +00006139 ? !D.getDeclSpec().isFriendSpecified()
Faisal Vali421b2d12017-12-29 05:41:00 +00006140 : D.getContext() == DeclaratorContext::FileContext &&
Richard Smithad1bbb92013-03-15 00:41:52 +00006141 D.getCXXScopeSpec().isValid() &&
6142 Actions.CurContext->isRecord());
Douglas Gregor3024f072012-04-16 07:05:22 +00006143 Sema::CXXThisScopeRAII ThisScope(Actions,
6144 dyn_cast<CXXRecordDecl>(Actions.CurContext),
Richard Smith01141a92013-01-14 01:55:13 +00006145 DS.getTypeQualifiers() |
Richard Smith034185c2013-04-21 01:08:50 +00006146 (D.getDeclSpec().isConstexprSpecified() &&
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006147 !getLangOpts().CPlusPlus14
Richard Smith01141a92013-01-14 01:55:13 +00006148 ? Qualifiers::Const : 0),
Douglas Gregor3024f072012-04-16 07:05:22 +00006149 IsCXX11MemberFunction);
Richard Smith2331bbf2012-05-02 22:22:32 +00006150
Douglas Gregor9e66af42011-07-05 16:44:18 +00006151 // Parse exception-specification[opt].
Richard Smith0b3a4622014-11-13 20:01:57 +00006152 bool Delayed = D.isFirstDeclarationOfMember() &&
Richard Smith3ef3e892014-11-20 22:32:11 +00006153 D.isFunctionDeclaratorAFunctionDeclaration();
6154 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6155 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6156 GetLookAheadToken(1).is(tok::l_paren) &&
6157 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6158 GetLookAheadToken(3).is(tok::l_paren) &&
6159 GetLookAheadToken(4).is(tok::identifier) &&
6160 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6161 // HACK: We've got an exception-specification
6162 // noexcept(noexcept(swap(...)))
6163 // or
6164 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6165 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6166 // for 'swap' will only find the function we're currently declaring,
6167 // whereas it expects to find a non-member swap through ADL. Turn off
6168 // delayed parsing to give it a chance to find what it expects.
6169 Delayed = false;
6170 }
Richard Smith0b3a4622014-11-13 20:01:57 +00006171 ESpecType = tryParseExceptionSpecification(Delayed,
6172 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00006173 DynamicExceptions,
6174 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00006175 NoexceptExpr,
6176 ExceptionSpecTokens);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006177 if (ESpecType != EST_None)
6178 EndLoc = ESpecRange.getEnd();
6179
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006180 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6181 // after the exception-specification.
Richard Smith89645bc2013-01-02 12:01:23 +00006182 MaybeParseCXX11Attributes(FnAttrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006183
Douglas Gregor9e66af42011-07-05 16:44:18 +00006184 // Parse trailing-return-type[opt].
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006185 LocalEndLoc = EndLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006186 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00006187 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
Faisal Vali090da2d2018-01-01 18:23:28 +00006188 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006189 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006190 LocalEndLoc = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00006191 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00006192 TrailingReturnType =
6193 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006194 EndLoc = Range.getEnd();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006195 }
Aaron Ballman606093a2017-10-15 15:01:42 +00006196 } else if (standardAttributesAllowed()) {
6197 MaybeParseCXX11Attributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006198 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006199 }
6200
Reid Kleckner078aea92016-12-09 17:14:05 +00006201 // Collect non-parameter declarations from the prototype if this is a function
6202 // declaration. They will be moved into the scope of the function. Only do
6203 // this in C and not C++, where the decls will continue to live in the
6204 // surrounding context.
6205 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6206 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6207 !getLangOpts().CPlusPlus) {
6208 for (Decl *D : getCurScope()->decls()) {
6209 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6210 if (!ND || isa<ParmVarDecl>(ND))
6211 continue;
6212 DeclsInPrototype.push_back(ND);
6213 }
6214 }
6215
Douglas Gregor9e66af42011-07-05 16:44:18 +00006216 // Remember that we parsed a function type, and remember the attributes.
Erich Keanec480f302018-07-12 21:09:05 +00006217 D.AddTypeInfo(DeclaratorChunk::getFunction(
6218 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6219 ParamInfo.size(), EllipsisLoc, RParenLoc,
6220 DS.getTypeQualifiers(), RefQualifierIsLValueRef,
6221 RefQualifierLoc, ConstQualifierLoc, VolatileQualifierLoc,
6222 RestrictQualifierLoc,
6223 /*MutableLoc=*/SourceLocation(), ESpecType, ESpecRange,
6224 DynamicExceptions.data(), DynamicExceptionRanges.data(),
6225 DynamicExceptions.size(),
6226 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6227 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
6228 LocalEndLoc, D, TrailingReturnType),
6229 std::move(FnAttrs), EndLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006230}
6231
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006232/// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6233/// true if a ref-qualifier is found.
6234bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6235 SourceLocation &RefQualifierLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00006236 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006237 Diag(Tok, getLangOpts().CPlusPlus11 ?
6238 diag::warn_cxx98_compat_ref_qualifier :
6239 diag::ext_ref_qualifier);
6240
6241 RefQualifierIsLValueRef = Tok.is(tok::amp);
6242 RefQualifierLoc = ConsumeToken();
6243 return true;
6244 }
6245 return false;
6246}
6247
Douglas Gregor9e66af42011-07-05 16:44:18 +00006248/// isFunctionDeclaratorIdentifierList - This parameter list may have an
6249/// identifier list form for a K&R-style function: void foo(a,b,c)
6250///
6251/// Note that identifier-lists are only allowed for normal declarators, not for
6252/// abstract-declarators.
6253bool Parser::isFunctionDeclaratorIdentifierList() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006254 return !getLangOpts().CPlusPlus
Douglas Gregor9e66af42011-07-05 16:44:18 +00006255 && Tok.is(tok::identifier)
6256 && !TryAltiVecVectorToken()
6257 // K&R identifier lists can't have typedefs as identifiers, per C99
6258 // 6.7.5.3p11.
6259 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6260 // Identifier lists follow a really simple grammar: the identifiers can
6261 // be followed *only* by a ", identifier" or ")". However, K&R
6262 // identifier lists are really rare in the brave new modern world, and
6263 // it is very common for someone to typo a type in a non-K&R style
6264 // list. If we are presented with something like: "void foo(intptr x,
6265 // float y)", we don't want to start parsing the function declarator as
6266 // though it is a K&R style declarator just because intptr is an
6267 // invalid type.
6268 //
6269 // To handle this, we check to see if the token after the first
6270 // identifier is a "," or ")". Only then do we parse it as an
6271 // identifier list.
Bruno Cardoso Lopes218c8742016-09-13 20:04:35 +00006272 && (!Tok.is(tok::eof) &&
6273 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006274}
6275
6276/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6277/// we found a K&R-style identifier list instead of a typed parameter list.
6278///
6279/// After returning, ParamInfo will hold the parsed parameters.
6280///
6281/// identifier-list: [C99 6.7.5]
6282/// identifier
6283/// identifier-list ',' identifier
6284///
6285void Parser::ParseFunctionDeclaratorIdentifierList(
6286 Declarator &D,
Craig Topper5603df42013-07-05 19:34:19 +00006287 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006288 // If there was no identifier specified for the declarator, either we are in
6289 // an abstract-declarator, or we are in a parameter declarator which was found
6290 // to be abstract. In abstract-declarators, identifier lists are not valid:
6291 // diagnose this.
6292 if (!D.getIdentifier())
6293 Diag(Tok, diag::ext_ident_list_in_param);
6294
6295 // Maintain an efficient lookup of params we have seen so far.
6296 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6297
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006298 do {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006299 // If this isn't an identifier, report the error and skip until ')'.
6300 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00006301 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00006302 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006303 // Forget we parsed anything.
6304 ParamInfo.clear();
6305 return;
6306 }
6307
6308 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6309
6310 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6311 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6312 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6313
6314 // Verify that the argument identifier has not already been mentioned.
David Blaikie82e95a32014-11-19 07:49:47 +00006315 if (!ParamsSoFar.insert(ParmII).second) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006316 Diag(Tok, diag::err_param_redefinition) << ParmII;
6317 } else {
6318 // Remember this identifier in ParamInfo.
6319 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6320 Tok.getLocation(),
Craig Topper161e4db2014-05-21 06:02:52 +00006321 nullptr));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006322 }
6323
6324 // Eat the identifier.
6325 ConsumeToken();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006326 // The list continues if we see a comma.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006327 } while (TryConsumeToken(tok::comma));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006328}
6329
6330/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6331/// after the opening parenthesis. This function will not parse a K&R-style
6332/// identifier list.
6333///
Richard Smith2620cd92012-04-11 04:01:28 +00006334/// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6335/// caller parsed those arguments immediately after the open paren - they should
6336/// be considered to be part of the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006337///
6338/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6339/// be the location of the ellipsis, if any was parsed.
6340///
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006341/// parameter-type-list: [C99 6.7.5]
6342/// parameter-list
6343/// parameter-list ',' '...'
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006344/// [C++] parameter-list '...'
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006345///
6346/// parameter-list: [C99 6.7.5]
6347/// parameter-declaration
6348/// parameter-list ',' parameter-declaration
6349///
6350/// parameter-declaration: [C99 6.7.5]
6351/// declaration-specifiers declarator
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006352/// [C++] declaration-specifiers declarator '=' assignment-expression
Sebastian Redldb63af22012-03-14 15:54:00 +00006353/// [C++11] initializer-clause
Chris Lattnere37e2332006-08-15 04:50:22 +00006354/// [GNU] declaration-specifiers declarator attributes
Sebastian Redlf769df52009-03-24 22:27:57 +00006355/// declaration-specifiers abstract-declarator[opt]
6356/// [C++] declaration-specifiers abstract-declarator[opt]
Chris Lattner58258242008-04-10 02:22:51 +00006357/// '=' assignment-expression
Chris Lattnere37e2332006-08-15 04:50:22 +00006358/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
Richard Smith2620cd92012-04-11 04:01:28 +00006359/// [C++11] attribute-specifier-seq parameter-declaration
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006360///
Douglas Gregor9e66af42011-07-05 16:44:18 +00006361void Parser::ParseParameterDeclarationClause(
6362 Declarator &D,
Richard Smith2620cd92012-04-11 04:01:28 +00006363 ParsedAttributes &FirstArgAttrs,
Craig Topper5603df42013-07-05 19:34:19 +00006364 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006365 SourceLocation &EllipsisLoc) {
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006366 do {
6367 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6368 // before deciding this was a parameter-declaration-clause.
6369 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Chris Lattner371ed4e2008-04-06 06:57:35 +00006370 break;
Mike Stump11289f42009-09-09 15:08:12 +00006371
Chris Lattner371ed4e2008-04-06 06:57:35 +00006372 // Parse the declaration-specifiers.
John McCall28a6aea2009-11-04 02:18:39 +00006373 // Just use the ParsingDeclaration "scope" of the declarator.
John McCall084e83d2011-03-24 11:26:52 +00006374 DeclSpec DS(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006375
Richard Smith2620cd92012-04-11 04:01:28 +00006376 // Parse any C++11 attributes.
Richard Smith89645bc2013-01-02 12:01:23 +00006377 MaybeParseCXX11Attributes(DS.getAttributes());
Richard Smith2620cd92012-04-11 04:01:28 +00006378
John McCall53fa7142010-12-24 02:08:15 +00006379 // Skip any Microsoft attributes before a param.
Chad Rosierf8a2e702012-12-20 20:37:53 +00006380 MaybeParseMicrosoftAttributes(DS.getAttributes());
John McCall53fa7142010-12-24 02:08:15 +00006381
6382 SourceLocation DSStart = Tok.getLocation();
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006383
6384 // If the caller parsed attributes for the first argument, add them now.
John McCall53fa7142010-12-24 02:08:15 +00006385 // Take them so that we only apply the attributes to the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006386 // FIXME: If we can leave the attributes in the token stream somehow, we can
Richard Smith2620cd92012-04-11 04:01:28 +00006387 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6388 // too much hassle.
6389 DS.takeAttributesFrom(FirstArgAttrs);
John McCall53fa7142010-12-24 02:08:15 +00006390
Faisal Valia534f072018-04-26 00:42:40 +00006391 ParseDeclarationSpecifiers(DS);
Mike Stump11289f42009-09-09 15:08:12 +00006392
Faisal Vali2b391ab2013-09-26 19:54:12 +00006393
Fangrui Song6907ce22018-07-30 19:24:48 +00006394 // Parse the declarator. This is "PrototypeContext" or
6395 // "LambdaExprParameterContext", because we must accept either
Faisal Vali2b391ab2013-09-26 19:54:12 +00006396 // 'declarator' or 'abstract-declarator' here.
Faisal Vali421b2d12017-12-29 05:41:00 +00006397 Declarator ParmDeclarator(
6398 DS, D.getContext() == DeclaratorContext::LambdaExprContext
6399 ? DeclaratorContext::LambdaExprParameterContext
6400 : DeclaratorContext::PrototypeContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00006401 ParseDeclarator(ParmDeclarator);
Chris Lattner371ed4e2008-04-06 06:57:35 +00006402
6403 // Parse GNU attributes, if present.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006404 MaybeParseGNUAttributes(ParmDeclarator);
Mike Stump11289f42009-09-09 15:08:12 +00006405
Chris Lattner371ed4e2008-04-06 06:57:35 +00006406 // Remember this parsed parameter in ParamInfo.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006407 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
Mike Stump11289f42009-09-09 15:08:12 +00006408
Douglas Gregor4d87df52008-12-16 21:30:33 +00006409 // DefArgToks is used when the parsing of default arguments needs
6410 // to be delayed.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006411 std::unique_ptr<CachedTokens> DefArgToks;
Douglas Gregor4d87df52008-12-16 21:30:33 +00006412
Chris Lattner371ed4e2008-04-06 06:57:35 +00006413 // If no parameter was specified, verify that *something* was specified,
6414 // otherwise we have a missing type and identifier.
Craig Topper161e4db2014-05-21 06:02:52 +00006415 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
Faisal Vali2b391ab2013-09-26 19:54:12 +00006416 ParmDeclarator.getNumTypeObjects() == 0) {
Chris Lattner371ed4e2008-04-06 06:57:35 +00006417 // Completely missing, emit error.
6418 Diag(DSStart, diag::err_missing_param);
6419 } else {
6420 // Otherwise, we have something. Add it and let semantic analysis try
6421 // to grok it and add the result to the ParamInfo we are building.
Mike Stump11289f42009-09-09 15:08:12 +00006422
Richard Smith36ee9fb2014-08-11 23:30:23 +00006423 // Last chance to recover from a misplaced ellipsis in an attempted
6424 // parameter pack declaration.
6425 if (Tok.is(tok::ellipsis) &&
6426 (NextToken().isNot(tok::r_paren) ||
6427 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6428 !Actions.isUnexpandedParameterPackPermitted())) &&
6429 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6430 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6431
Chris Lattner371ed4e2008-04-06 06:57:35 +00006432 // Inform the actions module about the parameter declarator, so it gets
6433 // added to the current scope.
Richard Smith95e1fb02014-08-27 03:23:12 +00006434 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006435 // Parse the default argument, if any. We parse the default
6436 // arguments in all dialects; the semantic analysis in
6437 // ActOnParamDefaultArgument will reject the default argument in
6438 // C.
6439 if (Tok.is(tok::equal)) {
Douglas Gregor58354032008-12-24 00:01:03 +00006440 SourceLocation EqualLoc = Tok.getLocation();
6441
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006442 // Parse the default argument
Faisal Vali421b2d12017-12-29 05:41:00 +00006443 if (D.getContext() == DeclaratorContext::MemberContext) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006444 // If we're inside a class definition, cache the tokens
6445 // corresponding to the default argument. We'll actually parse
6446 // them when we see the end of the class definition.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006447 DefArgToks.reset(new CachedTokens);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006448
David Majnemer906ed272015-01-13 05:28:24 +00006449 SourceLocation ArgStartLoc = NextToken().getLocation();
Richard Smith1fff95c2013-09-12 23:28:08 +00006450 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006451 DefArgToks.reset();
Serge Pavlovb4b35782014-07-22 01:54:49 +00006452 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006453 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006454 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
David Majnemer906ed272015-01-13 05:28:24 +00006455 ArgStartLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006456 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006457 } else {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006458 // Consume the '='.
Douglas Gregor58354032008-12-24 00:01:03 +00006459 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00006460
Chad Rosierc1183952012-06-26 22:30:43 +00006461 // The argument isn't actually potentially evaluated unless it is
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006462 // used.
Faisal Valid143a0c2017-04-01 21:30:49 +00006463 EnterExpressionEvaluationContext Eval(
6464 Actions,
6465 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6466 Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006467
Sebastian Redldb63af22012-03-14 15:54:00 +00006468 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006469 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006470 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +00006471 DefArgResult = ParseBraceInitializer();
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006472 } else
Sebastian Redldb63af22012-03-14 15:54:00 +00006473 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +00006474 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006475 if (DefArgResult.isInvalid()) {
Serge Pavlovb4b35782014-07-22 01:54:49 +00006476 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Alexey Bataevee6507d2013-11-18 08:17:37 +00006477 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006478 } else {
6479 // Inform the actions module about the default argument
6480 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006481 DefArgResult.get());
Douglas Gregor4d87df52008-12-16 21:30:33 +00006482 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006483 }
6484 }
Mike Stump11289f42009-09-09 15:08:12 +00006485
6486 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
Fangrui Song6907ce22018-07-30 19:24:48 +00006487 ParmDeclarator.getIdentifierLoc(),
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006488 Param, std::move(DefArgToks)));
Chris Lattner371ed4e2008-04-06 06:57:35 +00006489 }
6490
Richard Smith36ee9fb2014-08-11 23:30:23 +00006491 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6492 if (!getLangOpts().CPlusPlus) {
6493 // We have ellipsis without a preceding ',', which is ill-formed
6494 // in C. Complain and provide the fix.
6495 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6496 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6497 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6498 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6499 // It looks like this was supposed to be a parameter pack. Warn and
6500 // point out where the ellipsis should have gone.
6501 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6502 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6503 << ParmEllipsis.isValid() << ParmEllipsis;
6504 if (ParmEllipsis.isValid()) {
6505 Diag(ParmEllipsis,
6506 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6507 } else {
6508 Diag(ParmDeclarator.getIdentifierLoc(),
6509 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6510 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6511 "...")
6512 << !ParmDeclarator.hasName();
6513 }
6514 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006515 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
Richard Smith36ee9fb2014-08-11 23:30:23 +00006516 }
6517
6518 // We can't have any more parameters after an ellipsis.
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006519 break;
6520 }
Mike Stump11289f42009-09-09 15:08:12 +00006521
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006522 // If the next token is a comma, consume it and keep reading arguments.
6523 } while (TryConsumeToken(tok::comma));
Chris Lattner6c940e62008-04-06 06:34:08 +00006524}
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006525
Chris Lattnere8074e62006-08-06 18:30:15 +00006526/// [C90] direct-declarator '[' constant-expression[opt] ']'
6527/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6528/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6529/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6530/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006531/// [C++11] direct-declarator '[' constant-expression[opt] ']'
6532/// attribute-specifier-seq[opt]
Chris Lattnere8074e62006-08-06 18:30:15 +00006533void Parser::ParseBracketDeclarator(Declarator &D) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006534 if (CheckProhibitedCXX11Attribute())
6535 return;
6536
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006537 BalancedDelimiterTracker T(*this, tok::l_square);
6538 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00006539
Chris Lattner84a11622008-12-18 07:27:21 +00006540 // C array syntax has many features, but by-far the most common is [] and [4].
6541 // This code does a fast path to handle some of the most obvious cases.
6542 if (Tok.getKind() == tok::r_square) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006543 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006544 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006545 MaybeParseCXX11Attributes(attrs);
Chad Rosierc1183952012-06-26 22:30:43 +00006546
Chris Lattner84a11622008-12-18 07:27:21 +00006547 // Remember that we parsed the empty array type.
Craig Topper161e4db2014-05-21 06:02:52 +00006548 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006549 T.getOpenLocation(),
6550 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006551 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006552 return;
6553 } else if (Tok.getKind() == tok::numeric_constant &&
6554 GetLookAheadToken(1).is(tok::r_square)) {
6555 // [4] is very common. Parse the numeric constant expression.
Richard Smithbcc22fc2012-03-09 08:00:36 +00006556 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
Chris Lattner84a11622008-12-18 07:27:21 +00006557 ConsumeToken();
6558
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006559 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006560 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006561 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006562
Chris Lattner84a11622008-12-18 07:27:21 +00006563 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006564 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006565 T.getOpenLocation(),
6566 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00006567 std::move(attrs), T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006568 return;
Benjamin Kramer72dae622016-02-18 15:30:24 +00006569 } else if (Tok.getKind() == tok::code_completion) {
6570 Actions.CodeCompleteBracketDeclarator(getCurScope());
6571 return cutOffParsing();
Chris Lattner84a11622008-12-18 07:27:21 +00006572 }
Mike Stump11289f42009-09-09 15:08:12 +00006573
Chris Lattnere8074e62006-08-06 18:30:15 +00006574 // If valid, this location is the position where we read the 'static' keyword.
6575 SourceLocation StaticLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006576 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006577
Chris Lattnere8074e62006-08-06 18:30:15 +00006578 // If there is a type-qualifier-list, read it now.
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006579 // Type qualifiers in an array subscript are a C99 feature.
John McCall084e83d2011-03-24 11:26:52 +00006580 DeclSpec DS(AttrFactory);
Aaron Ballman08b06592014-07-22 12:44:22 +00006581 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
Mike Stump11289f42009-09-09 15:08:12 +00006582
Chris Lattnere8074e62006-08-06 18:30:15 +00006583 // If we haven't already read 'static', check to see if there is one after the
6584 // type-qualifier-list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006585 if (!StaticLoc.isValid())
6586 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006587
Chris Lattnere8074e62006-08-06 18:30:15 +00006588 // Handle "direct-declarator [ type-qual-list[opt] * ]".
Chris Lattnere8074e62006-08-06 18:30:15 +00006589 bool isStar = false;
John McCalldadc5752010-08-24 06:29:42 +00006590 ExprResult NumElements;
Mike Stump11289f42009-09-09 15:08:12 +00006591
Chris Lattner521ff2b2008-04-06 05:26:30 +00006592 // Handle the case where we have '[*]' as the array size. However, a leading
6593 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
Sylvestre Ledru830885c2012-07-23 08:59:39 +00006594 // the token after the star is a ']'. Since stars in arrays are
Chris Lattner521ff2b2008-04-06 05:26:30 +00006595 // infrequent, use of lookahead is not costly here.
6596 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
Chris Lattnerc439f0d2008-04-06 05:27:21 +00006597 ConsumeToken(); // Eat the '*'.
Chris Lattner1906f802006-08-06 19:14:46 +00006598
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006599 if (StaticLoc.isValid()) {
Chris Lattner521ff2b2008-04-06 05:26:30 +00006600 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006601 StaticLoc = SourceLocation(); // Drop the static.
6602 }
Chris Lattner521ff2b2008-04-06 05:26:30 +00006603 isStar = true;
Chris Lattner76c72282007-10-09 17:33:22 +00006604 } else if (Tok.isNot(tok::r_square)) {
Chris Lattner84a11622008-12-18 07:27:21 +00006605 // Note, in C89, this production uses the constant-expr production instead
6606 // of assignment-expr. The only difference is that assignment-expr allows
6607 // things like '=' and '*='. Sema rejects these in C89 mode because they
6608 // are not i-c-e's, so we don't need to distinguish between the two here.
Mike Stump11289f42009-09-09 15:08:12 +00006609
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006610 // Parse the constant-expression or assignment-expression now (depending
6611 // on dialect).
David Blaikiebbafb8a2012-03-11 07:00:24 +00006612 if (getLangOpts().CPlusPlus) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006613 NumElements = ParseConstantExpression();
Eli Friedmane0afc982012-01-21 01:01:51 +00006614 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00006615 EnterExpressionEvaluationContext Unevaluated(
6616 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Kaelyn Takata15867822014-11-21 18:48:04 +00006617 NumElements =
6618 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Eli Friedmane0afc982012-01-21 01:01:51 +00006619 }
David Majnemerf9834d52014-08-08 07:21:18 +00006620 } else {
6621 if (StaticLoc.isValid()) {
6622 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6623 StaticLoc = SourceLocation(); // Drop the static.
6624 }
Chris Lattner62591722006-08-12 18:40:58 +00006625 }
Mike Stump11289f42009-09-09 15:08:12 +00006626
Chris Lattner62591722006-08-12 18:40:58 +00006627 // If there was an error parsing the assignment-expression, recover.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00006628 if (NumElements.isInvalid()) {
Chris Lattnercd2a8c52009-04-24 22:30:50 +00006629 D.setInvalidType(true);
Chris Lattner62591722006-08-12 18:40:58 +00006630 // If the expression was invalid, skip it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00006631 SkipUntil(tok::r_square, StopAtSemi);
Chris Lattner62591722006-08-12 18:40:58 +00006632 return;
Chris Lattnere8074e62006-08-06 18:30:15 +00006633 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006634
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006635 T.consumeClose();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006636
Jordan Rose303e2f12016-11-10 23:28:17 +00006637 MaybeParseCXX11Attributes(DS.getAttributes());
Alexis Hunt96d5c762009-11-21 08:43:09 +00006638
Chris Lattner84a11622008-12-18 07:27:21 +00006639 // Remember that we parsed a array type, and remember its features.
Erich Keanec480f302018-07-12 21:09:05 +00006640 D.AddTypeInfo(
6641 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6642 isStar, NumElements.get(), T.getOpenLocation(),
6643 T.getCloseLocation()),
6644 std::move(DS.getAttributes()), T.getCloseLocation());
Chris Lattnere8074e62006-08-06 18:30:15 +00006645}
6646
Richard Trieuf4b81d02014-06-24 23:14:24 +00006647/// Diagnose brackets before an identifier.
6648void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6649 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6650 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6651
6652 SourceLocation StartBracketLoc = Tok.getLocation();
6653 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6654
6655 while (Tok.is(tok::l_square)) {
6656 ParseBracketDeclarator(TempDeclarator);
6657 }
6658
6659 // Stuff the location of the start of the brackets into the Declarator.
6660 // The diagnostics from ParseDirectDeclarator will make more sense if
6661 // they use this location instead.
6662 if (Tok.is(tok::semi))
6663 D.getName().EndLocation = StartBracketLoc;
6664
6665 SourceLocation SuggestParenLoc = Tok.getLocation();
6666
6667 // Now that the brackets are removed, try parsing the declarator again.
6668 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6669
6670 // Something went wrong parsing the brackets, in which case,
6671 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6672 // one here.
6673 if (TempDeclarator.getNumTypeObjects() == 0)
6674 return;
6675
6676 // Determine if parens will need to be suggested in the diagnostic.
6677 bool NeedParens = false;
6678 if (D.getNumTypeObjects() != 0) {
6679 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6680 case DeclaratorChunk::Pointer:
6681 case DeclaratorChunk::Reference:
6682 case DeclaratorChunk::BlockPointer:
6683 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00006684 case DeclaratorChunk::Pipe:
Richard Trieuf4b81d02014-06-24 23:14:24 +00006685 NeedParens = true;
6686 break;
6687 case DeclaratorChunk::Array:
6688 case DeclaratorChunk::Function:
6689 case DeclaratorChunk::Paren:
6690 break;
6691 }
6692 }
6693
6694 if (NeedParens) {
6695 // Create a DeclaratorChunk for the inserted parens.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006696 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Erich Keanec480f302018-07-12 21:09:05 +00006697 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
Richard Trieuf4b81d02014-06-24 23:14:24 +00006698 SourceLocation());
6699 }
6700
6701 // Adding back the bracket info to the end of the Declarator.
6702 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6703 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
Erich Keanec480f302018-07-12 21:09:05 +00006704 D.AddTypeInfo(Chunk, SourceLocation());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006705 }
6706
6707 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6708 // If parentheses are required, always suggest them.
6709 if (!D.getIdentifier() && !NeedParens)
6710 return;
6711
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006712 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
Richard Trieuf4b81d02014-06-24 23:14:24 +00006713
6714 // Generate the move bracket error message.
6715 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006716 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
Richard Trieuf4b81d02014-06-24 23:14:24 +00006717
6718 if (NeedParens) {
6719 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6720 << getLangOpts().CPlusPlus
6721 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6722 << FixItHint::CreateInsertion(EndLoc, ")")
6723 << FixItHint::CreateInsertionFromRange(
6724 EndLoc, CharSourceRange(BracketRange, true))
6725 << FixItHint::CreateRemoval(BracketRange);
6726 } else {
6727 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6728 << getLangOpts().CPlusPlus
6729 << FixItHint::CreateInsertionFromRange(
6730 EndLoc, CharSourceRange(BracketRange, true))
6731 << FixItHint::CreateRemoval(BracketRange);
6732 }
6733}
6734
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006735/// [GNU] typeof-specifier:
6736/// typeof ( expressions )
6737/// typeof ( type-name )
6738/// [GNU/C++] typeof unary-expression
Steve Naroffad373bd2007-07-31 12:34:36 +00006739///
6740void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
Chris Lattner76c72282007-10-09 17:33:22 +00006741 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006742 Token OpTok = Tok;
Steve Naroffad373bd2007-07-31 12:34:36 +00006743 SourceLocation StartLoc = ConsumeToken();
6744
John McCalle8595032010-01-13 20:03:27 +00006745 const bool hasParens = Tok.is(tok::l_paren);
6746
Faisal Valid143a0c2017-04-01 21:30:49 +00006747 EnterExpressionEvaluationContext Unevaluated(
6748 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6749 Sema::ReuseLambdaContextDecl);
Eli Friedmane0afc982012-01-21 01:01:51 +00006750
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006751 bool isCastExpr;
John McCallba7bf592010-08-24 05:47:05 +00006752 ParsedType CastTy;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006753 SourceRange CastRange;
Kaelyn Takata911260742014-12-19 01:28:40 +00006754 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6755 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
John McCalle8595032010-01-13 20:03:27 +00006756 if (hasParens)
6757 DS.setTypeofParensRange(CastRange);
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006758
6759 if (CastRange.getEnd().isInvalid())
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006760 // FIXME: Not accurate, the range gets one token more than it should.
6761 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006762 else
6763 DS.SetRangeEnd(CastRange.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +00006764
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006765 if (isCastExpr) {
6766 if (!CastTy) {
6767 DS.SetTypeSpecError();
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006768 return;
Douglas Gregor220cac52009-02-18 17:45:20 +00006769 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006770
Craig Topper161e4db2014-05-21 06:02:52 +00006771 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006772 unsigned DiagID;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006773 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6774 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006775 DiagID, CastTy,
6776 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006777 Diag(StartLoc, DiagID) << PrevSpec;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006778 return;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006779 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006780
Hiroshi Inoue533777f2017-07-02 06:12:49 +00006781 // If we get here, the operand to the typeof was an expression.
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006782 if (Operand.isInvalid()) {
6783 DS.SetTypeSpecError();
Steve Naroff4bd2f712007-08-02 02:53:48 +00006784 return;
Steve Naroffad373bd2007-07-31 12:34:36 +00006785 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006786
Eli Friedmane0afc982012-01-21 01:01:51 +00006787 // We might need to transform the operand if it is potentially evaluated.
6788 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6789 if (Operand.isInvalid()) {
6790 DS.SetTypeSpecError();
6791 return;
6792 }
6793
Craig Topper161e4db2014-05-21 06:02:52 +00006794 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006795 unsigned DiagID;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006796 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6797 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006798 DiagID, Operand.get(),
6799 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006800 Diag(StartLoc, DiagID) << PrevSpec;
Steve Naroffad373bd2007-07-31 12:34:36 +00006801}
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006802
Benjamin Kramere56f3932011-12-23 17:00:35 +00006803/// [C11] atomic-specifier:
Eli Friedman0dfb8892011-10-06 23:00:33 +00006804/// _Atomic ( type-name )
6805///
6806void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
Richard Smith8e1ac332013-03-28 01:55:44 +00006807 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6808 "Not an atomic specifier");
Eli Friedman0dfb8892011-10-06 23:00:33 +00006809
6810 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006811 BalancedDelimiterTracker T(*this, tok::l_paren);
Richard Smith8e1ac332013-03-28 01:55:44 +00006812 if (T.consumeOpen())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006813 return;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006814
6815 TypeResult Result = ParseTypeName();
6816 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00006817 SkipUntil(tok::r_paren, StopAtSemi);
Eli Friedman0dfb8892011-10-06 23:00:33 +00006818 return;
6819 }
6820
6821 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006822 T.consumeClose();
Eli Friedman0dfb8892011-10-06 23:00:33 +00006823
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006824 if (T.getCloseLocation().isInvalid())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006825 return;
6826
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006827 DS.setTypeofParensRange(T.getRange());
6828 DS.SetRangeEnd(T.getCloseLocation());
Eli Friedman0dfb8892011-10-06 23:00:33 +00006829
Craig Topper161e4db2014-05-21 06:02:52 +00006830 const char *PrevSpec = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006831 unsigned DiagID;
6832 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006833 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006834 Actions.getASTContext().getPrintingPolicy()))
Eli Friedman0dfb8892011-10-06 23:00:33 +00006835 Diag(StartLoc, DiagID) << PrevSpec;
6836}
6837
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006838/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6839/// from TryAltiVecVectorToken.
6840bool Parser::TryAltiVecVectorTokenOutOfLine() {
6841 Token Next = NextToken();
6842 switch (Next.getKind()) {
6843 default: return false;
6844 case tok::kw_short:
6845 case tok::kw_long:
6846 case tok::kw_signed:
6847 case tok::kw_unsigned:
6848 case tok::kw_void:
6849 case tok::kw_char:
6850 case tok::kw_int:
6851 case tok::kw_float:
6852 case tok::kw_double:
6853 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006854 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006855 case tok::kw___pixel:
6856 Tok.setKind(tok::kw___vector);
6857 return true;
6858 case tok::identifier:
6859 if (Next.getIdentifierInfo() == Ident_pixel) {
6860 Tok.setKind(tok::kw___vector);
6861 return true;
6862 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006863 if (Next.getIdentifierInfo() == Ident_bool) {
6864 Tok.setKind(tok::kw___vector);
6865 return true;
6866 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006867 return false;
6868 }
6869}
6870
6871bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6872 const char *&PrevSpec, unsigned &DiagID,
6873 bool &isInvalid) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006874 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006875 if (Tok.getIdentifierInfo() == Ident_vector) {
6876 Token Next = NextToken();
6877 switch (Next.getKind()) {
6878 case tok::kw_short:
6879 case tok::kw_long:
6880 case tok::kw_signed:
6881 case tok::kw_unsigned:
6882 case tok::kw_void:
6883 case tok::kw_char:
6884 case tok::kw_int:
6885 case tok::kw_float:
6886 case tok::kw_double:
6887 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006888 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006889 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006890 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006891 return true;
6892 case tok::identifier:
6893 if (Next.getIdentifierInfo() == Ident_pixel) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006894 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006895 return true;
6896 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006897 if (Next.getIdentifierInfo() == Ident_bool) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006898 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00006899 return true;
6900 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006901 break;
6902 default:
6903 break;
6904 }
Douglas Gregor9938e3b2010-06-16 15:28:57 +00006905 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006906 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006907 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006908 return true;
Bill Schmidt99a084b2013-07-03 20:54:09 +00006909 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6910 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006911 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00006912 return true;
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006913 }
6914 return false;
6915}