Bug Summary

File:clang/lib/Parse/ParseExprCXX.cpp
Warning:line 2054, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ParseExprCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/build-llvm/tools/clang/lib/Parse -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/build-llvm/tools/clang/lib/Parse -I /build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse -I /build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include -I /build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/build-llvm/tools/clang/lib/Parse -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-03-15-022507-3198-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp

/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp

1//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expression parsing implementation for C++.
10//
11//===----------------------------------------------------------------------===//
12#include "clang/Parse/Parser.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/Decl.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/Basic/PrettyStackTrace.h"
18#include "clang/Lex/LiteralSupport.h"
19#include "clang/Parse/ParseDiagnostic.h"
20#include "clang/Parse/RAIIObjectsForParser.h"
21#include "clang/Sema/DeclSpec.h"
22#include "clang/Sema/ParsedTemplate.h"
23#include "clang/Sema/Scope.h"
24#include "llvm/Support/ErrorHandling.h"
25#include <numeric>
26
27using namespace clang;
28
29static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
30 switch (Kind) {
31 // template name
32 case tok::unknown: return 0;
33 // casts
34 case tok::kw_addrspace_cast: return 1;
35 case tok::kw_const_cast: return 2;
36 case tok::kw_dynamic_cast: return 3;
37 case tok::kw_reinterpret_cast: return 4;
38 case tok::kw_static_cast: return 5;
39 default:
40 llvm_unreachable("Unknown type for digraph error message.")::llvm::llvm_unreachable_internal("Unknown type for digraph error message."
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 40)
;
41 }
42}
43
44// Are the two tokens adjacent in the same source file?
45bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
46 SourceManager &SM = PP.getSourceManager();
47 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
48 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
49 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
50}
51
52// Suggest fixit for "<::" after a cast.
53static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
54 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
55 // Pull '<:' and ':' off token stream.
56 if (!AtDigraph)
57 PP.Lex(DigraphToken);
58 PP.Lex(ColonToken);
59
60 SourceRange Range;
61 Range.setBegin(DigraphToken.getLocation());
62 Range.setEnd(ColonToken.getLocation());
63 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
64 << SelectDigraphErrorMessage(Kind)
65 << FixItHint::CreateReplacement(Range, "< ::");
66
67 // Update token information to reflect their change in token type.
68 ColonToken.setKind(tok::coloncolon);
69 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
70 ColonToken.setLength(2);
71 DigraphToken.setKind(tok::less);
72 DigraphToken.setLength(1);
73
74 // Push new tokens back to token stream.
75 PP.EnterToken(ColonToken, /*IsReinject*/ true);
76 if (!AtDigraph)
77 PP.EnterToken(DigraphToken, /*IsReinject*/ true);
78}
79
80// Check for '<::' which should be '< ::' instead of '[:' when following
81// a template name.
82void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
83 bool EnteringContext,
84 IdentifierInfo &II, CXXScopeSpec &SS) {
85 if (!Next.is(tok::l_square) || Next.getLength() != 2)
86 return;
87
88 Token SecondToken = GetLookAheadToken(2);
89 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
90 return;
91
92 TemplateTy Template;
93 UnqualifiedId TemplateName;
94 TemplateName.setIdentifier(&II, Tok.getLocation());
95 bool MemberOfUnknownSpecialization;
96 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
97 TemplateName, ObjectType, EnteringContext,
98 Template, MemberOfUnknownSpecialization))
99 return;
100
101 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
102 /*AtDigraph*/false);
103}
104
105/// Parse global scope or nested-name-specifier if present.
106///
107/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
108/// may be preceded by '::'). Note that this routine will not parse ::new or
109/// ::delete; it will just leave them in the token stream.
110///
111/// '::'[opt] nested-name-specifier
112/// '::'
113///
114/// nested-name-specifier:
115/// type-name '::'
116/// namespace-name '::'
117/// nested-name-specifier identifier '::'
118/// nested-name-specifier 'template'[opt] simple-template-id '::'
119///
120///
121/// \param SS the scope specifier that will be set to the parsed
122/// nested-name-specifier (or empty)
123///
124/// \param ObjectType if this nested-name-specifier is being parsed following
125/// the "." or "->" of a member access expression, this parameter provides the
126/// type of the object whose members are being accessed.
127///
128/// \param ObjectHadErrors if this unqualified-id occurs within a member access
129/// expression, indicates whether the original subexpressions had any errors.
130/// When true, diagnostics for missing 'template' keyword will be supressed.
131///
132/// \param EnteringContext whether we will be entering into the context of
133/// the nested-name-specifier after parsing it.
134///
135/// \param MayBePseudoDestructor When non-NULL, points to a flag that
136/// indicates whether this nested-name-specifier may be part of a
137/// pseudo-destructor name. In this case, the flag will be set false
138/// if we don't actually end up parsing a destructor name. Moreover,
139/// if we do end up determining that we are parsing a destructor name,
140/// the last component of the nested-name-specifier is not parsed as
141/// part of the scope specifier.
142///
143/// \param IsTypename If \c true, this nested-name-specifier is known to be
144/// part of a type name. This is used to improve error recovery.
145///
146/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
147/// filled in with the leading identifier in the last component of the
148/// nested-name-specifier, if any.
149///
150/// \param OnlyNamespace If true, only considers namespaces in lookup.
151///
152///
153/// \returns true if there was an error parsing a scope specifier
154bool Parser::ParseOptionalCXXScopeSpecifier(
155 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
156 bool EnteringContext, bool *MayBePseudoDestructor, bool IsTypename,
157 IdentifierInfo **LastII, bool OnlyNamespace, bool InUsingDeclaration) {
158 assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "Call sites of this function should be guarded by checking for C++"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Call sites of this function should be guarded by checking for C++\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 159, __PRETTY_FUNCTION__))
159 "Call sites of this function should be guarded by checking for C++")((getLangOpts().CPlusPlus && "Call sites of this function should be guarded by checking for C++"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Call sites of this function should be guarded by checking for C++\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 159, __PRETTY_FUNCTION__))
;
160
161 if (Tok.is(tok::annot_cxxscope)) {
162 assert(!LastII && "want last identifier but have already annotated scope")((!LastII && "want last identifier but have already annotated scope"
) ? static_cast<void> (0) : __assert_fail ("!LastII && \"want last identifier but have already annotated scope\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 162, __PRETTY_FUNCTION__))
;
163 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope")((!MayBePseudoDestructor && "unexpected annot_cxxscope"
) ? static_cast<void> (0) : __assert_fail ("!MayBePseudoDestructor && \"unexpected annot_cxxscope\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 163, __PRETTY_FUNCTION__))
;
164 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
165 Tok.getAnnotationRange(),
166 SS);
167 ConsumeAnnotationToken();
168 return false;
169 }
170
171 // Has to happen before any "return false"s in this function.
172 bool CheckForDestructor = false;
173 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
174 CheckForDestructor = true;
175 *MayBePseudoDestructor = false;
176 }
177
178 if (LastII)
179 *LastII = nullptr;
180
181 bool HasScopeSpecifier = false;
182
183 if (Tok.is(tok::coloncolon)) {
184 // ::new and ::delete aren't nested-name-specifiers.
185 tok::TokenKind NextKind = NextToken().getKind();
186 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
187 return false;
188
189 if (NextKind == tok::l_brace) {
190 // It is invalid to have :: {, consume the scope qualifier and pretend
191 // like we never saw it.
192 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
193 } else {
194 // '::' - Global scope qualifier.
195 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
196 return true;
197
198 HasScopeSpecifier = true;
199 }
200 }
201
202 if (Tok.is(tok::kw___super)) {
203 SourceLocation SuperLoc = ConsumeToken();
204 if (!Tok.is(tok::coloncolon)) {
205 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
206 return true;
207 }
208
209 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
210 }
211
212 if (!HasScopeSpecifier &&
213 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
214 DeclSpec DS(AttrFactory);
215 SourceLocation DeclLoc = Tok.getLocation();
216 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
217
218 SourceLocation CCLoc;
219 // Work around a standard defect: 'decltype(auto)::' is not a
220 // nested-name-specifier.
221 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
222 !TryConsumeToken(tok::coloncolon, CCLoc)) {
223 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
224 return false;
225 }
226
227 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
228 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
229
230 HasScopeSpecifier = true;
231 }
232
233 // Preferred type might change when parsing qualifiers, we need the original.
234 auto SavedType = PreferredType;
235 while (true) {
236 if (HasScopeSpecifier) {
237 if (Tok.is(tok::code_completion)) {
238 // Code completion for a nested-name-specifier, where the code
239 // completion token follows the '::'.
240 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext,
241 InUsingDeclaration, ObjectType.get(),
242 SavedType.get(SS.getBeginLoc()));
243 // Include code completion token into the range of the scope otherwise
244 // when we try to annotate the scope tokens the dangling code completion
245 // token will cause assertion in
246 // Preprocessor::AnnotatePreviousCachedTokens.
247 SS.setEndLoc(Tok.getLocation());
248 cutOffParsing();
249 return true;
250 }
251
252 // C++ [basic.lookup.classref]p5:
253 // If the qualified-id has the form
254 //
255 // ::class-name-or-namespace-name::...
256 //
257 // the class-name-or-namespace-name is looked up in global scope as a
258 // class-name or namespace-name.
259 //
260 // To implement this, we clear out the object type as soon as we've
261 // seen a leading '::' or part of a nested-name-specifier.
262 ObjectType = nullptr;
263 }
264
265 // nested-name-specifier:
266 // nested-name-specifier 'template'[opt] simple-template-id '::'
267
268 // Parse the optional 'template' keyword, then make sure we have
269 // 'identifier <' after it.
270 if (Tok.is(tok::kw_template)) {
271 // If we don't have a scope specifier or an object type, this isn't a
272 // nested-name-specifier, since they aren't allowed to start with
273 // 'template'.
274 if (!HasScopeSpecifier && !ObjectType)
275 break;
276
277 TentativeParsingAction TPA(*this);
278 SourceLocation TemplateKWLoc = ConsumeToken();
279
280 UnqualifiedId TemplateName;
281 if (Tok.is(tok::identifier)) {
282 // Consume the identifier.
283 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
284 ConsumeToken();
285 } else if (Tok.is(tok::kw_operator)) {
286 // We don't need to actually parse the unqualified-id in this case,
287 // because a simple-template-id cannot start with 'operator', but
288 // go ahead and parse it anyway for consistency with the case where
289 // we already annotated the template-id.
290 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
291 TemplateName)) {
292 TPA.Commit();
293 break;
294 }
295
296 if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId &&
297 TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) {
298 Diag(TemplateName.getSourceRange().getBegin(),
299 diag::err_id_after_template_in_nested_name_spec)
300 << TemplateName.getSourceRange();
301 TPA.Commit();
302 break;
303 }
304 } else {
305 TPA.Revert();
306 break;
307 }
308
309 // If the next token is not '<', we have a qualified-id that refers
310 // to a template name, such as T::template apply, but is not a
311 // template-id.
312 if (Tok.isNot(tok::less)) {
313 TPA.Revert();
314 break;
315 }
316
317 // Commit to parsing the template-id.
318 TPA.Commit();
319 TemplateTy Template;
320 TemplateNameKind TNK = Actions.ActOnTemplateName(
321 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
322 EnteringContext, Template, /*AllowInjectedClassName*/ true);
323 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
324 TemplateName, false))
325 return true;
326
327 continue;
328 }
329
330 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
331 // We have
332 //
333 // template-id '::'
334 //
335 // So we need to check whether the template-id is a simple-template-id of
336 // the right kind (it should name a type or be dependent), and then
337 // convert it into a type within the nested-name-specifier.
338 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
339 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
340 *MayBePseudoDestructor = true;
341 return false;
342 }
343
344 if (LastII)
345 *LastII = TemplateId->Name;
346
347 // Consume the template-id token.
348 ConsumeAnnotationToken();
349
350 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!")((Tok.is(tok::coloncolon) && "NextToken() not working properly!"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::coloncolon) && \"NextToken() not working properly!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 350, __PRETTY_FUNCTION__))
;
351 SourceLocation CCLoc = ConsumeToken();
352
353 HasScopeSpecifier = true;
354
355 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
356 TemplateId->NumArgs);
357
358 if (TemplateId->isInvalid() ||
359 Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
360 SS,
361 TemplateId->TemplateKWLoc,
362 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));
373 }
374
375 continue;
376 }
377
378 // 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();
390 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
391 ObjectType);
392
393 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
394 // and emit a fixit hint for it.
395 if (Next.is(tok::colon) && !ColonIsSacred) {
396 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
397 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)) {
402 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
403 << FixItHint::CreateReplacement(Next.getLocation(), "::");
404 // Recover as if the user wrote '::'.
405 Next.setKind(tok::coloncolon);
406 }
407 }
408
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 '::'.
414 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
415 << tok::identifier;
416 UnconsumeToken(Identifier); // Stick the identifier back.
417 Next = NextToken(); // Point Next at the '{' token.
418 }
419
420 if (Next.is(tok::coloncolon)) {
421 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
422 *MayBePseudoDestructor = true;
423 return false;
424 }
425
426 if (ColonIsSacred) {
427 const Token &Next2 = GetLookAheadToken(2);
428 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
429 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
430 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
431 << Next2.getName()
432 << FixItHint::CreateReplacement(Next.getLocation(), ":");
433 Token ColonColon;
434 PP.Lex(ColonColon);
435 ColonColon.setKind(tok::colon);
436 PP.EnterToken(ColonColon, /*IsReinject*/ true);
437 break;
438 }
439 }
440
441 if (LastII)
442 *LastII = &II;
443
444 // We have an identifier followed by a '::'. Lookup this name
445 // as the name in a nested-name-specifier.
446 Token Identifier = Tok;
447 SourceLocation IdLoc = ConsumeToken();
448 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&((Tok.isOneOf(tok::coloncolon, tok::colon) && "NextToken() not working properly!"
) ? static_cast<void> (0) : __assert_fail ("Tok.isOneOf(tok::coloncolon, tok::colon) && \"NextToken() not working properly!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 449, __PRETTY_FUNCTION__))
449 "NextToken() not working properly!")((Tok.isOneOf(tok::coloncolon, tok::colon) && "NextToken() not working properly!"
) ? static_cast<void> (0) : __assert_fail ("Tok.isOneOf(tok::coloncolon, tok::colon) && \"NextToken() not working properly!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 449, __PRETTY_FUNCTION__))
;
450 Token ColonColon = Tok;
451 SourceLocation CCLoc = ConsumeToken();
452
453 bool IsCorrectedToColon = false;
454 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
455 if (Actions.ActOnCXXNestedNameSpecifier(
456 getCurScope(), IdInfo, EnteringContext, SS, false,
457 CorrectionFlagPtr, OnlyNamespace)) {
458 // Identifier is not recognized as a nested name, but we can have
459 // mistyped '::' instead of ':'.
460 if (CorrectionFlagPtr && IsCorrectedToColon) {
461 ColonColon.setKind(tok::colon);
462 PP.EnterToken(Tok, /*IsReinject*/ true);
463 PP.EnterToken(ColonColon, /*IsReinject*/ true);
464 Tok = Identifier;
465 break;
466 }
467 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
468 }
469 HasScopeSpecifier = true;
470 continue;
471 }
472
473 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
474
475 // nested-name-specifier:
476 // type-name '<'
477 if (Next.is(tok::less)) {
478
479 TemplateTy Template;
480 UnqualifiedId TemplateName;
481 TemplateName.setIdentifier(&II, Tok.getLocation());
482 bool MemberOfUnknownSpecialization;
483 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
484 /*hasTemplateKeyword=*/false,
485 TemplateName,
486 ObjectType,
487 EnteringContext,
488 Template,
489 MemberOfUnknownSpecialization)) {
490 // If lookup didn't find anything, we treat the name as a template-name
491 // anyway. C++20 requires this, and in prior language modes it improves
492 // error recovery. But before we commit to this, check that we actually
493 // have something that looks like a template-argument-list next.
494 if (!IsTypename && TNK == TNK_Undeclared_template &&
495 isTemplateArgumentList(1) == TPResult::False)
496 break;
497
498 // We have found a template name, so annotate this token
499 // with a template-id annotation. We do not permit the
500 // template-id to be translated into a type annotation,
501 // because some clients (e.g., the parsing of class template
502 // specializations) still want to see the original template-id
503 // token, and it might not be a type at all (e.g. a concept name in a
504 // type-constraint).
505 ConsumeToken();
506 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
507 TemplateName, false))
508 return true;
509 continue;
510 }
511
512 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
513 (IsTypename || isTemplateArgumentList(1) == TPResult::True)) {
514 // If we had errors before, ObjectType can be dependent even without any
515 // templates. Do not report missing template keyword in that case.
516 if (!ObjectHadErrors) {
517 // We have something like t::getAs<T>, where getAs is a
518 // member of an unknown specialization. However, this will only
519 // parse correctly as a template, so suggest the keyword 'template'
520 // before 'getAs' and treat this as a dependent template name.
521 unsigned DiagID = diag::err_missing_dependent_template_keyword;
522 if (getLangOpts().MicrosoftExt)
523 DiagID = diag::warn_missing_dependent_template_keyword;
524
525 Diag(Tok.getLocation(), DiagID)
526 << II.getName()
527 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
528 }
529
530 SourceLocation TemplateNameLoc = ConsumeToken();
531
532 TemplateNameKind TNK = Actions.ActOnTemplateName(
533 getCurScope(), SS, TemplateNameLoc, TemplateName, ObjectType,
534 EnteringContext, Template, /*AllowInjectedClassName*/ true);
535 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
536 TemplateName, false))
537 return true;
538
539 continue;
540 }
541 }
542
543 // We don't have any tokens that form the beginning of a
544 // nested-name-specifier, so we're done.
545 break;
546 }
547
548 // Even if we didn't see any pieces of a nested-name-specifier, we
549 // still check whether there is a tilde in this position, which
550 // indicates a potential pseudo-destructor.
551 if (CheckForDestructor && !HasScopeSpecifier && Tok.is(tok::tilde))
552 *MayBePseudoDestructor = true;
553
554 return false;
555}
556
557ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS,
558 bool isAddressOfOperand,
559 Token &Replacement) {
560 ExprResult E;
561
562 // We may have already annotated this id-expression.
563 switch (Tok.getKind()) {
564 case tok::annot_non_type: {
565 NamedDecl *ND = getNonTypeAnnotation(Tok);
566 SourceLocation Loc = ConsumeAnnotationToken();
567 E = Actions.ActOnNameClassifiedAsNonType(getCurScope(), SS, ND, Loc, Tok);
568 break;
569 }
570
571 case tok::annot_non_type_dependent: {
572 IdentifierInfo *II = getIdentifierAnnotation(Tok);
573 SourceLocation Loc = ConsumeAnnotationToken();
574
575 // This is only the direct operand of an & operator if it is not
576 // followed by a postfix-expression suffix.
577 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
578 isAddressOfOperand = false;
579
580 E = Actions.ActOnNameClassifiedAsDependentNonType(SS, II, Loc,
581 isAddressOfOperand);
582 break;
583 }
584
585 case tok::annot_non_type_undeclared: {
586 assert(SS.isEmpty() &&((SS.isEmpty() && "undeclared non-type annotation should be unqualified"
) ? static_cast<void> (0) : __assert_fail ("SS.isEmpty() && \"undeclared non-type annotation should be unqualified\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 587, __PRETTY_FUNCTION__))
587 "undeclared non-type annotation should be unqualified")((SS.isEmpty() && "undeclared non-type annotation should be unqualified"
) ? static_cast<void> (0) : __assert_fail ("SS.isEmpty() && \"undeclared non-type annotation should be unqualified\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 587, __PRETTY_FUNCTION__))
;
588 IdentifierInfo *II = getIdentifierAnnotation(Tok);
589 SourceLocation Loc = ConsumeAnnotationToken();
590 E = Actions.ActOnNameClassifiedAsUndeclaredNonType(II, Loc);
591 break;
592 }
593
594 default:
595 SourceLocation TemplateKWLoc;
596 UnqualifiedId Name;
597 if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
598 /*ObjectHadErrors=*/false,
599 /*EnteringContext=*/false,
600 /*AllowDestructorName=*/false,
601 /*AllowConstructorName=*/false,
602 /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name))
603 return ExprError();
604
605 // This is only the direct operand of an & operator if it is not
606 // followed by a postfix-expression suffix.
607 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
608 isAddressOfOperand = false;
609
610 E = Actions.ActOnIdExpression(
611 getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
612 isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false,
613 &Replacement);
614 break;
615 }
616
617 if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
618 checkPotentialAngleBracket(E);
619 return E;
620}
621
622/// ParseCXXIdExpression - Handle id-expression.
623///
624/// id-expression:
625/// unqualified-id
626/// qualified-id
627///
628/// qualified-id:
629/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
630/// '::' identifier
631/// '::' operator-function-id
632/// '::' template-id
633///
634/// NOTE: The standard specifies that, for qualified-id, the parser does not
635/// expect:
636///
637/// '::' conversion-function-id
638/// '::' '~' class-name
639///
640/// This may cause a slight inconsistency on diagnostics:
641///
642/// class C {};
643/// namespace A {}
644/// void f() {
645/// :: A :: ~ C(); // Some Sema error about using destructor with a
646/// // namespace.
647/// :: ~ C(); // Some Parser error like 'unexpected ~'.
648/// }
649///
650/// We simplify the parser a bit and make it work like:
651///
652/// qualified-id:
653/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
654/// '::' unqualified-id
655///
656/// That way Sema can handle and report similar errors for namespaces and the
657/// global scope.
658///
659/// The isAddressOfOperand parameter indicates that this id-expression is a
660/// direct operand of the address-of operator. This is, besides member contexts,
661/// the only place where a qualified-id naming a non-static class member may
662/// appear.
663///
664ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
665 // qualified-id:
666 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
667 // '::' unqualified-id
668 //
669 CXXScopeSpec SS;
670 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
671 /*ObjectHadErrors=*/false,
672 /*EnteringContext=*/false);
673
674 Token Replacement;
675 ExprResult Result =
676 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
677 if (Result.isUnset()) {
678 // If the ExprResult is valid but null, then typo correction suggested a
679 // keyword replacement that needs to be reparsed.
680 UnconsumeToken(Replacement);
681 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
682 }
683 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "((!Result.isUnset() && "Typo correction suggested a keyword replacement "
"for a previous keyword suggestion") ? static_cast<void>
(0) : __assert_fail ("!Result.isUnset() && \"Typo correction suggested a keyword replacement \" \"for a previous keyword suggestion\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 684, __PRETTY_FUNCTION__))
684 "for a previous keyword suggestion")((!Result.isUnset() && "Typo correction suggested a keyword replacement "
"for a previous keyword suggestion") ? static_cast<void>
(0) : __assert_fail ("!Result.isUnset() && \"Typo correction suggested a keyword replacement \" \"for a previous keyword suggestion\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 684, __PRETTY_FUNCTION__))
;
685 return Result;
686}
687
688/// ParseLambdaExpression - Parse a C++11 lambda expression.
689///
690/// lambda-expression:
691/// lambda-introducer lambda-declarator[opt] compound-statement
692/// lambda-introducer '<' template-parameter-list '>'
693/// lambda-declarator[opt] compound-statement
694///
695/// lambda-introducer:
696/// '[' lambda-capture[opt] ']'
697///
698/// lambda-capture:
699/// capture-default
700/// capture-list
701/// capture-default ',' capture-list
702///
703/// capture-default:
704/// '&'
705/// '='
706///
707/// capture-list:
708/// capture
709/// capture-list ',' capture
710///
711/// capture:
712/// simple-capture
713/// init-capture [C++1y]
714///
715/// simple-capture:
716/// identifier
717/// '&' identifier
718/// 'this'
719///
720/// init-capture: [C++1y]
721/// identifier initializer
722/// '&' identifier initializer
723///
724/// lambda-declarator:
725/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
726/// 'mutable'[opt] exception-specification[opt]
727/// trailing-return-type[opt]
728///
729ExprResult Parser::ParseLambdaExpression() {
730 // Parse lambda-introducer.
731 LambdaIntroducer Intro;
732 if (ParseLambdaIntroducer(Intro)) {
733 SkipUntil(tok::r_square, StopAtSemi);
734 SkipUntil(tok::l_brace, StopAtSemi);
735 SkipUntil(tok::r_brace, StopAtSemi);
736 return ExprError();
737 }
738
739 return ParseLambdaExpressionAfterIntroducer(Intro);
740}
741
742/// Use lookahead and potentially tentative parsing to determine if we are
743/// looking at a C++11 lambda expression, and parse it if we are.
744///
745/// If we are not looking at a lambda expression, returns ExprError().
746ExprResult Parser::TryParseLambdaExpression() {
747 assert(getLangOpts().CPlusPlus11((getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) &&
"Not at the start of a possible lambda expression.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && \"Not at the start of a possible lambda expression.\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 749, __PRETTY_FUNCTION__))
748 && Tok.is(tok::l_square)((getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) &&
"Not at the start of a possible lambda expression.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && \"Not at the start of a possible lambda expression.\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 749, __PRETTY_FUNCTION__))
749 && "Not at the start of a possible lambda expression.")((getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) &&
"Not at the start of a possible lambda expression.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && \"Not at the start of a possible lambda expression.\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 749, __PRETTY_FUNCTION__))
;
750
751 const Token Next = NextToken();
752 if (Next.is(tok::eof)) // Nothing else to lookup here...
753 return ExprEmpty();
754
755 const Token After = GetLookAheadToken(2);
756 // If lookahead indicates this is a lambda...
757 if (Next.is(tok::r_square) || // []
758 Next.is(tok::equal) || // [=
759 (Next.is(tok::amp) && // [&] or [&,
760 After.isOneOf(tok::r_square, tok::comma)) ||
761 (Next.is(tok::identifier) && // [identifier]
762 After.is(tok::r_square)) ||
763 Next.is(tok::ellipsis)) { // [...
764 return ParseLambdaExpression();
765 }
766
767 // If lookahead indicates an ObjC message send...
768 // [identifier identifier
769 if (Next.is(tok::identifier) && After.is(tok::identifier))
770 return ExprEmpty();
771
772 // Here, we're stuck: lambda introducers and Objective-C message sends are
773 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
774 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
775 // writing two routines to parse a lambda introducer, just try to parse
776 // a lambda introducer first, and fall back if that fails.
777 LambdaIntroducer Intro;
778 {
779 TentativeParsingAction TPA(*this);
780 LambdaIntroducerTentativeParse Tentative;
781 if (ParseLambdaIntroducer(Intro, &Tentative)) {
782 TPA.Commit();
783 return ExprError();
784 }
785
786 switch (Tentative) {
787 case LambdaIntroducerTentativeParse::Success:
788 TPA.Commit();
789 break;
790
791 case LambdaIntroducerTentativeParse::Incomplete:
792 // Didn't fully parse the lambda-introducer, try again with a
793 // non-tentative parse.
794 TPA.Revert();
795 Intro = LambdaIntroducer();
796 if (ParseLambdaIntroducer(Intro))
797 return ExprError();
798 break;
799
800 case LambdaIntroducerTentativeParse::MessageSend:
801 case LambdaIntroducerTentativeParse::Invalid:
802 // Not a lambda-introducer, might be a message send.
803 TPA.Revert();
804 return ExprEmpty();
805 }
806 }
807
808 return ParseLambdaExpressionAfterIntroducer(Intro);
809}
810
811/// Parse a lambda introducer.
812/// \param Intro A LambdaIntroducer filled in with information about the
813/// contents of the lambda-introducer.
814/// \param Tentative If non-null, we are disambiguating between a
815/// lambda-introducer and some other construct. In this mode, we do not
816/// produce any diagnostics or take any other irreversible action unless
817/// we're sure that this is a lambda-expression.
818/// \return \c true if parsing (or disambiguation) failed with a diagnostic and
819/// the caller should bail out / recover.
820bool Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
821 LambdaIntroducerTentativeParse *Tentative) {
822 if (Tentative)
823 *Tentative = LambdaIntroducerTentativeParse::Success;
824
825 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.")((Tok.is(tok::l_square) && "Lambda expressions begin with '['."
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::l_square) && \"Lambda expressions begin with '['.\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 825, __PRETTY_FUNCTION__))
;
826 BalancedDelimiterTracker T(*this, tok::l_square);
827 T.consumeOpen();
828
829 Intro.Range.setBegin(T.getOpenLocation());
830
831 bool First = true;
832
833 // Produce a diagnostic if we're not tentatively parsing; otherwise track
834 // that our parse has failed.
835 auto Invalid = [&](llvm::function_ref<void()> Action) {
836 if (Tentative) {
837 *Tentative = LambdaIntroducerTentativeParse::Invalid;
838 return false;
839 }
840 Action();
841 return true;
842 };
843
844 // Perform some irreversible action if this is a non-tentative parse;
845 // otherwise note that our actions were incomplete.
846 auto NonTentativeAction = [&](llvm::function_ref<void()> Action) {
847 if (Tentative)
848 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
849 else
850 Action();
851 };
852
853 // Parse capture-default.
854 if (Tok.is(tok::amp) &&
855 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
856 Intro.Default = LCD_ByRef;
857 Intro.DefaultLoc = ConsumeToken();
858 First = false;
859 if (!Tok.getIdentifierInfo()) {
860 // This can only be a lambda; no need for tentative parsing any more.
861 // '[[and]]' can still be an attribute, though.
862 Tentative = nullptr;
863 }
864 } else if (Tok.is(tok::equal)) {
865 Intro.Default = LCD_ByCopy;
866 Intro.DefaultLoc = ConsumeToken();
867 First = false;
868 Tentative = nullptr;
869 }
870
871 while (Tok.isNot(tok::r_square)) {
872 if (!First) {
873 if (Tok.isNot(tok::comma)) {
874 // Provide a completion for a lambda introducer here. Except
875 // in Objective-C, where this is Almost Surely meant to be a message
876 // send. In that case, fail here and let the ObjC message
877 // expression parser perform the completion.
878 if (Tok.is(tok::code_completion) &&
879 !(getLangOpts().ObjC && Tentative)) {
880 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
881 /*AfterAmpersand=*/false);
882 cutOffParsing();
883 break;
884 }
885
886 return Invalid([&] {
887 Diag(Tok.getLocation(), diag::err_expected_comma_or_rsquare);
888 });
889 }
890 ConsumeToken();
891 }
892
893 if (Tok.is(tok::code_completion)) {
894 // If we're in Objective-C++ and we have a bare '[', then this is more
895 // likely to be a message receiver.
896 if (getLangOpts().ObjC && Tentative && First)
897 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
898 else
899 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
900 /*AfterAmpersand=*/false);
901 cutOffParsing();
902 break;
903 }
904
905 First = false;
906
907 // Parse capture.
908 LambdaCaptureKind Kind = LCK_ByCopy;
909 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
910 SourceLocation Loc;
911 IdentifierInfo *Id = nullptr;
912 SourceLocation EllipsisLocs[4];
913 ExprResult Init;
914 SourceLocation LocStart = Tok.getLocation();
915
916 if (Tok.is(tok::star)) {
917 Loc = ConsumeToken();
918 if (Tok.is(tok::kw_this)) {
919 ConsumeToken();
920 Kind = LCK_StarThis;
921 } else {
922 return Invalid([&] {
923 Diag(Tok.getLocation(), diag::err_expected_star_this_capture);
924 });
925 }
926 } else if (Tok.is(tok::kw_this)) {
927 Kind = LCK_This;
928 Loc = ConsumeToken();
929 } else if (Tok.isOneOf(tok::amp, tok::equal) &&
930 NextToken().isOneOf(tok::comma, tok::r_square) &&
931 Intro.Default == LCD_None) {
932 // We have a lone "&" or "=" which is either a misplaced capture-default
933 // or the start of a capture (in the "&" case) with the rest of the
934 // capture missing. Both are an error but a misplaced capture-default
935 // is more likely if we don't already have a capture default.
936 return Invalid(
937 [&] { Diag(Tok.getLocation(), diag::err_capture_default_first); });
938 } else {
939 TryConsumeToken(tok::ellipsis, EllipsisLocs[0]);
940
941 if (Tok.is(tok::amp)) {
942 Kind = LCK_ByRef;
943 ConsumeToken();
944
945 if (Tok.is(tok::code_completion)) {
946 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
947 /*AfterAmpersand=*/true);
948 cutOffParsing();
949 break;
950 }
951 }
952
953 TryConsumeToken(tok::ellipsis, EllipsisLocs[1]);
954
955 if (Tok.is(tok::identifier)) {
956 Id = Tok.getIdentifierInfo();
957 Loc = ConsumeToken();
958 } else if (Tok.is(tok::kw_this)) {
959 return Invalid([&] {
960 // FIXME: Suggest a fixit here.
961 Diag(Tok.getLocation(), diag::err_this_captured_by_reference);
962 });
963 } else {
964 return Invalid([&] {
965 Diag(Tok.getLocation(), diag::err_expected_capture);
966 });
967 }
968
969 TryConsumeToken(tok::ellipsis, EllipsisLocs[2]);
970
971 if (Tok.is(tok::l_paren)) {
972 BalancedDelimiterTracker Parens(*this, tok::l_paren);
973 Parens.consumeOpen();
974
975 InitKind = LambdaCaptureInitKind::DirectInit;
976
977 ExprVector Exprs;
978 CommaLocsTy Commas;
979 if (Tentative) {
980 Parens.skipToEnd();
981 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
982 } else if (ParseExpressionList(Exprs, Commas)) {
983 Parens.skipToEnd();
984 Init = ExprError();
985 } else {
986 Parens.consumeClose();
987 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
988 Parens.getCloseLocation(),
989 Exprs);
990 }
991 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
992 // Each lambda init-capture forms its own full expression, which clears
993 // Actions.MaybeODRUseExprs. So create an expression evaluation context
994 // to save the necessary state, and restore it later.
995 EnterExpressionEvaluationContext EC(
996 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
997
998 if (TryConsumeToken(tok::equal))
999 InitKind = LambdaCaptureInitKind::CopyInit;
1000 else
1001 InitKind = LambdaCaptureInitKind::ListInit;
1002
1003 if (!Tentative) {
1004 Init = ParseInitializer();
1005 } else if (Tok.is(tok::l_brace)) {
1006 BalancedDelimiterTracker Braces(*this, tok::l_brace);
1007 Braces.consumeOpen();
1008 Braces.skipToEnd();
1009 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
1010 } else {
1011 // We're disambiguating this:
1012 //
1013 // [..., x = expr
1014 //
1015 // We need to find the end of the following expression in order to
1016 // determine whether this is an Obj-C message send's receiver, a
1017 // C99 designator, or a lambda init-capture.
1018 //
1019 // Parse the expression to find where it ends, and annotate it back
1020 // onto the tokens. We would have parsed this expression the same way
1021 // in either case: both the RHS of an init-capture and the RHS of an
1022 // assignment expression are parsed as an initializer-clause, and in
1023 // neither case can anything be added to the scope between the '[' and
1024 // here.
1025 //
1026 // FIXME: This is horrible. Adding a mechanism to skip an expression
1027 // would be much cleaner.
1028 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
1029 // that instead. (And if we see a ':' with no matching '?', we can
1030 // classify this as an Obj-C message send.)
1031 SourceLocation StartLoc = Tok.getLocation();
1032 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
1033 Init = ParseInitializer();
1034 if (!Init.isInvalid())
1035 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
1036
1037 if (Tok.getLocation() != StartLoc) {
1038 // Back out the lexing of the token after the initializer.
1039 PP.RevertCachedTokens(1);
1040
1041 // Replace the consumed tokens with an appropriate annotation.
1042 Tok.setLocation(StartLoc);
1043 Tok.setKind(tok::annot_primary_expr);
1044 setExprAnnotation(Tok, Init);
1045 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
1046 PP.AnnotateCachedTokens(Tok);
1047
1048 // Consume the annotated initializer.
1049 ConsumeAnnotationToken();
1050 }
1051 }
1052 }
1053
1054 TryConsumeToken(tok::ellipsis, EllipsisLocs[3]);
1055 }
1056
1057 // Check if this is a message send before we act on a possible init-capture.
1058 if (Tentative && Tok.is(tok::identifier) &&
1059 NextToken().isOneOf(tok::colon, tok::r_square)) {
1060 // This can only be a message send. We're done with disambiguation.
1061 *Tentative = LambdaIntroducerTentativeParse::MessageSend;
1062 return false;
1063 }
1064
1065 // Ensure that any ellipsis was in the right place.
1066 SourceLocation EllipsisLoc;
1067 if (std::any_of(std::begin(EllipsisLocs), std::end(EllipsisLocs),
1068 [](SourceLocation Loc) { return Loc.isValid(); })) {
1069 // The '...' should appear before the identifier in an init-capture, and
1070 // after the identifier otherwise.
1071 bool InitCapture = InitKind != LambdaCaptureInitKind::NoInit;
1072 SourceLocation *ExpectedEllipsisLoc =
1073 !InitCapture ? &EllipsisLocs[2] :
1074 Kind == LCK_ByRef ? &EllipsisLocs[1] :
1075 &EllipsisLocs[0];
1076 EllipsisLoc = *ExpectedEllipsisLoc;
1077
1078 unsigned DiagID = 0;
1079 if (EllipsisLoc.isInvalid()) {
1080 DiagID = diag::err_lambda_capture_misplaced_ellipsis;
1081 for (SourceLocation Loc : EllipsisLocs) {
1082 if (Loc.isValid())
1083 EllipsisLoc = Loc;
1084 }
1085 } else {
1086 unsigned NumEllipses = std::accumulate(
1087 std::begin(EllipsisLocs), std::end(EllipsisLocs), 0,
1088 [](int N, SourceLocation Loc) { return N + Loc.isValid(); });
1089 if (NumEllipses > 1)
1090 DiagID = diag::err_lambda_capture_multiple_ellipses;
1091 }
1092 if (DiagID) {
1093 NonTentativeAction([&] {
1094 // Point the diagnostic at the first misplaced ellipsis.
1095 SourceLocation DiagLoc;
1096 for (SourceLocation &Loc : EllipsisLocs) {
1097 if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) {
1098 DiagLoc = Loc;
1099 break;
1100 }
1101 }
1102 assert(DiagLoc.isValid() && "no location for diagnostic")((DiagLoc.isValid() && "no location for diagnostic") ?
static_cast<void> (0) : __assert_fail ("DiagLoc.isValid() && \"no location for diagnostic\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1102, __PRETTY_FUNCTION__))
;
1103
1104 // Issue the diagnostic and produce fixits showing where the ellipsis
1105 // should have been written.
1106 auto &&D = Diag(DiagLoc, DiagID);
1107 if (DiagID == diag::err_lambda_capture_misplaced_ellipsis) {
1108 SourceLocation ExpectedLoc =
1109 InitCapture ? Loc
1110 : Lexer::getLocForEndOfToken(
1111 Loc, 0, PP.getSourceManager(), getLangOpts());
1112 D << InitCapture << FixItHint::CreateInsertion(ExpectedLoc, "...");
1113 }
1114 for (SourceLocation &Loc : EllipsisLocs) {
1115 if (&Loc != ExpectedEllipsisLoc && Loc.isValid())
1116 D << FixItHint::CreateRemoval(Loc);
1117 }
1118 });
1119 }
1120 }
1121
1122 // Process the init-capture initializers now rather than delaying until we
1123 // form the lambda-expression so that they can be handled in the context
1124 // enclosing the lambda-expression, rather than in the context of the
1125 // lambda-expression itself.
1126 ParsedType InitCaptureType;
1127 if (Init.isUsable())
1128 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
1129 if (Init.isUsable()) {
1130 NonTentativeAction([&] {
1131 // Get the pointer and store it in an lvalue, so we can use it as an
1132 // out argument.
1133 Expr *InitExpr = Init.get();
1134 // This performs any lvalue-to-rvalue conversions if necessary, which
1135 // can affect what gets captured in the containing decl-context.
1136 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
1137 Loc, Kind == LCK_ByRef, EllipsisLoc, Id, InitKind, InitExpr);
1138 Init = InitExpr;
1139 });
1140 }
1141
1142 SourceLocation LocEnd = PrevTokLocation;
1143
1144 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
1145 InitCaptureType, SourceRange(LocStart, LocEnd));
1146 }
1147
1148 T.consumeClose();
1149 Intro.Range.setEnd(T.getCloseLocation());
1150 return false;
1151}
1152
1153static void tryConsumeLambdaSpecifierToken(Parser &P,
1154 SourceLocation &MutableLoc,
1155 SourceLocation &ConstexprLoc,
1156 SourceLocation &ConstevalLoc,
1157 SourceLocation &DeclEndLoc) {
1158 assert(MutableLoc.isInvalid())((MutableLoc.isInvalid()) ? static_cast<void> (0) : __assert_fail
("MutableLoc.isInvalid()", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1158, __PRETTY_FUNCTION__))
;
1159 assert(ConstexprLoc.isInvalid())((ConstexprLoc.isInvalid()) ? static_cast<void> (0) : __assert_fail
("ConstexprLoc.isInvalid()", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1159, __PRETTY_FUNCTION__))
;
1160 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1161 // to the final of those locations. Emit an error if we have multiple
1162 // copies of those keywords and recover.
1163
1164 while (true) {
1165 switch (P.getCurToken().getKind()) {
1166 case tok::kw_mutable: {
1167 if (MutableLoc.isValid()) {
1168 P.Diag(P.getCurToken().getLocation(),
1169 diag::err_lambda_decl_specifier_repeated)
1170 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1171 }
1172 MutableLoc = P.ConsumeToken();
1173 DeclEndLoc = MutableLoc;
1174 break /*switch*/;
1175 }
1176 case tok::kw_constexpr:
1177 if (ConstexprLoc.isValid()) {
1178 P.Diag(P.getCurToken().getLocation(),
1179 diag::err_lambda_decl_specifier_repeated)
1180 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1181 }
1182 ConstexprLoc = P.ConsumeToken();
1183 DeclEndLoc = ConstexprLoc;
1184 break /*switch*/;
1185 case tok::kw_consteval:
1186 if (ConstevalLoc.isValid()) {
1187 P.Diag(P.getCurToken().getLocation(),
1188 diag::err_lambda_decl_specifier_repeated)
1189 << 2 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1190 }
1191 ConstevalLoc = P.ConsumeToken();
1192 DeclEndLoc = ConstevalLoc;
1193 break /*switch*/;
1194 default:
1195 return;
1196 }
1197 }
1198}
1199
1200static void
1201addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1202 DeclSpec &DS) {
1203 if (ConstexprLoc.isValid()) {
1204 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
1205 ? diag::ext_constexpr_on_lambda_cxx17
1206 : diag::warn_cxx14_compat_constexpr_on_lambda);
1207 const char *PrevSpec = nullptr;
1208 unsigned DiagID = 0;
1209 DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, ConstexprLoc, PrevSpec,
1210 DiagID);
1211 assert(PrevSpec == nullptr && DiagID == 0 &&((PrevSpec == nullptr && DiagID == 0 && "Constexpr cannot have been set previously!"
) ? static_cast<void> (0) : __assert_fail ("PrevSpec == nullptr && DiagID == 0 && \"Constexpr cannot have been set previously!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1212, __PRETTY_FUNCTION__))
1212 "Constexpr cannot have been set previously!")((PrevSpec == nullptr && DiagID == 0 && "Constexpr cannot have been set previously!"
) ? static_cast<void> (0) : __assert_fail ("PrevSpec == nullptr && DiagID == 0 && \"Constexpr cannot have been set previously!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1212, __PRETTY_FUNCTION__))
;
1213 }
1214}
1215
1216static void addConstevalToLambdaDeclSpecifier(Parser &P,
1217 SourceLocation ConstevalLoc,
1218 DeclSpec &DS) {
1219 if (ConstevalLoc.isValid()) {
1220 P.Diag(ConstevalLoc, diag::warn_cxx20_compat_consteval);
1221 const char *PrevSpec = nullptr;
1222 unsigned DiagID = 0;
1223 DS.SetConstexprSpec(ConstexprSpecKind::Consteval, ConstevalLoc, PrevSpec,
1224 DiagID);
1225 if (DiagID != 0)
1226 P.Diag(ConstevalLoc, DiagID) << PrevSpec;
1227 }
1228}
1229
1230/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1231/// expression.
1232ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1233 LambdaIntroducer &Intro) {
1234 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1235 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1236
1237 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1238 "lambda expression parsing");
1239
1240
1241
1242 // FIXME: Call into Actions to add any init-capture declarations to the
1243 // scope while parsing the lambda-declarator and compound-statement.
1244
1245 // Parse lambda-declarator[opt].
1246 DeclSpec DS(AttrFactory);
1247 Declarator D(DS, DeclaratorContext::LambdaExpr);
1248 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1249 Actions.PushLambdaScope();
1250
1251 ParsedAttributes Attr(AttrFactory);
1252 SourceLocation DeclLoc = Tok.getLocation();
1253 if (getLangOpts().CUDA) {
1254 // In CUDA code, GNU attributes are allowed to appear immediately after the
1255 // "[...]", even if there is no "(...)" before the lambda body.
1256 MaybeParseGNUAttributes(D);
1257 }
1258
1259 // Helper to emit a warning if we see a CUDA host/device/global attribute
1260 // after '(...)'. nvcc doesn't accept this.
1261 auto WarnIfHasCUDATargetAttr = [&] {
1262 if (getLangOpts().CUDA)
1263 for (const ParsedAttr &A : Attr)
1264 if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1265 A.getKind() == ParsedAttr::AT_CUDAHost ||
1266 A.getKind() == ParsedAttr::AT_CUDAGlobal)
1267 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1268 << A.getAttrName()->getName();
1269 };
1270
1271 MultiParseScope TemplateParamScope(*this);
1272 if (Tok.is(tok::less)) {
1273 Diag(Tok, getLangOpts().CPlusPlus20
1274 ? diag::warn_cxx17_compat_lambda_template_parameter_list
1275 : diag::ext_lambda_template_parameter_list);
1276
1277 SmallVector<NamedDecl*, 4> TemplateParams;
1278 SourceLocation LAngleLoc, RAngleLoc;
1279 if (ParseTemplateParameters(TemplateParamScope,
1280 CurTemplateDepthTracker.getDepth(),
1281 TemplateParams, LAngleLoc, RAngleLoc)) {
1282 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1283 return ExprError();
1284 }
1285
1286 if (TemplateParams.empty()) {
1287 Diag(RAngleLoc,
1288 diag::err_lambda_template_parameter_list_empty);
1289 } else {
1290 ExprResult RequiresClause;
1291 if (TryConsumeToken(tok::kw_requires)) {
1292 RequiresClause =
1293 Actions.ActOnRequiresClause(ParseConstraintLogicalOrExpression(
1294 /*IsTrailingRequiresClause=*/false));
1295 if (RequiresClause.isInvalid())
1296 SkipUntil({tok::l_brace, tok::l_paren}, StopAtSemi | StopBeforeMatch);
1297 }
1298
1299 Actions.ActOnLambdaExplicitTemplateParameterList(
1300 LAngleLoc, TemplateParams, RAngleLoc, RequiresClause);
1301 ++CurTemplateDepthTracker;
1302 }
1303 }
1304
1305 // Implement WG21 P2173, which allows attributes immediately before the
1306 // lambda declarator and applies them to the corresponding function operator
1307 // or operator template declaration. We accept this as a conforming extension
1308 // in all language modes that support lambdas.
1309 if (isCXX11AttributeSpecifier()) {
1310 Diag(Tok, getLangOpts().CPlusPlus2b
1311 ? diag::warn_cxx20_compat_decl_attrs_on_lambda
1312 : diag::ext_decl_attrs_on_lambda);
1313 MaybeParseCXX11Attributes(D);
1314 }
1315
1316 TypeResult TrailingReturnType;
1317 SourceLocation TrailingReturnTypeLoc;
1318 if (Tok.is(tok::l_paren)) {
1319 ParseScope PrototypeScope(this,
1320 Scope::FunctionPrototypeScope |
1321 Scope::FunctionDeclarationScope |
1322 Scope::DeclScope);
1323
1324 BalancedDelimiterTracker T(*this, tok::l_paren);
1325 T.consumeOpen();
1326 SourceLocation LParenLoc = T.getOpenLocation();
1327
1328 // Parse parameter-declaration-clause.
1329 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1330 SourceLocation EllipsisLoc;
1331
1332 if (Tok.isNot(tok::r_paren)) {
1333 Actions.RecordParsingTemplateParameterDepth(
1334 CurTemplateDepthTracker.getOriginalDepth());
1335
1336 ParseParameterDeclarationClause(D.getContext(), Attr, ParamInfo,
1337 EllipsisLoc);
1338 // For a generic lambda, each 'auto' within the parameter declaration
1339 // clause creates a template type parameter, so increment the depth.
1340 // If we've parsed any explicit template parameters, then the depth will
1341 // have already been incremented. So we make sure that at most a single
1342 // depth level is added.
1343 if (Actions.getCurGenericLambda())
1344 CurTemplateDepthTracker.setAddedDepth(1);
1345 }
1346
1347 T.consumeClose();
1348 SourceLocation RParenLoc = T.getCloseLocation();
1349 SourceLocation DeclEndLoc = RParenLoc;
1350
1351 // GNU-style attributes must be parsed before the mutable specifier to be
1352 // compatible with GCC. MSVC-style attributes must be parsed before the
1353 // mutable specifier to be compatible with MSVC.
1354 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec, Attr);
1355
1356 // Parse mutable-opt and/or constexpr-opt or consteval-opt, and update the
1357 // DeclEndLoc.
1358 SourceLocation MutableLoc;
1359 SourceLocation ConstexprLoc;
1360 SourceLocation ConstevalLoc;
1361 tryConsumeLambdaSpecifierToken(*this, MutableLoc, ConstexprLoc,
1362 ConstevalLoc, DeclEndLoc);
1363
1364 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1365 addConstevalToLambdaDeclSpecifier(*this, ConstevalLoc, DS);
1366 // Parse exception-specification[opt].
1367 ExceptionSpecificationType ESpecType = EST_None;
1368 SourceRange ESpecRange;
1369 SmallVector<ParsedType, 2> DynamicExceptions;
1370 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1371 ExprResult NoexceptExpr;
1372 CachedTokens *ExceptionSpecTokens;
1373 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1374 ESpecRange,
1375 DynamicExceptions,
1376 DynamicExceptionRanges,
1377 NoexceptExpr,
1378 ExceptionSpecTokens);
1379
1380 if (ESpecType != EST_None)
1381 DeclEndLoc = ESpecRange.getEnd();
1382
1383 // Parse attribute-specifier[opt].
1384 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1385
1386 // Parse OpenCL addr space attribute.
1387 if (Tok.isOneOf(tok::kw___private, tok::kw___global, tok::kw___local,
1388 tok::kw___constant, tok::kw___generic)) {
1389 ParseOpenCLQualifiers(DS.getAttributes());
1390 ConsumeToken();
1391 }
1392
1393 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1394
1395 // Parse trailing-return-type[opt].
1396 if (Tok.is(tok::arrow)) {
1397 FunLocalRangeEnd = Tok.getLocation();
1398 SourceRange Range;
1399 TrailingReturnType =
1400 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1401 TrailingReturnTypeLoc = Range.getBegin();
1402 if (Range.getEnd().isValid())
1403 DeclEndLoc = Range.getEnd();
1404 }
1405
1406 SourceLocation NoLoc;
1407 D.AddTypeInfo(DeclaratorChunk::getFunction(
1408 /*HasProto=*/true,
1409 /*IsAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1410 ParamInfo.size(), EllipsisLoc, RParenLoc,
1411 /*RefQualifierIsLvalueRef=*/true,
1412 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType,
1413 ESpecRange, DynamicExceptions.data(),
1414 DynamicExceptionRanges.data(), DynamicExceptions.size(),
1415 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1416 /*ExceptionSpecTokens*/ nullptr,
1417 /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
1418 TrailingReturnType, TrailingReturnTypeLoc, &DS),
1419 std::move(Attr), DeclEndLoc);
1420
1421 // Parse requires-clause[opt].
1422 if (Tok.is(tok::kw_requires))
1423 ParseTrailingRequiresClause(D);
1424
1425 PrototypeScope.Exit();
1426
1427 WarnIfHasCUDATargetAttr();
1428 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1429 tok::kw_constexpr, tok::kw_consteval,
1430 tok::kw___private, tok::kw___global, tok::kw___local,
1431 tok::kw___constant, tok::kw___generic,
1432 tok::kw_requires) ||
1433 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1434 // It's common to forget that one needs '()' before 'mutable', an attribute
1435 // specifier, the result type, or the requires clause. Deal with this.
1436 unsigned TokKind = 0;
1437 switch (Tok.getKind()) {
1438 case tok::kw_mutable: TokKind = 0; break;
1439 case tok::arrow: TokKind = 1; break;
1440 case tok::kw___attribute:
1441 case tok::kw___private:
1442 case tok::kw___global:
1443 case tok::kw___local:
1444 case tok::kw___constant:
1445 case tok::kw___generic:
1446 case tok::l_square: TokKind = 2; break;
1447 case tok::kw_constexpr: TokKind = 3; break;
1448 case tok::kw_consteval: TokKind = 4; break;
1449 case tok::kw_requires: TokKind = 5; break;
1450 default: llvm_unreachable("Unknown token kind")::llvm::llvm_unreachable_internal("Unknown token kind", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1450)
;
1451 }
1452
1453 Diag(Tok, diag::err_lambda_missing_parens)
1454 << TokKind
1455 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1456 SourceLocation DeclEndLoc = DeclLoc;
1457
1458 // GNU-style attributes must be parsed before the mutable specifier to be
1459 // compatible with GCC.
1460 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1461
1462 // Parse 'mutable', if it's there.
1463 SourceLocation MutableLoc;
1464 if (Tok.is(tok::kw_mutable)) {
1465 MutableLoc = ConsumeToken();
1466 DeclEndLoc = MutableLoc;
1467 }
1468
1469 // Parse attribute-specifier[opt].
1470 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1471
1472 // Parse the return type, if there is one.
1473 if (Tok.is(tok::arrow)) {
1474 SourceRange Range;
1475 TrailingReturnType =
1476 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1477 if (Range.getEnd().isValid())
1478 DeclEndLoc = Range.getEnd();
1479 }
1480
1481 SourceLocation NoLoc;
1482 D.AddTypeInfo(DeclaratorChunk::getFunction(
1483 /*HasProto=*/true,
1484 /*IsAmbiguous=*/false,
1485 /*LParenLoc=*/NoLoc,
1486 /*Params=*/nullptr,
1487 /*NumParams=*/0,
1488 /*EllipsisLoc=*/NoLoc,
1489 /*RParenLoc=*/NoLoc,
1490 /*RefQualifierIsLvalueRef=*/true,
1491 /*RefQualifierLoc=*/NoLoc, MutableLoc, EST_None,
1492 /*ESpecRange=*/SourceRange(),
1493 /*Exceptions=*/nullptr,
1494 /*ExceptionRanges=*/nullptr,
1495 /*NumExceptions=*/0,
1496 /*NoexceptExpr=*/nullptr,
1497 /*ExceptionSpecTokens=*/nullptr,
1498 /*DeclsInPrototype=*/None, DeclLoc, DeclEndLoc, D,
1499 TrailingReturnType),
1500 std::move(Attr), DeclEndLoc);
1501
1502 // Parse the requires-clause, if present.
1503 if (Tok.is(tok::kw_requires))
1504 ParseTrailingRequiresClause(D);
1505
1506 WarnIfHasCUDATargetAttr();
1507 }
1508
1509 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1510 // it.
1511 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1512 Scope::CompoundStmtScope;
1513 ParseScope BodyScope(this, ScopeFlags);
1514
1515 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1516
1517 // Parse compound-statement.
1518 if (!Tok.is(tok::l_brace)) {
1519 Diag(Tok, diag::err_expected_lambda_body);
1520 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1521 return ExprError();
1522 }
1523
1524 StmtResult Stmt(ParseCompoundStatementBody());
1525 BodyScope.Exit();
1526 TemplateParamScope.Exit();
1527
1528 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1529 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1530
1531 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1532 return ExprError();
1533}
1534
1535/// ParseCXXCasts - This handles the various ways to cast expressions to another
1536/// type.
1537///
1538/// postfix-expression: [C++ 5.2p1]
1539/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1540/// 'static_cast' '<' type-name '>' '(' expression ')'
1541/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1542/// 'const_cast' '<' type-name '>' '(' expression ')'
1543///
1544/// C++ for OpenCL s2.3.1 adds:
1545/// 'addrspace_cast' '<' type-name '>' '(' expression ')'
1546ExprResult Parser::ParseCXXCasts() {
1547 tok::TokenKind Kind = Tok.getKind();
1548 const char *CastName = nullptr; // For error messages
1549
1550 switch (Kind) {
1551 default: llvm_unreachable("Unknown C++ cast!")::llvm::llvm_unreachable_internal("Unknown C++ cast!", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1551)
;
1552 case tok::kw_addrspace_cast: CastName = "addrspace_cast"; break;
1553 case tok::kw_const_cast: CastName = "const_cast"; break;
1554 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1555 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1556 case tok::kw_static_cast: CastName = "static_cast"; break;
1557 }
1558
1559 SourceLocation OpLoc = ConsumeToken();
1560 SourceLocation LAngleBracketLoc = Tok.getLocation();
1561
1562 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1563 // diagnose error, suggest fix, and recover parsing.
1564 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1565 Token Next = NextToken();
1566 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1567 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1568 }
1569
1570 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1571 return ExprError();
1572
1573 // Parse the common declaration-specifiers piece.
1574 DeclSpec DS(AttrFactory);
1575 ParseSpecifierQualifierList(DS);
1576
1577 // Parse the abstract-declarator, if present.
1578 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
1579 ParseDeclarator(DeclaratorInfo);
1580
1581 SourceLocation RAngleBracketLoc = Tok.getLocation();
1582
1583 if (ExpectAndConsume(tok::greater))
1584 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1585
1586 BalancedDelimiterTracker T(*this, tok::l_paren);
1587
1588 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1589 return ExprError();
1590
1591 ExprResult Result = ParseExpression();
1592
1593 // Match the ')'.
1594 T.consumeClose();
1595
1596 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1597 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1598 LAngleBracketLoc, DeclaratorInfo,
1599 RAngleBracketLoc,
1600 T.getOpenLocation(), Result.get(),
1601 T.getCloseLocation());
1602
1603 return Result;
1604}
1605
1606/// ParseCXXTypeid - This handles the C++ typeid expression.
1607///
1608/// postfix-expression: [C++ 5.2p1]
1609/// 'typeid' '(' expression ')'
1610/// 'typeid' '(' type-id ')'
1611///
1612ExprResult Parser::ParseCXXTypeid() {
1613 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!")((Tok.is(tok::kw_typeid) && "Not 'typeid'!") ? static_cast
<void> (0) : __assert_fail ("Tok.is(tok::kw_typeid) && \"Not 'typeid'!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1613, __PRETTY_FUNCTION__))
;
1614
1615 SourceLocation OpLoc = ConsumeToken();
1616 SourceLocation LParenLoc, RParenLoc;
1617 BalancedDelimiterTracker T(*this, tok::l_paren);
1618
1619 // typeid expressions are always parenthesized.
1620 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1621 return ExprError();
1622 LParenLoc = T.getOpenLocation();
1623
1624 ExprResult Result;
1625
1626 // C++0x [expr.typeid]p3:
1627 // When typeid is applied to an expression other than an lvalue of a
1628 // polymorphic class type [...] The expression is an unevaluated
1629 // operand (Clause 5).
1630 //
1631 // Note that we can't tell whether the expression is an lvalue of a
1632 // polymorphic class type until after we've parsed the expression; we
1633 // speculatively assume the subexpression is unevaluated, and fix it up
1634 // later.
1635 //
1636 // We enter the unevaluated context before trying to determine whether we
1637 // have a type-id, because the tentative parse logic will try to resolve
1638 // names, and must treat them as unevaluated.
1639 EnterExpressionEvaluationContext Unevaluated(
1640 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1641 Sema::ReuseLambdaContextDecl);
1642
1643 if (isTypeIdInParens()) {
1644 TypeResult Ty = ParseTypeName();
1645
1646 // Match the ')'.
1647 T.consumeClose();
1648 RParenLoc = T.getCloseLocation();
1649 if (Ty.isInvalid() || RParenLoc.isInvalid())
1650 return ExprError();
1651
1652 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1653 Ty.get().getAsOpaquePtr(), RParenLoc);
1654 } else {
1655 Result = ParseExpression();
1656
1657 // Match the ')'.
1658 if (Result.isInvalid())
1659 SkipUntil(tok::r_paren, StopAtSemi);
1660 else {
1661 T.consumeClose();
1662 RParenLoc = T.getCloseLocation();
1663 if (RParenLoc.isInvalid())
1664 return ExprError();
1665
1666 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1667 Result.get(), RParenLoc);
1668 }
1669 }
1670
1671 return Result;
1672}
1673
1674/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1675///
1676/// '__uuidof' '(' expression ')'
1677/// '__uuidof' '(' type-id ')'
1678///
1679ExprResult Parser::ParseCXXUuidof() {
1680 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!")((Tok.is(tok::kw___uuidof) && "Not '__uuidof'!") ? static_cast
<void> (0) : __assert_fail ("Tok.is(tok::kw___uuidof) && \"Not '__uuidof'!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1680, __PRETTY_FUNCTION__))
;
1681
1682 SourceLocation OpLoc = ConsumeToken();
1683 BalancedDelimiterTracker T(*this, tok::l_paren);
1684
1685 // __uuidof expressions are always parenthesized.
1686 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1687 return ExprError();
1688
1689 ExprResult Result;
1690
1691 if (isTypeIdInParens()) {
1692 TypeResult Ty = ParseTypeName();
1693
1694 // Match the ')'.
1695 T.consumeClose();
1696
1697 if (Ty.isInvalid())
1698 return ExprError();
1699
1700 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1701 Ty.get().getAsOpaquePtr(),
1702 T.getCloseLocation());
1703 } else {
1704 EnterExpressionEvaluationContext Unevaluated(
1705 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1706 Result = ParseExpression();
1707
1708 // Match the ')'.
1709 if (Result.isInvalid())
1710 SkipUntil(tok::r_paren, StopAtSemi);
1711 else {
1712 T.consumeClose();
1713
1714 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1715 /*isType=*/false,
1716 Result.get(), T.getCloseLocation());
1717 }
1718 }
1719
1720 return Result;
1721}
1722
1723/// Parse a C++ pseudo-destructor expression after the base,
1724/// . or -> operator, and nested-name-specifier have already been
1725/// parsed. We're handling this fragment of the grammar:
1726///
1727/// postfix-expression: [C++2a expr.post]
1728/// postfix-expression . template[opt] id-expression
1729/// postfix-expression -> template[opt] id-expression
1730///
1731/// id-expression:
1732/// qualified-id
1733/// unqualified-id
1734///
1735/// qualified-id:
1736/// nested-name-specifier template[opt] unqualified-id
1737///
1738/// nested-name-specifier:
1739/// type-name ::
1740/// decltype-specifier :: FIXME: not implemented, but probably only
1741/// allowed in C++ grammar by accident
1742/// nested-name-specifier identifier ::
1743/// nested-name-specifier template[opt] simple-template-id ::
1744/// [...]
1745///
1746/// unqualified-id:
1747/// ~ type-name
1748/// ~ decltype-specifier
1749/// [...]
1750///
1751/// ... where the all but the last component of the nested-name-specifier
1752/// has already been parsed, and the base expression is not of a non-dependent
1753/// class type.
1754ExprResult
1755Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1756 tok::TokenKind OpKind,
1757 CXXScopeSpec &SS,
1758 ParsedType ObjectType) {
1759 // If the last component of the (optional) nested-name-specifier is
1760 // template[opt] simple-template-id, it has already been annotated.
1761 UnqualifiedId FirstTypeName;
1762 SourceLocation CCLoc;
1763 if (Tok.is(tok::identifier)) {
1764 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1765 ConsumeToken();
1766 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail")((Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::coloncolon) &&\"ParseOptionalCXXScopeSpecifier fail\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1766, __PRETTY_FUNCTION__))
;
1767 CCLoc = ConsumeToken();
1768 } else if (Tok.is(tok::annot_template_id)) {
1769 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1770 // FIXME: Carry on and build an AST representation for tooling.
1771 if (TemplateId->isInvalid())
1772 return ExprError();
1773 FirstTypeName.setTemplateId(TemplateId);
1774 ConsumeAnnotationToken();
1775 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail")((Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::coloncolon) &&\"ParseOptionalCXXScopeSpecifier fail\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1775, __PRETTY_FUNCTION__))
;
1776 CCLoc = ConsumeToken();
1777 } else {
1778 assert(SS.isEmpty() && "missing last component of nested name specifier")((SS.isEmpty() && "missing last component of nested name specifier"
) ? static_cast<void> (0) : __assert_fail ("SS.isEmpty() && \"missing last component of nested name specifier\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1778, __PRETTY_FUNCTION__))
;
1779 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1780 }
1781
1782 // Parse the tilde.
1783 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail")((Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::tilde) && \"ParseOptionalCXXScopeSpecifier fail\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1783, __PRETTY_FUNCTION__))
;
1784 SourceLocation TildeLoc = ConsumeToken();
1785
1786 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid()) {
1787 DeclSpec DS(AttrFactory);
1788 ParseDecltypeSpecifier(DS);
1789 if (DS.getTypeSpecType() == TST_error)
1790 return ExprError();
1791 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1792 TildeLoc, DS);
1793 }
1794
1795 if (!Tok.is(tok::identifier)) {
1796 Diag(Tok, diag::err_destructor_tilde_identifier);
1797 return ExprError();
1798 }
1799
1800 // Parse the second type.
1801 UnqualifiedId SecondTypeName;
1802 IdentifierInfo *Name = Tok.getIdentifierInfo();
1803 SourceLocation NameLoc = ConsumeToken();
1804 SecondTypeName.setIdentifier(Name, NameLoc);
1805
1806 // If there is a '<', the second type name is a template-id. Parse
1807 // it as such.
1808 //
1809 // FIXME: This is not a context in which a '<' is assumed to start a template
1810 // argument list. This affects examples such as
1811 // void f(auto *p) { p->~X<int>(); }
1812 // ... but there's no ambiguity, and nowhere to write 'template' in such an
1813 // example, so we accept it anyway.
1814 if (Tok.is(tok::less) &&
1815 ParseUnqualifiedIdTemplateId(
1816 SS, ObjectType, Base && Base->containsErrors(), SourceLocation(),
1817 Name, NameLoc, false, SecondTypeName,
1818 /*AssumeTemplateId=*/true))
1819 return ExprError();
1820
1821 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1822 SS, FirstTypeName, CCLoc, TildeLoc,
1823 SecondTypeName);
1824}
1825
1826/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1827///
1828/// boolean-literal: [C++ 2.13.5]
1829/// 'true'
1830/// 'false'
1831ExprResult Parser::ParseCXXBoolLiteral() {
1832 tok::TokenKind Kind = Tok.getKind();
1833 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1834}
1835
1836/// ParseThrowExpression - This handles the C++ throw expression.
1837///
1838/// throw-expression: [C++ 15]
1839/// 'throw' assignment-expression[opt]
1840ExprResult Parser::ParseThrowExpression() {
1841 assert(Tok.is(tok::kw_throw) && "Not throw!")((Tok.is(tok::kw_throw) && "Not throw!") ? static_cast
<void> (0) : __assert_fail ("Tok.is(tok::kw_throw) && \"Not throw!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1841, __PRETTY_FUNCTION__))
;
1842 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1843
1844 // If the current token isn't the start of an assignment-expression,
1845 // then the expression is not present. This handles things like:
1846 // "C ? throw : (void)42", which is crazy but legal.
1847 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1848 case tok::semi:
1849 case tok::r_paren:
1850 case tok::r_square:
1851 case tok::r_brace:
1852 case tok::colon:
1853 case tok::comma:
1854 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1855
1856 default:
1857 ExprResult Expr(ParseAssignmentExpression());
1858 if (Expr.isInvalid()) return Expr;
1859 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1860 }
1861}
1862
1863/// Parse the C++ Coroutines co_yield expression.
1864///
1865/// co_yield-expression:
1866/// 'co_yield' assignment-expression[opt]
1867ExprResult Parser::ParseCoyieldExpression() {
1868 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!")((Tok.is(tok::kw_co_yield) && "Not co_yield!") ? static_cast
<void> (0) : __assert_fail ("Tok.is(tok::kw_co_yield) && \"Not co_yield!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1868, __PRETTY_FUNCTION__))
;
1869
1870 SourceLocation Loc = ConsumeToken();
1871 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1872 : ParseAssignmentExpression();
1873 if (!Expr.isInvalid())
1874 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1875 return Expr;
1876}
1877
1878/// ParseCXXThis - This handles the C++ 'this' pointer.
1879///
1880/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1881/// a non-lvalue expression whose value is the address of the object for which
1882/// the function is called.
1883ExprResult Parser::ParseCXXThis() {
1884 assert(Tok.is(tok::kw_this) && "Not 'this'!")((Tok.is(tok::kw_this) && "Not 'this'!") ? static_cast
<void> (0) : __assert_fail ("Tok.is(tok::kw_this) && \"Not 'this'!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1884, __PRETTY_FUNCTION__))
;
1885 SourceLocation ThisLoc = ConsumeToken();
1886 return Actions.ActOnCXXThis(ThisLoc);
1887}
1888
1889/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1890/// Can be interpreted either as function-style casting ("int(x)")
1891/// or class type construction ("ClassType(x,y,z)")
1892/// or creation of a value-initialized type ("int()").
1893/// See [C++ 5.2.3].
1894///
1895/// postfix-expression: [C++ 5.2p1]
1896/// simple-type-specifier '(' expression-list[opt] ')'
1897/// [C++0x] simple-type-specifier braced-init-list
1898/// typename-specifier '(' expression-list[opt] ')'
1899/// [C++0x] typename-specifier braced-init-list
1900///
1901/// In C++1z onwards, the type specifier can also be a template-name.
1902ExprResult
1903Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1904 Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCast);
1905 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1906
1907 assert((Tok.is(tok::l_paren) ||(((Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 &&
Tok.is(tok::l_brace))) && "Expected '(' or '{'!") ? static_cast
<void> (0) : __assert_fail ("(Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) && \"Expected '(' or '{'!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1909, __PRETTY_FUNCTION__))
1908 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))(((Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 &&
Tok.is(tok::l_brace))) && "Expected '(' or '{'!") ? static_cast
<void> (0) : __assert_fail ("(Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) && \"Expected '(' or '{'!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1909, __PRETTY_FUNCTION__))
1909 && "Expected '(' or '{'!")(((Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 &&
Tok.is(tok::l_brace))) && "Expected '(' or '{'!") ? static_cast
<void> (0) : __assert_fail ("(Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) && \"Expected '(' or '{'!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1909, __PRETTY_FUNCTION__))
;
1910
1911 if (Tok.is(tok::l_brace)) {
1912 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1913 ExprResult Init = ParseBraceInitializer();
1914 if (Init.isInvalid())
1915 return Init;
1916 Expr *InitList = Init.get();
1917 return Actions.ActOnCXXTypeConstructExpr(
1918 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
1919 InitList->getEndLoc(), /*ListInitialization=*/true);
1920 } else {
1921 BalancedDelimiterTracker T(*this, tok::l_paren);
1922 T.consumeOpen();
1923
1924 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1925
1926 ExprVector Exprs;
1927 CommaLocsTy CommaLocs;
1928
1929 auto RunSignatureHelp = [&]() {
1930 QualType PreferredType;
1931 if (TypeRep)
1932 PreferredType = Actions.ProduceConstructorSignatureHelp(
1933 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
1934 DS.getEndLoc(), Exprs, T.getOpenLocation());
1935 CalledSignatureHelp = true;
1936 return PreferredType;
1937 };
1938
1939 if (Tok.isNot(tok::r_paren)) {
1940 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1941 PreferredType.enterFunctionArgument(Tok.getLocation(),
1942 RunSignatureHelp);
1943 })) {
1944 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1945 RunSignatureHelp();
1946 SkipUntil(tok::r_paren, StopAtSemi);
1947 return ExprError();
1948 }
1949 }
1950
1951 // Match the ')'.
1952 T.consumeClose();
1953
1954 // TypeRep could be null, if it references an invalid typedef.
1955 if (!TypeRep)
1956 return ExprError();
1957
1958 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&(((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
"Unexpected number of commas!") ? static_cast<void> (0
) : __assert_fail ("(Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&& \"Unexpected number of commas!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1959, __PRETTY_FUNCTION__))
1959 "Unexpected number of commas!")(((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
"Unexpected number of commas!") ? static_cast<void> (0
) : __assert_fail ("(Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&& \"Unexpected number of commas!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 1959, __PRETTY_FUNCTION__))
;
1960 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1961 Exprs, T.getCloseLocation(),
1962 /*ListInitialization=*/false);
1963 }
1964}
1965
1966/// ParseCXXCondition - if/switch/while condition expression.
1967///
1968/// condition:
1969/// expression
1970/// type-specifier-seq declarator '=' assignment-expression
1971/// [C++11] type-specifier-seq declarator '=' initializer-clause
1972/// [C++11] type-specifier-seq declarator braced-init-list
1973/// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1974/// brace-or-equal-initializer
1975/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1976/// '=' assignment-expression
1977///
1978/// In C++1z, a condition may in some contexts be preceded by an
1979/// optional init-statement. This function will parse that too.
1980///
1981/// \param InitStmt If non-null, an init-statement is permitted, and if present
1982/// will be parsed and stored here.
1983///
1984/// \param Loc The location of the start of the statement that requires this
1985/// condition, e.g., the "for" in a for loop.
1986///
1987/// \param FRI If non-null, a for range declaration is permitted, and if
1988/// present will be parsed and stored here, and a null result will be returned.
1989///
1990/// \returns The parsed condition.
1991Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1992 SourceLocation Loc,
1993 Sema::ConditionKind CK,
1994 ForRangeInfo *FRI) {
1995 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1996 PreferredType.enterCondition(Actions, Tok.getLocation());
1997
1998 if (Tok.is(tok::code_completion)) {
1
Taking false branch
5
Calling 'Token::is'
8
Returning from 'Token::is'
9
Taking false branch
1999 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
2000 cutOffParsing();
2001 return Sema::ConditionError();
2002 }
2003
2004 ParsedAttributesWithRange attrs(AttrFactory);
2005 MaybeParseCXX11Attributes(attrs);
2006
2007 const auto WarnOnInit = [this, &CK] {
2008 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
2009 ? diag::warn_cxx14_compat_init_statement
2010 : diag::ext_init_statement)
2011 << (CK == Sema::ConditionKind::Switch);
2012 };
2013
2014 // Determine what kind of thing we have.
2015 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
2
Control jumps to 'case InitStmtDecl:' at line 2049
10
Control jumps to 'case InitStmtDecl:' at line 2049
2016 case ConditionOrInitStatement::Expression: {
2017 ProhibitAttributes(attrs);
2018
2019 // We can have an empty expression here.
2020 // if (; true);
2021 if (InitStmt && Tok.is(tok::semi)) {
2022 WarnOnInit();
2023 SourceLocation SemiLoc = Tok.getLocation();
2024 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
2025 Diag(SemiLoc, diag::warn_empty_init_statement)
2026 << (CK == Sema::ConditionKind::Switch)
2027 << FixItHint::CreateRemoval(SemiLoc);
2028 }
2029 ConsumeToken();
2030 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
2031 return ParseCXXCondition(nullptr, Loc, CK);
2032 }
2033
2034 // Parse the expression.
2035 ExprResult Expr = ParseExpression(); // expression
2036 if (Expr.isInvalid())
2037 return Sema::ConditionError();
2038
2039 if (InitStmt && Tok.is(tok::semi)) {
2040 WarnOnInit();
2041 *InitStmt = Actions.ActOnExprStmt(Expr.get());
2042 ConsumeToken();
2043 return ParseCXXCondition(nullptr, Loc, CK);
2044 }
2045
2046 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
2047 }
2048
2049 case ConditionOrInitStatement::InitStmtDecl: {
2050 WarnOnInit();
2051 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2052 DeclGroupPtrTy DG = ParseSimpleDeclaration(
2053 DeclaratorContext::SelectionInit, DeclEnd, attrs, /*RequireSemi=*/true);
2054 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
11
Called C++ object pointer is null
2055 return ParseCXXCondition(nullptr, Loc, CK);
3
Passing null pointer value via 1st parameter 'InitStmt'
4
Calling 'Parser::ParseCXXCondition'
2056 }
2057
2058 case ConditionOrInitStatement::ForRangeDecl: {
2059 assert(FRI && "should not parse a for range declaration here")((FRI && "should not parse a for range declaration here"
) ? static_cast<void> (0) : __assert_fail ("FRI && \"should not parse a for range declaration here\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 2059, __PRETTY_FUNCTION__))
;
2060 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2061 DeclGroupPtrTy DG = ParseSimpleDeclaration(DeclaratorContext::ForInit,
2062 DeclEnd, attrs, false, FRI);
2063 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
2064 return Sema::ConditionResult();
2065 }
2066
2067 case ConditionOrInitStatement::ConditionDecl:
2068 case ConditionOrInitStatement::Error:
2069 break;
2070 }
2071
2072 // type-specifier-seq
2073 DeclSpec DS(AttrFactory);
2074 DS.takeAttributesFrom(attrs);
2075 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
2076
2077 // declarator
2078 Declarator DeclaratorInfo(DS, DeclaratorContext::Condition);
2079 ParseDeclarator(DeclaratorInfo);
2080
2081 // simple-asm-expr[opt]
2082 if (Tok.is(tok::kw_asm)) {
2083 SourceLocation Loc;
2084 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2085 if (AsmLabel.isInvalid()) {
2086 SkipUntil(tok::semi, StopAtSemi);
2087 return Sema::ConditionError();
2088 }
2089 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2090 DeclaratorInfo.SetRangeEnd(Loc);
2091 }
2092
2093 // If attributes are present, parse them.
2094 MaybeParseGNUAttributes(DeclaratorInfo);
2095
2096 // Type-check the declaration itself.
2097 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
2098 DeclaratorInfo);
2099 if (Dcl.isInvalid())
2100 return Sema::ConditionError();
2101 Decl *DeclOut = Dcl.get();
2102
2103 // '=' assignment-expression
2104 // If a '==' or '+=' is found, suggest a fixit to '='.
2105 bool CopyInitialization = isTokenEqualOrEqualTypo();
2106 if (CopyInitialization)
2107 ConsumeToken();
2108
2109 ExprResult InitExpr = ExprError();
2110 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2111 Diag(Tok.getLocation(),
2112 diag::warn_cxx98_compat_generalized_initializer_lists);
2113 InitExpr = ParseBraceInitializer();
2114 } else if (CopyInitialization) {
2115 PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
2116 InitExpr = ParseAssignmentExpression();
2117 } else if (Tok.is(tok::l_paren)) {
2118 // This was probably an attempt to initialize the variable.
2119 SourceLocation LParen = ConsumeParen(), RParen = LParen;
2120 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
2121 RParen = ConsumeParen();
2122 Diag(DeclOut->getLocation(),
2123 diag::err_expected_init_in_condition_lparen)
2124 << SourceRange(LParen, RParen);
2125 } else {
2126 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
2127 }
2128
2129 if (!InitExpr.isInvalid())
2130 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
2131 else
2132 Actions.ActOnInitializerError(DeclOut);
2133
2134 Actions.FinalizeDeclaration(DeclOut);
2135 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
2136}
2137
2138/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
2139/// This should only be called when the current token is known to be part of
2140/// simple-type-specifier.
2141///
2142/// simple-type-specifier:
2143/// '::'[opt] nested-name-specifier[opt] type-name
2144/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
2145/// char
2146/// wchar_t
2147/// bool
2148/// short
2149/// int
2150/// long
2151/// signed
2152/// unsigned
2153/// float
2154/// double
2155/// void
2156/// [GNU] typeof-specifier
2157/// [C++0x] auto [TODO]
2158///
2159/// type-name:
2160/// class-name
2161/// enum-name
2162/// typedef-name
2163///
2164void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
2165 DS.SetRangeStart(Tok.getLocation());
2166 const char *PrevSpec;
2167 unsigned DiagID;
2168 SourceLocation Loc = Tok.getLocation();
2169 const clang::PrintingPolicy &Policy =
2170 Actions.getASTContext().getPrintingPolicy();
2171
2172 switch (Tok.getKind()) {
2173 case tok::identifier: // foo::bar
2174 case tok::coloncolon: // ::foo::bar
2175 llvm_unreachable("Annotation token should already be formed!")::llvm::llvm_unreachable_internal("Annotation token should already be formed!"
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 2175)
;
2176 default:
2177 llvm_unreachable("Not a simple-type-specifier token!")::llvm::llvm_unreachable_internal("Not a simple-type-specifier token!"
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 2177)
;
2178
2179 // type-name
2180 case tok::annot_typename: {
2181 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
2182 getTypeAnnotation(Tok), Policy);
2183 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2184 ConsumeAnnotationToken();
2185
2186 DS.Finish(Actions, Policy);
2187 return;
2188 }
2189
2190 case tok::kw__ExtInt: {
2191 ExprResult ER = ParseExtIntegerArgument();
2192 if (ER.isInvalid())
2193 DS.SetTypeSpecError();
2194 else
2195 DS.SetExtIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
2196
2197 // Do this here because we have already consumed the close paren.
2198 DS.SetRangeEnd(PrevTokLocation);
2199 DS.Finish(Actions, Policy);
2200 return;
2201 }
2202
2203 // builtin types
2204 case tok::kw_short:
2205 DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec, DiagID,
2206 Policy);
2207 break;
2208 case tok::kw_long:
2209 DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec, DiagID,
2210 Policy);
2211 break;
2212 case tok::kw___int64:
2213 DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc, PrevSpec, DiagID,
2214 Policy);
2215 break;
2216 case tok::kw_signed:
2217 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
2218 break;
2219 case tok::kw_unsigned:
2220 DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec, DiagID);
2221 break;
2222 case tok::kw_void:
2223 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
2224 break;
2225 case tok::kw_char:
2226 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
2227 break;
2228 case tok::kw_int:
2229 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
2230 break;
2231 case tok::kw___int128:
2232 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
2233 break;
2234 case tok::kw___bf16:
2235 DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec, DiagID, Policy);
2236 break;
2237 case tok::kw_half:
2238 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
2239 break;
2240 case tok::kw_float:
2241 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
2242 break;
2243 case tok::kw_double:
2244 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
2245 break;
2246 case tok::kw__Float16:
2247 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
2248 break;
2249 case tok::kw___float128:
2250 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
2251 break;
2252 case tok::kw_wchar_t:
2253 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
2254 break;
2255 case tok::kw_char8_t:
2256 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
2257 break;
2258 case tok::kw_char16_t:
2259 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
2260 break;
2261 case tok::kw_char32_t:
2262 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
2263 break;
2264 case tok::kw_bool:
2265 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
2266 break;
2267#define GENERIC_IMAGE_TYPE(ImgType, Id) \
2268 case tok::kw_##ImgType##_t: \
2269 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
2270 Policy); \
2271 break;
2272#include "clang/Basic/OpenCLImageTypes.def"
2273
2274 case tok::annot_decltype:
2275 case tok::kw_decltype:
2276 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
2277 return DS.Finish(Actions, Policy);
2278
2279 // GNU typeof support.
2280 case tok::kw_typeof:
2281 ParseTypeofSpecifier(DS);
2282 DS.Finish(Actions, Policy);
2283 return;
2284 }
2285 ConsumeAnyToken();
2286 DS.SetRangeEnd(PrevTokLocation);
2287 DS.Finish(Actions, Policy);
2288}
2289
2290/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2291/// [dcl.name]), which is a non-empty sequence of type-specifiers,
2292/// e.g., "const short int". Note that the DeclSpec is *not* finished
2293/// by parsing the type-specifier-seq, because these sequences are
2294/// typically followed by some form of declarator. Returns true and
2295/// emits diagnostics if this is not a type-specifier-seq, false
2296/// otherwise.
2297///
2298/// type-specifier-seq: [C++ 8.1]
2299/// type-specifier type-specifier-seq[opt]
2300///
2301bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
2302 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
2303 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2304 return false;
2305}
2306
2307/// Finish parsing a C++ unqualified-id that is a template-id of
2308/// some form.
2309///
2310/// This routine is invoked when a '<' is encountered after an identifier or
2311/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2312/// whether the unqualified-id is actually a template-id. This routine will
2313/// then parse the template arguments and form the appropriate template-id to
2314/// return to the caller.
2315///
2316/// \param SS the nested-name-specifier that precedes this template-id, if
2317/// we're actually parsing a qualified-id.
2318///
2319/// \param ObjectType if this unqualified-id occurs within a member access
2320/// expression, the type of the base object whose member is being accessed.
2321///
2322/// \param ObjectHadErrors this unqualified-id occurs within a member access
2323/// expression, indicates whether the original subexpressions had any errors.
2324///
2325/// \param Name for constructor and destructor names, this is the actual
2326/// identifier that may be a template-name.
2327///
2328/// \param NameLoc the location of the class-name in a constructor or
2329/// destructor.
2330///
2331/// \param EnteringContext whether we're entering the scope of the
2332/// nested-name-specifier.
2333///
2334/// \param Id as input, describes the template-name or operator-function-id
2335/// that precedes the '<'. If template arguments were parsed successfully,
2336/// will be updated with the template-id.
2337///
2338/// \param AssumeTemplateId When true, this routine will assume that the name
2339/// refers to a template without performing name lookup to verify.
2340///
2341/// \returns true if a parse error occurred, false otherwise.
2342bool Parser::ParseUnqualifiedIdTemplateId(
2343 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
2344 SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc,
2345 bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId) {
2346 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id")((Tok.is(tok::less) && "Expected '<' to finish parsing a template-id"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::less) && \"Expected '<' to finish parsing a template-id\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 2346, __PRETTY_FUNCTION__))
;
2347
2348 TemplateTy Template;
2349 TemplateNameKind TNK = TNK_Non_template;
2350 switch (Id.getKind()) {
2351 case UnqualifiedIdKind::IK_Identifier:
2352 case UnqualifiedIdKind::IK_OperatorFunctionId:
2353 case UnqualifiedIdKind::IK_LiteralOperatorId:
2354 if (AssumeTemplateId) {
2355 // We defer the injected-class-name checks until we've found whether
2356 // this template-id is used to form a nested-name-specifier or not.
2357 TNK = Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Id,
2358 ObjectType, EnteringContext, Template,
2359 /*AllowInjectedClassName*/ true);
2360 } else {
2361 bool MemberOfUnknownSpecialization;
2362 TNK = Actions.isTemplateName(getCurScope(), SS,
2363 TemplateKWLoc.isValid(), Id,
2364 ObjectType, EnteringContext, Template,
2365 MemberOfUnknownSpecialization);
2366 // If lookup found nothing but we're assuming that this is a template
2367 // name, double-check that makes sense syntactically before committing
2368 // to it.
2369 if (TNK == TNK_Undeclared_template &&
2370 isTemplateArgumentList(0) == TPResult::False)
2371 return false;
2372
2373 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2374 ObjectType && isTemplateArgumentList(0) == TPResult::True) {
2375 // If we had errors before, ObjectType can be dependent even without any
2376 // templates, do not report missing template keyword in that case.
2377 if (!ObjectHadErrors) {
2378 // We have something like t->getAs<T>(), where getAs is a
2379 // member of an unknown specialization. However, this will only
2380 // parse correctly as a template, so suggest the keyword 'template'
2381 // before 'getAs' and treat this as a dependent template name.
2382 std::string Name;
2383 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
2384 Name = std::string(Id.Identifier->getName());
2385 else {
2386 Name = "operator ";
2387 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
2388 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2389 else
2390 Name += Id.Identifier->getName();
2391 }
2392 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2393 << Name
2394 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2395 }
2396 TNK = Actions.ActOnTemplateName(
2397 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2398 Template, /*AllowInjectedClassName*/ true);
2399 } else if (TNK == TNK_Non_template) {
2400 return false;
2401 }
2402 }
2403 break;
2404
2405 case UnqualifiedIdKind::IK_ConstructorName: {
2406 UnqualifiedId TemplateName;
2407 bool MemberOfUnknownSpecialization;
2408 TemplateName.setIdentifier(Name, NameLoc);
2409 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2410 TemplateName, ObjectType,
2411 EnteringContext, Template,
2412 MemberOfUnknownSpecialization);
2413 if (TNK == TNK_Non_template)
2414 return false;
2415 break;
2416 }
2417
2418 case UnqualifiedIdKind::IK_DestructorName: {
2419 UnqualifiedId TemplateName;
2420 bool MemberOfUnknownSpecialization;
2421 TemplateName.setIdentifier(Name, NameLoc);
2422 if (ObjectType) {
2423 TNK = Actions.ActOnTemplateName(
2424 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2425 EnteringContext, Template, /*AllowInjectedClassName*/ true);
2426 } else {
2427 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2428 TemplateName, ObjectType,
2429 EnteringContext, Template,
2430 MemberOfUnknownSpecialization);
2431
2432 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2433 Diag(NameLoc, diag::err_destructor_template_id)
2434 << Name << SS.getRange();
2435 // Carry on to parse the template arguments before bailing out.
2436 }
2437 }
2438 break;
2439 }
2440
2441 default:
2442 return false;
2443 }
2444
2445 // Parse the enclosed template argument list.
2446 SourceLocation LAngleLoc, RAngleLoc;
2447 TemplateArgList TemplateArgs;
2448 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2449 RAngleLoc))
2450 return true;
2451
2452 // If this is a non-template, we already issued a diagnostic.
2453 if (TNK == TNK_Non_template)
2454 return true;
2455
2456 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2457 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2458 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
2459 // Form a parsed representation of the template-id to be stored in the
2460 // UnqualifiedId.
2461
2462 // FIXME: Store name for literal operator too.
2463 IdentifierInfo *TemplateII =
2464 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2465 : nullptr;
2466 OverloadedOperatorKind OpKind =
2467 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2468 ? OO_None
2469 : Id.OperatorFunctionId.Operator;
2470
2471 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2472 TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2473 LAngleLoc, RAngleLoc, TemplateArgs, /*ArgsInvalid*/false, TemplateIds);
2474
2475 Id.setTemplateId(TemplateId);
2476 return false;
2477 }
2478
2479 // Bundle the template arguments together.
2480 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2481
2482 // Constructor and destructor names.
2483 TypeResult Type = Actions.ActOnTemplateIdType(
2484 getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc,
2485 TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true);
2486 if (Type.isInvalid())
2487 return true;
2488
2489 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
2490 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2491 else
2492 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2493
2494 return false;
2495}
2496
2497/// Parse an operator-function-id or conversion-function-id as part
2498/// of a C++ unqualified-id.
2499///
2500/// This routine is responsible only for parsing the operator-function-id or
2501/// conversion-function-id; it does not handle template arguments in any way.
2502///
2503/// \code
2504/// operator-function-id: [C++ 13.5]
2505/// 'operator' operator
2506///
2507/// operator: one of
2508/// new delete new[] delete[]
2509/// + - * / % ^ & | ~
2510/// ! = < > += -= *= /= %=
2511/// ^= &= |= << >> >>= <<= == !=
2512/// <= >= && || ++ -- , ->* ->
2513/// () [] <=>
2514///
2515/// conversion-function-id: [C++ 12.3.2]
2516/// operator conversion-type-id
2517///
2518/// conversion-type-id:
2519/// type-specifier-seq conversion-declarator[opt]
2520///
2521/// conversion-declarator:
2522/// ptr-operator conversion-declarator[opt]
2523/// \endcode
2524///
2525/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2526/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2527///
2528/// \param EnteringContext whether we are entering the scope of the
2529/// nested-name-specifier.
2530///
2531/// \param ObjectType if this unqualified-id occurs within a member access
2532/// expression, the type of the base object whose member is being accessed.
2533///
2534/// \param Result on a successful parse, contains the parsed unqualified-id.
2535///
2536/// \returns true if parsing fails, false otherwise.
2537bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2538 ParsedType ObjectType,
2539 UnqualifiedId &Result) {
2540 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword")((Tok.is(tok::kw_operator) && "Expected 'operator' keyword"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::kw_operator) && \"Expected 'operator' keyword\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 2540, __PRETTY_FUNCTION__))
;
2541
2542 // Consume the 'operator' keyword.
2543 SourceLocation KeywordLoc = ConsumeToken();
2544
2545 // Determine what kind of operator name we have.
2546 unsigned SymbolIdx = 0;
2547 SourceLocation SymbolLocations[3];
2548 OverloadedOperatorKind Op = OO_None;
2549 switch (Tok.getKind()) {
2550 case tok::kw_new:
2551 case tok::kw_delete: {
2552 bool isNew = Tok.getKind() == tok::kw_new;
2553 // Consume the 'new' or 'delete'.
2554 SymbolLocations[SymbolIdx++] = ConsumeToken();
2555 // Check for array new/delete.
2556 if (Tok.is(tok::l_square) &&
2557 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2558 // Consume the '[' and ']'.
2559 BalancedDelimiterTracker T(*this, tok::l_square);
2560 T.consumeOpen();
2561 T.consumeClose();
2562 if (T.getCloseLocation().isInvalid())
2563 return true;
2564
2565 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2566 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2567 Op = isNew? OO_Array_New : OO_Array_Delete;
2568 } else {
2569 Op = isNew? OO_New : OO_Delete;
2570 }
2571 break;
2572 }
2573
2574#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2575 case tok::Token: \
2576 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2577 Op = OO_##Name; \
2578 break;
2579#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2580#include "clang/Basic/OperatorKinds.def"
2581
2582 case tok::l_paren: {
2583 // Consume the '(' and ')'.
2584 BalancedDelimiterTracker T(*this, tok::l_paren);
2585 T.consumeOpen();
2586 T.consumeClose();
2587 if (T.getCloseLocation().isInvalid())
2588 return true;
2589
2590 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2591 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2592 Op = OO_Call;
2593 break;
2594 }
2595
2596 case tok::l_square: {
2597 // Consume the '[' and ']'.
2598 BalancedDelimiterTracker T(*this, tok::l_square);
2599 T.consumeOpen();
2600 T.consumeClose();
2601 if (T.getCloseLocation().isInvalid())
2602 return true;
2603
2604 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2605 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2606 Op = OO_Subscript;
2607 break;
2608 }
2609
2610 case tok::code_completion: {
2611 // Code completion for the operator name.
2612 Actions.CodeCompleteOperatorName(getCurScope());
2613 cutOffParsing();
2614 // Don't try to parse any further.
2615 return true;
2616 }
2617
2618 default:
2619 break;
2620 }
2621
2622 if (Op != OO_None) {
2623 // We have parsed an operator-function-id.
2624 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2625 return false;
2626 }
2627
2628 // Parse a literal-operator-id.
2629 //
2630 // literal-operator-id: C++11 [over.literal]
2631 // operator string-literal identifier
2632 // operator user-defined-string-literal
2633
2634 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2635 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2636
2637 SourceLocation DiagLoc;
2638 unsigned DiagId = 0;
2639
2640 // We're past translation phase 6, so perform string literal concatenation
2641 // before checking for "".
2642 SmallVector<Token, 4> Toks;
2643 SmallVector<SourceLocation, 4> TokLocs;
2644 while (isTokenStringLiteral()) {
2645 if (!Tok.is(tok::string_literal) && !DiagId) {
2646 // C++11 [over.literal]p1:
2647 // The string-literal or user-defined-string-literal in a
2648 // literal-operator-id shall have no encoding-prefix [...].
2649 DiagLoc = Tok.getLocation();
2650 DiagId = diag::err_literal_operator_string_prefix;
2651 }
2652 Toks.push_back(Tok);
2653 TokLocs.push_back(ConsumeStringToken());
2654 }
2655
2656 StringLiteralParser Literal(Toks, PP);
2657 if (Literal.hadError)
2658 return true;
2659
2660 // Grab the literal operator's suffix, which will be either the next token
2661 // or a ud-suffix from the string literal.
2662 IdentifierInfo *II = nullptr;
2663 SourceLocation SuffixLoc;
2664 if (!Literal.getUDSuffix().empty()) {
2665 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2666 SuffixLoc =
2667 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2668 Literal.getUDSuffixOffset(),
2669 PP.getSourceManager(), getLangOpts());
2670 } else if (Tok.is(tok::identifier)) {
2671 II = Tok.getIdentifierInfo();
2672 SuffixLoc = ConsumeToken();
2673 TokLocs.push_back(SuffixLoc);
2674 } else {
2675 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2676 return true;
2677 }
2678
2679 // The string literal must be empty.
2680 if (!Literal.GetString().empty() || Literal.Pascal) {
2681 // C++11 [over.literal]p1:
2682 // The string-literal or user-defined-string-literal in a
2683 // literal-operator-id shall [...] contain no characters
2684 // other than the implicit terminating '\0'.
2685 DiagLoc = TokLocs.front();
2686 DiagId = diag::err_literal_operator_string_not_empty;
2687 }
2688
2689 if (DiagId) {
2690 // This isn't a valid literal-operator-id, but we think we know
2691 // what the user meant. Tell them what they should have written.
2692 SmallString<32> Str;
2693 Str += "\"\"";
2694 Str += II->getName();
2695 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2696 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2697 }
2698
2699 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2700
2701 return Actions.checkLiteralOperatorId(SS, Result);
2702 }
2703
2704 // Parse a conversion-function-id.
2705 //
2706 // conversion-function-id: [C++ 12.3.2]
2707 // operator conversion-type-id
2708 //
2709 // conversion-type-id:
2710 // type-specifier-seq conversion-declarator[opt]
2711 //
2712 // conversion-declarator:
2713 // ptr-operator conversion-declarator[opt]
2714
2715 // Parse the type-specifier-seq.
2716 DeclSpec DS(AttrFactory);
2717 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2718 return true;
2719
2720 // Parse the conversion-declarator, which is merely a sequence of
2721 // ptr-operators.
2722 Declarator D(DS, DeclaratorContext::ConversionId);
2723 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2724
2725 // Finish up the type.
2726 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2727 if (Ty.isInvalid())
2728 return true;
2729
2730 // Note that this is a conversion-function-id.
2731 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2732 D.getSourceRange().getEnd());
2733 return false;
2734}
2735
2736/// Parse a C++ unqualified-id (or a C identifier), which describes the
2737/// name of an entity.
2738///
2739/// \code
2740/// unqualified-id: [C++ expr.prim.general]
2741/// identifier
2742/// operator-function-id
2743/// conversion-function-id
2744/// [C++0x] literal-operator-id [TODO]
2745/// ~ class-name
2746/// template-id
2747///
2748/// \endcode
2749///
2750/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2751/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2752///
2753/// \param ObjectType if this unqualified-id occurs within a member access
2754/// expression, the type of the base object whose member is being accessed.
2755///
2756/// \param ObjectHadErrors if this unqualified-id occurs within a member access
2757/// expression, indicates whether the original subexpressions had any errors.
2758/// When true, diagnostics for missing 'template' keyword will be supressed.
2759///
2760/// \param EnteringContext whether we are entering the scope of the
2761/// nested-name-specifier.
2762///
2763/// \param AllowDestructorName whether we allow parsing of a destructor name.
2764///
2765/// \param AllowConstructorName whether we allow parsing a constructor name.
2766///
2767/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2768///
2769/// \param Result on a successful parse, contains the parsed unqualified-id.
2770///
2771/// \returns true if parsing fails, false otherwise.
2772bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
2773 bool ObjectHadErrors, bool EnteringContext,
2774 bool AllowDestructorName,
2775 bool AllowConstructorName,
2776 bool AllowDeductionGuide,
2777 SourceLocation *TemplateKWLoc,
2778 UnqualifiedId &Result) {
2779 if (TemplateKWLoc)
2780 *TemplateKWLoc = SourceLocation();
2781
2782 // Handle 'A::template B'. This is for template-ids which have not
2783 // already been annotated by ParseOptionalCXXScopeSpecifier().
2784 bool TemplateSpecified = false;
2785 if (Tok.is(tok::kw_template)) {
2786 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2787 TemplateSpecified = true;
2788 *TemplateKWLoc = ConsumeToken();
2789 } else {
2790 SourceLocation TemplateLoc = ConsumeToken();
2791 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2792 << FixItHint::CreateRemoval(TemplateLoc);
2793 }
2794 }
2795
2796 // unqualified-id:
2797 // identifier
2798 // template-id (when it hasn't already been annotated)
2799 if (Tok.is(tok::identifier)) {
2800 // Consume the identifier.
2801 IdentifierInfo *Id = Tok.getIdentifierInfo();
2802 SourceLocation IdLoc = ConsumeToken();
2803
2804 if (!getLangOpts().CPlusPlus) {
2805 // If we're not in C++, only identifiers matter. Record the
2806 // identifier and return.
2807 Result.setIdentifier(Id, IdLoc);
2808 return false;
2809 }
2810
2811 ParsedTemplateTy TemplateName;
2812 if (AllowConstructorName &&
2813 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2814 // We have parsed a constructor name.
2815 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2816 EnteringContext);
2817 if (!Ty)
2818 return true;
2819 Result.setConstructorName(Ty, IdLoc, IdLoc);
2820 } else if (getLangOpts().CPlusPlus17 &&
2821 AllowDeductionGuide && SS.isEmpty() &&
2822 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2823 &TemplateName)) {
2824 // We have parsed a template-name naming a deduction guide.
2825 Result.setDeductionGuideName(TemplateName, IdLoc);
2826 } else {
2827 // We have parsed an identifier.
2828 Result.setIdentifier(Id, IdLoc);
2829 }
2830
2831 // If the next token is a '<', we may have a template.
2832 TemplateTy Template;
2833 if (Tok.is(tok::less))
2834 return ParseUnqualifiedIdTemplateId(
2835 SS, ObjectType, ObjectHadErrors,
2836 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2837 EnteringContext, Result, TemplateSpecified);
2838 else if (TemplateSpecified &&
2839 Actions.ActOnTemplateName(
2840 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2841 EnteringContext, Template,
2842 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2843 return true;
2844
2845 return false;
2846 }
2847
2848 // unqualified-id:
2849 // template-id (already parsed and annotated)
2850 if (Tok.is(tok::annot_template_id)) {
2851 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2852
2853 // FIXME: Consider passing invalid template-ids on to callers; they may
2854 // be able to recover better than we can.
2855 if (TemplateId->isInvalid()) {
2856 ConsumeAnnotationToken();
2857 return true;
2858 }
2859
2860 // If the template-name names the current class, then this is a constructor
2861 if (AllowConstructorName && TemplateId->Name &&
2862 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2863 if (SS.isSet()) {
2864 // C++ [class.qual]p2 specifies that a qualified template-name
2865 // is taken as the constructor name where a constructor can be
2866 // declared. Thus, the template arguments are extraneous, so
2867 // complain about them and remove them entirely.
2868 Diag(TemplateId->TemplateNameLoc,
2869 diag::err_out_of_line_constructor_template_id)
2870 << TemplateId->Name
2871 << FixItHint::CreateRemoval(
2872 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2873 ParsedType Ty = Actions.getConstructorName(
2874 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2875 EnteringContext);
2876 if (!Ty)
2877 return true;
2878 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2879 TemplateId->RAngleLoc);
2880 ConsumeAnnotationToken();
2881 return false;
2882 }
2883
2884 Result.setConstructorTemplateId(TemplateId);
2885 ConsumeAnnotationToken();
2886 return false;
2887 }
2888
2889 // We have already parsed a template-id; consume the annotation token as
2890 // our unqualified-id.
2891 Result.setTemplateId(TemplateId);
2892 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2893 if (TemplateLoc.isValid()) {
2894 if (TemplateKWLoc && (ObjectType || SS.isSet()))
2895 *TemplateKWLoc = TemplateLoc;
2896 else
2897 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2898 << FixItHint::CreateRemoval(TemplateLoc);
2899 }
2900 ConsumeAnnotationToken();
2901 return false;
2902 }
2903
2904 // unqualified-id:
2905 // operator-function-id
2906 // conversion-function-id
2907 if (Tok.is(tok::kw_operator)) {
2908 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2909 return true;
2910
2911 // If we have an operator-function-id or a literal-operator-id and the next
2912 // token is a '<', we may have a
2913 //
2914 // template-id:
2915 // operator-function-id < template-argument-list[opt] >
2916 TemplateTy Template;
2917 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2918 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
2919 Tok.is(tok::less))
2920 return ParseUnqualifiedIdTemplateId(
2921 SS, ObjectType, ObjectHadErrors,
2922 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2923 SourceLocation(), EnteringContext, Result, TemplateSpecified);
2924 else if (TemplateSpecified &&
2925 Actions.ActOnTemplateName(
2926 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2927 EnteringContext, Template,
2928 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2929 return true;
2930
2931 return false;
2932 }
2933
2934 if (getLangOpts().CPlusPlus &&
2935 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2936 // C++ [expr.unary.op]p10:
2937 // There is an ambiguity in the unary-expression ~X(), where X is a
2938 // class-name. The ambiguity is resolved in favor of treating ~ as a
2939 // unary complement rather than treating ~X as referring to a destructor.
2940
2941 // Parse the '~'.
2942 SourceLocation TildeLoc = ConsumeToken();
2943
2944 if (TemplateSpecified) {
2945 // C++ [temp.names]p3:
2946 // A name prefixed by the keyword template shall be a template-id [...]
2947 //
2948 // A template-id cannot begin with a '~' token. This would never work
2949 // anyway: x.~A<int>() would specify that the destructor is a template,
2950 // not that 'A' is a template.
2951 //
2952 // FIXME: Suggest replacing the attempted destructor name with a correct
2953 // destructor name and recover. (This is not trivial if this would become
2954 // a pseudo-destructor name).
2955 Diag(*TemplateKWLoc, diag::err_unexpected_template_in_destructor_name)
2956 << Tok.getLocation();
2957 return true;
2958 }
2959
2960 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2961 DeclSpec DS(AttrFactory);
2962 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2963 if (ParsedType Type =
2964 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
2965 Result.setDestructorName(TildeLoc, Type, EndLoc);
2966 return false;
2967 }
2968 return true;
2969 }
2970
2971 // Parse the class-name.
2972 if (Tok.isNot(tok::identifier)) {
2973 Diag(Tok, diag::err_destructor_tilde_identifier);
2974 return true;
2975 }
2976
2977 // If the user wrote ~T::T, correct it to T::~T.
2978 DeclaratorScopeObj DeclScopeObj(*this, SS);
2979 if (NextToken().is(tok::coloncolon)) {
2980 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2981 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2982 // it will confuse this recovery logic.
2983 ColonProtectionRAIIObject ColonRAII(*this, false);
2984
2985 if (SS.isSet()) {
2986 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2987 SS.clear();
2988 }
2989 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, ObjectHadErrors,
2990 EnteringContext))
2991 return true;
2992 if (SS.isNotEmpty())
2993 ObjectType = nullptr;
2994 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2995 !SS.isSet()) {
2996 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2997 return true;
2998 }
2999
3000 // Recover as if the tilde had been written before the identifier.
3001 Diag(TildeLoc, diag::err_destructor_tilde_scope)
3002 << FixItHint::CreateRemoval(TildeLoc)
3003 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
3004
3005 // Temporarily enter the scope for the rest of this function.
3006 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
3007 DeclScopeObj.EnterDeclaratorScope();
3008 }
3009
3010 // Parse the class-name (or template-name in a simple-template-id).
3011 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
3012 SourceLocation ClassNameLoc = ConsumeToken();
3013
3014 if (Tok.is(tok::less)) {
3015 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
3016 return ParseUnqualifiedIdTemplateId(
3017 SS, ObjectType, ObjectHadErrors,
3018 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
3019 ClassNameLoc, EnteringContext, Result, TemplateSpecified);
3020 }
3021
3022 // Note that this is a destructor name.
3023 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
3024 ClassNameLoc, getCurScope(),
3025 SS, ObjectType,
3026 EnteringContext);
3027 if (!Ty)
3028 return true;
3029
3030 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
3031 return false;
3032 }
3033
3034 Diag(Tok, diag::err_expected_unqualified_id)
3035 << getLangOpts().CPlusPlus;
3036 return true;
3037}
3038
3039/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
3040/// memory in a typesafe manner and call constructors.
3041///
3042/// This method is called to parse the new expression after the optional :: has
3043/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
3044/// is its location. Otherwise, "Start" is the location of the 'new' token.
3045///
3046/// new-expression:
3047/// '::'[opt] 'new' new-placement[opt] new-type-id
3048/// new-initializer[opt]
3049/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3050/// new-initializer[opt]
3051///
3052/// new-placement:
3053/// '(' expression-list ')'
3054///
3055/// new-type-id:
3056/// type-specifier-seq new-declarator[opt]
3057/// [GNU] attributes type-specifier-seq new-declarator[opt]
3058///
3059/// new-declarator:
3060/// ptr-operator new-declarator[opt]
3061/// direct-new-declarator
3062///
3063/// new-initializer:
3064/// '(' expression-list[opt] ')'
3065/// [C++0x] braced-init-list
3066///
3067ExprResult
3068Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
3069 assert(Tok.is(tok::kw_new) && "expected 'new' token")((Tok.is(tok::kw_new) && "expected 'new' token") ? static_cast
<void> (0) : __assert_fail ("Tok.is(tok::kw_new) && \"expected 'new' token\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3069, __PRETTY_FUNCTION__))
;
3070 ConsumeToken(); // Consume 'new'
3071
3072 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
3073 // second form of new-expression. It can't be a new-type-id.
3074
3075 ExprVector PlacementArgs;
3076 SourceLocation PlacementLParen, PlacementRParen;
3077
3078 SourceRange TypeIdParens;
3079 DeclSpec DS(AttrFactory);
3080 Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNew);
3081 if (Tok.is(tok::l_paren)) {
3082 // If it turns out to be a placement, we change the type location.
3083 BalancedDelimiterTracker T(*this, tok::l_paren);
3084 T.consumeOpen();
3085 PlacementLParen = T.getOpenLocation();
3086 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
3087 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3088 return ExprError();
3089 }
3090
3091 T.consumeClose();
3092 PlacementRParen = T.getCloseLocation();
3093 if (PlacementRParen.isInvalid()) {
3094 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3095 return ExprError();
3096 }
3097
3098 if (PlacementArgs.empty()) {
3099 // Reset the placement locations. There was no placement.
3100 TypeIdParens = T.getRange();
3101 PlacementLParen = PlacementRParen = SourceLocation();
3102 } else {
3103 // We still need the type.
3104 if (Tok.is(tok::l_paren)) {
3105 BalancedDelimiterTracker T(*this, tok::l_paren);
3106 T.consumeOpen();
3107 MaybeParseGNUAttributes(DeclaratorInfo);
3108 ParseSpecifierQualifierList(DS);
3109 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3110 ParseDeclarator(DeclaratorInfo);
3111 T.consumeClose();
3112 TypeIdParens = T.getRange();
3113 } else {
3114 MaybeParseGNUAttributes(DeclaratorInfo);
3115 if (ParseCXXTypeSpecifierSeq(DS))
3116 DeclaratorInfo.setInvalidType(true);
3117 else {
3118 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3119 ParseDeclaratorInternal(DeclaratorInfo,
3120 &Parser::ParseDirectNewDeclarator);
3121 }
3122 }
3123 }
3124 } else {
3125 // A new-type-id is a simplified type-id, where essentially the
3126 // direct-declarator is replaced by a direct-new-declarator.
3127 MaybeParseGNUAttributes(DeclaratorInfo);
3128 if (ParseCXXTypeSpecifierSeq(DS))
3129 DeclaratorInfo.setInvalidType(true);
3130 else {
3131 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3132 ParseDeclaratorInternal(DeclaratorInfo,
3133 &Parser::ParseDirectNewDeclarator);
3134 }
3135 }
3136 if (DeclaratorInfo.isInvalidType()) {
3137 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3138 return ExprError();
3139 }
3140
3141 ExprResult Initializer;
3142
3143 if (Tok.is(tok::l_paren)) {
3144 SourceLocation ConstructorLParen, ConstructorRParen;
3145 ExprVector ConstructorArgs;
3146 BalancedDelimiterTracker T(*this, tok::l_paren);
3147 T.consumeOpen();
3148 ConstructorLParen = T.getOpenLocation();
3149 if (Tok.isNot(tok::r_paren)) {
3150 CommaLocsTy CommaLocs;
3151 auto RunSignatureHelp = [&]() {
3152 ParsedType TypeRep =
3153 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
3154 QualType PreferredType;
3155 // ActOnTypeName might adjust DeclaratorInfo and return a null type even
3156 // the passing DeclaratorInfo is valid, e.g. running SignatureHelp on
3157 // `new decltype(invalid) (^)`.
3158 if (TypeRep)
3159 PreferredType = Actions.ProduceConstructorSignatureHelp(
3160 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
3161 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
3162 CalledSignatureHelp = true;
3163 return PreferredType;
3164 };
3165 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
3166 PreferredType.enterFunctionArgument(Tok.getLocation(),
3167 RunSignatureHelp);
3168 })) {
3169 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3170 RunSignatureHelp();
3171 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3172 return ExprError();
3173 }
3174 }
3175 T.consumeClose();
3176 ConstructorRParen = T.getCloseLocation();
3177 if (ConstructorRParen.isInvalid()) {
3178 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3179 return ExprError();
3180 }
3181 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
3182 ConstructorRParen,
3183 ConstructorArgs);
3184 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
3185 Diag(Tok.getLocation(),
3186 diag::warn_cxx98_compat_generalized_initializer_lists);
3187 Initializer = ParseBraceInitializer();
3188 }
3189 if (Initializer.isInvalid())
3190 return Initializer;
3191
3192 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
3193 PlacementArgs, PlacementRParen,
3194 TypeIdParens, DeclaratorInfo, Initializer.get());
3195}
3196
3197/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
3198/// passed to ParseDeclaratorInternal.
3199///
3200/// direct-new-declarator:
3201/// '[' expression[opt] ']'
3202/// direct-new-declarator '[' constant-expression ']'
3203///
3204void Parser::ParseDirectNewDeclarator(Declarator &D) {
3205 // Parse the array dimensions.
3206 bool First = true;
3207 while (Tok.is(tok::l_square)) {
3208 // An array-size expression can't start with a lambda.
3209 if (CheckProhibitedCXX11Attribute())
3210 continue;
3211
3212 BalancedDelimiterTracker T(*this, tok::l_square);
3213 T.consumeOpen();
3214
3215 ExprResult Size =
3216 First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression())
3217 : ParseConstantExpression();
3218 if (Size.isInvalid()) {
3219 // Recover
3220 SkipUntil(tok::r_square, StopAtSemi);
3221 return;
3222 }
3223 First = false;
3224
3225 T.consumeClose();
3226
3227 // Attributes here appertain to the array type. C++11 [expr.new]p5.
3228 ParsedAttributes Attrs(AttrFactory);
3229 MaybeParseCXX11Attributes(Attrs);
3230
3231 D.AddTypeInfo(DeclaratorChunk::getArray(0,
3232 /*isStatic=*/false, /*isStar=*/false,
3233 Size.get(), T.getOpenLocation(),
3234 T.getCloseLocation()),
3235 std::move(Attrs), T.getCloseLocation());
3236
3237 if (T.getCloseLocation().isInvalid())
3238 return;
3239 }
3240}
3241
3242/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
3243/// This ambiguity appears in the syntax of the C++ new operator.
3244///
3245/// new-expression:
3246/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3247/// new-initializer[opt]
3248///
3249/// new-placement:
3250/// '(' expression-list ')'
3251///
3252bool Parser::ParseExpressionListOrTypeId(
3253 SmallVectorImpl<Expr*> &PlacementArgs,
3254 Declarator &D) {
3255 // The '(' was already consumed.
3256 if (isTypeIdInParens()) {
3257 ParseSpecifierQualifierList(D.getMutableDeclSpec());
3258 D.SetSourceRange(D.getDeclSpec().getSourceRange());
3259 ParseDeclarator(D);
3260 return D.isInvalidType();
3261 }
3262
3263 // It's not a type, it has to be an expression list.
3264 // Discard the comma locations - ActOnCXXNew has enough parameters.
3265 CommaLocsTy CommaLocs;
3266 return ParseExpressionList(PlacementArgs, CommaLocs);
3267}
3268
3269/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
3270/// to free memory allocated by new.
3271///
3272/// This method is called to parse the 'delete' expression after the optional
3273/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
3274/// and "Start" is its location. Otherwise, "Start" is the location of the
3275/// 'delete' token.
3276///
3277/// delete-expression:
3278/// '::'[opt] 'delete' cast-expression
3279/// '::'[opt] 'delete' '[' ']' cast-expression
3280ExprResult
3281Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
3282 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword")((Tok.is(tok::kw_delete) && "Expected 'delete' keyword"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::kw_delete) && \"Expected 'delete' keyword\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3282, __PRETTY_FUNCTION__))
;
3283 ConsumeToken(); // Consume 'delete'
3284
3285 // Array delete?
3286 bool ArrayDelete = false;
3287 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
3288 // C++11 [expr.delete]p1:
3289 // Whenever the delete keyword is followed by empty square brackets, it
3290 // shall be interpreted as [array delete].
3291 // [Footnote: A lambda expression with a lambda-introducer that consists
3292 // of empty square brackets can follow the delete keyword if
3293 // the lambda expression is enclosed in parentheses.]
3294
3295 const Token Next = GetLookAheadToken(2);
3296
3297 // Basic lookahead to check if we have a lambda expression.
3298 if (Next.isOneOf(tok::l_brace, tok::less) ||
3299 (Next.is(tok::l_paren) &&
3300 (GetLookAheadToken(3).is(tok::r_paren) ||
3301 (GetLookAheadToken(3).is(tok::identifier) &&
3302 GetLookAheadToken(4).is(tok::identifier))))) {
3303 TentativeParsingAction TPA(*this);
3304 SourceLocation LSquareLoc = Tok.getLocation();
3305 SourceLocation RSquareLoc = NextToken().getLocation();
3306
3307 // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
3308 // case.
3309 SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch);
3310 SourceLocation RBraceLoc;
3311 bool EmitFixIt = false;
3312 if (Tok.is(tok::l_brace)) {
3313 ConsumeBrace();
3314 SkipUntil(tok::r_brace, StopBeforeMatch);
3315 RBraceLoc = Tok.getLocation();
3316 EmitFixIt = true;
3317 }
3318
3319 TPA.Revert();
3320
3321 if (EmitFixIt)
3322 Diag(Start, diag::err_lambda_after_delete)
3323 << SourceRange(Start, RSquareLoc)
3324 << FixItHint::CreateInsertion(LSquareLoc, "(")
3325 << FixItHint::CreateInsertion(
3326 Lexer::getLocForEndOfToken(
3327 RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()),
3328 ")");
3329 else
3330 Diag(Start, diag::err_lambda_after_delete)
3331 << SourceRange(Start, RSquareLoc);
3332
3333 // Warn that the non-capturing lambda isn't surrounded by parentheses
3334 // to disambiguate it from 'delete[]'.
3335 ExprResult Lambda = ParseLambdaExpression();
3336 if (Lambda.isInvalid())
3337 return ExprError();
3338
3339 // Evaluate any postfix expressions used on the lambda.
3340 Lambda = ParsePostfixExpressionSuffix(Lambda);
3341 if (Lambda.isInvalid())
3342 return ExprError();
3343 return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
3344 Lambda.get());
3345 }
3346
3347 ArrayDelete = true;
3348 BalancedDelimiterTracker T(*this, tok::l_square);
3349
3350 T.consumeOpen();
3351 T.consumeClose();
3352 if (T.getCloseLocation().isInvalid())
3353 return ExprError();
3354 }
3355
3356 ExprResult Operand(ParseCastExpression(AnyCastExpr));
3357 if (Operand.isInvalid())
3358 return Operand;
3359
3360 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
3361}
3362
3363/// ParseRequiresExpression - Parse a C++2a requires-expression.
3364/// C++2a [expr.prim.req]p1
3365/// A requires-expression provides a concise way to express requirements on
3366/// template arguments. A requirement is one that can be checked by name
3367/// lookup (6.4) or by checking properties of types and expressions.
3368///
3369/// requires-expression:
3370/// 'requires' requirement-parameter-list[opt] requirement-body
3371///
3372/// requirement-parameter-list:
3373/// '(' parameter-declaration-clause[opt] ')'
3374///
3375/// requirement-body:
3376/// '{' requirement-seq '}'
3377///
3378/// requirement-seq:
3379/// requirement
3380/// requirement-seq requirement
3381///
3382/// requirement:
3383/// simple-requirement
3384/// type-requirement
3385/// compound-requirement
3386/// nested-requirement
3387ExprResult Parser::ParseRequiresExpression() {
3388 assert(Tok.is(tok::kw_requires) && "Expected 'requires' keyword")((Tok.is(tok::kw_requires) && "Expected 'requires' keyword"
) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::kw_requires) && \"Expected 'requires' keyword\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3388, __PRETTY_FUNCTION__))
;
3389 SourceLocation RequiresKWLoc = ConsumeToken(); // Consume 'requires'
3390
3391 llvm::SmallVector<ParmVarDecl *, 2> LocalParameterDecls;
3392 if (Tok.is(tok::l_paren)) {
3393 // requirement parameter list is present.
3394 ParseScope LocalParametersScope(this, Scope::FunctionPrototypeScope |
3395 Scope::DeclScope);
3396 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3397 Parens.consumeOpen();
3398 if (!Tok.is(tok::r_paren)) {
3399 ParsedAttributes FirstArgAttrs(getAttrFactory());
3400 SourceLocation EllipsisLoc;
3401 llvm::SmallVector<DeclaratorChunk::ParamInfo, 2> LocalParameters;
3402 ParseParameterDeclarationClause(DeclaratorContext::RequiresExpr,
3403 FirstArgAttrs, LocalParameters,
3404 EllipsisLoc);
3405 if (EllipsisLoc.isValid())
3406 Diag(EllipsisLoc, diag::err_requires_expr_parameter_list_ellipsis);
3407 for (auto &ParamInfo : LocalParameters)
3408 LocalParameterDecls.push_back(cast<ParmVarDecl>(ParamInfo.Param));
3409 }
3410 Parens.consumeClose();
3411 }
3412
3413 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3414 if (Braces.expectAndConsume())
3415 return ExprError();
3416
3417 // Start of requirement list
3418 llvm::SmallVector<concepts::Requirement *, 2> Requirements;
3419
3420 // C++2a [expr.prim.req]p2
3421 // Expressions appearing within a requirement-body are unevaluated operands.
3422 EnterExpressionEvaluationContext Ctx(
3423 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
3424
3425 ParseScope BodyScope(this, Scope::DeclScope);
3426 RequiresExprBodyDecl *Body = Actions.ActOnStartRequiresExpr(
3427 RequiresKWLoc, LocalParameterDecls, getCurScope());
3428
3429 if (Tok.is(tok::r_brace)) {
3430 // Grammar does not allow an empty body.
3431 // requirement-body:
3432 // { requirement-seq }
3433 // requirement-seq:
3434 // requirement
3435 // requirement-seq requirement
3436 Diag(Tok, diag::err_empty_requires_expr);
3437 // Continue anyway and produce a requires expr with no requirements.
3438 } else {
3439 while (!Tok.is(tok::r_brace)) {
3440 switch (Tok.getKind()) {
3441 case tok::l_brace: {
3442 // Compound requirement
3443 // C++ [expr.prim.req.compound]
3444 // compound-requirement:
3445 // '{' expression '}' 'noexcept'[opt]
3446 // return-type-requirement[opt] ';'
3447 // return-type-requirement:
3448 // trailing-return-type
3449 // '->' cv-qualifier-seq[opt] constrained-parameter
3450 // cv-qualifier-seq[opt] abstract-declarator[opt]
3451 BalancedDelimiterTracker ExprBraces(*this, tok::l_brace);
3452 ExprBraces.consumeOpen();
3453 ExprResult Expression =
3454 Actions.CorrectDelayedTyposInExpr(ParseExpression());
3455 if (!Expression.isUsable()) {
3456 ExprBraces.skipToEnd();
3457 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3458 break;
3459 }
3460 if (ExprBraces.consumeClose())
3461 ExprBraces.skipToEnd();
3462
3463 concepts::Requirement *Req = nullptr;
3464 SourceLocation NoexceptLoc;
3465 TryConsumeToken(tok::kw_noexcept, NoexceptLoc);
3466 if (Tok.is(tok::semi)) {
3467 Req = Actions.ActOnCompoundRequirement(Expression.get(), NoexceptLoc);
3468 if (Req)
3469 Requirements.push_back(Req);
3470 break;
3471 }
3472 if (!TryConsumeToken(tok::arrow))
3473 // User probably forgot the arrow, remind them and try to continue.
3474 Diag(Tok, diag::err_requires_expr_missing_arrow)
3475 << FixItHint::CreateInsertion(Tok.getLocation(), "->");
3476 // Try to parse a 'type-constraint'
3477 if (TryAnnotateTypeConstraint()) {
3478 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3479 break;
3480 }
3481 if (!isTypeConstraintAnnotation()) {
3482 Diag(Tok, diag::err_requires_expr_expected_type_constraint);
3483 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3484 break;
3485 }
3486 CXXScopeSpec SS;
3487 if (Tok.is(tok::annot_cxxscope)) {
3488 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3489 Tok.getAnnotationRange(),
3490 SS);
3491 ConsumeAnnotationToken();
3492 }
3493
3494 Req = Actions.ActOnCompoundRequirement(
3495 Expression.get(), NoexceptLoc, SS, takeTemplateIdAnnotation(Tok),
3496 TemplateParameterDepth);
3497 ConsumeAnnotationToken();
3498 if (Req)
3499 Requirements.push_back(Req);
3500 break;
3501 }
3502 default: {
3503 bool PossibleRequiresExprInSimpleRequirement = false;
3504 if (Tok.is(tok::kw_requires)) {
3505 auto IsNestedRequirement = [&] {
3506 RevertingTentativeParsingAction TPA(*this);
3507 ConsumeToken(); // 'requires'
3508 if (Tok.is(tok::l_brace))
3509 // This is a requires expression
3510 // requires (T t) {
3511 // requires { t++; };
3512 // ... ^
3513 // }
3514 return false;
3515 if (Tok.is(tok::l_paren)) {
3516 // This might be the parameter list of a requires expression
3517 ConsumeParen();
3518 auto Res = TryParseParameterDeclarationClause();
3519 if (Res != TPResult::False) {
3520 // Skip to the closing parenthesis
3521 // FIXME: Don't traverse these tokens twice (here and in
3522 // TryParseParameterDeclarationClause).
3523 unsigned Depth = 1;
3524 while (Depth != 0) {
3525 if (Tok.is(tok::l_paren))
3526 Depth++;
3527 else if (Tok.is(tok::r_paren))
3528 Depth--;
3529 ConsumeAnyToken();
3530 }
3531 // requires (T t) {
3532 // requires () ?
3533 // ... ^
3534 // - OR -
3535 // requires (int x) ?
3536 // ... ^
3537 // }
3538 if (Tok.is(tok::l_brace))
3539 // requires (...) {
3540 // ^ - a requires expression as a
3541 // simple-requirement.
3542 return false;
3543 }
3544 }
3545 return true;
3546 };
3547 if (IsNestedRequirement()) {
3548 ConsumeToken();
3549 // Nested requirement
3550 // C++ [expr.prim.req.nested]
3551 // nested-requirement:
3552 // 'requires' constraint-expression ';'
3553 ExprResult ConstraintExpr =
3554 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
3555 if (ConstraintExpr.isInvalid() || !ConstraintExpr.isUsable()) {
3556 SkipUntil(tok::semi, tok::r_brace,
3557 SkipUntilFlags::StopBeforeMatch);
3558 break;
3559 }
3560 if (auto *Req =
3561 Actions.ActOnNestedRequirement(ConstraintExpr.get()))
3562 Requirements.push_back(Req);
3563 else {
3564 SkipUntil(tok::semi, tok::r_brace,
3565 SkipUntilFlags::StopBeforeMatch);
3566 break;
3567 }
3568 break;
3569 } else
3570 PossibleRequiresExprInSimpleRequirement = true;
3571 } else if (Tok.is(tok::kw_typename)) {
3572 // This might be 'typename T::value_type;' (a type requirement) or
3573 // 'typename T::value_type{};' (a simple requirement).
3574 TentativeParsingAction TPA(*this);
3575
3576 // We need to consume the typename to allow 'requires { typename a; }'
3577 SourceLocation TypenameKWLoc = ConsumeToken();
3578 if (TryAnnotateCXXScopeToken()) {
3579 TPA.Commit();
3580 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3581 break;
3582 }
3583 CXXScopeSpec SS;
3584 if (Tok.is(tok::annot_cxxscope)) {
3585 Actions.RestoreNestedNameSpecifierAnnotation(
3586 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3587 ConsumeAnnotationToken();
3588 }
3589
3590 if (Tok.isOneOf(tok::identifier, tok::annot_template_id) &&
3591 !NextToken().isOneOf(tok::l_brace, tok::l_paren)) {
3592 TPA.Commit();
3593 SourceLocation NameLoc = Tok.getLocation();
3594 IdentifierInfo *II = nullptr;
3595 TemplateIdAnnotation *TemplateId = nullptr;
3596 if (Tok.is(tok::identifier)) {
3597 II = Tok.getIdentifierInfo();
3598 ConsumeToken();
3599 } else {
3600 TemplateId = takeTemplateIdAnnotation(Tok);
3601 ConsumeAnnotationToken();
3602 if (TemplateId->isInvalid())
3603 break;
3604 }
3605
3606 if (auto *Req = Actions.ActOnTypeRequirement(TypenameKWLoc, SS,
3607 NameLoc, II,
3608 TemplateId)) {
3609 Requirements.push_back(Req);
3610 }
3611 break;
3612 }
3613 TPA.Revert();
3614 }
3615 // Simple requirement
3616 // C++ [expr.prim.req.simple]
3617 // simple-requirement:
3618 // expression ';'
3619 SourceLocation StartLoc = Tok.getLocation();
3620 ExprResult Expression =
3621 Actions.CorrectDelayedTyposInExpr(ParseExpression());
3622 if (!Expression.isUsable()) {
3623 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3624 break;
3625 }
3626 if (!Expression.isInvalid() && PossibleRequiresExprInSimpleRequirement)
3627 Diag(StartLoc, diag::warn_requires_expr_in_simple_requirement)
3628 << FixItHint::CreateInsertion(StartLoc, "requires");
3629 if (auto *Req = Actions.ActOnSimpleRequirement(Expression.get()))
3630 Requirements.push_back(Req);
3631 else {
3632 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3633 break;
3634 }
3635 // User may have tried to put some compound requirement stuff here
3636 if (Tok.is(tok::kw_noexcept)) {
3637 Diag(Tok, diag::err_requires_expr_simple_requirement_noexcept)
3638 << FixItHint::CreateInsertion(StartLoc, "{")
3639 << FixItHint::CreateInsertion(Tok.getLocation(), "}");
3640 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3641 break;
3642 }
3643 break;
3644 }
3645 }
3646 if (ExpectAndConsumeSemi(diag::err_expected_semi_requirement)) {
3647 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3648 TryConsumeToken(tok::semi);
3649 break;
3650 }
3651 }
3652 if (Requirements.empty()) {
3653 // Don't emit an empty requires expr here to avoid confusing the user with
3654 // other diagnostics quoting an empty requires expression they never
3655 // wrote.
3656 Braces.consumeClose();
3657 Actions.ActOnFinishRequiresExpr();
3658 return ExprError();
3659 }
3660 }
3661 Braces.consumeClose();
3662 Actions.ActOnFinishRequiresExpr();
3663 return Actions.ActOnRequiresExpr(RequiresKWLoc, Body, LocalParameterDecls,
3664 Requirements, Braces.getCloseLocation());
3665}
3666
3667static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
3668 switch (kind) {
3669 default: llvm_unreachable("Not a known type trait")::llvm::llvm_unreachable_internal("Not a known type trait", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3669)
;
3670#define TYPE_TRAIT_1(Spelling, Name, Key) \
3671case tok::kw_ ## Spelling: return UTT_ ## Name;
3672#define TYPE_TRAIT_2(Spelling, Name, Key) \
3673case tok::kw_ ## Spelling: return BTT_ ## Name;
3674#include "clang/Basic/TokenKinds.def"
3675#define TYPE_TRAIT_N(Spelling, Name, Key) \
3676 case tok::kw_ ## Spelling: return TT_ ## Name;
3677#include "clang/Basic/TokenKinds.def"
3678 }
3679}
3680
3681static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
3682 switch (kind) {
3683 default:
3684 llvm_unreachable("Not a known array type trait")::llvm::llvm_unreachable_internal("Not a known array type trait"
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3684)
;
3685#define ARRAY_TYPE_TRAIT(Spelling, Name, Key) \
3686 case tok::kw_##Spelling: \
3687 return ATT_##Name;
3688#include "clang/Basic/TokenKinds.def"
3689 }
3690}
3691
3692static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
3693 switch (kind) {
3694 default:
3695 llvm_unreachable("Not a known unary expression trait.")::llvm::llvm_unreachable_internal("Not a known unary expression trait."
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3695)
;
3696#define EXPRESSION_TRAIT(Spelling, Name, Key) \
3697 case tok::kw_##Spelling: \
3698 return ET_##Name;
3699#include "clang/Basic/TokenKinds.def"
3700 }
3701}
3702
3703static unsigned TypeTraitArity(tok::TokenKind kind) {
3704 switch (kind) {
3705 default: llvm_unreachable("Not a known type trait")::llvm::llvm_unreachable_internal("Not a known type trait", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3705)
;
3706#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3707#include "clang/Basic/TokenKinds.def"
3708 }
3709}
3710
3711/// Parse the built-in type-trait pseudo-functions that allow
3712/// implementation of the TR1/C++11 type traits templates.
3713///
3714/// primary-expression:
3715/// unary-type-trait '(' type-id ')'
3716/// binary-type-trait '(' type-id ',' type-id ')'
3717/// type-trait '(' type-id-seq ')'
3718///
3719/// type-id-seq:
3720/// type-id ...[opt] type-id-seq[opt]
3721///
3722ExprResult Parser::ParseTypeTrait() {
3723 tok::TokenKind Kind = Tok.getKind();
3724 unsigned Arity = TypeTraitArity(Kind);
3725
3726 SourceLocation Loc = ConsumeToken();
3727
3728 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3729 if (Parens.expectAndConsume())
3730 return ExprError();
3731
3732 SmallVector<ParsedType, 2> Args;
3733 do {
3734 // Parse the next type.
3735 TypeResult Ty = ParseTypeName();
3736 if (Ty.isInvalid()) {
3737 Parens.skipToEnd();
3738 return ExprError();
3739 }
3740
3741 // Parse the ellipsis, if present.
3742 if (Tok.is(tok::ellipsis)) {
3743 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3744 if (Ty.isInvalid()) {
3745 Parens.skipToEnd();
3746 return ExprError();
3747 }
3748 }
3749
3750 // Add this type to the list of arguments.
3751 Args.push_back(Ty.get());
3752 } while (TryConsumeToken(tok::comma));
3753
3754 if (Parens.consumeClose())
3755 return ExprError();
3756
3757 SourceLocation EndLoc = Parens.getCloseLocation();
3758
3759 if (Arity && Args.size() != Arity) {
3760 Diag(EndLoc, diag::err_type_trait_arity)
3761 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3762 return ExprError();
3763 }
3764
3765 if (!Arity && Args.empty()) {
3766 Diag(EndLoc, diag::err_type_trait_arity)
3767 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3768 return ExprError();
3769 }
3770
3771 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3772}
3773
3774/// ParseArrayTypeTrait - Parse the built-in array type-trait
3775/// pseudo-functions.
3776///
3777/// primary-expression:
3778/// [Embarcadero] '__array_rank' '(' type-id ')'
3779/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3780///
3781ExprResult Parser::ParseArrayTypeTrait() {
3782 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3783 SourceLocation Loc = ConsumeToken();
3784
3785 BalancedDelimiterTracker T(*this, tok::l_paren);
3786 if (T.expectAndConsume())
3787 return ExprError();
3788
3789 TypeResult Ty = ParseTypeName();
3790 if (Ty.isInvalid()) {
3791 SkipUntil(tok::comma, StopAtSemi);
3792 SkipUntil(tok::r_paren, StopAtSemi);
3793 return ExprError();
3794 }
3795
3796 switch (ATT) {
3797 case ATT_ArrayRank: {
3798 T.consumeClose();
3799 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3800 T.getCloseLocation());
3801 }
3802 case ATT_ArrayExtent: {
3803 if (ExpectAndConsume(tok::comma)) {
3804 SkipUntil(tok::r_paren, StopAtSemi);
3805 return ExprError();
3806 }
3807
3808 ExprResult DimExpr = ParseExpression();
3809 T.consumeClose();
3810
3811 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3812 T.getCloseLocation());
3813 }
3814 }
3815 llvm_unreachable("Invalid ArrayTypeTrait!")::llvm::llvm_unreachable_internal("Invalid ArrayTypeTrait!", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3815)
;
3816}
3817
3818/// ParseExpressionTrait - Parse built-in expression-trait
3819/// pseudo-functions like __is_lvalue_expr( xxx ).
3820///
3821/// primary-expression:
3822/// [Embarcadero] expression-trait '(' expression ')'
3823///
3824ExprResult Parser::ParseExpressionTrait() {
3825 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3826 SourceLocation Loc = ConsumeToken();
3827
3828 BalancedDelimiterTracker T(*this, tok::l_paren);
3829 if (T.expectAndConsume())
3830 return ExprError();
3831
3832 ExprResult Expr = ParseExpression();
3833
3834 T.consumeClose();
3835
3836 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3837 T.getCloseLocation());
3838}
3839
3840
3841/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3842/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3843/// based on the context past the parens.
3844ExprResult
3845Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3846 ParsedType &CastTy,
3847 BalancedDelimiterTracker &Tracker,
3848 ColonProtectionRAIIObject &ColonProt) {
3849 assert(getLangOpts().CPlusPlus && "Should only be called for C++!")((getLangOpts().CPlusPlus && "Should only be called for C++!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Should only be called for C++!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3849, __PRETTY_FUNCTION__))
;
3850 assert(ExprType == CastExpr && "Compound literals are not ambiguous!")((ExprType == CastExpr && "Compound literals are not ambiguous!"
) ? static_cast<void> (0) : __assert_fail ("ExprType == CastExpr && \"Compound literals are not ambiguous!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3850, __PRETTY_FUNCTION__))
;
3851 assert(isTypeIdInParens() && "Not a type-id!")((isTypeIdInParens() && "Not a type-id!") ? static_cast
<void> (0) : __assert_fail ("isTypeIdInParens() && \"Not a type-id!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3851, __PRETTY_FUNCTION__))
;
3852
3853 ExprResult Result(true);
3854 CastTy = nullptr;
3855
3856 // We need to disambiguate a very ugly part of the C++ syntax:
3857 //
3858 // (T())x; - type-id
3859 // (T())*x; - type-id
3860 // (T())/x; - expression
3861 // (T()); - expression
3862 //
3863 // The bad news is that we cannot use the specialized tentative parser, since
3864 // it can only verify that the thing inside the parens can be parsed as
3865 // type-id, it is not useful for determining the context past the parens.
3866 //
3867 // The good news is that the parser can disambiguate this part without
3868 // making any unnecessary Action calls.
3869 //
3870 // It uses a scheme similar to parsing inline methods. The parenthesized
3871 // tokens are cached, the context that follows is determined (possibly by
3872 // parsing a cast-expression), and then we re-introduce the cached tokens
3873 // into the token stream and parse them appropriately.
3874
3875 ParenParseOption ParseAs;
3876 CachedTokens Toks;
3877
3878 // Store the tokens of the parentheses. We will parse them after we determine
3879 // the context that follows them.
3880 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3881 // We didn't find the ')' we expected.
3882 Tracker.consumeClose();
3883 return ExprError();
3884 }
3885
3886 if (Tok.is(tok::l_brace)) {
3887 ParseAs = CompoundLiteral;
3888 } else {
3889 bool NotCastExpr;
3890 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3891 NotCastExpr = true;
3892 } else {
3893 // Try parsing the cast-expression that may follow.
3894 // If it is not a cast-expression, NotCastExpr will be true and no token
3895 // will be consumed.
3896 ColonProt.restore();
3897 Result = ParseCastExpression(AnyCastExpr,
3898 false/*isAddressofOperand*/,
3899 NotCastExpr,
3900 // type-id has priority.
3901 IsTypeCast);
3902 }
3903
3904 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3905 // an expression.
3906 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3907 }
3908
3909 // Create a fake EOF to mark end of Toks buffer.
3910 Token AttrEnd;
3911 AttrEnd.startToken();
3912 AttrEnd.setKind(tok::eof);
3913 AttrEnd.setLocation(Tok.getLocation());
3914 AttrEnd.setEofData(Toks.data());
3915 Toks.push_back(AttrEnd);
3916
3917 // The current token should go after the cached tokens.
3918 Toks.push_back(Tok);
3919 // Re-enter the stored parenthesized tokens into the token stream, so we may
3920 // parse them now.
3921 PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true,
3922 /*IsReinject*/ true);
3923 // Drop the current token and bring the first cached one. It's the same token
3924 // as when we entered this function.
3925 ConsumeAnyToken();
3926
3927 if (ParseAs >= CompoundLiteral) {
3928 // Parse the type declarator.
3929 DeclSpec DS(AttrFactory);
3930 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
3931 {
3932 ColonProtectionRAIIObject InnerColonProtection(*this);
3933 ParseSpecifierQualifierList(DS);
3934 ParseDeclarator(DeclaratorInfo);
3935 }
3936
3937 // Match the ')'.
3938 Tracker.consumeClose();
3939 ColonProt.restore();
3940
3941 // Consume EOF marker for Toks buffer.
3942 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())((Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData
()) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()"
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3942, __PRETTY_FUNCTION__))
;
3943 ConsumeAnyToken();
3944
3945 if (ParseAs == CompoundLiteral) {
3946 ExprType = CompoundLiteral;
3947 if (DeclaratorInfo.isInvalidType())
3948 return ExprError();
3949
3950 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3951 return ParseCompoundLiteralExpression(Ty.get(),
3952 Tracker.getOpenLocation(),
3953 Tracker.getCloseLocation());
3954 }
3955
3956 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3957 assert(ParseAs == CastExpr)((ParseAs == CastExpr) ? static_cast<void> (0) : __assert_fail
("ParseAs == CastExpr", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3957, __PRETTY_FUNCTION__))
;
3958
3959 if (DeclaratorInfo.isInvalidType())
3960 return ExprError();
3961
3962 // Result is what ParseCastExpression returned earlier.
3963 if (!Result.isInvalid())
3964 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3965 DeclaratorInfo, CastTy,
3966 Tracker.getCloseLocation(), Result.get());
3967 return Result;
3968 }
3969
3970 // Not a compound literal, and not followed by a cast-expression.
3971 assert(ParseAs == SimpleExpr)((ParseAs == SimpleExpr) ? static_cast<void> (0) : __assert_fail
("ParseAs == SimpleExpr", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3971, __PRETTY_FUNCTION__))
;
3972
3973 ExprType = SimpleExpr;
3974 Result = ParseExpression();
3975 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3976 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3977 Tok.getLocation(), Result.get());
3978
3979 // Match the ')'.
3980 if (Result.isInvalid()) {
3981 while (Tok.isNot(tok::eof))
3982 ConsumeAnyToken();
3983 assert(Tok.getEofData() == AttrEnd.getEofData())((Tok.getEofData() == AttrEnd.getEofData()) ? static_cast<
void> (0) : __assert_fail ("Tok.getEofData() == AttrEnd.getEofData()"
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3983, __PRETTY_FUNCTION__))
;
3984 ConsumeAnyToken();
3985 return ExprError();
3986 }
3987
3988 Tracker.consumeClose();
3989 // Consume EOF marker for Toks buffer.
3990 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())((Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData
()) ? static_cast<void> (0) : __assert_fail ("Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()"
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/lib/Parse/ParseExprCXX.cpp"
, 3990, __PRETTY_FUNCTION__))
;
3991 ConsumeAnyToken();
3992 return Result;
3993}
3994
3995/// Parse a __builtin_bit_cast(T, E).
3996ExprResult Parser::ParseBuiltinBitCast() {
3997 SourceLocation KWLoc = ConsumeToken();
3998
3999 BalancedDelimiterTracker T(*this, tok::l_paren);
4000 if (T.expectAndConsume(diag::err_expected_lparen_after, "__builtin_bit_cast"))
4001 return ExprError();
4002
4003 // Parse the common declaration-specifiers piece.
4004 DeclSpec DS(AttrFactory);
4005 ParseSpecifierQualifierList(DS);
4006
4007 // Parse the abstract-declarator, if present.
4008 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
4009 ParseDeclarator(DeclaratorInfo);
4010
4011 if (ExpectAndConsume(tok::comma)) {
4012 Diag(Tok.getLocation(), diag::err_expected) << tok::comma;
4013 SkipUntil(tok::r_paren, StopAtSemi);
4014 return ExprError();
4015 }
4016
4017 ExprResult Operand = ParseExpression();
4018
4019 if (T.consumeClose())
4020 return ExprError();
4021
4022 if (Operand.isInvalid() || DeclaratorInfo.isInvalidType())
4023 return ExprError();
4024
4025 return Actions.ActOnBuiltinBitCastExpr(KWLoc, DeclaratorInfo, Operand,
4026 T.getCloseLocation());
4027}

/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h

1//===--- Token.h - Token interface ------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Token interface.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LEX_TOKEN_H
14#define LLVM_CLANG_LEX_TOKEN_H
15
16#include "clang/Basic/SourceLocation.h"
17#include "clang/Basic/TokenKinds.h"
18#include "llvm/ADT/StringRef.h"
19#include <cassert>
20
21namespace clang {
22
23class IdentifierInfo;
24
25/// Token - This structure provides full information about a lexed token.
26/// It is not intended to be space efficient, it is intended to return as much
27/// information as possible about each returned token. This is expected to be
28/// compressed into a smaller form if memory footprint is important.
29///
30/// The parser can create a special "annotation token" representing a stream of
31/// tokens that were parsed and semantically resolved, e.g.: "foo::MyClass<int>"
32/// can be represented by a single typename annotation token that carries
33/// information about the SourceRange of the tokens and the type object.
34class Token {
35 /// The location of the token. This is actually a SourceLocation.
36 unsigned Loc;
37
38 // Conceptually these next two fields could be in a union. However, this
39 // causes gcc 4.2 to pessimize LexTokenInternal, a very performance critical
40 // routine. Keeping as separate members with casts until a more beautiful fix
41 // presents itself.
42
43 /// UintData - This holds either the length of the token text, when
44 /// a normal token, or the end of the SourceRange when an annotation
45 /// token.
46 unsigned UintData;
47
48 /// PtrData - This is a union of four different pointer types, which depends
49 /// on what type of token this is:
50 /// Identifiers, keywords, etc:
51 /// This is an IdentifierInfo*, which contains the uniqued identifier
52 /// spelling.
53 /// Literals: isLiteral() returns true.
54 /// This is a pointer to the start of the token in a text buffer, which
55 /// may be dirty (have trigraphs / escaped newlines).
56 /// Annotations (resolved type names, C++ scopes, etc): isAnnotation().
57 /// This is a pointer to sema-specific data for the annotation token.
58 /// Eof:
59 // This is a pointer to a Decl.
60 /// Other:
61 /// This is null.
62 void *PtrData;
63
64 /// Kind - The actual flavor of token this is.
65 tok::TokenKind Kind;
66
67 /// Flags - Bits we track about this token, members of the TokenFlags enum.
68 unsigned short Flags;
69
70public:
71 // Various flags set per token:
72 enum TokenFlags {
73 StartOfLine = 0x01, // At start of line or only after whitespace
74 // (considering the line after macro expansion).
75 LeadingSpace = 0x02, // Whitespace exists before this token (considering
76 // whitespace after macro expansion).
77 DisableExpand = 0x04, // This identifier may never be macro expanded.
78 NeedsCleaning = 0x08, // Contained an escaped newline or trigraph.
79 LeadingEmptyMacro = 0x10, // Empty macro exists before this token.
80 HasUDSuffix = 0x20, // This string or character literal has a ud-suffix.
81 HasUCN = 0x40, // This identifier contains a UCN.
82 IgnoredComma = 0x80, // This comma is not a macro argument separator (MS).
83 StringifiedInMacro = 0x100, // This string or character literal is formed by
84 // macro stringizing or charizing operator.
85 CommaAfterElided = 0x200, // The comma following this token was elided (MS).
86 IsEditorPlaceholder = 0x400, // This identifier is a placeholder.
87 IsReinjected = 0x800, // A phase 4 token that was produced before and
88 // re-added, e.g. via EnterTokenStream. Annotation
89 // tokens are *not* reinjected.
90 };
91
92 tok::TokenKind getKind() const { return Kind; }
93 void setKind(tok::TokenKind K) { Kind = K; }
94
95 /// is/isNot - Predicates to check if this token is a specific kind, as in
96 /// "if (Tok.is(tok::l_brace)) {...}".
97 bool is(tok::TokenKind K) const { return Kind == K; }
6
Assuming 'K' is not equal to field 'Kind'
7
Returning zero, which participates in a condition later
98 bool isNot(tok::TokenKind K) const { return Kind != K; }
99 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
100 return is(K1) || is(K2);
101 }
102 template <typename... Ts>
103 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, Ts... Ks) const {
104 return is(K1) || isOneOf(K2, Ks...);
105 }
106
107 /// Return true if this is a raw identifier (when lexing
108 /// in raw mode) or a non-keyword identifier (when lexing in non-raw mode).
109 bool isAnyIdentifier() const {
110 return tok::isAnyIdentifier(getKind());
111 }
112
113 /// Return true if this is a "literal", like a numeric
114 /// constant, string, etc.
115 bool isLiteral() const {
116 return tok::isLiteral(getKind());
117 }
118
119 /// Return true if this is any of tok::annot_* kind tokens.
120 bool isAnnotation() const {
121 return tok::isAnnotation(getKind());
122 }
123
124 /// Return a source location identifier for the specified
125 /// offset in the current file.
126 SourceLocation getLocation() const {
127 return SourceLocation::getFromRawEncoding(Loc);
128 }
129 unsigned getLength() const {
130 assert(!isAnnotation() && "Annotation tokens have no length field")((!isAnnotation() && "Annotation tokens have no length field"
) ? static_cast<void> (0) : __assert_fail ("!isAnnotation() && \"Annotation tokens have no length field\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 130, __PRETTY_FUNCTION__))
;
131 return UintData;
132 }
133
134 void setLocation(SourceLocation L) { Loc = L.getRawEncoding(); }
135 void setLength(unsigned Len) {
136 assert(!isAnnotation() && "Annotation tokens have no length field")((!isAnnotation() && "Annotation tokens have no length field"
) ? static_cast<void> (0) : __assert_fail ("!isAnnotation() && \"Annotation tokens have no length field\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 136, __PRETTY_FUNCTION__))
;
137 UintData = Len;
138 }
139
140 SourceLocation getAnnotationEndLoc() const {
141 assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token")((isAnnotation() && "Used AnnotEndLocID on non-annotation token"
) ? static_cast<void> (0) : __assert_fail ("isAnnotation() && \"Used AnnotEndLocID on non-annotation token\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 141, __PRETTY_FUNCTION__))
;
142 return SourceLocation::getFromRawEncoding(UintData ? UintData : Loc);
143 }
144 void setAnnotationEndLoc(SourceLocation L) {
145 assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token")((isAnnotation() && "Used AnnotEndLocID on non-annotation token"
) ? static_cast<void> (0) : __assert_fail ("isAnnotation() && \"Used AnnotEndLocID on non-annotation token\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 145, __PRETTY_FUNCTION__))
;
146 UintData = L.getRawEncoding();
147 }
148
149 SourceLocation getLastLoc() const {
150 return isAnnotation() ? getAnnotationEndLoc() : getLocation();
151 }
152
153 SourceLocation getEndLoc() const {
154 return isAnnotation() ? getAnnotationEndLoc()
155 : getLocation().getLocWithOffset(getLength());
156 }
157
158 /// SourceRange of the group of tokens that this annotation token
159 /// represents.
160 SourceRange getAnnotationRange() const {
161 return SourceRange(getLocation(), getAnnotationEndLoc());
162 }
163 void setAnnotationRange(SourceRange R) {
164 setLocation(R.getBegin());
165 setAnnotationEndLoc(R.getEnd());
166 }
167
168 const char *getName() const { return tok::getTokenName(Kind); }
169
170 /// Reset all flags to cleared.
171 void startToken() {
172 Kind = tok::unknown;
173 Flags = 0;
174 PtrData = nullptr;
175 UintData = 0;
176 Loc = SourceLocation().getRawEncoding();
177 }
178
179 IdentifierInfo *getIdentifierInfo() const {
180 assert(isNot(tok::raw_identifier) &&((isNot(tok::raw_identifier) && "getIdentifierInfo() on a tok::raw_identifier token!"
) ? static_cast<void> (0) : __assert_fail ("isNot(tok::raw_identifier) && \"getIdentifierInfo() on a tok::raw_identifier token!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 181, __PRETTY_FUNCTION__))
181 "getIdentifierInfo() on a tok::raw_identifier token!")((isNot(tok::raw_identifier) && "getIdentifierInfo() on a tok::raw_identifier token!"
) ? static_cast<void> (0) : __assert_fail ("isNot(tok::raw_identifier) && \"getIdentifierInfo() on a tok::raw_identifier token!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 181, __PRETTY_FUNCTION__))
;
182 assert(!isAnnotation() &&((!isAnnotation() && "getIdentifierInfo() on an annotation token!"
) ? static_cast<void> (0) : __assert_fail ("!isAnnotation() && \"getIdentifierInfo() on an annotation token!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 183, __PRETTY_FUNCTION__))
183 "getIdentifierInfo() on an annotation token!")((!isAnnotation() && "getIdentifierInfo() on an annotation token!"
) ? static_cast<void> (0) : __assert_fail ("!isAnnotation() && \"getIdentifierInfo() on an annotation token!\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 183, __PRETTY_FUNCTION__))
;
184 if (isLiteral()) return nullptr;
185 if (is(tok::eof)) return nullptr;
186 return (IdentifierInfo*) PtrData;
187 }
188 void setIdentifierInfo(IdentifierInfo *II) {
189 PtrData = (void*) II;
190 }
191
192 const void *getEofData() const {
193 assert(is(tok::eof))((is(tok::eof)) ? static_cast<void> (0) : __assert_fail
("is(tok::eof)", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 193, __PRETTY_FUNCTION__))
;
194 return reinterpret_cast<const void *>(PtrData);
195 }
196 void setEofData(const void *D) {
197 assert(is(tok::eof))((is(tok::eof)) ? static_cast<void> (0) : __assert_fail
("is(tok::eof)", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 197, __PRETTY_FUNCTION__))
;
198 assert(!PtrData)((!PtrData) ? static_cast<void> (0) : __assert_fail ("!PtrData"
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 198, __PRETTY_FUNCTION__))
;
199 PtrData = const_cast<void *>(D);
200 }
201
202 /// getRawIdentifier - For a raw identifier token (i.e., an identifier
203 /// lexed in raw mode), returns a reference to the text substring in the
204 /// buffer if known.
205 StringRef getRawIdentifier() const {
206 assert(is(tok::raw_identifier))((is(tok::raw_identifier)) ? static_cast<void> (0) : __assert_fail
("is(tok::raw_identifier)", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 206, __PRETTY_FUNCTION__))
;
207 return StringRef(reinterpret_cast<const char *>(PtrData), getLength());
208 }
209 void setRawIdentifierData(const char *Ptr) {
210 assert(is(tok::raw_identifier))((is(tok::raw_identifier)) ? static_cast<void> (0) : __assert_fail
("is(tok::raw_identifier)", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 210, __PRETTY_FUNCTION__))
;
211 PtrData = const_cast<char*>(Ptr);
212 }
213
214 /// getLiteralData - For a literal token (numeric constant, string, etc), this
215 /// returns a pointer to the start of it in the text buffer if known, null
216 /// otherwise.
217 const char *getLiteralData() const {
218 assert(isLiteral() && "Cannot get literal data of non-literal")((isLiteral() && "Cannot get literal data of non-literal"
) ? static_cast<void> (0) : __assert_fail ("isLiteral() && \"Cannot get literal data of non-literal\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 218, __PRETTY_FUNCTION__))
;
219 return reinterpret_cast<const char*>(PtrData);
220 }
221 void setLiteralData(const char *Ptr) {
222 assert(isLiteral() && "Cannot set literal data of non-literal")((isLiteral() && "Cannot set literal data of non-literal"
) ? static_cast<void> (0) : __assert_fail ("isLiteral() && \"Cannot set literal data of non-literal\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 222, __PRETTY_FUNCTION__))
;
223 PtrData = const_cast<char*>(Ptr);
224 }
225
226 void *getAnnotationValue() const {
227 assert(isAnnotation() && "Used AnnotVal on non-annotation token")((isAnnotation() && "Used AnnotVal on non-annotation token"
) ? static_cast<void> (0) : __assert_fail ("isAnnotation() && \"Used AnnotVal on non-annotation token\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 227, __PRETTY_FUNCTION__))
;
228 return PtrData;
229 }
230 void setAnnotationValue(void *val) {
231 assert(isAnnotation() && "Used AnnotVal on non-annotation token")((isAnnotation() && "Used AnnotVal on non-annotation token"
) ? static_cast<void> (0) : __assert_fail ("isAnnotation() && \"Used AnnotVal on non-annotation token\""
, "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/clang/include/clang/Lex/Token.h"
, 231, __PRETTY_FUNCTION__))
;
232 PtrData = val;
233 }
234
235 /// Set the specified flag.
236 void setFlag(TokenFlags Flag) {
237 Flags |= Flag;
238 }
239
240 /// Get the specified flag.
241 bool getFlag(TokenFlags Flag) const {
242 return (Flags & Flag) != 0;
243 }
244
245 /// Unset the specified flag.
246 void clearFlag(TokenFlags Flag) {
247 Flags &= ~Flag;
248 }
249
250 /// Return the internal represtation of the flags.
251 ///
252 /// This is only intended for low-level operations such as writing tokens to
253 /// disk.
254 unsigned getFlags() const {
255 return Flags;
256 }
257
258 /// Set a flag to either true or false.
259 void setFlagValue(TokenFlags Flag, bool Val) {
260 if (Val)
261 setFlag(Flag);
262 else
263 clearFlag(Flag);
264 }
265
266 /// isAtStartOfLine - Return true if this token is at the start of a line.
267 ///
268 bool isAtStartOfLine() const { return getFlag(StartOfLine); }
269
270 /// Return true if this token has whitespace before it.
271 ///
272 bool hasLeadingSpace() const { return getFlag(LeadingSpace); }
273
274 /// Return true if this identifier token should never
275 /// be expanded in the future, due to C99 6.10.3.4p2.
276 bool isExpandDisabled() const { return getFlag(DisableExpand); }
277
278 /// Return true if we have an ObjC keyword identifier.
279 bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const;
280
281 /// Return the ObjC keyword kind.
282 tok::ObjCKeywordKind getObjCKeywordID() const;
283
284 /// Return true if this token has trigraphs or escaped newlines in it.
285 bool needsCleaning() const { return getFlag(NeedsCleaning); }
286
287 /// Return true if this token has an empty macro before it.
288 ///
289 bool hasLeadingEmptyMacro() const { return getFlag(LeadingEmptyMacro); }
290
291 /// Return true if this token is a string or character literal which
292 /// has a ud-suffix.
293 bool hasUDSuffix() const { return getFlag(HasUDSuffix); }
294
295 /// Returns true if this token contains a universal character name.
296 bool hasUCN() const { return getFlag(HasUCN); }
297
298 /// Returns true if this token is formed by macro by stringizing or charizing
299 /// operator.
300 bool stringifiedInMacro() const { return getFlag(StringifiedInMacro); }
301
302 /// Returns true if the comma after this token was elided.
303 bool commaAfterElided() const { return getFlag(CommaAfterElided); }
304
305 /// Returns true if this token is an editor placeholder.
306 ///
307 /// Editor placeholders are produced by the code-completion engine and are
308 /// represented as characters between '<#' and '#>' in the source code. The
309 /// lexer uses identifier tokens to represent placeholders.
310 bool isEditorPlaceholder() const { return getFlag(IsEditorPlaceholder); }
311};
312
313/// Information about the conditional stack (\#if directives)
314/// currently active.
315struct PPConditionalInfo {
316 /// Location where the conditional started.
317 SourceLocation IfLoc;
318
319 /// True if this was contained in a skipping directive, e.g.,
320 /// in a "\#if 0" block.
321 bool WasSkipping;
322
323 /// True if we have emitted tokens already, and now we're in
324 /// an \#else block or something. Only useful in Skipping blocks.
325 bool FoundNonSkip;
326
327 /// True if we've seen a \#else in this block. If so,
328 /// \#elif/\#else directives are not allowed.
329 bool FoundElse;
330};
331
332} // end namespace clang
333
334#endif // LLVM_CLANG_LEX_TOKEN_H