blob: a5a340ad22b5a414b9c9626dc37d298acb2394a3 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
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 Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation for C++.
11//
12//===----------------------------------------------------------------------===//
Vassil Vassilev11ad3392017-03-23 15:11:07 +000013#include "clang/Parse/Parser.h"
Erik Verbruggen888d52a2014-01-15 09:15:43 +000014#include "clang/AST/ASTContext.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000015#include "clang/AST/DeclTemplate.h"
Eli Friedmanc7c97142012-01-04 02:40:39 +000016#include "clang/Basic/PrettyStackTrace.h"
Richard Smith7d182a72012-03-08 23:06:02 +000017#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Parse/ParseDiagnostic.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000019#include "clang/Parse/RAIIObjectsForParser.h"
John McCall8b0666c2010-08-20 18:27:03 +000020#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/Scope.h"
Douglas Gregor7861a802009-11-03 01:35:08 +000023#include "llvm/Support/ErrorHandling.h"
24
Faisal Vali2b391ab2013-09-26 19:54:12 +000025
Chris Lattner29375652006-12-04 18:06:35 +000026using namespace clang;
27
Alp Tokerf990cef2014-01-07 02:35:33 +000028static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
29 switch (Kind) {
30 // template name
31 case tok::unknown: return 0;
32 // casts
33 case tok::kw_const_cast: return 1;
34 case tok::kw_dynamic_cast: return 2;
35 case tok::kw_reinterpret_cast: return 3;
36 case tok::kw_static_cast: return 4;
37 default:
38 llvm_unreachable("Unknown type for digraph error message.");
39 }
40}
41
Richard Smith55858492011-04-14 21:45:45 +000042// Are the two tokens adjacent in the same source file?
Richard Smith7b3f3222012-06-18 06:11:04 +000043bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
Richard Smith55858492011-04-14 21:45:45 +000044 SourceManager &SM = PP.getSourceManager();
45 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000046 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
Richard Smith55858492011-04-14 21:45:45 +000047 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
48}
49
50// Suggest fixit for "<::" after a cast.
51static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
52 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
53 // Pull '<:' and ':' off token stream.
54 if (!AtDigraph)
55 PP.Lex(DigraphToken);
56 PP.Lex(ColonToken);
57
58 SourceRange Range;
59 Range.setBegin(DigraphToken.getLocation());
60 Range.setEnd(ColonToken.getLocation());
61 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
Alp Tokerf990cef2014-01-07 02:35:33 +000062 << SelectDigraphErrorMessage(Kind)
63 << FixItHint::CreateReplacement(Range, "< ::");
Richard Smith55858492011-04-14 21:45:45 +000064
65 // Update token information to reflect their change in token type.
66 ColonToken.setKind(tok::coloncolon);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000067 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
Richard Smith55858492011-04-14 21:45:45 +000068 ColonToken.setLength(2);
69 DigraphToken.setKind(tok::less);
70 DigraphToken.setLength(1);
71
72 // Push new tokens back to token stream.
73 PP.EnterToken(ColonToken);
74 if (!AtDigraph)
75 PP.EnterToken(DigraphToken);
76}
77
Richard Trieu01fc0012011-09-19 19:01:00 +000078// Check for '<::' which should be '< ::' instead of '[:' when following
79// a template name.
80void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
81 bool EnteringContext,
82 IdentifierInfo &II, CXXScopeSpec &SS) {
Richard Trieu02e25db2011-09-20 20:03:50 +000083 if (!Next.is(tok::l_square) || Next.getLength() != 2)
Richard Trieu01fc0012011-09-19 19:01:00 +000084 return;
85
86 Token SecondToken = GetLookAheadToken(2);
Richard Smith7b3f3222012-06-18 06:11:04 +000087 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
Richard Trieu01fc0012011-09-19 19:01:00 +000088 return;
89
90 TemplateTy Template;
91 UnqualifiedId TemplateName;
92 TemplateName.setIdentifier(&II, Tok.getLocation());
93 bool MemberOfUnknownSpecialization;
94 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
95 TemplateName, ObjectType, EnteringContext,
96 Template, MemberOfUnknownSpecialization))
97 return;
98
Alp Tokerf990cef2014-01-07 02:35:33 +000099 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
100 /*AtDigraph*/false);
Richard Trieu01fc0012011-09-19 19:01:00 +0000101}
102
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000103/// Parse global scope or nested-name-specifier if present.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000104///
105/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
Mike Stump11289f42009-09-09 15:08:12 +0000106/// may be preceded by '::'). Note that this routine will not parse ::new or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000107/// ::delete; it will just leave them in the token stream.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000108///
109/// '::'[opt] nested-name-specifier
110/// '::'
111///
112/// nested-name-specifier:
113/// type-name '::'
114/// namespace-name '::'
115/// nested-name-specifier identifier '::'
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000116/// nested-name-specifier 'template'[opt] simple-template-id '::'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000117///
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000118///
Mike Stump11289f42009-09-09 15:08:12 +0000119/// \param SS the scope specifier that will be set to the parsed
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000120/// nested-name-specifier (or empty)
121///
Mike Stump11289f42009-09-09 15:08:12 +0000122/// \param ObjectType if this nested-name-specifier is being parsed following
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000123/// the "." or "->" of a member access expression, this parameter provides the
124/// type of the object whose members are being accessed.
125///
126/// \param EnteringContext whether we will be entering into the context of
127/// the nested-name-specifier after parsing it.
128///
Douglas Gregore610ada2010-02-24 18:44:31 +0000129/// \param MayBePseudoDestructor When non-NULL, points to a flag that
130/// indicates whether this nested-name-specifier may be part of a
131/// pseudo-destructor name. In this case, the flag will be set false
132/// if we don't actually end up parsing a destructor name. Moreorover,
133/// if we do end up determining that we are parsing a destructor name,
134/// the last component of the nested-name-specifier is not parsed as
135/// part of the scope specifier.
Richard Smith7447af42013-03-26 01:15:19 +0000136///
137/// \param IsTypename If \c true, this nested-name-specifier is known to be
138/// part of a type name. This is used to improve error recovery.
139///
140/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
141/// filled in with the leading identifier in the last component of the
142/// nested-name-specifier, if any.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000143///
Matthias Gehredc01bb42017-03-17 21:41:20 +0000144/// \param OnlyNamespace If true, only considers namespaces in lookup.
145///
John McCall1f476a12010-02-26 08:45:28 +0000146/// \returns true if there was an error parsing a scope specifier
Douglas Gregore861bac2009-08-25 22:51:20 +0000147bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +0000148 ParsedType ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000149 bool EnteringContext,
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000150 bool *MayBePseudoDestructor,
Richard Smith7447af42013-03-26 01:15:19 +0000151 bool IsTypename,
Matthias Gehredc01bb42017-03-17 21:41:20 +0000152 IdentifierInfo **LastII,
153 bool OnlyNamespace) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000154 assert(getLangOpts().CPlusPlus &&
Chris Lattnerb5134c02009-01-05 01:24:05 +0000155 "Call sites of this function should be guarded by checking for C++");
Mike Stump11289f42009-09-09 15:08:12 +0000156
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000157 if (Tok.is(tok::annot_cxxscope)) {
Richard Smith7447af42013-03-26 01:15:19 +0000158 assert(!LastII && "want last identifier but have already annotated scope");
Nico Weberc60aa712015-02-16 22:32:46 +0000159 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
Douglas Gregor869ad452011-02-24 17:54:50 +0000160 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
161 Tok.getAnnotationRange(),
162 SS);
Richard Smithaf3b3252017-05-18 19:21:48 +0000163 ConsumeAnnotationToken();
John McCall1f476a12010-02-26 08:45:28 +0000164 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000165 }
Chris Lattnerf9b2cd42009-01-04 21:14:15 +0000166
Larisse Voufob959c3c2013-08-06 05:49:26 +0000167 if (Tok.is(tok::annot_template_id)) {
168 // If the current token is an annotated template id, it may already have
169 // a scope specifier. Restore it.
170 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
171 SS = TemplateId->SS;
172 }
173
Nico Weberc60aa712015-02-16 22:32:46 +0000174 // Has to happen before any "return false"s in this function.
175 bool CheckForDestructor = false;
176 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
177 CheckForDestructor = true;
178 *MayBePseudoDestructor = false;
179 }
180
Richard Smith7447af42013-03-26 01:15:19 +0000181 if (LastII)
Craig Topper161e4db2014-05-21 06:02:52 +0000182 *LastII = nullptr;
Richard Smith7447af42013-03-26 01:15:19 +0000183
Douglas Gregor7f741122009-02-25 19:37:18 +0000184 bool HasScopeSpecifier = false;
185
Chris Lattner8a7d10d2009-01-05 03:55:46 +0000186 if (Tok.is(tok::coloncolon)) {
187 // ::new and ::delete aren't nested-name-specifiers.
188 tok::TokenKind NextKind = NextToken().getKind();
189 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
190 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000191
David Majnemere8fb28f2014-12-29 19:19:18 +0000192 if (NextKind == tok::l_brace) {
193 // It is invalid to have :: {, consume the scope qualifier and pretend
194 // like we never saw it.
195 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
196 } else {
197 // '::' - Global scope qualifier.
198 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
199 return true;
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000200
David Majnemere8fb28f2014-12-29 19:19:18 +0000201 HasScopeSpecifier = true;
202 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000203 }
204
Nikola Smiljanic67860242014-09-26 00:28:20 +0000205 if (Tok.is(tok::kw___super)) {
206 SourceLocation SuperLoc = ConsumeToken();
207 if (!Tok.is(tok::coloncolon)) {
208 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
209 return true;
210 }
211
212 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
213 }
214
Richard Smitha9d10012014-10-04 01:57:39 +0000215 if (!HasScopeSpecifier &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000216 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000217 DeclSpec DS(AttrFactory);
218 SourceLocation DeclLoc = Tok.getLocation();
219 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000220
221 SourceLocation CCLoc;
Richard Smith3f846bd2017-02-08 19:58:48 +0000222 // Work around a standard defect: 'decltype(auto)::' is not a
223 // nested-name-specifier.
224 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
225 !TryConsumeToken(tok::coloncolon, CCLoc)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000226 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
227 return false;
228 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000229
David Blaikie15a430a2011-12-04 05:04:18 +0000230 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
231 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
232
233 HasScopeSpecifier = true;
234 }
235
Douglas Gregor7f741122009-02-25 19:37:18 +0000236 while (true) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000237 if (HasScopeSpecifier) {
238 // C++ [basic.lookup.classref]p5:
239 // If the qualified-id has the form
Douglas Gregor308047d2009-09-09 00:23:06 +0000240 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000241 // ::class-name-or-namespace-name::...
Douglas Gregor308047d2009-09-09 00:23:06 +0000242 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000243 // the class-name-or-namespace-name is looked up in global scope as a
244 // class-name or namespace-name.
245 //
246 // To implement this, we clear out the object type as soon as we've
247 // seen a leading '::' or part of a nested-name-specifier.
David Blaikieefdccaa2016-01-15 23:43:34 +0000248 ObjectType = nullptr;
249
Douglas Gregor2436e712009-09-17 21:32:03 +0000250 if (Tok.is(tok::code_completion)) {
251 // Code completion for a nested-name-specifier, where the code
Jan Korousc217b1b2017-11-02 16:37:00 +0000252 // completion token follows the '::'.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000253 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidis7d94c922011-04-23 01:04:12 +0000254 // Include code completion token into the range of the scope otherwise
255 // when we try to annotate the scope tokens the dangling code completion
256 // token will cause assertion in
257 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000258 SS.setEndLoc(Tok.getLocation());
259 cutOffParsing();
260 return true;
Douglas Gregor2436e712009-09-17 21:32:03 +0000261 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000262 }
Mike Stump11289f42009-09-09 15:08:12 +0000263
Douglas Gregor7f741122009-02-25 19:37:18 +0000264 // nested-name-specifier:
Chris Lattner0eed3a62009-06-26 03:47:46 +0000265 // nested-name-specifier 'template'[opt] simple-template-id '::'
266
267 // Parse the optional 'template' keyword, then make sure we have
268 // 'identifier <' after it.
269 if (Tok.is(tok::kw_template)) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000270 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedman2624be42009-08-29 04:08:08 +0000271 // nested-name-specifier, since they aren't allowed to start with
272 // 'template'.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000273 if (!HasScopeSpecifier && !ObjectType)
Eli Friedman2624be42009-08-29 04:08:08 +0000274 break;
275
Douglas Gregor120635b2009-11-11 16:39:34 +0000276 TentativeParsingAction TPA(*this);
Chris Lattner0eed3a62009-06-26 03:47:46 +0000277 SourceLocation TemplateKWLoc = ConsumeToken();
Richard Smithd091dc12013-12-05 00:58:33 +0000278
Douglas Gregor71395fa2009-11-04 00:56:37 +0000279 UnqualifiedId TemplateName;
280 if (Tok.is(tok::identifier)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000281 // Consume the identifier.
Douglas Gregor120635b2009-11-11 16:39:34 +0000282 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor71395fa2009-11-04 00:56:37 +0000283 ConsumeToken();
284 } else if (Tok.is(tok::kw_operator)) {
Richard Smithd091dc12013-12-05 00:58:33 +0000285 // We don't need to actually parse the unqualified-id in this case,
286 // because a simple-template-id cannot start with 'operator', but
287 // go ahead and parse it anyway for consistency with the case where
288 // we already annotated the template-id.
289 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor120635b2009-11-11 16:39:34 +0000290 TemplateName)) {
291 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000292 break;
Douglas Gregor120635b2009-11-11 16:39:34 +0000293 }
Richard Smithd091dc12013-12-05 00:58:33 +0000294
Faisal Vali2ab8c152017-12-30 04:15:27 +0000295 if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId &&
296 TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000297 Diag(TemplateName.getSourceRange().getBegin(),
298 diag::err_id_after_template_in_nested_name_spec)
299 << TemplateName.getSourceRange();
Douglas Gregor120635b2009-11-11 16:39:34 +0000300 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000301 break;
302 }
303 } else {
Douglas Gregor120635b2009-11-11 16:39:34 +0000304 TPA.Revert();
Chris Lattner0eed3a62009-06-26 03:47:46 +0000305 break;
306 }
Mike Stump11289f42009-09-09 15:08:12 +0000307
Douglas Gregor120635b2009-11-11 16:39:34 +0000308 // If the next token is not '<', we have a qualified-id that refers
309 // to a template name, such as T::template apply, but is not a
310 // template-id.
311 if (Tok.isNot(tok::less)) {
312 TPA.Revert();
313 break;
314 }
315
316 // Commit to parsing the template-id.
317 TPA.Commit();
Douglas Gregorbb119652010-06-16 23:00:59 +0000318 TemplateTy Template;
Richard Smithfd3dae02017-01-20 00:20:39 +0000319 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
320 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
321 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000322 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
323 TemplateName, false))
Douglas Gregorbb119652010-06-16 23:00:59 +0000324 return true;
325 } else
John McCall1f476a12010-02-26 08:45:28 +0000326 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000327
Chris Lattner0eed3a62009-06-26 03:47:46 +0000328 continue;
329 }
Mike Stump11289f42009-09-09 15:08:12 +0000330
Douglas Gregor7f741122009-02-25 19:37:18 +0000331 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump11289f42009-09-09 15:08:12 +0000332 // We have
Douglas Gregor7f741122009-02-25 19:37:18 +0000333 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000334 // template-id '::'
Douglas Gregor7f741122009-02-25 19:37:18 +0000335 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000336 // So we need to check whether the template-id is a simple-template-id of
337 // the right kind (it should name a type or be dependent), and then
Douglas Gregorb67535d2009-03-31 00:43:58 +0000338 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000339 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregore610ada2010-02-24 18:44:31 +0000340 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
341 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000342 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000343 }
344
Richard Smith7447af42013-03-26 01:15:19 +0000345 if (LastII)
346 *LastII = TemplateId->Name;
347
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000348 // Consume the template-id token.
Richard Smithaf3b3252017-05-18 19:21:48 +0000349 ConsumeAnnotationToken();
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000350
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000351 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
352 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000353
David Blaikie8c045bc2011-11-07 03:30:03 +0000354 HasScopeSpecifier = true;
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000355
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000356 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000357 TemplateId->NumArgs);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000358
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000359 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000360 SS,
361 TemplateId->TemplateKWLoc,
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000362 TemplateId->Template,
363 TemplateId->TemplateNameLoc,
364 TemplateId->LAngleLoc,
365 TemplateArgsPtr,
366 TemplateId->RAngleLoc,
367 CCLoc,
368 EnteringContext)) {
369 SourceLocation StartLoc
370 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
371 : TemplateId->TemplateNameLoc;
372 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner704edfb2009-06-26 03:45:46 +0000373 }
Argyrios Kyrtzidis13935672011-05-03 18:45:38 +0000374
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000375 continue;
Douglas Gregor7f741122009-02-25 19:37:18 +0000376 }
377
Chris Lattnere2355f72009-06-26 03:52:38 +0000378 // The rest of the nested-name-specifier possibilities start with
379 // tok::identifier.
380 if (Tok.isNot(tok::identifier))
381 break;
382
383 IdentifierInfo &II = *Tok.getIdentifierInfo();
384
385 // nested-name-specifier:
386 // type-name '::'
387 // namespace-name '::'
388 // nested-name-specifier identifier '::'
389 Token Next = NextToken();
Serge Pavlovd931b9f2016-08-08 04:02:15 +0000390 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
391 ObjectType);
392
Chris Lattner1c428032009-12-07 01:36:53 +0000393 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
394 // and emit a fixit hint for it.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000395 if (Next.is(tok::colon) && !ColonIsSacred) {
Serge Pavlovd931b9f2016-08-08 04:02:15 +0000396 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000397 EnteringContext) &&
398 // If the token after the colon isn't an identifier, it's still an
399 // error, but they probably meant something else strange so don't
400 // recover like this.
401 PP.LookAhead(1).is(tok::identifier)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000402 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
Douglas Gregora771f462010-03-31 17:46:05 +0000403 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregor90d554e2010-02-21 18:36:56 +0000404 // Recover as if the user wrote '::'.
405 Next.setKind(tok::coloncolon);
406 }
Chris Lattner1c428032009-12-07 01:36:53 +0000407 }
David Majnemerf58efd92014-12-29 23:12:23 +0000408
409 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
410 // It is invalid to have :: {, consume the scope qualifier and pretend
411 // like we never saw it.
412 Token Identifier = Tok; // Stash away the identifier.
413 ConsumeToken(); // Eat the identifier, current token is now '::'.
David Majnemerec3f49d2014-12-29 23:24:27 +0000414 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
415 << tok::identifier;
David Majnemerf58efd92014-12-29 23:12:23 +0000416 UnconsumeToken(Identifier); // Stick the identifier back.
417 Next = NextToken(); // Point Next at the '{' token.
418 }
419
Chris Lattnere2355f72009-06-26 03:52:38 +0000420 if (Next.is(tok::coloncolon)) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000421 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Serge Pavlovd931b9f2016-08-08 04:02:15 +0000422 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, IdInfo)) {
Douglas Gregore610ada2010-02-24 18:44:31 +0000423 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000424 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000425 }
426
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000427 if (ColonIsSacred) {
428 const Token &Next2 = GetLookAheadToken(2);
429 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
430 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
431 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
432 << Next2.getName()
433 << FixItHint::CreateReplacement(Next.getLocation(), ":");
434 Token ColonColon;
435 PP.Lex(ColonColon);
436 ColonColon.setKind(tok::colon);
437 PP.EnterToken(ColonColon);
438 break;
439 }
440 }
441
Richard Smith7447af42013-03-26 01:15:19 +0000442 if (LastII)
443 *LastII = &II;
444
Chris Lattnere2355f72009-06-26 03:52:38 +0000445 // We have an identifier followed by a '::'. Lookup this name
446 // as the name in a nested-name-specifier.
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000447 Token Identifier = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000448 SourceLocation IdLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000449 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
Chris Lattner1c428032009-12-07 01:36:53 +0000450 "NextToken() not working properly!");
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000451 Token ColonColon = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000452 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000453
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000454 bool IsCorrectedToColon = false;
Craig Topper161e4db2014-05-21 06:02:52 +0000455 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
Matthias Gehredc01bb42017-03-17 21:41:20 +0000456 if (Actions.ActOnCXXNestedNameSpecifier(
457 getCurScope(), IdInfo, EnteringContext, SS, false,
458 CorrectionFlagPtr, OnlyNamespace)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000459 // Identifier is not recognized as a nested name, but we can have
460 // mistyped '::' instead of ':'.
461 if (CorrectionFlagPtr && IsCorrectedToColon) {
462 ColonColon.setKind(tok::colon);
463 PP.EnterToken(Tok);
464 PP.EnterToken(ColonColon);
465 Tok = Identifier;
466 break;
467 }
Douglas Gregor90c99722011-02-24 00:17:56 +0000468 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000469 }
470 HasScopeSpecifier = true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000471 continue;
472 }
Mike Stump11289f42009-09-09 15:08:12 +0000473
Richard Trieu01fc0012011-09-19 19:01:00 +0000474 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smith55858492011-04-14 21:45:45 +0000475
Chris Lattnere2355f72009-06-26 03:52:38 +0000476 // nested-name-specifier:
477 // type-name '<'
478 if (Next.is(tok::less)) {
479 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000480 UnqualifiedId TemplateName;
481 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor786123d2010-05-21 23:18:07 +0000482 bool MemberOfUnknownSpecialization;
Douglas Gregor0be31a22010-07-02 17:43:08 +0000483 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000484 /*hasTemplateKeyword=*/false,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000485 TemplateName,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000486 ObjectType,
Douglas Gregore861bac2009-08-25 22:51:20 +0000487 EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000488 Template,
489 MemberOfUnknownSpecialization)) {
David Blaikie8c045bc2011-11-07 03:30:03 +0000490 // We have found a template name, so annotate this token
Chris Lattnere2355f72009-06-26 03:52:38 +0000491 // with a template-id annotation. We do not permit the
492 // template-id to be translated into a type annotation,
493 // because some clients (e.g., the parsing of class template
494 // specializations) still want to see the original template-id
495 // token.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000496 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000497 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
498 TemplateName, false))
John McCall1f476a12010-02-26 08:45:28 +0000499 return true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000500 continue;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000501 }
502
Douglas Gregor20c38a72010-05-21 23:43:39 +0000503 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000504 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregor20c38a72010-05-21 23:43:39 +0000505 // We have something like t::getAs<T>, where getAs is a
506 // member of an unknown specialization. However, this will only
507 // parse correctly as a template, so suggest the keyword 'template'
508 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000509 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000510 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000511 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000512
513 Diag(Tok.getLocation(), DiagID)
Douglas Gregor20c38a72010-05-21 23:43:39 +0000514 << II.getName()
515 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
Richard Smithfd3dae02017-01-20 00:20:39 +0000516
517 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
Richard Smith79810042018-05-11 02:43:08 +0000518 getCurScope(), SS, Tok.getLocation(), TemplateName, ObjectType,
Richard Smithfd3dae02017-01-20 00:20:39 +0000519 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
Douglas Gregorbb119652010-06-16 23:00:59 +0000520 // Consume the identifier.
521 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000522 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
523 TemplateName, false))
524 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000525 }
526 else
Douglas Gregor20c38a72010-05-21 23:43:39 +0000527 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000528
Douglas Gregor20c38a72010-05-21 23:43:39 +0000529 continue;
Chris Lattnere2355f72009-06-26 03:52:38 +0000530 }
531 }
532
Douglas Gregor7f741122009-02-25 19:37:18 +0000533 // We don't have any tokens that form the beginning of a
534 // nested-name-specifier, so we're done.
535 break;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000536 }
Mike Stump11289f42009-09-09 15:08:12 +0000537
Douglas Gregore610ada2010-02-24 18:44:31 +0000538 // Even if we didn't see any pieces of a nested-name-specifier, we
539 // still check whether there is a tilde in this position, which
540 // indicates a potential pseudo-destructor.
541 if (CheckForDestructor && Tok.is(tok::tilde))
542 *MayBePseudoDestructor = true;
543
John McCall1f476a12010-02-26 08:45:28 +0000544 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000545}
546
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000547ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
548 Token &Replacement) {
549 SourceLocation TemplateKWLoc;
550 UnqualifiedId Name;
551 if (ParseUnqualifiedId(SS,
552 /*EnteringContext=*/false,
553 /*AllowDestructorName=*/false,
554 /*AllowConstructorName=*/false,
Richard Smith35845152017-02-07 01:37:30 +0000555 /*AllowDeductionGuide=*/false,
Richard Smithc08b6932018-04-27 02:00:13 +0000556 /*ObjectType=*/nullptr, &TemplateKWLoc, Name))
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000557 return ExprError();
558
559 // This is only the direct operand of an & operator if it is not
560 // followed by a postfix-expression suffix.
561 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
562 isAddressOfOperand = false;
563
564 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
565 Tok.is(tok::l_paren), isAddressOfOperand,
566 nullptr, /*IsInlineAsmIdentifier=*/false,
567 &Replacement);
568}
569
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000570/// ParseCXXIdExpression - Handle id-expression.
571///
572/// id-expression:
573/// unqualified-id
574/// qualified-id
575///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000576/// qualified-id:
577/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
578/// '::' identifier
579/// '::' operator-function-id
Douglas Gregora727cb92009-06-30 22:34:41 +0000580/// '::' template-id
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000581///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000582/// NOTE: The standard specifies that, for qualified-id, the parser does not
583/// expect:
584///
585/// '::' conversion-function-id
586/// '::' '~' class-name
587///
588/// This may cause a slight inconsistency on diagnostics:
589///
590/// class C {};
591/// namespace A {}
592/// void f() {
593/// :: A :: ~ C(); // Some Sema error about using destructor with a
594/// // namespace.
595/// :: ~ C(); // Some Parser error like 'unexpected ~'.
596/// }
597///
598/// We simplify the parser a bit and make it work like:
599///
600/// qualified-id:
601/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
602/// '::' unqualified-id
603///
604/// That way Sema can handle and report similar errors for namespaces and the
605/// global scope.
606///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000607/// The isAddressOfOperand parameter indicates that this id-expression is a
608/// direct operand of the address-of operator. This is, besides member contexts,
609/// the only place where a qualified-id naming a non-static class member may
610/// appear.
611///
John McCalldadc5752010-08-24 06:29:42 +0000612ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000613 // qualified-id:
614 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
615 // '::' unqualified-id
616 //
617 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +0000618 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000619
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000620 Token Replacement;
Nico Weber01a46ad2015-02-15 06:15:40 +0000621 ExprResult Result =
622 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000623 if (Result.isUnset()) {
624 // If the ExprResult is valid but null, then typo correction suggested a
625 // keyword replacement that needs to be reparsed.
626 UnconsumeToken(Replacement);
627 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
628 }
629 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
630 "for a previous keyword suggestion");
631 return Result;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000632}
633
Richard Smith21b3ab42013-05-09 21:36:41 +0000634/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000635///
636/// lambda-expression:
637/// lambda-introducer lambda-declarator[opt] compound-statement
638///
639/// lambda-introducer:
640/// '[' lambda-capture[opt] ']'
641///
642/// lambda-capture:
643/// capture-default
644/// capture-list
645/// capture-default ',' capture-list
646///
647/// capture-default:
648/// '&'
649/// '='
650///
651/// capture-list:
652/// capture
653/// capture-list ',' capture
654///
655/// capture:
Richard Smith21b3ab42013-05-09 21:36:41 +0000656/// simple-capture
657/// init-capture [C++1y]
658///
659/// simple-capture:
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000660/// identifier
661/// '&' identifier
662/// 'this'
663///
Richard Smith21b3ab42013-05-09 21:36:41 +0000664/// init-capture: [C++1y]
665/// identifier initializer
666/// '&' identifier initializer
667///
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000668/// lambda-declarator:
669/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
670/// 'mutable'[opt] exception-specification[opt]
671/// trailing-return-type[opt]
672///
673ExprResult Parser::ParseLambdaExpression() {
674 // Parse lambda-introducer.
675 LambdaIntroducer Intro;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000676 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000677 if (DiagID) {
678 Diag(Tok, DiagID.getValue());
David Majnemer234b8182015-01-12 03:36:37 +0000679 SkipUntil(tok::r_square, StopAtSemi);
680 SkipUntil(tok::l_brace, StopAtSemi);
681 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000682 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000683 }
684
685 return ParseLambdaExpressionAfterIntroducer(Intro);
686}
687
688/// TryParseLambdaExpression - Use lookahead and potentially tentative
689/// parsing to determine if we are looking at a C++0x lambda expression, and parse
690/// it if we are.
691///
692/// If we are not looking at a lambda expression, returns ExprError().
693ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000694 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000695 && Tok.is(tok::l_square)
696 && "Not at the start of a possible lambda expression.");
697
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000698 const Token Next = NextToken();
699 if (Next.is(tok::eof)) // Nothing else to lookup here...
700 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000701
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000702 const Token After = GetLookAheadToken(2);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000703 // If lookahead indicates this is a lambda...
704 if (Next.is(tok::r_square) || // []
705 Next.is(tok::equal) || // [=
706 (Next.is(tok::amp) && // [&] or [&,
707 (After.is(tok::r_square) ||
708 After.is(tok::comma))) ||
709 (Next.is(tok::identifier) && // [identifier]
710 After.is(tok::r_square))) {
711 return ParseLambdaExpression();
712 }
713
Eli Friedmanc7c97142012-01-04 02:40:39 +0000714 // If lookahead indicates an ObjC message send...
715 // [identifier identifier
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000716 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000717 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000718 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000719
Eli Friedmanc7c97142012-01-04 02:40:39 +0000720 // Here, we're stuck: lambda introducers and Objective-C message sends are
721 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
722 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
723 // writing two routines to parse a lambda introducer, just try to parse
724 // a lambda introducer first, and fall back if that fails.
725 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000726 LambdaIntroducer Intro;
727 if (TryParseLambdaIntroducer(Intro))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000728 return ExprEmpty();
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000729
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000730 return ParseLambdaExpressionAfterIntroducer(Intro);
731}
732
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000733/// Parse a lambda introducer.
Richard Smithf44d2a82013-05-21 22:21:19 +0000734/// \param Intro A LambdaIntroducer filled in with information about the
735/// contents of the lambda-introducer.
736/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
737/// message send and a lambda expression. In this mode, we will
738/// sometimes skip the initializers for init-captures and not fully
739/// populate \p Intro. This flag will be set to \c true if we do so.
740/// \return A DiagnosticID if it hit something unexpected. The location for
Malcolm Parsonsffd21d32017-01-11 11:23:22 +0000741/// the diagnostic is that of the current token.
Richard Smithf44d2a82013-05-21 22:21:19 +0000742Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
743 bool *SkippedInits) {
David Blaikie05785d12013-02-20 22:23:23 +0000744 typedef Optional<unsigned> DiagResult;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000745
746 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000747 BalancedDelimiterTracker T(*this, tok::l_square);
748 T.consumeOpen();
749
750 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000751
752 bool first = true;
753
754 // Parse capture-default.
755 if (Tok.is(tok::amp) &&
756 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
757 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000758 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000759 first = false;
760 } else if (Tok.is(tok::equal)) {
761 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000762 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000763 first = false;
764 }
765
766 while (Tok.isNot(tok::r_square)) {
767 if (!first) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000768 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000769 // Provide a completion for a lambda introducer here. Except
770 // in Objective-C, where this is Almost Surely meant to be a message
771 // send. In that case, fail here and let the ObjC message
772 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000773 if (Tok.is(tok::code_completion) &&
774 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
775 !Intro.Captures.empty())) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000776 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
777 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000778 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000779 break;
780 }
781
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000782 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregord8c61782012-02-15 15:34:24 +0000783 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000784 ConsumeToken();
785 }
786
Douglas Gregord8c61782012-02-15 15:34:24 +0000787 if (Tok.is(tok::code_completion)) {
788 // If we're in Objective-C++ and we have a bare '[', then this is more
789 // likely to be a message receiver.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000790 if (getLangOpts().ObjC1 && first)
Douglas Gregord8c61782012-02-15 15:34:24 +0000791 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
792 else
793 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
794 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000795 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000796 break;
797 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000798
Douglas Gregord8c61782012-02-15 15:34:24 +0000799 first = false;
800
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000801 // Parse capture.
802 LambdaCaptureKind Kind = LCK_ByCopy;
Richard Smith42b10572015-11-11 01:36:17 +0000803 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000804 SourceLocation Loc;
Craig Topper161e4db2014-05-21 06:02:52 +0000805 IdentifierInfo *Id = nullptr;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000806 SourceLocation EllipsisLoc;
Richard Smith21b3ab42013-05-09 21:36:41 +0000807 ExprResult Init;
Faisal Validc6b5962016-03-21 09:25:37 +0000808
809 if (Tok.is(tok::star)) {
810 Loc = ConsumeToken();
811 if (Tok.is(tok::kw_this)) {
812 ConsumeToken();
813 Kind = LCK_StarThis;
814 } else {
815 return DiagResult(diag::err_expected_star_this_capture);
816 }
817 } else if (Tok.is(tok::kw_this)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000818 Kind = LCK_This;
819 Loc = ConsumeToken();
820 } else {
821 if (Tok.is(tok::amp)) {
822 Kind = LCK_ByRef;
823 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000824
825 if (Tok.is(tok::code_completion)) {
826 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
827 /*AfterAmpersand=*/true);
Alp Toker1c583cc2014-05-02 03:43:14 +0000828 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000829 break;
830 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000831 }
832
833 if (Tok.is(tok::identifier)) {
834 Id = Tok.getIdentifierInfo();
835 Loc = ConsumeToken();
836 } else if (Tok.is(tok::kw_this)) {
837 // FIXME: If we want to suggest a fixit here, will need to return more
838 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
839 // Clear()ed to prevent emission in case of tentative parsing?
840 return DiagResult(diag::err_this_captured_by_reference);
841 } else {
842 return DiagResult(diag::err_expected_capture);
843 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000844
845 if (Tok.is(tok::l_paren)) {
846 BalancedDelimiterTracker Parens(*this, tok::l_paren);
847 Parens.consumeOpen();
848
Richard Smith42b10572015-11-11 01:36:17 +0000849 InitKind = LambdaCaptureInitKind::DirectInit;
850
Richard Smith21b3ab42013-05-09 21:36:41 +0000851 ExprVector Exprs;
852 CommaLocsTy Commas;
Richard Smithf44d2a82013-05-21 22:21:19 +0000853 if (SkippedInits) {
854 Parens.skipToEnd();
855 *SkippedInits = true;
856 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000857 Parens.skipToEnd();
858 Init = ExprError();
859 } else {
860 Parens.consumeClose();
861 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
862 Parens.getCloseLocation(),
863 Exprs);
864 }
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000865 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000866 // Each lambda init-capture forms its own full expression, which clears
867 // Actions.MaybeODRUseExprs. So create an expression evaluation context
868 // to save the necessary state, and restore it later.
Faisal Valid143a0c2017-04-01 21:30:49 +0000869 EnterExpressionEvaluationContext EC(
870 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith42b10572015-11-11 01:36:17 +0000871
872 if (TryConsumeToken(tok::equal))
873 InitKind = LambdaCaptureInitKind::CopyInit;
874 else
875 InitKind = LambdaCaptureInitKind::ListInit;
Richard Smith21b3ab42013-05-09 21:36:41 +0000876
Richard Smith215f4232015-02-11 02:41:33 +0000877 if (!SkippedInits) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000878 Init = ParseInitializer();
Richard Smith215f4232015-02-11 02:41:33 +0000879 } else if (Tok.is(tok::l_brace)) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000880 BalancedDelimiterTracker Braces(*this, tok::l_brace);
881 Braces.consumeOpen();
882 Braces.skipToEnd();
883 *SkippedInits = true;
884 } else {
885 // We're disambiguating this:
886 //
887 // [..., x = expr
888 //
889 // We need to find the end of the following expression in order to
Richard Smith9e2f0a42014-04-13 04:31:48 +0000890 // determine whether this is an Obj-C message send's receiver, a
891 // C99 designator, or a lambda init-capture.
Richard Smithf44d2a82013-05-21 22:21:19 +0000892 //
893 // Parse the expression to find where it ends, and annotate it back
894 // onto the tokens. We would have parsed this expression the same way
895 // in either case: both the RHS of an init-capture and the RHS of an
896 // assignment expression are parsed as an initializer-clause, and in
897 // neither case can anything be added to the scope between the '[' and
898 // here.
899 //
900 // FIXME: This is horrible. Adding a mechanism to skip an expression
901 // would be much cleaner.
902 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
903 // that instead. (And if we see a ':' with no matching '?', we can
904 // classify this as an Obj-C message send.)
905 SourceLocation StartLoc = Tok.getLocation();
906 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
907 Init = ParseInitializer();
Akira Hatanaka51e60f92016-12-20 02:11:29 +0000908 if (!Init.isInvalid())
909 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
Richard Smithf44d2a82013-05-21 22:21:19 +0000910
911 if (Tok.getLocation() != StartLoc) {
912 // Back out the lexing of the token after the initializer.
913 PP.RevertCachedTokens(1);
914
915 // Replace the consumed tokens with an appropriate annotation.
916 Tok.setLocation(StartLoc);
917 Tok.setKind(tok::annot_primary_expr);
918 setExprAnnotation(Tok, Init);
919 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
920 PP.AnnotateCachedTokens(Tok);
921
922 // Consume the annotated initializer.
Richard Smithaf3b3252017-05-18 19:21:48 +0000923 ConsumeAnnotationToken();
Richard Smithf44d2a82013-05-21 22:21:19 +0000924 }
925 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000926 } else
927 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000928 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000929 // If this is an init capture, process the initialization expression
930 // right away. For lambda init-captures such as the following:
931 // const int x = 10;
932 // auto L = [i = x+1](int a) {
933 // return [j = x+2,
934 // &k = x](char b) { };
935 // };
936 // keep in mind that each lambda init-capture has to have:
937 // - its initialization expression executed in the context
938 // of the enclosing/parent decl-context.
939 // - but the variable itself has to be 'injected' into the
940 // decl-context of its lambda's call-operator (which has
941 // not yet been created).
942 // Each init-expression is a full-expression that has to get
943 // Sema-analyzed (for capturing etc.) before its lambda's
944 // call-operator's decl-context, scope & scopeinfo are pushed on their
945 // respective stacks. Thus if any variable is odr-used in the init-capture
946 // it will correctly get captured in the enclosing lambda, if one exists.
947 // The init-variables above are created later once the lambdascope and
948 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000949
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000950 // Since the lambda init-capture's initializer expression occurs in the
951 // context of the enclosing function or lambda, therefore we can not wait
952 // till a lambda scope has been pushed on before deciding whether the
953 // variable needs to be captured. We also need to process all
954 // lvalue-to-rvalue conversions and discarded-value conversions,
955 // so that we can avoid capturing certain constant variables.
956 // For e.g.,
957 // void test() {
958 // const int x = 10;
959 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
960 // return [y = x](int i) { <-- don't capture by enclosing lambda
961 // return y;
962 // }
963 // };
Richard Smithbdb84f32016-07-22 23:36:59 +0000964 // }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000965 // If x was not const, the second use would require 'L' to capture, and
966 // that would be an error.
967
Richard Smith42b10572015-11-11 01:36:17 +0000968 ParsedType InitCaptureType;
Volodymyr Sapsaib0f1aae2017-08-22 17:55:19 +0000969 if (!Init.isInvalid())
970 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000971 if (Init.isUsable()) {
972 // Get the pointer and store it in an lvalue, so we can use it as an
973 // out argument.
974 Expr *InitExpr = Init.get();
975 // This performs any lvalue-to-rvalue conversions if necessary, which
976 // can affect what gets captured in the containing decl-context.
Richard Smith42b10572015-11-11 01:36:17 +0000977 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
978 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000979 Init = InitExpr;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000980 }
Richard Smith42b10572015-11-11 01:36:17 +0000981 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
982 InitCaptureType);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000983 }
984
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000985 T.consumeClose();
986 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000987 return DiagResult();
988}
989
Douglas Gregord8c61782012-02-15 15:34:24 +0000990/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000991///
992/// Returns true if it hit something unexpected.
993bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
Jan Korous06aa2af2017-11-06 17:42:17 +0000994 {
995 bool SkippedInits = false;
996 TentativeParsingAction PA1(*this);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000997
Jan Korous06aa2af2017-11-06 17:42:17 +0000998 if (ParseLambdaIntroducer(Intro, &SkippedInits)) {
999 PA1.Revert();
1000 return true;
1001 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001002
Jan Korous06aa2af2017-11-06 17:42:17 +00001003 if (!SkippedInits) {
1004 PA1.Commit();
1005 return false;
1006 }
1007
1008 PA1.Revert();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001009 }
1010
Jan Korous06aa2af2017-11-06 17:42:17 +00001011 // Try to parse it again, but this time parse the init-captures too.
1012 Intro = LambdaIntroducer();
1013 TentativeParsingAction PA2(*this);
1014
1015 if (!ParseLambdaIntroducer(Intro)) {
1016 PA2.Commit();
Richard Smithf44d2a82013-05-21 22:21:19 +00001017 return false;
1018 }
1019
Jan Korous06aa2af2017-11-06 17:42:17 +00001020 PA2.Revert();
1021 return true;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001022}
1023
Faisal Valia734ab92016-03-26 16:11:37 +00001024static void
1025tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
1026 SourceLocation &ConstexprLoc,
1027 SourceLocation &DeclEndLoc) {
1028 assert(MutableLoc.isInvalid());
1029 assert(ConstexprLoc.isInvalid());
1030 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1031 // to the final of those locations. Emit an error if we have multiple
1032 // copies of those keywords and recover.
1033
1034 while (true) {
1035 switch (P.getCurToken().getKind()) {
1036 case tok::kw_mutable: {
1037 if (MutableLoc.isValid()) {
1038 P.Diag(P.getCurToken().getLocation(),
1039 diag::err_lambda_decl_specifier_repeated)
1040 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1041 }
1042 MutableLoc = P.ConsumeToken();
1043 DeclEndLoc = MutableLoc;
1044 break /*switch*/;
1045 }
1046 case tok::kw_constexpr:
1047 if (ConstexprLoc.isValid()) {
1048 P.Diag(P.getCurToken().getLocation(),
1049 diag::err_lambda_decl_specifier_repeated)
1050 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1051 }
1052 ConstexprLoc = P.ConsumeToken();
1053 DeclEndLoc = ConstexprLoc;
1054 break /*switch*/;
1055 default:
1056 return;
1057 }
1058 }
1059}
1060
1061static void
1062addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1063 DeclSpec &DS) {
1064 if (ConstexprLoc.isValid()) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001065 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
Richard Smithb115e5d2017-08-13 23:37:29 +00001066 ? diag::ext_constexpr_on_lambda_cxx17
Faisal Valia734ab92016-03-26 16:11:37 +00001067 : diag::warn_cxx14_compat_constexpr_on_lambda);
1068 const char *PrevSpec = nullptr;
1069 unsigned DiagID = 0;
1070 DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1071 assert(PrevSpec == nullptr && DiagID == 0 &&
1072 "Constexpr cannot have been set previously!");
1073 }
1074}
1075
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001076/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1077/// expression.
1078ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1079 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +00001080 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1081 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1082
1083 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1084 "lambda expression parsing");
1085
Faisal Vali2b391ab2013-09-26 19:54:12 +00001086
1087
Richard Smith21b3ab42013-05-09 21:36:41 +00001088 // FIXME: Call into Actions to add any init-capture declarations to the
1089 // scope while parsing the lambda-declarator and compound-statement.
1090
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001091 // Parse lambda-declarator[opt].
1092 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00001093 Declarator D(DS, DeclaratorContext::LambdaExprContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001094 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001095 Actions.PushLambdaScope();
1096
1097 ParsedAttributes Attr(AttrFactory);
1098 SourceLocation DeclLoc = Tok.getLocation();
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001099 if (getLangOpts().CUDA) {
1100 // In CUDA code, GNU attributes are allowed to appear immediately after the
1101 // "[...]", even if there is no "(...)" before the lambda body.
Justin Lebar0139a5d2016-09-30 19:55:48 +00001102 MaybeParseGNUAttributes(D);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001103 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001104
Justin Lebare46ea722016-09-30 19:55:55 +00001105 // Helper to emit a warning if we see a CUDA host/device/global attribute
1106 // after '(...)'. nvcc doesn't accept this.
1107 auto WarnIfHasCUDATargetAttr = [&] {
1108 if (getLangOpts().CUDA)
1109 for (auto *A = Attr.getList(); A != nullptr; A = A->getNext())
1110 if (A->getKind() == AttributeList::AT_CUDADevice ||
1111 A->getKind() == AttributeList::AT_CUDAHost ||
1112 A->getKind() == AttributeList::AT_CUDAGlobal)
1113 Diag(A->getLoc(), diag::warn_cuda_attr_lambda_position)
1114 << A->getName()->getName();
1115 };
1116
David Majnemere01c4662015-01-09 05:10:55 +00001117 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001118 if (Tok.is(tok::l_paren)) {
1119 ParseScope PrototypeScope(this,
1120 Scope::FunctionPrototypeScope |
Richard Smithe233fbf2013-01-28 22:42:45 +00001121 Scope::FunctionDeclarationScope |
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001122 Scope::DeclScope);
1123
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001124 BalancedDelimiterTracker T(*this, tok::l_paren);
1125 T.consumeOpen();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001126 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001127
1128 // Parse parameter-declaration-clause.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001129 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001130 SourceLocation EllipsisLoc;
Faisal Vali2b391ab2013-09-26 19:54:12 +00001131
1132 if (Tok.isNot(tok::r_paren)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00001133 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001134 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001135 // For a generic lambda, each 'auto' within the parameter declaration
1136 // clause creates a template type parameter, so increment the depth.
1137 if (Actions.getCurGenericLambda())
1138 ++CurTemplateDepthTracker;
1139 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001140 T.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001141 SourceLocation RParenLoc = T.getCloseLocation();
Justin Lebar0139a5d2016-09-30 19:55:48 +00001142 SourceLocation DeclEndLoc = RParenLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001143
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001144 // GNU-style attributes must be parsed before the mutable specifier to be
1145 // compatible with GCC.
1146 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1147
David Majnemerbda86322015-02-04 08:22:46 +00001148 // MSVC-style attributes must be parsed before the mutable specifier to be
1149 // compatible with MSVC.
Aaron Ballman068aa512015-05-20 20:58:33 +00001150 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
David Majnemerbda86322015-02-04 08:22:46 +00001151
Faisal Valia734ab92016-03-26 16:11:37 +00001152 // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001153 SourceLocation MutableLoc;
Faisal Valia734ab92016-03-26 16:11:37 +00001154 SourceLocation ConstexprLoc;
1155 tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1156 DeclEndLoc);
1157
1158 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001159
1160 // Parse exception-specification[opt].
1161 ExceptionSpecificationType ESpecType = EST_None;
1162 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001163 SmallVector<ParsedType, 2> DynamicExceptions;
1164 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001165 ExprResult NoexceptExpr;
Richard Smith0b3a4622014-11-13 20:01:57 +00001166 CachedTokens *ExceptionSpecTokens;
1167 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1168 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00001169 DynamicExceptions,
1170 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00001171 NoexceptExpr,
1172 ExceptionSpecTokens);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001173
1174 if (ESpecType != EST_None)
1175 DeclEndLoc = ESpecRange.getEnd();
1176
1177 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +00001178 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001179
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001180 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1181
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001182 // Parse trailing-return-type[opt].
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001183 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001184 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001185 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00001186 TrailingReturnType =
1187 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001188 if (Range.getEnd().isValid())
1189 DeclEndLoc = Range.getEnd();
1190 }
1191
1192 PrototypeScope.Exit();
1193
Justin Lebare46ea722016-09-30 19:55:55 +00001194 WarnIfHasCUDATargetAttr();
1195
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001196 SourceLocation NoLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001197 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001198 /*isAmbiguous=*/false,
1199 LParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001200 ParamInfo.data(), ParamInfo.size(),
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001201 EllipsisLoc, RParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001202 DS.getTypeQualifiers(),
1203 /*RefQualifierIsLValueRef=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001204 /*RefQualifierLoc=*/NoLoc,
1205 /*ConstQualifierLoc=*/NoLoc,
1206 /*VolatileQualifierLoc=*/NoLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00001207 /*RestrictQualifierLoc=*/NoLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001208 MutableLoc,
Nathan Wilsone23a9a42015-08-26 04:19:36 +00001209 ESpecType, ESpecRange,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001210 DynamicExceptions.data(),
1211 DynamicExceptionRanges.data(),
1212 DynamicExceptions.size(),
1213 NoexceptExpr.isUsable() ?
Craig Topper161e4db2014-05-21 06:02:52 +00001214 NoexceptExpr.get() : nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00001215 /*ExceptionSpecTokens*/nullptr,
Reid Kleckner078aea92016-12-09 17:14:05 +00001216 /*DeclsInPrototype=*/None,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001217 LParenLoc, FunLocalRangeEnd, D,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001218 TrailingReturnType),
1219 Attr, DeclEndLoc);
Faisal Valia734ab92016-03-26 16:11:37 +00001220 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1221 tok::kw_constexpr) ||
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001222 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1223 // It's common to forget that one needs '()' before 'mutable', an attribute
1224 // specifier, or the result type. Deal with this.
1225 unsigned TokKind = 0;
1226 switch (Tok.getKind()) {
1227 case tok::kw_mutable: TokKind = 0; break;
1228 case tok::arrow: TokKind = 1; break;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001229 case tok::kw___attribute:
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001230 case tok::l_square: TokKind = 2; break;
Faisal Valia734ab92016-03-26 16:11:37 +00001231 case tok::kw_constexpr: TokKind = 3; break;
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001232 default: llvm_unreachable("Unknown token kind");
1233 }
1234
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001235 Diag(Tok, diag::err_lambda_missing_parens)
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001236 << TokKind
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001237 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
Justin Lebar0139a5d2016-09-30 19:55:48 +00001238 SourceLocation DeclEndLoc = DeclLoc;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001239
1240 // GNU-style attributes must be parsed before the mutable specifier to be
1241 // compatible with GCC.
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001242 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1243
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001244 // Parse 'mutable', if it's there.
1245 SourceLocation MutableLoc;
1246 if (Tok.is(tok::kw_mutable)) {
1247 MutableLoc = ConsumeToken();
1248 DeclEndLoc = MutableLoc;
1249 }
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001250
1251 // Parse attribute-specifier[opt].
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001252 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1253
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001254 // Parse the return type, if there is one.
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001255 if (Tok.is(tok::arrow)) {
1256 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00001257 TrailingReturnType =
1258 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001259 if (Range.getEnd().isValid())
David Majnemere01c4662015-01-09 05:10:55 +00001260 DeclEndLoc = Range.getEnd();
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001261 }
1262
Justin Lebare46ea722016-09-30 19:55:55 +00001263 WarnIfHasCUDATargetAttr();
1264
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001265 SourceLocation NoLoc;
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001266 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001267 /*isAmbiguous=*/false,
1268 /*LParenLoc=*/NoLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00001269 /*Params=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001270 /*NumParams=*/0,
1271 /*EllipsisLoc=*/NoLoc,
1272 /*RParenLoc=*/NoLoc,
1273 /*TypeQuals=*/0,
1274 /*RefQualifierIsLValueRef=*/true,
1275 /*RefQualifierLoc=*/NoLoc,
1276 /*ConstQualifierLoc=*/NoLoc,
1277 /*VolatileQualifierLoc=*/NoLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00001278 /*RestrictQualifierLoc=*/NoLoc,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001279 MutableLoc,
1280 EST_None,
Nathan Wilsone23a9a42015-08-26 04:19:36 +00001281 /*ESpecRange=*/SourceRange(),
Craig Topper161e4db2014-05-21 06:02:52 +00001282 /*Exceptions=*/nullptr,
1283 /*ExceptionRanges=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001284 /*NumExceptions=*/0,
Craig Topper161e4db2014-05-21 06:02:52 +00001285 /*NoexceptExpr=*/nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00001286 /*ExceptionSpecTokens=*/nullptr,
Reid Kleckner078aea92016-12-09 17:14:05 +00001287 /*DeclsInPrototype=*/None,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001288 DeclLoc, DeclEndLoc, D,
1289 TrailingReturnType),
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001290 Attr, DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001291 }
1292
Eli Friedman4817cf72012-01-06 03:05:34 +00001293 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1294 // it.
Momchil Velikov57c681f2017-08-10 15:43:06 +00001295 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1296 Scope::CompoundStmtScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001297 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001298
Eli Friedman71c80552012-01-05 03:35:19 +00001299 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1300
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001301 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001302 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001303 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001304 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1305 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001306 }
1307
Eli Friedmanc7c97142012-01-04 02:40:39 +00001308 StmtResult Stmt(ParseCompoundStatementBody());
1309 BodyScope.Exit();
1310
David Majnemere01c4662015-01-09 05:10:55 +00001311 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001312 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
David Majnemere01c4662015-01-09 05:10:55 +00001313
Eli Friedman898caf82012-01-04 02:46:53 +00001314 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1315 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001316}
1317
Chris Lattner29375652006-12-04 18:06:35 +00001318/// ParseCXXCasts - This handles the various ways to cast expressions to another
1319/// type.
1320///
1321/// postfix-expression: [C++ 5.2p1]
1322/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1323/// 'static_cast' '<' type-name '>' '(' expression ')'
1324/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1325/// 'const_cast' '<' type-name '>' '(' expression ')'
1326///
John McCalldadc5752010-08-24 06:29:42 +00001327ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001328 tok::TokenKind Kind = Tok.getKind();
Craig Topper161e4db2014-05-21 06:02:52 +00001329 const char *CastName = nullptr; // For error messages
Chris Lattner29375652006-12-04 18:06:35 +00001330
1331 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001332 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001333 case tok::kw_const_cast: CastName = "const_cast"; break;
1334 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1335 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1336 case tok::kw_static_cast: CastName = "static_cast"; break;
1337 }
1338
1339 SourceLocation OpLoc = ConsumeToken();
1340 SourceLocation LAngleBracketLoc = Tok.getLocation();
1341
Richard Smith55858492011-04-14 21:45:45 +00001342 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1343 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001344 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1345 Token Next = NextToken();
1346 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1347 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1348 }
Richard Smith55858492011-04-14 21:45:45 +00001349
Chris Lattner29375652006-12-04 18:06:35 +00001350 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001351 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001352
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001353 // Parse the common declaration-specifiers piece.
1354 DeclSpec DS(AttrFactory);
1355 ParseSpecifierQualifierList(DS);
1356
1357 // Parse the abstract-declarator, if present.
Faisal Vali421b2d12017-12-29 05:41:00 +00001358 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001359 ParseDeclarator(DeclaratorInfo);
1360
Chris Lattner29375652006-12-04 18:06:35 +00001361 SourceLocation RAngleBracketLoc = Tok.getLocation();
1362
Alp Toker383d2c42014-01-01 03:08:43 +00001363 if (ExpectAndConsume(tok::greater))
Alp Tokerec543272013-12-24 09:48:30 +00001364 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Chris Lattner29375652006-12-04 18:06:35 +00001365
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001366 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001367
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001368 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001369 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001370
John McCalldadc5752010-08-24 06:29:42 +00001371 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001372
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001373 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001374 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001375
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001376 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001377 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001378 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001379 RAngleBracketLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001380 T.getOpenLocation(), Result.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001381 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001382
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001383 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001384}
Bill Wendling4073ed52007-02-13 01:51:42 +00001385
Sebastian Redlc4704762008-11-11 11:37:55 +00001386/// ParseCXXTypeid - This handles the C++ typeid expression.
1387///
1388/// postfix-expression: [C++ 5.2p1]
1389/// 'typeid' '(' expression ')'
1390/// 'typeid' '(' type-id ')'
1391///
John McCalldadc5752010-08-24 06:29:42 +00001392ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001393 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1394
1395 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001396 SourceLocation LParenLoc, RParenLoc;
1397 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001398
1399 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001400 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001401 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001402 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001403
John McCalldadc5752010-08-24 06:29:42 +00001404 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001405
Richard Smith4f605af2012-08-18 00:55:03 +00001406 // C++0x [expr.typeid]p3:
1407 // When typeid is applied to an expression other than an lvalue of a
1408 // polymorphic class type [...] The expression is an unevaluated
1409 // operand (Clause 5).
1410 //
1411 // Note that we can't tell whether the expression is an lvalue of a
1412 // polymorphic class type until after we've parsed the expression; we
1413 // speculatively assume the subexpression is unevaluated, and fix it up
1414 // later.
1415 //
1416 // We enter the unevaluated context before trying to determine whether we
1417 // have a type-id, because the tentative parse logic will try to resolve
1418 // names, and must treat them as unevaluated.
Faisal Valid143a0c2017-04-01 21:30:49 +00001419 EnterExpressionEvaluationContext Unevaluated(
1420 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1421 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001422
Sebastian Redlc4704762008-11-11 11:37:55 +00001423 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001424 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001425
1426 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001427 T.consumeClose();
1428 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001429 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001430 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001431
1432 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001433 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001434 } else {
1435 Result = ParseExpression();
1436
1437 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001438 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001439 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc4704762008-11-11 11:37:55 +00001440 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001441 T.consumeClose();
1442 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001443 if (RParenLoc.isInvalid())
1444 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001445
Sebastian Redlc4704762008-11-11 11:37:55 +00001446 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001447 Result.get(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001448 }
1449 }
1450
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001451 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001452}
1453
Francois Pichet9f4f2072010-09-08 12:20:18 +00001454/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1455///
1456/// '__uuidof' '(' expression ')'
1457/// '__uuidof' '(' type-id ')'
1458///
1459ExprResult Parser::ParseCXXUuidof() {
1460 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1461
1462 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001463 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001464
1465 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001466 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001467 return ExprError();
1468
1469 ExprResult Result;
1470
1471 if (isTypeIdInParens()) {
1472 TypeResult Ty = ParseTypeName();
1473
1474 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001475 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001476
1477 if (Ty.isInvalid())
1478 return ExprError();
1479
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001480 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1481 Ty.get().getAsOpaquePtr(),
1482 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001483 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00001484 EnterExpressionEvaluationContext Unevaluated(
1485 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001486 Result = ParseExpression();
1487
1488 // Match the ')'.
1489 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001490 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001491 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001492 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001493
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001494 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1495 /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001496 Result.get(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001497 }
1498 }
1499
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001500 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001501}
1502
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001503/// Parse a C++ pseudo-destructor expression after the base,
Douglas Gregore610ada2010-02-24 18:44:31 +00001504/// . or -> operator, and nested-name-specifier have already been
1505/// parsed.
1506///
1507/// postfix-expression: [C++ 5.2]
1508/// postfix-expression . pseudo-destructor-name
1509/// postfix-expression -> pseudo-destructor-name
1510///
1511/// pseudo-destructor-name:
1512/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1513/// ::[opt] nested-name-specifier template simple-template-id ::
1514/// ~type-name
1515/// ::[opt] nested-name-specifier[opt] ~type-name
1516///
John McCalldadc5752010-08-24 06:29:42 +00001517ExprResult
Craig Toppera2c51532014-10-30 05:30:05 +00001518Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00001519 tok::TokenKind OpKind,
1520 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001521 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001522 // We're parsing either a pseudo-destructor-name or a dependent
1523 // member access that has the same form as a
1524 // pseudo-destructor-name. We parse both in the same way and let
1525 // the action model sort them out.
1526 //
1527 // Note that the ::[opt] nested-name-specifier[opt] has already
1528 // been parsed, and if there was a simple-template-id, it has
1529 // been coalesced into a template-id annotation token.
1530 UnqualifiedId FirstTypeName;
1531 SourceLocation CCLoc;
1532 if (Tok.is(tok::identifier)) {
1533 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1534 ConsumeToken();
1535 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1536 CCLoc = ConsumeToken();
1537 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001538 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1539 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001540 FirstTypeName.setTemplateId(
1541 (TemplateIdAnnotation *)Tok.getAnnotationValue());
Richard Smithaf3b3252017-05-18 19:21:48 +00001542 ConsumeAnnotationToken();
Douglas Gregore610ada2010-02-24 18:44:31 +00001543 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1544 CCLoc = ConsumeToken();
1545 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001546 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregore610ada2010-02-24 18:44:31 +00001547 }
1548
1549 // Parse the tilde.
1550 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1551 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001552
1553 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1554 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001555 ParseDecltypeSpecifier(DS);
Faisal Vali090da2d2018-01-01 18:23:28 +00001556 if (DS.getTypeSpecType() == TST_error)
David Blaikie1d578782011-12-16 16:03:09 +00001557 return ExprError();
David Majnemerced8bdf2015-02-25 17:36:15 +00001558 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1559 TildeLoc, DS);
David Blaikie1d578782011-12-16 16:03:09 +00001560 }
1561
Douglas Gregore610ada2010-02-24 18:44:31 +00001562 if (!Tok.is(tok::identifier)) {
1563 Diag(Tok, diag::err_destructor_tilde_identifier);
1564 return ExprError();
1565 }
1566
1567 // Parse the second type.
1568 UnqualifiedId SecondTypeName;
1569 IdentifierInfo *Name = Tok.getIdentifierInfo();
1570 SourceLocation NameLoc = ConsumeToken();
1571 SecondTypeName.setIdentifier(Name, NameLoc);
1572
1573 // If there is a '<', the second type name is a template-id. Parse
1574 // it as such.
1575 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001576 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1577 Name, NameLoc,
1578 false, ObjectType, SecondTypeName,
1579 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001580 return ExprError();
1581
David Majnemerced8bdf2015-02-25 17:36:15 +00001582 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1583 SS, FirstTypeName, CCLoc, TildeLoc,
1584 SecondTypeName);
Douglas Gregore610ada2010-02-24 18:44:31 +00001585}
1586
Bill Wendling4073ed52007-02-13 01:51:42 +00001587/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1588///
1589/// boolean-literal: [C++ 2.13.5]
1590/// 'true'
1591/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001592ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001593 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001594 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001595}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001596
1597/// ParseThrowExpression - This handles the C++ throw expression.
1598///
1599/// throw-expression: [C++ 15]
1600/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001601ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001602 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001603 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001604
Chris Lattner65dd8432008-04-06 06:02:23 +00001605 // If the current token isn't the start of an assignment-expression,
1606 // then the expression is not present. This handles things like:
1607 // "C ? throw : (void)42", which is crazy but legal.
1608 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1609 case tok::semi:
1610 case tok::r_paren:
1611 case tok::r_square:
1612 case tok::r_brace:
1613 case tok::colon:
1614 case tok::comma:
Craig Topper161e4db2014-05-21 06:02:52 +00001615 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001616
Chris Lattner65dd8432008-04-06 06:02:23 +00001617 default:
John McCalldadc5752010-08-24 06:29:42 +00001618 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001619 if (Expr.isInvalid()) return Expr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001620 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner65dd8432008-04-06 06:02:23 +00001621 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001622}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001623
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001624/// Parse the C++ Coroutines co_yield expression.
Richard Smith0e304ea2015-10-22 04:46:14 +00001625///
1626/// co_yield-expression:
1627/// 'co_yield' assignment-expression[opt]
1628ExprResult Parser::ParseCoyieldExpression() {
1629 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1630
1631 SourceLocation Loc = ConsumeToken();
Richard Smithae3d1472015-11-20 22:47:10 +00001632 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1633 : ParseAssignmentExpression();
Richard Smithcfd53b42015-10-22 06:13:50 +00001634 if (!Expr.isInvalid())
Richard Smith9f690bd2015-10-27 06:02:45 +00001635 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
Richard Smith0e304ea2015-10-22 04:46:14 +00001636 return Expr;
1637}
1638
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001639/// ParseCXXThis - This handles the C++ 'this' pointer.
1640///
1641/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1642/// a non-lvalue expression whose value is the address of the object for which
1643/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001644ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001645 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1646 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001647 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001648}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001649
1650/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1651/// Can be interpreted either as function-style casting ("int(x)")
1652/// or class type construction ("ClassType(x,y,z)")
1653/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001654/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001655///
1656/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001657/// simple-type-specifier '(' expression-list[opt] ')'
1658/// [C++0x] simple-type-specifier braced-init-list
1659/// typename-specifier '(' expression-list[opt] ')'
1660/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001661///
Richard Smith600b5262017-01-26 20:40:47 +00001662/// In C++1z onwards, the type specifier can also be a template-name.
John McCalldadc5752010-08-24 06:29:42 +00001663ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001664Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Faisal Vali421b2d12017-12-29 05:41:00 +00001665 Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCastContext);
John McCallba7bf592010-08-24 05:47:05 +00001666 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001667
Sebastian Redl3da34892011-06-05 12:23:16 +00001668 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001669 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001670 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001671
Sebastian Redl3da34892011-06-05 12:23:16 +00001672 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001673 ExprResult Init = ParseBraceInitializer();
1674 if (Init.isInvalid())
1675 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001676 Expr *InitList = Init.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001677 return Actions.ActOnCXXTypeConstructExpr(
1678 TypeRep, InitList->getLocStart(), MultiExprArg(&InitList, 1),
1679 InitList->getLocEnd(), /*ListInitialization=*/true);
Sebastian Redl3da34892011-06-05 12:23:16 +00001680 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001681 BalancedDelimiterTracker T(*this, tok::l_paren);
1682 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001683
Benjamin Kramerf0623432012-08-23 22:51:59 +00001684 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001685 CommaLocsTy CommaLocs;
1686
1687 if (Tok.isNot(tok::r_paren)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00001688 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1689 Actions.CodeCompleteConstructor(getCurScope(),
1690 TypeRep.get()->getCanonicalTypeInternal(),
1691 DS.getLocEnd(), Exprs);
1692 })) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001693 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00001694 return ExprError();
1695 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001696 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001697
1698 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001699 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001700
1701 // TypeRep could be null, if it references an invalid typedef.
1702 if (!TypeRep)
1703 return ExprError();
1704
1705 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1706 "Unexpected number of commas!");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001707 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1708 Exprs, T.getCloseLocation(),
1709 /*ListInitialization=*/false);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001710 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001711}
1712
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001713/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001714///
1715/// condition:
1716/// expression
1717/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001718/// [C++11] type-specifier-seq declarator '=' initializer-clause
1719/// [C++11] type-specifier-seq declarator braced-init-list
Zhihao Yuanc81f4532017-12-07 07:03:15 +00001720/// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1721/// brace-or-equal-initializer
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001722/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1723/// '=' assignment-expression
1724///
Richard Smithc7a05a92016-06-29 21:17:59 +00001725/// In C++1z, a condition may in some contexts be preceded by an
1726/// optional init-statement. This function will parse that too.
1727///
1728/// \param InitStmt If non-null, an init-statement is permitted, and if present
1729/// will be parsed and stored here.
1730///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001731/// \param Loc The location of the start of the statement that requires this
1732/// condition, e.g., the "for" in a for loop.
1733///
Richard Smith03a4aa32016-06-23 19:02:52 +00001734/// \returns The parsed condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001735Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1736 SourceLocation Loc,
Richard Smith03a4aa32016-06-23 19:02:52 +00001737 Sema::ConditionKind CK) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00001738 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1739
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001740 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001741 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001742 cutOffParsing();
Richard Smith03a4aa32016-06-23 19:02:52 +00001743 return Sema::ConditionError();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001744 }
1745
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001746 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001747 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001748
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001749 const auto WarnOnInit = [this, &CK] {
1750 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1751 ? diag::warn_cxx14_compat_init_statement
1752 : diag::ext_init_statement)
1753 << (CK == Sema::ConditionKind::Switch);
1754 };
1755
Richard Smithc7a05a92016-06-29 21:17:59 +00001756 // Determine what kind of thing we have.
1757 switch (isCXXConditionDeclarationOrInitStatement(InitStmt)) {
1758 case ConditionOrInitStatement::Expression: {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001759 ProhibitAttributes(attrs);
1760
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001761 // We can have an empty expression here.
1762 // if (; true);
1763 if (InitStmt && Tok.is(tok::semi)) {
1764 WarnOnInit();
1765 SourceLocation SemiLoc = ConsumeToken();
1766 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
1767 return ParseCXXCondition(nullptr, Loc, CK);
1768 }
1769
Douglas Gregore60e41a2010-05-06 17:25:47 +00001770 // Parse the expression.
Richard Smith03a4aa32016-06-23 19:02:52 +00001771 ExprResult Expr = ParseExpression(); // expression
1772 if (Expr.isInvalid())
1773 return Sema::ConditionError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00001774
Richard Smithc7a05a92016-06-29 21:17:59 +00001775 if (InitStmt && Tok.is(tok::semi)) {
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001776 WarnOnInit();
Richard Smithc7a05a92016-06-29 21:17:59 +00001777 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1778 ConsumeToken();
1779 return ParseCXXCondition(nullptr, Loc, CK);
1780 }
1781
Richard Smith03a4aa32016-06-23 19:02:52 +00001782 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001783 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001784
Richard Smithc7a05a92016-06-29 21:17:59 +00001785 case ConditionOrInitStatement::InitStmtDecl: {
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001786 WarnOnInit();
Richard Smithc7a05a92016-06-29 21:17:59 +00001787 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Faisal Vali421b2d12017-12-29 05:41:00 +00001788 DeclGroupPtrTy DG =
1789 ParseSimpleDeclaration(DeclaratorContext::InitStmtContext, DeclEnd,
1790 attrs, /*RequireSemi=*/true);
Richard Smithc7a05a92016-06-29 21:17:59 +00001791 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1792 return ParseCXXCondition(nullptr, Loc, CK);
1793 }
1794
1795 case ConditionOrInitStatement::ConditionDecl:
1796 case ConditionOrInitStatement::Error:
1797 break;
1798 }
1799
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001800 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001801 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001802 DS.takeAttributesFrom(attrs);
Faisal Vali7db85c52017-12-31 00:06:40 +00001803 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001804
1805 // declarator
Faisal Vali421b2d12017-12-29 05:41:00 +00001806 Declarator DeclaratorInfo(DS, DeclaratorContext::ConditionContext);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001807 ParseDeclarator(DeclaratorInfo);
1808
1809 // simple-asm-expr[opt]
1810 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001811 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001812 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001813 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001814 SkipUntil(tok::semi, StopAtSemi);
Richard Smith03a4aa32016-06-23 19:02:52 +00001815 return Sema::ConditionError();
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001816 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001817 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001818 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001819 }
1820
1821 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001822 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001823
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001824 // Type-check the declaration itself.
John McCalldadc5752010-08-24 06:29:42 +00001825 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001826 DeclaratorInfo);
Richard Smith03a4aa32016-06-23 19:02:52 +00001827 if (Dcl.isInvalid())
1828 return Sema::ConditionError();
1829 Decl *DeclOut = Dcl.get();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001830
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001831 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001832 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001833 bool CopyInitialization = isTokenEqualOrEqualTypo();
1834 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001835 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001836
1837 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001838 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001839 Diag(Tok.getLocation(),
1840 diag::warn_cxx98_compat_generalized_initializer_lists);
1841 InitExpr = ParseBraceInitializer();
1842 } else if (CopyInitialization) {
1843 InitExpr = ParseAssignmentExpression();
1844 } else if (Tok.is(tok::l_paren)) {
1845 // This was probably an attempt to initialize the variable.
1846 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001847 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith2a15b742012-02-22 06:49:09 +00001848 RParen = ConsumeParen();
Richard Smith03a4aa32016-06-23 19:02:52 +00001849 Diag(DeclOut->getLocation(),
Richard Smith2a15b742012-02-22 06:49:09 +00001850 diag::err_expected_init_in_condition_lparen)
1851 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001852 } else {
Richard Smith03a4aa32016-06-23 19:02:52 +00001853 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001854 }
Richard Smith2a15b742012-02-22 06:49:09 +00001855
1856 if (!InitExpr.isInvalid())
Richard Smith3beb7c62017-01-12 02:27:38 +00001857 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
Richard Smith27d807c2013-04-30 13:56:41 +00001858 else
1859 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001860
Richard Smithb2bc2e62011-02-21 20:05:19 +00001861 Actions.FinalizeDeclaration(DeclOut);
Richard Smith03a4aa32016-06-23 19:02:52 +00001862 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001863}
1864
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001865/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1866/// This should only be called when the current token is known to be part of
1867/// simple-type-specifier.
1868///
1869/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001870/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001871/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1872/// char
1873/// wchar_t
1874/// bool
1875/// short
1876/// int
1877/// long
1878/// signed
1879/// unsigned
1880/// float
1881/// double
1882/// void
1883/// [GNU] typeof-specifier
1884/// [C++0x] auto [TODO]
1885///
1886/// type-name:
1887/// class-name
1888/// enum-name
1889/// typedef-name
1890///
1891void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1892 DS.SetRangeStart(Tok.getLocation());
1893 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001894 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001895 SourceLocation Loc = Tok.getLocation();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001896 const clang::PrintingPolicy &Policy =
1897 Actions.getASTContext().getPrintingPolicy();
Mike Stump11289f42009-09-09 15:08:12 +00001898
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001899 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001900 case tok::identifier: // foo::bar
1901 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001902 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001903 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001904 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001905
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001906 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001907 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001908 if (getTypeAnnotation(Tok))
1909 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001910 getTypeAnnotation(Tok), Policy);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001911 else
1912 DS.SetTypeSpecError();
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001913
1914 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00001915 ConsumeAnnotationToken();
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001916
Craig Topper25122412015-11-15 03:32:11 +00001917 DS.Finish(Actions, Policy);
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001918 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001919 }
Mike Stump11289f42009-09-09 15:08:12 +00001920
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001921 // builtin types
1922 case tok::kw_short:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001923 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001924 break;
1925 case tok::kw_long:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001926 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001927 break;
Francois Pichet84133e42011-04-28 01:59:37 +00001928 case tok::kw___int64:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001929 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00001930 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001931 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00001932 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001933 break;
1934 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00001935 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001936 break;
1937 case tok::kw_void:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001938 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001939 break;
1940 case tok::kw_char:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001941 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001942 break;
1943 case tok::kw_int:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001944 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001945 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00001946 case tok::kw___int128:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001947 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00001948 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001949 case tok::kw_half:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001950 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001951 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001952 case tok::kw_float:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001953 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001954 break;
1955 case tok::kw_double:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001956 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001957 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001958 case tok::kw__Float16:
1959 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
1960 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001961 case tok::kw___float128:
1962 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
1963 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001964 case tok::kw_wchar_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001965 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001966 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00001967 case tok::kw_char8_t:
1968 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
1969 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001970 case tok::kw_char16_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001971 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001972 break;
1973 case tok::kw_char32_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001974 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001975 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001976 case tok::kw_bool:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001977 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001978 break;
David Blaikie25896afb2012-01-24 05:47:35 +00001979 case tok::annot_decltype:
1980 case tok::kw_decltype:
1981 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Craig Topper25122412015-11-15 03:32:11 +00001982 return DS.Finish(Actions, Policy);
Mike Stump11289f42009-09-09 15:08:12 +00001983
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001984 // GNU typeof support.
1985 case tok::kw_typeof:
1986 ParseTypeofSpecifier(DS);
Craig Topper25122412015-11-15 03:32:11 +00001987 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001988 return;
1989 }
Richard Smithaf3b3252017-05-18 19:21:48 +00001990 ConsumeAnyToken();
1991 DS.SetRangeEnd(PrevTokLocation);
Craig Topper25122412015-11-15 03:32:11 +00001992 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001993}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001994
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001995/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1996/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1997/// e.g., "const short int". Note that the DeclSpec is *not* finished
1998/// by parsing the type-specifier-seq, because these sequences are
1999/// typically followed by some form of declarator. Returns true and
2000/// emits diagnostics if this is not a type-specifier-seq, false
2001/// otherwise.
2002///
2003/// type-specifier-seq: [C++ 8.1]
2004/// type-specifier type-specifier-seq[opt]
2005///
2006bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Faisal Vali7db85c52017-12-31 00:06:40 +00002007 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
Craig Topper25122412015-11-15 03:32:11 +00002008 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002009 return false;
2010}
2011
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002012/// Finish parsing a C++ unqualified-id that is a template-id of
Douglas Gregor7861a802009-11-03 01:35:08 +00002013/// some form.
2014///
2015/// This routine is invoked when a '<' is encountered after an identifier or
2016/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2017/// whether the unqualified-id is actually a template-id. This routine will
2018/// then parse the template arguments and form the appropriate template-id to
2019/// return to the caller.
2020///
2021/// \param SS the nested-name-specifier that precedes this template-id, if
2022/// we're actually parsing a qualified-id.
2023///
2024/// \param Name for constructor and destructor names, this is the actual
2025/// identifier that may be a template-name.
2026///
2027/// \param NameLoc the location of the class-name in a constructor or
2028/// destructor.
2029///
2030/// \param EnteringContext whether we're entering the scope of the
2031/// nested-name-specifier.
2032///
Douglas Gregor127ea592009-11-03 21:24:04 +00002033/// \param ObjectType if this unqualified-id occurs within a member access
2034/// expression, the type of the base object whose member is being accessed.
2035///
Douglas Gregor7861a802009-11-03 01:35:08 +00002036/// \param Id as input, describes the template-name or operator-function-id
2037/// that precedes the '<'. If template arguments were parsed successfully,
2038/// will be updated with the template-id.
2039///
Douglas Gregore610ada2010-02-24 18:44:31 +00002040/// \param AssumeTemplateId When true, this routine will assume that the name
2041/// refers to a template without performing name lookup to verify.
2042///
Douglas Gregor7861a802009-11-03 01:35:08 +00002043/// \returns true if a parse error occurred, false otherwise.
2044bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002045 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002046 IdentifierInfo *Name,
2047 SourceLocation NameLoc,
2048 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002049 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00002050 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002051 bool AssumeTemplateId) {
Richard Smithc08b6932018-04-27 02:00:13 +00002052 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2053
Douglas Gregor7861a802009-11-03 01:35:08 +00002054 TemplateTy Template;
2055 TemplateNameKind TNK = TNK_Non_template;
2056 switch (Id.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00002057 case UnqualifiedIdKind::IK_Identifier:
2058 case UnqualifiedIdKind::IK_OperatorFunctionId:
2059 case UnqualifiedIdKind::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00002060 if (AssumeTemplateId) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002061 // We defer the injected-class-name checks until we've found whether
2062 // this template-id is used to form a nested-name-specifier or not.
2063 TNK = Actions.ActOnDependentTemplateName(
2064 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2065 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002066 if (TNK == TNK_Non_template)
2067 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00002068 } else {
2069 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002070 TNK = Actions.isTemplateName(getCurScope(), SS,
2071 TemplateKWLoc.isValid(), Id,
2072 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00002073 MemberOfUnknownSpecialization);
2074
2075 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2076 ObjectType && IsTemplateArgumentList()) {
2077 // We have something like t->getAs<T>(), where getAs is a
2078 // member of an unknown specialization. However, this will only
2079 // parse correctly as a template, so suggest the keyword 'template'
2080 // before 'getAs' and treat this as a dependent template name.
2081 std::string Name;
Faisal Vali2ab8c152017-12-30 04:15:27 +00002082 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
Douglas Gregor786123d2010-05-21 23:18:07 +00002083 Name = Id.Identifier->getName();
2084 else {
2085 Name = "operator ";
Faisal Vali2ab8c152017-12-30 04:15:27 +00002086 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
Douglas Gregor786123d2010-05-21 23:18:07 +00002087 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2088 else
2089 Name += Id.Identifier->getName();
2090 }
2091 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2092 << Name
2093 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Richard Smithfd3dae02017-01-20 00:20:39 +00002094 TNK = Actions.ActOnDependentTemplateName(
2095 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2096 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002097 if (TNK == TNK_Non_template)
Douglas Gregor786123d2010-05-21 23:18:07 +00002098 return true;
2099 }
2100 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002101 break;
2102
Faisal Vali2ab8c152017-12-30 04:15:27 +00002103 case UnqualifiedIdKind::IK_ConstructorName: {
Douglas Gregor3cf81312009-11-03 23:16:33 +00002104 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002105 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002106 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002107 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2108 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002109 EnteringContext, Template,
2110 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00002111 break;
2112 }
2113
Faisal Vali2ab8c152017-12-30 04:15:27 +00002114 case UnqualifiedIdKind::IK_DestructorName: {
Douglas Gregor3cf81312009-11-03 23:16:33 +00002115 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002116 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002117 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002118 if (ObjectType) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002119 TNK = Actions.ActOnDependentTemplateName(
2120 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2121 EnteringContext, Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002122 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002123 return true;
2124 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002125 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2126 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002127 EnteringContext, Template,
2128 MemberOfUnknownSpecialization);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002129
John McCallba7bf592010-08-24 05:47:05 +00002130 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002131 Diag(NameLoc, diag::err_destructor_template_id)
2132 << Name << SS.getRange();
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002133 return true;
2134 }
2135 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002136 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002137 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002138
2139 default:
2140 return false;
2141 }
2142
2143 if (TNK == TNK_Non_template)
2144 return false;
2145
2146 // Parse the enclosed template argument list.
2147 SourceLocation LAngleLoc, RAngleLoc;
2148 TemplateArgList TemplateArgs;
Richard Smithc08b6932018-04-27 02:00:13 +00002149 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2150 RAngleLoc))
Douglas Gregor7861a802009-11-03 01:35:08 +00002151 return true;
Richard Smithc08b6932018-04-27 02:00:13 +00002152
Faisal Vali2ab8c152017-12-30 04:15:27 +00002153 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2154 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2155 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002156 // Form a parsed representation of the template-id to be stored in the
2157 // UnqualifiedId.
Douglas Gregor7861a802009-11-03 01:35:08 +00002158
Richard Smith72bfbd82013-12-04 00:28:23 +00002159 // FIXME: Store name for literal operator too.
Faisal Vali43caf672017-05-23 01:07:12 +00002160 IdentifierInfo *TemplateII =
Faisal Vali2ab8c152017-12-30 04:15:27 +00002161 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2162 : nullptr;
2163 OverloadedOperatorKind OpKind =
2164 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2165 ? OO_None
2166 : Id.OperatorFunctionId.Operator;
Douglas Gregor7861a802009-11-03 01:35:08 +00002167
Faisal Vali43caf672017-05-23 01:07:12 +00002168 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2169 SS, TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2170 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
2171
Douglas Gregor7861a802009-11-03 01:35:08 +00002172 Id.setTemplateId(TemplateId);
2173 return false;
2174 }
2175
2176 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002177 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002178
Douglas Gregor7861a802009-11-03 01:35:08 +00002179 // Constructor and destructor names.
John McCallfaf5fb42010-08-26 23:41:50 +00002180 TypeResult Type
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002181 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00002182 Template, Name, NameLoc,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002183 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2184 /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00002185 if (Type.isInvalid())
2186 return true;
2187
Faisal Vali2ab8c152017-12-30 04:15:27 +00002188 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
Douglas Gregor7861a802009-11-03 01:35:08 +00002189 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2190 else
2191 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2192
2193 return false;
2194}
2195
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002196/// Parse an operator-function-id or conversion-function-id as part
Douglas Gregor71395fa2009-11-04 00:56:37 +00002197/// of a C++ unqualified-id.
2198///
2199/// This routine is responsible only for parsing the operator-function-id or
2200/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00002201///
2202/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00002203/// operator-function-id: [C++ 13.5]
2204/// 'operator' operator
2205///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002206/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00002207/// new delete new[] delete[]
2208/// + - * / % ^ & | ~
2209/// ! = < > += -= *= /= %=
2210/// ^= &= |= << >> >>= <<= == !=
2211/// <= >= && || ++ -- , ->* ->
Richard Smithd30b23d2017-12-01 02:13:10 +00002212/// () [] <=>
Douglas Gregor7861a802009-11-03 01:35:08 +00002213///
2214/// conversion-function-id: [C++ 12.3.2]
2215/// operator conversion-type-id
2216///
2217/// conversion-type-id:
2218/// type-specifier-seq conversion-declarator[opt]
2219///
2220/// conversion-declarator:
2221/// ptr-operator conversion-declarator[opt]
2222/// \endcode
2223///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002224/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00002225/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2226///
2227/// \param EnteringContext whether we are entering the scope of the
2228/// nested-name-specifier.
2229///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002230/// \param ObjectType if this unqualified-id occurs within a member access
2231/// expression, the type of the base object whose member is being accessed.
2232///
2233/// \param Result on a successful parse, contains the parsed unqualified-id.
2234///
2235/// \returns true if parsing fails, false otherwise.
2236bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002237 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002238 UnqualifiedId &Result) {
2239 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2240
2241 // Consume the 'operator' keyword.
2242 SourceLocation KeywordLoc = ConsumeToken();
2243
2244 // Determine what kind of operator name we have.
2245 unsigned SymbolIdx = 0;
2246 SourceLocation SymbolLocations[3];
2247 OverloadedOperatorKind Op = OO_None;
2248 switch (Tok.getKind()) {
2249 case tok::kw_new:
2250 case tok::kw_delete: {
2251 bool isNew = Tok.getKind() == tok::kw_new;
2252 // Consume the 'new' or 'delete'.
2253 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002254 // Check for array new/delete.
2255 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002256 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002257 // Consume the '[' and ']'.
2258 BalancedDelimiterTracker T(*this, tok::l_square);
2259 T.consumeOpen();
2260 T.consumeClose();
2261 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002262 return true;
2263
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002264 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2265 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002266 Op = isNew? OO_Array_New : OO_Array_Delete;
2267 } else {
2268 Op = isNew? OO_New : OO_Delete;
2269 }
2270 break;
2271 }
2272
2273#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2274 case tok::Token: \
2275 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2276 Op = OO_##Name; \
2277 break;
2278#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2279#include "clang/Basic/OperatorKinds.def"
2280
2281 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002282 // Consume the '(' and ')'.
2283 BalancedDelimiterTracker T(*this, tok::l_paren);
2284 T.consumeOpen();
2285 T.consumeClose();
2286 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002287 return true;
2288
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002289 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2290 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002291 Op = OO_Call;
2292 break;
2293 }
2294
2295 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002296 // Consume the '[' and ']'.
2297 BalancedDelimiterTracker T(*this, tok::l_square);
2298 T.consumeOpen();
2299 T.consumeClose();
2300 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002301 return true;
2302
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002303 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2304 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002305 Op = OO_Subscript;
2306 break;
2307 }
2308
2309 case tok::code_completion: {
2310 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002311 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002312 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002313 // Don't try to parse any further.
2314 return true;
2315 }
2316
2317 default:
2318 break;
2319 }
2320
2321 if (Op != OO_None) {
2322 // We have parsed an operator-function-id.
2323 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2324 return false;
2325 }
Alexis Hunt34458502009-11-28 04:44:28 +00002326
2327 // Parse a literal-operator-id.
2328 //
Richard Smith6f212062012-10-20 08:41:10 +00002329 // literal-operator-id: C++11 [over.literal]
2330 // operator string-literal identifier
2331 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002332
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002333 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002334 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002335
Richard Smith7d182a72012-03-08 23:06:02 +00002336 SourceLocation DiagLoc;
2337 unsigned DiagId = 0;
2338
2339 // We're past translation phase 6, so perform string literal concatenation
2340 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002341 SmallVector<Token, 4> Toks;
2342 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002343 while (isTokenStringLiteral()) {
2344 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002345 // C++11 [over.literal]p1:
2346 // The string-literal or user-defined-string-literal in a
2347 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002348 DiagLoc = Tok.getLocation();
2349 DiagId = diag::err_literal_operator_string_prefix;
2350 }
2351 Toks.push_back(Tok);
2352 TokLocs.push_back(ConsumeStringToken());
2353 }
2354
Craig Topper9d5583e2014-06-26 04:58:39 +00002355 StringLiteralParser Literal(Toks, PP);
Richard Smith7d182a72012-03-08 23:06:02 +00002356 if (Literal.hadError)
2357 return true;
2358
2359 // Grab the literal operator's suffix, which will be either the next token
2360 // or a ud-suffix from the string literal.
Craig Topper161e4db2014-05-21 06:02:52 +00002361 IdentifierInfo *II = nullptr;
Richard Smith7d182a72012-03-08 23:06:02 +00002362 SourceLocation SuffixLoc;
2363 if (!Literal.getUDSuffix().empty()) {
2364 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2365 SuffixLoc =
2366 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2367 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002368 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002369 } else if (Tok.is(tok::identifier)) {
2370 II = Tok.getIdentifierInfo();
2371 SuffixLoc = ConsumeToken();
2372 TokLocs.push_back(SuffixLoc);
2373 } else {
Alp Tokerec543272013-12-24 09:48:30 +00002374 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexis Hunt34458502009-11-28 04:44:28 +00002375 return true;
2376 }
2377
Richard Smith7d182a72012-03-08 23:06:02 +00002378 // The string literal must be empty.
2379 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002380 // C++11 [over.literal]p1:
2381 // The string-literal or user-defined-string-literal in a
2382 // literal-operator-id shall [...] contain no characters
2383 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002384 DiagLoc = TokLocs.front();
2385 DiagId = diag::err_literal_operator_string_not_empty;
2386 }
2387
2388 if (DiagId) {
2389 // This isn't a valid literal-operator-id, but we think we know
2390 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002391 SmallString<32> Str;
Richard Smithe87aeb32015-10-08 00:17:59 +00002392 Str += "\"\"";
Richard Smith7d182a72012-03-08 23:06:02 +00002393 Str += II->getName();
2394 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2395 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2396 }
2397
2398 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Richard Smithd091dc12013-12-05 00:58:33 +00002399
2400 return Actions.checkLiteralOperatorId(SS, Result);
Alexis Hunt34458502009-11-28 04:44:28 +00002401 }
Richard Smithd091dc12013-12-05 00:58:33 +00002402
Douglas Gregor71395fa2009-11-04 00:56:37 +00002403 // Parse a conversion-function-id.
2404 //
2405 // conversion-function-id: [C++ 12.3.2]
2406 // operator conversion-type-id
2407 //
2408 // conversion-type-id:
2409 // type-specifier-seq conversion-declarator[opt]
2410 //
2411 // conversion-declarator:
2412 // ptr-operator conversion-declarator[opt]
2413
2414 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002415 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002416 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002417 return true;
2418
2419 // Parse the conversion-declarator, which is merely a sequence of
2420 // ptr-operators.
Faisal Vali421b2d12017-12-29 05:41:00 +00002421 Declarator D(DS, DeclaratorContext::ConversionIdContext);
Craig Topper161e4db2014-05-21 06:02:52 +00002422 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2423
Douglas Gregor71395fa2009-11-04 00:56:37 +00002424 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002425 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002426 if (Ty.isInvalid())
2427 return true;
2428
2429 // Note that this is a conversion-function-id.
2430 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2431 D.getSourceRange().getEnd());
2432 return false;
2433}
2434
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002435/// Parse a C++ unqualified-id (or a C identifier), which describes the
Douglas Gregor71395fa2009-11-04 00:56:37 +00002436/// name of an entity.
2437///
2438/// \code
2439/// unqualified-id: [C++ expr.prim.general]
2440/// identifier
2441/// operator-function-id
2442/// conversion-function-id
2443/// [C++0x] literal-operator-id [TODO]
2444/// ~ class-name
2445/// template-id
2446///
2447/// \endcode
2448///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002449/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002450/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2451///
2452/// \param EnteringContext whether we are entering the scope of the
2453/// nested-name-specifier.
2454///
Douglas Gregor7861a802009-11-03 01:35:08 +00002455/// \param AllowDestructorName whether we allow parsing of a destructor name.
2456///
2457/// \param AllowConstructorName whether we allow parsing a constructor name.
2458///
Richard Smith35845152017-02-07 01:37:30 +00002459/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2460///
Douglas Gregor127ea592009-11-03 21:24:04 +00002461/// \param ObjectType if this unqualified-id occurs within a member access
2462/// expression, the type of the base object whose member is being accessed.
2463///
Douglas Gregor7861a802009-11-03 01:35:08 +00002464/// \param Result on a successful parse, contains the parsed unqualified-id.
2465///
2466/// \returns true if parsing fails, false otherwise.
2467bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2468 bool AllowDestructorName,
2469 bool AllowConstructorName,
Richard Smith35845152017-02-07 01:37:30 +00002470 bool AllowDeductionGuide,
John McCallba7bf592010-08-24 05:47:05 +00002471 ParsedType ObjectType,
Richard Smithc08b6932018-04-27 02:00:13 +00002472 SourceLocation *TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002473 UnqualifiedId &Result) {
Richard Smithc08b6932018-04-27 02:00:13 +00002474 if (TemplateKWLoc)
2475 *TemplateKWLoc = SourceLocation();
Douglas Gregorb22ee882010-05-05 05:58:24 +00002476
2477 // Handle 'A::template B'. This is for template-ids which have not
2478 // already been annotated by ParseOptionalCXXScopeSpecifier().
2479 bool TemplateSpecified = false;
Richard Smithc08b6932018-04-27 02:00:13 +00002480 if (Tok.is(tok::kw_template)) {
2481 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2482 TemplateSpecified = true;
2483 *TemplateKWLoc = ConsumeToken();
2484 } else {
2485 SourceLocation TemplateLoc = ConsumeToken();
2486 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2487 << FixItHint::CreateRemoval(TemplateLoc);
2488 }
Douglas Gregorb22ee882010-05-05 05:58:24 +00002489 }
2490
Douglas Gregor7861a802009-11-03 01:35:08 +00002491 // unqualified-id:
2492 // identifier
2493 // template-id (when it hasn't already been annotated)
2494 if (Tok.is(tok::identifier)) {
2495 // Consume the identifier.
2496 IdentifierInfo *Id = Tok.getIdentifierInfo();
2497 SourceLocation IdLoc = ConsumeToken();
2498
David Blaikiebbafb8a2012-03-11 07:00:24 +00002499 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002500 // If we're not in C++, only identifiers matter. Record the
2501 // identifier and return.
2502 Result.setIdentifier(Id, IdLoc);
2503 return false;
2504 }
2505
Richard Smith35845152017-02-07 01:37:30 +00002506 ParsedTemplateTy TemplateName;
Douglas Gregor7861a802009-11-03 01:35:08 +00002507 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002508 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002509 // We have parsed a constructor name.
Richard Smith69bc9aa2018-06-22 19:50:19 +00002510 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2511 EnteringContext);
Richard Smith715ee072018-06-20 21:58:20 +00002512 if (!Ty)
2513 return true;
Abramo Bagnara4244b432012-01-27 08:46:19 +00002514 Result.setConstructorName(Ty, IdLoc, IdLoc);
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002515 } else if (getLangOpts().CPlusPlus17 &&
Richard Smith35845152017-02-07 01:37:30 +00002516 AllowDeductionGuide && SS.isEmpty() &&
2517 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2518 &TemplateName)) {
2519 // We have parsed a template-name naming a deduction guide.
2520 Result.setDeductionGuideName(TemplateName, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002521 } else {
2522 // We have parsed an identifier.
2523 Result.setIdentifier(Id, IdLoc);
2524 }
2525
2526 // If the next token is a '<', we may have a template.
Richard Smithc08b6932018-04-27 02:00:13 +00002527 TemplateTy Template;
2528 if (Tok.is(tok::less))
2529 return ParseUnqualifiedIdTemplateId(
2530 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2531 EnteringContext, ObjectType, Result, TemplateSpecified);
2532 else if (TemplateSpecified &&
2533 Actions.ActOnDependentTemplateName(
2534 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2535 EnteringContext, Template,
2536 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2537 return true;
2538
Douglas Gregor7861a802009-11-03 01:35:08 +00002539 return false;
2540 }
2541
2542 // unqualified-id:
2543 // template-id (already parsed and annotated)
2544 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002545 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002546
2547 // If the template-name names the current class, then this is a constructor
2548 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002549 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002550 if (SS.isSet()) {
2551 // C++ [class.qual]p2 specifies that a qualified template-name
2552 // is taken as the constructor name where a constructor can be
2553 // declared. Thus, the template arguments are extraneous, so
2554 // complain about them and remove them entirely.
2555 Diag(TemplateId->TemplateNameLoc,
2556 diag::err_out_of_line_constructor_template_id)
2557 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002558 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002559 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Richard Smith715ee072018-06-20 21:58:20 +00002560 ParsedType Ty = Actions.getConstructorName(
Richard Smith69bc9aa2018-06-22 19:50:19 +00002561 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2562 EnteringContext);
Richard Smith715ee072018-06-20 21:58:20 +00002563 if (!Ty)
2564 return true;
Abramo Bagnara4244b432012-01-27 08:46:19 +00002565 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002566 TemplateId->RAngleLoc);
Richard Smithaf3b3252017-05-18 19:21:48 +00002567 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002568 return false;
2569 }
2570
2571 Result.setConstructorTemplateId(TemplateId);
Richard Smithaf3b3252017-05-18 19:21:48 +00002572 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002573 return false;
2574 }
2575
Douglas Gregor7861a802009-11-03 01:35:08 +00002576 // We have already parsed a template-id; consume the annotation token as
2577 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002578 Result.setTemplateId(TemplateId);
Richard Smithc08b6932018-04-27 02:00:13 +00002579 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2580 if (TemplateLoc.isValid()) {
2581 if (TemplateKWLoc && (ObjectType || SS.isSet()))
2582 *TemplateKWLoc = TemplateLoc;
2583 else
2584 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2585 << FixItHint::CreateRemoval(TemplateLoc);
2586 }
Richard Smithaf3b3252017-05-18 19:21:48 +00002587 ConsumeAnnotationToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00002588 return false;
2589 }
2590
2591 // unqualified-id:
2592 // operator-function-id
2593 // conversion-function-id
2594 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002595 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002596 return true;
2597
Alexis Hunted0530f2009-11-28 08:58:14 +00002598 // If we have an operator-function-id or a literal-operator-id and the next
2599 // token is a '<', we may have a
Douglas Gregor71395fa2009-11-04 00:56:37 +00002600 //
2601 // template-id:
2602 // operator-function-id < template-argument-list[opt] >
Richard Smithc08b6932018-04-27 02:00:13 +00002603 TemplateTy Template;
Faisal Vali2ab8c152017-12-30 04:15:27 +00002604 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2605 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
Richard Smithc08b6932018-04-27 02:00:13 +00002606 Tok.is(tok::less))
2607 return ParseUnqualifiedIdTemplateId(
2608 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2609 SourceLocation(), EnteringContext, ObjectType, Result,
2610 TemplateSpecified);
2611 else if (TemplateSpecified &&
2612 Actions.ActOnDependentTemplateName(
2613 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2614 EnteringContext, Template,
2615 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2616 return true;
Craig Topper161e4db2014-05-21 06:02:52 +00002617
Douglas Gregor7861a802009-11-03 01:35:08 +00002618 return false;
2619 }
2620
David Blaikiebbafb8a2012-03-11 07:00:24 +00002621 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002622 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002623 // C++ [expr.unary.op]p10:
2624 // There is an ambiguity in the unary-expression ~X(), where X is a
2625 // class-name. The ambiguity is resolved in favor of treating ~ as a
2626 // unary complement rather than treating ~X as referring to a destructor.
2627
2628 // Parse the '~'.
2629 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002630
2631 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2632 DeclSpec DS(AttrFactory);
2633 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Richard Smithef2cd8f2017-02-08 20:39:08 +00002634 if (ParsedType Type =
2635 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
David Blaikieecd8a942011-12-08 16:13:53 +00002636 Result.setDestructorName(TildeLoc, Type, EndLoc);
2637 return false;
2638 }
2639 return true;
2640 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002641
2642 // Parse the class-name.
2643 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002644 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002645 return true;
2646 }
2647
Richard Smithefa6f732014-09-06 02:06:12 +00002648 // If the user wrote ~T::T, correct it to T::~T.
Richard Smith64e033f2015-01-15 00:48:52 +00002649 DeclaratorScopeObj DeclScopeObj(*this, SS);
Nico Weber10d02b52015-02-02 04:18:38 +00002650 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
Nico Weberf9e37be2015-01-30 16:53:11 +00002651 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2652 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2653 // it will confuse this recovery logic.
2654 ColonProtectionRAIIObject ColonRAII(*this, false);
2655
Richard Smithefa6f732014-09-06 02:06:12 +00002656 if (SS.isSet()) {
2657 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2658 SS.clear();
2659 }
2660 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2661 return true;
Nico Weber7f8ec522015-02-02 05:33:50 +00002662 if (SS.isNotEmpty())
David Blaikieefdccaa2016-01-15 23:43:34 +00002663 ObjectType = nullptr;
Nico Weberd0045862015-01-30 04:05:15 +00002664 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
Benjamin Kramer3012e592015-03-29 14:35:39 +00002665 !SS.isSet()) {
Richard Smithefa6f732014-09-06 02:06:12 +00002666 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2667 return true;
2668 }
2669
2670 // Recover as if the tilde had been written before the identifier.
2671 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2672 << FixItHint::CreateRemoval(TildeLoc)
2673 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
Richard Smith64e033f2015-01-15 00:48:52 +00002674
2675 // Temporarily enter the scope for the rest of this function.
2676 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2677 DeclScopeObj.EnterDeclaratorScope();
Richard Smithefa6f732014-09-06 02:06:12 +00002678 }
2679
Douglas Gregor7861a802009-11-03 01:35:08 +00002680 // Parse the class-name (or template-name in a simple-template-id).
2681 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2682 SourceLocation ClassNameLoc = ConsumeToken();
Richard Smithefa6f732014-09-06 02:06:12 +00002683
Richard Smithc08b6932018-04-27 02:00:13 +00002684 if (Tok.is(tok::less)) {
David Blaikieefdccaa2016-01-15 23:43:34 +00002685 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
Richard Smithc08b6932018-04-27 02:00:13 +00002686 return ParseUnqualifiedIdTemplateId(
2687 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
2688 ClassNameLoc, EnteringContext, ObjectType, Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002689 }
Richard Smithefa6f732014-09-06 02:06:12 +00002690
Douglas Gregor7861a802009-11-03 01:35:08 +00002691 // Note that this is a destructor name.
John McCallba7bf592010-08-24 05:47:05 +00002692 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2693 ClassNameLoc, getCurScope(),
2694 SS, ObjectType,
2695 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002696 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002697 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002698
Douglas Gregor7861a802009-11-03 01:35:08 +00002699 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002700 return false;
2701 }
2702
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002703 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002704 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002705 return true;
2706}
2707
Sebastian Redlbd150f42008-11-21 19:14:01 +00002708/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2709/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002710///
Chris Lattner109faf22009-01-04 21:25:24 +00002711/// This method is called to parse the new expression after the optional :: has
2712/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2713/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002714///
2715/// new-expression:
2716/// '::'[opt] 'new' new-placement[opt] new-type-id
2717/// new-initializer[opt]
2718/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2719/// new-initializer[opt]
2720///
2721/// new-placement:
2722/// '(' expression-list ')'
2723///
Sebastian Redl351bb782008-12-02 14:43:59 +00002724/// new-type-id:
2725/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002726/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002727///
2728/// new-declarator:
2729/// ptr-operator new-declarator[opt]
2730/// direct-new-declarator
2731///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002732/// new-initializer:
2733/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002734/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002735///
John McCalldadc5752010-08-24 06:29:42 +00002736ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002737Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2738 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2739 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002740
2741 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2742 // second form of new-expression. It can't be a new-type-id.
2743
Benjamin Kramerf0623432012-08-23 22:51:59 +00002744 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002745 SourceLocation PlacementLParen, PlacementRParen;
2746
Douglas Gregorf2753b32010-07-13 15:54:32 +00002747 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002748 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00002749 Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002750 if (Tok.is(tok::l_paren)) {
2751 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002752 BalancedDelimiterTracker T(*this, tok::l_paren);
2753 T.consumeOpen();
2754 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002755 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002756 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002757 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002758 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002759
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002760 T.consumeClose();
2761 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002762 if (PlacementRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002763 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002764 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002765 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002766
Sebastian Redl351bb782008-12-02 14:43:59 +00002767 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002768 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002769 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002770 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002771 } else {
2772 // We still need the type.
2773 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002774 BalancedDelimiterTracker T(*this, tok::l_paren);
2775 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002776 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002777 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002778 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002779 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002780 T.consumeClose();
2781 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002782 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002783 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002784 if (ParseCXXTypeSpecifierSeq(DS))
2785 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002786 else {
2787 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002788 ParseDeclaratorInternal(DeclaratorInfo,
2789 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002790 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002791 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002792 }
2793 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002794 // A new-type-id is a simplified type-id, where essentially the
2795 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00002796 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002797 if (ParseCXXTypeSpecifierSeq(DS))
2798 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002799 else {
2800 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002801 ParseDeclaratorInternal(DeclaratorInfo,
2802 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002803 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002804 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002805 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002806 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002807 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002808 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002809
Sebastian Redl6047f072012-02-16 12:22:20 +00002810 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002811
2812 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002813 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002814 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002815 BalancedDelimiterTracker T(*this, tok::l_paren);
2816 T.consumeOpen();
2817 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002818 if (Tok.isNot(tok::r_paren)) {
2819 CommaLocsTy CommaLocs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002820 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2821 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2822 DeclaratorInfo).get();
2823 Actions.CodeCompleteConstructor(getCurScope(),
2824 TypeRep.get()->getCanonicalTypeInternal(),
2825 DeclaratorInfo.getLocEnd(),
2826 ConstructorArgs);
2827 })) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002828 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002829 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002830 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002831 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002832 T.consumeClose();
2833 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002834 if (ConstructorRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002835 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002836 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002837 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002838 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2839 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002840 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002841 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002842 Diag(Tok.getLocation(),
2843 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002844 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002845 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002846 if (Initializer.isInvalid())
2847 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002848
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002849 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002850 PlacementArgs, PlacementRParen,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002851 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002852}
2853
Sebastian Redlbd150f42008-11-21 19:14:01 +00002854/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2855/// passed to ParseDeclaratorInternal.
2856///
2857/// direct-new-declarator:
2858/// '[' expression ']'
2859/// direct-new-declarator '[' constant-expression ']'
2860///
Chris Lattner109faf22009-01-04 21:25:24 +00002861void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002862 // Parse the array dimensions.
2863 bool first = true;
2864 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002865 // An array-size expression can't start with a lambda.
2866 if (CheckProhibitedCXX11Attribute())
2867 continue;
2868
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002869 BalancedDelimiterTracker T(*this, tok::l_square);
2870 T.consumeOpen();
2871
John McCalldadc5752010-08-24 06:29:42 +00002872 ExprResult Size(first ? ParseExpression()
Sebastian Redl59b5e512008-12-11 21:36:32 +00002873 : ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002874 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002875 // Recover
Alexey Bataevee6507d2013-11-18 08:17:37 +00002876 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002877 return;
2878 }
2879 first = false;
2880
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002881 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002882
Bill Wendling44426052012-12-20 19:22:21 +00002883 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002884 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002885 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002886
John McCall084e83d2011-03-24 11:26:52 +00002887 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002888 /*static=*/false, /*star=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002889 Size.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002890 T.getOpenLocation(),
2891 T.getCloseLocation()),
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002892 Attrs, T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002893
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002894 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00002895 return;
2896 }
2897}
2898
2899/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2900/// This ambiguity appears in the syntax of the C++ new operator.
2901///
2902/// new-expression:
2903/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2904/// new-initializer[opt]
2905///
2906/// new-placement:
2907/// '(' expression-list ')'
2908///
John McCall37ad5512010-08-23 06:44:23 +00002909bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002910 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00002911 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002912 // The '(' was already consumed.
2913 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002914 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002915 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002916 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002917 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002918 }
2919
2920 // It's not a type, it has to be an expression list.
2921 // Discard the comma locations - ActOnCXXNew has enough parameters.
2922 CommaLocsTy CommaLocs;
2923 return ParseExpressionList(PlacementArgs, CommaLocs);
2924}
2925
2926/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2927/// to free memory allocated by new.
2928///
Chris Lattner109faf22009-01-04 21:25:24 +00002929/// This method is called to parse the 'delete' expression after the optional
2930/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2931/// and "Start" is its location. Otherwise, "Start" is the location of the
2932/// 'delete' token.
2933///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002934/// delete-expression:
2935/// '::'[opt] 'delete' cast-expression
2936/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00002937ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002938Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2939 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2940 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002941
2942 // Array delete?
2943 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002944 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00002945 // C++11 [expr.delete]p1:
2946 // Whenever the delete keyword is followed by empty square brackets, it
2947 // shall be interpreted as [array delete].
2948 // [Footnote: A lambda expression with a lambda-introducer that consists
2949 // of empty square brackets can follow the delete keyword if
2950 // the lambda expression is enclosed in parentheses.]
2951 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2952 // lambda-introducer.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002953 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002954 BalancedDelimiterTracker T(*this, tok::l_square);
2955
2956 T.consumeOpen();
2957 T.consumeClose();
2958 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00002959 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002960 }
2961
John McCalldadc5752010-08-24 06:29:42 +00002962 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002963 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002964 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002965
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002966 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002967}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002968
Douglas Gregor29c42f22012-02-24 07:38:34 +00002969static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2970 switch (kind) {
2971 default: llvm_unreachable("Not a known type trait");
Alp Toker95e7ff22014-01-01 05:57:51 +00002972#define TYPE_TRAIT_1(Spelling, Name, Key) \
2973case tok::kw_ ## Spelling: return UTT_ ## Name;
Alp Tokercbb90342013-12-13 20:49:58 +00002974#define TYPE_TRAIT_2(Spelling, Name, Key) \
2975case tok::kw_ ## Spelling: return BTT_ ## Name;
2976#include "clang/Basic/TokenKinds.def"
Alp Toker40f9b1c2013-12-12 21:23:03 +00002977#define TYPE_TRAIT_N(Spelling, Name, Key) \
2978 case tok::kw_ ## Spelling: return TT_ ## Name;
2979#include "clang/Basic/TokenKinds.def"
Douglas Gregor29c42f22012-02-24 07:38:34 +00002980 }
2981}
2982
John Wiegley6242b6a2011-04-28 00:16:57 +00002983static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2984 switch(kind) {
2985 default: llvm_unreachable("Not a known binary type trait");
2986 case tok::kw___array_rank: return ATT_ArrayRank;
2987 case tok::kw___array_extent: return ATT_ArrayExtent;
2988 }
2989}
2990
John Wiegleyf9f65842011-04-25 06:54:41 +00002991static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2992 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002993 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00002994 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2995 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2996 }
2997}
2998
Alp Toker40f9b1c2013-12-12 21:23:03 +00002999static unsigned TypeTraitArity(tok::TokenKind kind) {
3000 switch (kind) {
3001 default: llvm_unreachable("Not a known type trait");
3002#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3003#include "clang/Basic/TokenKinds.def"
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003004 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003005}
3006
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003007/// Parse the built-in type-trait pseudo-functions that allow
Douglas Gregor29c42f22012-02-24 07:38:34 +00003008/// implementation of the TR1/C++11 type traits templates.
3009///
3010/// primary-expression:
Alp Toker40f9b1c2013-12-12 21:23:03 +00003011/// unary-type-trait '(' type-id ')'
3012/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor29c42f22012-02-24 07:38:34 +00003013/// type-trait '(' type-id-seq ')'
3014///
3015/// type-id-seq:
3016/// type-id ...[opt] type-id-seq[opt]
3017///
3018ExprResult Parser::ParseTypeTrait() {
Alp Toker40f9b1c2013-12-12 21:23:03 +00003019 tok::TokenKind Kind = Tok.getKind();
3020 unsigned Arity = TypeTraitArity(Kind);
3021
Douglas Gregor29c42f22012-02-24 07:38:34 +00003022 SourceLocation Loc = ConsumeToken();
3023
3024 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003025 if (Parens.expectAndConsume())
Douglas Gregor29c42f22012-02-24 07:38:34 +00003026 return ExprError();
3027
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003028 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00003029 do {
3030 // Parse the next type.
3031 TypeResult Ty = ParseTypeName();
3032 if (Ty.isInvalid()) {
3033 Parens.skipToEnd();
3034 return ExprError();
3035 }
3036
3037 // Parse the ellipsis, if present.
3038 if (Tok.is(tok::ellipsis)) {
3039 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3040 if (Ty.isInvalid()) {
3041 Parens.skipToEnd();
3042 return ExprError();
3043 }
3044 }
3045
3046 // Add this type to the list of arguments.
3047 Args.push_back(Ty.get());
Alp Tokera3ebe6e2013-12-17 14:12:37 +00003048 } while (TryConsumeToken(tok::comma));
3049
Douglas Gregor29c42f22012-02-24 07:38:34 +00003050 if (Parens.consumeClose())
3051 return ExprError();
Alp Toker40f9b1c2013-12-12 21:23:03 +00003052
3053 SourceLocation EndLoc = Parens.getCloseLocation();
3054
3055 if (Arity && Args.size() != Arity) {
3056 Diag(EndLoc, diag::err_type_trait_arity)
3057 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3058 return ExprError();
3059 }
3060
3061 if (!Arity && Args.empty()) {
3062 Diag(EndLoc, diag::err_type_trait_arity)
3063 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3064 return ExprError();
3065 }
3066
Alp Toker88f64e62013-12-13 21:19:30 +00003067 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor29c42f22012-02-24 07:38:34 +00003068}
3069
John Wiegley6242b6a2011-04-28 00:16:57 +00003070/// ParseArrayTypeTrait - Parse the built-in array type-trait
3071/// pseudo-functions.
3072///
3073/// primary-expression:
3074/// [Embarcadero] '__array_rank' '(' type-id ')'
3075/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3076///
3077ExprResult Parser::ParseArrayTypeTrait() {
3078 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3079 SourceLocation Loc = ConsumeToken();
3080
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003081 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003082 if (T.expectAndConsume())
John Wiegley6242b6a2011-04-28 00:16:57 +00003083 return ExprError();
3084
3085 TypeResult Ty = ParseTypeName();
3086 if (Ty.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003087 SkipUntil(tok::comma, StopAtSemi);
3088 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003089 return ExprError();
3090 }
3091
3092 switch (ATT) {
3093 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003094 T.consumeClose();
Craig Topper161e4db2014-05-21 06:02:52 +00003095 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003096 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003097 }
3098 case ATT_ArrayExtent: {
Alp Toker383d2c42014-01-01 03:08:43 +00003099 if (ExpectAndConsume(tok::comma)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003100 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003101 return ExprError();
3102 }
3103
3104 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003105 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00003106
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003107 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3108 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003109 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003110 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003111 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00003112}
3113
John Wiegleyf9f65842011-04-25 06:54:41 +00003114/// ParseExpressionTrait - Parse built-in expression-trait
3115/// pseudo-functions like __is_lvalue_expr( xxx ).
3116///
3117/// primary-expression:
3118/// [Embarcadero] expression-trait '(' expression ')'
3119///
3120ExprResult Parser::ParseExpressionTrait() {
3121 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3122 SourceLocation Loc = ConsumeToken();
3123
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003124 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003125 if (T.expectAndConsume())
John Wiegleyf9f65842011-04-25 06:54:41 +00003126 return ExprError();
3127
3128 ExprResult Expr = ParseExpression();
3129
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003130 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00003131
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003132 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3133 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00003134}
3135
3136
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003137/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3138/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3139/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00003140ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003141Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00003142 ParsedType &CastTy,
Richard Smith87e11a42014-05-15 02:43:47 +00003143 BalancedDelimiterTracker &Tracker,
3144 ColonProtectionRAIIObject &ColonProt) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003145 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003146 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3147 assert(isTypeIdInParens() && "Not a type-id!");
3148
John McCalldadc5752010-08-24 06:29:42 +00003149 ExprResult Result(true);
David Blaikieefdccaa2016-01-15 23:43:34 +00003150 CastTy = nullptr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003151
3152 // We need to disambiguate a very ugly part of the C++ syntax:
3153 //
3154 // (T())x; - type-id
3155 // (T())*x; - type-id
3156 // (T())/x; - expression
3157 // (T()); - expression
3158 //
3159 // The bad news is that we cannot use the specialized tentative parser, since
3160 // it can only verify that the thing inside the parens can be parsed as
3161 // type-id, it is not useful for determining the context past the parens.
3162 //
3163 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00003164 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003165 //
3166 // It uses a scheme similar to parsing inline methods. The parenthesized
3167 // tokens are cached, the context that follows is determined (possibly by
3168 // parsing a cast-expression), and then we re-introduce the cached tokens
3169 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003170
Mike Stump11289f42009-09-09 15:08:12 +00003171 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003172 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003173
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003174 // Store the tokens of the parentheses. We will parse them after we determine
3175 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00003176 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003177 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003178 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003179 return ExprError();
3180 }
3181
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003182 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003183 ParseAs = CompoundLiteral;
3184 } else {
3185 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00003186 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3187 NotCastExpr = true;
3188 } else {
3189 // Try parsing the cast-expression that may follow.
3190 // If it is not a cast-expression, NotCastExpr will be true and no token
3191 // will be consumed.
Richard Smith87e11a42014-05-15 02:43:47 +00003192 ColonProt.restore();
Eli Friedmancf7530f2009-05-25 19:41:42 +00003193 Result = ParseCastExpression(false/*isUnaryExpression*/,
3194 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00003195 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003196 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00003197 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00003198 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003199
3200 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3201 // an expression.
3202 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003203 }
3204
Alexey Bataev703a93c2016-02-04 04:22:09 +00003205 // Create a fake EOF to mark end of Toks buffer.
3206 Token AttrEnd;
3207 AttrEnd.startToken();
3208 AttrEnd.setKind(tok::eof);
3209 AttrEnd.setLocation(Tok.getLocation());
3210 AttrEnd.setEofData(Toks.data());
3211 Toks.push_back(AttrEnd);
3212
Mike Stump11289f42009-09-09 15:08:12 +00003213 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003214 Toks.push_back(Tok);
3215 // Re-enter the stored parenthesized tokens into the token stream, so we may
3216 // parse them now.
David Blaikie2eabcc92016-02-09 18:52:09 +00003217 PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003218 // Drop the current token and bring the first cached one. It's the same token
3219 // as when we entered this function.
3220 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003221
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003222 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003223 // Parse the type declarator.
3224 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00003225 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Richard Smith87e11a42014-05-15 02:43:47 +00003226 {
3227 ColonProtectionRAIIObject InnerColonProtection(*this);
3228 ParseSpecifierQualifierList(DS);
3229 ParseDeclarator(DeclaratorInfo);
3230 }
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003231
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003232 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003233 Tracker.consumeClose();
Richard Smith87e11a42014-05-15 02:43:47 +00003234 ColonProt.restore();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003235
Alexey Bataev703a93c2016-02-04 04:22:09 +00003236 // Consume EOF marker for Toks buffer.
3237 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3238 ConsumeAnyToken();
3239
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003240 if (ParseAs == CompoundLiteral) {
3241 ExprType = CompoundLiteral;
Richard Smithaba8b362014-05-15 02:51:15 +00003242 if (DeclaratorInfo.isInvalidType())
3243 return ExprError();
3244
3245 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Richard Smith87e11a42014-05-15 02:43:47 +00003246 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003247 Tracker.getOpenLocation(),
3248 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003249 }
Mike Stump11289f42009-09-09 15:08:12 +00003250
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003251 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3252 assert(ParseAs == CastExpr);
3253
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003254 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003255 return ExprError();
3256
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003257 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003258 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003259 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3260 DeclaratorInfo, CastTy,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003261 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003262 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003263 }
Mike Stump11289f42009-09-09 15:08:12 +00003264
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003265 // Not a compound literal, and not followed by a cast-expression.
3266 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003267
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003268 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003269 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003270 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003271 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003272 Tok.getLocation(), Result.get());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003273
3274 // Match the ')'.
3275 if (Result.isInvalid()) {
Alexey Bataev703a93c2016-02-04 04:22:09 +00003276 while (Tok.isNot(tok::eof))
3277 ConsumeAnyToken();
3278 assert(Tok.getEofData() == AttrEnd.getEofData());
3279 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003280 return ExprError();
3281 }
Mike Stump11289f42009-09-09 15:08:12 +00003282
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003283 Tracker.consumeClose();
Alexey Bataev703a93c2016-02-04 04:22:09 +00003284 // Consume EOF marker for Toks buffer.
3285 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3286 ConsumeAnyToken();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003287 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003288}