blob: d1f87c9df07398fa6db8a20278b7d205f0c36b05 [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)
56 DS.addAttributes(Attrs->getList());
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,
Aaron Ballman00e99962013-08-31 01:11:41 +0000165 AttributeList::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,
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000172 SourceLocation(), AttributeList::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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000218/// Determine whether the given attribute parses a type argument.
Aaron Ballman4768b312013-11-04 12:55:56 +0000219static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000220#define CLANG_ATTR_TYPE_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000221 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000222#include "clang/Parse/AttrParserStringSwitches.inc"
Aaron Ballman4768b312013-11-04 12:55:56 +0000223 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000224#undef CLANG_ATTR_TYPE_ARG_LIST
Aaron Ballman4768b312013-11-04 12:55:56 +0000225}
226
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000227/// Determine whether the given attribute requires parsing its arguments
Aaron Ballman15b27b92014-01-09 19:39:35 +0000228/// in an unevaluated context or not.
229static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
Aaron Ballman35db2b32014-01-29 22:13:45 +0000230#define CLANG_ATTR_ARG_CONTEXT_LIST
Aaron Ballman15b27b92014-01-09 19:39:35 +0000231 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
Aaron Ballman35db2b32014-01-29 22:13:45 +0000232#include "clang/Parse/AttrParserStringSwitches.inc"
Aaron Ballman15b27b92014-01-09 19:39:35 +0000233 .Default(false);
Aaron Ballman35db2b32014-01-29 22:13:45 +0000234#undef CLANG_ATTR_ARG_CONTEXT_LIST
Aaron Ballman15b27b92014-01-09 19:39:35 +0000235}
236
Richard Smithfeefaf52013-09-03 18:01:40 +0000237IdentifierLoc *Parser::ParseIdentifierLoc() {
238 assert(Tok.is(tok::identifier) && "expected an identifier");
239 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
240 Tok.getLocation(),
241 Tok.getIdentifierInfo());
242 ConsumeToken();
243 return IL;
244}
245
Richard Smithb1f9a282013-10-31 01:56:18 +0000246void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
247 SourceLocation AttrNameLoc,
248 ParsedAttributes &Attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000249 SourceLocation *EndLoc,
250 IdentifierInfo *ScopeName,
251 SourceLocation ScopeLoc,
252 AttributeList::Syntax Syntax) {
Richard Smithb1f9a282013-10-31 01:56:18 +0000253 BalancedDelimiterTracker Parens(*this, tok::l_paren);
254 Parens.consumeOpen();
255
256 TypeResult T;
257 if (Tok.isNot(tok::r_paren))
258 T = ParseTypeName();
259
260 if (Parens.consumeClose())
261 return;
262
263 if (T.isInvalid())
264 return;
265
266 if (T.isUsable())
267 Attrs.addNewTypeAttr(&AttrName,
Craig Topper161e4db2014-05-21 06:02:52 +0000268 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000269 ScopeName, ScopeLoc, T.get(), Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000270 else
271 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000272 ScopeName, ScopeLoc, nullptr, 0, Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000273}
274
Aaron Ballman35f94212014-04-14 16:03:22 +0000275unsigned Parser::ParseAttributeArgsCommon(
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000276 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
277 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
278 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
279 // Ignore the left paren location for now.
280 ConsumeParen();
281
282 ArgsVector ArgExprs;
283 if (Tok.is(tok::identifier)) {
284 // If this attribute wants an 'identifier' argument, make it so.
285 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName);
286 AttributeList::Kind AttrKind =
287 AttributeList::getKind(AttrName, ScopeName, Syntax);
288
289 // If we don't know how to parse this attribute, but this is the only
290 // token in this argument, assume it's meant to be an identifier.
291 if (AttrKind == AttributeList::UnknownAttribute ||
292 AttrKind == AttributeList::IgnoredAttribute) {
293 const Token &Next = NextToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000294 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000295 }
296
297 if (IsIdentifierArg)
298 ArgExprs.push_back(ParseIdentifierLoc());
299 }
300
301 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
302 // Eat the comma.
303 if (!ArgExprs.empty())
304 ConsumeToken();
305
306 // Parse the non-empty comma-separated list of expressions.
307 do {
Richard Smith917316f2017-01-07 19:42:26 +0000308 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
George Burgess IVa19ea342016-11-10 20:43:52 +0000309 EnterExpressionEvaluationContext Unevaluated(
Faisal Valid143a0c2017-04-01 21:30:49 +0000310 Actions,
311 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
312 : Sema::ExpressionEvaluationContext::ConstantEvaluated,
Richard Smith917316f2017-01-07 19:42:26 +0000313 /*LambdaContextDecl=*/nullptr,
314 /*IsDecltype=*/false);
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000315
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000316 ExprResult ArgExpr(
317 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000318 if (ArgExpr.isInvalid()) {
319 SkipUntil(tok::r_paren, StopAtSemi);
Aaron Ballman35f94212014-04-14 16:03:22 +0000320 return 0;
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000321 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000322 ArgExprs.push_back(ArgExpr.get());
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000323 // Eat the comma, move to the next argument
324 } while (TryConsumeToken(tok::comma));
325 }
326
327 SourceLocation RParen = Tok.getLocation();
328 if (!ExpectAndConsume(tok::r_paren)) {
329 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
330 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
331 ArgExprs.data(), ArgExprs.size(), Syntax);
332 }
333
334 if (EndLoc)
335 *EndLoc = RParen;
Aaron Ballman35f94212014-04-14 16:03:22 +0000336
337 return static_cast<unsigned>(ArgExprs.size());
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000338}
339
Michael Han23214e52012-10-03 01:56:22 +0000340/// Parse the arguments to a parameterized GNU attribute or
341/// a C++11 attribute in "gnu" namespace.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000342void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
343 SourceLocation AttrNameLoc,
344 ParsedAttributes &Attrs,
Michael Han23214e52012-10-03 01:56:22 +0000345 SourceLocation *EndLoc,
346 IdentifierInfo *ScopeName,
347 SourceLocation ScopeLoc,
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000348 AttributeList::Syntax Syntax,
349 Declarator *D) {
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000350
351 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
352
Richard Smith66e71682013-10-24 01:07:54 +0000353 AttributeList::Kind AttrKind =
Richard Smithb1f9a282013-10-31 01:56:18 +0000354 AttributeList::getKind(AttrName, ScopeName, Syntax);
Richard Smith66e71682013-10-24 01:07:54 +0000355
Richard Smith66e71682013-10-24 01:07:54 +0000356 if (AttrKind == AttributeList::AT_Availability) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000357 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
358 ScopeLoc, Syntax);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000359 return;
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000360 } else if (AttrKind == AttributeList::AT_ExternalSourceSymbol) {
361 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
362 ScopeName, ScopeLoc, Syntax);
363 return;
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000364 } else if (AttrKind == AttributeList::AT_ObjCBridgeRelated) {
365 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
366 ScopeName, ScopeLoc, Syntax);
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +0000367 return;
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000368 } else if (AttrKind == AttributeList::AT_TypeTagForDatatype) {
369 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
370 ScopeName, ScopeLoc, Syntax);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000371 return;
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000372 } else if (attributeIsTypeArgAttr(*AttrName)) {
373 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
374 ScopeLoc, Syntax);
Richard Smithb1f9a282013-10-31 01:56:18 +0000375 return;
376 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000377
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000378 // These may refer to the function arguments, but need to be parsed early to
379 // participate in determining whether it's a redeclaration.
George Burgess IVa19ea342016-11-10 20:43:52 +0000380 llvm::Optional<ParseScope> PrototypeScope;
Ulrich Weigandef5aa292015-07-13 14:13:01 +0000381 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
382 D && D->isFunctionDeclarator()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000383 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
George Burgess IVa19ea342016-11-10 20:43:52 +0000384 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
385 Scope::FunctionDeclarationScope |
386 Scope::DeclScope);
Alp Tokerc5350722014-02-26 22:27:52 +0000387 for (unsigned i = 0; i != FTI.NumParams; ++i) {
388 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000389 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
390 }
391 }
392
Aaron Ballmanb8e20392014-03-31 17:32:39 +0000393 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
394 ScopeLoc, Syntax);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +0000395}
396
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000397unsigned Parser::ParseClangAttributeArgs(
398 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
399 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
400 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
401 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
402
403 AttributeList::Kind AttrKind =
404 AttributeList::getKind(AttrName, ScopeName, Syntax);
405
Aaron Ballman38bbc162018-02-24 17:16:42 +0000406 switch (AttrKind) {
407 default:
408 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
409 ScopeName, ScopeLoc, Syntax);
410 case AttributeList::AT_ExternalSourceSymbol:
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000411 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
412 ScopeName, ScopeLoc, Syntax);
Aaron Ballman38bbc162018-02-24 17:16:42 +0000413 break;
414 case AttributeList::AT_Availability:
415 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
416 ScopeLoc, Syntax);
417 break;
Aaron Ballmanc248b0f2018-02-24 17:37:37 +0000418 case AttributeList::AT_ObjCBridgeRelated:
419 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
420 ScopeName, ScopeLoc, Syntax);
421 break;
Aaron Ballmana26d8ee2018-02-25 14:01:04 +0000422 case AttributeList::AT_TypeTagForDatatype:
423 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
424 ScopeName, ScopeLoc, Syntax);
425 break;
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000426 }
Aaron Ballman38bbc162018-02-24 17:16:42 +0000427 return Attrs.getList() ? Attrs.getList()->getNumArgs() : 0;
Alex Lorenzd5d27e12017-03-01 18:06:25 +0000428}
429
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000430bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
431 SourceLocation AttrNameLoc,
432 ParsedAttributes &Attrs) {
433 // If the attribute isn't known, we will not attempt to parse any
434 // arguments.
435 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
Bob Wilson7c730832015-07-20 22:57:31 +0000436 getTargetInfo(), getLangOpts())) {
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000437 // Eat the left paren, then skip to the ending right paren.
438 ConsumeParen();
439 SkipUntil(tok::r_paren);
440 return false;
Aaron Ballman478faed2012-06-19 22:09:27 +0000441 }
Aaron Ballman478faed2012-06-19 22:09:27 +0000442
Aaron Ballman95d57032014-04-14 16:44:26 +0000443 SourceLocation OpenParenLoc = Tok.getLocation();
444
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000445 if (AttrName->getName() == "property") {
Aaron Ballman478faed2012-06-19 22:09:27 +0000446 // The property declspec is more complex in that it can take one or two
Chad Rosierc1183952012-06-26 22:30:43 +0000447 // assignment expressions as a parameter, but the lhs of the assignment
Aaron Ballman478faed2012-06-19 22:09:27 +0000448 // must be named get or put.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000449
John McCall5e77d762013-04-16 07:28:30 +0000450 BalancedDelimiterTracker T(*this, tok::l_paren);
451 T.expectAndConsume(diag::err_expected_lparen_after,
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000452 AttrName->getNameStart(), tok::r_paren);
John McCall5e77d762013-04-16 07:28:30 +0000453
454 enum AccessorKind {
455 AK_Invalid = -1,
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000456 AK_Put = 0,
457 AK_Get = 1 // indices into AccessorNames
John McCall5e77d762013-04-16 07:28:30 +0000458 };
Craig Topper161e4db2014-05-21 06:02:52 +0000459 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
John McCall5e77d762013-04-16 07:28:30 +0000460 bool HasInvalidAccessor = false;
461
462 // Parse the accessor specifications.
463 while (true) {
464 // Stop if this doesn't look like an accessor spec.
465 if (!Tok.is(tok::identifier)) {
466 // If the user wrote a completely empty list, use a special diagnostic.
467 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
Craig Topper161e4db2014-05-21 06:02:52 +0000468 AccessorNames[AK_Put] == nullptr &&
469 AccessorNames[AK_Get] == nullptr) {
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000470 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
John McCall5e77d762013-04-16 07:28:30 +0000471 break;
472 }
473
474 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
475 break;
476 }
477
478 AccessorKind Kind;
479 SourceLocation KindLoc = Tok.getLocation();
480 StringRef KindStr = Tok.getIdentifierInfo()->getName();
481 if (KindStr == "get") {
482 Kind = AK_Get;
483 } else if (KindStr == "put") {
484 Kind = AK_Put;
485
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000486 // Recover from the common mistake of using 'set' instead of 'put'.
John McCall5e77d762013-04-16 07:28:30 +0000487 } else if (KindStr == "set") {
488 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000489 << FixItHint::CreateReplacement(KindLoc, "put");
John McCall5e77d762013-04-16 07:28:30 +0000490 Kind = AK_Put;
491
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000492 // Handle the mistake of forgetting the accessor kind by skipping
493 // this accessor.
John McCall5e77d762013-04-16 07:28:30 +0000494 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
495 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
496 ConsumeToken();
497 HasInvalidAccessor = true;
498 goto next_property_accessor;
499
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000500 // Otherwise, complain about the unknown accessor kind.
John McCall5e77d762013-04-16 07:28:30 +0000501 } else {
502 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
503 HasInvalidAccessor = true;
504 Kind = AK_Invalid;
505
506 // Try to keep parsing unless it doesn't look like an accessor spec.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000507 if (!NextToken().is(tok::equal))
508 break;
John McCall5e77d762013-04-16 07:28:30 +0000509 }
510
511 // Consume the identifier.
512 ConsumeToken();
513
514 // Consume the '='.
Alp Toker8fbec672013-12-17 23:29:36 +0000515 if (!TryConsumeToken(tok::equal)) {
John McCall5e77d762013-04-16 07:28:30 +0000516 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000517 << KindStr;
John McCall5e77d762013-04-16 07:28:30 +0000518 break;
519 }
520
521 // Expect the method name.
522 if (!Tok.is(tok::identifier)) {
523 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
524 break;
525 }
526
527 if (Kind == AK_Invalid) {
528 // Just drop invalid accessors.
Craig Topper161e4db2014-05-21 06:02:52 +0000529 } else if (AccessorNames[Kind] != nullptr) {
John McCall5e77d762013-04-16 07:28:30 +0000530 // Complain about the repeated accessor, ignore it, and keep parsing.
531 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
532 } else {
533 AccessorNames[Kind] = Tok.getIdentifierInfo();
534 }
535 ConsumeToken();
536
537 next_property_accessor:
538 // Keep processing accessors until we run out.
Alp Toker094e5212014-01-05 03:27:11 +0000539 if (TryConsumeToken(tok::comma))
John McCall5e77d762013-04-16 07:28:30 +0000540 continue;
541
542 // If we run into the ')', stop without consuming it.
Alp Toker094e5212014-01-05 03:27:11 +0000543 if (Tok.is(tok::r_paren))
John McCall5e77d762013-04-16 07:28:30 +0000544 break;
Alp Toker094e5212014-01-05 03:27:11 +0000545
546 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
547 break;
John McCall5e77d762013-04-16 07:28:30 +0000548 }
549
550 // Only add the property attribute if it was well-formed.
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000551 if (!HasInvalidAccessor)
Craig Topper161e4db2014-05-21 06:02:52 +0000552 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
John McCall5e77d762013-04-16 07:28:30 +0000553 AccessorNames[AK_Get], AccessorNames[AK_Put],
554 AttributeList::AS_Declspec);
Aaron Ballman478faed2012-06-19 22:09:27 +0000555 T.skipToEnd();
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000556 return !HasInvalidAccessor;
Aaron Ballman478faed2012-06-19 22:09:27 +0000557 }
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000558
Aaron Ballman95d57032014-04-14 16:44:26 +0000559 unsigned NumArgs =
560 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
561 SourceLocation(), AttributeList::AS_Declspec);
562
563 // If this attribute's args were parsed, and it was expected to have
564 // arguments but none were provided, emit a diagnostic.
565 const AttributeList *Attr = Attrs.getList();
566 if (Attr && Attr->getMaxArgs() && !NumArgs) {
Aaron Ballmanef5d94c2014-04-15 00:36:39 +0000567 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
Aaron Ballman95d57032014-04-14 16:44:26 +0000568 return false;
569 }
Aaron Ballmanfdd783a2014-03-31 18:18:43 +0000570 return true;
Aaron Ballman478faed2012-06-19 22:09:27 +0000571}
572
Eli Friedman06de2b52009-06-08 07:21:15 +0000573/// [MS] decl-specifier:
574/// __declspec ( extended-decl-modifier-seq )
575///
576/// [MS] extended-decl-modifier-seq:
577/// extended-decl-modifier[opt]
578/// extended-decl-modifier extended-decl-modifier-seq
Aaron Ballman068aa512015-05-20 20:58:33 +0000579void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
580 SourceLocation *End) {
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +0000581 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
Steve Naroff3a9b7e02008-12-24 20:59:21 +0000582 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
Eli Friedman06de2b52009-06-08 07:21:15 +0000583
Aaron Ballman068aa512015-05-20 20:58:33 +0000584 while (Tok.is(tok::kw___declspec)) {
585 ConsumeToken();
586 BalancedDelimiterTracker T(*this, tok::l_paren);
587 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
588 tok::r_paren))
Aaron Ballman478faed2012-06-19 22:09:27 +0000589 return;
Aaron Ballman478faed2012-06-19 22:09:27 +0000590
Aaron Ballman068aa512015-05-20 20:58:33 +0000591 // An empty declspec is perfectly legal and should not warn. Additionally,
592 // you can specify multiple attributes per declspec.
593 while (Tok.isNot(tok::r_paren)) {
594 // Attribute not present.
595 if (TryConsumeToken(tok::comma))
596 continue;
597
598 // We expect either a well-known identifier or a generic string. Anything
599 // else is a malformed declspec.
600 bool IsString = Tok.getKind() == tok::string_literal;
601 if (!IsString && Tok.getKind() != tok::identifier &&
602 Tok.getKind() != tok::kw_restrict) {
603 Diag(Tok, diag::err_ms_declspec_type);
Aaron Ballman478faed2012-06-19 22:09:27 +0000604 T.skipToEnd();
605 return;
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000606 }
Aaron Ballman068aa512015-05-20 20:58:33 +0000607
608 IdentifierInfo *AttrName;
609 SourceLocation AttrNameLoc;
610 if (IsString) {
611 SmallString<8> StrBuffer;
612 bool Invalid = false;
613 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
614 if (Invalid) {
615 T.skipToEnd();
616 return;
617 }
618 AttrName = PP.getIdentifierInfo(Str);
619 AttrNameLoc = ConsumeStringToken();
620 } else {
621 AttrName = Tok.getIdentifierInfo();
622 AttrNameLoc = ConsumeToken();
623 }
624
625 bool AttrHandled = false;
626
627 // Parse attribute arguments.
628 if (Tok.is(tok::l_paren))
629 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
630 else if (AttrName->getName() == "property")
631 // The property attribute must have an argument list.
632 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
633 << AttrName->getName();
634
635 if (!AttrHandled)
636 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
637 AttributeList::AS_Declspec);
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000638 }
Aaron Ballman068aa512015-05-20 20:58:33 +0000639 T.consumeClose();
640 if (End)
641 *End = T.getCloseLocation();
Jakob Stoklund Olesene1c0ae62012-06-19 21:48:43 +0000642 }
Eli Friedman53339e02009-06-08 23:27:34 +0000643}
644
John McCall53fa7142010-12-24 02:08:15 +0000645void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
Eli Friedman53339e02009-06-08 23:27:34 +0000646 // Treat these like attributes
Reid Klecknerd7857f02014-10-24 17:42:17 +0000647 while (true) {
648 switch (Tok.getKind()) {
649 case tok::kw___fastcall:
650 case tok::kw___stdcall:
651 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +0000652 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +0000653 case tok::kw___cdecl:
654 case tok::kw___vectorcall:
655 case tok::kw___ptr64:
656 case tok::kw___w64:
657 case tok::kw___ptr32:
Reid Klecknerd7857f02014-10-24 17:42:17 +0000658 case tok::kw___sptr:
659 case tok::kw___uptr: {
660 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
661 SourceLocation AttrNameLoc = ConsumeToken();
662 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
663 AttributeList::AS_Keyword);
664 break;
665 }
666 default:
667 return;
668 }
Eli Friedman53339e02009-06-08 23:27:34 +0000669 }
Steve Naroff3a9b7e02008-12-24 20:59:21 +0000670}
671
Nico Rieckeaaae272014-12-04 23:31:08 +0000672void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
673 SourceLocation StartLoc = Tok.getLocation();
674 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
675
676 if (EndLoc.isValid()) {
677 SourceRange Range(StartLoc, EndLoc);
678 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
679 }
680}
681
682SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
683 SourceLocation EndLoc;
684
685 while (true) {
686 switch (Tok.getKind()) {
687 case tok::kw_const:
688 case tok::kw_volatile:
689 case tok::kw___fastcall:
690 case tok::kw___stdcall:
691 case tok::kw___thiscall:
692 case tok::kw___cdecl:
693 case tok::kw___vectorcall:
694 case tok::kw___ptr32:
695 case tok::kw___ptr64:
696 case tok::kw___w64:
697 case tok::kw___unaligned:
698 case tok::kw___sptr:
699 case tok::kw___uptr:
700 EndLoc = ConsumeToken();
701 break;
702 default:
703 return EndLoc;
704 }
705 }
706}
707
John McCall53fa7142010-12-24 02:08:15 +0000708void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
Dawn Perchik335e16b2010-09-03 01:29:35 +0000709 // Treat these like attributes
710 while (Tok.is(tok::kw___pascal)) {
711 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
712 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000713 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Aaron Ballman00e99962013-08-31 01:11:41 +0000714 AttributeList::AS_Keyword);
Dawn Perchik335e16b2010-09-03 01:29:35 +0000715 }
John McCall53fa7142010-12-24 02:08:15 +0000716}
717
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +0000718void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000719 // Treat these like attributes
720 while (Tok.is(tok::kw___kernel)) {
Richard Smith0cdcc982013-01-29 01:24:26 +0000721 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000722 SourceLocation AttrNameLoc = ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000723 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Aaron Ballman00e99962013-08-31 01:11:41 +0000724 AttributeList::AS_Keyword);
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +0000725 }
726}
727
Aaron Ballman05d76ea2014-01-14 01:29:54 +0000728void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
729 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
730 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +0000731 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
Aaron Ballman26891332014-01-14 17:41:53 +0000732 AttributeList::AS_Keyword);
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000733}
734
Douglas Gregor261a89b2015-06-19 17:51:05 +0000735void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
736 // Treat these like attributes, even though they're type specifiers.
737 while (true) {
738 switch (Tok.getKind()) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +0000739 case tok::kw__Nonnull:
740 case tok::kw__Nullable:
741 case tok::kw__Null_unspecified: {
Douglas Gregor261a89b2015-06-19 17:51:05 +0000742 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
743 SourceLocation AttrNameLoc = ConsumeToken();
744 if (!getLangOpts().ObjC1)
745 Diag(AttrNameLoc, diag::ext_nullability)
746 << AttrName;
747 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
748 AttributeList::AS_Keyword);
749 break;
750 }
751 default:
752 return;
753 }
754 }
755}
756
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000757static bool VersionNumberSeparator(const char Separator) {
758 return (Separator == '.' || Separator == '_');
759}
760
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000761/// Parse a version number.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000762///
763/// version:
764/// simple-integer
Jan Korous23255692018-05-17 11:51:49 +0000765/// simple-integer '.' simple-integer
766/// simple-integer '_' simple-integer
767/// simple-integer '.' simple-integer '.' simple-integer
768/// simple-integer '_' simple-integer '_' simple-integer
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000769VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
Erik Pilkington29099de2016-07-16 00:35:23 +0000770 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000771
772 if (!Tok.is(tok::numeric_constant)) {
773 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000774 SkipUntil(tok::comma, tok::r_paren,
775 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000776 return VersionTuple();
777 }
778
779 // Parse the major (and possibly minor and subminor) versions, which
780 // are stored in the numeric constant. We utilize a quirk of the
781 // lexer, which is that it handles something like 1.2.3 as a single
782 // numeric constant, rather than two separate tokens.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000783 SmallString<512> Buffer;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000784 Buffer.resize(Tok.getLength()+1);
785 const char *ThisTokBegin = &Buffer[0];
786
787 // Get the spelling of the token, which eliminates trigraphs, etc.
788 bool Invalid = false;
789 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
790 if (Invalid)
791 return VersionTuple();
792
793 // Parse the major version.
794 unsigned AfterMajor = 0;
795 unsigned Major = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000796 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000797 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
798 ++AfterMajor;
799 }
800
801 if (AfterMajor == 0) {
802 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000803 SkipUntil(tok::comma, tok::r_paren,
804 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000805 return VersionTuple();
806 }
807
808 if (AfterMajor == ActualLength) {
809 ConsumeToken();
810
811 // We only had a single version component.
812 if (Major == 0) {
813 Diag(Tok, diag::err_zero_version);
814 return VersionTuple();
815 }
816
817 return VersionTuple(Major);
818 }
819
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000820 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
821 if (!VersionNumberSeparator(AfterMajorSeparator)
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000822 || (AfterMajor + 1 == ActualLength)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000823 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000824 SkipUntil(tok::comma, tok::r_paren,
825 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000826 return VersionTuple();
827 }
828
829 // Parse the minor version.
830 unsigned AfterMinor = AfterMajor + 1;
831 unsigned Minor = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000832 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000833 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
834 ++AfterMinor;
835 }
836
837 if (AfterMinor == ActualLength) {
838 ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +0000839
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000840 // We had major.minor.
841 if (Major == 0 && Minor == 0) {
842 Diag(Tok, diag::err_zero_version);
843 return VersionTuple();
844 }
845
Jan Korous23255692018-05-17 11:51:49 +0000846 return VersionTuple(Major, Minor);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000847 }
848
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000849 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
Fariborz Jahaniandbc956d2014-10-02 16:39:45 +0000850 // If what follows is not a '.' or '_', we have a problem.
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000851 if (!VersionNumberSeparator(AfterMinorSeparator)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000852 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000853 SkipUntil(tok::comma, tok::r_paren,
854 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Chad Rosierc1183952012-06-26 22:30:43 +0000855 return VersionTuple();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000856 }
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000857
Fariborz Jahanianb6161612014-10-03 17:21:12 +0000858 // Warn if separators, be it '.' or '_', do not match.
Fariborz Jahaniance72e632014-10-02 17:57:26 +0000859 if (AfterMajorSeparator != AfterMinorSeparator)
860 Diag(Tok, diag::warn_expected_consistent_version_separator);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000861
862 // Parse the subminor version.
863 unsigned AfterSubminor = AfterMinor + 1;
864 unsigned Subminor = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000865 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000866 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
867 ++AfterSubminor;
868 }
869
870 if (AfterSubminor != ActualLength) {
871 Diag(Tok, diag::err_expected_version);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000872 SkipUntil(tok::comma, tok::r_paren,
873 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000874 return VersionTuple();
875 }
876 ConsumeToken();
Jan Korous23255692018-05-17 11:51:49 +0000877 return VersionTuple(Major, Minor, Subminor);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000878}
879
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000880/// Parse the contents of the "availability" attribute.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000881///
882/// availability-attribute:
Manman Ren75bc6762016-03-21 17:30:55 +0000883/// 'availability' '(' platform ',' opt-strict version-arg-list,
884/// opt-replacement, opt-message')'
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000885///
886/// platform:
887/// identifier
888///
Manman Rend8039df2016-02-22 04:47:24 +0000889/// opt-strict:
890/// 'strict' ','
Manman Renb636b902016-02-17 22:05:48 +0000891///
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000892/// version-arg-list:
893/// version-arg
894/// version-arg ',' version-arg-list
895///
896/// version-arg:
897/// 'introduced' '=' version
898/// 'deprecated' '=' version
Douglas Gregorfdd417f2012-03-11 04:53:21 +0000899/// 'obsoleted' = version
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000900/// 'unavailable'
Manman Ren75bc6762016-03-21 17:30:55 +0000901/// opt-replacement:
902/// 'replacement' '=' <string>
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000903/// opt-message:
904/// 'message' '=' <string>
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000905void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
906 SourceLocation AvailabilityLoc,
907 ParsedAttributes &attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +0000908 SourceLocation *endLoc,
909 IdentifierInfo *ScopeName,
910 SourceLocation ScopeLoc,
911 AttributeList::Syntax Syntax) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000912 enum { Introduced, Deprecated, Obsoleted, Unknown };
913 AvailabilityChange Changes[Unknown];
Manman Ren75bc6762016-03-21 17:30:55 +0000914 ExprResult MessageExpr, ReplacementExpr;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000915
916 // Opening '('.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000917 BalancedDelimiterTracker T(*this, tok::l_paren);
918 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +0000919 Diag(Tok, diag::err_expected) << tok::l_paren;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000920 return;
921 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000922
Manman Renb636b902016-02-17 22:05:48 +0000923 // Parse the platform name.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000924 if (Tok.isNot(tok::identifier)) {
925 Diag(Tok, diag::err_availability_expected_platform);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000926 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000927 return;
928 }
Richard Smithfeefaf52013-09-03 18:01:40 +0000929 IdentifierLoc *Platform = ParseIdentifierLoc();
Alex Lorenz0b1ce8b2017-08-15 14:42:01 +0000930 if (const IdentifierInfo *const Ident = Platform->Ident) {
931 // Canonicalize platform name from "macosx" to "macos".
932 if (Ident->getName() == "macosx")
933 Platform->Ident = PP.getIdentifierInfo("macos");
934 // Canonicalize platform name from "macosx_app_extension" to
935 // "macos_app_extension".
936 else if (Ident->getName() == "macosx_app_extension")
937 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
938 else
939 Platform->Ident = PP.getIdentifierInfo(
940 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
941 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000942
943 // Parse the ',' following the platform name.
Alp Toker383d2c42014-01-01 03:08:43 +0000944 if (ExpectAndConsume(tok::comma)) {
945 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000946 return;
Alp Toker383d2c42014-01-01 03:08:43 +0000947 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000948
949 // If we haven't grabbed the pointers for the identifiers
950 // "introduced", "deprecated", and "obsoleted", do so now.
951 if (!Ident_introduced) {
952 Ident_introduced = PP.getIdentifierInfo("introduced");
953 Ident_deprecated = PP.getIdentifierInfo("deprecated");
954 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000955 Ident_unavailable = PP.getIdentifierInfo("unavailable");
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000956 Ident_message = PP.getIdentifierInfo("message");
Manman Rend8039df2016-02-22 04:47:24 +0000957 Ident_strict = PP.getIdentifierInfo("strict");
Manman Ren75bc6762016-03-21 17:30:55 +0000958 Ident_replacement = PP.getIdentifierInfo("replacement");
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000959 }
960
Manman Ren75bc6762016-03-21 17:30:55 +0000961 // Parse the optional "strict", the optional "replacement" and the set of
Manman Renb636b902016-02-17 22:05:48 +0000962 // introductions/deprecations/removals.
Manman Rend8039df2016-02-22 04:47:24 +0000963 SourceLocation UnavailableLoc, StrictLoc;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000964 do {
965 if (Tok.isNot(tok::identifier)) {
966 Diag(Tok, diag::err_availability_expected_change);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000967 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000968 return;
969 }
970 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
971 SourceLocation KeywordLoc = ConsumeToken();
972
Manman Rend8039df2016-02-22 04:47:24 +0000973 if (Keyword == Ident_strict) {
974 if (StrictLoc.isValid()) {
Manman Renb636b902016-02-17 22:05:48 +0000975 Diag(KeywordLoc, diag::err_availability_redundant)
Manman Rend8039df2016-02-22 04:47:24 +0000976 << Keyword << SourceRange(StrictLoc);
Manman Renb636b902016-02-17 22:05:48 +0000977 }
Manman Rend8039df2016-02-22 04:47:24 +0000978 StrictLoc = KeywordLoc;
Manman Renb636b902016-02-17 22:05:48 +0000979 continue;
980 }
981
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000982 if (Keyword == Ident_unavailable) {
983 if (UnavailableLoc.isValid()) {
984 Diag(KeywordLoc, diag::err_availability_redundant)
985 << Keyword << SourceRange(UnavailableLoc);
Chad Rosierc1183952012-06-26 22:30:43 +0000986 }
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000987 UnavailableLoc = KeywordLoc;
Alp Toker97650562014-01-10 11:19:30 +0000988 continue;
Chad Rosierc1183952012-06-26 22:30:43 +0000989 }
990
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000991 if (Tok.isNot(tok::equal)) {
Alp Tokerec543272013-12-24 09:48:30 +0000992 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
Alexey Bataevee6507d2013-11-18 08:17:37 +0000993 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000994 return;
995 }
996 ConsumeToken();
Manman Ren75bc6762016-03-21 17:30:55 +0000997 if (Keyword == Ident_message || Keyword == Ident_replacement) {
David Majnemer2e498302014-07-18 05:43:12 +0000998 if (Tok.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000999 Diag(Tok, diag::err_expected_string_literal)
1000 << /*Source='availability attribute'*/2;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001001 SkipUntil(tok::r_paren, StopAtSemi);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001002 return;
1003 }
Manman Ren75bc6762016-03-21 17:30:55 +00001004 if (Keyword == Ident_message)
1005 MessageExpr = ParseStringLiteralExpression();
1006 else
1007 ReplacementExpr = ParseStringLiteralExpression();
David Majnemer2e498302014-07-18 05:43:12 +00001008 // Also reject wide string literals.
1009 if (StringLiteral *MessageStringLiteral =
1010 cast_or_null<StringLiteral>(MessageExpr.get())) {
1011 if (MessageStringLiteral->getCharByteWidth() != 1) {
1012 Diag(MessageStringLiteral->getSourceRange().getBegin(),
1013 diag::err_expected_string_literal)
1014 << /*Source='availability attribute'*/ 2;
1015 SkipUntil(tok::r_paren, StopAtSemi);
1016 return;
1017 }
1018 }
Manman Ren75bc6762016-03-21 17:30:55 +00001019 if (Keyword == Ident_message)
1020 break;
1021 else
1022 continue;
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00001023 }
Chad Rosierc1183952012-06-26 22:30:43 +00001024
Fariborz Jahanian5a29e6a2014-11-05 23:58:55 +00001025 // Special handling of 'NA' only when applied to introduced or
1026 // deprecated.
1027 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1028 Tok.is(tok::identifier)) {
1029 IdentifierInfo *NA = Tok.getIdentifierInfo();
1030 if (NA->getName() == "NA") {
1031 ConsumeToken();
1032 if (Keyword == Ident_introduced)
1033 UnavailableLoc = KeywordLoc;
1034 continue;
1035 }
1036 }
1037
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001038 SourceRange VersionRange;
1039 VersionTuple Version = ParseVersionTuple(VersionRange);
Chad Rosierc1183952012-06-26 22:30:43 +00001040
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001041 if (Version.empty()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001042 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001043 return;
1044 }
1045
1046 unsigned Index;
1047 if (Keyword == Ident_introduced)
1048 Index = Introduced;
1049 else if (Keyword == Ident_deprecated)
1050 Index = Deprecated;
1051 else if (Keyword == Ident_obsoleted)
1052 Index = Obsoleted;
Chad Rosierc1183952012-06-26 22:30:43 +00001053 else
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001054 Index = Unknown;
1055
1056 if (Index < Unknown) {
1057 if (!Changes[Index].KeywordLoc.isInvalid()) {
1058 Diag(KeywordLoc, diag::err_availability_redundant)
Chad Rosierc1183952012-06-26 22:30:43 +00001059 << Keyword
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001060 << SourceRange(Changes[Index].KeywordLoc,
1061 Changes[Index].VersionRange.getEnd());
1062 }
1063
1064 Changes[Index].KeywordLoc = KeywordLoc;
1065 Changes[Index].Version = Version;
1066 Changes[Index].VersionRange = VersionRange;
1067 } else {
1068 Diag(KeywordLoc, diag::err_availability_unknown_change)
1069 << Keyword << VersionRange;
1070 }
1071
Alp Toker97650562014-01-10 11:19:30 +00001072 } while (TryConsumeToken(tok::comma));
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001073
1074 // Closing ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001075 if (T.consumeClose())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001076 return;
1077
1078 if (endLoc)
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001079 *endLoc = T.getCloseLocation();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001080
Douglas Gregor7ab142b2011-03-26 03:35:55 +00001081 // The 'unavailable' availability cannot be combined with any other
1082 // availability changes. Make sure that hasn't happened.
1083 if (UnavailableLoc.isValid()) {
1084 bool Complained = false;
1085 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1086 if (Changes[Index].KeywordLoc.isValid()) {
1087 if (!Complained) {
1088 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1089 << SourceRange(Changes[Index].KeywordLoc,
1090 Changes[Index].VersionRange.getEnd());
1091 Complained = true;
1092 }
1093
1094 // Clear out the availability.
1095 Changes[Index] = AvailabilityChange();
1096 }
1097 }
1098 }
1099
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001100 // Record this attribute
Chad Rosierc1183952012-06-26 22:30:43 +00001101 attrs.addNew(&Availability,
1102 SourceRange(AvailabilityLoc, T.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001103 ScopeName, ScopeLoc,
Aaron Ballman00e99962013-08-31 01:11:41 +00001104 Platform,
John McCall084e83d2011-03-24 11:26:52 +00001105 Changes[Introduced],
1106 Changes[Deprecated],
Chad Rosierc1183952012-06-26 22:30:43 +00001107 Changes[Obsoleted],
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001108 UnavailableLoc, MessageExpr.get(),
Manman Ren75bc6762016-03-21 17:30:55 +00001109 Syntax, StrictLoc, ReplacementExpr.get());
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001110}
1111
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001112/// Parse the contents of the "external_source_symbol" attribute.
Alex Lorenzd5d27e12017-03-01 18:06:25 +00001113///
1114/// external-source-symbol-attribute:
1115/// 'external_source_symbol' '(' keyword-arg-list ')'
1116///
1117/// keyword-arg-list:
1118/// keyword-arg
1119/// keyword-arg ',' keyword-arg-list
1120///
1121/// keyword-arg:
1122/// 'language' '=' <string>
1123/// 'defined_in' '=' <string>
1124/// 'generated_declaration'
1125void Parser::ParseExternalSourceSymbolAttribute(
1126 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1127 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1128 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
1129 // Opening '('.
1130 BalancedDelimiterTracker T(*this, tok::l_paren);
1131 if (T.expectAndConsume())
1132 return;
1133
1134 // Initialize the pointers for the keyword identifiers when required.
1135 if (!Ident_language) {
1136 Ident_language = PP.getIdentifierInfo("language");
1137 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1138 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1139 }
1140
1141 ExprResult Language;
1142 bool HasLanguage = false;
1143 ExprResult DefinedInExpr;
1144 bool HasDefinedIn = false;
1145 IdentifierLoc *GeneratedDeclaration = nullptr;
1146
1147 // Parse the language/defined_in/generated_declaration keywords
1148 do {
1149 if (Tok.isNot(tok::identifier)) {
1150 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1151 SkipUntil(tok::r_paren, StopAtSemi);
1152 return;
1153 }
1154
1155 SourceLocation KeywordLoc = Tok.getLocation();
1156 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1157 if (Keyword == Ident_generated_declaration) {
1158 if (GeneratedDeclaration) {
1159 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1160 SkipUntil(tok::r_paren, StopAtSemi);
1161 return;
1162 }
1163 GeneratedDeclaration = ParseIdentifierLoc();
1164 continue;
1165 }
1166
1167 if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1168 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1169 SkipUntil(tok::r_paren, StopAtSemi);
1170 return;
1171 }
1172
1173 ConsumeToken();
1174 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1175 Keyword->getName())) {
1176 SkipUntil(tok::r_paren, StopAtSemi);
1177 return;
1178 }
1179
1180 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1181 if (Keyword == Ident_language)
1182 HasLanguage = true;
1183 else
1184 HasDefinedIn = true;
1185
1186 if (Tok.isNot(tok::string_literal)) {
1187 Diag(Tok, diag::err_expected_string_literal)
1188 << /*Source='external_source_symbol attribute'*/ 3
1189 << /*language | source container*/ (Keyword != Ident_language);
1190 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1191 continue;
1192 }
1193 if (Keyword == Ident_language) {
1194 if (HadLanguage) {
1195 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1196 << Keyword;
1197 ParseStringLiteralExpression();
1198 continue;
1199 }
1200 Language = ParseStringLiteralExpression();
1201 } else {
1202 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1203 if (HadDefinedIn) {
1204 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1205 << Keyword;
1206 ParseStringLiteralExpression();
1207 continue;
1208 }
1209 DefinedInExpr = ParseStringLiteralExpression();
1210 }
1211 } while (TryConsumeToken(tok::comma));
1212
1213 // Closing ')'.
1214 if (T.consumeClose())
1215 return;
1216 if (EndLoc)
1217 *EndLoc = T.getCloseLocation();
1218
1219 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1220 GeneratedDeclaration};
1221 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1222 ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1223}
1224
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001225/// Parse the contents of the "objc_bridge_related" attribute.
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001226/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1227/// related_class:
1228/// Identifier
1229///
1230/// opt-class_method:
1231/// Identifier: | <empty>
1232///
1233/// opt-instance_method:
1234/// Identifier | <empty>
1235///
1236void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1237 SourceLocation ObjCBridgeRelatedLoc,
1238 ParsedAttributes &attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001239 SourceLocation *endLoc,
1240 IdentifierInfo *ScopeName,
1241 SourceLocation ScopeLoc,
1242 AttributeList::Syntax Syntax) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001243 // Opening '('.
1244 BalancedDelimiterTracker T(*this, tok::l_paren);
1245 if (T.consumeOpen()) {
Alp Tokerec543272013-12-24 09:48:30 +00001246 Diag(Tok, diag::err_expected) << tok::l_paren;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001247 return;
1248 }
1249
1250 // Parse the related class name.
1251 if (Tok.isNot(tok::identifier)) {
1252 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1253 SkipUntil(tok::r_paren, StopAtSemi);
1254 return;
1255 }
1256 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
Alp Toker97650562014-01-10 11:19:30 +00001257 if (ExpectAndConsume(tok::comma)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001258 SkipUntil(tok::r_paren, StopAtSemi);
1259 return;
1260 }
Alp Toker8fbec672013-12-17 23:29:36 +00001261
Aaron Ballman48a533d2018-02-27 23:49:28 +00001262 // Parse class method name. It's non-optional in the sense that a trailing
1263 // comma is required, but it can be the empty string, and then we record a
1264 // nullptr.
Craig Topper161e4db2014-05-21 06:02:52 +00001265 IdentifierLoc *ClassMethod = nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001266 if (Tok.is(tok::identifier)) {
1267 ClassMethod = ParseIdentifierLoc();
Alp Toker8fbec672013-12-17 23:29:36 +00001268 if (!TryConsumeToken(tok::colon)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001269 Diag(Tok, diag::err_objcbridge_related_selector_name);
1270 SkipUntil(tok::r_paren, StopAtSemi);
1271 return;
1272 }
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001273 }
Alp Toker8fbec672013-12-17 23:29:36 +00001274 if (!TryConsumeToken(tok::comma)) {
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001275 if (Tok.is(tok::colon))
1276 Diag(Tok, diag::err_objcbridge_related_selector_name);
1277 else
Alp Tokerec543272013-12-24 09:48:30 +00001278 Diag(Tok, diag::err_expected) << tok::comma;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001279 SkipUntil(tok::r_paren, StopAtSemi);
1280 return;
1281 }
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001282
Aaron Ballman48a533d2018-02-27 23:49:28 +00001283 // Parse instance method name. Also non-optional but empty string is
1284 // permitted.
Craig Topper161e4db2014-05-21 06:02:52 +00001285 IdentifierLoc *InstanceMethod = nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001286 if (Tok.is(tok::identifier))
1287 InstanceMethod = ParseIdentifierLoc();
1288 else if (Tok.isNot(tok::r_paren)) {
Alp Tokerec543272013-12-24 09:48:30 +00001289 Diag(Tok, diag::err_expected) << tok::r_paren;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001290 SkipUntil(tok::r_paren, StopAtSemi);
1291 return;
1292 }
1293
1294 // Closing ')'.
1295 if (T.consumeClose())
1296 return;
1297
1298 if (endLoc)
1299 *endLoc = T.getCloseLocation();
1300
1301 // Record this attribute
1302 attrs.addNew(&ObjCBridgeRelated,
1303 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001304 ScopeName, ScopeLoc,
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001305 RelatedClass,
1306 ClassMethod,
1307 InstanceMethod,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001308 Syntax);
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00001309}
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001310
Bill Wendling44426052012-12-20 19:22:21 +00001311// Late Parsed Attributes:
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001312// See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1313
1314void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1315
1316void Parser::LateParsedClass::ParseLexedAttributes() {
1317 Self->ParseLexedAttributes(*Class);
1318}
1319
1320void Parser::LateParsedAttribute::ParseLexedAttributes() {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001321 Self->ParseLexedAttribute(*this, true, false);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001322}
1323
1324/// Wrapper class which calls ParseLexedAttribute, after setting up the
1325/// scope appropriately.
1326void Parser::ParseLexedAttributes(ParsingClass &Class) {
1327 // Deal with templates
1328 // FIXME: Test cases to make sure this does the right thing for templates.
1329 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1330 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1331 HasTemplateScope);
1332 if (HasTemplateScope)
1333 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1334
Douglas Gregor3024f072012-04-16 07:05:22 +00001335 // Set or update the scope flags.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001336 bool AlreadyHasClassScope = Class.TopLevelClass;
Douglas Gregor3024f072012-04-16 07:05:22 +00001337 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001338 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1339 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1340
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001341 // Enter the scope of nested classes
1342 if (!AlreadyHasClassScope)
1343 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1344 Class.TagOrTemplate);
Benjamin Kramer1d373c62012-05-17 12:01:52 +00001345 if (!Class.LateParsedDeclarations.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001346 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1347 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1348 }
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001349 }
Chad Rosierc1183952012-06-26 22:30:43 +00001350
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001351 if (!AlreadyHasClassScope)
1352 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1353 Class.TagOrTemplate);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001354}
1355
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001356/// Parse all attributes in LAs, and attach them to Decl D.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001357void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1358 bool EnterScope, bool OnDefinition) {
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001359 assert(LAs.parseSoon() &&
1360 "Attribute list should be marked for immediate parsing.");
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001361 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
DeLesley Hutchins19c722d2012-08-15 22:41:04 +00001362 if (D)
1363 LAs[i]->addDecl(D);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001364 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
Benjamin Kramerbafc49a2012-04-14 12:44:47 +00001365 delete LAs[i];
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001366 }
1367 LAs.clear();
1368}
1369
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001370/// Finish parsing an attribute for which parsing was delayed.
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001371/// This will be called at the end of parsing a class declaration
1372/// for each LateParsedAttribute. We consume the saved tokens and
Chad Rosierc1183952012-06-26 22:30:43 +00001373/// create an attribute with the arguments filled in. We add this
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001374/// to the Attribute list for the decl.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001375void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1376 bool EnterScope, bool OnDefinition) {
David Majnemerd5946f52015-01-13 08:35:24 +00001377 // Create a fake EOF so that attribute parsing won't go off the end of the
1378 // attribute.
1379 Token AttrEnd;
1380 AttrEnd.startToken();
1381 AttrEnd.setKind(tok::eof);
1382 AttrEnd.setLocation(Tok.getLocation());
1383 AttrEnd.setEofData(LA.Toks.data());
1384 LA.Toks.push_back(AttrEnd);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001385
1386 // Append the current token at the end of the new token stream so that it
1387 // doesn't get lost.
1388 LA.Toks.push_back(Tok);
David Blaikie2eabcc92016-02-09 18:52:09 +00001389 PP.EnterTokenStream(LA.Toks, true);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001390 // Consume the previously pushed token.
Argyrios Kyrtzidisc36633c2013-03-27 23:58:17 +00001391 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001392
1393 ParsedAttributes Attrs(AttrFactory);
1394 SourceLocation endLoc;
1395
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001396 if (LA.Decls.size() > 0) {
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001397 Decl *D = LA.Decls[0];
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001398 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1399 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001400
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001401 // Allow 'this' within late-parsed attributes.
Richard Smithc3d2ebb2013-06-07 02:33:37 +00001402 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0,
1403 ND && ND->isCXXInstanceMember());
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001404
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001405 if (LA.Decls.size() == 1) {
1406 // If the Decl is templatized, add template parameters to scope.
1407 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1408 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1409 if (HasTemplateScope)
1410 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001411
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001412 // If the Decl is on a function, add function parameters to the scope.
1413 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
Momchil Velikov57c681f2017-08-10 15:43:06 +00001414 ParseScope FnScope(
1415 this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
1416 HasFunScope);
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001417 if (HasFunScope)
1418 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001419
Michael Han23214e52012-10-03 01:56:22 +00001420 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00001421 nullptr, SourceLocation(), AttributeList::AS_GNU,
1422 nullptr);
DeLesley Hutchinsf1150d32012-08-20 21:32:18 +00001423
1424 if (HasFunScope) {
1425 Actions.ActOnExitFunctionContext();
1426 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1427 }
1428 if (HasTemplateScope) {
1429 TempScope.Exit();
1430 }
1431 } else {
1432 // If there are multiple decls, then the decl cannot be within the
1433 // function scope.
Michael Han23214e52012-10-03 01:56:22 +00001434 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00001435 nullptr, SourceLocation(), AttributeList::AS_GNU,
1436 nullptr);
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001437 }
DeLesley Hutchins71d61032012-03-02 22:29:50 +00001438 } else {
1439 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001440 }
1441
Aaron Ballman9a99e0d2014-01-20 17:18:35 +00001442 const AttributeList *AL = Attrs.getList();
1443 if (OnDefinition && AL && !AL->isCXX11Attribute() &&
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001444 AL->isKnownToGCC())
Aaron Ballman9a99e0d2014-01-20 17:18:35 +00001445 Diag(Tok, diag::warn_attribute_on_function_definition)
1446 << &LA.AttrName;
1447
1448 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00001449 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001450
David Majnemerd5946f52015-01-13 08:35:24 +00001451 // Due to a parsing error, we either went over the cached tokens or
1452 // there are still cached tokens left, so we skip the leftover tokens.
1453 while (Tok.isNot(tok::eof))
1454 ConsumeAnyToken();
1455
1456 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1457 ConsumeAnyToken();
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00001458}
1459
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001460void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1461 SourceLocation AttrNameLoc,
1462 ParsedAttributes &Attrs,
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001463 SourceLocation *EndLoc,
1464 IdentifierInfo *ScopeName,
1465 SourceLocation ScopeLoc,
1466 AttributeList::Syntax Syntax) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001467 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1468
1469 BalancedDelimiterTracker T(*this, tok::l_paren);
1470 T.consumeOpen();
1471
1472 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001473 Diag(Tok, diag::err_expected) << tok::identifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001474 T.skipToEnd();
1475 return;
1476 }
Richard Smithfeefaf52013-09-03 18:01:40 +00001477 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001478
Alp Toker094e5212014-01-05 03:27:11 +00001479 if (ExpectAndConsume(tok::comma)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001480 T.skipToEnd();
1481 return;
1482 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001483
1484 SourceRange MatchingCTypeRange;
1485 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1486 if (MatchingCType.isInvalid()) {
1487 T.skipToEnd();
1488 return;
1489 }
1490
1491 bool LayoutCompatible = false;
1492 bool MustBeNull = false;
Alp Toker8fbec672013-12-17 23:29:36 +00001493 while (TryConsumeToken(tok::comma)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001494 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00001495 Diag(Tok, diag::err_expected) << tok::identifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001496 T.skipToEnd();
1497 return;
1498 }
1499 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1500 if (Flag->isStr("layout_compatible"))
1501 LayoutCompatible = true;
1502 else if (Flag->isStr("must_be_null"))
1503 MustBeNull = true;
1504 else {
1505 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1506 T.skipToEnd();
1507 return;
1508 }
1509 ConsumeToken(); // consume flag
1510 }
1511
1512 if (!T.consumeClose()) {
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001513 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001514 ArgumentKind, MatchingCType.get(),
Aaron Ballman80f1529c2014-07-16 20:21:50 +00001515 LayoutCompatible, MustBeNull, Syntax);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001516 }
1517
1518 if (EndLoc)
1519 *EndLoc = T.getCloseLocation();
1520}
1521
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001522/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1523/// of a C++11 attribute-specifier in a location where an attribute is not
1524/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1525/// situation.
1526///
1527/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1528/// this doesn't appear to actually be an attribute-specifier, and the caller
1529/// should try to parse it.
1530bool Parser::DiagnoseProhibitedCXX11Attribute() {
1531 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1532
1533 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1534 case CAK_NotAttributeSpecifier:
1535 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1536 return false;
1537
1538 case CAK_InvalidAttributeSpecifier:
1539 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1540 return false;
1541
1542 case CAK_AttributeSpecifier:
1543 // Parse and discard the attributes.
1544 SourceLocation BeginLoc = ConsumeBracket();
1545 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001546 SkipUntil(tok::r_square);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001547 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1548 SourceLocation EndLoc = ConsumeBracket();
1549 Diag(BeginLoc, diag::err_attributes_not_allowed)
1550 << SourceRange(BeginLoc, EndLoc);
1551 return true;
1552 }
Chandler Carruthd8f7d382012-04-10 16:03:08 +00001553 llvm_unreachable("All cases handled above.");
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001554}
1555
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001556/// We have found the opening square brackets of a C++11
Richard Smith98155ad2013-02-20 01:17:14 +00001557/// attribute-specifier in a location where an attribute is not permitted, but
1558/// we know where the attributes ought to be written. Parse them anyway, and
1559/// provide a fixit moving them to the right place.
Richard Smith4c96e992013-02-19 23:47:15 +00001560void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1561 SourceLocation CorrectLocation) {
1562 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1563 Tok.is(tok::kw_alignas));
1564
1565 // Consume the attributes.
1566 SourceLocation Loc = Tok.getLocation();
1567 ParseCXX11Attributes(Attrs);
1568 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
Faisal Valic5089c02017-12-25 22:23:20 +00001569 // FIXME: use err_attributes_misplaced
Richard Smith4c96e992013-02-19 23:47:15 +00001570 Diag(Loc, diag::err_attributes_not_allowed)
1571 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1572 << FixItHint::CreateRemoval(AttrRange);
1573}
1574
Faisal Valic5089c02017-12-25 22:23:20 +00001575void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs,
1576 const SourceLocation CorrectLocation) {
1577 if (CorrectLocation.isValid()) {
1578 CharSourceRange AttrRange(attrs.Range, true);
1579 Diag(CorrectLocation, diag::err_attributes_misplaced)
1580 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1581 << FixItHint::CreateRemoval(AttrRange);
1582 } else
1583 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed) << attrs.Range;
Dawn Perchik335e16b2010-09-03 01:29:35 +00001584}
1585
Richard Smith49cc1cc2016-08-18 21:59:42 +00001586void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1587 unsigned DiagID) {
1588 for (AttributeList *Attr = Attrs.getList(); Attr; Attr = Attr->getNext()) {
Aaron Ballman606093a2017-10-15 15:01:42 +00001589 if (!Attr->isCXX11Attribute() && !Attr->isC2xAttribute())
Richard Smith49cc1cc2016-08-18 21:59:42 +00001590 continue;
1591 if (Attr->getKind() == AttributeList::UnknownAttribute)
1592 Diag(Attr->getLoc(), diag::warn_unknown_attribute_ignored)
1593 << Attr->getName();
1594 else {
1595 Diag(Attr->getLoc(), DiagID)
1596 << Attr->getName();
1597 Attr->setInvalid();
Michael Han64536a62012-11-06 19:34:54 +00001598 }
Michael Han64536a62012-11-06 19:34:54 +00001599 }
1600}
1601
Nico Weber32a0fc72016-09-03 03:01:32 +00001602// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1603// applies to var, not the type Foo.
David Majnemer936b4112015-04-19 07:53:29 +00001604// As an exception to the rule, __declspec(align(...)) before the
1605// class-key affects the type instead of the variable.
Nico Weber32a0fc72016-09-03 03:01:32 +00001606// Also, Microsoft-style [attributes] seem to affect the type instead of the
1607// variable.
1608// This function moves attributes that should apply to the type off DS to Attrs.
1609void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1610 DeclSpec &DS,
1611 Sema::TagUseKind TUK) {
David Majnemer936b4112015-04-19 07:53:29 +00001612 if (TUK == Sema::TUK_Reference)
1613 return;
1614
1615 ParsedAttributes &PA = DS.getAttributes();
1616 AttributeList *AL = PA.getList();
1617 AttributeList *Prev = nullptr;
Nico Weber88f5ed92016-09-13 18:55:26 +00001618 AttributeList *TypeAttrHead = nullptr;
1619 AttributeList *TypeAttrTail = nullptr;
David Majnemer936b4112015-04-19 07:53:29 +00001620 while (AL) {
1621 AttributeList *Next = AL->getNext();
1622
Nico Weber32a0fc72016-09-03 03:01:32 +00001623 if ((AL->getKind() == AttributeList::AT_Aligned &&
1624 AL->isDeclspecAttribute()) ||
1625 AL->isMicrosoftAttribute()) {
David Majnemer936b4112015-04-19 07:53:29 +00001626 // Stitch the attribute into the tag's attribute list.
Nico Weber88f5ed92016-09-13 18:55:26 +00001627 if (TypeAttrTail)
1628 TypeAttrTail->setNext(AL);
1629 else
1630 TypeAttrHead = AL;
1631 TypeAttrTail = AL;
1632 TypeAttrTail->setNext(nullptr);
David Majnemer936b4112015-04-19 07:53:29 +00001633
1634 // Remove the attribute from the variable's attribute list.
1635 if (Prev) {
1636 // Set the last variable attribute's next attribute to be the attribute
1637 // after the current one.
1638 Prev->setNext(Next);
1639 } else {
1640 // Removing the head of the list requires us to reset the head to the
1641 // next attribute.
1642 PA.set(Next);
1643 }
1644 } else {
1645 Prev = AL;
1646 }
1647
1648 AL = Next;
1649 }
Nico Weber88f5ed92016-09-13 18:55:26 +00001650
1651 // Find end of type attributes Attrs and add NewTypeAttributes in the same
Michael Kruse41dd6ce2018-06-25 20:06:13 +00001652 // order they were in originally. (Remember, in AttributeList things earlier
1653 // in source order are later in the list, since new attributes are added to
1654 // the front of the list.)
Nico Weber88f5ed92016-09-13 18:55:26 +00001655 Attrs.addAllAtEnd(TypeAttrHead);
David Majnemer936b4112015-04-19 07:53:29 +00001656}
1657
Chris Lattner53361ac2006-08-10 05:19:57 +00001658/// ParseDeclaration - Parse a full 'declaration', which consists of
1659/// declaration-specifiers, some number of declarators, and a semicolon.
Faisal Vali421b2d12017-12-29 05:41:00 +00001660/// 'Context' should be a DeclaratorContext value. This returns the
Chris Lattner49836b42009-04-02 04:16:50 +00001661/// location of the semicolon in DeclEnd.
Chris Lattnera5235172007-08-25 06:57:03 +00001662///
1663/// declaration: [C99 6.7]
1664/// block-declaration ->
1665/// simple-declaration
1666/// others [FIXME]
Douglas Gregoreb31f392008-12-01 23:54:00 +00001667/// [C++] template-declaration
Chris Lattnera5235172007-08-25 06:57:03 +00001668/// [C++] namespace-definition
Douglas Gregord7c4d982008-12-30 03:27:21 +00001669/// [C++] using-directive
Douglas Gregor77b50e12009-06-22 23:06:13 +00001670/// [C++] using-declaration
Richard Smithc202b282012-04-14 00:33:13 +00001671/// [C++11/C11] static_assert-declaration
Chris Lattnera5235172007-08-25 06:57:03 +00001672/// others... [FIXME]
1673///
Faisal Vali421b2d12017-12-29 05:41:00 +00001674Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
Alexis Hunt96d5c762009-11-21 08:43:09 +00001675 SourceLocation &DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +00001676 ParsedAttributesWithRange &attrs) {
Argyrios Kyrtzidis355094e2010-06-17 10:52:18 +00001677 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Fariborz Jahanian59b75282011-08-30 17:10:52 +00001678 // Must temporarily exit the objective-c container scope for
1679 // parsing c none objective-c decls.
1680 ObjCDeclContextSwitch ObjCDC(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00001681
Craig Topper161e4db2014-05-21 06:02:52 +00001682 Decl *SingleDecl = nullptr;
Chris Lattnera5235172007-08-25 06:57:03 +00001683 switch (Tok.getKind()) {
Douglas Gregoreb31f392008-12-01 23:54:00 +00001684 case tok::kw_template:
Douglas Gregor23996282009-05-12 21:31:51 +00001685 case tok::kw_export:
John McCall53fa7142010-12-24 02:08:15 +00001686 ProhibitAttributes(attrs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001687 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001688 break;
Sebastian Redl67667942010-08-27 23:12:46 +00001689 case tok::kw_inline:
Sebastian Redl5a5f2c72010-08-31 00:36:45 +00001690 // Could be the start of an inline namespace. Allowed as an ext in C++03.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001691 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
John McCall53fa7142010-12-24 02:08:15 +00001692 ProhibitAttributes(attrs);
Sebastian Redl67667942010-08-27 23:12:46 +00001693 SourceLocation InlineLoc = ConsumeToken();
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00001694 return ParseNamespace(Context, DeclEnd, InlineLoc);
Sebastian Redl67667942010-08-27 23:12:46 +00001695 }
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001696 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
Fariborz Jahanian1db5c942010-09-28 20:42:35 +00001697 true);
Chris Lattnera5235172007-08-25 06:57:03 +00001698 case tok::kw_namespace:
John McCall53fa7142010-12-24 02:08:15 +00001699 ProhibitAttributes(attrs);
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00001700 return ParseNamespace(Context, DeclEnd);
Douglas Gregord7c4d982008-12-30 03:27:21 +00001701 case tok::kw_using:
Richard Smith6f1daa42016-12-16 00:58:48 +00001702 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1703 DeclEnd, attrs);
Anders Carlssonf24fcff62009-03-11 16:27:10 +00001704 case tok::kw_static_assert:
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00001705 case tok::kw__Static_assert:
John McCall53fa7142010-12-24 02:08:15 +00001706 ProhibitAttributes(attrs);
Chris Lattner49836b42009-04-02 04:16:50 +00001707 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001708 break;
Chris Lattnera5235172007-08-25 06:57:03 +00001709 default:
Rafael Espindola1bd906d2014-10-22 14:27:08 +00001710 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
Chris Lattnera5235172007-08-25 06:57:03 +00001711 }
Chad Rosierc1183952012-06-26 22:30:43 +00001712
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001713 // This routine returns a DeclGroup, if the thing we parsed only contains a
Richard Smith6f1daa42016-12-16 00:58:48 +00001714 // single decl, convert it now.
1715 return Actions.ConvertDeclToDeclGroup(SingleDecl);
Chris Lattnera5235172007-08-25 06:57:03 +00001716}
1717
1718/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1719/// declaration-specifiers init-declarator-list[opt] ';'
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001720/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1721/// init-declarator-list ';'
Chris Lattnera5235172007-08-25 06:57:03 +00001722///[C90/C++]init-declarator-list ';' [TODO]
1723/// [OMP] threadprivate-directive [TODO]
Chris Lattner32dc41c2009-03-29 17:27:48 +00001724///
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001725/// for-range-declaration: [C++11 6.5p1: stmt.ranged]
Richard Smith02e85f32011-04-14 22:09:26 +00001726/// attribute-specifier-seq[opt] type-specifier-seq declarator
1727///
Chris Lattner32dc41c2009-03-29 17:27:48 +00001728/// If RequireSemi is false, this does not check for a ';' at the end of the
Chris Lattner005fc1b2010-04-05 18:18:31 +00001729/// declaration. If it is true, it checks for and eats it.
Richard Smith02e85f32011-04-14 22:09:26 +00001730///
1731/// If FRI is non-null, we might be parsing a for-range-declaration instead
1732/// of a simple-declaration. If we find that we are, we also parse the
1733/// for-range-initializer, and place it here.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001734Parser::DeclGroupPtrTy
Faisal Vali421b2d12017-12-29 05:41:00 +00001735Parser::ParseSimpleDeclaration(DeclaratorContext Context,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001736 SourceLocation &DeclEnd,
Richard Smith2386c8b2013-02-22 09:06:26 +00001737 ParsedAttributesWithRange &Attrs,
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001738 bool RequireSemi, ForRangeInit *FRI) {
Chris Lattner53361ac2006-08-10 05:19:57 +00001739 // Parse the common declaration-specifiers piece.
John McCall28a6aea2009-11-04 02:18:39 +00001740 ParsingDeclSpec DS(*this);
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001741
Richard Smith404dfb42013-11-19 22:47:36 +00001742 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
Faisal Valia534f072018-04-26 00:42:40 +00001743 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
Richard Smith404dfb42013-11-19 22:47:36 +00001744
1745 // If we had a free-standing type definition with a missing semicolon, we
1746 // may get this far before the problem becomes obvious.
1747 if (DS.hasTagDefinition() &&
1748 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
David Blaikie0403cb12016-01-15 23:43:25 +00001749 return nullptr;
Abramo Bagnara1cd83682012-01-07 10:52:36 +00001750
Chris Lattner0e894622006-08-13 19:58:17 +00001751 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1752 // declaration-specifiers init-declarator-list[opt] ';'
Chris Lattner76c72282007-10-09 17:33:22 +00001753 if (Tok.is(tok::semi)) {
Richard Smith2386c8b2013-02-22 09:06:26 +00001754 ProhibitAttributes(Attrs);
Argyrios Kyrtzidisfbb2bb52012-05-16 23:49:15 +00001755 DeclEnd = Tok.getLocation();
Chris Lattner005fc1b2010-04-05 18:18:31 +00001756 if (RequireSemi) ConsumeToken();
Nico Weber7b837f52016-01-28 19:25:00 +00001757 RecordDecl *AnonRecord = nullptr;
John McCall48871652010-08-21 09:40:31 +00001758 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00001759 DS, AnonRecord);
John McCall28a6aea2009-11-04 02:18:39 +00001760 DS.complete(TheDecl);
Nico Weber7b837f52016-01-28 19:25:00 +00001761 if (AnonRecord) {
1762 Decl* decls[] = {AnonRecord, TheDecl};
Richard Smith3beb7c62017-01-12 02:27:38 +00001763 return Actions.BuildDeclaratorGroup(decls);
Nico Weber7b837f52016-01-28 19:25:00 +00001764 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001765 return Actions.ConvertDeclToDeclGroup(TheDecl);
Chris Lattner0e894622006-08-13 19:58:17 +00001766 }
Chad Rosierc1183952012-06-26 22:30:43 +00001767
Richard Smith2386c8b2013-02-22 09:06:26 +00001768 DS.takeAttributesFrom(Attrs);
Reid Klecknerd61a3112014-12-15 23:16:32 +00001769 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
John McCalld5a36322009-11-03 19:26:08 +00001770}
Mike Stump11289f42009-09-09 15:08:12 +00001771
Richard Smith09f76ee2011-10-19 21:33:05 +00001772/// Returns true if this might be the start of a declarator, or a common typo
1773/// for a declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001774bool Parser::MightBeDeclarator(DeclaratorContext Context) {
Richard Smith09f76ee2011-10-19 21:33:05 +00001775 switch (Tok.getKind()) {
1776 case tok::annot_cxxscope:
1777 case tok::annot_template_id:
1778 case tok::caret:
1779 case tok::code_completion:
1780 case tok::coloncolon:
1781 case tok::ellipsis:
1782 case tok::kw___attribute:
1783 case tok::kw_operator:
1784 case tok::l_paren:
1785 case tok::star:
1786 return true;
1787
1788 case tok::amp:
1789 case tok::ampamp:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001790 return getLangOpts().CPlusPlus;
Richard Smith09f76ee2011-10-19 21:33:05 +00001791
Richard Smithc8a79032012-01-09 22:31:44 +00001792 case tok::l_square: // Might be an attribute on an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001793 return Context == DeclaratorContext::MemberContext &&
1794 getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
Richard Smithc8a79032012-01-09 22:31:44 +00001795
1796 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001797 return Context == DeclaratorContext::MemberContext ||
1798 getLangOpts().CPlusPlus;
Richard Smithc8a79032012-01-09 22:31:44 +00001799
Richard Smith09f76ee2011-10-19 21:33:05 +00001800 case tok::identifier:
1801 switch (NextToken().getKind()) {
1802 case tok::code_completion:
1803 case tok::coloncolon:
1804 case tok::comma:
1805 case tok::equal:
1806 case tok::equalequal: // Might be a typo for '='.
1807 case tok::kw_alignas:
1808 case tok::kw_asm:
1809 case tok::kw___attribute:
1810 case tok::l_brace:
1811 case tok::l_paren:
1812 case tok::l_square:
1813 case tok::less:
1814 case tok::r_brace:
1815 case tok::r_paren:
1816 case tok::r_square:
1817 case tok::semi:
1818 return true;
1819
1820 case tok::colon:
1821 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
Richard Smithc8a79032012-01-09 22:31:44 +00001822 // and in block scope it's probably a label. Inside a class definition,
1823 // this is a bit-field.
Faisal Vali421b2d12017-12-29 05:41:00 +00001824 return Context == DeclaratorContext::MemberContext ||
1825 (getLangOpts().CPlusPlus &&
1826 Context == DeclaratorContext::FileContext);
Richard Smithc8a79032012-01-09 22:31:44 +00001827
1828 case tok::identifier: // Possible virt-specifier.
Richard Smith89645bc2013-01-02 12:01:23 +00001829 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
Richard Smith09f76ee2011-10-19 21:33:05 +00001830
1831 default:
1832 return false;
1833 }
1834
1835 default:
1836 return false;
1837 }
1838}
1839
Richard Smithb8caac82012-04-11 20:59:20 +00001840/// Skip until we reach something which seems like a sensible place to pick
1841/// up parsing after a malformed declaration. This will sometimes stop sooner
1842/// than SkipUntil(tok::r_brace) would, but will never stop later.
1843void Parser::SkipMalformedDecl() {
1844 while (true) {
1845 switch (Tok.getKind()) {
1846 case tok::l_brace:
1847 // Skip until matching }, then stop. We've probably skipped over
1848 // a malformed class or function definition or similar.
1849 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001850 SkipUntil(tok::r_brace);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001851 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
Richard Smithb8caac82012-04-11 20:59:20 +00001852 // This declaration isn't over yet. Keep skipping.
1853 continue;
1854 }
Alp Toker8fbec672013-12-17 23:29:36 +00001855 TryConsumeToken(tok::semi);
Richard Smithb8caac82012-04-11 20:59:20 +00001856 return;
1857
1858 case tok::l_square:
1859 ConsumeBracket();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001860 SkipUntil(tok::r_square);
Richard Smithb8caac82012-04-11 20:59:20 +00001861 continue;
1862
1863 case tok::l_paren:
1864 ConsumeParen();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001865 SkipUntil(tok::r_paren);
Richard Smithb8caac82012-04-11 20:59:20 +00001866 continue;
1867
1868 case tok::r_brace:
1869 return;
1870
1871 case tok::semi:
1872 ConsumeToken();
1873 return;
1874
1875 case tok::kw_inline:
1876 // 'inline namespace' at the start of a line is almost certainly
Jordan Rose12e730c2012-07-09 16:54:53 +00001877 // a good place to pick back up parsing, except in an Objective-C
1878 // @interface context.
1879 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1880 (!ParsingInObjCContainer || CurParsedObjCImpl))
Richard Smithb8caac82012-04-11 20:59:20 +00001881 return;
1882 break;
1883
1884 case tok::kw_namespace:
1885 // 'namespace' at the start of a line is almost certainly a good
Jordan Rose12e730c2012-07-09 16:54:53 +00001886 // place to pick back up parsing, except in an Objective-C
1887 // @interface context.
1888 if (Tok.isAtStartOfLine() &&
1889 (!ParsingInObjCContainer || CurParsedObjCImpl))
1890 return;
1891 break;
1892
1893 case tok::at:
1894 // @end is very much like } in Objective-C contexts.
1895 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1896 ParsingInObjCContainer)
1897 return;
1898 break;
1899
1900 case tok::minus:
1901 case tok::plus:
1902 // - and + probably start new method declarations in Objective-C contexts.
1903 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
Richard Smithb8caac82012-04-11 20:59:20 +00001904 return;
1905 break;
1906
1907 case tok::eof:
Richard Smith34f30512013-11-23 04:06:09 +00001908 case tok::annot_module_begin:
1909 case tok::annot_module_end:
1910 case tok::annot_module_include:
Richard Smithb8caac82012-04-11 20:59:20 +00001911 return;
1912
1913 default:
1914 break;
1915 }
1916
1917 ConsumeAnyToken();
1918 }
1919}
1920
John McCalld5a36322009-11-03 19:26:08 +00001921/// ParseDeclGroup - Having concluded that this is either a function
1922/// definition or a group of object declarations, actually parse the
1923/// result.
John McCall28a6aea2009-11-04 02:18:39 +00001924Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
Faisal Vali421b2d12017-12-29 05:41:00 +00001925 DeclaratorContext Context,
Richard Smith02e85f32011-04-14 22:09:26 +00001926 SourceLocation *DeclEnd,
1927 ForRangeInit *FRI) {
John McCalld5a36322009-11-03 19:26:08 +00001928 // Parse the first declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001929 ParsingDeclarator D(*this, DS, Context);
John McCalld5a36322009-11-03 19:26:08 +00001930 ParseDeclarator(D);
Chris Lattner32dc41c2009-03-29 17:27:48 +00001931
John McCalld5a36322009-11-03 19:26:08 +00001932 // Bail out if the first declarator didn't seem well-formed.
1933 if (!D.hasName() && !D.mayOmitIdentifier()) {
Richard Smithb8caac82012-04-11 20:59:20 +00001934 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00001935 return nullptr;
Chris Lattnerefb0f112009-03-29 17:18:04 +00001936 }
Mike Stump11289f42009-09-09 15:08:12 +00001937
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001938 // Save late-parsed attributes for now; they need to be parsed in the
1939 // appropriate function scope after the function Decl has been constructed.
DeLesley Hutchins66e300e2012-11-02 21:44:32 +00001940 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1941 LateParsedAttrList LateParsedAttrs(true);
Richard Smith99c464c2014-11-10 21:10:32 +00001942 if (D.isFunctionDeclarator()) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00001943 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1944
Richard Smith99c464c2014-11-10 21:10:32 +00001945 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1946 // attribute. If we find the keyword here, tell the user to put it
1947 // at the start instead.
1948 if (Tok.is(tok::kw__Noreturn)) {
1949 SourceLocation Loc = ConsumeToken();
1950 const char *PrevSpec;
1951 unsigned DiagID;
1952
1953 // We can offer a fixit if it's valid to mark this function as _Noreturn
1954 // and we don't have any other declarators in this declaration.
1955 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1956 MaybeParseGNUAttributes(D, &LateParsedAttrs);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001957 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
Richard Smith99c464c2014-11-10 21:10:32 +00001958
1959 Diag(Loc, diag::err_c11_noreturn_misplaced)
1960 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
1961 << (Fixit ? FixItHint::CreateInsertion(D.getLocStart(), "_Noreturn ")
1962 : FixItHint());
1963 }
1964 }
1965
Chris Lattnerdbb1e932010-07-11 22:24:20 +00001966 // Check to see if we have a function *definition* which must have a body.
Douglas Gregor012efe22013-04-16 16:01:32 +00001967 if (D.isFunctionDeclarator() &&
Chris Lattnerdbb1e932010-07-11 22:24:20 +00001968 // Look at the next token to make sure that this isn't a function
1969 // declaration. We have to check this because __attribute__ might be the
1970 // start of a function definition in GCC-extended K&R C.
Fariborz Jahanian712bb812012-08-10 15:54:40 +00001971 !isDeclarationAfterDeclarator()) {
Chad Rosierc1183952012-06-26 22:30:43 +00001972
Reid Klecknerd61a3112014-12-15 23:16:32 +00001973 // Function definitions are only allowed at file scope and in C++ classes.
1974 // The C++ inline method definition case is handled elsewhere, so we only
1975 // need to handle the file scope definition case.
Faisal Vali421b2d12017-12-29 05:41:00 +00001976 if (Context == DeclaratorContext::FileContext) {
Douglas Gregor012efe22013-04-16 16:01:32 +00001977 if (isStartOfFunctionDefinition(D)) {
1978 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1979 Diag(Tok, diag::err_function_declared_typedef);
John McCalld5a36322009-11-03 19:26:08 +00001980
Douglas Gregor012efe22013-04-16 16:01:32 +00001981 // Recover by treating the 'typedef' as spurious.
1982 DS.ClearStorageClassSpecs();
1983 }
1984
1985 Decl *TheDecl =
1986 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1987 return Actions.ConvertDeclToDeclGroup(TheDecl);
John McCalld5a36322009-11-03 19:26:08 +00001988 }
1989
Douglas Gregor012efe22013-04-16 16:01:32 +00001990 if (isDeclarationSpecifier()) {
Nico Weber6b05f382015-02-18 04:53:03 +00001991 // If there is an invalid declaration specifier right after the
1992 // function prototype, then we must be in a missing semicolon case
1993 // where this isn't actually a body. Just fall through into the code
1994 // that handles it as a prototype, and let the top-level code handle
1995 // the erroneous declspec where it would otherwise expect a comma or
1996 // semicolon.
Douglas Gregor012efe22013-04-16 16:01:32 +00001997 } else {
1998 Diag(Tok, diag::err_expected_fn_body);
1999 SkipUntil(tok::semi);
David Blaikie0403cb12016-01-15 23:43:25 +00002000 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00002001 }
John McCalld5a36322009-11-03 19:26:08 +00002002 } else {
Douglas Gregor012efe22013-04-16 16:01:32 +00002003 if (Tok.is(tok::l_brace)) {
2004 Diag(Tok, diag::err_function_definition_not_allowed);
Serge Pavlov1de51512013-12-09 05:25:47 +00002005 SkipMalformedDecl();
David Blaikie0403cb12016-01-15 23:43:25 +00002006 return nullptr;
Douglas Gregor012efe22013-04-16 16:01:32 +00002007 }
John McCalld5a36322009-11-03 19:26:08 +00002008 }
2009 }
2010
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002011 if (ParseAsmAttributesAfterDeclarator(D))
David Blaikie0403cb12016-01-15 23:43:25 +00002012 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00002013
2014 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2015 // must parse and analyze the for-range-initializer before the declaration is
2016 // analyzed.
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002017 //
2018 // Handle the Objective-C for-in loop variable similarly, although we
2019 // don't need to parse the container in advance.
2020 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2021 bool IsForRangeLoop = false;
Alp Toker8fbec672013-12-17 23:29:36 +00002022 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002023 IsForRangeLoop = true;
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002024 if (Tok.is(tok::l_brace))
2025 FRI->RangeExpr = ParseBraceInitializer();
2026 else
2027 FRI->RangeExpr = ParseExpression();
2028 }
2029
Richard Smith02e85f32011-04-14 22:09:26 +00002030 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
George Karpenkovec38cf72018-03-29 00:56:24 +00002031 if (IsForRangeLoop) {
Douglas Gregor2eb1c572013-04-08 20:52:24 +00002032 Actions.ActOnCXXForRangeDecl(ThisDecl);
George Karpenkovec38cf72018-03-29 00:56:24 +00002033 } else {
2034 // Obj-C for loop
2035 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2036 VD->setObjCForDecl(true);
2037 }
Richard Smith02e85f32011-04-14 22:09:26 +00002038 Actions.FinalizeDeclaration(ThisDecl);
John McCallcf6e0c82012-01-27 01:29:43 +00002039 D.complete(ThisDecl);
Rafael Espindolaab417692013-07-09 12:05:01 +00002040 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
Richard Smith02e85f32011-04-14 22:09:26 +00002041 }
2042
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002043 SmallVector<Decl *, 8> DeclsInGroup;
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002044 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2045 D, ParsedTemplateInfo(), FRI);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002046 if (LateParsedAttrs.size() > 0)
2047 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
John McCall28a6aea2009-11-04 02:18:39 +00002048 D.complete(FirstDecl);
John McCall48871652010-08-21 09:40:31 +00002049 if (FirstDecl)
John McCalld5a36322009-11-03 19:26:08 +00002050 DeclsInGroup.push_back(FirstDecl);
2051
Faisal Vali421b2d12017-12-29 05:41:00 +00002052 bool ExpectSemi = Context != DeclaratorContext::ForContext;
Fariborz Jahanian577574a2012-07-02 23:37:09 +00002053
John McCalld5a36322009-11-03 19:26:08 +00002054 // If we don't have a comma, it is either the end of the list (a ';') or an
2055 // error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00002056 SourceLocation CommaLoc;
2057 while (TryConsumeToken(tok::comma, CommaLoc)) {
Richard Smith09f76ee2011-10-19 21:33:05 +00002058 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2059 // This comma was followed by a line-break and something which can't be
2060 // the start of a declarator. The comma was probably a typo for a
2061 // semicolon.
2062 Diag(CommaLoc, diag::err_expected_semi_declaration)
2063 << FixItHint::CreateReplacement(CommaLoc, ";");
2064 ExpectSemi = false;
2065 break;
2066 }
John McCalld5a36322009-11-03 19:26:08 +00002067
2068 // Parse the next declarator.
2069 D.clear();
Richard Smith8d06f422012-01-12 23:53:29 +00002070 D.setCommaLoc(CommaLoc);
John McCalld5a36322009-11-03 19:26:08 +00002071
2072 // Accept attributes in an init-declarator. In the first declarator in a
2073 // declaration, these would be part of the declspec. In subsequent
2074 // declarators, they become part of the declarator itself, so that they
2075 // don't apply to declarators after *this* one. Examples:
2076 // short __attribute__((common)) var; -> declspec
2077 // short var __attribute__((common)); -> declarator
2078 // short x, __attribute__((common)) var; -> declarator
John McCall53fa7142010-12-24 02:08:15 +00002079 MaybeParseGNUAttributes(D);
John McCalld5a36322009-11-03 19:26:08 +00002080
Nico Rieckeaaae272014-12-04 23:31:08 +00002081 // MSVC parses but ignores qualifiers after the comma as an extension.
2082 if (getLangOpts().MicrosoftExt)
2083 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2084
John McCalld5a36322009-11-03 19:26:08 +00002085 ParseDeclarator(D);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002086 if (!D.isInvalidType()) {
2087 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2088 D.complete(ThisDecl);
2089 if (ThisDecl)
Chad Rosierc1183952012-06-26 22:30:43 +00002090 DeclsInGroup.push_back(ThisDecl);
Fariborz Jahanian372030b2012-01-13 00:14:12 +00002091 }
John McCalld5a36322009-11-03 19:26:08 +00002092 }
2093
2094 if (DeclEnd)
2095 *DeclEnd = Tok.getLocation();
2096
Richard Smith09f76ee2011-10-19 21:33:05 +00002097 if (ExpectSemi &&
Faisal Vali421b2d12017-12-29 05:41:00 +00002098 ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
Chris Lattner02f1b612012-04-28 16:12:17 +00002099 ? diag::err_invalid_token_after_toplevel_declarator
2100 : diag::err_expected_semi_declaration)) {
Chris Lattner13901342010-07-11 22:42:07 +00002101 // Okay, there was no semicolon and one was expected. If we see a
2102 // declaration specifier, just assume it was missing and continue parsing.
2103 // Otherwise things are very confused and we skip to recover.
2104 if (!isDeclarationSpecifier()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002105 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Alp Toker8fbec672013-12-17 23:29:36 +00002106 TryConsumeToken(tok::semi);
Chris Lattner13901342010-07-11 22:42:07 +00002107 }
John McCalld5a36322009-11-03 19:26:08 +00002108 }
2109
Rafael Espindolaab417692013-07-09 12:05:01 +00002110 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
Chris Lattner53361ac2006-08-10 05:19:57 +00002111}
2112
Richard Smith02e85f32011-04-14 22:09:26 +00002113/// Parse an optional simple-asm-expr and attributes, and attach them to a
2114/// declarator. Returns true on an error.
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002115bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
Richard Smith02e85f32011-04-14 22:09:26 +00002116 // If a simple-asm-expr is present, parse it.
2117 if (Tok.is(tok::kw_asm)) {
2118 SourceLocation Loc;
2119 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2120 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002121 SkipUntil(tok::semi, StopBeforeMatch);
Richard Smith02e85f32011-04-14 22:09:26 +00002122 return true;
2123 }
2124
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002125 D.setAsmLabel(AsmLabel.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002126 D.SetRangeEnd(Loc);
2127 }
2128
2129 MaybeParseGNUAttributes(D);
2130 return false;
2131}
2132
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002133/// Parse 'declaration' after parsing 'declaration-specifiers
Douglas Gregor23996282009-05-12 21:31:51 +00002134/// declarator'. This method parses the remainder of the declaration
2135/// (including any attributes or initializer, among other things) and
2136/// finalizes the declaration.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002137///
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002138/// init-declarator: [C99 6.7]
2139/// declarator
2140/// declarator '=' initializer
Chris Lattner6d7e6342006-08-15 03:41:14 +00002141/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2142/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002143/// [C++] declarator initializer[opt]
2144///
2145/// [C++] initializer:
2146/// [C++] '=' initializer-clause
2147/// [C++] '(' expression-list ')'
Sebastian Redlf769df52009-03-24 22:27:57 +00002148/// [C++0x] '=' 'default' [TODO]
2149/// [C++0x] '=' 'delete'
Sebastian Redl3da34892011-06-05 12:23:16 +00002150/// [C++0x] braced-init-list
Sebastian Redlf769df52009-03-24 22:27:57 +00002151///
2152/// According to the standard grammar, =default and =delete are function
2153/// definitions, but that definitely doesn't fit with the parser here.
Chris Lattnerf0f3baa2006-08-14 00:15:20 +00002154///
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002155Decl *Parser::ParseDeclarationAfterDeclarator(
2156 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +00002157 if (ParseAsmAttributesAfterDeclarator(D))
Craig Topper161e4db2014-05-21 06:02:52 +00002158 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002159
Richard Smith02e85f32011-04-14 22:09:26 +00002160 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2161}
Mike Stump11289f42009-09-09 15:08:12 +00002162
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002163Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2164 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
Richard Smithc95d2c52017-09-22 04:25:05 +00002165 // RAII type used to track whether we're inside an initializer.
2166 struct InitializerScopeRAII {
2167 Parser &P;
2168 Declarator &D;
2169 Decl *ThisDecl;
2170
2171 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2172 : P(P), D(D), ThisDecl(ThisDecl) {
2173 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2174 Scope *S = nullptr;
2175 if (D.getCXXScopeSpec().isSet()) {
2176 P.EnterScope(0);
2177 S = P.getCurScope();
2178 }
2179 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2180 }
2181 }
2182 ~InitializerScopeRAII() { pop(); }
2183 void pop() {
2184 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2185 Scope *S = nullptr;
2186 if (D.getCXXScopeSpec().isSet())
2187 S = P.getCurScope();
2188 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2189 if (S)
2190 P.ExitScope();
2191 }
2192 ThisDecl = nullptr;
2193 }
2194 };
2195
Douglas Gregor23996282009-05-12 21:31:51 +00002196 // Inform the current actions module that we just parsed this declarator.
Craig Topper161e4db2014-05-21 06:02:52 +00002197 Decl *ThisDecl = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00002198 switch (TemplateInfo.Kind) {
2199 case ParsedTemplateInfo::NonTemplate:
Douglas Gregor0be31a22010-07-02 17:43:08 +00002200 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
Douglas Gregor450f00842009-09-25 18:43:00 +00002201 break;
Chad Rosierc1183952012-06-26 22:30:43 +00002202
Douglas Gregor450f00842009-09-25 18:43:00 +00002203 case ParsedTemplateInfo::Template:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002204 case ParsedTemplateInfo::ExplicitSpecialization: {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002205 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002206 *TemplateInfo.TemplateParams,
Douglas Gregor450f00842009-09-25 18:43:00 +00002207 D);
Larisse Voufo833b05a2013-08-06 07:33:00 +00002208 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002209 // Re-direct this decl to refer to the templated decl so that we can
2210 // initialize it.
2211 ThisDecl = VT->getTemplatedDecl();
2212 break;
2213 }
2214 case ParsedTemplateInfo::ExplicitInstantiation: {
2215 if (Tok.is(tok::semi)) {
2216 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2217 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2218 if (ThisRes.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002219 SkipUntil(tok::semi, StopBeforeMatch);
Craig Topper161e4db2014-05-21 06:02:52 +00002220 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002221 }
2222 ThisDecl = ThisRes.get();
2223 } else {
2224 // FIXME: This check should be for a variable template instantiation only.
2225
2226 // Check that this is a valid instantiation
Faisal Vali2ab8c152017-12-30 04:15:27 +00002227 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002228 // If the declarator-id is not a template-id, issue a diagnostic and
2229 // recover by ignoring the 'template' keyword.
2230 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2231 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2232 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2233 } else {
2234 SourceLocation LAngleLoc =
2235 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2236 Diag(D.getIdentifierLoc(),
2237 diag::err_explicit_instantiation_with_definition)
2238 << SourceRange(TemplateInfo.TemplateLoc)
2239 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2240
2241 // Recover as if it were an explicit specialization.
2242 TemplateParameterLists FakedParamLists;
2243 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +00002244 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +00002245 LAngleLoc, nullptr));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002246
2247 ThisDecl =
2248 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2249 }
2250 }
Douglas Gregor450f00842009-09-25 18:43:00 +00002251 break;
2252 }
2253 }
Mike Stump11289f42009-09-09 15:08:12 +00002254
Douglas Gregor23996282009-05-12 21:31:51 +00002255 // Parse declarator '=' initializer.
Richard Trieuc64d3232012-01-18 22:54:52 +00002256 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Trieu4972a6d2012-01-19 22:01:51 +00002257 if (isTokenEqualOrEqualTypo()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002258 SourceLocation EqualLoc = ConsumeToken();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002259
Anders Carlsson991285e2010-09-24 21:25:25 +00002260 if (Tok.is(tok::kw_delete)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002261 if (D.isFunctionDeclarator())
2262 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2263 << 1 /* delete */;
2264 else
2265 Diag(ConsumeToken(), diag::err_deleted_non_function);
Alexis Hunt5dafebc2011-05-06 01:42:00 +00002266 } else if (Tok.is(tok::kw_default)) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002267 if (D.isFunctionDeclarator())
Sebastian Redl46afb552012-02-11 23:51:21 +00002268 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2269 << 0 /* default */;
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002270 else
2271 Diag(ConsumeToken(), diag::err_default_special_members);
Douglas Gregor23996282009-05-12 21:31:51 +00002272 } else {
Richard Smithc95d2c52017-09-22 04:25:05 +00002273 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002274
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002275 if (Tok.is(tok::code_completion)) {
Douglas Gregor0be31a22010-07-02 17:43:08 +00002276 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
Peter Collingbourne6b4fdc22012-07-27 12:56:09 +00002277 Actions.FinalizeDeclaration(ThisDecl);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002278 cutOffParsing();
Craig Topper161e4db2014-05-21 06:02:52 +00002279 return nullptr;
Douglas Gregor7aa6b222010-05-30 01:49:25 +00002280 }
Chad Rosierc1183952012-06-26 22:30:43 +00002281
John McCalldadc5752010-08-24 06:29:42 +00002282 ExprResult Init(ParseInitializer());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002283
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002284 // If this is the only decl in (possibly) range based for statement,
2285 // our best guess is that the user meant ':' instead of '='.
2286 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2287 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2288 << FixItHint::CreateReplacement(EqualLoc, ":");
2289 // We are trying to stop parser from looking for ';' in this for
2290 // statement, therefore preventing spurious errors to be issued.
2291 FRI->ColonLoc = EqualLoc;
2292 Init = ExprError();
2293 FRI->RangeExpr = Init;
2294 }
2295
Richard Smithc95d2c52017-09-22 04:25:05 +00002296 InitScope.pop();
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00002297
Douglas Gregor23996282009-05-12 21:31:51 +00002298 if (Init.isInvalid()) {
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002299 SmallVector<tok::TokenKind, 2> StopTokens;
2300 StopTokens.push_back(tok::comma);
Faisal Vali421b2d12017-12-29 05:41:00 +00002301 if (D.getContext() == DeclaratorContext::ForContext ||
2302 D.getContext() == DeclaratorContext::InitStmtContext)
Ismail Pazarbasi49ff7542014-05-08 11:28:25 +00002303 StopTokens.push_back(tok::r_paren);
2304 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
Douglas Gregor604c3022010-03-01 18:27:54 +00002305 Actions.ActOnInitializerError(ThisDecl);
2306 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002307 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002308 /*DirectInit=*/false);
Douglas Gregor23996282009-05-12 21:31:51 +00002309 }
2310 } else if (Tok.is(tok::l_paren)) {
2311 // Parse C++ direct initializer: '(' expression-list ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002312 BalancedDelimiterTracker T(*this, tok::l_paren);
2313 T.consumeOpen();
2314
Benjamin Kramerf0623432012-08-23 22:51:59 +00002315 ExprVector Exprs;
Douglas Gregor23996282009-05-12 21:31:51 +00002316 CommaLocsTy CommaLocs;
2317
Richard Smithc95d2c52017-09-22 04:25:05 +00002318 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Douglas Gregor613bf102009-12-22 17:47:17 +00002319
Ilya Biryukovcbea95d2017-09-08 13:36:38 +00002320 llvm::function_ref<void()> ExprListCompleter;
2321 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2322 auto ConstructorCompleter = [&, ThisVarDecl] {
2323 Actions.CodeCompleteConstructor(
2324 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2325 ThisDecl->getLocation(), Exprs);
2326 };
2327 if (ThisVarDecl) {
2328 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2329 // VarDecl. This is an error and it is reported in a call to
2330 // Actions.ActOnInitializerError(). However, we call
2331 // CodeCompleteConstructor only on VarDecls, falling back to default
2332 // completer in other cases.
2333 ExprListCompleter = ConstructorCompleter;
2334 }
2335
2336 if (ParseExpressionList(Exprs, CommaLocs, ExprListCompleter)) {
David Blaikieeae04112012-10-10 23:15:05 +00002337 Actions.ActOnInitializerError(ThisDecl);
Alexey Bataevee6507d2013-11-18 08:17:37 +00002338 SkipUntil(tok::r_paren, StopAtSemi);
Douglas Gregor23996282009-05-12 21:31:51 +00002339 } else {
2340 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002341 T.consumeClose();
Douglas Gregor23996282009-05-12 21:31:51 +00002342
2343 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2344 "Unexpected number of commas!");
Douglas Gregor613bf102009-12-22 17:47:17 +00002345
Richard Smithc95d2c52017-09-22 04:25:05 +00002346 InitScope.pop();
Douglas Gregor613bf102009-12-22 17:47:17 +00002347
Sebastian Redla9351792012-02-11 23:51:47 +00002348 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2349 T.getCloseLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002350 Exprs);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002351 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00002352 /*DirectInit=*/true);
Douglas Gregor23996282009-05-12 21:31:51 +00002353 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002354 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
Fariborz Jahanian8be1ecd2012-07-03 23:22:13 +00002355 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
Sebastian Redl3da34892011-06-05 12:23:16 +00002356 // Parse C++0x braced-init-list.
Richard Smith5d164bc2011-10-15 05:09:34 +00002357 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2358
Richard Smithc95d2c52017-09-22 04:25:05 +00002359 InitializerScopeRAII InitScope(*this, D, ThisDecl);
Sebastian Redl3da34892011-06-05 12:23:16 +00002360
2361 ExprResult Init(ParseBraceInitializer());
2362
Richard Smithc95d2c52017-09-22 04:25:05 +00002363 InitScope.pop();
Sebastian Redl3da34892011-06-05 12:23:16 +00002364
2365 if (Init.isInvalid()) {
2366 Actions.ActOnInitializerError(ThisDecl);
2367 } else
Richard Smith3beb7c62017-01-12 02:27:38 +00002368 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
Sebastian Redl3da34892011-06-05 12:23:16 +00002369
Douglas Gregor23996282009-05-12 21:31:51 +00002370 } else {
Richard Smith3beb7c62017-01-12 02:27:38 +00002371 Actions.ActOnUninitializedDecl(ThisDecl);
Douglas Gregor23996282009-05-12 21:31:51 +00002372 }
2373
Richard Smithb2bc2e62011-02-21 20:05:19 +00002374 Actions.FinalizeDeclaration(ThisDecl);
2375
Douglas Gregor23996282009-05-12 21:31:51 +00002376 return ThisDecl;
2377}
2378
Chris Lattner1890ac82006-08-13 01:16:23 +00002379/// ParseSpecifierQualifierList
2380/// specifier-qualifier-list:
2381/// type-specifier specifier-qualifier-list[opt]
2382/// type-qualifier specifier-qualifier-list[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002383/// [GNU] attributes specifier-qualifier-list[opt]
Chris Lattner1890ac82006-08-13 01:16:23 +00002384///
Richard Smithc5b05522012-03-12 07:56:15 +00002385void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2386 DeclSpecContext DSC) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002387 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2388 /// parse declaration-specifiers and complain about extra stuff.
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002389 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
Faisal Valia534f072018-04-26 00:42:40 +00002390 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
Mike Stump11289f42009-09-09 15:08:12 +00002391
Chris Lattner1890ac82006-08-13 01:16:23 +00002392 // Validate declspec for type-name.
2393 unsigned Specs = DS.getParsedSpecifiers();
Richard Smith649c7b062014-01-08 00:56:48 +00002394 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
Richard Smithc5b05522012-03-12 07:56:15 +00002395 Diag(Tok, diag::err_expected_type);
2396 DS.SetTypeSpecError();
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00002397 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
Chris Lattner1890ac82006-08-13 01:16:23 +00002398 Diag(Tok, diag::err_typename_requires_specqual);
Richard Smithc5b05522012-03-12 07:56:15 +00002399 if (!DS.hasTypeSpecifier())
2400 DS.SetTypeSpecError();
2401 }
Mike Stump11289f42009-09-09 15:08:12 +00002402
Chris Lattner1b22eed2006-11-28 05:12:07 +00002403 // Issue diagnostic and remove storage class if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002404 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
Chris Lattner1b22eed2006-11-28 05:12:07 +00002405 if (DS.getStorageClassSpecLoc().isValid())
2406 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2407 else
Richard Smithb4a9e862013-04-12 22:46:28 +00002408 Diag(DS.getThreadStorageClassSpecLoc(),
2409 diag::err_typename_invalid_storageclass);
Chris Lattnera925dc62006-11-28 04:33:46 +00002410 DS.ClearStorageClassSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002411 }
Mike Stump11289f42009-09-09 15:08:12 +00002412
Craig Topper3f13d4d22015-11-14 18:15:55 +00002413 // Issue diagnostic and remove function specifier if present.
Chris Lattner1890ac82006-08-13 01:16:23 +00002414 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
Douglas Gregor61956c42008-10-31 09:07:45 +00002415 if (DS.isInlineSpecified())
2416 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2417 if (DS.isVirtualSpecified())
2418 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2419 if (DS.isExplicitSpecified())
2420 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
Chris Lattnera925dc62006-11-28 04:33:46 +00002421 DS.ClearFunctionSpecs();
Chris Lattner1890ac82006-08-13 01:16:23 +00002422 }
Richard Smithc5b05522012-03-12 07:56:15 +00002423
2424 // Issue diagnostic and remove constexpr specfier if present.
Faisal Vali7db85c52017-12-31 00:06:40 +00002425 if (DS.isConstexprSpecified() && DSC != DeclSpecContext::DSC_condition) {
Richard Smithc5b05522012-03-12 07:56:15 +00002426 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2427 DS.ClearConstexprSpec();
2428 }
Chris Lattner1890ac82006-08-13 01:16:23 +00002429}
Chris Lattner53361ac2006-08-10 05:19:57 +00002430
Chris Lattner6cc055a2009-04-12 20:42:31 +00002431/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2432/// specified token is valid after the identifier in a declarator which
2433/// immediately follows the declspec. For example, these things are valid:
2434///
2435/// int x [ 4]; // direct-declarator
2436/// int x ( int y); // direct-declarator
2437/// int(int x ) // direct-declarator
2438/// int x ; // simple-declaration
2439/// int x = 17; // init-declarator-list
2440/// int x , y; // init-declarator-list
2441/// int x __asm__ ("foo"); // init-declarator-list
Chris Lattnera723ba92009-04-14 21:16:09 +00002442/// int x : 4; // struct-declarator
Chris Lattner2b988c12009-04-12 22:29:43 +00002443/// int x { 5}; // C++'0x unified initializers
Chris Lattner6cc055a2009-04-12 20:42:31 +00002444///
2445/// This is not, because 'x' does not immediately follow the declspec (though
2446/// ')' happens to be valid anyway).
2447/// int (x)
2448///
2449static bool isValidAfterIdentifierInDeclarator(const Token &T) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002450 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2451 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2452 tok::colon);
Chris Lattner6cc055a2009-04-12 20:42:31 +00002453}
2454
Chris Lattner20a0c612009-04-14 21:34:55 +00002455/// ParseImplicitInt - This method is called when we have an non-typename
2456/// identifier in a declspec (which normally terminates the decl spec) when
2457/// the declspec has no type specifier. In this case, the declspec is either
2458/// malformed or is "implicit int" (in K&R and C89).
2459///
2460/// This method handles diagnosing this prettily and returns false if the
2461/// declspec is done being processed. If it recovers and thinks there may be
2462/// other pieces of declspec after it, it returns true.
2463///
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002464bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002465 const ParsedTemplateInfo &TemplateInfo,
Richard Smitha0a5d502014-05-08 22:32:00 +00002466 AccessSpecifier AS, DeclSpecContext DSC,
Michael Han9407e502012-11-26 22:54:45 +00002467 ParsedAttributesWithRange &Attrs) {
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002468 assert(Tok.is(tok::identifier) && "should have identifier");
Mike Stump11289f42009-09-09 15:08:12 +00002469
Chris Lattner20a0c612009-04-14 21:34:55 +00002470 SourceLocation Loc = Tok.getLocation();
2471 // If we see an identifier that is not a type name, we normally would
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002472 // parse it as the identifier being declared. However, when a typename
Chris Lattner20a0c612009-04-14 21:34:55 +00002473 // is typo'd or the definition is not included, this will incorrectly
2474 // parse the typename as the identifier name and fall over misparsing
2475 // later parts of the diagnostic.
2476 //
2477 // As such, we try to do some look-ahead in cases where this would
2478 // otherwise be an "implicit-int" case to see if this is invalid. For
2479 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2480 // an identifier with implicit int, we'd get a parse error because the
2481 // next token is obviously invalid for a type. Parse these as a case
2482 // with an invalid type specifier.
2483 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
Mike Stump11289f42009-09-09 15:08:12 +00002484
Chris Lattner20a0c612009-04-14 21:34:55 +00002485 // Since we know that this either implicit int (which is rare) or an
Richard Smitha952ebb2012-05-15 21:01:51 +00002486 // error, do lookahead to try to do better recovery. This never applies
2487 // within a type specifier. Outside of C++, we allow this even if the
2488 // language doesn't "officially" support implicit int -- we support
Richard Smith3b870382013-04-30 22:43:51 +00002489 // implicit int as an extension in C99 and C11.
Richard Smith649c7b062014-01-08 00:56:48 +00002490 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
Richard Smithc5b05522012-03-12 07:56:15 +00002491 isValidAfterIdentifierInDeclarator(NextToken())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002492 // If this token is valid for implicit int, e.g. "static x = 4", then
2493 // we just avoid eating the identifier, so it will be parsed as the
2494 // identifier in the declarator.
2495 return false;
2496 }
Mike Stump11289f42009-09-09 15:08:12 +00002497
Richard Smitha952ebb2012-05-15 21:01:51 +00002498 if (getLangOpts().CPlusPlus &&
2499 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2500 // Don't require a type specifier if we have the 'auto' storage class
2501 // specifier in C++98 -- we'll promote it to a type specifier.
Richard Smithfb8b7b92013-10-15 00:00:26 +00002502 if (SS)
2503 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
Richard Smitha952ebb2012-05-15 21:01:51 +00002504 return false;
2505 }
2506
Reid Kleckner9a96e422016-05-24 21:23:54 +00002507 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2508 getLangOpts().MSVCCompat) {
2509 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2510 // Give Sema a chance to recover if we are in a template with dependent base
2511 // classes.
2512 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2513 *Tok.getIdentifierInfo(), Tok.getLocation(),
Faisal Vali7db85c52017-12-31 00:06:40 +00002514 DSC == DeclSpecContext::DSC_template_type_arg)) {
Reid Kleckner9a96e422016-05-24 21:23:54 +00002515 const char *PrevSpec;
2516 unsigned DiagID;
2517 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2518 Actions.getASTContext().getPrintingPolicy());
2519 DS.SetRangeEnd(Tok.getLocation());
2520 ConsumeToken();
2521 return false;
2522 }
2523 }
2524
Chris Lattner20a0c612009-04-14 21:34:55 +00002525 // Otherwise, if we don't consume this token, we are going to emit an
2526 // error anyway. Try to recover from various common problems. Check
2527 // to see if this was a reference to a tag name without a tag specified.
2528 // This is a common problem in C (saying 'foo' instead of 'struct foo').
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002529 //
2530 // C++ doesn't need this, and isTagName doesn't take SS.
Craig Topper161e4db2014-05-21 06:02:52 +00002531 if (SS == nullptr) {
2532 const char *TagName = nullptr, *FixitTagName = nullptr;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002533 tok::TokenKind TagKind = tok::unknown;
Mike Stump11289f42009-09-09 15:08:12 +00002534
Douglas Gregor0be31a22010-07-02 17:43:08 +00002535 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
Chris Lattner20a0c612009-04-14 21:34:55 +00002536 default: break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002537 case DeclSpec::TST_enum:
2538 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2539 case DeclSpec::TST_union:
2540 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2541 case DeclSpec::TST_struct:
2542 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
Joao Matosdc86f942012-08-31 18:45:21 +00002543 case DeclSpec::TST_interface:
2544 TagName="__interface"; FixitTagName = "__interface ";
2545 TagKind=tok::kw___interface;break;
Argyrios Kyrtzidis1f329402011-04-21 17:29:47 +00002546 case DeclSpec::TST_class:
2547 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
Chris Lattner20a0c612009-04-14 21:34:55 +00002548 }
Mike Stump11289f42009-09-09 15:08:12 +00002549
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002550 if (TagName) {
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002551 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2552 LookupResult R(Actions, TokenName, SourceLocation(),
2553 Sema::LookupOrdinaryName);
2554
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002555 Diag(Loc, diag::err_use_of_tag_name_without_tag)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002556 << TokenName << TagName << getLangOpts().CPlusPlus
2557 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2558
2559 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2560 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2561 I != IEnd; ++I)
Kaelyn Uhrain3fe3f852012-04-27 18:26:49 +00002562 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
Kaelyn Uhrain031643e2012-04-26 23:36:17 +00002563 << TokenName << TagName;
2564 }
Mike Stump11289f42009-09-09 15:08:12 +00002565
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002566 // Parse this as a tag as if the missing tag were present.
2567 if (TagKind == tok::kw_enum)
Faisal Vali7db85c52017-12-31 00:06:40 +00002568 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2569 DeclSpecContext::DSC_normal);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002570 else
Richard Smithc5b05522012-03-12 07:56:15 +00002571 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
Faisal Vali7db85c52017-12-31 00:06:40 +00002572 /*EnteringContext*/ false,
2573 DeclSpecContext::DSC_normal, Attrs);
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00002574 return true;
2575 }
Chris Lattner20a0c612009-04-14 21:34:55 +00002576 }
Mike Stump11289f42009-09-09 15:08:12 +00002577
Richard Smithfe904f02012-05-15 21:29:55 +00002578 // Determine whether this identifier could plausibly be the name of something
Richard Smithedd124e2012-05-15 21:42:17 +00002579 // being declared (with a missing type).
Faisal Vali7db85c52017-12-31 00:06:40 +00002580 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2581 DSC == DeclSpecContext::DSC_class)) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002582 // Look ahead to the next token to try to figure out what this declaration
2583 // was supposed to be.
2584 switch (NextToken().getKind()) {
Richard Smitha952ebb2012-05-15 21:01:51 +00002585 case tok::l_paren: {
2586 // static x(4); // 'x' is not a type
2587 // x(int n); // 'x' is not a type
2588 // x (*p)[]; // 'x' is a type
2589 //
Richard Smitha0a5d502014-05-08 22:32:00 +00002590 // Since we're in an error case, we can afford to perform a tentative
2591 // parse to determine which case we're in.
Richard Smitha952ebb2012-05-15 21:01:51 +00002592 TentativeParsingAction PA(*this);
2593 ConsumeToken();
2594 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2595 PA.Revert();
Richard Smithfb8b7b92013-10-15 00:00:26 +00002596
Richard Smithee390432014-05-16 01:56:53 +00002597 if (TPR != TPResult::False) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002598 // The identifier is followed by a parenthesized declarator.
2599 // It's supposed to be a type.
2600 break;
2601 }
2602
2603 // If we're in a context where we could be declaring a constructor,
2604 // check whether this is a constructor declaration with a bogus name.
Faisal Vali7db85c52017-12-31 00:06:40 +00002605 if (DSC == DeclSpecContext::DSC_class ||
2606 (DSC == DeclSpecContext::DSC_top_level && SS)) {
Richard Smithfb8b7b92013-10-15 00:00:26 +00002607 IdentifierInfo *II = Tok.getIdentifierInfo();
2608 if (Actions.isCurrentClassNameTypo(II, SS)) {
2609 Diag(Loc, diag::err_constructor_bad_name)
2610 << Tok.getIdentifierInfo() << II
2611 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2612 Tok.setIdentifierInfo(II);
2613 }
2614 }
2615 // Fall through.
Galina Kistanova77674252017-06-01 21:15:34 +00002616 LLVM_FALLTHROUGH;
Richard Smitha952ebb2012-05-15 21:01:51 +00002617 }
Richard Smithfb8b7b92013-10-15 00:00:26 +00002618 case tok::comma:
2619 case tok::equal:
2620 case tok::kw_asm:
2621 case tok::l_brace:
2622 case tok::l_square:
2623 case tok::semi:
2624 // This looks like a variable or function declaration. The type is
2625 // probably missing. We're done parsing decl-specifiers.
2626 if (SS)
2627 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2628 return false;
Richard Smitha952ebb2012-05-15 21:01:51 +00002629
2630 default:
2631 // This is probably supposed to be a type. This includes cases like:
2632 // int f(itn);
2633 // struct S { unsinged : 4; };
2634 break;
2635 }
2636 }
2637
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002638 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2639 // and attempt to recover.
John McCallba7bf592010-08-24 05:47:05 +00002640 ParsedType T;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +00002641 IdentifierInfo *II = Tok.getIdentifierInfo();
Richard Smith52f8d192017-05-10 21:32:16 +00002642 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002643 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
Richard Smith52f8d192017-05-10 21:32:16 +00002644 IsTemplateName);
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002645 if (T) {
2646 // The action has suggested that the type T could be used. Set that as
2647 // the type in the declaration specifiers, consume the would-be type
2648 // name token, and we're done.
2649 const char *PrevSpec;
2650 unsigned DiagID;
2651 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2652 Actions.getASTContext().getPrintingPolicy());
2653 DS.SetRangeEnd(Tok.getLocation());
2654 ConsumeToken();
2655 // There may be other declaration specifiers after this.
2656 return true;
2657 } else if (II != Tok.getIdentifierInfo()) {
2658 // If no type was suggested, the correction is to a keyword
2659 Tok.setKind(II->getTokenID());
2660 // There may be other declaration specifiers after this.
2661 return true;
Douglas Gregor15e56022009-10-13 23:27:22 +00002662 }
Mike Stump11289f42009-09-09 15:08:12 +00002663
Reid Klecknerc05ca5e2014-06-19 01:23:22 +00002664 // Otherwise, the action had no suggestion for us. Mark this as an error.
Richard Smithc5b05522012-03-12 07:56:15 +00002665 DS.SetTypeSpecError();
Chris Lattner20a0c612009-04-14 21:34:55 +00002666 DS.SetRangeEnd(Tok.getLocation());
2667 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00002668
Richard Smith52f8d192017-05-10 21:32:16 +00002669 // Eat any following template arguments.
2670 if (IsTemplateName) {
2671 SourceLocation LAngle, RAngle;
2672 TemplateArgList Args;
2673 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2674 }
2675
Chris Lattner20a0c612009-04-14 21:34:55 +00002676 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2677 // avoid rippling error messages on subsequent uses of the same type,
2678 // could be useful if #include was forgotten.
2679 return false;
2680}
2681
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002682/// Determine the declaration specifier context from the declarator
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002683/// context.
2684///
2685/// \param Context the declarator context, which is one of the
Faisal Vali421b2d12017-12-29 05:41:00 +00002686/// DeclaratorContext enumerator values.
Chad Rosierc1183952012-06-26 22:30:43 +00002687Parser::DeclSpecContext
Faisal Vali421b2d12017-12-29 05:41:00 +00002688Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2689 if (Context == DeclaratorContext::MemberContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002690 return DeclSpecContext::DSC_class;
Faisal Vali421b2d12017-12-29 05:41:00 +00002691 if (Context == DeclaratorContext::FileContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002692 return DeclSpecContext::DSC_top_level;
Faisal Vali421b2d12017-12-29 05:41:00 +00002693 if (Context == DeclaratorContext::TemplateParamContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002694 return DeclSpecContext::DSC_template_param;
Richard Smith77a9c602018-02-28 03:02:23 +00002695 if (Context == DeclaratorContext::TemplateArgContext ||
2696 Context == DeclaratorContext::TemplateTypeArgContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002697 return DeclSpecContext::DSC_template_type_arg;
Richard Smithe303e352018-02-02 22:24:54 +00002698 if (Context == DeclaratorContext::TrailingReturnContext ||
2699 Context == DeclaratorContext::TrailingReturnVarContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002700 return DeclSpecContext::DSC_trailing;
Faisal Vali421b2d12017-12-29 05:41:00 +00002701 if (Context == DeclaratorContext::AliasDeclContext ||
2702 Context == DeclaratorContext::AliasTemplateContext)
Faisal Vali7db85c52017-12-31 00:06:40 +00002703 return DeclSpecContext::DSC_alias_declaration;
2704 return DeclSpecContext::DSC_normal;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002705}
2706
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002707/// ParseAlignArgument - Parse the argument to an alignment-specifier.
2708///
2709/// FIXME: Simply returns an alignof() expression if the argument is a
2710/// type. Ideally, the type should be propagated directly into Sema.
2711///
Benjamin Kramere56f3932011-12-23 17:00:35 +00002712/// [C11] type-id
2713/// [C11] constant-expression
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002714/// [C++0x] type-id ...[opt]
2715/// [C++0x] assignment-expression ...[opt]
2716ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2717 SourceLocation &EllipsisLoc) {
2718 ExprResult ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002719 if (isTypeIdInParens()) {
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002720 SourceLocation TypeLoc = Tok.getLocation();
2721 ParsedType Ty = ParseTypeName().get();
2722 SourceRange TypeRange(Start, Tok.getLocation());
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002723 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2724 Ty.getAsOpaquePtr(), TypeRange);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002725 } else
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002726 ER = ParseConstantExpression();
2727
Alp Toker8fbec672013-12-17 23:29:36 +00002728 if (getLangOpts().CPlusPlus11)
2729 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002730
2731 return ER;
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002732}
2733
2734/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2735/// attribute to Attrs.
2736///
2737/// alignment-specifier:
Benjamin Kramere56f3932011-12-23 17:00:35 +00002738/// [C11] '_Alignas' '(' type-id ')'
2739/// [C11] '_Alignas' '(' constant-expression ')'
Richard Smithd11c7a12013-01-29 01:48:07 +00002740/// [C++11] 'alignas' '(' type-id ...[opt] ')'
2741/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002742void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
Richard Smith44c247f2013-02-22 08:32:16 +00002743 SourceLocation *EndLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002744 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002745 "Not an alignment-specifier!");
2746
Richard Smithd11c7a12013-01-29 01:48:07 +00002747 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2748 SourceLocation KWLoc = ConsumeToken();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002749
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002750 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002751 if (T.expectAndConsume())
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002752 return;
2753
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002754 SourceLocation EllipsisLoc;
2755 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002756 if (ArgExpr.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002757 T.skipToEnd();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002758 return;
2759 }
2760
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002761 T.consumeClose();
Richard Smith44c247f2013-02-22 08:32:16 +00002762 if (EndLoc)
2763 *EndLoc = T.getCloseLocation();
Peter Collingbourne7d33cd32011-10-23 20:07:52 +00002764
Aaron Ballman00e99962013-08-31 01:11:41 +00002765 ArgsVector ArgExprs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002766 ArgExprs.push_back(ArgExpr.get());
Craig Topper161e4db2014-05-21 06:02:52 +00002767 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
Aaron Ballman00e99962013-08-31 01:11:41 +00002768 AttributeList::AS_Keyword, EllipsisLoc);
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00002769}
2770
Richard Smith404dfb42013-11-19 22:47:36 +00002771/// Determine whether we're looking at something that might be a declarator
2772/// in a simple-declaration. If it can't possibly be a declarator, maybe
2773/// diagnose a missing semicolon after a prior tag definition in the decl
2774/// specifier.
2775///
2776/// \return \c true if an error occurred and this can't be any kind of
2777/// declaration.
2778bool
2779Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2780 DeclSpecContext DSContext,
2781 LateParsedAttrList *LateAttrs) {
2782 assert(DS.hasTagDefinition() && "shouldn't call this");
2783
Faisal Vali7db85c52017-12-31 00:06:40 +00002784 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2785 DSContext == DeclSpecContext::DSC_top_level);
Richard Smith404dfb42013-11-19 22:47:36 +00002786
2787 if (getLangOpts().CPlusPlus &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002788 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2789 tok::annot_template_id) &&
Richard Smith404dfb42013-11-19 22:47:36 +00002790 TryAnnotateCXXScopeToken(EnteringContext)) {
2791 SkipMalformedDecl();
2792 return true;
2793 }
2794
Richard Smith698875a2013-11-20 23:40:57 +00002795 bool HasScope = Tok.is(tok::annot_cxxscope);
2796 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2797 Token AfterScope = HasScope ? NextToken() : Tok;
2798
Richard Smith404dfb42013-11-19 22:47:36 +00002799 // Determine whether the following tokens could possibly be a
2800 // declarator.
Richard Smith698875a2013-11-20 23:40:57 +00002801 bool MightBeDeclarator = true;
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002802 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
Richard Smith698875a2013-11-20 23:40:57 +00002803 // A declarator-id can't start with 'typename'.
2804 MightBeDeclarator = false;
2805 } else if (AfterScope.is(tok::annot_template_id)) {
2806 // If we have a type expressed as a template-id, this cannot be a
2807 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2808 TemplateIdAnnotation *Annot =
2809 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2810 if (Annot->Kind == TNK_Type_template)
2811 MightBeDeclarator = false;
2812 } else if (AfterScope.is(tok::identifier)) {
2813 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2814
Richard Smith404dfb42013-11-19 22:47:36 +00002815 // These tokens cannot come after the declarator-id in a
2816 // simple-declaration, and are likely to come after a type-specifier.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002817 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2818 tok::annot_cxxscope, tok::coloncolon)) {
Richard Smith698875a2013-11-20 23:40:57 +00002819 // Missing a semicolon.
2820 MightBeDeclarator = false;
2821 } else if (HasScope) {
2822 // If the declarator-id has a scope specifier, it must redeclare a
2823 // previously-declared entity. If that's a type (and this is not a
2824 // typedef), that's an error.
2825 CXXScopeSpec SS;
2826 Actions.RestoreNestedNameSpecifierAnnotation(
2827 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2828 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2829 Sema::NameClassification Classification = Actions.ClassifyName(
2830 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2831 /*IsAddressOfOperand*/false);
2832 switch (Classification.getKind()) {
2833 case Sema::NC_Error:
2834 SkipMalformedDecl();
2835 return true;
Richard Smith404dfb42013-11-19 22:47:36 +00002836
Richard Smith698875a2013-11-20 23:40:57 +00002837 case Sema::NC_Keyword:
2838 case Sema::NC_NestedNameSpecifier:
2839 llvm_unreachable("typo correction and nested name specifiers not "
2840 "possible here");
Richard Smith404dfb42013-11-19 22:47:36 +00002841
Richard Smith698875a2013-11-20 23:40:57 +00002842 case Sema::NC_Type:
2843 case Sema::NC_TypeTemplate:
2844 // Not a previously-declared non-type entity.
2845 MightBeDeclarator = false;
2846 break;
Richard Smith404dfb42013-11-19 22:47:36 +00002847
Richard Smith698875a2013-11-20 23:40:57 +00002848 case Sema::NC_Unknown:
2849 case Sema::NC_Expression:
2850 case Sema::NC_VarTemplate:
2851 case Sema::NC_FunctionTemplate:
2852 // Might be a redeclaration of a prior entity.
2853 break;
2854 }
Richard Smith404dfb42013-11-19 22:47:36 +00002855 }
Richard Smith404dfb42013-11-19 22:47:36 +00002856 }
2857
Richard Smith698875a2013-11-20 23:40:57 +00002858 if (MightBeDeclarator)
Richard Smith404dfb42013-11-19 22:47:36 +00002859 return false;
2860
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002861 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
Richard Smith404dfb42013-11-19 22:47:36 +00002862 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()),
Alp Toker383d2c42014-01-01 03:08:43 +00002863 diag::err_expected_after)
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002864 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
Richard Smith404dfb42013-11-19 22:47:36 +00002865
2866 // Try to recover from the typo, by dropping the tag definition and parsing
2867 // the problematic tokens as a type.
2868 //
2869 // FIXME: Split the DeclSpec into pieces for the standalone
2870 // declaration and pieces for the following declaration, instead
2871 // of assuming that all the other pieces attach to new declaration,
2872 // and call ParsedFreeStandingDeclSpec as appropriate.
2873 DS.ClearTypeSpecType();
2874 ParsedTemplateInfo NotATemplate;
Faisal Valia534f072018-04-26 00:42:40 +00002875 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
Richard Smith404dfb42013-11-19 22:47:36 +00002876 return false;
2877}
2878
Leonard Chanab80f3c2018-06-14 14:53:51 +00002879// Choose the apprpriate diagnostic error for why fixed point types are
2880// disabled, set the previous specifier, and mark as invalid.
2881static void SetupFixedPointError(const LangOptions &LangOpts,
2882 const char *&PrevSpec, unsigned &DiagID,
2883 bool &isInvalid) {
2884 assert(!LangOpts.FixedPoint);
2885 DiagID = diag::err_fixed_point_not_enabled;
2886 PrevSpec = ""; // Not used by diagnostic
2887 isInvalid = true;
2888}
2889
Faisal Valia534f072018-04-26 00:42:40 +00002890/// ParseDeclarationSpecifiers
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002891/// declaration-specifiers: [C99 6.7]
Chris Lattner3b561a32006-08-13 00:12:11 +00002892/// storage-class-specifier declaration-specifiers[opt]
2893/// type-specifier declaration-specifiers[opt]
Chris Lattner3b561a32006-08-13 00:12:11 +00002894/// [C99] function-specifier declaration-specifiers[opt]
Benjamin Kramere56f3932011-12-23 17:00:35 +00002895/// [C11] alignment-specifier declaration-specifiers[opt]
Chris Lattnere37e2332006-08-15 04:50:22 +00002896/// [GNU] attributes declaration-specifiers[opt]
Douglas Gregor26701a42011-09-09 02:06:17 +00002897/// [Clang] '__module_private__' declaration-specifiers[opt]
Douglas Gregorab209d82015-07-07 03:58:42 +00002898/// [ObjC1] '__kindof' declaration-specifiers[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002899///
Chris Lattnerf63f89a2006-08-05 03:28:50 +00002900/// storage-class-specifier: [C99 6.7.1]
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002901/// 'typedef'
2902/// 'extern'
2903/// 'static'
2904/// 'auto'
2905/// 'register'
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002906/// [C++] 'mutable'
Richard Smithb4a9e862013-04-12 22:46:28 +00002907/// [C++11] 'thread_local'
2908/// [C11] '_Thread_local'
Chris Lattnerda48a8e2006-08-04 05:25:55 +00002909/// [GNU] '__thread'
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002910/// function-specifier: [C99 6.7.4]
Chris Lattner3b561a32006-08-13 00:12:11 +00002911/// [C99] 'inline'
Douglas Gregor61956c42008-10-31 09:07:45 +00002912/// [C++] 'virtual'
2913/// [C++] 'explicit'
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00002914/// [OpenCL] '__kernel'
Anders Carlssoncd8db412009-05-06 04:46:28 +00002915/// 'friend': [C++ dcl.friend]
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00002916/// 'constexpr': [C++0x dcl.constexpr]
Faisal Valia534f072018-04-26 00:42:40 +00002917void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002918 const ParsedTemplateInfo &TemplateInfo,
John McCall07e91c02009-08-06 02:15:43 +00002919 AccessSpecifier AS,
DeLesley Hutchinsbd2ee132012-03-02 22:12:59 +00002920 DeclSpecContext DSContext,
2921 LateParsedAttrList *LateAttrs) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002922 if (DS.getSourceRange().isInvalid()) {
David Majnemer24b28302014-07-26 05:41:31 +00002923 // Start the range at the current token but make the end of the range
2924 // invalid. This will make the entire range invalid unless we successfully
2925 // consume a token.
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002926 DS.SetRangeStart(Tok.getLocation());
David Majnemer24b28302014-07-26 05:41:31 +00002927 DS.SetRangeEnd(SourceLocation());
Douglas Gregor0e7dde52011-04-24 05:37:28 +00002928 }
Chad Rosierc1183952012-06-26 22:30:43 +00002929
Faisal Vali7db85c52017-12-31 00:06:40 +00002930 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2931 DSContext == DeclSpecContext::DSC_top_level);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002932 bool AttrsLastTime = false;
2933 ParsedAttributesWithRange attrs(AttrFactory);
Benjamin Kramere4812142015-03-12 14:28:38 +00002934 // We use Sema's policy to get bool macros right.
Richard Smith301bc212016-05-19 01:39:10 +00002935 PrintingPolicy Policy = Actions.getPrintingPolicy();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002936 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00002937 bool isInvalid = false;
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00002938 bool isStorageClass = false;
Craig Topper161e4db2014-05-21 06:02:52 +00002939 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00002940 unsigned DiagID = 0;
2941
David Majnemer51fd8a02015-07-22 23:46:18 +00002942 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2943 // implementation for VS2013 uses _Atomic as an identifier for one of the
2944 // classes in <atomic>.
2945 //
2946 // A typedef declaration containing _Atomic<...> is among the places where
2947 // the class is used. If we are currently parsing such a declaration, treat
2948 // the token as an identifier.
2949 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2950 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2951 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2952 Tok.setKind(tok::identifier);
2953
Chris Lattner4d8f8732006-11-28 05:05:08 +00002954 SourceLocation Loc = Tok.getLocation();
Douglas Gregor450c75a2008-11-07 15:42:26 +00002955
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00002956 switch (Tok.getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00002957 default:
Chris Lattner0974b232008-07-26 00:20:22 +00002958 DoneWithDeclSpec:
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002959 if (!AttrsLastTime)
2960 ProhibitAttributes(attrs);
Michael Han64536a62012-11-06 19:34:54 +00002961 else {
2962 // Reject C++11 attributes that appertain to decl specifiers as
2963 // we don't support any C++11 attributes that appertain to decl
2964 // specifiers. This also conforms to what g++ 4.8 is doing.
Richard Smith49cc1cc2016-08-18 21:59:42 +00002965 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
Michael Han64536a62012-11-06 19:34:54 +00002966
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002967 DS.takeAttributesFrom(attrs);
Michael Han64536a62012-11-06 19:34:54 +00002968 }
Peter Collingbourne70188b32011-09-29 18:03:57 +00002969
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002970 // If this is not a declaration specifier token, we're done reading decl
2971 // specifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00002972 DS.Finish(Actions, Policy);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00002973 return;
Mike Stump11289f42009-09-09 15:08:12 +00002974
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002975 case tok::l_square:
2976 case tok::kw_alignas:
Aaron Ballman606093a2017-10-15 15:01:42 +00002977 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002978 goto DoneWithDeclSpec;
2979
2980 ProhibitAttributes(attrs);
2981 // FIXME: It would be good to recover by accepting the attributes,
2982 // but attempting to do that now would cause serious
2983 // madness in terms of diagnostics.
2984 attrs.clear();
2985 attrs.Range = SourceRange();
2986
2987 ParseCXX11Attributes(attrs);
2988 AttrsLastTime = true;
Chad Rosierc1183952012-06-26 22:30:43 +00002989 continue;
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00002990
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002991 case tok::code_completion: {
John McCallfaf5fb42010-08-26 23:41:50 +00002992 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002993 if (DS.hasTypeSpecifier()) {
2994 bool AllowNonIdentifiers
2995 = (getCurScope()->getFlags() & (Scope::ControlScope |
2996 Scope::BlockScope |
2997 Scope::TemplateParamScope |
2998 Scope::FunctionPrototypeScope |
2999 Scope::AtCatchScope)) == 0;
3000 bool AllowNestedNameSpecifiers
Faisal Vali7db85c52017-12-31 00:06:40 +00003001 = DSContext == DeclSpecContext::DSC_top_level ||
3002 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003003
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003004 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
Chad Rosierc1183952012-06-26 22:30:43 +00003005 AllowNonIdentifiers,
Douglas Gregorbfcea8b2010-09-16 15:14:18 +00003006 AllowNestedNameSpecifiers);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003007 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00003008 }
3009
Douglas Gregor80039242011-02-15 20:33:25 +00003010 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3011 CCC = Sema::PCC_LocalDeclarationSpecifiers;
3012 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
Faisal Vali7db85c52017-12-31 00:06:40 +00003013 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3014 : Sema::PCC_Template;
3015 else if (DSContext == DeclSpecContext::DSC_class)
John McCallfaf5fb42010-08-26 23:41:50 +00003016 CCC = Sema::PCC_Class;
Argyrios Kyrtzidisb6c6a582012-02-07 16:50:53 +00003017 else if (CurParsedObjCImpl)
John McCallfaf5fb42010-08-26 23:41:50 +00003018 CCC = Sema::PCC_ObjCImplementation;
Chad Rosierc1183952012-06-26 22:30:43 +00003019
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003020 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003021 return cutOffParsing();
Douglas Gregorc49f5b22010-08-23 18:23:48 +00003022 }
3023
Chris Lattnerbd31aa32009-01-05 00:07:25 +00003024 case tok::coloncolon: // ::foo::bar
John McCall1f476a12010-02-26 08:45:28 +00003025 // C++ scope specifier. Annotate and loop, or bail out on error.
Eli Friedman2a1d9a92013-08-15 23:59:20 +00003026 if (TryAnnotateCXXScopeToken(EnteringContext)) {
John McCall1f476a12010-02-26 08:45:28 +00003027 if (!DS.hasTypeSpecifier())
3028 DS.SetTypeSpecError();
3029 goto DoneWithDeclSpec;
3030 }
John McCall8bc2a702010-03-01 18:20:46 +00003031 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3032 goto DoneWithDeclSpec;
John McCall1f476a12010-02-26 08:45:28 +00003033 continue;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003034
3035 case tok::annot_cxxscope: {
Richard Smith3092a3b2012-05-09 18:56:43 +00003036 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003037 goto DoneWithDeclSpec;
3038
John McCall9dab4e62009-12-12 11:40:51 +00003039 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00003040 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3041 Tok.getAnnotationRange(),
3042 SS);
John McCall9dab4e62009-12-12 11:40:51 +00003043
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003044 // We are looking for a qualified typename.
Douglas Gregor167fa622009-03-25 15:40:00 +00003045 Token Next = NextToken();
Mike Stump11289f42009-09-09 15:08:12 +00003046 if (Next.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003047 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
Douglas Gregorb67535d2009-03-31 00:43:58 +00003048 ->Kind == TNK_Type_template) {
Douglas Gregor167fa622009-03-25 15:40:00 +00003049 // We have a qualified template-id, e.g., N::A<int>
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003050
Richard Smith74f02342017-01-19 21:00:13 +00003051 // If this would be a valid constructor declaration with template
3052 // arguments, we will reject the attempt to form an invalid type-id
3053 // referring to the injected-class-name when we annotate the token,
3054 // per C++ [class.qual]p2.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003055 //
Richard Smith74f02342017-01-19 21:00:13 +00003056 // To improve diagnostics for this case, parse the declaration as a
3057 // constructor (and reject the extra template arguments later).
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003058 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
Faisal Vali7db85c52017-12-31 00:06:40 +00003059 if ((DSContext == DeclSpecContext::DSC_top_level ||
3060 DSContext == DeclSpecContext::DSC_class) &&
John McCall84821e72010-04-13 06:39:49 +00003061 TemplateId->Name &&
Richard Smith74f02342017-01-19 21:00:13 +00003062 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003063 isConstructorDeclarator(/*Unqualified*/ false)) {
Richard Smith74f02342017-01-19 21:00:13 +00003064 // The user meant this to be an out-of-line constructor
3065 // definition, but template arguments are not allowed
3066 // there. Just allow this as a constructor; we'll
3067 // complain about it later.
3068 goto DoneWithDeclSpec;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003069 }
3070
John McCall9dab4e62009-12-12 11:40:51 +00003071 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003072 ConsumeAnnotationToken(); // The C++ scope.
Mike Stump11289f42009-09-09 15:08:12 +00003073 assert(Tok.is(tok::annot_template_id) &&
Douglas Gregor167fa622009-03-25 15:40:00 +00003074 "ParseOptionalCXXScopeSpecifier not working");
Douglas Gregore7c20652011-03-02 00:47:37 +00003075 AnnotateTemplateIdTokenAsType();
Douglas Gregor167fa622009-03-25 15:40:00 +00003076 continue;
3077 }
3078
Douglas Gregorc5790df2009-09-28 07:26:33 +00003079 if (Next.is(tok::annot_typename)) {
John McCall9dab4e62009-12-12 11:40:51 +00003080 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003081 ConsumeAnnotationToken(); // The C++ scope.
John McCallba7bf592010-08-24 05:47:05 +00003082 if (Tok.getAnnotationValue()) {
3083 ParsedType T = getTypeAnnotation(Tok);
Nico Weber77430342010-11-22 10:30:56 +00003084 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
Chad Rosierc1183952012-06-26 22:30:43 +00003085 Tok.getAnnotationEndLoc(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003086 PrevSpec, DiagID, T, Policy);
Richard Smithda837032012-09-14 18:27:01 +00003087 if (isInvalid)
3088 break;
John McCallba7bf592010-08-24 05:47:05 +00003089 }
Douglas Gregorc5790df2009-09-28 07:26:33 +00003090 else
3091 DS.SetTypeSpecError();
3092 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003093 ConsumeAnnotationToken(); // The typename
Douglas Gregorc5790df2009-09-28 07:26:33 +00003094 }
3095
Douglas Gregor167fa622009-03-25 15:40:00 +00003096 if (Next.isNot(tok::identifier))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003097 goto DoneWithDeclSpec;
3098
Richard Smith74f02342017-01-19 21:00:13 +00003099 // Check whether this is a constructor declaration. If we're in a
3100 // context where the identifier could be a class name, and it has the
3101 // shape of a constructor declaration, process it as one.
Faisal Vali7db85c52017-12-31 00:06:40 +00003102 if ((DSContext == DeclSpecContext::DSC_top_level ||
3103 DSContext == DeclSpecContext::DSC_class) &&
Chad Rosierc1183952012-06-26 22:30:43 +00003104 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
Richard Smith74f02342017-01-19 21:00:13 +00003105 &SS) &&
3106 isConstructorDeclarator(/*Unqualified*/ false))
3107 goto DoneWithDeclSpec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003108
David Blaikieefdccaa2016-01-15 23:43:34 +00003109 ParsedType TypeRep =
3110 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3111 getCurScope(), &SS, false, false, nullptr,
3112 /*IsCtorOrDtorName=*/false,
Richard Smith600b5262017-01-26 20:40:47 +00003113 /*WantNonTrivialSourceInfo=*/true,
3114 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003115
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003116 // If the referenced identifier is not a type, then this declspec is
3117 // erroneous: We already checked about that it has no type specifier, and
3118 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
Mike Stump11289f42009-09-09 15:08:12 +00003119 // typename.
David Blaikie7d170102013-05-15 07:37:26 +00003120 if (!TypeRep) {
Richard Smithaf3b3252017-05-18 19:21:48 +00003121 // Eat the scope spec so the identifier is current.
3122 ConsumeAnnotationToken();
Michael Han9407e502012-11-26 22:54:45 +00003123 ParsedAttributesWithRange Attrs(AttrFactory);
3124 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3125 if (!Attrs.empty()) {
3126 AttrsLastTime = true;
3127 attrs.takeAllFrom(Attrs);
3128 }
3129 continue;
3130 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003131 goto DoneWithDeclSpec;
Chris Lattnerb4a8fe82009-04-14 22:17:06 +00003132 }
Mike Stump11289f42009-09-09 15:08:12 +00003133
John McCall9dab4e62009-12-12 11:40:51 +00003134 DS.getTypeSpecScope() = SS;
Richard Smithaf3b3252017-05-18 19:21:48 +00003135 ConsumeAnnotationToken(); // The C++ scope.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003136
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003137 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003138 DiagID, TypeRep, Policy);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003139 if (isInvalid)
3140 break;
Mike Stump11289f42009-09-09 15:08:12 +00003141
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00003142 DS.SetRangeEnd(Tok.getLocation());
3143 ConsumeToken(); // The typename.
3144
3145 continue;
3146 }
Mike Stump11289f42009-09-09 15:08:12 +00003147
Chris Lattnere387d9e2009-01-21 19:48:37 +00003148 case tok::annot_typename: {
Richard Smith404dfb42013-11-19 22:47:36 +00003149 // If we've previously seen a tag definition, we were almost surely
3150 // missing a semicolon after it.
3151 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3152 goto DoneWithDeclSpec;
3153
John McCallba7bf592010-08-24 05:47:05 +00003154 if (Tok.getAnnotationValue()) {
3155 ParsedType T = getTypeAnnotation(Tok);
Nico Weber7f8bb362010-11-22 12:50:03 +00003156 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003157 DiagID, T, Policy);
John McCallba7bf592010-08-24 05:47:05 +00003158 } else
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003159 DS.SetTypeSpecError();
Chad Rosierc1183952012-06-26 22:30:43 +00003160
Chris Lattner005fc1b2010-04-05 18:18:31 +00003161 if (isInvalid)
3162 break;
3163
Chris Lattnere387d9e2009-01-21 19:48:37 +00003164 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00003165 ConsumeAnnotationToken(); // The typename
Mike Stump11289f42009-09-09 15:08:12 +00003166
Chris Lattnere387d9e2009-01-21 19:48:37 +00003167 continue;
3168 }
Mike Stump11289f42009-09-09 15:08:12 +00003169
Douglas Gregor06873092011-04-28 15:48:45 +00003170 case tok::kw___is_signed:
3171 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3172 // typically treats it as a trait. If we see __is_signed as it appears
3173 // in libstdc++, e.g.,
3174 //
3175 // static const bool __is_signed;
3176 //
3177 // then treat __is_signed as an identifier rather than as a keyword.
Faisal Vali090da2d2018-01-01 18:23:28 +00003178 if (DS.getTypeSpecType() == TST_bool &&
Douglas Gregor06873092011-04-28 15:48:45 +00003179 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
Alp Toker47642d22013-12-03 06:13:01 +00003180 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3181 TryKeywordIdentFallback(true);
Douglas Gregor06873092011-04-28 15:48:45 +00003182
3183 // We're done with the declaration-specifiers.
3184 goto DoneWithDeclSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00003185
Chris Lattner16fac4f2008-07-26 01:18:38 +00003186 // typedef-name
Nikola Smiljanic67860242014-09-26 00:28:20 +00003187 case tok::kw___super:
David Blaikie15a430a2011-12-04 05:04:18 +00003188 case tok::kw_decltype:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003189 case tok::identifier: {
Reid Klecknerc582f012014-07-14 18:19:58 +00003190 // This identifier can only be a typedef name if we haven't already seen
3191 // a type-specifier. Without this check we misparse:
3192 // typedef int X; struct Y { short X; }; as 'short int'.
3193 if (DS.hasTypeSpecifier())
3194 goto DoneWithDeclSpec;
3195
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003196 // If the token is an identifier named "__declspec" and Microsoft
3197 // extensions are not enabled, it is likely that there will be cascading
3198 // parse errors if this really is a __declspec attribute. Attempt to
3199 // recognize that scenario and recover gracefully.
3200 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3201 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3202 Diag(Loc, diag::err_ms_attributes_not_enabled);
3203
3204 // The next token should be an open paren. If it is, eat the entire
3205 // attribute declaration and continue.
3206 if (NextToken().is(tok::l_paren)) {
3207 // Consume the __declspec identifier.
Richard Trieuba057372017-02-14 23:56:55 +00003208 ConsumeToken();
Aaron Ballman52d0aaa2017-02-14 22:47:20 +00003209
3210 // Eat the parens and everything between them.
3211 BalancedDelimiterTracker T(*this, tok::l_paren);
3212 if (T.consumeOpen()) {
3213 assert(false && "Not a left paren?");
3214 return;
3215 }
3216 T.skipToEnd();
3217 continue;
3218 }
3219 }
3220
Serge Pavlov458ea762014-07-16 05:16:52 +00003221 // In C++, check to see if this is a scope specifier like foo::bar::, if
3222 // so handle it as such. This is important for ctor parsing.
3223 if (getLangOpts().CPlusPlus) {
3224 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3225 DS.SetTypeSpecError();
3226 goto DoneWithDeclSpec;
3227 }
3228 if (!Tok.is(tok::identifier))
3229 continue;
3230 }
3231
John Thompson22334602010-02-05 00:12:22 +00003232 // Check for need to substitute AltiVec keyword tokens.
3233 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3234 break;
3235
Richard Smith3092a3b2012-05-09 18:56:43 +00003236 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3237 // allow the use of a typedef name as a type specifier.
3238 if (DS.isTypeAltiVecVector())
3239 goto DoneWithDeclSpec;
3240
Faisal Vali7db85c52017-12-31 00:06:40 +00003241 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3242 isObjCInstancetype()) {
Douglas Gregor5c0870a2015-06-19 23:18:00 +00003243 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3244 assert(TypeRep);
3245 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3246 DiagID, TypeRep, Policy);
3247 if (isInvalid)
3248 break;
3249
3250 DS.SetRangeEnd(Loc);
3251 ConsumeToken();
3252 continue;
3253 }
3254
Richard Smith715ee072018-06-20 21:58:20 +00003255 // If we're in a context where the identifier could be a class name,
3256 // check whether this is a constructor declaration.
3257 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3258 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3259 isConstructorDeclarator(/*Unqualified*/true))
3260 goto DoneWithDeclSpec;
3261
Richard Smith600b5262017-01-26 20:40:47 +00003262 ParsedType TypeRep = Actions.getTypeName(
3263 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3264 false, false, nullptr, false, false,
3265 isClassTemplateDeductionContext(DSContext));
Douglas Gregor8bf42052009-02-09 18:46:07 +00003266
Chris Lattner6cc055a2009-04-12 20:42:31 +00003267 // If this is not a typedef name, don't parse it as part of the declspec,
3268 // it must be an implicit int or an error.
John McCallba7bf592010-08-24 05:47:05 +00003269 if (!TypeRep) {
Michael Han9407e502012-11-26 22:54:45 +00003270 ParsedAttributesWithRange Attrs(AttrFactory);
Craig Topper161e4db2014-05-21 06:02:52 +00003271 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
Michael Han9407e502012-11-26 22:54:45 +00003272 if (!Attrs.empty()) {
3273 AttrsLastTime = true;
3274 attrs.takeAllFrom(Attrs);
3275 }
3276 continue;
3277 }
Chris Lattner16fac4f2008-07-26 01:18:38 +00003278 goto DoneWithDeclSpec;
Chris Lattner6cc055a2009-04-12 20:42:31 +00003279 }
Douglas Gregor8bf42052009-02-09 18:46:07 +00003280
Richard Smith35845152017-02-07 01:37:30 +00003281 // Likewise, if this is a context where the identifier could be a template
3282 // name, check whether this is a deduction guide declaration.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003283 if (getLangOpts().CPlusPlus17 &&
Faisal Vali7db85c52017-12-31 00:06:40 +00003284 (DSContext == DeclSpecContext::DSC_class ||
3285 DSContext == DeclSpecContext::DSC_top_level) &&
Richard Smith35845152017-02-07 01:37:30 +00003286 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3287 Tok.getLocation()) &&
3288 isConstructorDeclarator(/*Unqualified*/ true,
3289 /*DeductionGuide*/ true))
3290 goto DoneWithDeclSpec;
3291
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003292 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003293 DiagID, TypeRep, Policy);
Chris Lattner16fac4f2008-07-26 01:18:38 +00003294 if (isInvalid)
3295 break;
Mike Stump11289f42009-09-09 15:08:12 +00003296
Chris Lattner16fac4f2008-07-26 01:18:38 +00003297 DS.SetRangeEnd(Tok.getLocation());
3298 ConsumeToken(); // The identifier
3299
Douglas Gregore9d95f12015-07-07 03:57:35 +00003300 // Objective-C supports type arguments and protocol references
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003301 // following an Objective-C object or object pointer
3302 // type. Handle either one of them.
Douglas Gregore9d95f12015-07-07 03:57:35 +00003303 if (Tok.is(tok::less) && getLangOpts().ObjC1) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003304 SourceLocation NewEndLoc;
3305 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3306 Loc, TypeRep, /*consumeLastToken=*/true,
3307 NewEndLoc);
3308 if (NewTypeRep.isUsable()) {
3309 DS.UpdateTypeRep(NewTypeRep.get());
3310 DS.SetRangeEnd(NewEndLoc);
3311 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00003312 }
Chad Rosierc1183952012-06-26 22:30:43 +00003313
Steve Naroffcd5e7822008-09-22 10:28:57 +00003314 // Need to support trailing type qualifiers (e.g. "id<p> const").
3315 // If a type specifier follows, it will be diagnosed elsewhere.
3316 continue;
Chris Lattner16fac4f2008-07-26 01:18:38 +00003317 }
Douglas Gregor7f741122009-02-25 19:37:18 +00003318
3319 // type-name
3320 case tok::annot_template_id: {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00003321 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorb67535d2009-03-31 00:43:58 +00003322 if (TemplateId->Kind != TNK_Type_template) {
Douglas Gregor7f741122009-02-25 19:37:18 +00003323 // This template-id does not refer to a type name, so we're
3324 // done with the type-specifiers.
3325 goto DoneWithDeclSpec;
3326 }
3327
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003328 // If we're in a context where the template-id could be a
3329 // constructor name or specialization, check whether this is a
3330 // constructor declaration.
Faisal Vali7db85c52017-12-31 00:06:40 +00003331 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00003332 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
Richard Smith446161b2014-03-03 21:12:53 +00003333 isConstructorDeclarator(TemplateId->SS.isEmpty()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003334 goto DoneWithDeclSpec;
3335
Douglas Gregor7f741122009-02-25 19:37:18 +00003336 // Turn the template-id annotation token into a type annotation
3337 // token, then try again to parse it as a type-specifier.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00003338 AnnotateTemplateIdTokenAsType();
Douglas Gregor7f741122009-02-25 19:37:18 +00003339 continue;
3340 }
3341
Chris Lattnere37e2332006-08-15 04:50:22 +00003342 // GNU attributes support.
3343 case tok::kw___attribute:
Craig Topper161e4db2014-05-21 06:02:52 +00003344 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
Chris Lattnerb95cca02006-10-17 03:01:08 +00003345 continue;
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003346
3347 // Microsoft declspec support.
3348 case tok::kw___declspec:
Aaron Ballman068aa512015-05-20 20:58:33 +00003349 ParseMicrosoftDeclSpecs(DS.getAttributes());
Steve Naroff3a9b7e02008-12-24 20:59:21 +00003350 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003351
Steve Naroff44ac7772008-12-25 14:16:32 +00003352 // Microsoft single token adornments.
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003353 case tok::kw___forceinline: {
Serge Pavlov750db652013-11-13 06:57:53 +00003354 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003355 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
Richard Smithda837032012-09-14 18:27:01 +00003356 SourceLocation AttrNameLoc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00003357 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3358 nullptr, 0, AttributeList::AS_Keyword);
Richard Smithda837032012-09-14 18:27:01 +00003359 break;
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00003360 }
Eli Friedman53339e02009-06-08 23:27:34 +00003361
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003362 case tok::kw___unaligned:
3363 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3364 getLangOpts());
3365 break;
3366
Aaron Ballman317a77f2013-05-22 23:25:32 +00003367 case tok::kw___sptr:
3368 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00003369 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00003370 case tok::kw___ptr32:
Steve Narofff9c29d42008-12-25 14:41:26 +00003371 case tok::kw___w64:
Steve Naroff44ac7772008-12-25 14:16:32 +00003372 case tok::kw___cdecl:
3373 case tok::kw___stdcall:
3374 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00003375 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00003376 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00003377 case tok::kw___vectorcall:
John McCall53fa7142010-12-24 02:08:15 +00003378 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00003379 continue;
3380
Dawn Perchik335e16b2010-09-03 01:29:35 +00003381 // Borland single token adornments.
3382 case tok::kw___pascal:
John McCall53fa7142010-12-24 02:08:15 +00003383 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00003384 continue;
3385
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003386 // OpenCL single token adornments.
3387 case tok::kw___kernel:
Anastasia Stulova6bdbcbb2016-02-19 18:30:11 +00003388 ParseOpenCLKernelAttributes(DS.getAttributes());
Peter Collingbourne7ce13fc2011-02-14 01:42:53 +00003389 continue;
3390
Douglas Gregor261a89b2015-06-19 17:51:05 +00003391 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00003392 case tok::kw__Nonnull:
3393 case tok::kw__Nullable:
3394 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00003395 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3396 continue;
3397
Douglas Gregorab209d82015-07-07 03:58:42 +00003398 // Objective-C 'kindof' types.
3399 case tok::kw___kindof:
3400 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3401 nullptr, 0, AttributeList::AS_Keyword);
3402 (void)ConsumeToken();
3403 continue;
3404
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003405 // storage-class-specifier
3406 case tok::kw_typedef:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003407 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003408 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003409 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003410 break;
3411 case tok::kw_extern:
Richard Smithb4a9e862013-04-12 22:46:28 +00003412 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003413 Diag(Tok, diag::ext_thread_before) << "extern";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003414 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003415 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003416 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003417 break;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003418 case tok::kw___private_extern__:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003419 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003420 Loc, PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003421 isStorageClass = true;
Steve Naroff2050b0d2007-12-18 00:16:02 +00003422 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003423 case tok::kw_static:
Richard Smithb4a9e862013-04-12 22:46:28 +00003424 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
Chris Lattner6d29c102008-11-18 07:48:38 +00003425 Diag(Tok, diag::ext_thread_before) << "static";
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003426 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003427 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003428 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003429 break;
3430 case tok::kw_auto:
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003431 if (getLangOpts().CPlusPlus11) {
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003432 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003433 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003434 PrevSpec, DiagID, Policy);
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003435 if (!isInvalid)
Richard Smith58c74332011-09-04 19:54:14 +00003436 Diag(Tok, diag::ext_auto_storage_class)
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003437 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith58c74332011-09-04 19:54:14 +00003438 } else
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003439 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003440 DiagID, Policy);
Richard Smith58c74332011-09-04 19:54:14 +00003441 } else
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003442 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003443 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003444 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003445 break;
Richard Smithe301ba22015-11-11 02:02:15 +00003446 case tok::kw___auto_type:
3447 Diag(Tok, diag::ext_auto_type);
3448 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3449 DiagID, Policy);
3450 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003451 case tok::kw_register:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003452 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003453 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003454 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003455 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003456 case tok::kw_mutable:
Peter Collingbourne485b80f2011-10-06 03:01:00 +00003457 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003458 PrevSpec, DiagID, Policy);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003459 isStorageClass = true;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00003460 break;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003461 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00003462 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3463 PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003464 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003465 break;
3466 case tok::kw_thread_local:
3467 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3468 PrevSpec, DiagID);
Sven van Haastregtc4100832018-04-24 14:47:29 +00003469 isStorageClass = true;
Richard Smithb4a9e862013-04-12 22:46:28 +00003470 break;
3471 case tok::kw__Thread_local:
3472 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3473 Loc, PrevSpec, DiagID);
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003474 isStorageClass = true;
Chris Lattnerf63f89a2006-08-05 03:28:50 +00003475 break;
Mike Stump11289f42009-09-09 15:08:12 +00003476
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003477 // function-specifier
3478 case tok::kw_inline:
Serge Pavlov750db652013-11-13 06:57:53 +00003479 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003480 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003481 case tok::kw_virtual:
Sven van Haastregt49ffffb2018-04-23 11:23:47 +00003482 // OpenCL C++ v1.0 s2.9: the virtual function qualifier is not supported.
3483 if (getLangOpts().OpenCLCPlusPlus) {
3484 DiagID = diag::err_openclcxx_virtual_function;
3485 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3486 isInvalid = true;
3487 }
3488 else {
3489 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3490 }
Douglas Gregor61956c42008-10-31 09:07:45 +00003491 break;
Douglas Gregor61956c42008-10-31 09:07:45 +00003492 case tok::kw_explicit:
Serge Pavlov750db652013-11-13 06:57:53 +00003493 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
Douglas Gregor61956c42008-10-31 09:07:45 +00003494 break;
Richard Smith0015f092013-01-17 22:16:11 +00003495 case tok::kw__Noreturn:
3496 if (!getLangOpts().C11)
3497 Diag(Loc, diag::ext_c11_noreturn);
Serge Pavlov750db652013-11-13 06:57:53 +00003498 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
Richard Smith0015f092013-01-17 22:16:11 +00003499 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003500
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003501 // alignment-specifier
3502 case tok::kw__Alignas:
David Blaikiebbafb8a2012-03-11 07:00:24 +00003503 if (!getLangOpts().C11)
Jordan Rose58d54722012-06-30 21:33:57 +00003504 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00003505 ParseAlignmentSpecifier(DS.getAttributes());
3506 continue;
3507
Anders Carlssoncd8db412009-05-06 04:46:28 +00003508 // friend
3509 case tok::kw_friend:
Faisal Vali7db85c52017-12-31 00:06:40 +00003510 if (DSContext == DeclSpecContext::DSC_class)
John McCall07e91c02009-08-06 02:15:43 +00003511 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3512 else {
3513 PrevSpec = ""; // not actually used by the diagnostic
3514 DiagID = diag::err_friend_invalid_in_context;
3515 isInvalid = true;
3516 }
Anders Carlssoncd8db412009-05-06 04:46:28 +00003517 break;
Mike Stump11289f42009-09-09 15:08:12 +00003518
Douglas Gregor26701a42011-09-09 02:06:17 +00003519 // Modules
3520 case tok::kw___module_private__:
3521 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3522 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003523
Sebastian Redl39c2a8b2009-11-05 15:47:02 +00003524 // constexpr
3525 case tok::kw_constexpr:
3526 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3527 break;
3528
Chris Lattnere387d9e2009-01-21 19:48:37 +00003529 // type-specifier
3530 case tok::kw_short:
John McCall49bfce42009-08-03 20:12:06 +00003531 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003532 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003533 break;
3534 case tok::kw_long:
3535 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
John McCall49bfce42009-08-03 20:12:06 +00003536 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003537 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003538 else
John McCall49bfce42009-08-03 20:12:06 +00003539 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003540 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003541 break;
Francois Pichet84133e42011-04-28 01:59:37 +00003542 case tok::kw___int64:
3543 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003544 DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00003545 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003546 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00003547 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3548 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003549 break;
3550 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00003551 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3552 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003553 break;
3554 case tok::kw__Complex:
John McCall49bfce42009-08-03 20:12:06 +00003555 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3556 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003557 break;
3558 case tok::kw__Imaginary:
John McCall49bfce42009-08-03 20:12:06 +00003559 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3560 DiagID);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003561 break;
3562 case tok::kw_void:
John McCall49bfce42009-08-03 20:12:06 +00003563 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003564 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003565 break;
3566 case tok::kw_char:
John McCall49bfce42009-08-03 20:12:06 +00003567 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003568 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003569 break;
3570 case tok::kw_int:
John McCall49bfce42009-08-03 20:12:06 +00003571 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003572 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003573 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00003574 case tok::kw___int128:
3575 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003576 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003577 break;
3578 case tok::kw_half:
3579 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003580 DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00003581 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003582 case tok::kw_float:
John McCall49bfce42009-08-03 20:12:06 +00003583 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003584 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003585 break;
3586 case tok::kw_double:
John McCall49bfce42009-08-03 20:12:06 +00003587 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003588 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003589 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00003590 case tok::kw__Float16:
3591 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3592 DiagID, Policy);
3593 break;
Leonard Chanf921d852018-06-04 16:07:52 +00003594 case tok::kw__Accum:
3595 if (!getLangOpts().FixedPoint) {
Leonard Chanab80f3c2018-06-14 14:53:51 +00003596 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
Leonard Chanf921d852018-06-04 16:07:52 +00003597 } else {
3598 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3599 DiagID, Policy);
3600 }
3601 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00003602 case tok::kw__Fract:
3603 if (!getLangOpts().FixedPoint) {
3604 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3605 } else {
3606 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3607 DiagID, Policy);
3608 }
3609 break;
3610 case tok::kw__Sat:
3611 if (!getLangOpts().FixedPoint) {
3612 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3613 } else {
3614 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3615 }
3616 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003617 case tok::kw___float128:
3618 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3619 DiagID, Policy);
3620 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003621 case tok::kw_wchar_t:
John McCall49bfce42009-08-03 20:12:06 +00003622 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003623 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003624 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00003625 case tok::kw_char8_t:
3626 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3627 DiagID, Policy);
3628 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003629 case tok::kw_char16_t:
John McCall49bfce42009-08-03 20:12:06 +00003630 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003631 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003632 break;
3633 case tok::kw_char32_t:
John McCall49bfce42009-08-03 20:12:06 +00003634 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003635 DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003636 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003637 case tok::kw_bool:
3638 case tok::kw__Bool:
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003639 if (Tok.is(tok::kw_bool) &&
3640 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3641 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3642 PrevSpec = ""; // Not used by the diagnostic.
3643 DiagID = diag::err_bool_redeclaration;
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003644 // For better error recovery.
3645 Tok.setKind(tok::identifier);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003646 isInvalid = true;
3647 } else {
3648 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003649 DiagID, Policy);
Argyrios Kyrtzidis20ee5ae2010-11-16 18:18:13 +00003650 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003651 break;
3652 case tok::kw__Decimal32:
John McCall49bfce42009-08-03 20:12:06 +00003653 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003654 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003655 break;
3656 case tok::kw__Decimal64:
John McCall49bfce42009-08-03 20:12:06 +00003657 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003658 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003659 break;
3660 case tok::kw__Decimal128:
John McCall49bfce42009-08-03 20:12:06 +00003661 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003662 DiagID, Policy);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003663 break;
John Thompson22334602010-02-05 00:12:22 +00003664 case tok::kw___vector:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003665 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003666 break;
3667 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003668 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
John Thompson22334602010-02-05 00:12:22 +00003669 break;
Bill Seurercf2c96b2015-01-12 19:35:51 +00003670 case tok::kw___bool:
3671 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3672 break;
Xiuli Pan9c14e282016-01-09 12:53:17 +00003673 case tok::kw_pipe:
3674 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3675 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3676 // support the "pipe" word as identifier.
3677 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3678 goto DoneWithDeclSpec;
3679 }
3680 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3681 break;
Alexey Bader954ba212016-04-08 13:40:33 +00003682#define GENERIC_IMAGE_TYPE(ImgType, Id) \
3683 case tok::kw_##ImgType##_t: \
3684 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3685 DiagID, Policy); \
3686 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00003687#include "clang/Basic/OpenCLImageTypes.def"
John McCall39439732011-04-09 22:50:59 +00003688 case tok::kw___unknown_anytype:
Faisal Vali090da2d2018-01-01 18:23:28 +00003689 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003690 PrevSpec, DiagID, Policy);
John McCall39439732011-04-09 22:50:59 +00003691 break;
Chris Lattnere387d9e2009-01-21 19:48:37 +00003692
3693 // class-specifier:
3694 case tok::kw_class:
3695 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00003696 case tok::kw___interface:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003697 case tok::kw_union: {
3698 tok::TokenKind Kind = Tok.getKind();
3699 ConsumeToken();
Michael Han9407e502012-11-26 22:54:45 +00003700
3701 // These are attributes following class specifiers.
3702 // To produce better diagnostic, we parse them when
3703 // parsing class specifier.
Bill Wendling44426052012-12-20 19:22:21 +00003704 ParsedAttributesWithRange Attributes(AttrFactory);
Richard Smithc5b05522012-03-12 07:56:15 +00003705 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
Bill Wendling44426052012-12-20 19:22:21 +00003706 EnteringContext, DSContext, Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003707
3708 // If there are attributes following class specifier,
3709 // take them over and handle them here.
Bill Wendling44426052012-12-20 19:22:21 +00003710 if (!Attributes.empty()) {
Michael Han9407e502012-11-26 22:54:45 +00003711 AttrsLastTime = true;
Bill Wendling44426052012-12-20 19:22:21 +00003712 attrs.takeAllFrom(Attributes);
Michael Han9407e502012-11-26 22:54:45 +00003713 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003714 continue;
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003715 }
Chris Lattnere387d9e2009-01-21 19:48:37 +00003716
3717 // enum-specifier:
3718 case tok::kw_enum:
Chris Lattnerffaa0e62009-04-12 21:49:30 +00003719 ConsumeToken();
Richard Smithc5b05522012-03-12 07:56:15 +00003720 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
Chris Lattnere387d9e2009-01-21 19:48:37 +00003721 continue;
Faisal Valia534f072018-04-26 00:42:40 +00003722
Chris Lattnere387d9e2009-01-21 19:48:37 +00003723 // cv-qualifier:
3724 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00003725 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003726 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003727 break;
3728 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00003729 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003730 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003731 break;
3732 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00003733 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00003734 getLangOpts());
Chris Lattnere387d9e2009-01-21 19:48:37 +00003735 break;
3736
Douglas Gregor333489b2009-03-27 23:10:48 +00003737 // C++ typename-specifier:
3738 case tok::kw_typename:
John McCall1f476a12010-02-26 08:45:28 +00003739 if (TryAnnotateTypeOrScopeToken()) {
3740 DS.SetTypeSpecError();
3741 goto DoneWithDeclSpec;
3742 }
3743 if (!Tok.is(tok::kw_typename))
Douglas Gregor333489b2009-03-27 23:10:48 +00003744 continue;
3745 break;
3746
Chris Lattnere387d9e2009-01-21 19:48:37 +00003747 // GNU typeof support.
3748 case tok::kw_typeof:
3749 ParseTypeofSpecifier(DS);
3750 continue;
3751
David Blaikie15a430a2011-12-04 05:04:18 +00003752 case tok::annot_decltype:
Anders Carlsson74948d02009-06-24 17:47:40 +00003753 ParseDecltypeSpecifier(DS);
3754 continue;
3755
David Majnemer15b311c2016-06-14 03:20:28 +00003756 case tok::annot_pragma_pack:
3757 HandlePragmaPack();
3758 continue;
3759
3760 case tok::annot_pragma_ms_pragma:
3761 HandlePragmaMSPragma();
3762 continue;
3763
3764 case tok::annot_pragma_ms_vtordisp:
3765 HandlePragmaMSVtorDisp();
3766 continue;
3767
3768 case tok::annot_pragma_ms_pointers_to_members:
3769 HandlePragmaMSPointersToMembers();
3770 continue;
3771
Alexis Hunt4a257072011-05-19 05:37:45 +00003772 case tok::kw___underlying_type:
3773 ParseUnderlyingTypeSpecifier(DS);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003774 continue;
3775
3776 case tok::kw__Atomic:
Richard Smith8e1ac332013-03-28 01:55:44 +00003777 // C11 6.7.2.4/4:
3778 // If the _Atomic keyword is immediately followed by a left parenthesis,
3779 // it is interpreted as a type specifier (with a type name), not as a
3780 // type qualifier.
3781 if (NextToken().is(tok::l_paren)) {
3782 ParseAtomicSpecifier(DS);
3783 continue;
3784 }
3785 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3786 getLangOpts());
3787 break;
Alexis Hunt4a257072011-05-19 05:37:45 +00003788
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003789 // OpenCL access qualifiers:
3790 case tok::kw___read_only:
3791 case tok::kw___write_only:
3792 case tok::kw___read_write:
3793 // OpenCL C++ 1.0 s2.2: access qualifiers are reserved keywords.
3794 if (Actions.getLangOpts().OpenCLCPlusPlus) {
3795 DiagID = diag::err_openclcxx_reserved;
3796 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3797 isInvalid = true;
3798 }
3799 ParseOpenCLQualifiers(DS.getAttributes());
3800 break;
3801
3802 // OpenCL address space qualifiers:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003803 case tok::kw___generic:
3804 // generic address space is introduced only in OpenCL v2.0
3805 // see OpenCL C Spec v2.0 s6.5.5
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003806 if (Actions.getLangOpts().OpenCLVersion < 200 &&
3807 !Actions.getLangOpts().OpenCLCPlusPlus) {
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00003808 DiagID = diag::err_opencl_unknown_type_specifier;
3809 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3810 isInvalid = true;
3811 break;
3812 };
Galina Kistanova77674252017-06-01 21:15:34 +00003813 LLVM_FALLTHROUGH;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003814 case tok::kw___private:
3815 case tok::kw___global:
3816 case tok::kw___local:
3817 case tok::kw___constant:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00003818 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003819 break;
Chad Rosierc1183952012-06-26 22:30:43 +00003820
Steve Naroffcfdf6162008-06-05 00:02:44 +00003821 case tok::less:
Chris Lattner16fac4f2008-07-26 01:18:38 +00003822 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
Chris Lattner0974b232008-07-26 00:20:22 +00003823 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3824 // but we support it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003825 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
Chris Lattner0974b232008-07-26 00:20:22 +00003826 goto DoneWithDeclSpec;
Mike Stump11289f42009-09-09 15:08:12 +00003827
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00003828 SourceLocation StartLoc = Tok.getLocation();
3829 SourceLocation EndLoc;
3830 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3831 if (Type.isUsable()) {
3832 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3833 PrevSpec, DiagID, Type.get(),
3834 Actions.getASTContext().getPrintingPolicy()))
3835 Diag(StartLoc, DiagID) << PrevSpec;
3836
3837 DS.SetRangeEnd(EndLoc);
3838 } else {
3839 DS.SetTypeSpecError();
3840 }
Chad Rosierc1183952012-06-26 22:30:43 +00003841
Douglas Gregor06e41ae2010-10-21 23:17:00 +00003842 // Need to support trailing type qualifiers (e.g. "id<p> const").
3843 // If a type specifier follows, it will be diagnosed elsewhere.
3844 continue;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003845 }
John McCall49bfce42009-08-03 20:12:06 +00003846 // If the specifier wasn't legal, issue a diagnostic.
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003847 if (isInvalid) {
3848 assert(PrevSpec && "Method did not return previous specifier!");
John McCall49bfce42009-08-03 20:12:06 +00003849 assert(DiagID);
Chad Rosierc1183952012-06-26 22:30:43 +00003850
Douglas Gregora05f5ab2010-08-23 14:34:43 +00003851 if (DiagID == diag::ext_duplicate_declspec)
3852 Diag(Tok, DiagID)
3853 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003854 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00003855 Diag(Tok, DiagID) << getLangOpts().OpenCLCPlusPlus
3856 << getLangOpts().getOpenCLVersionTuple().getAsString()
3857 << PrevSpec << isStorageClass;
Anastasia Stulova43ab9a02016-05-12 16:28:25 +00003858 } else
Douglas Gregora05f5ab2010-08-23 14:34:43 +00003859 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerb9093cd2006-08-04 04:39:53 +00003860 }
Fariborz Jahanianbb6db562011-02-22 23:17:49 +00003861
Chris Lattner2e232092008-03-13 06:29:04 +00003862 DS.SetRangeEnd(Tok.getLocation());
Fariborz Jahanian2b059992011-04-19 21:42:37 +00003863 if (DiagID != diag::err_bool_redeclaration)
Volodymyr Sapsai9f7b5cc2018-04-10 18:29:47 +00003864 // After an error the next token can be an annotation token.
3865 ConsumeAnyToken();
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00003866
3867 AttrsLastTime = false;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00003868 }
3869}
Douglas Gregoreb31f392008-12-01 23:54:00 +00003870
Chris Lattner70ae4912007-10-29 04:42:53 +00003871/// ParseStructDeclaration - Parse a struct declaration without the terminating
3872/// semicolon.
3873///
Chris Lattner90a26b02007-01-23 04:38:16 +00003874/// struct-declaration:
Aaron Ballman606093a2017-10-15 15:01:42 +00003875/// [C2x] attributes-specifier-seq[opt]
3876/// specifier-qualifier-list struct-declarator-list
Chris Lattner736ed5d2007-06-09 05:59:07 +00003877/// [GNU] __extension__ struct-declaration
Chris Lattner70ae4912007-10-29 04:42:53 +00003878/// [GNU] specifier-qualifier-list
Chris Lattner90a26b02007-01-23 04:38:16 +00003879/// struct-declarator-list:
3880/// struct-declarator
3881/// struct-declarator-list ',' struct-declarator
3882/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3883/// struct-declarator:
3884/// declarator
3885/// [GNU] declarator attributes[opt]
3886/// declarator[opt] ':' constant-expression
3887/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3888///
Benjamin Kramera39beb92014-09-03 11:06:10 +00003889void Parser::ParseStructDeclaration(
3890 ParsingDeclSpec &DS,
3891 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
Chad Rosierc1183952012-06-26 22:30:43 +00003892
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003893 if (Tok.is(tok::kw___extension__)) {
3894 // __extension__ silences extension warnings in the subexpression.
3895 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Steve Naroff97170802007-08-20 22:28:22 +00003896 ConsumeToken();
Benjamin Kramera39beb92014-09-03 11:06:10 +00003897 return ParseStructDeclaration(DS, FieldsCallback);
Chris Lattnerf02ef3e2008-10-20 06:45:43 +00003898 }
Mike Stump11289f42009-09-09 15:08:12 +00003899
Aaron Ballman606093a2017-10-15 15:01:42 +00003900 // Parse leading attributes.
3901 ParsedAttributesWithRange Attrs(AttrFactory);
3902 MaybeParseCXX11Attributes(Attrs);
3903 DS.takeAttributesFrom(Attrs);
3904
Steve Naroff97170802007-08-20 22:28:22 +00003905 // Parse the common specifier-qualifiers-list piece.
Steve Naroff97170802007-08-20 22:28:22 +00003906 ParseSpecifierQualifierList(DS);
Mike Stump11289f42009-09-09 15:08:12 +00003907
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003908 // If there are no declarators, this is a free-standing declaration
3909 // specifier. Let the actions module cope with it.
Chris Lattner76c72282007-10-09 17:33:22 +00003910 if (Tok.is(tok::semi)) {
Nico Weber7b837f52016-01-28 19:25:00 +00003911 RecordDecl *AnonRecord = nullptr;
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003912 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
Nico Weber7b837f52016-01-28 19:25:00 +00003913 DS, AnonRecord);
3914 assert(!AnonRecord && "Did not expect anonymous struct or union here");
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003915 DS.complete(TheDecl);
Steve Naroff97170802007-08-20 22:28:22 +00003916 return;
3917 }
3918
3919 // Read struct-declarators until we find the semicolon.
John McCallcfefb6d2009-11-03 02:38:08 +00003920 bool FirstDeclarator = true;
Richard Smith8d06f422012-01-12 23:53:29 +00003921 SourceLocation CommaLoc;
Steve Naroff97170802007-08-20 22:28:22 +00003922 while (1) {
Eli Friedman89b1f2c2012-08-08 23:04:35 +00003923 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
Richard Smith8d06f422012-01-12 23:53:29 +00003924 DeclaratorInfo.D.setCommaLoc(CommaLoc);
John McCallcfefb6d2009-11-03 02:38:08 +00003925
Bill Wendling44426052012-12-20 19:22:21 +00003926 // Attributes are only allowed here on successive declarators.
John McCall53fa7142010-12-24 02:08:15 +00003927 if (!FirstDeclarator)
3928 MaybeParseGNUAttributes(DeclaratorInfo.D);
Mike Stump11289f42009-09-09 15:08:12 +00003929
Steve Naroff97170802007-08-20 22:28:22 +00003930 /// struct-declarator: declarator
3931 /// struct-declarator: declarator[opt] ':' constant-expression
Chris Lattner17c3b1f2009-12-10 01:59:24 +00003932 if (Tok.isNot(tok::colon)) {
3933 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3934 ColonProtectionRAIIObject X(*this);
Chris Lattnera12405b2008-04-10 06:46:29 +00003935 ParseDeclarator(DeclaratorInfo.D);
Richard Smith3d1a94c2014-08-12 00:22:39 +00003936 } else
3937 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003938
Alp Toker8fbec672013-12-17 23:29:36 +00003939 if (TryConsumeToken(tok::colon)) {
John McCalldadc5752010-08-24 06:29:42 +00003940 ExprResult Res(ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00003941 if (Res.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00003942 SkipUntil(tok::semi, StopBeforeMatch);
Chris Lattner32295d32008-04-10 06:15:14 +00003943 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003944 DeclaratorInfo.BitfieldSize = Res.get();
Steve Naroff97170802007-08-20 22:28:22 +00003945 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003946
Steve Naroff97170802007-08-20 22:28:22 +00003947 // If attributes exist after the declarator, parse them.
John McCall53fa7142010-12-24 02:08:15 +00003948 MaybeParseGNUAttributes(DeclaratorInfo.D);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003949
John McCallcfefb6d2009-11-03 02:38:08 +00003950 // We're done with this declarator; invoke the callback.
Benjamin Kramera39beb92014-09-03 11:06:10 +00003951 FieldsCallback(DeclaratorInfo);
John McCallcfefb6d2009-11-03 02:38:08 +00003952
Steve Naroff97170802007-08-20 22:28:22 +00003953 // If we don't have a comma, it is either the end of the list (a ';')
3954 // or an error, bail out.
Alp Toker8fbec672013-12-17 23:29:36 +00003955 if (!TryConsumeToken(tok::comma, CommaLoc))
Chris Lattner70ae4912007-10-29 04:42:53 +00003956 return;
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003957
John McCallcfefb6d2009-11-03 02:38:08 +00003958 FirstDeclarator = false;
Steve Naroff97170802007-08-20 22:28:22 +00003959 }
Steve Naroff97170802007-08-20 22:28:22 +00003960}
3961
3962/// ParseStructUnionBody
3963/// struct-contents:
3964/// struct-declaration-list
3965/// [EXT] empty
3966/// [GNU] "struct-declaration-list" without terminatoring ';'
3967/// struct-declaration-list:
3968/// struct-declaration
3969/// struct-declaration-list struct-declaration
Chris Lattner535b8302008-06-21 19:39:06 +00003970/// [OBC] '@' 'defs' '(' class-name ')'
Steve Naroff97170802007-08-20 22:28:22 +00003971///
Chris Lattner1300fb92007-01-23 23:42:53 +00003972void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
Faisal Vali090da2d2018-01-01 18:23:28 +00003973 unsigned TagType, Decl *TagDecl) {
Jordan Rose1e879d82018-03-23 00:07:18 +00003974 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003975 "parsing struct/union body");
Andy Gibbs22e140b2013-04-03 09:31:19 +00003976 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
Mike Stump11289f42009-09-09 15:08:12 +00003977
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003978 BalancedDelimiterTracker T(*this, tok::l_brace);
3979 if (T.consumeOpen())
3980 return;
Mike Stump11289f42009-09-09 15:08:12 +00003981
Douglas Gregor658b9552009-01-09 22:42:13 +00003982 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00003983 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003984
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003985 SmallVector<Decl *, 32> FieldDecls;
Chris Lattnera12405b2008-04-10 06:46:29 +00003986
Chris Lattner7b9ace62007-01-23 20:11:08 +00003987 // While we still have something to read, read the declarations in the struct.
Richard Smith752ada82015-11-17 23:32:01 +00003988 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3989 Tok.isNot(tok::eof)) {
Chris Lattner90a26b02007-01-23 04:38:16 +00003990 // Each iteration of this loop reads one struct-declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003991
Chris Lattner736ed5d2007-06-09 05:59:07 +00003992 // Check for extraneous top-level semicolon.
Chris Lattner76c72282007-10-09 17:33:22 +00003993 if (Tok.is(tok::semi)) {
Richard Smith87f5dc52012-07-23 05:45:25 +00003994 ConsumeExtraSemi(InsideStruct, TagType);
Chris Lattner36e46a22007-06-09 05:49:55 +00003995 continue;
3996 }
Chris Lattnera12405b2008-04-10 06:46:29 +00003997
Andy Gibbsc804e082013-04-03 09:46:04 +00003998 // Parse _Static_assert declaration.
3999 if (Tok.is(tok::kw__Static_assert)) {
4000 SourceLocation DeclEnd;
4001 ParseStaticAssertDeclaration(DeclEnd);
4002 continue;
4003 }
4004
Argyrios Kyrtzidis71c12fb2013-04-18 01:42:35 +00004005 if (Tok.is(tok::annot_pragma_pack)) {
4006 HandlePragmaPack();
4007 continue;
4008 }
4009
4010 if (Tok.is(tok::annot_pragma_align)) {
4011 HandlePragmaAlign();
4012 continue;
4013 }
4014
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004015 if (Tok.is(tok::annot_pragma_openmp)) {
Alexey Bataev587e1de2016-03-30 10:43:55 +00004016 // Result can be ignored, because it must be always empty.
4017 AccessSpecifier AS = AS_none;
4018 ParsedAttributesWithRange Attrs(AttrFactory);
4019 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
Alexey Bataev4652e4b2015-08-12 07:10:54 +00004020 continue;
4021 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004022
John McCallcfefb6d2009-11-03 02:38:08 +00004023 if (!Tok.is(tok::at)) {
Benjamin Kramera39beb92014-09-03 11:06:10 +00004024 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4025 // Install the declarator into the current TagDecl.
4026 Decl *Field =
4027 Actions.ActOnField(getCurScope(), TagDecl,
4028 FD.D.getDeclSpec().getSourceRange().getBegin(),
4029 FD.D, FD.BitfieldSize);
4030 FieldDecls.push_back(Field);
4031 FD.complete(Field);
4032 };
John McCallcfefb6d2009-11-03 02:38:08 +00004033
Eli Friedman89b1f2c2012-08-08 23:04:35 +00004034 // Parse all the comma separated declarators.
4035 ParsingDeclSpec DS(*this);
Benjamin Kramera39beb92014-09-03 11:06:10 +00004036 ParseStructDeclaration(DS, CFieldCallback);
Chris Lattner535b8302008-06-21 19:39:06 +00004037 } else { // Handle @defs
4038 ConsumeToken();
4039 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4040 Diag(Tok, diag::err_unexpected_at);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004041 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004042 continue;
4043 }
4044 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004045 ExpectAndConsume(tok::l_paren);
Chris Lattner535b8302008-06-21 19:39:06 +00004046 if (!Tok.is(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004047 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00004048 SkipUntil(tok::semi);
Chris Lattner535b8302008-06-21 19:39:06 +00004049 continue;
4050 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004051 SmallVector<Decl *, 16> Fields;
Douglas Gregor0be31a22010-07-02 17:43:08 +00004052 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004053 Tok.getIdentifierInfo(), Fields);
Chris Lattner535b8302008-06-21 19:39:06 +00004054 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4055 ConsumeToken();
Alp Toker383d2c42014-01-01 03:08:43 +00004056 ExpectAndConsume(tok::r_paren);
Mike Stump11289f42009-09-09 15:08:12 +00004057 }
Chris Lattner736ed5d2007-06-09 05:59:07 +00004058
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004059 if (TryConsumeToken(tok::semi))
4060 continue;
4061
4062 if (Tok.is(tok::r_brace)) {
Chris Lattner245c5332010-02-02 00:37:27 +00004063 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
Chris Lattner0c7e82d2007-06-09 05:54:40 +00004064 break;
Chris Lattner90a26b02007-01-23 04:38:16 +00004065 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004066
4067 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4068 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4069 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4070 // If we stopped at a ';', eat it.
4071 TryConsumeToken(tok::semi);
Chris Lattner90a26b02007-01-23 04:38:16 +00004072 }
Mike Stump11289f42009-09-09 15:08:12 +00004073
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004074 T.consumeClose();
Mike Stump11289f42009-09-09 15:08:12 +00004075
John McCall084e83d2011-03-24 11:26:52 +00004076 ParsedAttributes attrs(AttrFactory);
Chris Lattner90a26b02007-01-23 04:38:16 +00004077 // If attributes exist after struct contents, parse them.
John McCall53fa7142010-12-24 02:08:15 +00004078 MaybeParseGNUAttributes(attrs);
Daniel Dunbar15619c72008-10-03 02:03:53 +00004079
Douglas Gregor0be31a22010-07-02 17:43:08 +00004080 Actions.ActOnFields(getCurScope(),
David Blaikie751c5582011-09-22 02:58:26 +00004081 RecordLoc, TagDecl, FieldDecls,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004082 T.getOpenLocation(), T.getCloseLocation(),
John McCall53fa7142010-12-24 02:08:15 +00004083 attrs.getList());
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004084 StructScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004085 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
Chris Lattner90a26b02007-01-23 04:38:16 +00004086}
4087
Chris Lattner3b561a32006-08-13 00:12:11 +00004088/// ParseEnumSpecifier
Chris Lattner1890ac82006-08-13 01:16:23 +00004089/// enum-specifier: [C99 6.7.2.2]
Chris Lattner3b561a32006-08-13 00:12:11 +00004090/// 'enum' identifier[opt] '{' enumerator-list '}'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004091///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
Chris Lattnere37e2332006-08-15 04:50:22 +00004092/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4093/// '}' attributes[opt]
Aaron Ballman9ecff022012-03-01 04:09:28 +00004094/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4095/// '}'
Chris Lattner3b561a32006-08-13 00:12:11 +00004096/// 'enum' identifier
Chris Lattnere37e2332006-08-15 04:50:22 +00004097/// [GNU] 'enum' attributes[opt] identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004098///
Richard Smith7d137e32012-03-23 03:33:32 +00004099/// [C++11] enum-head '{' enumerator-list[opt] '}'
4100/// [C++11] enum-head '{' enumerator-list ',' '}'
Douglas Gregor0bf31402010-10-08 23:50:27 +00004101///
Richard Smith7d137e32012-03-23 03:33:32 +00004102/// enum-head: [C++11]
4103/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4104/// enum-key attribute-specifier-seq[opt] nested-name-specifier
4105/// identifier enum-base[opt]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004106///
Richard Smith7d137e32012-03-23 03:33:32 +00004107/// enum-key: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004108/// 'enum'
4109/// 'enum' 'class'
4110/// 'enum' 'struct'
4111///
Richard Smith7d137e32012-03-23 03:33:32 +00004112/// enum-base: [C++11]
Douglas Gregor0bf31402010-10-08 23:50:27 +00004113/// ':' type-specifier-seq
4114///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004115/// [C++] elaborated-type-specifier:
4116/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4117///
Chris Lattnerffaa0e62009-04-12 21:49:30 +00004118void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
Douglas Gregordc70c3a2010-03-02 17:53:14 +00004119 const ParsedTemplateInfo &TemplateInfo,
Richard Smithc5b05522012-03-12 07:56:15 +00004120 AccessSpecifier AS, DeclSpecContext DSC) {
Chris Lattnerffbc2712007-01-25 06:05:38 +00004121 // Parse the tag portion of this.
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004122 if (Tok.is(tok::code_completion)) {
4123 // Code completion for an enum name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004124 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00004125 return cutOffParsing();
Douglas Gregorf45b0cf2009-09-18 15:37:17 +00004126 }
John McCallcb432fa2011-07-06 05:58:41 +00004127
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004128 // If attributes exist after tag, parse them.
4129 ParsedAttributesWithRange attrs(AttrFactory);
4130 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004131 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004132 MaybeParseMicrosoftDeclSpecs(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004133
Richard Smith0f8ee222012-01-10 01:33:14 +00004134 SourceLocation ScopedEnumKWLoc;
John McCallcb432fa2011-07-06 05:58:41 +00004135 bool IsScopedUsingClassTag = false;
4136
John McCallbeae29a2012-06-23 22:30:04 +00004137 // In C++11, recognize 'enum class' and 'enum struct'.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00004138 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
Richard Trieud0d87b52013-04-23 02:47:36 +00004139 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4140 : diag::ext_scoped_enum);
John McCallcb432fa2011-07-06 05:58:41 +00004141 IsScopedUsingClassTag = Tok.is(tok::kw_class);
Richard Smith0f8ee222012-01-10 01:33:14 +00004142 ScopedEnumKWLoc = ConsumeToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004143
Bill Wendling44426052012-12-20 19:22:21 +00004144 // Attributes are not allowed between these keywords. Diagnose,
John McCallbeae29a2012-06-23 22:30:04 +00004145 // but then just treat them like they appeared in the right place.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004146 ProhibitAttributes(attrs);
John McCallbeae29a2012-06-23 22:30:04 +00004147
4148 // They are allowed afterwards, though.
4149 MaybeParseGNUAttributes(attrs);
Richard Smith89645bc2013-01-02 12:01:23 +00004150 MaybeParseCXX11Attributes(attrs);
Aaron Ballman068aa512015-05-20 20:58:33 +00004151 MaybeParseMicrosoftDeclSpecs(attrs);
John McCallcb432fa2011-07-06 05:58:41 +00004152 }
Richard Smith7d137e32012-03-23 03:33:32 +00004153
John McCall6347b682012-05-07 06:16:58 +00004154 // C++11 [temp.explicit]p12:
4155 // The usual access controls do not apply to names used to specify
4156 // explicit instantiations.
4157 // We extend this to also cover explicit specializations. Note that
4158 // we don't suppress if this turns out to be an elaborated type
4159 // specifier.
4160 bool shouldDelayDiagsInTag =
4161 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4162 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4163 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
Richard Smith7d137e32012-03-23 03:33:32 +00004164
Richard Smithbfdb1082012-03-12 08:56:40 +00004165 // Enum definitions should not be parsed in a trailing-return-type.
Faisal Vali7db85c52017-12-31 00:06:40 +00004166 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
Richard Smithbfdb1082012-03-12 08:56:40 +00004167
4168 bool AllowFixedUnderlyingType = AllowDeclaration &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004169 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
Richard Smithbfdb1082012-03-12 08:56:40 +00004170 getLangOpts().ObjC2);
John McCallcb432fa2011-07-06 05:58:41 +00004171
Abramo Bagnarad7548482010-05-19 21:37:53 +00004172 CXXScopeSpec &SS = DS.getTypeSpecScope();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004173 if (getLangOpts().CPlusPlus) {
John McCallcb432fa2011-07-06 05:58:41 +00004174 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4175 // if a fixed underlying type is allowed.
4176 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
Chad Rosierc1183952012-06-26 22:30:43 +00004177
Nico Webercfaa4cd2015-02-15 07:26:13 +00004178 CXXScopeSpec Spec;
David Blaikieefdccaa2016-01-15 23:43:34 +00004179 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
Richard Smith1d4b2e12013-04-01 21:43:41 +00004180 /*EnteringContext=*/true))
John McCall1f476a12010-02-26 08:45:28 +00004181 return;
4182
Nico Webercfaa4cd2015-02-15 07:26:13 +00004183 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00004184 Diag(Tok, diag::err_expected) << tok::identifier;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004185 if (Tok.isNot(tok::l_brace)) {
4186 // Has no name and is not a definition.
4187 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004188 SkipUntil(tok::comma, StopAtSemi);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004189 return;
4190 }
4191 }
Nico Webercfaa4cd2015-02-15 07:26:13 +00004192
4193 SS = Spec;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004194 }
Mike Stump11289f42009-09-09 15:08:12 +00004195
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004196 // Must have either 'enum name' or 'enum {...}'.
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004197 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
Richard Smithbfdb1082012-03-12 08:56:40 +00004198 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
Alp Tokerec543272013-12-24 09:48:30 +00004199 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
Mike Stump11289f42009-09-09 15:08:12 +00004200
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004201 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004202 SkipUntil(tok::comma, StopAtSemi);
Chris Lattner3b561a32006-08-13 00:12:11 +00004203 return;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004204 }
Mike Stump11289f42009-09-09 15:08:12 +00004205
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004206 // If an identifier is present, consume and remember it.
Craig Topper161e4db2014-05-21 06:02:52 +00004207 IdentifierInfo *Name = nullptr;
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004208 SourceLocation NameLoc;
4209 if (Tok.is(tok::identifier)) {
4210 Name = Tok.getIdentifierInfo();
4211 NameLoc = ConsumeToken();
4212 }
Mike Stump11289f42009-09-09 15:08:12 +00004213
Richard Smith0f8ee222012-01-10 01:33:14 +00004214 if (!Name && ScopedEnumKWLoc.isValid()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00004215 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4216 // declaration of a scoped enumeration.
4217 Diag(Tok, diag::err_scoped_enum_missing_identifier);
Richard Smith0f8ee222012-01-10 01:33:14 +00004218 ScopedEnumKWLoc = SourceLocation();
Abramo Bagnara0e05e242010-12-03 18:54:17 +00004219 IsScopedUsingClassTag = false;
Douglas Gregor0bf31402010-10-08 23:50:27 +00004220 }
4221
John McCall6347b682012-05-07 06:16:58 +00004222 // Okay, end the suppression area. We'll decide whether to emit the
4223 // diagnostics in a second.
4224 if (shouldDelayDiagsInTag)
4225 diagsFromTag.done();
Richard Smith7d137e32012-03-23 03:33:32 +00004226
Douglas Gregor0bf31402010-10-08 23:50:27 +00004227 TypeResult BaseType;
4228
Douglas Gregord1f69f62010-12-01 17:42:47 +00004229 // Parse the fixed underlying type.
Richard Smith200f47c2012-07-02 19:14:01 +00004230 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004231 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004232 bool PossibleBitfield = false;
Richard Smith200f47c2012-07-02 19:14:01 +00004233 if (CanBeBitfield) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004234 // If we're in class scope, this can either be an enum declaration with
4235 // an underlying type, or a declaration of a bitfield member. We try to
4236 // use a simple disambiguation scheme first to catch the common cases
Chad Rosierc1183952012-06-26 22:30:43 +00004237 // (integer literal, sizeof); if it's still ambiguous, we then consider
4238 // anything that's a simple-type-specifier followed by '(' as an
4239 // expression. This suffices because function types are not valid
Douglas Gregord1f69f62010-12-01 17:42:47 +00004240 // underlying types anyway.
Faisal Valid143a0c2017-04-01 21:30:49 +00004241 EnterExpressionEvaluationContext Unevaluated(
4242 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Douglas Gregord1f69f62010-12-01 17:42:47 +00004243 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
Chad Rosierc1183952012-06-26 22:30:43 +00004244 // If the next token starts an expression, we know we're parsing a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004245 // bit-field. This is the common case.
Richard Smithee390432014-05-16 01:56:53 +00004246 if (TPR == TPResult::True)
Douglas Gregord1f69f62010-12-01 17:42:47 +00004247 PossibleBitfield = true;
4248 // If the next token starts a type-specifier-seq, it may be either a
4249 // a fixed underlying type or the start of a function-style cast in C++;
Chad Rosierc1183952012-06-26 22:30:43 +00004250 // lookahead one more token to see if it's obvious that we have a
Douglas Gregord1f69f62010-12-01 17:42:47 +00004251 // fixed underlying type.
Richard Smithee390432014-05-16 01:56:53 +00004252 else if (TPR == TPResult::False &&
Douglas Gregord1f69f62010-12-01 17:42:47 +00004253 GetLookAheadToken(2).getKind() == tok::semi) {
4254 // Consume the ':'.
4255 ConsumeToken();
4256 } else {
4257 // We have the start of a type-specifier-seq, so we have to perform
4258 // tentative parsing to determine whether we have an expression or a
4259 // type.
4260 TentativeParsingAction TPA(*this);
4261
4262 // Consume the ':'.
4263 ConsumeToken();
Richard Smith1e3b0f02012-02-23 01:36:12 +00004264
4265 // If we see a type specifier followed by an open-brace, we have an
4266 // ambiguity between an underlying type and a C++11 braced
4267 // function-style cast. Resolve this by always treating it as an
4268 // underlying type.
4269 // FIXME: The standard is not entirely clear on how to disambiguate in
4270 // this case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004271 if ((getLangOpts().CPlusPlus &&
Richard Smithee390432014-05-16 01:56:53 +00004272 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00004273 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
Douglas Gregord1f69f62010-12-01 17:42:47 +00004274 // We'll parse this as a bitfield later.
4275 PossibleBitfield = true;
4276 TPA.Revert();
4277 } else {
4278 // We have a type-specifier-seq.
4279 TPA.Commit();
4280 }
4281 }
4282 } else {
4283 // Consume the ':'.
4284 ConsumeToken();
4285 }
4286
4287 if (!PossibleBitfield) {
4288 SourceRange Range;
4289 BaseType = ParseTypeName(&Range);
Chad Rosierc1183952012-06-26 22:30:43 +00004290
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004291 if (getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00004292 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
Eli Friedman0d0355ab2012-11-02 01:34:28 +00004293 } else if (!getLangOpts().ObjC2) {
4294 if (getLangOpts().CPlusPlus)
4295 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
4296 else
4297 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
4298 }
Douglas Gregord1f69f62010-12-01 17:42:47 +00004299 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004300 }
4301
Richard Smith0f8ee222012-01-10 01:33:14 +00004302 // There are four options here. If we have 'friend enum foo;' then this is a
4303 // friend declaration, and cannot have an accompanying definition. If we have
4304 // 'enum foo;', then this is a forward declaration. If we have
4305 // 'enum foo {...' then this is a definition. Otherwise we have something
4306 // like 'enum foo xyz', a reference.
Argyrios Kyrtzidisf01fa822008-09-11 00:21:41 +00004307 //
4308 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4309 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4310 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4311 //
John McCallfaf5fb42010-08-26 23:41:50 +00004312 Sema::TagUseKind TUK;
John McCall6347b682012-05-07 06:16:58 +00004313 if (!AllowDeclaration) {
Richard Smithbfdb1082012-03-12 08:56:40 +00004314 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004315 } else if (Tok.is(tok::l_brace)) {
4316 if (DS.isFriendSpecified()) {
4317 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4318 << SourceRange(DS.getFriendSpecLoc());
4319 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004320 SkipUntil(tok::r_brace, StopAtSemi);
John McCall6347b682012-05-07 06:16:58 +00004321 TUK = Sema::TUK_Friend;
4322 } else {
4323 TUK = Sema::TUK_Definition;
4324 }
Richard Smith649c7b062014-01-08 00:56:48 +00004325 } else if (!isTypeSpecifier(DSC) &&
Richard Smith369b9f92012-06-25 21:37:02 +00004326 (Tok.is(tok::semi) ||
Richard Smith200f47c2012-07-02 19:14:01 +00004327 (Tok.isAtStartOfLine() &&
4328 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
Richard Smith369b9f92012-06-25 21:37:02 +00004329 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4330 if (Tok.isNot(tok::semi)) {
4331 // A semicolon was missing after this declaration. Diagnose and recover.
Alp Toker383d2c42014-01-01 03:08:43 +00004332 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004333 PP.EnterToken(Tok);
4334 Tok.setKind(tok::semi);
4335 }
John McCall6347b682012-05-07 06:16:58 +00004336 } else {
John McCallfaf5fb42010-08-26 23:41:50 +00004337 TUK = Sema::TUK_Reference;
John McCall6347b682012-05-07 06:16:58 +00004338 }
4339
4340 // If this is an elaborated type specifier, and we delayed
4341 // diagnostics before, just merge them into the current pool.
4342 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4343 diagsFromTag.redelay();
4344 }
Richard Smith7d137e32012-03-23 03:33:32 +00004345
4346 MultiTemplateParamsArg TParams;
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004347 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
John McCallfaf5fb42010-08-26 23:41:50 +00004348 TUK != Sema::TUK_Reference) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004349 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
Richard Smith7d137e32012-03-23 03:33:32 +00004350 // Skip the rest of this declarator, up until the comma or semicolon.
4351 Diag(Tok, diag::err_enum_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +00004352 SkipUntil(tok::comma, StopAtSemi);
Richard Smith7d137e32012-03-23 03:33:32 +00004353 return;
4354 }
4355
4356 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4357 // Enumerations can't be explicitly instantiated.
4358 DS.SetTypeSpecError();
4359 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4360 return;
4361 }
4362
4363 assert(TemplateInfo.TemplateParams && "no template parameters");
4364 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4365 TemplateInfo.TemplateParams->size());
Douglas Gregorcbbf3e32010-05-03 17:48:54 +00004366 }
Chad Rosierc1183952012-06-26 22:30:43 +00004367
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004368 if (TUK == Sema::TUK_Reference)
4369 ProhibitAttributes(attrs);
Richard Smith7d137e32012-03-23 03:33:32 +00004370
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004371 if (!Name && TUK != Sema::TUK_Definition) {
4372 Diag(Tok, diag::err_enumerator_unnamed_no_def);
Richard Smith7d137e32012-03-23 03:33:32 +00004373
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004374 // Skip the rest of this declarator, up until the comma or semicolon.
Alexey Bataevee6507d2013-11-18 08:17:37 +00004375 SkipUntil(tok::comma, StopAtSemi);
Douglas Gregor6cd5ae42011-02-22 02:55:24 +00004376 return;
4377 }
Richard Smith7d137e32012-03-23 03:33:32 +00004378
Nico Weber32a0fc72016-09-03 03:01:32 +00004379 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
David Majnemer936b4112015-04-19 07:53:29 +00004380
Richard Smithd9ba2242015-05-07 03:54:19 +00004381 Sema::SkipBodyInfo SkipBody;
4382 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4383 NextToken().is(tok::identifier))
4384 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4385 NextToken().getIdentifierInfo(),
4386 NextToken().getLocation());
4387
Douglas Gregord6ab8742009-05-28 23:31:59 +00004388 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004389 bool IsDependent = false;
Craig Topper161e4db2014-05-21 06:02:52 +00004390 const char *PrevSpec = nullptr;
Douglas Gregorba41d012010-04-24 16:38:41 +00004391 unsigned DiagID;
Faisal Vali7db85c52017-12-31 00:06:40 +00004392 Decl *TagDecl = Actions.ActOnTag(
4393 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4394 attrs.getList(), AS, DS.getModulePrivateSpecLoc(), TParams, Owned,
4395 IsDependent, ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4396 DSC == DeclSpecContext::DSC_type_specifier,
4397 DSC == DeclSpecContext::DSC_template_param ||
4398 DSC == DeclSpecContext::DSC_template_type_arg,
4399 &SkipBody);
Richard Smithd9ba2242015-05-07 03:54:19 +00004400
4401 if (SkipBody.ShouldSkip) {
4402 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4403
4404 BalancedDelimiterTracker T(*this, tok::l_brace);
4405 T.consumeOpen();
4406 T.skipToEnd();
4407
4408 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4409 NameLoc.isValid() ? NameLoc : StartLoc,
4410 PrevSpec, DiagID, TagDecl, Owned,
4411 Actions.getASTContext().getPrintingPolicy()))
4412 Diag(StartLoc, DiagID) << PrevSpec;
4413 return;
4414 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00004415
Douglas Gregorba41d012010-04-24 16:38:41 +00004416 if (IsDependent) {
Chad Rosierc1183952012-06-26 22:30:43 +00004417 // This enum has a dependent nested-name-specifier. Handle it as a
Douglas Gregorba41d012010-04-24 16:38:41 +00004418 // dependent tag.
4419 if (!Name) {
4420 DS.SetTypeSpecError();
4421 Diag(Tok, diag::err_expected_type_name_after_typename);
4422 return;
4423 }
Chad Rosierc1183952012-06-26 22:30:43 +00004424
Nico Weber83ea0122014-05-03 21:57:40 +00004425 TypeResult Type = Actions.ActOnDependentTag(
4426 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
Douglas Gregorba41d012010-04-24 16:38:41 +00004427 if (Type.isInvalid()) {
4428 DS.SetTypeSpecError();
4429 return;
4430 }
Chad Rosierc1183952012-06-26 22:30:43 +00004431
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004432 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4433 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004434 PrevSpec, DiagID, Type.get(),
4435 Actions.getASTContext().getPrintingPolicy()))
Douglas Gregorba41d012010-04-24 16:38:41 +00004436 Diag(StartLoc, DiagID) << PrevSpec;
Chad Rosierc1183952012-06-26 22:30:43 +00004437
Douglas Gregorba41d012010-04-24 16:38:41 +00004438 return;
4439 }
Mike Stump11289f42009-09-09 15:08:12 +00004440
John McCall48871652010-08-21 09:40:31 +00004441 if (!TagDecl) {
Chad Rosierc1183952012-06-26 22:30:43 +00004442 // The action failed to produce an enumeration tag. If this is a
Douglas Gregorba41d012010-04-24 16:38:41 +00004443 // definition, consume the entire definition.
Richard Smithbfdb1082012-03-12 08:56:40 +00004444 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
Douglas Gregorba41d012010-04-24 16:38:41 +00004445 ConsumeBrace();
Alexey Bataevee6507d2013-11-18 08:17:37 +00004446 SkipUntil(tok::r_brace, StopAtSemi);
Douglas Gregorba41d012010-04-24 16:38:41 +00004447 }
Chad Rosierc1183952012-06-26 22:30:43 +00004448
Douglas Gregorba41d012010-04-24 16:38:41 +00004449 DS.SetTypeSpecError();
4450 return;
4451 }
Richard Smith0f8ee222012-01-10 01:33:14 +00004452
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004453 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4454 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4455 ParseEnumBody(StartLoc, D);
4456 if (SkipBody.CheckSameAsPrevious &&
4457 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4458 DS.SetTypeSpecError();
4459 return;
4460 }
4461 }
Mike Stump11289f42009-09-09 15:08:12 +00004462
Abramo Bagnara9875a3c2011-03-16 20:16:18 +00004463 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4464 NameLoc.isValid() ? NameLoc : StartLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00004465 PrevSpec, DiagID, TagDecl, Owned,
4466 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00004467 Diag(StartLoc, DiagID) << PrevSpec;
Chris Lattner3b561a32006-08-13 00:12:11 +00004468}
4469
Chris Lattnerc1915e22007-01-25 07:29:02 +00004470/// ParseEnumBody - Parse a {} enclosed enumerator-list.
4471/// enumerator-list:
4472/// enumerator
4473/// enumerator-list ',' enumerator
4474/// enumerator:
Aaron Ballman730476b2014-11-08 15:33:35 +00004475/// enumeration-constant attributes[opt]
4476/// enumeration-constant attributes[opt] '=' constant-expression
Chris Lattnerc1915e22007-01-25 07:29:02 +00004477/// enumeration-constant:
4478/// identifier
4479///
John McCall48871652010-08-21 09:40:31 +00004480void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004481 // Enter the scope of the enum body and start the definition.
Hans Wennborgfe781452014-06-17 00:00:18 +00004482 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
Douglas Gregor0be31a22010-07-02 17:43:08 +00004483 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
Douglas Gregor07665a62009-01-05 19:45:36 +00004484
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004485 BalancedDelimiterTracker T(*this, tok::l_brace);
4486 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00004487
Chris Lattner37256fb2007-08-27 17:24:30 +00004488 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
David Blaikiebbafb8a2012-03-11 07:00:24 +00004489 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
Richard Smithf8812672016-12-02 22:38:31 +00004490 Diag(Tok, diag::err_empty_enum);
Mike Stump11289f42009-09-09 15:08:12 +00004491
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004492 SmallVector<Decl *, 32> EnumConstantDecls;
Jordan Rose60ac3162015-04-30 17:20:30 +00004493 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
Chris Lattnerc1915e22007-01-25 07:29:02 +00004494
Craig Topper161e4db2014-05-21 06:02:52 +00004495 Decl *LastEnumConstDecl = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004496
Chris Lattnerc1915e22007-01-25 07:29:02 +00004497 // Parse the enumerator-list.
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004498 while (Tok.isNot(tok::r_brace)) {
4499 // Parse enumerator. If failed, try skipping till the start of the next
4500 // enumerator definition.
4501 if (Tok.isNot(tok::identifier)) {
4502 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4503 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4504 TryConsumeToken(tok::comma))
4505 continue;
4506 break;
4507 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004508 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4509 SourceLocation IdentLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00004510
John McCall811a0f52010-10-22 23:36:17 +00004511 // If attributes exist after the enumerator, parse them.
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00004512 ParsedAttributesWithRange attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004513 MaybeParseGNUAttributes(attrs);
Aaron Ballman730476b2014-11-08 15:33:35 +00004514 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
Aaron Ballman606093a2017-10-15 15:01:42 +00004515 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4516 if (getLangOpts().CPlusPlus)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004517 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
Aaron Ballman606093a2017-10-15 15:01:42 +00004518 ? diag::warn_cxx14_compat_ns_enum_attribute
4519 : diag::ext_ns_enum_attribute)
4520 << 1 /*enumerator*/;
Aaron Ballman730476b2014-11-08 15:33:35 +00004521 ParseCXX11Attributes(attrs);
4522 }
John McCall811a0f52010-10-22 23:36:17 +00004523
Chris Lattnerc1915e22007-01-25 07:29:02 +00004524 SourceLocation EqualLoc;
John McCalldadc5752010-08-24 06:29:42 +00004525 ExprResult AssignedVal;
Jordan Rose60ac3162015-04-30 17:20:30 +00004526 EnumAvailabilityDiags.emplace_back(*this);
Chad Rosierc1183952012-06-26 22:30:43 +00004527
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004528 if (TryConsumeToken(tok::equal, EqualLoc)) {
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00004529 AssignedVal = ParseConstantExpression();
4530 if (AssignedVal.isInvalid())
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004531 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
Chris Lattnerc1915e22007-01-25 07:29:02 +00004532 }
Mike Stump11289f42009-09-09 15:08:12 +00004533
Chris Lattnerc1915e22007-01-25 07:29:02 +00004534 // Install the enumerator constant into EnumDecl.
Bruno Cardoso Lopesdf0ee342017-07-01 00:06:47 +00004535 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4536 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident,
4537 attrs.getList(), EqualLoc, AssignedVal.get());
Jordan Rose60ac3162015-04-30 17:20:30 +00004538 EnumAvailabilityDiags.back().done();
Chad Rosierc1183952012-06-26 22:30:43 +00004539
Chris Lattner4ef40012007-06-11 01:28:17 +00004540 EnumConstantDecls.push_back(EnumConstDecl);
4541 LastEnumConstDecl = EnumConstDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004542
Douglas Gregorce66d022010-09-07 14:51:08 +00004543 if (Tok.is(tok::identifier)) {
4544 // We're missing a comma between enumerators.
Richard Smithbdb84f32016-07-22 23:36:59 +00004545 SourceLocation Loc = getEndOfPreviousToken();
Chad Rosierc1183952012-06-26 22:30:43 +00004546 Diag(Loc, diag::err_enumerator_list_missing_comma)
Douglas Gregorce66d022010-09-07 14:51:08 +00004547 << FixItHint::CreateInsertion(Loc, ", ");
4548 continue;
4549 }
Chad Rosierc1183952012-06-26 22:30:43 +00004550
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004551 // Emumerator definition must be finished, only comma or r_brace are
4552 // allowed here.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00004553 SourceLocation CommaLoc;
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004554 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4555 if (EqualLoc.isValid())
4556 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4557 << tok::comma;
4558 else
4559 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4560 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4561 if (TryConsumeToken(tok::comma, CommaLoc))
4562 continue;
4563 } else {
4564 break;
4565 }
4566 }
Mike Stump11289f42009-09-09 15:08:12 +00004567
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004568 // If comma is followed by r_brace, emit appropriate warning.
4569 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004570 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
Richard Smith87f5dc52012-07-23 05:45:25 +00004571 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4572 diag::ext_enumerator_list_comma_cxx :
4573 diag::ext_enumerator_list_comma_c)
Richard Smith5d164bc2011-10-15 05:09:34 +00004574 << FixItHint::CreateRemoval(CommaLoc);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004575 else if (getLangOpts().CPlusPlus11)
Richard Smith5d164bc2011-10-15 05:09:34 +00004576 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4577 << FixItHint::CreateRemoval(CommaLoc);
Serge Pavlov2e3ecb62013-12-31 06:26:03 +00004578 break;
Richard Smith5d164bc2011-10-15 05:09:34 +00004579 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004580 }
Mike Stump11289f42009-09-09 15:08:12 +00004581
Chris Lattnerc1915e22007-01-25 07:29:02 +00004582 // Eat the }.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004583 T.consumeClose();
Chris Lattnerc1915e22007-01-25 07:29:02 +00004584
Chris Lattnerc1915e22007-01-25 07:29:02 +00004585 // If attributes exist after the identifier list, parse them.
John McCall084e83d2011-03-24 11:26:52 +00004586 ParsedAttributes attrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +00004587 MaybeParseGNUAttributes(attrs);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004588
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004589 Actions.ActOnEnumBody(StartLoc, T.getRange(),
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +00004590 EnumDecl, EnumConstantDecls,
4591 getCurScope(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00004592 attrs.getList());
Mike Stump11289f42009-09-09 15:08:12 +00004593
Jordan Rose60ac3162015-04-30 17:20:30 +00004594 // Now handle enum constant availability diagnostics.
4595 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4596 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4597 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4598 EnumAvailabilityDiags[i].redelay();
4599 PD.complete(EnumConstantDecls[i]);
4600 }
4601
Douglas Gregor82ac25e2009-01-08 20:45:30 +00004602 EnumScope.Exit();
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004603 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
Richard Smith369b9f92012-06-25 21:37:02 +00004604
4605 // The next token must be valid after an enum definition. If not, a ';'
4606 // was probably forgotten.
Richard Smith200f47c2012-07-02 19:14:01 +00004607 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4608 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
Alp Toker383d2c42014-01-01 03:08:43 +00004609 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
Richard Smith369b9f92012-06-25 21:37:02 +00004610 // Push this token back into the preprocessor and change our current token
4611 // to ';' so that the rest of the code recovers as though there were an
4612 // ';' after the definition.
4613 PP.EnterToken(Tok);
4614 Tok.setKind(tok::semi);
4615 }
Chris Lattnerc1915e22007-01-25 07:29:02 +00004616}
Chris Lattner3b561a32006-08-13 00:12:11 +00004617
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004618/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4619/// is definitely a type-specifier. Return false if it isn't part of a type
4620/// specifier or if we're not sure.
4621bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4622 switch (Tok.getKind()) {
4623 default: return false;
4624 // type-specifiers
4625 case tok::kw_short:
4626 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004627 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004628 case tok::kw___int128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004629 case tok::kw_signed:
4630 case tok::kw_unsigned:
4631 case tok::kw__Complex:
4632 case tok::kw__Imaginary:
4633 case tok::kw_void:
4634 case tok::kw_char:
4635 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004636 case tok::kw_char8_t:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004637 case tok::kw_char16_t:
4638 case tok::kw_char32_t:
4639 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004640 case tok::kw_half:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004641 case tok::kw_float:
4642 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004643 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004644 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004645 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004646 case tok::kw___float128:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004647 case tok::kw_bool:
4648 case tok::kw__Bool:
4649 case tok::kw__Decimal32:
4650 case tok::kw__Decimal64:
4651 case tok::kw__Decimal128:
4652 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004653#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004654#include "clang/Basic/OpenCLImageTypes.def"
Chad Rosierc1183952012-06-26 22:30:43 +00004655
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004656 // struct-or-union-specifier (C99) or class-specifier (C++)
4657 case tok::kw_class:
4658 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004659 case tok::kw___interface:
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004660 case tok::kw_union:
4661 // enum-specifier
4662 case tok::kw_enum:
Chad Rosierc1183952012-06-26 22:30:43 +00004663
Chris Lattnerfd48afe2010-02-28 18:18:36 +00004664 // typedef-name
4665 case tok::annot_typename:
4666 return true;
4667 }
4668}
4669
Steve Naroff69e8f9e2008-02-11 23:15:56 +00004670/// isTypeSpecifierQualifier - Return true if the current token could be the
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004671/// start of a specifier-qualifier-list.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004672bool Parser::isTypeSpecifierQualifier() {
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004673 switch (Tok.getKind()) {
4674 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004675
Chris Lattner020bab92009-01-04 23:41:41 +00004676 case tok::identifier: // foo::bar
John Thompson22334602010-02-05 00:12:22 +00004677 if (TryAltiVecVectorToken())
4678 return true;
4679 // Fall through.
Douglas Gregor333489b2009-03-27 23:10:48 +00004680 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004681 // Annotate typenames and C++ scope specifiers. If we get one, just
4682 // recurse to handle whatever we get.
4683 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004684 return true;
4685 if (Tok.is(tok::identifier))
4686 return false;
4687 return isTypeSpecifierQualifier();
Douglas Gregor333489b2009-03-27 23:10:48 +00004688
Chris Lattner020bab92009-01-04 23:41:41 +00004689 case tok::coloncolon: // ::foo::bar
4690 if (NextToken().is(tok::kw_new) || // ::new
4691 NextToken().is(tok::kw_delete)) // ::delete
4692 return false;
4693
Chris Lattner020bab92009-01-04 23:41:41 +00004694 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004695 return true;
4696 return isTypeSpecifierQualifier();
Mike Stump11289f42009-09-09 15:08:12 +00004697
Chris Lattnere37e2332006-08-15 04:50:22 +00004698 // GNU attributes support.
4699 case tok::kw___attribute:
Steve Naroffad373bd2007-07-31 12:34:36 +00004700 // GNU typeof support.
4701 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004702
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004703 // type-specifiers
4704 case tok::kw_short:
4705 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004706 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004707 case tok::kw___int128:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004708 case tok::kw_signed:
4709 case tok::kw_unsigned:
4710 case tok::kw__Complex:
4711 case tok::kw__Imaginary:
4712 case tok::kw_void:
4713 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004714 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004715 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004716 case tok::kw_char16_t:
4717 case tok::kw_char32_t:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004718 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004719 case tok::kw_half:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004720 case tok::kw_float:
4721 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004722 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004723 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004724 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004725 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004726 case tok::kw_bool:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004727 case tok::kw__Bool:
4728 case tok::kw__Decimal32:
4729 case tok::kw__Decimal64:
4730 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004731 case tok::kw___vector:
Alexey Bader954ba212016-04-08 13:40:33 +00004732#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004733#include "clang/Basic/OpenCLImageTypes.def"
Mike Stump11289f42009-09-09 15:08:12 +00004734
Chris Lattner861a2262008-04-13 18:59:07 +00004735 // struct-or-union-specifier (C99) or class-specifier (C++)
4736 case tok::kw_class:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004737 case tok::kw_struct:
Joao Matosdc86f942012-08-31 18:45:21 +00004738 case tok::kw___interface:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004739 case tok::kw_union:
4740 // enum-specifier
4741 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004742
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004743 // type-qualifier
4744 case tok::kw_const:
4745 case tok::kw_volatile:
4746 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004747 case tok::kw__Sat:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004748
John McCallea0a39e2012-11-14 00:49:39 +00004749 // Debugger support.
4750 case tok::kw___unknown_anytype:
4751
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00004752 // typedef-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00004753 case tok::annot_typename:
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004754 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004755
Chris Lattner409bf7d2008-10-20 00:25:30 +00004756 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4757 case tok::less:
David Blaikiebbafb8a2012-03-11 07:00:24 +00004758 return getLangOpts().ObjC1;
Mike Stump11289f42009-09-09 15:08:12 +00004759
Steve Naroff44ac7772008-12-25 14:16:32 +00004760 case tok::kw___cdecl:
4761 case tok::kw___stdcall:
4762 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004763 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004764 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004765 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004766 case tok::kw___w64:
4767 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004768 case tok::kw___ptr32:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004769 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004770 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004771
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004772 case tok::kw__Nonnull:
4773 case tok::kw__Nullable:
4774 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004775
Douglas Gregorab209d82015-07-07 03:58:42 +00004776 case tok::kw___kindof:
4777
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004778 case tok::kw___private:
4779 case tok::kw___local:
4780 case tok::kw___global:
4781 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004782 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004783 case tok::kw___read_only:
4784 case tok::kw___read_write:
4785 case tok::kw___write_only:
4786
Eli Friedman53339e02009-06-08 23:27:34 +00004787 return true;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004788
Richard Smith8e1ac332013-03-28 01:55:44 +00004789 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004790 case tok::kw__Atomic:
4791 return true;
Chris Lattnerf5fbd792006-08-10 23:56:11 +00004792 }
4793}
4794
Chris Lattneracd58a32006-08-06 17:24:14 +00004795/// isDeclarationSpecifier() - Return true if the current token is part of a
4796/// declaration specifier.
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004797///
4798/// \param DisambiguatingWithExpression True to indicate that the purpose of
4799/// this check is to disambiguate between an expression and a declaration.
4800bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
Chris Lattneracd58a32006-08-06 17:24:14 +00004801 switch (Tok.getKind()) {
4802 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00004803
Xiuli Pan9c14e282016-01-09 12:53:17 +00004804 case tok::kw_pipe:
4805 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4806
Chris Lattner020bab92009-01-04 23:41:41 +00004807 case tok::identifier: // foo::bar
Steve Naroff9527bbf2009-03-09 21:12:44 +00004808 // Unfortunate hack to support "Class.factoryMethod" notation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004809 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
Steve Naroff9527bbf2009-03-09 21:12:44 +00004810 return false;
John Thompson22334602010-02-05 00:12:22 +00004811 if (TryAltiVecVectorToken())
4812 return true;
4813 // Fall through.
David Blaikie15a430a2011-12-04 05:04:18 +00004814 case tok::kw_decltype: // decltype(T())::type
Douglas Gregor333489b2009-03-27 23:10:48 +00004815 case tok::kw_typename: // typename T::type
Chris Lattner020bab92009-01-04 23:41:41 +00004816 // Annotate typenames and C++ scope specifiers. If we get one, just
4817 // recurse to handle whatever we get.
4818 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004819 return true;
4820 if (Tok.is(tok::identifier))
4821 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004822
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004823 // If we're in Objective-C and we have an Objective-C class type followed
Chad Rosierc1183952012-06-26 22:30:43 +00004824 // by an identifier and then either ':' or ']', in a place where an
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004825 // expression is permitted, then this is probably a class message send
4826 // missing the initial '['. In this case, we won't consider this to be
4827 // the start of a declaration.
Chad Rosierc1183952012-06-26 22:30:43 +00004828 if (DisambiguatingWithExpression &&
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00004829 isStartOfObjCClassMessageMissingOpenBracket())
4830 return false;
Chad Rosierc1183952012-06-26 22:30:43 +00004831
John McCall1f476a12010-02-26 08:45:28 +00004832 return isDeclarationSpecifier();
4833
Chris Lattner020bab92009-01-04 23:41:41 +00004834 case tok::coloncolon: // ::foo::bar
4835 if (NextToken().is(tok::kw_new) || // ::new
4836 NextToken().is(tok::kw_delete)) // ::delete
4837 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004838
Chris Lattner020bab92009-01-04 23:41:41 +00004839 // Annotate typenames and C++ scope specifiers. If we get one, just
4840 // recurse to handle whatever we get.
4841 if (TryAnnotateTypeOrScopeToken())
John McCall1f476a12010-02-26 08:45:28 +00004842 return true;
4843 return isDeclarationSpecifier();
Mike Stump11289f42009-09-09 15:08:12 +00004844
Chris Lattneracd58a32006-08-06 17:24:14 +00004845 // storage-class-specifier
4846 case tok::kw_typedef:
4847 case tok::kw_extern:
Steve Naroff2050b0d2007-12-18 00:16:02 +00004848 case tok::kw___private_extern__:
Chris Lattneracd58a32006-08-06 17:24:14 +00004849 case tok::kw_static:
4850 case tok::kw_auto:
Richard Smithe301ba22015-11-11 02:02:15 +00004851 case tok::kw___auto_type:
Chris Lattneracd58a32006-08-06 17:24:14 +00004852 case tok::kw_register:
4853 case tok::kw___thread:
Richard Smithb4a9e862013-04-12 22:46:28 +00004854 case tok::kw_thread_local:
4855 case tok::kw__Thread_local:
Mike Stump11289f42009-09-09 15:08:12 +00004856
Douglas Gregor26701a42011-09-09 02:06:17 +00004857 // Modules
4858 case tok::kw___module_private__:
Chad Rosierc1183952012-06-26 22:30:43 +00004859
John McCallea0a39e2012-11-14 00:49:39 +00004860 // Debugger support
4861 case tok::kw___unknown_anytype:
4862
Chris Lattneracd58a32006-08-06 17:24:14 +00004863 // type-specifiers
4864 case tok::kw_short:
4865 case tok::kw_long:
Francois Pichet84133e42011-04-28 01:59:37 +00004866 case tok::kw___int64:
Richard Smithf016bbc2012-04-04 06:24:32 +00004867 case tok::kw___int128:
Chris Lattneracd58a32006-08-06 17:24:14 +00004868 case tok::kw_signed:
4869 case tok::kw_unsigned:
4870 case tok::kw__Complex:
4871 case tok::kw__Imaginary:
4872 case tok::kw_void:
4873 case tok::kw_char:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004874 case tok::kw_wchar_t:
Richard Smith3a8244d2018-05-01 05:02:45 +00004875 case tok::kw_char8_t:
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004876 case tok::kw_char16_t:
4877 case tok::kw_char32_t:
4878
Chris Lattneracd58a32006-08-06 17:24:14 +00004879 case tok::kw_int:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004880 case tok::kw_half:
Chris Lattneracd58a32006-08-06 17:24:14 +00004881 case tok::kw_float:
4882 case tok::kw_double:
Leonard Chanf921d852018-06-04 16:07:52 +00004883 case tok::kw__Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004884 case tok::kw__Fract:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00004885 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004886 case tok::kw___float128:
Chris Lattnerbb31a422007-11-15 05:25:19 +00004887 case tok::kw_bool:
Chris Lattneracd58a32006-08-06 17:24:14 +00004888 case tok::kw__Bool:
4889 case tok::kw__Decimal32:
4890 case tok::kw__Decimal64:
4891 case tok::kw__Decimal128:
John Thompson22334602010-02-05 00:12:22 +00004892 case tok::kw___vector:
Mike Stump11289f42009-09-09 15:08:12 +00004893
Chris Lattner861a2262008-04-13 18:59:07 +00004894 // struct-or-union-specifier (C99) or class-specifier (C++)
4895 case tok::kw_class:
Chris Lattneracd58a32006-08-06 17:24:14 +00004896 case tok::kw_struct:
4897 case tok::kw_union:
Joao Matosdc86f942012-08-31 18:45:21 +00004898 case tok::kw___interface:
Chris Lattneracd58a32006-08-06 17:24:14 +00004899 // enum-specifier
4900 case tok::kw_enum:
Mike Stump11289f42009-09-09 15:08:12 +00004901
Chris Lattneracd58a32006-08-06 17:24:14 +00004902 // type-qualifier
4903 case tok::kw_const:
4904 case tok::kw_volatile:
4905 case tok::kw_restrict:
Leonard Chanab80f3c2018-06-14 14:53:51 +00004906 case tok::kw__Sat:
Steve Naroffad373bd2007-07-31 12:34:36 +00004907
Chris Lattneracd58a32006-08-06 17:24:14 +00004908 // function-specifier
4909 case tok::kw_inline:
Douglas Gregor61956c42008-10-31 09:07:45 +00004910 case tok::kw_virtual:
4911 case tok::kw_explicit:
Richard Smith0015f092013-01-17 22:16:11 +00004912 case tok::kw__Noreturn:
Chris Lattner7b20dc72007-08-09 16:40:21 +00004913
Richard Smith1dba27c2013-01-29 09:02:09 +00004914 // alignment-specifier
4915 case tok::kw__Alignas:
4916
Richard Smithd16fe122012-10-25 00:00:53 +00004917 // friend keyword.
4918 case tok::kw_friend:
4919
Peter Collingbourne3d9cbdc2011-04-15 00:35:57 +00004920 // static_assert-declaration
4921 case tok::kw__Static_assert:
4922
Chris Lattner599e47e2007-08-09 17:01:07 +00004923 // GNU typeof support.
4924 case tok::kw_typeof:
Mike Stump11289f42009-09-09 15:08:12 +00004925
Chris Lattner599e47e2007-08-09 17:01:07 +00004926 // GNU attributes.
Chris Lattner7b20dc72007-08-09 16:40:21 +00004927 case tok::kw___attribute:
Mike Stump11289f42009-09-09 15:08:12 +00004928
Richard Smithd16fe122012-10-25 00:00:53 +00004929 // C++11 decltype and constexpr.
David Blaikie15a430a2011-12-04 05:04:18 +00004930 case tok::annot_decltype:
Richard Smithd16fe122012-10-25 00:00:53 +00004931 case tok::kw_constexpr:
Francois Pichete878cb62011-06-19 08:02:06 +00004932
Richard Smith8e1ac332013-03-28 01:55:44 +00004933 // C11 _Atomic
Eli Friedman0dfb8892011-10-06 23:00:33 +00004934 case tok::kw__Atomic:
4935 return true;
4936
Chris Lattner8b2ec162008-07-26 03:38:44 +00004937 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4938 case tok::less:
David Blaikiebbafb8a2012-03-11 07:00:24 +00004939 return getLangOpts().ObjC1;
Mike Stump11289f42009-09-09 15:08:12 +00004940
Douglas Gregor19b7acf2011-04-27 05:41:15 +00004941 // typedef-name
4942 case tok::annot_typename:
4943 return !DisambiguatingWithExpression ||
4944 !isStartOfObjCClassMessageMissingOpenBracket();
Chad Rosierc1183952012-06-26 22:30:43 +00004945
Steve Narofff192fab2009-01-06 19:34:12 +00004946 case tok::kw___declspec:
Steve Naroff44ac7772008-12-25 14:16:32 +00004947 case tok::kw___cdecl:
4948 case tok::kw___stdcall:
4949 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00004950 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00004951 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00004952 case tok::kw___vectorcall:
Eli Friedman53339e02009-06-08 23:27:34 +00004953 case tok::kw___w64:
Aaron Ballman317a77f2013-05-22 23:25:32 +00004954 case tok::kw___sptr:
4955 case tok::kw___uptr:
Eli Friedman53339e02009-06-08 23:27:34 +00004956 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00004957 case tok::kw___ptr32:
Eli Friedman53339e02009-06-08 23:27:34 +00004958 case tok::kw___forceinline:
Dawn Perchik335e16b2010-09-03 01:29:35 +00004959 case tok::kw___pascal:
Francois Pichet17ed0202011-08-18 09:59:55 +00004960 case tok::kw___unaligned:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004961
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004962 case tok::kw__Nonnull:
4963 case tok::kw__Nullable:
4964 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00004965
Douglas Gregorab209d82015-07-07 03:58:42 +00004966 case tok::kw___kindof:
4967
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004968 case tok::kw___private:
4969 case tok::kw___local:
4970 case tok::kw___global:
4971 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00004972 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004973 case tok::kw___read_only:
4974 case tok::kw___read_write:
4975 case tok::kw___write_only:
Alexey Bader954ba212016-04-08 13:40:33 +00004976#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +00004977#include "clang/Basic/OpenCLImageTypes.def"
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00004978
Eli Friedman53339e02009-06-08 23:27:34 +00004979 return true;
Chris Lattneracd58a32006-08-06 17:24:14 +00004980 }
4981}
4982
Richard Smith35845152017-02-07 01:37:30 +00004983bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004984 TentativeParsingAction TPA(*this);
4985
4986 // Parse the C++ scope specifier.
4987 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00004988 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00004989 /*EnteringContext=*/true)) {
John McCall1f476a12010-02-26 08:45:28 +00004990 TPA.Revert();
4991 return false;
4992 }
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004993
4994 // Parse the constructor name.
Richard Smithaf3b3252017-05-18 19:21:48 +00004995 if (Tok.is(tok::identifier)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004996 // We already know that we have a constructor name; just consume
4997 // the token.
4998 ConsumeToken();
Richard Smithaf3b3252017-05-18 19:21:48 +00004999 } else if (Tok.is(tok::annot_template_id)) {
5000 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005001 } else {
5002 TPA.Revert();
5003 return false;
5004 }
5005
Richard Smith8f8697f2017-02-08 01:16:55 +00005006 // There may be attributes here, appertaining to the constructor name or type
5007 // we just stepped past.
5008 SkipCXX11Attributes();
5009
Richard Smith43f340f2012-03-27 23:05:05 +00005010 // Current class name must be followed by a left parenthesis.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005011 if (Tok.isNot(tok::l_paren)) {
5012 TPA.Revert();
5013 return false;
5014 }
5015 ConsumeParen();
5016
Richard Smith43f340f2012-03-27 23:05:05 +00005017 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5018 // that we have a constructor.
5019 if (Tok.is(tok::r_paren) ||
5020 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005021 TPA.Revert();
5022 return true;
5023 }
5024
Richard Smithf2163662013-09-06 00:12:20 +00005025 // A C++11 attribute here signals that we have a constructor, and is an
5026 // attribute on the first constructor parameter.
5027 if (getLangOpts().CPlusPlus11 &&
5028 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5029 /*OuterMightBeMessageSend*/ true)) {
5030 TPA.Revert();
5031 return true;
5032 }
5033
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005034 // If we need to, enter the specified scope.
5035 DeclaratorScopeObj DeclScopeObj(*this, SS);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005036 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005037 DeclScopeObj.EnterDeclaratorScope();
5038
Francois Pichet79f3a872011-01-31 04:54:32 +00005039 // Optionally skip Microsoft attributes.
John McCall084e83d2011-03-24 11:26:52 +00005040 ParsedAttributes Attrs(AttrFactory);
Francois Pichet79f3a872011-01-31 04:54:32 +00005041 MaybeParseMicrosoftAttributes(Attrs);
5042
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005043 // Check whether the next token(s) are part of a declaration
5044 // specifier, in which case we have the start of a parameter and,
5045 // therefore, we know that this is a constructor.
Richard Smithefd009d2012-03-27 00:56:56 +00005046 bool IsConstructor = false;
5047 if (isDeclarationSpecifier())
5048 IsConstructor = true;
5049 else if (Tok.is(tok::identifier) ||
5050 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5051 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5052 // This might be a parenthesized member name, but is more likely to
5053 // be a constructor declaration with an invalid argument type. Keep
5054 // looking.
5055 if (Tok.is(tok::annot_cxxscope))
Richard Smithaf3b3252017-05-18 19:21:48 +00005056 ConsumeAnnotationToken();
Richard Smithefd009d2012-03-27 00:56:56 +00005057 ConsumeToken();
5058
5059 // If this is not a constructor, we must be parsing a declarator,
Richard Smith1453e312012-03-27 01:42:32 +00005060 // which must have one of the following syntactic forms (see the
5061 // grammar extract at the start of ParseDirectDeclarator):
Richard Smithefd009d2012-03-27 00:56:56 +00005062 switch (Tok.getKind()) {
5063 case tok::l_paren:
5064 // C(X ( int));
5065 case tok::l_square:
5066 // C(X [ 5]);
5067 // C(X [ [attribute]]);
5068 case tok::coloncolon:
5069 // C(X :: Y);
5070 // C(X :: *p);
Richard Smithefd009d2012-03-27 00:56:56 +00005071 // Assume this isn't a constructor, rather than assuming it's a
5072 // constructor with an unnamed parameter of an ill-formed type.
5073 break;
5074
Richard Smith446161b2014-03-03 21:12:53 +00005075 case tok::r_paren:
5076 // C(X )
Richard Smith8f8697f2017-02-08 01:16:55 +00005077
5078 // Skip past the right-paren and any following attributes to get to
5079 // the function body or trailing-return-type.
5080 ConsumeParen();
5081 SkipCXX11Attributes();
5082
Richard Smith35845152017-02-07 01:37:30 +00005083 if (DeductionGuide) {
5084 // C(X) -> ... is a deduction guide.
Richard Smith8f8697f2017-02-08 01:16:55 +00005085 IsConstructor = Tok.is(tok::arrow);
Richard Smith35845152017-02-07 01:37:30 +00005086 break;
5087 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005088 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
Richard Smith446161b2014-03-03 21:12:53 +00005089 // Assume these were meant to be constructors:
5090 // C(X) : (the name of a bit-field cannot be parenthesized).
5091 // C(X) try (this is otherwise ill-formed).
5092 IsConstructor = true;
5093 }
Richard Smith8f8697f2017-02-08 01:16:55 +00005094 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
Richard Smith446161b2014-03-03 21:12:53 +00005095 // If we have a constructor name within the class definition,
5096 // assume these were meant to be constructors:
5097 // C(X) {
5098 // C(X) ;
5099 // ... because otherwise we would be declaring a non-static data
5100 // member that is ill-formed because it's of the same type as its
5101 // surrounding class.
5102 //
5103 // FIXME: We can actually do this whether or not the name is qualified,
5104 // because if it is qualified in this context it must be being used as
Richard Smith35845152017-02-07 01:37:30 +00005105 // a constructor name.
Richard Smith446161b2014-03-03 21:12:53 +00005106 // currently, so we're somewhat conservative here.
5107 IsConstructor = IsUnqualified;
5108 }
5109 break;
5110
Richard Smithefd009d2012-03-27 00:56:56 +00005111 default:
5112 IsConstructor = true;
5113 break;
5114 }
5115 }
5116
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005117 TPA.Revert();
5118 return IsConstructor;
5119}
Chris Lattnerb9093cd2006-08-04 04:39:53 +00005120
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005121/// ParseTypeQualifierListOpt
Dawn Perchik335e16b2010-09-03 01:29:35 +00005122/// type-qualifier-list: [C99 6.7.5]
5123/// type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005124/// [vendor] attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005125/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005126/// type-qualifier-list type-qualifier
Chad Rosierc1183952012-06-26 22:30:43 +00005127/// [vendor] type-qualifier-list attributes
Aaron Ballman08b06592014-07-22 12:44:22 +00005128/// [ only if AttrReqs & AR_VendorAttributesParsed ]
Dawn Perchik335e16b2010-09-03 01:29:35 +00005129/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
Aaron Ballman08b06592014-07-22 12:44:22 +00005130/// [ only if AttReqs & AR_CXX11AttributesParsed ]
5131/// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5132/// AttrRequirements bitmask values.
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005133void Parser::ParseTypeQualifierListOpt(
5134 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5135 bool IdentifierRequired,
5136 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
Aaron Ballman606093a2017-10-15 15:01:42 +00005137 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005138 isCXX11AttributeSpecifier()) {
John McCall084e83d2011-03-24 11:26:52 +00005139 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith3dff2512012-04-10 03:25:07 +00005140 ParseCXX11Attributes(attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005141 DS.takeAttributesFrom(attrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005142 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005143
5144 SourceLocation EndLoc;
5145
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005146 while (1) {
John McCall49bfce42009-08-03 20:12:06 +00005147 bool isInvalid = false;
Craig Topper161e4db2014-05-21 06:02:52 +00005148 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00005149 unsigned DiagID = 0;
Chris Lattner60809f52006-11-28 05:18:46 +00005150 SourceLocation Loc = Tok.getLocation();
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005151
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005152 switch (Tok.getKind()) {
Douglas Gregor28c78432010-08-27 17:35:51 +00005153 case tok::code_completion:
Alex Lorenz8f4d3992017-02-13 23:19:40 +00005154 if (CodeCompletionHandler)
5155 (*CodeCompletionHandler)();
5156 else
5157 Actions.CodeCompleteTypeQualifiers(DS);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00005158 return cutOffParsing();
Chad Rosierc1183952012-06-26 22:30:43 +00005159
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005160 case tok::kw_const:
John McCall49bfce42009-08-03 20:12:06 +00005161 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005162 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005163 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005164 case tok::kw_volatile:
John McCall49bfce42009-08-03 20:12:06 +00005165 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005166 getLangOpts());
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005167 break;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005168 case tok::kw_restrict:
John McCall49bfce42009-08-03 20:12:06 +00005169 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
Richard Smith87e79512012-10-17 23:31:46 +00005170 getLangOpts());
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005171 break;
Richard Smith8e1ac332013-03-28 01:55:44 +00005172 case tok::kw__Atomic:
5173 if (!AtomicAllowed)
5174 goto DoneWithTypeQuals;
5175 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5176 getLangOpts());
5177 break;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005178
5179 // OpenCL qualifiers:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005180 case tok::kw___private:
5181 case tok::kw___global:
5182 case tok::kw___local:
5183 case tok::kw___constant:
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +00005184 case tok::kw___generic:
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005185 case tok::kw___read_only:
5186 case tok::kw___write_only:
5187 case tok::kw___read_write:
Aaron Ballman05d76ea2014-01-14 01:29:54 +00005188 ParseOpenCLQualifiers(DS.getAttributes());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00005189 break;
5190
Andrey Bokhanko45d41322016-05-11 18:38:21 +00005191 case tok::kw___unaligned:
5192 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5193 getLangOpts());
5194 break;
Aaron Ballman317a77f2013-05-22 23:25:32 +00005195 case tok::kw___uptr:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005196 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
Alp Toker62c5b572013-11-26 01:30:10 +00005197 // with the MS modifier keyword.
Aaron Ballman08b06592014-07-22 12:44:22 +00005198 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
Alp Toker47642d22013-12-03 06:13:01 +00005199 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5200 if (TryKeywordIdentFallback(false))
5201 continue;
Alp Toker62c5b572013-11-26 01:30:10 +00005202 }
Galina Kistanova77674252017-06-01 21:15:34 +00005203 LLVM_FALLTHROUGH;
Alp Toker62c5b572013-11-26 01:30:10 +00005204 case tok::kw___sptr:
Eli Friedman53339e02009-06-08 23:27:34 +00005205 case tok::kw___w64:
Steve Narofff9c29d42008-12-25 14:41:26 +00005206 case tok::kw___ptr64:
Francois Pichetf2fb4112011-08-25 00:36:46 +00005207 case tok::kw___ptr32:
Steve Naroff44ac7772008-12-25 14:16:32 +00005208 case tok::kw___cdecl:
5209 case tok::kw___stdcall:
5210 case tok::kw___fastcall:
Douglas Gregora941dca2010-05-18 16:57:00 +00005211 case tok::kw___thiscall:
Erich Keane757d3172016-11-02 18:29:35 +00005212 case tok::kw___regcall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005213 case tok::kw___vectorcall:
Aaron Ballman08b06592014-07-22 12:44:22 +00005214 if (AttrReqs & AR_DeclspecAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005215 ParseMicrosoftTypeAttributes(DS.getAttributes());
Eli Friedman53339e02009-06-08 23:27:34 +00005216 continue;
5217 }
5218 goto DoneWithTypeQuals;
Dawn Perchik335e16b2010-09-03 01:29:35 +00005219 case tok::kw___pascal:
Aaron Ballman08b06592014-07-22 12:44:22 +00005220 if (AttrReqs & AR_VendorAttributesParsed) {
John McCall53fa7142010-12-24 02:08:15 +00005221 ParseBorlandTypeAttributes(DS.getAttributes());
Dawn Perchik335e16b2010-09-03 01:29:35 +00005222 continue;
5223 }
5224 goto DoneWithTypeQuals;
Douglas Gregor261a89b2015-06-19 17:51:05 +00005225
5226 // Nullability type specifiers.
Douglas Gregoraea7afd2015-06-24 22:02:08 +00005227 case tok::kw__Nonnull:
5228 case tok::kw__Nullable:
5229 case tok::kw__Null_unspecified:
Douglas Gregor261a89b2015-06-19 17:51:05 +00005230 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5231 continue;
5232
Douglas Gregorab209d82015-07-07 03:58:42 +00005233 // Objective-C 'kindof' types.
5234 case tok::kw___kindof:
5235 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5236 nullptr, 0, AttributeList::AS_Keyword);
5237 (void)ConsumeToken();
5238 continue;
5239
Chris Lattnere37e2332006-08-15 04:50:22 +00005240 case tok::kw___attribute:
Aaron Ballman08b06592014-07-22 12:44:22 +00005241 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5242 // When GNU attributes are expressly forbidden, diagnose their usage.
5243 Diag(Tok, diag::err_attributes_not_allowed);
5244
5245 // Parse the attributes even if they are rejected to ensure that error
5246 // recovery is graceful.
5247 if (AttrReqs & AR_GNUAttributesParsed ||
5248 AttrReqs & AR_GNUAttributesParsedAndRejected) {
John McCall53fa7142010-12-24 02:08:15 +00005249 ParseGNUAttributes(DS.getAttributes());
Chris Lattnercf0bab22008-12-18 07:02:59 +00005250 continue; // do *not* consume the next token!
5251 }
5252 // otherwise, FALL THROUGH!
Galina Kistanova77674252017-06-01 21:15:34 +00005253 LLVM_FALLTHROUGH;
Chris Lattnercf0bab22008-12-18 07:02:59 +00005254 default:
Steve Naroff44ac7772008-12-25 14:16:32 +00005255 DoneWithTypeQuals:
Chris Lattnercf0bab22008-12-18 07:02:59 +00005256 // If this is not a type-qualifier token, we're done reading type
5257 // qualifiers. First verify that DeclSpec's are consistent.
Craig Topper25122412015-11-15 03:32:11 +00005258 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005259 if (EndLoc.isValid())
5260 DS.SetRangeEnd(EndLoc);
Chris Lattnercf0bab22008-12-18 07:02:59 +00005261 return;
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005262 }
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00005263
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005264 // If the specifier combination wasn't legal, issue a diagnostic.
5265 if (isInvalid) {
5266 assert(PrevSpec && "Method did not return previous specifier!");
Chris Lattner6d29c102008-11-18 07:48:38 +00005267 Diag(Tok, DiagID) << PrevSpec;
Chris Lattnerd9c3c592006-08-05 06:26:47 +00005268 }
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00005269 EndLoc = ConsumeToken();
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005270 }
5271}
5272
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005273/// ParseDeclarator - Parse and verify a newly-initialized declarator.
5274///
5275void Parser::ParseDeclarator(Declarator &D) {
5276 /// This implements the 'declarator' production in the C grammar, then checks
5277 /// for well-formedness and issues diagnostics.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005278 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerd5d0a6c2006-08-07 00:58:14 +00005279}
5280
Richard Smith0b350b92014-10-28 16:55:02 +00005281static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
Faisal Vali421b2d12017-12-29 05:41:00 +00005282 DeclaratorContext TheContext) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005283 if (Kind == tok::star || Kind == tok::caret)
5284 return true;
5285
Xiuli Pan9c14e282016-01-09 12:53:17 +00005286 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5287 return true;
5288
Richard Smith0efa75c2012-03-29 01:16:42 +00005289 if (!Lang.CPlusPlus)
5290 return false;
5291
Richard Smith0b350b92014-10-28 16:55:02 +00005292 if (Kind == tok::amp)
5293 return true;
5294
5295 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5296 // But we must not parse them in conversion-type-ids and new-type-ids, since
5297 // those can be legitimately followed by a && operator.
5298 // (The same thing can in theory happen after a trailing-return-type, but
5299 // since those are a C++11 feature, there is no rejects-valid issue there.)
5300 if (Kind == tok::ampamp)
Faisal Vali421b2d12017-12-29 05:41:00 +00005301 return Lang.CPlusPlus11 ||
5302 (TheContext != DeclaratorContext::ConversionIdContext &&
5303 TheContext != DeclaratorContext::CXXNewContext);
Richard Smith0b350b92014-10-28 16:55:02 +00005304
5305 return false;
Richard Smith0efa75c2012-03-29 01:16:42 +00005306}
5307
Xiuli Pan9c14e282016-01-09 12:53:17 +00005308// Indicates whether the given declarator is a pipe declarator.
5309static bool isPipeDeclerator(const Declarator &D) {
5310 const unsigned NumTypes = D.getNumTypeObjects();
5311
5312 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5313 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5314 return true;
5315
5316 return false;
5317}
5318
Sebastian Redlbd150f42008-11-21 19:14:01 +00005319/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5320/// is parsed by the function passed to it. Pass null, and the direct-declarator
5321/// isn't parsed at all, making this function effectively parse the C++
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005322/// ptr-operator production.
5323///
Richard Smith09f76ee2011-10-19 21:33:05 +00005324/// If the grammar of this construct is extended, matching changes must also be
Richard Smith1453e312012-03-27 01:42:32 +00005325/// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5326/// isConstructorDeclarator.
Richard Smith09f76ee2011-10-19 21:33:05 +00005327///
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005328/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5329/// [C] pointer[opt] direct-declarator
5330/// [C++] direct-declarator
5331/// [C++] ptr-operator declarator
Chris Lattner6c7416c2006-08-07 00:19:33 +00005332///
5333/// pointer: [C99 6.7.5]
5334/// '*' type-qualifier-list[opt]
5335/// '*' type-qualifier-list[opt] pointer
5336///
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005337/// ptr-operator:
5338/// '*' cv-qualifier-seq[opt]
5339/// '&'
Sebastian Redled0f3b02009-03-15 22:02:01 +00005340/// [C++0x] '&&'
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005341/// [GNU] '&' restrict[opt] attributes[opt]
Sebastian Redled0f3b02009-03-15 22:02:01 +00005342/// [GNU?] '&&' restrict[opt] attributes[opt]
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005343/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
Sebastian Redlbd150f42008-11-21 19:14:01 +00005344void Parser::ParseDeclaratorInternal(Declarator &D,
5345 DirectDeclParseFunction DirectDeclParser) {
Douglas Gregor66a985d2009-08-26 14:27:30 +00005346 if (Diags.hasAllExtensionsSilenced())
5347 D.setExtension();
Chad Rosierc1183952012-06-26 22:30:43 +00005348
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005349 // C++ member pointers start with a '::' or a nested-name.
5350 // Member pointers get special handling, since there's no place for the
5351 // scope spec in the generic path below.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005352 if (getLangOpts().CPlusPlus &&
Richard Smith83c2ecf2016-02-02 23:34:49 +00005353 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
Serge Pavlov458ea762014-07-16 05:16:52 +00005354 (Tok.is(tok::identifier) &&
5355 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
Chris Lattner803802d2009-03-24 17:04:48 +00005356 Tok.is(tok::annot_cxxscope))) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005357 bool EnteringContext =
5358 D.getContext() == DeclaratorContext::FileContext ||
5359 D.getContext() == DeclaratorContext::MemberContext;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005360 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +00005361 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005362
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +00005363 if (SS.isNotEmpty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005364 if (Tok.isNot(tok::star)) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005365 // The scope spec really belongs to the direct-declarator.
Richard Smith5f044ad2013-01-08 22:43:49 +00005366 if (D.mayHaveIdentifier())
5367 D.getCXXScopeSpec() = SS;
5368 else
5369 AnnotateScopeToken(SS, true);
5370
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005371 if (DirectDeclParser)
5372 (this->*DirectDeclParser)(D);
5373 return;
5374 }
5375
5376 SourceLocation Loc = ConsumeToken();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005377 D.SetRangeEnd(Loc);
John McCall084e83d2011-03-24 11:26:52 +00005378 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005379 ParseTypeQualifierListOpt(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005380 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005381
5382 // Recurse to parse whatever is left.
5383 ParseDeclaratorInternal(D, DirectDeclParser);
5384
5385 // Sema will have to catch (syntactically invalid) pointers into global
5386 // scope. It has to catch pointers into namespace scope anyway.
5387 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
Richard Smitha865a162014-12-19 02:07:47 +00005388 DS.getLocEnd()),
John McCall084e83d2011-03-24 11:26:52 +00005389 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005390 /* Don't replace range end. */SourceLocation());
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005391 return;
5392 }
5393 }
5394
5395 tok::TokenKind Kind = Tok.getKind();
Xiuli Pan9c14e282016-01-09 12:53:17 +00005396
5397 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
Xiuli Pan11e13f62016-02-26 03:13:03 +00005398 DeclSpec DS(AttrFactory);
5399 ParseTypeQualifierListOpt(DS);
Xiuli Pan9c14e282016-01-09 12:53:17 +00005400
5401 D.AddTypeInfo(
5402 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
5403 DS.getAttributes(), SourceLocation());
5404 }
5405
Steve Naroffec33ed92008-08-27 16:04:49 +00005406 // Not a pointer, C++ reference, or block.
Richard Smith0b350b92014-10-28 16:55:02 +00005407 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00005408 if (DirectDeclParser)
5409 (this->*DirectDeclParser)(D);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005410 return;
5411 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005412
Sebastian Redled0f3b02009-03-15 22:02:01 +00005413 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5414 // '&&' -> rvalue reference
Sebastian Redl3b27be62009-03-23 00:00:23 +00005415 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005416 D.SetRangeEnd(Loc);
Bill Wendling3708c182007-05-27 10:15:43 +00005417
Chris Lattner9eac9312009-03-27 04:18:06 +00005418 if (Kind == tok::star || Kind == tok::caret) {
Chris Lattner788404f2008-02-21 01:32:26 +00005419 // Is a pointer.
John McCall084e83d2011-03-24 11:26:52 +00005420 DeclSpec DS(AttrFactory);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005421
Aaron Ballman08b06592014-07-22 12:44:22 +00005422 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5423 // C++11 attributes are allowed.
5424 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
Faisal Vali421b2d12017-12-29 05:41:00 +00005425 ((D.getContext() != DeclaratorContext::CXXNewContext)
5426 ? AR_GNUAttributesParsed
5427 : AR_GNUAttributesParsedAndRejected);
Aaron Ballman08b06592014-07-22 12:44:22 +00005428 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005429 D.ExtendWithDeclSpec(DS);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00005430
Bill Wendling3708c182007-05-27 10:15:43 +00005431 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005432 ParseDeclaratorInternal(D, DirectDeclParser);
Steve Naroffec33ed92008-08-27 16:04:49 +00005433 if (Kind == tok::star)
5434 // Remember that we parsed a pointer type, and remember the type-quals.
5435 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
Chandler Carruthe71b378d2011-02-23 18:51:59 +00005436 DS.getConstSpecLoc(),
5437 DS.getVolatileSpecLoc(),
Benjamin Kramerd0028dc2015-03-29 16:42:06 +00005438 DS.getRestrictSpecLoc(),
Andrey Bokhanko45d41322016-05-11 18:38:21 +00005439 DS.getAtomicSpecLoc(),
5440 DS.getUnalignedSpecLoc()),
John McCall084e83d2011-03-24 11:26:52 +00005441 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005442 SourceLocation());
Steve Naroffec33ed92008-08-27 16:04:49 +00005443 else
5444 // Remember that we parsed a Block type, and remember the type-quals.
Mike Stump11289f42009-09-09 15:08:12 +00005445 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
John McCall084e83d2011-03-24 11:26:52 +00005446 Loc),
5447 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005448 SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005449 } else {
5450 // Is a reference
John McCall084e83d2011-03-24 11:26:52 +00005451 DeclSpec DS(AttrFactory);
Bill Wendling93efb222007-06-02 23:28:54 +00005452
Sebastian Redl3b27be62009-03-23 00:00:23 +00005453 // Complain about rvalue references in C++03, but then go on and build
5454 // the declarator.
Richard Smith5d164bc2011-10-15 05:09:34 +00005455 if (Kind == tok::ampamp)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005456 Diag(Loc, getLangOpts().CPlusPlus11 ?
Richard Smith5d164bc2011-10-15 05:09:34 +00005457 diag::warn_cxx98_compat_rvalue_reference :
5458 diag::ext_rvalue_reference);
Sebastian Redl3b27be62009-03-23 00:00:23 +00005459
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005460 // GNU-style and C++11 attributes are allowed here, as is restrict.
5461 ParseTypeQualifierListOpt(DS);
5462 D.ExtendWithDeclSpec(DS);
5463
Bill Wendling93efb222007-06-02 23:28:54 +00005464 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5465 // cv-qualifiers are introduced through the use of a typedef or of a
5466 // template type argument, in which case the cv-qualifiers are ignored.
Bill Wendling93efb222007-06-02 23:28:54 +00005467 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5468 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5469 Diag(DS.getConstSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005470 diag::err_invalid_reference_qualifier_application) << "const";
Bill Wendling93efb222007-06-02 23:28:54 +00005471 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5472 Diag(DS.getVolatileSpecLoc(),
Chris Lattner6d29c102008-11-18 07:48:38 +00005473 diag::err_invalid_reference_qualifier_application) << "volatile";
Richard Smith8e1ac332013-03-28 01:55:44 +00005474 // 'restrict' is permitted as an extension.
5475 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5476 Diag(DS.getAtomicSpecLoc(),
5477 diag::err_invalid_reference_qualifier_application) << "_Atomic";
Bill Wendling93efb222007-06-02 23:28:54 +00005478 }
Bill Wendling3708c182007-05-27 10:15:43 +00005479
5480 // Recursively parse the declarator.
Sebastian Redlbd150f42008-11-21 19:14:01 +00005481 ParseDeclaratorInternal(D, DirectDeclParser);
Bill Wendling3708c182007-05-27 10:15:43 +00005482
Douglas Gregor66583c52008-11-03 15:51:28 +00005483 if (D.getNumTypeObjects() > 0) {
5484 // C++ [dcl.ref]p4: There shall be no references to references.
5485 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5486 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
Chris Lattnerebad6a22008-11-19 07:37:42 +00005487 if (const IdentifierInfo *II = D.getIdentifier())
5488 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5489 << II;
5490 else
5491 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5492 << "type name";
Douglas Gregor66583c52008-11-03 15:51:28 +00005493
Sebastian Redlbd150f42008-11-21 19:14:01 +00005494 // Once we've complained about the reference-to-reference, we
Douglas Gregor66583c52008-11-03 15:51:28 +00005495 // can go ahead and build the (technically ill-formed)
5496 // declarator: reference collapsing will take care of it.
5497 }
5498 }
5499
Richard Smith8e1ac332013-03-28 01:55:44 +00005500 // Remember that we parsed a reference type.
Chris Lattner788404f2008-02-21 01:32:26 +00005501 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
Sebastian Redled0f3b02009-03-15 22:02:01 +00005502 Kind == tok::amp),
John McCall084e83d2011-03-24 11:26:52 +00005503 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005504 SourceLocation());
Bill Wendling3708c182007-05-27 10:15:43 +00005505 }
Chris Lattner6c7416c2006-08-07 00:19:33 +00005506}
5507
Richard Trieuf4b81d02014-06-24 23:14:24 +00005508// When correcting from misplaced brackets before the identifier, the location
5509// is saved inside the declarator so that other diagnostic messages can use
5510// them. This extracts and returns that location, or returns the provided
5511// location if a stored location does not exist.
5512static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5513 SourceLocation Loc) {
5514 if (D.getName().StartLocation.isInvalid() &&
5515 D.getName().EndLocation.isValid())
5516 return D.getName().EndLocation;
5517
5518 return Loc;
5519}
5520
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005521/// ParseDirectDeclarator
5522/// direct-declarator: [C99 6.7.5]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005523/// [C99] identifier
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005524/// '(' declarator ')'
5525/// [GNU] '(' attributes declarator ')'
Chris Lattnere8074e62006-08-06 18:30:15 +00005526/// [C90] direct-declarator '[' constant-expression[opt] ']'
5527/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5528/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5529/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5530/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005531/// [C++11] direct-declarator '[' constant-expression[opt] ']'
5532/// attribute-specifier-seq[opt]
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00005533/// direct-declarator '(' parameter-type-list ')'
5534/// direct-declarator '(' identifier-list[opt] ')'
5535/// [GNU] direct-declarator '(' parameter-forward-declarations
5536/// parameter-type-list[opt] ')'
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00005537/// [C++] direct-declarator '(' parameter-declaration-clause ')'
5538/// cv-qualifier-seq[opt] exception-specification[opt]
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005539/// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5540/// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5541/// ref-qualifier[opt] exception-specification[opt]
Douglas Gregor61956c42008-10-31 09:07:45 +00005542/// [C++] declarator-id
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005543/// [C++11] declarator-id attribute-specifier-seq[opt]
Douglas Gregor831c93f2008-11-05 20:51:48 +00005544///
5545/// declarator-id: [C++ 8]
Douglas Gregor27b4c162010-12-23 22:44:42 +00005546/// '...'[opt] id-expression
Douglas Gregor831c93f2008-11-05 20:51:48 +00005547/// '::'[opt] nested-name-specifier[opt] type-name
5548///
5549/// id-expression: [C++ 5.1]
5550/// unqualified-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005551/// qualified-id
Douglas Gregor831c93f2008-11-05 20:51:48 +00005552///
5553/// unqualified-id: [C++ 5.1]
Mike Stump11289f42009-09-09 15:08:12 +00005554/// identifier
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005555/// operator-function-id
Douglas Gregord90fd522009-09-25 21:45:23 +00005556/// conversion-function-id
Mike Stump11289f42009-09-09 15:08:12 +00005557/// '~' class-name
Douglas Gregor7f741122009-02-25 19:37:18 +00005558/// template-id
Argyrios Kyrtzidise4426352008-11-07 22:02:30 +00005559///
Richard Smithbdb84f32016-07-22 23:36:59 +00005560/// C++17 adds the following, which we also handle here:
5561///
5562/// simple-declaration:
5563/// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5564///
Richard Smith1453e312012-03-27 01:42:32 +00005565/// Note, any additional constructs added here may need corresponding changes
5566/// in isConstructorDeclarator.
Chris Lattneracd58a32006-08-06 17:24:14 +00005567void Parser::ParseDirectDeclarator(Declarator &D) {
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005568 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00005569
David Blaikiebbafb8a2012-03-11 07:00:24 +00005570 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
Richard Smithbdb84f32016-07-22 23:36:59 +00005571 // This might be a C++17 structured binding.
5572 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5573 D.getCXXScopeSpec().isEmpty())
5574 return ParseDecompositionDeclarator(D);
5575
Serge Pavlov458ea762014-07-16 05:16:52 +00005576 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5577 // this context it is a bitfield. Also in range-based for statement colon
5578 // may delimit for-range-declaration.
Faisal Vali421b2d12017-12-29 05:41:00 +00005579 ColonProtectionRAIIObject X(
5580 *this, D.getContext() == DeclaratorContext::MemberContext ||
5581 (D.getContext() == DeclaratorContext::ForContext &&
5582 getLangOpts().CPlusPlus11));
Serge Pavlov458ea762014-07-16 05:16:52 +00005583
Douglas Gregor7861a802009-11-03 01:35:08 +00005584 // ParseDeclaratorInternal might already have parsed the scope.
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005585 if (D.getCXXScopeSpec().isEmpty()) {
Faisal Vali421b2d12017-12-29 05:41:00 +00005586 bool EnteringContext =
5587 D.getContext() == DeclaratorContext::FileContext ||
5588 D.getContext() == DeclaratorContext::MemberContext;
David Blaikieefdccaa2016-01-15 23:43:34 +00005589 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
Douglas Gregordf593fb2011-11-07 17:33:42 +00005590 EnteringContext);
John McCall1f476a12010-02-26 08:45:28 +00005591 }
5592
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005593 if (D.getCXXScopeSpec().isValid()) {
Richard Smith64e033f2015-01-15 00:48:52 +00005594 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5595 D.getCXXScopeSpec()))
John McCall2b058ef2009-12-11 20:04:54 +00005596 // Change the declaration context for name lookup, until this function
5597 // is exited (and the declarator has been parsed).
5598 DeclScopeObj.EnterDeclaratorScope();
Alex Lorenze151f0102016-12-07 10:24:44 +00005599 else if (getObjCDeclContext()) {
5600 // Ensure that we don't interpret the next token as an identifier when
5601 // dealing with declarations in an Objective-C container.
5602 D.SetIdentifier(nullptr, Tok.getLocation());
5603 D.setInvalidType(true);
5604 ConsumeToken();
5605 goto PastIdentifier;
5606 }
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005607 }
5608
Douglas Gregor27b4c162010-12-23 22:44:42 +00005609 // C++0x [dcl.fct]p14:
Faisal Vali8435a692014-12-04 12:40:21 +00005610 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5611 // parameter-declaration-clause without a preceding comma. In this case,
5612 // the ellipsis is parsed as part of the abstract-declarator if the type
5613 // of the parameter either names a template parameter pack that has not
5614 // been expanded or contains auto; otherwise, it is parsed as part of the
5615 // parameter-declaration-clause.
Richard Smith0efa75c2012-03-29 01:16:42 +00005616 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
Faisal Vali421b2d12017-12-29 05:41:00 +00005617 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5618 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5619 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
Douglas Gregor27b4c162010-12-23 22:44:42 +00005620 NextToken().is(tok::r_paren) &&
Richard Smithb19337f2013-02-20 20:19:27 +00005621 !D.hasGroupingParens() &&
Faisal Vali8435a692014-12-04 12:40:21 +00005622 !Actions.containsUnexpandedParameterPacks(D) &&
Faisal Vali090da2d2018-01-01 18:23:28 +00005623 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005624 SourceLocation EllipsisLoc = ConsumeToken();
Richard Smith0b350b92014-10-28 16:55:02 +00005625 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
Richard Smith0efa75c2012-03-29 01:16:42 +00005626 // The ellipsis was put in the wrong place. Recover, and explain to
5627 // the user what they should have done.
5628 ParseDeclarator(D);
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00005629 if (EllipsisLoc.isValid())
5630 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00005631 return;
5632 } else
5633 D.setEllipsisLoc(EllipsisLoc);
5634
5635 // The ellipsis can't be followed by a parenthesized declarator. We
5636 // check for that in ParseParenDeclarator, after we have disambiguated
5637 // the l_paren token.
5638 }
5639
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005640 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5641 tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00005642 // We found something that indicates the start of an unqualified-id.
5643 // Parse that unqualified-id.
John McCall84821e72010-04-13 06:39:49 +00005644 bool AllowConstructorName;
Richard Smith35845152017-02-07 01:37:30 +00005645 bool AllowDeductionGuide;
5646 if (D.getDeclSpec().hasTypeSpecifier()) {
John McCall84821e72010-04-13 06:39:49 +00005647 AllowConstructorName = false;
Richard Smith35845152017-02-07 01:37:30 +00005648 AllowDeductionGuide = false;
5649 } else if (D.getCXXScopeSpec().isSet()) {
John McCall84821e72010-04-13 06:39:49 +00005650 AllowConstructorName =
Faisal Vali421b2d12017-12-29 05:41:00 +00005651 (D.getContext() == DeclaratorContext::FileContext ||
5652 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005653 AllowDeductionGuide = false;
5654 } else {
Faisal Vali421b2d12017-12-29 05:41:00 +00005655 AllowConstructorName =
5656 (D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005657 AllowDeductionGuide =
Faisal Vali421b2d12017-12-29 05:41:00 +00005658 (D.getContext() == DeclaratorContext::FileContext ||
5659 D.getContext() == DeclaratorContext::MemberContext);
Richard Smith35845152017-02-07 01:37:30 +00005660 }
John McCall84821e72010-04-13 06:39:49 +00005661
Richard Smith64e033f2015-01-15 00:48:52 +00005662 bool HadScope = D.getCXXScopeSpec().isValid();
Chad Rosierc1183952012-06-26 22:30:43 +00005663 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5664 /*EnteringContext=*/true,
David Blaikieefdccaa2016-01-15 23:43:34 +00005665 /*AllowDestructorName=*/true, AllowConstructorName,
Richard Smithc08b6932018-04-27 02:00:13 +00005666 AllowDeductionGuide, nullptr, nullptr,
Richard Smith35845152017-02-07 01:37:30 +00005667 D.getName()) ||
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005668 // Once we're past the identifier, if the scope was bad, mark the
5669 // whole declarator bad.
5670 D.getCXXScopeSpec().isInvalid()) {
Craig Topper161e4db2014-05-21 06:02:52 +00005671 D.SetIdentifier(nullptr, Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005672 D.setInvalidType(true);
Douglas Gregor7861a802009-11-03 01:35:08 +00005673 } else {
Richard Smith64e033f2015-01-15 00:48:52 +00005674 // ParseUnqualifiedId might have parsed a scope specifier during error
5675 // recovery. If it did so, enter that scope.
5676 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5677 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5678 D.getCXXScopeSpec()))
5679 DeclScopeObj.EnterDeclaratorScope();
5680
Douglas Gregor7861a802009-11-03 01:35:08 +00005681 // Parsed the unqualified-id; update range information and move along.
5682 if (D.getSourceRange().getBegin().isInvalid())
5683 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5684 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005685 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005686 goto PastIdentifier;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005687 }
Richard Smithd63db6e2015-12-19 02:40:19 +00005688
5689 if (D.getCXXScopeSpec().isNotEmpty()) {
5690 // We have a scope specifier but no following unqualified-id.
5691 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5692 diag::err_expected_unqualified_id)
5693 << /*C++*/1;
5694 D.SetIdentifier(nullptr, Tok.getLocation());
5695 goto PastIdentifier;
5696 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005697 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005698 assert(!getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005699 "There's a C++-specific check for tok::identifier above");
5700 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5701 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Richard Trieu2664dc12014-05-05 22:06:50 +00005702 D.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005703 ConsumeToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00005704 goto PastIdentifier;
Richard Smith74639b12017-05-19 01:54:59 +00005705 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5706 // We're not allowed an identifier here, but we got one. Try to figure out
5707 // if the user was trying to attach a name to the type, or whether the name
5708 // is some unrelated trailing syntax.
5709 bool DiagnoseIdentifier = false;
5710 if (D.hasGroupingParens())
5711 // An identifier within parens is unlikely to be intended to be anything
5712 // other than a name being "declared".
5713 DiagnoseIdentifier = true;
Richard Smith77a9c602018-02-28 03:02:23 +00005714 else if (D.getContext() == DeclaratorContext::TemplateArgContext)
Richard Smith74639b12017-05-19 01:54:59 +00005715 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5716 DiagnoseIdentifier =
5717 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali421b2d12017-12-29 05:41:00 +00005718 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5719 D.getContext() == DeclaratorContext::AliasTemplateContext)
Richard Smith74639b12017-05-19 01:54:59 +00005720 // The most likely error is that the ';' was forgotten.
5721 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
Richard Smithe303e352018-02-02 22:24:54 +00005722 else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5723 D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
Richard Smith74639b12017-05-19 01:54:59 +00005724 !isCXX11VirtSpecifier(Tok))
5725 DiagnoseIdentifier = NextToken().isOneOf(
5726 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5727 if (DiagnoseIdentifier) {
Richard Smithf39720b2013-10-13 22:12:28 +00005728 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5729 << FixItHint::CreateRemoval(Tok.getLocation());
Craig Topper161e4db2014-05-21 06:02:52 +00005730 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithf39720b2013-10-13 22:12:28 +00005731 ConsumeToken();
5732 goto PastIdentifier;
5733 }
Douglas Gregor7861a802009-11-03 01:35:08 +00005734 }
Richard Smith0efa75c2012-03-29 01:16:42 +00005735
Douglas Gregor7861a802009-11-03 01:35:08 +00005736 if (Tok.is(tok::l_paren)) {
Richard Smithe303e352018-02-02 22:24:54 +00005737 // If this might be an abstract-declarator followed by a direct-initializer,
5738 // check whether this is a valid declarator chunk. If it can't be, assume
5739 // that it's an initializer instead.
5740 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5741 RevertingTentativeParsingAction PA(*this);
5742 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5743 TPResult::False) {
5744 D.SetIdentifier(nullptr, Tok.getLocation());
5745 goto PastIdentifier;
5746 }
5747 }
5748
Chris Lattneracd58a32006-08-06 17:24:14 +00005749 // direct-declarator: '(' declarator ')'
Chris Lattnere37e2332006-08-15 04:50:22 +00005750 // direct-declarator: '(' attributes declarator ')'
Chris Lattneracd58a32006-08-06 17:24:14 +00005751 // Example: 'char (*X)' or 'int (*XX)(void)'
5752 ParseParenDeclarator(D);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005753
5754 // If the declarator was parenthesized, we entered the declarator
5755 // scope when parsing the parenthesized declarator, then exited
5756 // the scope already. Re-enter the scope, if we need to.
5757 if (D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005758 // If there was an error parsing parenthesized declarator, declarator
Richard Smith0efa75c2012-03-29 01:16:42 +00005759 // scope may have been entered before. Don't do it again.
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005760 if (!D.isInvalidType() &&
Nico Weber6b05f382015-02-18 04:53:03 +00005761 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5762 D.getCXXScopeSpec()))
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005763 // Change the declaration context for name lookup, until this function
5764 // is exited (and the declarator has been parsed).
Fariborz Jahanian358acd52010-08-17 23:50:37 +00005765 DeclScopeObj.EnterDeclaratorScope();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005766 }
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005767 } else if (D.mayOmitIdentifier()) {
Chris Lattneracd58a32006-08-06 17:24:14 +00005768 // This could be something simple like "int" (in which case the declarator
5769 // portion is empty), if an abstract-declarator is allowed.
Craig Topper161e4db2014-05-21 06:02:52 +00005770 D.SetIdentifier(nullptr, Tok.getLocation());
Richard Smithb19337f2013-02-20 20:19:27 +00005771
5772 // The grammar for abstract-pack-declarator does not allow grouping parens.
5773 // FIXME: Revisit this once core issue 1488 is resolved.
5774 if (D.hasEllipsis() && D.hasGroupingParens())
5775 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5776 diag::ext_abstract_pack_declarator_parens);
Chris Lattneracd58a32006-08-06 17:24:14 +00005777 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00005778 if (Tok.getKind() == tok::annot_pragma_parser_crash)
David Blaikie5bd4c2a2012-08-21 18:56:49 +00005779 LLVM_BUILTIN_TRAP;
Richard Trieuf4b81d02014-06-24 23:14:24 +00005780 if (Tok.is(tok::l_square))
5781 return ParseMisplacedBracketDeclarator(D);
Faisal Vali421b2d12017-12-29 05:41:00 +00005782 if (D.getContext() == DeclaratorContext::MemberContext) {
Alex Lorenzf1278212017-04-11 15:01:53 +00005783 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5784 // treating these keyword as valid member names.
5785 if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus &&
5786 Tok.getIdentifierInfo() &&
5787 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5788 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5789 diag::err_expected_member_name_or_semi_objcxx_keyword)
5790 << Tok.getIdentifierInfo()
5791 << (D.getDeclSpec().isEmpty() ? SourceRange()
5792 : D.getDeclSpec().getSourceRange());
5793 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5794 D.SetRangeEnd(Tok.getLocation());
5795 ConsumeToken();
5796 goto PastIdentifier;
5797 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005798 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5799 diag::err_expected_member_name_or_semi)
Richard Trieua1342402014-05-02 23:40:32 +00005800 << (D.getDeclSpec().isEmpty() ? SourceRange()
5801 : D.getDeclSpec().getSourceRange());
Richard Trieuf4b81d02014-06-24 23:14:24 +00005802 } else if (getLangOpts().CPlusPlus) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00005803 if (Tok.isOneOf(tok::period, tok::arrow))
Richard Trieu9c672672013-01-26 02:31:38 +00005804 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
Richard Trieu2f586962013-09-05 02:31:33 +00005805 else {
5806 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5807 if (Tok.isAtStartOfLine() && Loc.isValid())
5808 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5809 << getLangOpts().CPlusPlus;
5810 else
Richard Trieuf4b81d02014-06-24 23:14:24 +00005811 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5812 diag::err_expected_unqualified_id)
Richard Trieu2f586962013-09-05 02:31:33 +00005813 << getLangOpts().CPlusPlus;
5814 }
Richard Trieuf4b81d02014-06-24 23:14:24 +00005815 } else {
5816 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5817 diag::err_expected_either)
5818 << tok::identifier << tok::l_paren;
5819 }
Craig Topper161e4db2014-05-21 06:02:52 +00005820 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattner8c5dd732008-11-11 06:13:16 +00005821 D.setInvalidType(true);
Chris Lattneracd58a32006-08-06 17:24:14 +00005822 }
Mike Stump11289f42009-09-09 15:08:12 +00005823
Argyrios Kyrtzidis9323b042008-11-26 22:40:03 +00005824 PastIdentifier:
Chris Lattneracd58a32006-08-06 17:24:14 +00005825 assert(D.isPastIdentifier() &&
5826 "Haven't past the location of the identifier yet?");
Mike Stump11289f42009-09-09 15:08:12 +00005827
Richard Smith7bdcc4a2012-04-10 01:32:12 +00005828 // Don't parse attributes unless we have parsed an unparenthesized name.
5829 if (D.hasName() && !D.getNumTypeObjects())
Richard Smith89645bc2013-01-02 12:01:23 +00005830 MaybeParseCXX11Attributes(D);
Alexis Hunt96d5c762009-11-21 08:43:09 +00005831
Chris Lattneracd58a32006-08-06 17:24:14 +00005832 while (1) {
Chris Lattner76c72282007-10-09 17:33:22 +00005833 if (Tok.is(tok::l_paren)) {
David Blaikie15a430a2011-12-04 05:04:18 +00005834 // Enter function-declaration scope, limiting any declarators to the
5835 // function prototype scope, including parameter declarators.
5836 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00005837 Scope::FunctionPrototypeScope|Scope::DeclScope|
5838 (D.isFunctionDeclaratorAFunctionDeclaration()
5839 ? Scope::FunctionDeclarationScope : 0));
5840
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005841 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5842 // In such a case, check if we actually have a function declarator; if it
5843 // is not, the declarator has been fully parsed.
Richard Smith943c4402012-07-30 21:30:52 +00005844 bool IsAmbiguous = false;
Richard Smith4f605af2012-08-18 00:55:03 +00005845 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5846 // The name of the declarator, if any, is tentatively declared within
5847 // a possible direct initializer.
5848 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5849 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5850 TentativelyDeclaredIdentifiers.pop_back();
5851 if (!IsFunctionDecl)
5852 break;
5853 }
John McCall084e83d2011-03-24 11:26:52 +00005854 ParsedAttributes attrs(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005855 BalancedDelimiterTracker T(*this, tok::l_paren);
5856 T.consumeOpen();
Richard Smith943c4402012-07-30 21:30:52 +00005857 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
David Blaikie15a430a2011-12-04 05:04:18 +00005858 PrototypeScope.Exit();
Chris Lattner76c72282007-10-09 17:33:22 +00005859 } else if (Tok.is(tok::l_square)) {
Chris Lattnere8074e62006-08-06 18:30:15 +00005860 ParseBracketDeclarator(D);
Chris Lattneracd58a32006-08-06 17:24:14 +00005861 } else {
5862 break;
5863 }
5864 }
Chad Rosierc1183952012-06-26 22:30:43 +00005865}
Chris Lattneracd58a32006-08-06 17:24:14 +00005866
Richard Smithbdb84f32016-07-22 23:36:59 +00005867void Parser::ParseDecompositionDeclarator(Declarator &D) {
5868 assert(Tok.is(tok::l_square));
5869
5870 // If this doesn't look like a structured binding, maybe it's a misplaced
5871 // array declarator.
5872 // FIXME: Consume the l_square first so we don't need extra lookahead for
5873 // this.
5874 if (!(NextToken().is(tok::identifier) &&
5875 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5876 !(NextToken().is(tok::r_square) &&
5877 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5878 return ParseMisplacedBracketDeclarator(D);
5879
5880 BalancedDelimiterTracker T(*this, tok::l_square);
5881 T.consumeOpen();
5882
5883 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5884 while (Tok.isNot(tok::r_square)) {
5885 if (!Bindings.empty()) {
5886 if (Tok.is(tok::comma))
5887 ConsumeToken();
5888 else {
5889 if (Tok.is(tok::identifier)) {
5890 SourceLocation EndLoc = getEndOfPreviousToken();
5891 Diag(EndLoc, diag::err_expected)
5892 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5893 } else {
5894 Diag(Tok, diag::err_expected_comma_or_rsquare);
5895 }
5896
5897 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5898 StopAtSemi | StopBeforeMatch);
5899 if (Tok.is(tok::comma))
5900 ConsumeToken();
5901 else if (Tok.isNot(tok::identifier))
5902 break;
5903 }
5904 }
5905
5906 if (Tok.isNot(tok::identifier)) {
5907 Diag(Tok, diag::err_expected) << tok::identifier;
5908 break;
5909 }
5910
5911 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
5912 ConsumeToken();
5913 }
5914
5915 if (Tok.isNot(tok::r_square))
5916 // We've already diagnosed a problem here.
5917 T.skipToEnd();
5918 else {
5919 // C++17 does not allow the identifier-list in a structured binding
5920 // to be empty.
5921 if (Bindings.empty())
5922 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
5923
5924 T.consumeClose();
5925 }
5926
5927 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
5928 T.getCloseLocation());
5929}
5930
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005931/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5932/// only called before the identifier, so these are most likely just grouping
Mike Stump11289f42009-09-09 15:08:12 +00005933/// parens for precedence. If we find that these are actually function
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005934/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5935///
5936/// direct-declarator:
5937/// '(' declarator ')'
5938/// [GNU] '(' attributes declarator ')'
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005939/// direct-declarator '(' parameter-type-list ')'
5940/// direct-declarator '(' identifier-list[opt] ')'
5941/// [GNU] direct-declarator '(' parameter-forward-declarations
5942/// parameter-type-list[opt] ')'
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005943///
5944void Parser::ParseParenDeclarator(Declarator &D) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00005945 BalancedDelimiterTracker T(*this, tok::l_paren);
5946 T.consumeOpen();
5947
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005948 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
Mike Stump11289f42009-09-09 15:08:12 +00005949
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005950 // Eat any attributes before we look at whether this is a grouping or function
5951 // declarator paren. If this is a grouping paren, the attribute applies to
5952 // the type being built up, for example:
5953 // int (__attribute__(()) *x)(long y)
5954 // If this ends up not being a grouping paren, the attribute applies to the
5955 // first argument, for example:
5956 // int (__attribute__(()) int x)
5957 // In either case, we need to eat any attributes to be able to determine what
5958 // sort of paren this is.
5959 //
John McCall084e83d2011-03-24 11:26:52 +00005960 ParsedAttributes attrs(AttrFactory);
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005961 bool RequiresArg = false;
5962 if (Tok.is(tok::kw___attribute)) {
John McCall53fa7142010-12-24 02:08:15 +00005963 ParseGNUAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00005964
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00005965 // We require that the argument list (if this is a non-grouping paren) be
5966 // present even if the attribute list was empty.
5967 RequiresArg = true;
5968 }
Chad Rosiereea9ca72012-12-21 21:22:20 +00005969
Steve Naroff44ac7772008-12-25 14:16:32 +00005970 // Eat any Microsoft extensions.
Chad Rosiereea9ca72012-12-21 21:22:20 +00005971 ParseMicrosoftTypeAttributes(attrs);
5972
Dawn Perchik335e16b2010-09-03 01:29:35 +00005973 // Eat any Borland extensions.
Ted Kremenek5eec2b02010-11-10 05:59:39 +00005974 if (Tok.is(tok::kw___pascal))
John McCall53fa7142010-12-24 02:08:15 +00005975 ParseBorlandTypeAttributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00005976
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005977 // If we haven't past the identifier yet (or where the identifier would be
5978 // stored, if this is an abstract declarator), then this is probably just
5979 // grouping parens. However, if this could be an abstract-declarator, then
5980 // this could also be the start of function arguments (consider 'void()').
5981 bool isGrouping;
Mike Stump11289f42009-09-09 15:08:12 +00005982
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005983 if (!D.mayOmitIdentifier()) {
5984 // If this can't be an abstract-declarator, this *must* be a grouping
5985 // paren, because we haven't seen the identifier yet.
5986 isGrouping = true;
5987 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
Richard Smith43f340f2012-03-27 23:05:05 +00005988 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5989 NextToken().is(tok::r_paren)) || // C++ int(...)
Richard Smith2620cd92012-04-11 04:01:28 +00005990 isDeclarationSpecifier() || // 'int(int)' is a function.
5991 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00005992 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5993 // considered to be a type, not a K&R identifier-list.
5994 isGrouping = false;
5995 } else {
5996 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5997 isGrouping = true;
5998 }
Mike Stump11289f42009-09-09 15:08:12 +00005999
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006000 // If this is a grouping paren, handle:
6001 // direct-declarator: '(' declarator ')'
6002 // direct-declarator: '(' attributes declarator ')'
6003 if (isGrouping) {
Richard Smith0efa75c2012-03-29 01:16:42 +00006004 SourceLocation EllipsisLoc = D.getEllipsisLoc();
6005 D.setEllipsisLoc(SourceLocation());
6006
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006007 bool hadGroupingParens = D.hasGroupingParens();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006008 D.setGroupingParens(true);
Sebastian Redlbd150f42008-11-21 19:14:01 +00006009 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006010 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006011 T.consumeClose();
Chad Rosierc1183952012-06-26 22:30:43 +00006012 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006013 T.getCloseLocation()),
6014 attrs, T.getCloseLocation());
Argyrios Kyrtzidis8ae36842008-10-07 10:21:57 +00006015
6016 D.setGroupingParens(hadGroupingParens);
Richard Smith0efa75c2012-03-29 01:16:42 +00006017
6018 // An ellipsis cannot be placed outside parentheses.
6019 if (EllipsisLoc.isValid())
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +00006020 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
Richard Smith0efa75c2012-03-29 01:16:42 +00006021
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006022 return;
6023 }
Mike Stump11289f42009-09-09 15:08:12 +00006024
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006025 // Okay, if this wasn't a grouping paren, it must be the start of a function
6026 // argument list. Recognize that this declarator will never have an
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006027 // identifier (and remember where it would have been), then call into
6028 // ParseFunctionDeclarator to handle of argument list.
Craig Topper161e4db2014-05-21 06:02:52 +00006029 D.SetIdentifier(nullptr, Tok.getLocation());
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006030
David Blaikie15a430a2011-12-04 05:04:18 +00006031 // Enter function-declaration scope, limiting any declarators to the
6032 // function prototype scope, including parameter declarators.
6033 ParseScope PrototypeScope(this,
Richard Smithe233fbf2013-01-28 22:42:45 +00006034 Scope::FunctionPrototypeScope | Scope::DeclScope |
6035 (D.isFunctionDeclaratorAFunctionDeclaration()
6036 ? Scope::FunctionDeclarationScope : 0));
Richard Smith943c4402012-07-30 21:30:52 +00006037 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
David Blaikie15a430a2011-12-04 05:04:18 +00006038 PrototypeScope.Exit();
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006039}
6040
6041/// ParseFunctionDeclarator - We are after the identifier and have parsed the
6042/// declarator D up to a paren, which indicates that we are parsing function
6043/// arguments.
Chris Lattneracd58a32006-08-06 17:24:14 +00006044///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006045/// If FirstArgAttrs is non-null, then the caller parsed those arguments
6046/// immediately after the open paren - they should be considered to be the
6047/// first argument of a parameter.
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006048///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006049/// If RequiresArg is true, then the first argument of the function is required
6050/// to be present and required to not be an identifier list.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006051///
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006052/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6053/// (C++11) ref-qualifier[opt], exception-specification[opt],
6054/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
6055///
6056/// [C++11] exception-specification:
Douglas Gregor9e66af42011-07-05 16:44:18 +00006057/// dynamic-exception-specification
6058/// noexcept-specification
6059///
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006060void Parser::ParseFunctionDeclarator(Declarator &D,
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006061 ParsedAttributes &FirstArgAttrs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006062 BalancedDelimiterTracker &Tracker,
Richard Smith943c4402012-07-30 21:30:52 +00006063 bool IsAmbiguous,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006064 bool RequiresArg) {
Chad Rosierc1183952012-06-26 22:30:43 +00006065 assert(getCurScope()->isFunctionPrototypeScope() &&
David Blaikie15a430a2011-12-04 05:04:18 +00006066 "Should call from a Function scope");
Douglas Gregor9e66af42011-07-05 16:44:18 +00006067 // lparen is already consumed!
6068 assert(D.isPastIdentifier() && "Should not call before identifier!");
6069
6070 // This should be true when the function has typed arguments.
6071 // Otherwise, it is treated as a K&R-style function.
6072 bool HasProto = false;
6073 // Build up an array of information about the parsed arguments.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006074 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006075 // Remember where we see an ellipsis, if any.
6076 SourceLocation EllipsisLoc;
6077
6078 DeclSpec DS(AttrFactory);
6079 bool RefQualifierIsLValueRef = true;
6080 SourceLocation RefQualifierLoc;
Douglas Gregore248eea2011-10-19 06:04:55 +00006081 SourceLocation ConstQualifierLoc;
6082 SourceLocation VolatileQualifierLoc;
Hal Finkel23a07392014-10-20 17:32:04 +00006083 SourceLocation RestrictQualifierLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006084 ExceptionSpecificationType ESpecType = EST_None;
6085 SourceRange ESpecRange;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006086 SmallVector<ParsedType, 2> DynamicExceptions;
6087 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006088 ExprResult NoexceptExpr;
Hans Wennborgdcfba332015-10-06 23:40:43 +00006089 CachedTokens *ExceptionSpecTokens = nullptr;
Aaron Ballman606093a2017-10-15 15:01:42 +00006090 ParsedAttributesWithRange FnAttrs(AttrFactory);
Richard Smith700537c2012-06-12 01:51:59 +00006091 TypeResult TrailingReturnType;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006092
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006093 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6094 EndLoc is the end location for the function declarator.
6095 They differ for trailing return types. */
6096 SourceLocation StartLoc, LocalEndLoc, EndLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006097 SourceLocation LParenLoc, RParenLoc;
6098 LParenLoc = Tracker.getOpenLocation();
6099 StartLoc = LParenLoc;
6100
Douglas Gregor9e66af42011-07-05 16:44:18 +00006101 if (isFunctionDeclaratorIdentifierList()) {
6102 if (RequiresArg)
6103 Diag(Tok, diag::err_argument_required_after_attribute);
6104
6105 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6106
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006107 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006108 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006109 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006110 EndLoc = RParenLoc;
Aaron Ballman606093a2017-10-15 15:01:42 +00006111
6112 // If there are attributes following the identifier list, parse them and
6113 // prohibit them.
6114 MaybeParseCXX11Attributes(FnAttrs);
6115 ProhibitAttributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006116 } else {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006117 if (Tok.isNot(tok::r_paren))
Faisal Vali2b391ab2013-09-26 19:54:12 +00006118 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
6119 EllipsisLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006120 else if (RequiresArg)
6121 Diag(Tok, diag::err_argument_required_after_attribute);
6122
Alexey Bader1f277942017-10-11 11:16:31 +00006123 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6124 || getLangOpts().OpenCL;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006125
6126 // If we have the closing ')', eat it.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006127 Tracker.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006128 RParenLoc = Tracker.getCloseLocation();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006129 LocalEndLoc = RParenLoc;
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006130 EndLoc = RParenLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006131
David Blaikiebbafb8a2012-03-11 07:00:24 +00006132 if (getLangOpts().CPlusPlus) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006133 // FIXME: Accept these components in any order, and produce fixits to
6134 // correct the order if the user gets it wrong. Ideally we should deal
Ehsan Akhgari93ed5cf2015-03-25 00:53:27 +00006135 // with the pure-specifier in the same way.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006136
6137 // Parse cv-qualifier-seq[opt].
Aaron Ballman08b06592014-07-22 12:44:22 +00006138 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
Alex Lorenz8f4d3992017-02-13 23:19:40 +00006139 /*AtomicAllowed*/ false,
6140 /*IdentifierRequired=*/false,
6141 llvm::function_ref<void()>([&]() {
6142 Actions.CodeCompleteFunctionQualifiers(DS, D);
6143 }));
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006144 if (!DS.getSourceRange().getEnd().isInvalid()) {
6145 EndLoc = DS.getSourceRange().getEnd();
6146 ConstQualifierLoc = DS.getConstSpecLoc();
6147 VolatileQualifierLoc = DS.getVolatileSpecLoc();
Hal Finkel23a07392014-10-20 17:32:04 +00006148 RestrictQualifierLoc = DS.getRestrictSpecLoc();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006149 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006150
6151 // Parse ref-qualifier[opt].
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006152 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
Douglas Gregor9e66af42011-07-05 16:44:18 +00006153 EndLoc = RefQualifierLoc;
Douglas Gregor9e66af42011-07-05 16:44:18 +00006154
Douglas Gregor3024f072012-04-16 07:05:22 +00006155 // C++11 [expr.prim.general]p3:
Chad Rosierc1183952012-06-26 22:30:43 +00006156 // If a declaration declares a member function or member function
6157 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00006158 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Chad Rosierc1183952012-06-26 22:30:43 +00006159 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00006160 // declarator.
Richard Smithad1bbb92013-03-15 00:41:52 +00006161 // FIXME: currently, "static" case isn't handled correctly.
Chad Rosierc1183952012-06-26 22:30:43 +00006162 bool IsCXX11MemberFunction =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006163 getLangOpts().CPlusPlus11 &&
Richard Smith990a6922014-01-17 21:01:18 +00006164 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
Faisal Vali421b2d12017-12-29 05:41:00 +00006165 (D.getContext() == DeclaratorContext::MemberContext
Richard Smithad1bbb92013-03-15 00:41:52 +00006166 ? !D.getDeclSpec().isFriendSpecified()
Faisal Vali421b2d12017-12-29 05:41:00 +00006167 : D.getContext() == DeclaratorContext::FileContext &&
Richard Smithad1bbb92013-03-15 00:41:52 +00006168 D.getCXXScopeSpec().isValid() &&
6169 Actions.CurContext->isRecord());
Douglas Gregor3024f072012-04-16 07:05:22 +00006170 Sema::CXXThisScopeRAII ThisScope(Actions,
6171 dyn_cast<CXXRecordDecl>(Actions.CurContext),
Richard Smith01141a92013-01-14 01:55:13 +00006172 DS.getTypeQualifiers() |
Richard Smith034185c2013-04-21 01:08:50 +00006173 (D.getDeclSpec().isConstexprSpecified() &&
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006174 !getLangOpts().CPlusPlus14
Richard Smith01141a92013-01-14 01:55:13 +00006175 ? Qualifiers::Const : 0),
Douglas Gregor3024f072012-04-16 07:05:22 +00006176 IsCXX11MemberFunction);
Richard Smith2331bbf2012-05-02 22:22:32 +00006177
Douglas Gregor9e66af42011-07-05 16:44:18 +00006178 // Parse exception-specification[opt].
Richard Smith0b3a4622014-11-13 20:01:57 +00006179 bool Delayed = D.isFirstDeclarationOfMember() &&
Richard Smith3ef3e892014-11-20 22:32:11 +00006180 D.isFunctionDeclaratorAFunctionDeclaration();
6181 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6182 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6183 GetLookAheadToken(1).is(tok::l_paren) &&
6184 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6185 GetLookAheadToken(3).is(tok::l_paren) &&
6186 GetLookAheadToken(4).is(tok::identifier) &&
6187 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6188 // HACK: We've got an exception-specification
6189 // noexcept(noexcept(swap(...)))
6190 // or
6191 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6192 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6193 // for 'swap' will only find the function we're currently declaring,
6194 // whereas it expects to find a non-member swap through ADL. Turn off
6195 // delayed parsing to give it a chance to find what it expects.
6196 Delayed = false;
6197 }
Richard Smith0b3a4622014-11-13 20:01:57 +00006198 ESpecType = tryParseExceptionSpecification(Delayed,
6199 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00006200 DynamicExceptions,
6201 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00006202 NoexceptExpr,
6203 ExceptionSpecTokens);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006204 if (ESpecType != EST_None)
6205 EndLoc = ESpecRange.getEnd();
6206
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006207 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6208 // after the exception-specification.
Richard Smith89645bc2013-01-02 12:01:23 +00006209 MaybeParseCXX11Attributes(FnAttrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006210
Douglas Gregor9e66af42011-07-05 16:44:18 +00006211 // Parse trailing-return-type[opt].
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006212 LocalEndLoc = EndLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006213 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
Richard Smith5d164bc2011-10-15 05:09:34 +00006214 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
Faisal Vali090da2d2018-01-01 18:23:28 +00006215 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006216 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006217 LocalEndLoc = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00006218 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00006219 TrailingReturnType =
6220 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006221 EndLoc = Range.getEnd();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006222 }
Aaron Ballman606093a2017-10-15 15:01:42 +00006223 } else if (standardAttributesAllowed()) {
6224 MaybeParseCXX11Attributes(FnAttrs);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006225 }
Douglas Gregor9e66af42011-07-05 16:44:18 +00006226 }
6227
Reid Kleckner078aea92016-12-09 17:14:05 +00006228 // Collect non-parameter declarations from the prototype if this is a function
6229 // declaration. They will be moved into the scope of the function. Only do
6230 // this in C and not C++, where the decls will continue to live in the
6231 // surrounding context.
6232 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6233 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6234 !getLangOpts().CPlusPlus) {
6235 for (Decl *D : getCurScope()->decls()) {
6236 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6237 if (!ND || isa<ParmVarDecl>(ND))
6238 continue;
6239 DeclsInPrototype.push_back(ND);
6240 }
6241 }
6242
Douglas Gregor9e66af42011-07-05 16:44:18 +00006243 // Remember that we parsed a function type, and remember the attributes.
6244 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006245 IsAmbiguous,
6246 LParenLoc,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006247 ParamInfo.data(), ParamInfo.size(),
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00006248 EllipsisLoc, RParenLoc,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006249 DS.getTypeQualifiers(),
6250 RefQualifierIsLValueRef,
Douglas Gregore248eea2011-10-19 06:04:55 +00006251 RefQualifierLoc, ConstQualifierLoc,
6252 VolatileQualifierLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00006253 RestrictQualifierLoc,
Douglas Gregorad69e652011-07-13 21:47:47 +00006254 /*MutableLoc=*/SourceLocation(),
Nathan Wilsone23a9a42015-08-26 04:19:36 +00006255 ESpecType, ESpecRange,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006256 DynamicExceptions.data(),
6257 DynamicExceptionRanges.data(),
6258 DynamicExceptions.size(),
6259 NoexceptExpr.isUsable() ?
Craig Topper161e4db2014-05-21 06:02:52 +00006260 NoexceptExpr.get() : nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00006261 ExceptionSpecTokens,
Reid Kleckner078aea92016-12-09 17:14:05 +00006262 DeclsInPrototype,
Abramo Bagnara2fc03ca2012-10-15 21:05:46 +00006263 StartLoc, LocalEndLoc, D,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006264 TrailingReturnType),
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006265 FnAttrs, EndLoc);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006266}
6267
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006268/// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6269/// true if a ref-qualifier is found.
6270bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6271 SourceLocation &RefQualifierLoc) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00006272 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
Ehsan Akhgaric07d1e22015-03-25 00:53:33 +00006273 Diag(Tok, getLangOpts().CPlusPlus11 ?
6274 diag::warn_cxx98_compat_ref_qualifier :
6275 diag::ext_ref_qualifier);
6276
6277 RefQualifierIsLValueRef = Tok.is(tok::amp);
6278 RefQualifierLoc = ConsumeToken();
6279 return true;
6280 }
6281 return false;
6282}
6283
Douglas Gregor9e66af42011-07-05 16:44:18 +00006284/// isFunctionDeclaratorIdentifierList - This parameter list may have an
6285/// identifier list form for a K&R-style function: void foo(a,b,c)
6286///
6287/// Note that identifier-lists are only allowed for normal declarators, not for
6288/// abstract-declarators.
6289bool Parser::isFunctionDeclaratorIdentifierList() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006290 return !getLangOpts().CPlusPlus
Douglas Gregor9e66af42011-07-05 16:44:18 +00006291 && Tok.is(tok::identifier)
6292 && !TryAltiVecVectorToken()
6293 // K&R identifier lists can't have typedefs as identifiers, per C99
6294 // 6.7.5.3p11.
6295 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6296 // Identifier lists follow a really simple grammar: the identifiers can
6297 // be followed *only* by a ", identifier" or ")". However, K&R
6298 // identifier lists are really rare in the brave new modern world, and
6299 // it is very common for someone to typo a type in a non-K&R style
6300 // list. If we are presented with something like: "void foo(intptr x,
6301 // float y)", we don't want to start parsing the function declarator as
6302 // though it is a K&R style declarator just because intptr is an
6303 // invalid type.
6304 //
6305 // To handle this, we check to see if the token after the first
6306 // identifier is a "," or ")". Only then do we parse it as an
6307 // identifier list.
Bruno Cardoso Lopes218c8742016-09-13 20:04:35 +00006308 && (!Tok.is(tok::eof) &&
6309 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006310}
6311
6312/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6313/// we found a K&R-style identifier list instead of a typed parameter list.
6314///
6315/// After returning, ParamInfo will hold the parsed parameters.
6316///
6317/// identifier-list: [C99 6.7.5]
6318/// identifier
6319/// identifier-list ',' identifier
6320///
6321void Parser::ParseFunctionDeclaratorIdentifierList(
6322 Declarator &D,
Craig Topper5603df42013-07-05 19:34:19 +00006323 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006324 // If there was no identifier specified for the declarator, either we are in
6325 // an abstract-declarator, or we are in a parameter declarator which was found
6326 // to be abstract. In abstract-declarators, identifier lists are not valid:
6327 // diagnose this.
6328 if (!D.getIdentifier())
6329 Diag(Tok, diag::ext_ident_list_in_param);
6330
6331 // Maintain an efficient lookup of params we have seen so far.
6332 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6333
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006334 do {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006335 // If this isn't an identifier, report the error and skip until ')'.
6336 if (Tok.isNot(tok::identifier)) {
Alp Tokerec543272013-12-24 09:48:30 +00006337 Diag(Tok, diag::err_expected) << tok::identifier;
Alexey Bataevee6507d2013-11-18 08:17:37 +00006338 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor9e66af42011-07-05 16:44:18 +00006339 // Forget we parsed anything.
6340 ParamInfo.clear();
6341 return;
6342 }
6343
6344 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6345
6346 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6347 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6348 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6349
6350 // Verify that the argument identifier has not already been mentioned.
David Blaikie82e95a32014-11-19 07:49:47 +00006351 if (!ParamsSoFar.insert(ParmII).second) {
Douglas Gregor9e66af42011-07-05 16:44:18 +00006352 Diag(Tok, diag::err_param_redefinition) << ParmII;
6353 } else {
6354 // Remember this identifier in ParamInfo.
6355 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6356 Tok.getLocation(),
Craig Topper161e4db2014-05-21 06:02:52 +00006357 nullptr));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006358 }
6359
6360 // Eat the identifier.
6361 ConsumeToken();
Douglas Gregor9e66af42011-07-05 16:44:18 +00006362 // The list continues if we see a comma.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006363 } while (TryConsumeToken(tok::comma));
Douglas Gregor9e66af42011-07-05 16:44:18 +00006364}
6365
6366/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6367/// after the opening parenthesis. This function will not parse a K&R-style
6368/// identifier list.
6369///
Richard Smith2620cd92012-04-11 04:01:28 +00006370/// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6371/// caller parsed those arguments immediately after the open paren - they should
6372/// be considered to be part of the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006373///
6374/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6375/// be the location of the ellipsis, if any was parsed.
6376///
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006377/// parameter-type-list: [C99 6.7.5]
6378/// parameter-list
6379/// parameter-list ',' '...'
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006380/// [C++] parameter-list '...'
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006381///
6382/// parameter-list: [C99 6.7.5]
6383/// parameter-declaration
6384/// parameter-list ',' parameter-declaration
6385///
6386/// parameter-declaration: [C99 6.7.5]
6387/// declaration-specifiers declarator
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006388/// [C++] declaration-specifiers declarator '=' assignment-expression
Sebastian Redldb63af22012-03-14 15:54:00 +00006389/// [C++11] initializer-clause
Chris Lattnere37e2332006-08-15 04:50:22 +00006390/// [GNU] declaration-specifiers declarator attributes
Sebastian Redlf769df52009-03-24 22:27:57 +00006391/// declaration-specifiers abstract-declarator[opt]
6392/// [C++] declaration-specifiers abstract-declarator[opt]
Chris Lattner58258242008-04-10 02:22:51 +00006393/// '=' assignment-expression
Chris Lattnere37e2332006-08-15 04:50:22 +00006394/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
Richard Smith2620cd92012-04-11 04:01:28 +00006395/// [C++11] attribute-specifier-seq parameter-declaration
Chris Lattnerc0acd3d2006-07-31 05:13:43 +00006396///
Douglas Gregor9e66af42011-07-05 16:44:18 +00006397void Parser::ParseParameterDeclarationClause(
6398 Declarator &D,
Richard Smith2620cd92012-04-11 04:01:28 +00006399 ParsedAttributes &FirstArgAttrs,
Craig Topper5603df42013-07-05 19:34:19 +00006400 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
Douglas Gregor9e66af42011-07-05 16:44:18 +00006401 SourceLocation &EllipsisLoc) {
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006402 do {
6403 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6404 // before deciding this was a parameter-declaration-clause.
6405 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Chris Lattner371ed4e2008-04-06 06:57:35 +00006406 break;
Mike Stump11289f42009-09-09 15:08:12 +00006407
Chris Lattner371ed4e2008-04-06 06:57:35 +00006408 // Parse the declaration-specifiers.
John McCall28a6aea2009-11-04 02:18:39 +00006409 // Just use the ParsingDeclaration "scope" of the declarator.
John McCall084e83d2011-03-24 11:26:52 +00006410 DeclSpec DS(AttrFactory);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006411
Richard Smith2620cd92012-04-11 04:01:28 +00006412 // Parse any C++11 attributes.
Richard Smith89645bc2013-01-02 12:01:23 +00006413 MaybeParseCXX11Attributes(DS.getAttributes());
Richard Smith2620cd92012-04-11 04:01:28 +00006414
John McCall53fa7142010-12-24 02:08:15 +00006415 // Skip any Microsoft attributes before a param.
Chad Rosierf8a2e702012-12-20 20:37:53 +00006416 MaybeParseMicrosoftAttributes(DS.getAttributes());
John McCall53fa7142010-12-24 02:08:15 +00006417
6418 SourceLocation DSStart = Tok.getLocation();
Chris Lattner8ff2c6c2008-10-20 02:05:46 +00006419
6420 // If the caller parsed attributes for the first argument, add them now.
John McCall53fa7142010-12-24 02:08:15 +00006421 // Take them so that we only apply the attributes to the first parameter.
Douglas Gregor9e66af42011-07-05 16:44:18 +00006422 // FIXME: If we can leave the attributes in the token stream somehow, we can
Richard Smith2620cd92012-04-11 04:01:28 +00006423 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6424 // too much hassle.
6425 DS.takeAttributesFrom(FirstArgAttrs);
John McCall53fa7142010-12-24 02:08:15 +00006426
Faisal Valia534f072018-04-26 00:42:40 +00006427 ParseDeclarationSpecifiers(DS);
Mike Stump11289f42009-09-09 15:08:12 +00006428
Faisal Vali2b391ab2013-09-26 19:54:12 +00006429
6430 // Parse the declarator. This is "PrototypeContext" or
6431 // "LambdaExprParameterContext", because we must accept either
6432 // 'declarator' or 'abstract-declarator' here.
Faisal Vali421b2d12017-12-29 05:41:00 +00006433 Declarator ParmDeclarator(
6434 DS, D.getContext() == DeclaratorContext::LambdaExprContext
6435 ? DeclaratorContext::LambdaExprParameterContext
6436 : DeclaratorContext::PrototypeContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00006437 ParseDeclarator(ParmDeclarator);
Chris Lattner371ed4e2008-04-06 06:57:35 +00006438
6439 // Parse GNU attributes, if present.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006440 MaybeParseGNUAttributes(ParmDeclarator);
Mike Stump11289f42009-09-09 15:08:12 +00006441
Chris Lattner371ed4e2008-04-06 06:57:35 +00006442 // Remember this parsed parameter in ParamInfo.
Faisal Vali2b391ab2013-09-26 19:54:12 +00006443 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
Mike Stump11289f42009-09-09 15:08:12 +00006444
Douglas Gregor4d87df52008-12-16 21:30:33 +00006445 // DefArgToks is used when the parsing of default arguments needs
6446 // to be delayed.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006447 std::unique_ptr<CachedTokens> DefArgToks;
Douglas Gregor4d87df52008-12-16 21:30:33 +00006448
Chris Lattner371ed4e2008-04-06 06:57:35 +00006449 // If no parameter was specified, verify that *something* was specified,
6450 // otherwise we have a missing type and identifier.
Craig Topper161e4db2014-05-21 06:02:52 +00006451 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
Faisal Vali2b391ab2013-09-26 19:54:12 +00006452 ParmDeclarator.getNumTypeObjects() == 0) {
Chris Lattner371ed4e2008-04-06 06:57:35 +00006453 // Completely missing, emit error.
6454 Diag(DSStart, diag::err_missing_param);
6455 } else {
6456 // Otherwise, we have something. Add it and let semantic analysis try
6457 // to grok it and add the result to the ParamInfo we are building.
Mike Stump11289f42009-09-09 15:08:12 +00006458
Richard Smith36ee9fb2014-08-11 23:30:23 +00006459 // Last chance to recover from a misplaced ellipsis in an attempted
6460 // parameter pack declaration.
6461 if (Tok.is(tok::ellipsis) &&
6462 (NextToken().isNot(tok::r_paren) ||
6463 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6464 !Actions.isUnexpandedParameterPackPermitted())) &&
6465 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6466 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6467
Chris Lattner371ed4e2008-04-06 06:57:35 +00006468 // Inform the actions module about the parameter declarator, so it gets
6469 // added to the current scope.
Richard Smith95e1fb02014-08-27 03:23:12 +00006470 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006471 // Parse the default argument, if any. We parse the default
6472 // arguments in all dialects; the semantic analysis in
6473 // ActOnParamDefaultArgument will reject the default argument in
6474 // C.
6475 if (Tok.is(tok::equal)) {
Douglas Gregor58354032008-12-24 00:01:03 +00006476 SourceLocation EqualLoc = Tok.getLocation();
6477
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006478 // Parse the default argument
Faisal Vali421b2d12017-12-29 05:41:00 +00006479 if (D.getContext() == DeclaratorContext::MemberContext) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006480 // If we're inside a class definition, cache the tokens
6481 // corresponding to the default argument. We'll actually parse
6482 // them when we see the end of the class definition.
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006483 DefArgToks.reset(new CachedTokens);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006484
David Majnemer906ed272015-01-13 05:28:24 +00006485 SourceLocation ArgStartLoc = NextToken().getLocation();
Richard Smith1fff95c2013-09-12 23:28:08 +00006486 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006487 DefArgToks.reset();
Serge Pavlovb4b35782014-07-22 01:54:49 +00006488 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006489 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006490 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
David Majnemer906ed272015-01-13 05:28:24 +00006491 ArgStartLoc);
Argyrios Kyrtzidis249179c2010-08-06 09:47:24 +00006492 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006493 } else {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006494 // Consume the '='.
Douglas Gregor58354032008-12-24 00:01:03 +00006495 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +00006496
Chad Rosierc1183952012-06-26 22:30:43 +00006497 // The argument isn't actually potentially evaluated unless it is
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006498 // used.
Faisal Valid143a0c2017-04-01 21:30:49 +00006499 EnterExpressionEvaluationContext Eval(
6500 Actions,
6501 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6502 Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00006503
Sebastian Redldb63af22012-03-14 15:54:00 +00006504 ExprResult DefArgResult;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006505 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006506 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redldb63af22012-03-14 15:54:00 +00006507 DefArgResult = ParseBraceInitializer();
Sebastian Redl1678d5f2012-03-18 22:25:45 +00006508 } else
Sebastian Redldb63af22012-03-14 15:54:00 +00006509 DefArgResult = ParseAssignmentExpression();
Kaelyn Takatab16e6322014-11-20 22:06:40 +00006510 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006511 if (DefArgResult.isInvalid()) {
Serge Pavlovb4b35782014-07-22 01:54:49 +00006512 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
Alexey Bataevee6507d2013-11-18 08:17:37 +00006513 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006514 } else {
6515 // Inform the actions module about the default argument
6516 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006517 DefArgResult.get());
Douglas Gregor4d87df52008-12-16 21:30:33 +00006518 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006519 }
6520 }
Mike Stump11289f42009-09-09 15:08:12 +00006521
6522 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
Faisal Vali2b391ab2013-09-26 19:54:12 +00006523 ParmDeclarator.getIdentifierLoc(),
Malcolm Parsonsff0382c2016-11-17 17:52:58 +00006524 Param, std::move(DefArgToks)));
Chris Lattner371ed4e2008-04-06 06:57:35 +00006525 }
6526
Richard Smith36ee9fb2014-08-11 23:30:23 +00006527 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6528 if (!getLangOpts().CPlusPlus) {
6529 // We have ellipsis without a preceding ',', which is ill-formed
6530 // in C. Complain and provide the fix.
6531 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6532 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6533 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6534 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6535 // It looks like this was supposed to be a parameter pack. Warn and
6536 // point out where the ellipsis should have gone.
6537 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6538 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6539 << ParmEllipsis.isValid() << ParmEllipsis;
6540 if (ParmEllipsis.isValid()) {
6541 Diag(ParmEllipsis,
6542 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6543 } else {
6544 Diag(ParmDeclarator.getIdentifierLoc(),
6545 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6546 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6547 "...")
6548 << !ParmDeclarator.hasName();
6549 }
6550 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006551 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
Richard Smith36ee9fb2014-08-11 23:30:23 +00006552 }
6553
6554 // We can't have any more parameters after an ellipsis.
Douglas Gregor9bfc2e52009-09-22 21:41:40 +00006555 break;
6556 }
Mike Stump11289f42009-09-09 15:08:12 +00006557
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006558 // If the next token is a comma, consume it and keep reading arguments.
6559 } while (TryConsumeToken(tok::comma));
Chris Lattner6c940e62008-04-06 06:34:08 +00006560}
Chris Lattnerc0a1c7d2008-04-06 05:45:57 +00006561
Chris Lattnere8074e62006-08-06 18:30:15 +00006562/// [C90] direct-declarator '[' constant-expression[opt] ']'
6563/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6564/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6565/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6566/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006567/// [C++11] direct-declarator '[' constant-expression[opt] ']'
6568/// attribute-specifier-seq[opt]
Chris Lattnere8074e62006-08-06 18:30:15 +00006569void Parser::ParseBracketDeclarator(Declarator &D) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00006570 if (CheckProhibitedCXX11Attribute())
6571 return;
6572
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006573 BalancedDelimiterTracker T(*this, tok::l_square);
6574 T.consumeOpen();
Mike Stump11289f42009-09-09 15:08:12 +00006575
Chris Lattner84a11622008-12-18 07:27:21 +00006576 // C array syntax has many features, but by-far the most common is [] and [4].
6577 // This code does a fast path to handle some of the most obvious cases.
6578 if (Tok.getKind() == tok::r_square) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006579 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006580 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006581 MaybeParseCXX11Attributes(attrs);
Chad Rosierc1183952012-06-26 22:30:43 +00006582
Chris Lattner84a11622008-12-18 07:27:21 +00006583 // Remember that we parsed the empty array type.
Craig Topper161e4db2014-05-21 06:02:52 +00006584 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006585 T.getOpenLocation(),
6586 T.getCloseLocation()),
6587 attrs, T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006588 return;
6589 } else if (Tok.getKind() == tok::numeric_constant &&
6590 GetLookAheadToken(1).is(tok::r_square)) {
6591 // [4] is very common. Parse the numeric constant expression.
Richard Smithbcc22fc2012-03-09 08:00:36 +00006592 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
Chris Lattner84a11622008-12-18 07:27:21 +00006593 ConsumeToken();
6594
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006595 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00006596 ParsedAttributes attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00006597 MaybeParseCXX11Attributes(attrs);
Mike Stump11289f42009-09-09 15:08:12 +00006598
Chris Lattner84a11622008-12-18 07:27:21 +00006599 // Remember that we parsed a array type, and remember its features.
Nikola Smiljanicc531dcc2013-01-11 08:33:05 +00006600 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006601 ExprRes.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006602 T.getOpenLocation(),
6603 T.getCloseLocation()),
6604 attrs, T.getCloseLocation());
Chris Lattner84a11622008-12-18 07:27:21 +00006605 return;
Benjamin Kramer72dae622016-02-18 15:30:24 +00006606 } else if (Tok.getKind() == tok::code_completion) {
6607 Actions.CodeCompleteBracketDeclarator(getCurScope());
6608 return cutOffParsing();
Chris Lattner84a11622008-12-18 07:27:21 +00006609 }
Mike Stump11289f42009-09-09 15:08:12 +00006610
Chris Lattnere8074e62006-08-06 18:30:15 +00006611 // If valid, this location is the position where we read the 'static' keyword.
6612 SourceLocation StaticLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006613 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006614
Chris Lattnere8074e62006-08-06 18:30:15 +00006615 // If there is a type-qualifier-list, read it now.
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006616 // Type qualifiers in an array subscript are a C99 feature.
John McCall084e83d2011-03-24 11:26:52 +00006617 DeclSpec DS(AttrFactory);
Aaron Ballman08b06592014-07-22 12:44:22 +00006618 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
Mike Stump11289f42009-09-09 15:08:12 +00006619
Chris Lattnere8074e62006-08-06 18:30:15 +00006620 // If we haven't already read 'static', check to see if there is one after the
6621 // type-qualifier-list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00006622 if (!StaticLoc.isValid())
6623 TryConsumeToken(tok::kw_static, StaticLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006624
Chris Lattnere8074e62006-08-06 18:30:15 +00006625 // Handle "direct-declarator [ type-qual-list[opt] * ]".
Chris Lattnere8074e62006-08-06 18:30:15 +00006626 bool isStar = false;
John McCalldadc5752010-08-24 06:29:42 +00006627 ExprResult NumElements;
Mike Stump11289f42009-09-09 15:08:12 +00006628
Chris Lattner521ff2b2008-04-06 05:26:30 +00006629 // Handle the case where we have '[*]' as the array size. However, a leading
6630 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
Sylvestre Ledru830885c2012-07-23 08:59:39 +00006631 // the token after the star is a ']'. Since stars in arrays are
Chris Lattner521ff2b2008-04-06 05:26:30 +00006632 // infrequent, use of lookahead is not costly here.
6633 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
Chris Lattnerc439f0d2008-04-06 05:27:21 +00006634 ConsumeToken(); // Eat the '*'.
Chris Lattner1906f802006-08-06 19:14:46 +00006635
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006636 if (StaticLoc.isValid()) {
Chris Lattner521ff2b2008-04-06 05:26:30 +00006637 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
Chris Lattnerb6ec4e72008-12-18 06:50:14 +00006638 StaticLoc = SourceLocation(); // Drop the static.
6639 }
Chris Lattner521ff2b2008-04-06 05:26:30 +00006640 isStar = true;
Chris Lattner76c72282007-10-09 17:33:22 +00006641 } else if (Tok.isNot(tok::r_square)) {
Chris Lattner84a11622008-12-18 07:27:21 +00006642 // Note, in C89, this production uses the constant-expr production instead
6643 // of assignment-expr. The only difference is that assignment-expr allows
6644 // things like '=' and '*='. Sema rejects these in C89 mode because they
6645 // are not i-c-e's, so we don't need to distinguish between the two here.
Mike Stump11289f42009-09-09 15:08:12 +00006646
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006647 // Parse the constant-expression or assignment-expression now (depending
6648 // on dialect).
David Blaikiebbafb8a2012-03-11 07:00:24 +00006649 if (getLangOpts().CPlusPlus) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006650 NumElements = ParseConstantExpression();
Eli Friedmane0afc982012-01-21 01:01:51 +00006651 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00006652 EnterExpressionEvaluationContext Unevaluated(
6653 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Kaelyn Takata15867822014-11-21 18:48:04 +00006654 NumElements =
6655 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Eli Friedmane0afc982012-01-21 01:01:51 +00006656 }
David Majnemerf9834d52014-08-08 07:21:18 +00006657 } else {
6658 if (StaticLoc.isValid()) {
6659 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6660 StaticLoc = SourceLocation(); // Drop the static.
6661 }
Chris Lattner62591722006-08-12 18:40:58 +00006662 }
Mike Stump11289f42009-09-09 15:08:12 +00006663
Chris Lattner62591722006-08-12 18:40:58 +00006664 // If there was an error parsing the assignment-expression, recover.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00006665 if (NumElements.isInvalid()) {
Chris Lattnercd2a8c52009-04-24 22:30:50 +00006666 D.setInvalidType(true);
Chris Lattner62591722006-08-12 18:40:58 +00006667 // If the expression was invalid, skip it.
Alexey Bataevee6507d2013-11-18 08:17:37 +00006668 SkipUntil(tok::r_square, StopAtSemi);
Chris Lattner62591722006-08-12 18:40:58 +00006669 return;
Chris Lattnere8074e62006-08-06 18:30:15 +00006670 }
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006671
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006672 T.consumeClose();
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006673
Jordan Rose303e2f12016-11-10 23:28:17 +00006674 MaybeParseCXX11Attributes(DS.getAttributes());
Alexis Hunt96d5c762009-11-21 08:43:09 +00006675
Chris Lattner84a11622008-12-18 07:27:21 +00006676 // Remember that we parsed a array type, and remember its features.
John McCall084e83d2011-03-24 11:26:52 +00006677 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
Chris Lattnercbc426d2006-12-02 06:43:02 +00006678 StaticLoc.isValid(), isStar,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006679 NumElements.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006680 T.getOpenLocation(),
6681 T.getCloseLocation()),
Jordan Rose303e2f12016-11-10 23:28:17 +00006682 DS.getAttributes(), T.getCloseLocation());
Chris Lattnere8074e62006-08-06 18:30:15 +00006683}
6684
Richard Trieuf4b81d02014-06-24 23:14:24 +00006685/// Diagnose brackets before an identifier.
6686void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6687 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6688 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6689
6690 SourceLocation StartBracketLoc = Tok.getLocation();
6691 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6692
6693 while (Tok.is(tok::l_square)) {
6694 ParseBracketDeclarator(TempDeclarator);
6695 }
6696
6697 // Stuff the location of the start of the brackets into the Declarator.
6698 // The diagnostics from ParseDirectDeclarator will make more sense if
6699 // they use this location instead.
6700 if (Tok.is(tok::semi))
6701 D.getName().EndLocation = StartBracketLoc;
6702
6703 SourceLocation SuggestParenLoc = Tok.getLocation();
6704
6705 // Now that the brackets are removed, try parsing the declarator again.
6706 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6707
6708 // Something went wrong parsing the brackets, in which case,
6709 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6710 // one here.
6711 if (TempDeclarator.getNumTypeObjects() == 0)
6712 return;
6713
6714 // Determine if parens will need to be suggested in the diagnostic.
6715 bool NeedParens = false;
6716 if (D.getNumTypeObjects() != 0) {
6717 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6718 case DeclaratorChunk::Pointer:
6719 case DeclaratorChunk::Reference:
6720 case DeclaratorChunk::BlockPointer:
6721 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00006722 case DeclaratorChunk::Pipe:
Richard Trieuf4b81d02014-06-24 23:14:24 +00006723 NeedParens = true;
6724 break;
6725 case DeclaratorChunk::Array:
6726 case DeclaratorChunk::Function:
6727 case DeclaratorChunk::Paren:
6728 break;
6729 }
6730 }
6731
6732 if (NeedParens) {
6733 // Create a DeclaratorChunk for the inserted parens.
6734 ParsedAttributes attrs(AttrFactory);
6735 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6736 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs,
6737 SourceLocation());
6738 }
6739
6740 // Adding back the bracket info to the end of the Declarator.
6741 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6742 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
6743 ParsedAttributes attrs(AttrFactory);
6744 attrs.set(Chunk.Common.AttrList);
6745 D.AddTypeInfo(Chunk, attrs, SourceLocation());
6746 }
6747
6748 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6749 // If parentheses are required, always suggest them.
6750 if (!D.getIdentifier() && !NeedParens)
6751 return;
6752
6753 SourceLocation EndBracketLoc = TempDeclarator.getLocEnd();
6754
6755 // Generate the move bracket error message.
6756 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
6757 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6758
6759 if (NeedParens) {
6760 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6761 << getLangOpts().CPlusPlus
6762 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6763 << FixItHint::CreateInsertion(EndLoc, ")")
6764 << FixItHint::CreateInsertionFromRange(
6765 EndLoc, CharSourceRange(BracketRange, true))
6766 << FixItHint::CreateRemoval(BracketRange);
6767 } else {
6768 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6769 << getLangOpts().CPlusPlus
6770 << FixItHint::CreateInsertionFromRange(
6771 EndLoc, CharSourceRange(BracketRange, true))
6772 << FixItHint::CreateRemoval(BracketRange);
6773 }
6774}
6775
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006776/// [GNU] typeof-specifier:
6777/// typeof ( expressions )
6778/// typeof ( type-name )
6779/// [GNU/C++] typeof unary-expression
Steve Naroffad373bd2007-07-31 12:34:36 +00006780///
6781void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
Chris Lattner76c72282007-10-09 17:33:22 +00006782 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006783 Token OpTok = Tok;
Steve Naroffad373bd2007-07-31 12:34:36 +00006784 SourceLocation StartLoc = ConsumeToken();
6785
John McCalle8595032010-01-13 20:03:27 +00006786 const bool hasParens = Tok.is(tok::l_paren);
6787
Faisal Valid143a0c2017-04-01 21:30:49 +00006788 EnterExpressionEvaluationContext Unevaluated(
6789 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6790 Sema::ReuseLambdaContextDecl);
Eli Friedmane0afc982012-01-21 01:01:51 +00006791
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006792 bool isCastExpr;
John McCallba7bf592010-08-24 05:47:05 +00006793 ParsedType CastTy;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006794 SourceRange CastRange;
Kaelyn Takata911260742014-12-19 01:28:40 +00006795 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6796 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
John McCalle8595032010-01-13 20:03:27 +00006797 if (hasParens)
6798 DS.setTypeofParensRange(CastRange);
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006799
6800 if (CastRange.getEnd().isInvalid())
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006801 // FIXME: Not accurate, the range gets one token more than it should.
6802 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006803 else
6804 DS.SetRangeEnd(CastRange.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +00006805
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006806 if (isCastExpr) {
6807 if (!CastTy) {
6808 DS.SetTypeSpecError();
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006809 return;
Douglas Gregor220cac52009-02-18 17:45:20 +00006810 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006811
Craig Topper161e4db2014-05-21 06:02:52 +00006812 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006813 unsigned DiagID;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006814 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6815 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006816 DiagID, CastTy,
6817 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006818 Diag(StartLoc, DiagID) << PrevSpec;
Argyrios Kyrtzidis7bd98442009-05-22 10:22:50 +00006819 return;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006820 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006821
Hiroshi Inoue533777f2017-07-02 06:12:49 +00006822 // If we get here, the operand to the typeof was an expression.
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006823 if (Operand.isInvalid()) {
6824 DS.SetTypeSpecError();
Steve Naroff4bd2f712007-08-02 02:53:48 +00006825 return;
Steve Naroffad373bd2007-07-31 12:34:36 +00006826 }
Argyrios Kyrtzidis2545aeb2008-09-05 11:26:19 +00006827
Eli Friedmane0afc982012-01-21 01:01:51 +00006828 // We might need to transform the operand if it is potentially evaluated.
6829 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6830 if (Operand.isInvalid()) {
6831 DS.SetTypeSpecError();
6832 return;
6833 }
6834
Craig Topper161e4db2014-05-21 06:02:52 +00006835 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00006836 unsigned DiagID;
Argyrios Kyrtzidisf5cc7ac2009-05-22 10:22:18 +00006837 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6838 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006839 DiagID, Operand.get(),
6840 Actions.getASTContext().getPrintingPolicy()))
John McCall49bfce42009-08-03 20:12:06 +00006841 Diag(StartLoc, DiagID) << PrevSpec;
Steve Naroffad373bd2007-07-31 12:34:36 +00006842}
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006843
Benjamin Kramere56f3932011-12-23 17:00:35 +00006844/// [C11] atomic-specifier:
Eli Friedman0dfb8892011-10-06 23:00:33 +00006845/// _Atomic ( type-name )
6846///
6847void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
Richard Smith8e1ac332013-03-28 01:55:44 +00006848 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6849 "Not an atomic specifier");
Eli Friedman0dfb8892011-10-06 23:00:33 +00006850
6851 SourceLocation StartLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006852 BalancedDelimiterTracker T(*this, tok::l_paren);
Richard Smith8e1ac332013-03-28 01:55:44 +00006853 if (T.consumeOpen())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006854 return;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006855
6856 TypeResult Result = ParseTypeName();
6857 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00006858 SkipUntil(tok::r_paren, StopAtSemi);
Eli Friedman0dfb8892011-10-06 23:00:33 +00006859 return;
6860 }
6861
6862 // Match the ')'
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006863 T.consumeClose();
Eli Friedman0dfb8892011-10-06 23:00:33 +00006864
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006865 if (T.getCloseLocation().isInvalid())
Eli Friedman0dfb8892011-10-06 23:00:33 +00006866 return;
6867
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00006868 DS.setTypeofParensRange(T.getRange());
6869 DS.SetRangeEnd(T.getCloseLocation());
Eli Friedman0dfb8892011-10-06 23:00:33 +00006870
Craig Topper161e4db2014-05-21 06:02:52 +00006871 const char *PrevSpec = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00006872 unsigned DiagID;
6873 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006874 DiagID, Result.get(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006875 Actions.getASTContext().getPrintingPolicy()))
Eli Friedman0dfb8892011-10-06 23:00:33 +00006876 Diag(StartLoc, DiagID) << PrevSpec;
6877}
6878
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006879/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6880/// from TryAltiVecVectorToken.
6881bool Parser::TryAltiVecVectorTokenOutOfLine() {
6882 Token Next = NextToken();
6883 switch (Next.getKind()) {
6884 default: return false;
6885 case tok::kw_short:
6886 case tok::kw_long:
6887 case tok::kw_signed:
6888 case tok::kw_unsigned:
6889 case tok::kw_void:
6890 case tok::kw_char:
6891 case tok::kw_int:
6892 case tok::kw_float:
6893 case tok::kw_double:
6894 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006895 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006896 case tok::kw___pixel:
6897 Tok.setKind(tok::kw___vector);
6898 return true;
6899 case tok::identifier:
6900 if (Next.getIdentifierInfo() == Ident_pixel) {
6901 Tok.setKind(tok::kw___vector);
6902 return true;
6903 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006904 if (Next.getIdentifierInfo() == Ident_bool) {
6905 Tok.setKind(tok::kw___vector);
6906 return true;
6907 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006908 return false;
6909 }
6910}
6911
6912bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6913 const char *&PrevSpec, unsigned &DiagID,
6914 bool &isInvalid) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006915 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006916 if (Tok.getIdentifierInfo() == Ident_vector) {
6917 Token Next = NextToken();
6918 switch (Next.getKind()) {
6919 case tok::kw_short:
6920 case tok::kw_long:
6921 case tok::kw_signed:
6922 case tok::kw_unsigned:
6923 case tok::kw_void:
6924 case tok::kw_char:
6925 case tok::kw_int:
6926 case tok::kw_float:
6927 case tok::kw_double:
6928 case tok::kw_bool:
Bill Seurercf2c96b2015-01-12 19:35:51 +00006929 case tok::kw___bool:
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006930 case tok::kw___pixel:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006931 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006932 return true;
6933 case tok::identifier:
6934 if (Next.getIdentifierInfo() == Ident_pixel) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006935 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006936 return true;
6937 }
Bill Schmidt99a084b2013-07-03 20:54:09 +00006938 if (Next.getIdentifierInfo() == Ident_bool) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006939 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00006940 return true;
6941 }
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006942 break;
6943 default:
6944 break;
6945 }
Douglas Gregor9938e3b2010-06-16 15:28:57 +00006946 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006947 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006948 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006949 return true;
Bill Schmidt99a084b2013-07-03 20:54:09 +00006950 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6951 DS.isTypeAltiVecVector()) {
Erik Verbruggen888d52a2014-01-15 09:15:43 +00006952 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
Bill Schmidt99a084b2013-07-03 20:54:09 +00006953 return true;
Chris Lattner73a9c7d2010-02-28 18:33:55 +00006954 }
6955 return false;
6956}