Bug Summary

File:clang/lib/Parse/ParseExprCXX.cpp
Warning:line 2046, 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 -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/build-llvm/tools/clang/lib/Parse -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Parse -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/include -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/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-12/lib/clang/12.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-12~++20210124100612+2afaf072f5c1/build-llvm/tools/clang/lib/Parse -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1=. -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 -o /tmp/scan-build-2021-01-24-223304-31662-1 -x c++ /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp

/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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 TypeResult TrailingReturnType;
1306 SourceLocation TrailingReturnTypeLoc;
1307 if (Tok.is(tok::l_paren)) {
1308 ParseScope PrototypeScope(this,
1309 Scope::FunctionPrototypeScope |
1310 Scope::FunctionDeclarationScope |
1311 Scope::DeclScope);
1312
1313 BalancedDelimiterTracker T(*this, tok::l_paren);
1314 T.consumeOpen();
1315 SourceLocation LParenLoc = T.getOpenLocation();
1316
1317 // Parse parameter-declaration-clause.
1318 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1319 SourceLocation EllipsisLoc;
1320
1321 if (Tok.isNot(tok::r_paren)) {
1322 Actions.RecordParsingTemplateParameterDepth(
1323 CurTemplateDepthTracker.getOriginalDepth());
1324
1325 ParseParameterDeclarationClause(D.getContext(), Attr, ParamInfo,
1326 EllipsisLoc);
1327 // For a generic lambda, each 'auto' within the parameter declaration
1328 // clause creates a template type parameter, so increment the depth.
1329 // If we've parsed any explicit template parameters, then the depth will
1330 // have already been incremented. So we make sure that at most a single
1331 // depth level is added.
1332 if (Actions.getCurGenericLambda())
1333 CurTemplateDepthTracker.setAddedDepth(1);
1334 }
1335
1336 T.consumeClose();
1337 SourceLocation RParenLoc = T.getCloseLocation();
1338 SourceLocation DeclEndLoc = RParenLoc;
1339
1340 // GNU-style attributes must be parsed before the mutable specifier to be
1341 // compatible with GCC.
1342 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1343
1344 // MSVC-style attributes must be parsed before the mutable specifier to be
1345 // compatible with MSVC.
1346 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
1347
1348 // Parse mutable-opt and/or constexpr-opt or consteval-opt, and update the
1349 // DeclEndLoc.
1350 SourceLocation MutableLoc;
1351 SourceLocation ConstexprLoc;
1352 SourceLocation ConstevalLoc;
1353 tryConsumeLambdaSpecifierToken(*this, MutableLoc, ConstexprLoc,
1354 ConstevalLoc, DeclEndLoc);
1355
1356 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1357 addConstevalToLambdaDeclSpecifier(*this, ConstevalLoc, DS);
1358 // Parse exception-specification[opt].
1359 ExceptionSpecificationType ESpecType = EST_None;
1360 SourceRange ESpecRange;
1361 SmallVector<ParsedType, 2> DynamicExceptions;
1362 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1363 ExprResult NoexceptExpr;
1364 CachedTokens *ExceptionSpecTokens;
1365 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1366 ESpecRange,
1367 DynamicExceptions,
1368 DynamicExceptionRanges,
1369 NoexceptExpr,
1370 ExceptionSpecTokens);
1371
1372 if (ESpecType != EST_None)
1373 DeclEndLoc = ESpecRange.getEnd();
1374
1375 // Parse attribute-specifier[opt].
1376 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1377
1378 // Parse OpenCL addr space attribute.
1379 if (Tok.isOneOf(tok::kw___private, tok::kw___global, tok::kw___local,
1380 tok::kw___constant, tok::kw___generic)) {
1381 ParseOpenCLQualifiers(DS.getAttributes());
1382 ConsumeToken();
1383 }
1384
1385 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1386
1387 // Parse trailing-return-type[opt].
1388 if (Tok.is(tok::arrow)) {
1389 FunLocalRangeEnd = Tok.getLocation();
1390 SourceRange Range;
1391 TrailingReturnType =
1392 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1393 TrailingReturnTypeLoc = Range.getBegin();
1394 if (Range.getEnd().isValid())
1395 DeclEndLoc = Range.getEnd();
1396 }
1397
1398 SourceLocation NoLoc;
1399 D.AddTypeInfo(DeclaratorChunk::getFunction(
1400 /*HasProto=*/true,
1401 /*IsAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1402 ParamInfo.size(), EllipsisLoc, RParenLoc,
1403 /*RefQualifierIsLvalueRef=*/true,
1404 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType,
1405 ESpecRange, DynamicExceptions.data(),
1406 DynamicExceptionRanges.data(), DynamicExceptions.size(),
1407 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1408 /*ExceptionSpecTokens*/ nullptr,
1409 /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
1410 TrailingReturnType, TrailingReturnTypeLoc, &DS),
1411 std::move(Attr), DeclEndLoc);
1412
1413 // Parse requires-clause[opt].
1414 if (Tok.is(tok::kw_requires))
1415 ParseTrailingRequiresClause(D);
1416
1417 PrototypeScope.Exit();
1418
1419 WarnIfHasCUDATargetAttr();
1420 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1421 tok::kw_constexpr, tok::kw_consteval,
1422 tok::kw___private, tok::kw___global, tok::kw___local,
1423 tok::kw___constant, tok::kw___generic,
1424 tok::kw_requires) ||
1425 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1426 // It's common to forget that one needs '()' before 'mutable', an attribute
1427 // specifier, the result type, or the requires clause. Deal with this.
1428 unsigned TokKind = 0;
1429 switch (Tok.getKind()) {
1430 case tok::kw_mutable: TokKind = 0; break;
1431 case tok::arrow: TokKind = 1; break;
1432 case tok::kw___attribute:
1433 case tok::kw___private:
1434 case tok::kw___global:
1435 case tok::kw___local:
1436 case tok::kw___constant:
1437 case tok::kw___generic:
1438 case tok::l_square: TokKind = 2; break;
1439 case tok::kw_constexpr: TokKind = 3; break;
1440 case tok::kw_consteval: TokKind = 4; break;
1441 case tok::kw_requires: TokKind = 5; break;
1442 default: llvm_unreachable("Unknown token kind")::llvm::llvm_unreachable_internal("Unknown token kind", "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1442)
;
1443 }
1444
1445 Diag(Tok, diag::err_lambda_missing_parens)
1446 << TokKind
1447 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1448 SourceLocation DeclEndLoc = DeclLoc;
1449
1450 // GNU-style attributes must be parsed before the mutable specifier to be
1451 // compatible with GCC.
1452 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1453
1454 // Parse 'mutable', if it's there.
1455 SourceLocation MutableLoc;
1456 if (Tok.is(tok::kw_mutable)) {
1457 MutableLoc = ConsumeToken();
1458 DeclEndLoc = MutableLoc;
1459 }
1460
1461 // Parse attribute-specifier[opt].
1462 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1463
1464 // Parse the return type, if there is one.
1465 if (Tok.is(tok::arrow)) {
1466 SourceRange Range;
1467 TrailingReturnType =
1468 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1469 if (Range.getEnd().isValid())
1470 DeclEndLoc = Range.getEnd();
1471 }
1472
1473 SourceLocation NoLoc;
1474 D.AddTypeInfo(DeclaratorChunk::getFunction(
1475 /*HasProto=*/true,
1476 /*IsAmbiguous=*/false,
1477 /*LParenLoc=*/NoLoc,
1478 /*Params=*/nullptr,
1479 /*NumParams=*/0,
1480 /*EllipsisLoc=*/NoLoc,
1481 /*RParenLoc=*/NoLoc,
1482 /*RefQualifierIsLvalueRef=*/true,
1483 /*RefQualifierLoc=*/NoLoc, MutableLoc, EST_None,
1484 /*ESpecRange=*/SourceRange(),
1485 /*Exceptions=*/nullptr,
1486 /*ExceptionRanges=*/nullptr,
1487 /*NumExceptions=*/0,
1488 /*NoexceptExpr=*/nullptr,
1489 /*ExceptionSpecTokens=*/nullptr,
1490 /*DeclsInPrototype=*/None, DeclLoc, DeclEndLoc, D,
1491 TrailingReturnType),
1492 std::move(Attr), DeclEndLoc);
1493
1494 // Parse the requires-clause, if present.
1495 if (Tok.is(tok::kw_requires))
1496 ParseTrailingRequiresClause(D);
1497
1498 WarnIfHasCUDATargetAttr();
1499 }
1500
1501 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1502 // it.
1503 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1504 Scope::CompoundStmtScope;
1505 ParseScope BodyScope(this, ScopeFlags);
1506
1507 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1508
1509 // Parse compound-statement.
1510 if (!Tok.is(tok::l_brace)) {
1511 Diag(Tok, diag::err_expected_lambda_body);
1512 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1513 return ExprError();
1514 }
1515
1516 StmtResult Stmt(ParseCompoundStatementBody());
1517 BodyScope.Exit();
1518 TemplateParamScope.Exit();
1519
1520 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1521 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1522
1523 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1524 return ExprError();
1525}
1526
1527/// ParseCXXCasts - This handles the various ways to cast expressions to another
1528/// type.
1529///
1530/// postfix-expression: [C++ 5.2p1]
1531/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1532/// 'static_cast' '<' type-name '>' '(' expression ')'
1533/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1534/// 'const_cast' '<' type-name '>' '(' expression ')'
1535///
1536/// C++ for OpenCL s2.3.1 adds:
1537/// 'addrspace_cast' '<' type-name '>' '(' expression ')'
1538ExprResult Parser::ParseCXXCasts() {
1539 tok::TokenKind Kind = Tok.getKind();
1540 const char *CastName = nullptr; // For error messages
1541
1542 switch (Kind) {
1543 default: llvm_unreachable("Unknown C++ cast!")::llvm::llvm_unreachable_internal("Unknown C++ cast!", "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1543)
;
1544 case tok::kw_addrspace_cast: CastName = "addrspace_cast"; break;
1545 case tok::kw_const_cast: CastName = "const_cast"; break;
1546 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1547 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1548 case tok::kw_static_cast: CastName = "static_cast"; break;
1549 }
1550
1551 SourceLocation OpLoc = ConsumeToken();
1552 SourceLocation LAngleBracketLoc = Tok.getLocation();
1553
1554 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1555 // diagnose error, suggest fix, and recover parsing.
1556 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1557 Token Next = NextToken();
1558 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1559 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1560 }
1561
1562 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1563 return ExprError();
1564
1565 // Parse the common declaration-specifiers piece.
1566 DeclSpec DS(AttrFactory);
1567 ParseSpecifierQualifierList(DS);
1568
1569 // Parse the abstract-declarator, if present.
1570 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
1571 ParseDeclarator(DeclaratorInfo);
1572
1573 SourceLocation RAngleBracketLoc = Tok.getLocation();
1574
1575 if (ExpectAndConsume(tok::greater))
1576 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1577
1578 BalancedDelimiterTracker T(*this, tok::l_paren);
1579
1580 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1581 return ExprError();
1582
1583 ExprResult Result = ParseExpression();
1584
1585 // Match the ')'.
1586 T.consumeClose();
1587
1588 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1589 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1590 LAngleBracketLoc, DeclaratorInfo,
1591 RAngleBracketLoc,
1592 T.getOpenLocation(), Result.get(),
1593 T.getCloseLocation());
1594
1595 return Result;
1596}
1597
1598/// ParseCXXTypeid - This handles the C++ typeid expression.
1599///
1600/// postfix-expression: [C++ 5.2p1]
1601/// 'typeid' '(' expression ')'
1602/// 'typeid' '(' type-id ')'
1603///
1604ExprResult Parser::ParseCXXTypeid() {
1605 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1605, __PRETTY_FUNCTION__))
;
1606
1607 SourceLocation OpLoc = ConsumeToken();
1608 SourceLocation LParenLoc, RParenLoc;
1609 BalancedDelimiterTracker T(*this, tok::l_paren);
1610
1611 // typeid expressions are always parenthesized.
1612 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1613 return ExprError();
1614 LParenLoc = T.getOpenLocation();
1615
1616 ExprResult Result;
1617
1618 // C++0x [expr.typeid]p3:
1619 // When typeid is applied to an expression other than an lvalue of a
1620 // polymorphic class type [...] The expression is an unevaluated
1621 // operand (Clause 5).
1622 //
1623 // Note that we can't tell whether the expression is an lvalue of a
1624 // polymorphic class type until after we've parsed the expression; we
1625 // speculatively assume the subexpression is unevaluated, and fix it up
1626 // later.
1627 //
1628 // We enter the unevaluated context before trying to determine whether we
1629 // have a type-id, because the tentative parse logic will try to resolve
1630 // names, and must treat them as unevaluated.
1631 EnterExpressionEvaluationContext Unevaluated(
1632 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1633 Sema::ReuseLambdaContextDecl);
1634
1635 if (isTypeIdInParens()) {
1636 TypeResult Ty = ParseTypeName();
1637
1638 // Match the ')'.
1639 T.consumeClose();
1640 RParenLoc = T.getCloseLocation();
1641 if (Ty.isInvalid() || RParenLoc.isInvalid())
1642 return ExprError();
1643
1644 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1645 Ty.get().getAsOpaquePtr(), RParenLoc);
1646 } else {
1647 Result = ParseExpression();
1648
1649 // Match the ')'.
1650 if (Result.isInvalid())
1651 SkipUntil(tok::r_paren, StopAtSemi);
1652 else {
1653 T.consumeClose();
1654 RParenLoc = T.getCloseLocation();
1655 if (RParenLoc.isInvalid())
1656 return ExprError();
1657
1658 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1659 Result.get(), RParenLoc);
1660 }
1661 }
1662
1663 return Result;
1664}
1665
1666/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1667///
1668/// '__uuidof' '(' expression ')'
1669/// '__uuidof' '(' type-id ')'
1670///
1671ExprResult Parser::ParseCXXUuidof() {
1672 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1672, __PRETTY_FUNCTION__))
;
1673
1674 SourceLocation OpLoc = ConsumeToken();
1675 BalancedDelimiterTracker T(*this, tok::l_paren);
1676
1677 // __uuidof expressions are always parenthesized.
1678 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1679 return ExprError();
1680
1681 ExprResult Result;
1682
1683 if (isTypeIdInParens()) {
1684 TypeResult Ty = ParseTypeName();
1685
1686 // Match the ')'.
1687 T.consumeClose();
1688
1689 if (Ty.isInvalid())
1690 return ExprError();
1691
1692 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1693 Ty.get().getAsOpaquePtr(),
1694 T.getCloseLocation());
1695 } else {
1696 EnterExpressionEvaluationContext Unevaluated(
1697 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1698 Result = ParseExpression();
1699
1700 // Match the ')'.
1701 if (Result.isInvalid())
1702 SkipUntil(tok::r_paren, StopAtSemi);
1703 else {
1704 T.consumeClose();
1705
1706 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1707 /*isType=*/false,
1708 Result.get(), T.getCloseLocation());
1709 }
1710 }
1711
1712 return Result;
1713}
1714
1715/// Parse a C++ pseudo-destructor expression after the base,
1716/// . or -> operator, and nested-name-specifier have already been
1717/// parsed. We're handling this fragment of the grammar:
1718///
1719/// postfix-expression: [C++2a expr.post]
1720/// postfix-expression . template[opt] id-expression
1721/// postfix-expression -> template[opt] id-expression
1722///
1723/// id-expression:
1724/// qualified-id
1725/// unqualified-id
1726///
1727/// qualified-id:
1728/// nested-name-specifier template[opt] unqualified-id
1729///
1730/// nested-name-specifier:
1731/// type-name ::
1732/// decltype-specifier :: FIXME: not implemented, but probably only
1733/// allowed in C++ grammar by accident
1734/// nested-name-specifier identifier ::
1735/// nested-name-specifier template[opt] simple-template-id ::
1736/// [...]
1737///
1738/// unqualified-id:
1739/// ~ type-name
1740/// ~ decltype-specifier
1741/// [...]
1742///
1743/// ... where the all but the last component of the nested-name-specifier
1744/// has already been parsed, and the base expression is not of a non-dependent
1745/// class type.
1746ExprResult
1747Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1748 tok::TokenKind OpKind,
1749 CXXScopeSpec &SS,
1750 ParsedType ObjectType) {
1751 // If the last component of the (optional) nested-name-specifier is
1752 // template[opt] simple-template-id, it has already been annotated.
1753 UnqualifiedId FirstTypeName;
1754 SourceLocation CCLoc;
1755 if (Tok.is(tok::identifier)) {
1756 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1757 ConsumeToken();
1758 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1758, __PRETTY_FUNCTION__))
;
1759 CCLoc = ConsumeToken();
1760 } else if (Tok.is(tok::annot_template_id)) {
1761 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1762 // FIXME: Carry on and build an AST representation for tooling.
1763 if (TemplateId->isInvalid())
1764 return ExprError();
1765 FirstTypeName.setTemplateId(TemplateId);
1766 ConsumeAnnotationToken();
1767 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1767, __PRETTY_FUNCTION__))
;
1768 CCLoc = ConsumeToken();
1769 } else {
1770 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1770, __PRETTY_FUNCTION__))
;
1771 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1772 }
1773
1774 // Parse the tilde.
1775 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1775, __PRETTY_FUNCTION__))
;
1776 SourceLocation TildeLoc = ConsumeToken();
1777
1778 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid()) {
1779 DeclSpec DS(AttrFactory);
1780 ParseDecltypeSpecifier(DS);
1781 if (DS.getTypeSpecType() == TST_error)
1782 return ExprError();
1783 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1784 TildeLoc, DS);
1785 }
1786
1787 if (!Tok.is(tok::identifier)) {
1788 Diag(Tok, diag::err_destructor_tilde_identifier);
1789 return ExprError();
1790 }
1791
1792 // Parse the second type.
1793 UnqualifiedId SecondTypeName;
1794 IdentifierInfo *Name = Tok.getIdentifierInfo();
1795 SourceLocation NameLoc = ConsumeToken();
1796 SecondTypeName.setIdentifier(Name, NameLoc);
1797
1798 // If there is a '<', the second type name is a template-id. Parse
1799 // it as such.
1800 //
1801 // FIXME: This is not a context in which a '<' is assumed to start a template
1802 // argument list. This affects examples such as
1803 // void f(auto *p) { p->~X<int>(); }
1804 // ... but there's no ambiguity, and nowhere to write 'template' in such an
1805 // example, so we accept it anyway.
1806 if (Tok.is(tok::less) &&
1807 ParseUnqualifiedIdTemplateId(
1808 SS, ObjectType, Base && Base->containsErrors(), SourceLocation(),
1809 Name, NameLoc, false, SecondTypeName,
1810 /*AssumeTemplateId=*/true))
1811 return ExprError();
1812
1813 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1814 SS, FirstTypeName, CCLoc, TildeLoc,
1815 SecondTypeName);
1816}
1817
1818/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1819///
1820/// boolean-literal: [C++ 2.13.5]
1821/// 'true'
1822/// 'false'
1823ExprResult Parser::ParseCXXBoolLiteral() {
1824 tok::TokenKind Kind = Tok.getKind();
1825 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1826}
1827
1828/// ParseThrowExpression - This handles the C++ throw expression.
1829///
1830/// throw-expression: [C++ 15]
1831/// 'throw' assignment-expression[opt]
1832ExprResult Parser::ParseThrowExpression() {
1833 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1833, __PRETTY_FUNCTION__))
;
1834 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1835
1836 // If the current token isn't the start of an assignment-expression,
1837 // then the expression is not present. This handles things like:
1838 // "C ? throw : (void)42", which is crazy but legal.
1839 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1840 case tok::semi:
1841 case tok::r_paren:
1842 case tok::r_square:
1843 case tok::r_brace:
1844 case tok::colon:
1845 case tok::comma:
1846 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1847
1848 default:
1849 ExprResult Expr(ParseAssignmentExpression());
1850 if (Expr.isInvalid()) return Expr;
1851 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1852 }
1853}
1854
1855/// Parse the C++ Coroutines co_yield expression.
1856///
1857/// co_yield-expression:
1858/// 'co_yield' assignment-expression[opt]
1859ExprResult Parser::ParseCoyieldExpression() {
1860 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1860, __PRETTY_FUNCTION__))
;
1861
1862 SourceLocation Loc = ConsumeToken();
1863 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1864 : ParseAssignmentExpression();
1865 if (!Expr.isInvalid())
1866 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1867 return Expr;
1868}
1869
1870/// ParseCXXThis - This handles the C++ 'this' pointer.
1871///
1872/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1873/// a non-lvalue expression whose value is the address of the object for which
1874/// the function is called.
1875ExprResult Parser::ParseCXXThis() {
1876 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1876, __PRETTY_FUNCTION__))
;
1877 SourceLocation ThisLoc = ConsumeToken();
1878 return Actions.ActOnCXXThis(ThisLoc);
1879}
1880
1881/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1882/// Can be interpreted either as function-style casting ("int(x)")
1883/// or class type construction ("ClassType(x,y,z)")
1884/// or creation of a value-initialized type ("int()").
1885/// See [C++ 5.2.3].
1886///
1887/// postfix-expression: [C++ 5.2p1]
1888/// simple-type-specifier '(' expression-list[opt] ')'
1889/// [C++0x] simple-type-specifier braced-init-list
1890/// typename-specifier '(' expression-list[opt] ')'
1891/// [C++0x] typename-specifier braced-init-list
1892///
1893/// In C++1z onwards, the type specifier can also be a template-name.
1894ExprResult
1895Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1896 Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCast);
1897 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1898
1899 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1901, __PRETTY_FUNCTION__))
1900 (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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1901, __PRETTY_FUNCTION__))
1901 && "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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1901, __PRETTY_FUNCTION__))
;
1902
1903 if (Tok.is(tok::l_brace)) {
1904 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1905 ExprResult Init = ParseBraceInitializer();
1906 if (Init.isInvalid())
1907 return Init;
1908 Expr *InitList = Init.get();
1909 return Actions.ActOnCXXTypeConstructExpr(
1910 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
1911 InitList->getEndLoc(), /*ListInitialization=*/true);
1912 } else {
1913 BalancedDelimiterTracker T(*this, tok::l_paren);
1914 T.consumeOpen();
1915
1916 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1917
1918 ExprVector Exprs;
1919 CommaLocsTy CommaLocs;
1920
1921 auto RunSignatureHelp = [&]() {
1922 QualType PreferredType;
1923 if (TypeRep)
1924 PreferredType = Actions.ProduceConstructorSignatureHelp(
1925 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
1926 DS.getEndLoc(), Exprs, T.getOpenLocation());
1927 CalledSignatureHelp = true;
1928 return PreferredType;
1929 };
1930
1931 if (Tok.isNot(tok::r_paren)) {
1932 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1933 PreferredType.enterFunctionArgument(Tok.getLocation(),
1934 RunSignatureHelp);
1935 })) {
1936 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1937 RunSignatureHelp();
1938 SkipUntil(tok::r_paren, StopAtSemi);
1939 return ExprError();
1940 }
1941 }
1942
1943 // Match the ')'.
1944 T.consumeClose();
1945
1946 // TypeRep could be null, if it references an invalid typedef.
1947 if (!TypeRep)
1948 return ExprError();
1949
1950 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1951, __PRETTY_FUNCTION__))
1951 "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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 1951, __PRETTY_FUNCTION__))
;
1952 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1953 Exprs, T.getCloseLocation(),
1954 /*ListInitialization=*/false);
1955 }
1956}
1957
1958/// ParseCXXCondition - if/switch/while condition expression.
1959///
1960/// condition:
1961/// expression
1962/// type-specifier-seq declarator '=' assignment-expression
1963/// [C++11] type-specifier-seq declarator '=' initializer-clause
1964/// [C++11] type-specifier-seq declarator braced-init-list
1965/// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1966/// brace-or-equal-initializer
1967/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1968/// '=' assignment-expression
1969///
1970/// In C++1z, a condition may in some contexts be preceded by an
1971/// optional init-statement. This function will parse that too.
1972///
1973/// \param InitStmt If non-null, an init-statement is permitted, and if present
1974/// will be parsed and stored here.
1975///
1976/// \param Loc The location of the start of the statement that requires this
1977/// condition, e.g., the "for" in a for loop.
1978///
1979/// \param FRI If non-null, a for range declaration is permitted, and if
1980/// present will be parsed and stored here, and a null result will be returned.
1981///
1982/// \returns The parsed condition.
1983Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1984 SourceLocation Loc,
1985 Sema::ConditionKind CK,
1986 ForRangeInfo *FRI) {
1987 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1988 PreferredType.enterCondition(Actions, Tok.getLocation());
1989
1990 if (Tok.is(tok::code_completion)) {
1
Taking false branch
5
Calling 'Token::is'
8
Returning from 'Token::is'
9
Taking false branch
1991 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1992 cutOffParsing();
1993 return Sema::ConditionError();
1994 }
1995
1996 ParsedAttributesWithRange attrs(AttrFactory);
1997 MaybeParseCXX11Attributes(attrs);
1998
1999 const auto WarnOnInit = [this, &CK] {
2000 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
2001 ? diag::warn_cxx14_compat_init_statement
2002 : diag::ext_init_statement)
2003 << (CK == Sema::ConditionKind::Switch);
2004 };
2005
2006 // Determine what kind of thing we have.
2007 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
2
Control jumps to 'case InitStmtDecl:' at line 2041
10
Control jumps to 'case InitStmtDecl:' at line 2041
2008 case ConditionOrInitStatement::Expression: {
2009 ProhibitAttributes(attrs);
2010
2011 // We can have an empty expression here.
2012 // if (; true);
2013 if (InitStmt && Tok.is(tok::semi)) {
2014 WarnOnInit();
2015 SourceLocation SemiLoc = Tok.getLocation();
2016 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
2017 Diag(SemiLoc, diag::warn_empty_init_statement)
2018 << (CK == Sema::ConditionKind::Switch)
2019 << FixItHint::CreateRemoval(SemiLoc);
2020 }
2021 ConsumeToken();
2022 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
2023 return ParseCXXCondition(nullptr, Loc, CK);
2024 }
2025
2026 // Parse the expression.
2027 ExprResult Expr = ParseExpression(); // expression
2028 if (Expr.isInvalid())
2029 return Sema::ConditionError();
2030
2031 if (InitStmt && Tok.is(tok::semi)) {
2032 WarnOnInit();
2033 *InitStmt = Actions.ActOnExprStmt(Expr.get());
2034 ConsumeToken();
2035 return ParseCXXCondition(nullptr, Loc, CK);
2036 }
2037
2038 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
2039 }
2040
2041 case ConditionOrInitStatement::InitStmtDecl: {
2042 WarnOnInit();
2043 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2044 DeclGroupPtrTy DG = ParseSimpleDeclaration(
2045 DeclaratorContext::SelectionInit, DeclEnd, attrs, /*RequireSemi=*/true);
2046 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
11
Called C++ object pointer is null
2047 return ParseCXXCondition(nullptr, Loc, CK);
3
Passing null pointer value via 1st parameter 'InitStmt'
4
Calling 'Parser::ParseCXXCondition'
2048 }
2049
2050 case ConditionOrInitStatement::ForRangeDecl: {
2051 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 2051, __PRETTY_FUNCTION__))
;
2052 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2053 DeclGroupPtrTy DG = ParseSimpleDeclaration(DeclaratorContext::ForInit,
2054 DeclEnd, attrs, false, FRI);
2055 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
2056 return Sema::ConditionResult();
2057 }
2058
2059 case ConditionOrInitStatement::ConditionDecl:
2060 case ConditionOrInitStatement::Error:
2061 break;
2062 }
2063
2064 // type-specifier-seq
2065 DeclSpec DS(AttrFactory);
2066 DS.takeAttributesFrom(attrs);
2067 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
2068
2069 // declarator
2070 Declarator DeclaratorInfo(DS, DeclaratorContext::Condition);
2071 ParseDeclarator(DeclaratorInfo);
2072
2073 // simple-asm-expr[opt]
2074 if (Tok.is(tok::kw_asm)) {
2075 SourceLocation Loc;
2076 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2077 if (AsmLabel.isInvalid()) {
2078 SkipUntil(tok::semi, StopAtSemi);
2079 return Sema::ConditionError();
2080 }
2081 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2082 DeclaratorInfo.SetRangeEnd(Loc);
2083 }
2084
2085 // If attributes are present, parse them.
2086 MaybeParseGNUAttributes(DeclaratorInfo);
2087
2088 // Type-check the declaration itself.
2089 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
2090 DeclaratorInfo);
2091 if (Dcl.isInvalid())
2092 return Sema::ConditionError();
2093 Decl *DeclOut = Dcl.get();
2094
2095 // '=' assignment-expression
2096 // If a '==' or '+=' is found, suggest a fixit to '='.
2097 bool CopyInitialization = isTokenEqualOrEqualTypo();
2098 if (CopyInitialization)
2099 ConsumeToken();
2100
2101 ExprResult InitExpr = ExprError();
2102 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2103 Diag(Tok.getLocation(),
2104 diag::warn_cxx98_compat_generalized_initializer_lists);
2105 InitExpr = ParseBraceInitializer();
2106 } else if (CopyInitialization) {
2107 PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
2108 InitExpr = ParseAssignmentExpression();
2109 } else if (Tok.is(tok::l_paren)) {
2110 // This was probably an attempt to initialize the variable.
2111 SourceLocation LParen = ConsumeParen(), RParen = LParen;
2112 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
2113 RParen = ConsumeParen();
2114 Diag(DeclOut->getLocation(),
2115 diag::err_expected_init_in_condition_lparen)
2116 << SourceRange(LParen, RParen);
2117 } else {
2118 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
2119 }
2120
2121 if (!InitExpr.isInvalid())
2122 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
2123 else
2124 Actions.ActOnInitializerError(DeclOut);
2125
2126 Actions.FinalizeDeclaration(DeclOut);
2127 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
2128}
2129
2130/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
2131/// This should only be called when the current token is known to be part of
2132/// simple-type-specifier.
2133///
2134/// simple-type-specifier:
2135/// '::'[opt] nested-name-specifier[opt] type-name
2136/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
2137/// char
2138/// wchar_t
2139/// bool
2140/// short
2141/// int
2142/// long
2143/// signed
2144/// unsigned
2145/// float
2146/// double
2147/// void
2148/// [GNU] typeof-specifier
2149/// [C++0x] auto [TODO]
2150///
2151/// type-name:
2152/// class-name
2153/// enum-name
2154/// typedef-name
2155///
2156void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
2157 DS.SetRangeStart(Tok.getLocation());
2158 const char *PrevSpec;
2159 unsigned DiagID;
2160 SourceLocation Loc = Tok.getLocation();
2161 const clang::PrintingPolicy &Policy =
2162 Actions.getASTContext().getPrintingPolicy();
2163
2164 switch (Tok.getKind()) {
2165 case tok::identifier: // foo::bar
2166 case tok::coloncolon: // ::foo::bar
2167 llvm_unreachable("Annotation token should already be formed!")::llvm::llvm_unreachable_internal("Annotation token should already be formed!"
, "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 2167)
;
2168 default:
2169 llvm_unreachable("Not a simple-type-specifier token!")::llvm::llvm_unreachable_internal("Not a simple-type-specifier token!"
, "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 2169)
;
2170
2171 // type-name
2172 case tok::annot_typename: {
2173 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
2174 getTypeAnnotation(Tok), Policy);
2175 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2176 ConsumeAnnotationToken();
2177
2178 DS.Finish(Actions, Policy);
2179 return;
2180 }
2181
2182 case tok::kw__ExtInt: {
2183 ExprResult ER = ParseExtIntegerArgument();
2184 if (ER.isInvalid())
2185 DS.SetTypeSpecError();
2186 else
2187 DS.SetExtIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
2188
2189 // Do this here because we have already consumed the close paren.
2190 DS.SetRangeEnd(PrevTokLocation);
2191 DS.Finish(Actions, Policy);
2192 return;
2193 }
2194
2195 // builtin types
2196 case tok::kw_short:
2197 DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec, DiagID,
2198 Policy);
2199 break;
2200 case tok::kw_long:
2201 DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec, DiagID,
2202 Policy);
2203 break;
2204 case tok::kw___int64:
2205 DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc, PrevSpec, DiagID,
2206 Policy);
2207 break;
2208 case tok::kw_signed:
2209 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
2210 break;
2211 case tok::kw_unsigned:
2212 DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec, DiagID);
2213 break;
2214 case tok::kw_void:
2215 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
2216 break;
2217 case tok::kw_char:
2218 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
2219 break;
2220 case tok::kw_int:
2221 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
2222 break;
2223 case tok::kw___int128:
2224 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
2225 break;
2226 case tok::kw___bf16:
2227 DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec, DiagID, Policy);
2228 break;
2229 case tok::kw_half:
2230 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
2231 break;
2232 case tok::kw_float:
2233 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
2234 break;
2235 case tok::kw_double:
2236 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
2237 break;
2238 case tok::kw__Float16:
2239 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
2240 break;
2241 case tok::kw___float128:
2242 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
2243 break;
2244 case tok::kw_wchar_t:
2245 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
2246 break;
2247 case tok::kw_char8_t:
2248 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
2249 break;
2250 case tok::kw_char16_t:
2251 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
2252 break;
2253 case tok::kw_char32_t:
2254 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
2255 break;
2256 case tok::kw_bool:
2257 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
2258 break;
2259#define GENERIC_IMAGE_TYPE(ImgType, Id) \
2260 case tok::kw_##ImgType##_t: \
2261 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
2262 Policy); \
2263 break;
2264#include "clang/Basic/OpenCLImageTypes.def"
2265
2266 case tok::annot_decltype:
2267 case tok::kw_decltype:
2268 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
2269 return DS.Finish(Actions, Policy);
2270
2271 // GNU typeof support.
2272 case tok::kw_typeof:
2273 ParseTypeofSpecifier(DS);
2274 DS.Finish(Actions, Policy);
2275 return;
2276 }
2277 ConsumeAnyToken();
2278 DS.SetRangeEnd(PrevTokLocation);
2279 DS.Finish(Actions, Policy);
2280}
2281
2282/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2283/// [dcl.name]), which is a non-empty sequence of type-specifiers,
2284/// e.g., "const short int". Note that the DeclSpec is *not* finished
2285/// by parsing the type-specifier-seq, because these sequences are
2286/// typically followed by some form of declarator. Returns true and
2287/// emits diagnostics if this is not a type-specifier-seq, false
2288/// otherwise.
2289///
2290/// type-specifier-seq: [C++ 8.1]
2291/// type-specifier type-specifier-seq[opt]
2292///
2293bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
2294 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
2295 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2296 return false;
2297}
2298
2299/// Finish parsing a C++ unqualified-id that is a template-id of
2300/// some form.
2301///
2302/// This routine is invoked when a '<' is encountered after an identifier or
2303/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2304/// whether the unqualified-id is actually a template-id. This routine will
2305/// then parse the template arguments and form the appropriate template-id to
2306/// return to the caller.
2307///
2308/// \param SS the nested-name-specifier that precedes this template-id, if
2309/// we're actually parsing a qualified-id.
2310///
2311/// \param ObjectType if this unqualified-id occurs within a member access
2312/// expression, the type of the base object whose member is being accessed.
2313///
2314/// \param ObjectHadErrors this unqualified-id occurs within a member access
2315/// expression, indicates whether the original subexpressions had any errors.
2316///
2317/// \param Name for constructor and destructor names, this is the actual
2318/// identifier that may be a template-name.
2319///
2320/// \param NameLoc the location of the class-name in a constructor or
2321/// destructor.
2322///
2323/// \param EnteringContext whether we're entering the scope of the
2324/// nested-name-specifier.
2325///
2326/// \param Id as input, describes the template-name or operator-function-id
2327/// that precedes the '<'. If template arguments were parsed successfully,
2328/// will be updated with the template-id.
2329///
2330/// \param AssumeTemplateId When true, this routine will assume that the name
2331/// refers to a template without performing name lookup to verify.
2332///
2333/// \returns true if a parse error occurred, false otherwise.
2334bool Parser::ParseUnqualifiedIdTemplateId(
2335 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
2336 SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc,
2337 bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId) {
2338 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 2338, __PRETTY_FUNCTION__))
;
2339
2340 TemplateTy Template;
2341 TemplateNameKind TNK = TNK_Non_template;
2342 switch (Id.getKind()) {
2343 case UnqualifiedIdKind::IK_Identifier:
2344 case UnqualifiedIdKind::IK_OperatorFunctionId:
2345 case UnqualifiedIdKind::IK_LiteralOperatorId:
2346 if (AssumeTemplateId) {
2347 // We defer the injected-class-name checks until we've found whether
2348 // this template-id is used to form a nested-name-specifier or not.
2349 TNK = Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Id,
2350 ObjectType, EnteringContext, Template,
2351 /*AllowInjectedClassName*/ true);
2352 } else {
2353 bool MemberOfUnknownSpecialization;
2354 TNK = Actions.isTemplateName(getCurScope(), SS,
2355 TemplateKWLoc.isValid(), Id,
2356 ObjectType, EnteringContext, Template,
2357 MemberOfUnknownSpecialization);
2358 // If lookup found nothing but we're assuming that this is a template
2359 // name, double-check that makes sense syntactically before committing
2360 // to it.
2361 if (TNK == TNK_Undeclared_template &&
2362 isTemplateArgumentList(0) == TPResult::False)
2363 return false;
2364
2365 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2366 ObjectType && isTemplateArgumentList(0) == TPResult::True) {
2367 // If we had errors before, ObjectType can be dependent even without any
2368 // templates, do not report missing template keyword in that case.
2369 if (!ObjectHadErrors) {
2370 // We have something like t->getAs<T>(), where getAs is a
2371 // member of an unknown specialization. However, this will only
2372 // parse correctly as a template, so suggest the keyword 'template'
2373 // before 'getAs' and treat this as a dependent template name.
2374 std::string Name;
2375 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
2376 Name = std::string(Id.Identifier->getName());
2377 else {
2378 Name = "operator ";
2379 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
2380 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2381 else
2382 Name += Id.Identifier->getName();
2383 }
2384 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2385 << Name
2386 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2387 }
2388 TNK = Actions.ActOnTemplateName(
2389 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2390 Template, /*AllowInjectedClassName*/ true);
2391 } else if (TNK == TNK_Non_template) {
2392 return false;
2393 }
2394 }
2395 break;
2396
2397 case UnqualifiedIdKind::IK_ConstructorName: {
2398 UnqualifiedId TemplateName;
2399 bool MemberOfUnknownSpecialization;
2400 TemplateName.setIdentifier(Name, NameLoc);
2401 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2402 TemplateName, ObjectType,
2403 EnteringContext, Template,
2404 MemberOfUnknownSpecialization);
2405 if (TNK == TNK_Non_template)
2406 return false;
2407 break;
2408 }
2409
2410 case UnqualifiedIdKind::IK_DestructorName: {
2411 UnqualifiedId TemplateName;
2412 bool MemberOfUnknownSpecialization;
2413 TemplateName.setIdentifier(Name, NameLoc);
2414 if (ObjectType) {
2415 TNK = Actions.ActOnTemplateName(
2416 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2417 EnteringContext, Template, /*AllowInjectedClassName*/ true);
2418 } else {
2419 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2420 TemplateName, ObjectType,
2421 EnteringContext, Template,
2422 MemberOfUnknownSpecialization);
2423
2424 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2425 Diag(NameLoc, diag::err_destructor_template_id)
2426 << Name << SS.getRange();
2427 // Carry on to parse the template arguments before bailing out.
2428 }
2429 }
2430 break;
2431 }
2432
2433 default:
2434 return false;
2435 }
2436
2437 // Parse the enclosed template argument list.
2438 SourceLocation LAngleLoc, RAngleLoc;
2439 TemplateArgList TemplateArgs;
2440 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2441 RAngleLoc))
2442 return true;
2443
2444 // If this is a non-template, we already issued a diagnostic.
2445 if (TNK == TNK_Non_template)
2446 return true;
2447
2448 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2449 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2450 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
2451 // Form a parsed representation of the template-id to be stored in the
2452 // UnqualifiedId.
2453
2454 // FIXME: Store name for literal operator too.
2455 IdentifierInfo *TemplateII =
2456 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2457 : nullptr;
2458 OverloadedOperatorKind OpKind =
2459 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2460 ? OO_None
2461 : Id.OperatorFunctionId.Operator;
2462
2463 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2464 TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2465 LAngleLoc, RAngleLoc, TemplateArgs, /*ArgsInvalid*/false, TemplateIds);
2466
2467 Id.setTemplateId(TemplateId);
2468 return false;
2469 }
2470
2471 // Bundle the template arguments together.
2472 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2473
2474 // Constructor and destructor names.
2475 TypeResult Type = Actions.ActOnTemplateIdType(
2476 getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc,
2477 TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true);
2478 if (Type.isInvalid())
2479 return true;
2480
2481 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
2482 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2483 else
2484 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2485
2486 return false;
2487}
2488
2489/// Parse an operator-function-id or conversion-function-id as part
2490/// of a C++ unqualified-id.
2491///
2492/// This routine is responsible only for parsing the operator-function-id or
2493/// conversion-function-id; it does not handle template arguments in any way.
2494///
2495/// \code
2496/// operator-function-id: [C++ 13.5]
2497/// 'operator' operator
2498///
2499/// operator: one of
2500/// new delete new[] delete[]
2501/// + - * / % ^ & | ~
2502/// ! = < > += -= *= /= %=
2503/// ^= &= |= << >> >>= <<= == !=
2504/// <= >= && || ++ -- , ->* ->
2505/// () [] <=>
2506///
2507/// conversion-function-id: [C++ 12.3.2]
2508/// operator conversion-type-id
2509///
2510/// conversion-type-id:
2511/// type-specifier-seq conversion-declarator[opt]
2512///
2513/// conversion-declarator:
2514/// ptr-operator conversion-declarator[opt]
2515/// \endcode
2516///
2517/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2518/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2519///
2520/// \param EnteringContext whether we are entering the scope of the
2521/// nested-name-specifier.
2522///
2523/// \param ObjectType if this unqualified-id occurs within a member access
2524/// expression, the type of the base object whose member is being accessed.
2525///
2526/// \param Result on a successful parse, contains the parsed unqualified-id.
2527///
2528/// \returns true if parsing fails, false otherwise.
2529bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2530 ParsedType ObjectType,
2531 UnqualifiedId &Result) {
2532 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 2532, __PRETTY_FUNCTION__))
;
2533
2534 // Consume the 'operator' keyword.
2535 SourceLocation KeywordLoc = ConsumeToken();
2536
2537 // Determine what kind of operator name we have.
2538 unsigned SymbolIdx = 0;
2539 SourceLocation SymbolLocations[3];
2540 OverloadedOperatorKind Op = OO_None;
2541 switch (Tok.getKind()) {
2542 case tok::kw_new:
2543 case tok::kw_delete: {
2544 bool isNew = Tok.getKind() == tok::kw_new;
2545 // Consume the 'new' or 'delete'.
2546 SymbolLocations[SymbolIdx++] = ConsumeToken();
2547 // Check for array new/delete.
2548 if (Tok.is(tok::l_square) &&
2549 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2550 // Consume the '[' and ']'.
2551 BalancedDelimiterTracker T(*this, tok::l_square);
2552 T.consumeOpen();
2553 T.consumeClose();
2554 if (T.getCloseLocation().isInvalid())
2555 return true;
2556
2557 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2558 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2559 Op = isNew? OO_Array_New : OO_Array_Delete;
2560 } else {
2561 Op = isNew? OO_New : OO_Delete;
2562 }
2563 break;
2564 }
2565
2566#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2567 case tok::Token: \
2568 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2569 Op = OO_##Name; \
2570 break;
2571#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2572#include "clang/Basic/OperatorKinds.def"
2573
2574 case tok::l_paren: {
2575 // Consume the '(' and ')'.
2576 BalancedDelimiterTracker T(*this, tok::l_paren);
2577 T.consumeOpen();
2578 T.consumeClose();
2579 if (T.getCloseLocation().isInvalid())
2580 return true;
2581
2582 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2583 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2584 Op = OO_Call;
2585 break;
2586 }
2587
2588 case tok::l_square: {
2589 // Consume the '[' and ']'.
2590 BalancedDelimiterTracker T(*this, tok::l_square);
2591 T.consumeOpen();
2592 T.consumeClose();
2593 if (T.getCloseLocation().isInvalid())
2594 return true;
2595
2596 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2597 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2598 Op = OO_Subscript;
2599 break;
2600 }
2601
2602 case tok::code_completion: {
2603 // Code completion for the operator name.
2604 Actions.CodeCompleteOperatorName(getCurScope());
2605 cutOffParsing();
2606 // Don't try to parse any further.
2607 return true;
2608 }
2609
2610 default:
2611 break;
2612 }
2613
2614 if (Op != OO_None) {
2615 // We have parsed an operator-function-id.
2616 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2617 return false;
2618 }
2619
2620 // Parse a literal-operator-id.
2621 //
2622 // literal-operator-id: C++11 [over.literal]
2623 // operator string-literal identifier
2624 // operator user-defined-string-literal
2625
2626 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2627 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2628
2629 SourceLocation DiagLoc;
2630 unsigned DiagId = 0;
2631
2632 // We're past translation phase 6, so perform string literal concatenation
2633 // before checking for "".
2634 SmallVector<Token, 4> Toks;
2635 SmallVector<SourceLocation, 4> TokLocs;
2636 while (isTokenStringLiteral()) {
2637 if (!Tok.is(tok::string_literal) && !DiagId) {
2638 // C++11 [over.literal]p1:
2639 // The string-literal or user-defined-string-literal in a
2640 // literal-operator-id shall have no encoding-prefix [...].
2641 DiagLoc = Tok.getLocation();
2642 DiagId = diag::err_literal_operator_string_prefix;
2643 }
2644 Toks.push_back(Tok);
2645 TokLocs.push_back(ConsumeStringToken());
2646 }
2647
2648 StringLiteralParser Literal(Toks, PP);
2649 if (Literal.hadError)
2650 return true;
2651
2652 // Grab the literal operator's suffix, which will be either the next token
2653 // or a ud-suffix from the string literal.
2654 IdentifierInfo *II = nullptr;
2655 SourceLocation SuffixLoc;
2656 if (!Literal.getUDSuffix().empty()) {
2657 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2658 SuffixLoc =
2659 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2660 Literal.getUDSuffixOffset(),
2661 PP.getSourceManager(), getLangOpts());
2662 } else if (Tok.is(tok::identifier)) {
2663 II = Tok.getIdentifierInfo();
2664 SuffixLoc = ConsumeToken();
2665 TokLocs.push_back(SuffixLoc);
2666 } else {
2667 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2668 return true;
2669 }
2670
2671 // The string literal must be empty.
2672 if (!Literal.GetString().empty() || Literal.Pascal) {
2673 // C++11 [over.literal]p1:
2674 // The string-literal or user-defined-string-literal in a
2675 // literal-operator-id shall [...] contain no characters
2676 // other than the implicit terminating '\0'.
2677 DiagLoc = TokLocs.front();
2678 DiagId = diag::err_literal_operator_string_not_empty;
2679 }
2680
2681 if (DiagId) {
2682 // This isn't a valid literal-operator-id, but we think we know
2683 // what the user meant. Tell them what they should have written.
2684 SmallString<32> Str;
2685 Str += "\"\"";
2686 Str += II->getName();
2687 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2688 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2689 }
2690
2691 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2692
2693 return Actions.checkLiteralOperatorId(SS, Result);
2694 }
2695
2696 // Parse a conversion-function-id.
2697 //
2698 // conversion-function-id: [C++ 12.3.2]
2699 // operator conversion-type-id
2700 //
2701 // conversion-type-id:
2702 // type-specifier-seq conversion-declarator[opt]
2703 //
2704 // conversion-declarator:
2705 // ptr-operator conversion-declarator[opt]
2706
2707 // Parse the type-specifier-seq.
2708 DeclSpec DS(AttrFactory);
2709 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2710 return true;
2711
2712 // Parse the conversion-declarator, which is merely a sequence of
2713 // ptr-operators.
2714 Declarator D(DS, DeclaratorContext::ConversionId);
2715 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2716
2717 // Finish up the type.
2718 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2719 if (Ty.isInvalid())
2720 return true;
2721
2722 // Note that this is a conversion-function-id.
2723 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2724 D.getSourceRange().getEnd());
2725 return false;
2726}
2727
2728/// Parse a C++ unqualified-id (or a C identifier), which describes the
2729/// name of an entity.
2730///
2731/// \code
2732/// unqualified-id: [C++ expr.prim.general]
2733/// identifier
2734/// operator-function-id
2735/// conversion-function-id
2736/// [C++0x] literal-operator-id [TODO]
2737/// ~ class-name
2738/// template-id
2739///
2740/// \endcode
2741///
2742/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2743/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2744///
2745/// \param ObjectType if this unqualified-id occurs within a member access
2746/// expression, the type of the base object whose member is being accessed.
2747///
2748/// \param ObjectHadErrors if this unqualified-id occurs within a member access
2749/// expression, indicates whether the original subexpressions had any errors.
2750/// When true, diagnostics for missing 'template' keyword will be supressed.
2751///
2752/// \param EnteringContext whether we are entering the scope of the
2753/// nested-name-specifier.
2754///
2755/// \param AllowDestructorName whether we allow parsing of a destructor name.
2756///
2757/// \param AllowConstructorName whether we allow parsing a constructor name.
2758///
2759/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2760///
2761/// \param Result on a successful parse, contains the parsed unqualified-id.
2762///
2763/// \returns true if parsing fails, false otherwise.
2764bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
2765 bool ObjectHadErrors, bool EnteringContext,
2766 bool AllowDestructorName,
2767 bool AllowConstructorName,
2768 bool AllowDeductionGuide,
2769 SourceLocation *TemplateKWLoc,
2770 UnqualifiedId &Result) {
2771 if (TemplateKWLoc)
2772 *TemplateKWLoc = SourceLocation();
2773
2774 // Handle 'A::template B'. This is for template-ids which have not
2775 // already been annotated by ParseOptionalCXXScopeSpecifier().
2776 bool TemplateSpecified = false;
2777 if (Tok.is(tok::kw_template)) {
2778 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2779 TemplateSpecified = true;
2780 *TemplateKWLoc = ConsumeToken();
2781 } else {
2782 SourceLocation TemplateLoc = ConsumeToken();
2783 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2784 << FixItHint::CreateRemoval(TemplateLoc);
2785 }
2786 }
2787
2788 // unqualified-id:
2789 // identifier
2790 // template-id (when it hasn't already been annotated)
2791 if (Tok.is(tok::identifier)) {
2792 // Consume the identifier.
2793 IdentifierInfo *Id = Tok.getIdentifierInfo();
2794 SourceLocation IdLoc = ConsumeToken();
2795
2796 if (!getLangOpts().CPlusPlus) {
2797 // If we're not in C++, only identifiers matter. Record the
2798 // identifier and return.
2799 Result.setIdentifier(Id, IdLoc);
2800 return false;
2801 }
2802
2803 ParsedTemplateTy TemplateName;
2804 if (AllowConstructorName &&
2805 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2806 // We have parsed a constructor name.
2807 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2808 EnteringContext);
2809 if (!Ty)
2810 return true;
2811 Result.setConstructorName(Ty, IdLoc, IdLoc);
2812 } else if (getLangOpts().CPlusPlus17 &&
2813 AllowDeductionGuide && SS.isEmpty() &&
2814 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2815 &TemplateName)) {
2816 // We have parsed a template-name naming a deduction guide.
2817 Result.setDeductionGuideName(TemplateName, IdLoc);
2818 } else {
2819 // We have parsed an identifier.
2820 Result.setIdentifier(Id, IdLoc);
2821 }
2822
2823 // If the next token is a '<', we may have a template.
2824 TemplateTy Template;
2825 if (Tok.is(tok::less))
2826 return ParseUnqualifiedIdTemplateId(
2827 SS, ObjectType, ObjectHadErrors,
2828 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2829 EnteringContext, Result, TemplateSpecified);
2830 else if (TemplateSpecified &&
2831 Actions.ActOnTemplateName(
2832 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2833 EnteringContext, Template,
2834 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2835 return true;
2836
2837 return false;
2838 }
2839
2840 // unqualified-id:
2841 // template-id (already parsed and annotated)
2842 if (Tok.is(tok::annot_template_id)) {
2843 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2844
2845 // FIXME: Consider passing invalid template-ids on to callers; they may
2846 // be able to recover better than we can.
2847 if (TemplateId->isInvalid()) {
2848 ConsumeAnnotationToken();
2849 return true;
2850 }
2851
2852 // If the template-name names the current class, then this is a constructor
2853 if (AllowConstructorName && TemplateId->Name &&
2854 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2855 if (SS.isSet()) {
2856 // C++ [class.qual]p2 specifies that a qualified template-name
2857 // is taken as the constructor name where a constructor can be
2858 // declared. Thus, the template arguments are extraneous, so
2859 // complain about them and remove them entirely.
2860 Diag(TemplateId->TemplateNameLoc,
2861 diag::err_out_of_line_constructor_template_id)
2862 << TemplateId->Name
2863 << FixItHint::CreateRemoval(
2864 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2865 ParsedType Ty = Actions.getConstructorName(
2866 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2867 EnteringContext);
2868 if (!Ty)
2869 return true;
2870 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2871 TemplateId->RAngleLoc);
2872 ConsumeAnnotationToken();
2873 return false;
2874 }
2875
2876 Result.setConstructorTemplateId(TemplateId);
2877 ConsumeAnnotationToken();
2878 return false;
2879 }
2880
2881 // We have already parsed a template-id; consume the annotation token as
2882 // our unqualified-id.
2883 Result.setTemplateId(TemplateId);
2884 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2885 if (TemplateLoc.isValid()) {
2886 if (TemplateKWLoc && (ObjectType || SS.isSet()))
2887 *TemplateKWLoc = TemplateLoc;
2888 else
2889 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2890 << FixItHint::CreateRemoval(TemplateLoc);
2891 }
2892 ConsumeAnnotationToken();
2893 return false;
2894 }
2895
2896 // unqualified-id:
2897 // operator-function-id
2898 // conversion-function-id
2899 if (Tok.is(tok::kw_operator)) {
2900 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2901 return true;
2902
2903 // If we have an operator-function-id or a literal-operator-id and the next
2904 // token is a '<', we may have a
2905 //
2906 // template-id:
2907 // operator-function-id < template-argument-list[opt] >
2908 TemplateTy Template;
2909 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2910 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
2911 Tok.is(tok::less))
2912 return ParseUnqualifiedIdTemplateId(
2913 SS, ObjectType, ObjectHadErrors,
2914 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2915 SourceLocation(), EnteringContext, Result, TemplateSpecified);
2916 else if (TemplateSpecified &&
2917 Actions.ActOnTemplateName(
2918 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2919 EnteringContext, Template,
2920 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2921 return true;
2922
2923 return false;
2924 }
2925
2926 if (getLangOpts().CPlusPlus &&
2927 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2928 // C++ [expr.unary.op]p10:
2929 // There is an ambiguity in the unary-expression ~X(), where X is a
2930 // class-name. The ambiguity is resolved in favor of treating ~ as a
2931 // unary complement rather than treating ~X as referring to a destructor.
2932
2933 // Parse the '~'.
2934 SourceLocation TildeLoc = ConsumeToken();
2935
2936 if (TemplateSpecified) {
2937 // C++ [temp.names]p3:
2938 // A name prefixed by the keyword template shall be a template-id [...]
2939 //
2940 // A template-id cannot begin with a '~' token. This would never work
2941 // anyway: x.~A<int>() would specify that the destructor is a template,
2942 // not that 'A' is a template.
2943 //
2944 // FIXME: Suggest replacing the attempted destructor name with a correct
2945 // destructor name and recover. (This is not trivial if this would become
2946 // a pseudo-destructor name).
2947 Diag(*TemplateKWLoc, diag::err_unexpected_template_in_destructor_name)
2948 << Tok.getLocation();
2949 return true;
2950 }
2951
2952 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2953 DeclSpec DS(AttrFactory);
2954 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2955 if (ParsedType Type =
2956 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
2957 Result.setDestructorName(TildeLoc, Type, EndLoc);
2958 return false;
2959 }
2960 return true;
2961 }
2962
2963 // Parse the class-name.
2964 if (Tok.isNot(tok::identifier)) {
2965 Diag(Tok, diag::err_destructor_tilde_identifier);
2966 return true;
2967 }
2968
2969 // If the user wrote ~T::T, correct it to T::~T.
2970 DeclaratorScopeObj DeclScopeObj(*this, SS);
2971 if (NextToken().is(tok::coloncolon)) {
2972 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2973 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2974 // it will confuse this recovery logic.
2975 ColonProtectionRAIIObject ColonRAII(*this, false);
2976
2977 if (SS.isSet()) {
2978 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2979 SS.clear();
2980 }
2981 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, ObjectHadErrors,
2982 EnteringContext))
2983 return true;
2984 if (SS.isNotEmpty())
2985 ObjectType = nullptr;
2986 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2987 !SS.isSet()) {
2988 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2989 return true;
2990 }
2991
2992 // Recover as if the tilde had been written before the identifier.
2993 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2994 << FixItHint::CreateRemoval(TildeLoc)
2995 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2996
2997 // Temporarily enter the scope for the rest of this function.
2998 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2999 DeclScopeObj.EnterDeclaratorScope();
3000 }
3001
3002 // Parse the class-name (or template-name in a simple-template-id).
3003 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
3004 SourceLocation ClassNameLoc = ConsumeToken();
3005
3006 if (Tok.is(tok::less)) {
3007 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
3008 return ParseUnqualifiedIdTemplateId(
3009 SS, ObjectType, ObjectHadErrors,
3010 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
3011 ClassNameLoc, EnteringContext, Result, TemplateSpecified);
3012 }
3013
3014 // Note that this is a destructor name.
3015 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
3016 ClassNameLoc, getCurScope(),
3017 SS, ObjectType,
3018 EnteringContext);
3019 if (!Ty)
3020 return true;
3021
3022 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
3023 return false;
3024 }
3025
3026 Diag(Tok, diag::err_expected_unqualified_id)
3027 << getLangOpts().CPlusPlus;
3028 return true;
3029}
3030
3031/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
3032/// memory in a typesafe manner and call constructors.
3033///
3034/// This method is called to parse the new expression after the optional :: has
3035/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
3036/// is its location. Otherwise, "Start" is the location of the 'new' token.
3037///
3038/// new-expression:
3039/// '::'[opt] 'new' new-placement[opt] new-type-id
3040/// new-initializer[opt]
3041/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3042/// new-initializer[opt]
3043///
3044/// new-placement:
3045/// '(' expression-list ')'
3046///
3047/// new-type-id:
3048/// type-specifier-seq new-declarator[opt]
3049/// [GNU] attributes type-specifier-seq new-declarator[opt]
3050///
3051/// new-declarator:
3052/// ptr-operator new-declarator[opt]
3053/// direct-new-declarator
3054///
3055/// new-initializer:
3056/// '(' expression-list[opt] ')'
3057/// [C++0x] braced-init-list
3058///
3059ExprResult
3060Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
3061 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3061, __PRETTY_FUNCTION__))
;
3062 ConsumeToken(); // Consume 'new'
3063
3064 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
3065 // second form of new-expression. It can't be a new-type-id.
3066
3067 ExprVector PlacementArgs;
3068 SourceLocation PlacementLParen, PlacementRParen;
3069
3070 SourceRange TypeIdParens;
3071 DeclSpec DS(AttrFactory);
3072 Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNew);
3073 if (Tok.is(tok::l_paren)) {
3074 // If it turns out to be a placement, we change the type location.
3075 BalancedDelimiterTracker T(*this, tok::l_paren);
3076 T.consumeOpen();
3077 PlacementLParen = T.getOpenLocation();
3078 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
3079 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3080 return ExprError();
3081 }
3082
3083 T.consumeClose();
3084 PlacementRParen = T.getCloseLocation();
3085 if (PlacementRParen.isInvalid()) {
3086 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3087 return ExprError();
3088 }
3089
3090 if (PlacementArgs.empty()) {
3091 // Reset the placement locations. There was no placement.
3092 TypeIdParens = T.getRange();
3093 PlacementLParen = PlacementRParen = SourceLocation();
3094 } else {
3095 // We still need the type.
3096 if (Tok.is(tok::l_paren)) {
3097 BalancedDelimiterTracker T(*this, tok::l_paren);
3098 T.consumeOpen();
3099 MaybeParseGNUAttributes(DeclaratorInfo);
3100 ParseSpecifierQualifierList(DS);
3101 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3102 ParseDeclarator(DeclaratorInfo);
3103 T.consumeClose();
3104 TypeIdParens = T.getRange();
3105 } else {
3106 MaybeParseGNUAttributes(DeclaratorInfo);
3107 if (ParseCXXTypeSpecifierSeq(DS))
3108 DeclaratorInfo.setInvalidType(true);
3109 else {
3110 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3111 ParseDeclaratorInternal(DeclaratorInfo,
3112 &Parser::ParseDirectNewDeclarator);
3113 }
3114 }
3115 }
3116 } else {
3117 // A new-type-id is a simplified type-id, where essentially the
3118 // direct-declarator is replaced by a direct-new-declarator.
3119 MaybeParseGNUAttributes(DeclaratorInfo);
3120 if (ParseCXXTypeSpecifierSeq(DS))
3121 DeclaratorInfo.setInvalidType(true);
3122 else {
3123 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3124 ParseDeclaratorInternal(DeclaratorInfo,
3125 &Parser::ParseDirectNewDeclarator);
3126 }
3127 }
3128 if (DeclaratorInfo.isInvalidType()) {
3129 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3130 return ExprError();
3131 }
3132
3133 ExprResult Initializer;
3134
3135 if (Tok.is(tok::l_paren)) {
3136 SourceLocation ConstructorLParen, ConstructorRParen;
3137 ExprVector ConstructorArgs;
3138 BalancedDelimiterTracker T(*this, tok::l_paren);
3139 T.consumeOpen();
3140 ConstructorLParen = T.getOpenLocation();
3141 if (Tok.isNot(tok::r_paren)) {
3142 CommaLocsTy CommaLocs;
3143 auto RunSignatureHelp = [&]() {
3144 ParsedType TypeRep =
3145 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
3146 QualType PreferredType;
3147 // ActOnTypeName might adjust DeclaratorInfo and return a null type even
3148 // the passing DeclaratorInfo is valid, e.g. running SignatureHelp on
3149 // `new decltype(invalid) (^)`.
3150 if (TypeRep)
3151 PreferredType = Actions.ProduceConstructorSignatureHelp(
3152 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
3153 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
3154 CalledSignatureHelp = true;
3155 return PreferredType;
3156 };
3157 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
3158 PreferredType.enterFunctionArgument(Tok.getLocation(),
3159 RunSignatureHelp);
3160 })) {
3161 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3162 RunSignatureHelp();
3163 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3164 return ExprError();
3165 }
3166 }
3167 T.consumeClose();
3168 ConstructorRParen = T.getCloseLocation();
3169 if (ConstructorRParen.isInvalid()) {
3170 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3171 return ExprError();
3172 }
3173 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
3174 ConstructorRParen,
3175 ConstructorArgs);
3176 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
3177 Diag(Tok.getLocation(),
3178 diag::warn_cxx98_compat_generalized_initializer_lists);
3179 Initializer = ParseBraceInitializer();
3180 }
3181 if (Initializer.isInvalid())
3182 return Initializer;
3183
3184 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
3185 PlacementArgs, PlacementRParen,
3186 TypeIdParens, DeclaratorInfo, Initializer.get());
3187}
3188
3189/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
3190/// passed to ParseDeclaratorInternal.
3191///
3192/// direct-new-declarator:
3193/// '[' expression[opt] ']'
3194/// direct-new-declarator '[' constant-expression ']'
3195///
3196void Parser::ParseDirectNewDeclarator(Declarator &D) {
3197 // Parse the array dimensions.
3198 bool First = true;
3199 while (Tok.is(tok::l_square)) {
3200 // An array-size expression can't start with a lambda.
3201 if (CheckProhibitedCXX11Attribute())
3202 continue;
3203
3204 BalancedDelimiterTracker T(*this, tok::l_square);
3205 T.consumeOpen();
3206
3207 ExprResult Size =
3208 First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression())
3209 : ParseConstantExpression();
3210 if (Size.isInvalid()) {
3211 // Recover
3212 SkipUntil(tok::r_square, StopAtSemi);
3213 return;
3214 }
3215 First = false;
3216
3217 T.consumeClose();
3218
3219 // Attributes here appertain to the array type. C++11 [expr.new]p5.
3220 ParsedAttributes Attrs(AttrFactory);
3221 MaybeParseCXX11Attributes(Attrs);
3222
3223 D.AddTypeInfo(DeclaratorChunk::getArray(0,
3224 /*isStatic=*/false, /*isStar=*/false,
3225 Size.get(), T.getOpenLocation(),
3226 T.getCloseLocation()),
3227 std::move(Attrs), T.getCloseLocation());
3228
3229 if (T.getCloseLocation().isInvalid())
3230 return;
3231 }
3232}
3233
3234/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
3235/// This ambiguity appears in the syntax of the C++ new operator.
3236///
3237/// new-expression:
3238/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3239/// new-initializer[opt]
3240///
3241/// new-placement:
3242/// '(' expression-list ')'
3243///
3244bool Parser::ParseExpressionListOrTypeId(
3245 SmallVectorImpl<Expr*> &PlacementArgs,
3246 Declarator &D) {
3247 // The '(' was already consumed.
3248 if (isTypeIdInParens()) {
3249 ParseSpecifierQualifierList(D.getMutableDeclSpec());
3250 D.SetSourceRange(D.getDeclSpec().getSourceRange());
3251 ParseDeclarator(D);
3252 return D.isInvalidType();
3253 }
3254
3255 // It's not a type, it has to be an expression list.
3256 // Discard the comma locations - ActOnCXXNew has enough parameters.
3257 CommaLocsTy CommaLocs;
3258 return ParseExpressionList(PlacementArgs, CommaLocs);
3259}
3260
3261/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
3262/// to free memory allocated by new.
3263///
3264/// This method is called to parse the 'delete' expression after the optional
3265/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
3266/// and "Start" is its location. Otherwise, "Start" is the location of the
3267/// 'delete' token.
3268///
3269/// delete-expression:
3270/// '::'[opt] 'delete' cast-expression
3271/// '::'[opt] 'delete' '[' ']' cast-expression
3272ExprResult
3273Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
3274 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3274, __PRETTY_FUNCTION__))
;
3275 ConsumeToken(); // Consume 'delete'
3276
3277 // Array delete?
3278 bool ArrayDelete = false;
3279 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
3280 // C++11 [expr.delete]p1:
3281 // Whenever the delete keyword is followed by empty square brackets, it
3282 // shall be interpreted as [array delete].
3283 // [Footnote: A lambda expression with a lambda-introducer that consists
3284 // of empty square brackets can follow the delete keyword if
3285 // the lambda expression is enclosed in parentheses.]
3286
3287 const Token Next = GetLookAheadToken(2);
3288
3289 // Basic lookahead to check if we have a lambda expression.
3290 if (Next.isOneOf(tok::l_brace, tok::less) ||
3291 (Next.is(tok::l_paren) &&
3292 (GetLookAheadToken(3).is(tok::r_paren) ||
3293 (GetLookAheadToken(3).is(tok::identifier) &&
3294 GetLookAheadToken(4).is(tok::identifier))))) {
3295 TentativeParsingAction TPA(*this);
3296 SourceLocation LSquareLoc = Tok.getLocation();
3297 SourceLocation RSquareLoc = NextToken().getLocation();
3298
3299 // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
3300 // case.
3301 SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch);
3302 SourceLocation RBraceLoc;
3303 bool EmitFixIt = false;
3304 if (Tok.is(tok::l_brace)) {
3305 ConsumeBrace();
3306 SkipUntil(tok::r_brace, StopBeforeMatch);
3307 RBraceLoc = Tok.getLocation();
3308 EmitFixIt = true;
3309 }
3310
3311 TPA.Revert();
3312
3313 if (EmitFixIt)
3314 Diag(Start, diag::err_lambda_after_delete)
3315 << SourceRange(Start, RSquareLoc)
3316 << FixItHint::CreateInsertion(LSquareLoc, "(")
3317 << FixItHint::CreateInsertion(
3318 Lexer::getLocForEndOfToken(
3319 RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()),
3320 ")");
3321 else
3322 Diag(Start, diag::err_lambda_after_delete)
3323 << SourceRange(Start, RSquareLoc);
3324
3325 // Warn that the non-capturing lambda isn't surrounded by parentheses
3326 // to disambiguate it from 'delete[]'.
3327 ExprResult Lambda = ParseLambdaExpression();
3328 if (Lambda.isInvalid())
3329 return ExprError();
3330
3331 // Evaluate any postfix expressions used on the lambda.
3332 Lambda = ParsePostfixExpressionSuffix(Lambda);
3333 if (Lambda.isInvalid())
3334 return ExprError();
3335 return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
3336 Lambda.get());
3337 }
3338
3339 ArrayDelete = true;
3340 BalancedDelimiterTracker T(*this, tok::l_square);
3341
3342 T.consumeOpen();
3343 T.consumeClose();
3344 if (T.getCloseLocation().isInvalid())
3345 return ExprError();
3346 }
3347
3348 ExprResult Operand(ParseCastExpression(AnyCastExpr));
3349 if (Operand.isInvalid())
3350 return Operand;
3351
3352 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
3353}
3354
3355/// ParseRequiresExpression - Parse a C++2a requires-expression.
3356/// C++2a [expr.prim.req]p1
3357/// A requires-expression provides a concise way to express requirements on
3358/// template arguments. A requirement is one that can be checked by name
3359/// lookup (6.4) or by checking properties of types and expressions.
3360///
3361/// requires-expression:
3362/// 'requires' requirement-parameter-list[opt] requirement-body
3363///
3364/// requirement-parameter-list:
3365/// '(' parameter-declaration-clause[opt] ')'
3366///
3367/// requirement-body:
3368/// '{' requirement-seq '}'
3369///
3370/// requirement-seq:
3371/// requirement
3372/// requirement-seq requirement
3373///
3374/// requirement:
3375/// simple-requirement
3376/// type-requirement
3377/// compound-requirement
3378/// nested-requirement
3379ExprResult Parser::ParseRequiresExpression() {
3380 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3380, __PRETTY_FUNCTION__))
;
3381 SourceLocation RequiresKWLoc = ConsumeToken(); // Consume 'requires'
3382
3383 llvm::SmallVector<ParmVarDecl *, 2> LocalParameterDecls;
3384 if (Tok.is(tok::l_paren)) {
3385 // requirement parameter list is present.
3386 ParseScope LocalParametersScope(this, Scope::FunctionPrototypeScope |
3387 Scope::DeclScope);
3388 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3389 Parens.consumeOpen();
3390 if (!Tok.is(tok::r_paren)) {
3391 ParsedAttributes FirstArgAttrs(getAttrFactory());
3392 SourceLocation EllipsisLoc;
3393 llvm::SmallVector<DeclaratorChunk::ParamInfo, 2> LocalParameters;
3394 ParseParameterDeclarationClause(DeclaratorContext::RequiresExpr,
3395 FirstArgAttrs, LocalParameters,
3396 EllipsisLoc);
3397 if (EllipsisLoc.isValid())
3398 Diag(EllipsisLoc, diag::err_requires_expr_parameter_list_ellipsis);
3399 for (auto &ParamInfo : LocalParameters)
3400 LocalParameterDecls.push_back(cast<ParmVarDecl>(ParamInfo.Param));
3401 }
3402 Parens.consumeClose();
3403 }
3404
3405 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3406 if (Braces.expectAndConsume())
3407 return ExprError();
3408
3409 // Start of requirement list
3410 llvm::SmallVector<concepts::Requirement *, 2> Requirements;
3411
3412 // C++2a [expr.prim.req]p2
3413 // Expressions appearing within a requirement-body are unevaluated operands.
3414 EnterExpressionEvaluationContext Ctx(
3415 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
3416
3417 ParseScope BodyScope(this, Scope::DeclScope);
3418 RequiresExprBodyDecl *Body = Actions.ActOnStartRequiresExpr(
3419 RequiresKWLoc, LocalParameterDecls, getCurScope());
3420
3421 if (Tok.is(tok::r_brace)) {
3422 // Grammar does not allow an empty body.
3423 // requirement-body:
3424 // { requirement-seq }
3425 // requirement-seq:
3426 // requirement
3427 // requirement-seq requirement
3428 Diag(Tok, diag::err_empty_requires_expr);
3429 // Continue anyway and produce a requires expr with no requirements.
3430 } else {
3431 while (!Tok.is(tok::r_brace)) {
3432 switch (Tok.getKind()) {
3433 case tok::l_brace: {
3434 // Compound requirement
3435 // C++ [expr.prim.req.compound]
3436 // compound-requirement:
3437 // '{' expression '}' 'noexcept'[opt]
3438 // return-type-requirement[opt] ';'
3439 // return-type-requirement:
3440 // trailing-return-type
3441 // '->' cv-qualifier-seq[opt] constrained-parameter
3442 // cv-qualifier-seq[opt] abstract-declarator[opt]
3443 BalancedDelimiterTracker ExprBraces(*this, tok::l_brace);
3444 ExprBraces.consumeOpen();
3445 ExprResult Expression =
3446 Actions.CorrectDelayedTyposInExpr(ParseExpression());
3447 if (!Expression.isUsable()) {
3448 ExprBraces.skipToEnd();
3449 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3450 break;
3451 }
3452 if (ExprBraces.consumeClose())
3453 ExprBraces.skipToEnd();
3454
3455 concepts::Requirement *Req = nullptr;
3456 SourceLocation NoexceptLoc;
3457 TryConsumeToken(tok::kw_noexcept, NoexceptLoc);
3458 if (Tok.is(tok::semi)) {
3459 Req = Actions.ActOnCompoundRequirement(Expression.get(), NoexceptLoc);
3460 if (Req)
3461 Requirements.push_back(Req);
3462 break;
3463 }
3464 if (!TryConsumeToken(tok::arrow))
3465 // User probably forgot the arrow, remind them and try to continue.
3466 Diag(Tok, diag::err_requires_expr_missing_arrow)
3467 << FixItHint::CreateInsertion(Tok.getLocation(), "->");
3468 // Try to parse a 'type-constraint'
3469 if (TryAnnotateTypeConstraint()) {
3470 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3471 break;
3472 }
3473 if (!isTypeConstraintAnnotation()) {
3474 Diag(Tok, diag::err_requires_expr_expected_type_constraint);
3475 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3476 break;
3477 }
3478 CXXScopeSpec SS;
3479 if (Tok.is(tok::annot_cxxscope)) {
3480 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3481 Tok.getAnnotationRange(),
3482 SS);
3483 ConsumeAnnotationToken();
3484 }
3485
3486 Req = Actions.ActOnCompoundRequirement(
3487 Expression.get(), NoexceptLoc, SS, takeTemplateIdAnnotation(Tok),
3488 TemplateParameterDepth);
3489 ConsumeAnnotationToken();
3490 if (Req)
3491 Requirements.push_back(Req);
3492 break;
3493 }
3494 default: {
3495 bool PossibleRequiresExprInSimpleRequirement = false;
3496 if (Tok.is(tok::kw_requires)) {
3497 auto IsNestedRequirement = [&] {
3498 RevertingTentativeParsingAction TPA(*this);
3499 ConsumeToken(); // 'requires'
3500 if (Tok.is(tok::l_brace))
3501 // This is a requires expression
3502 // requires (T t) {
3503 // requires { t++; };
3504 // ... ^
3505 // }
3506 return false;
3507 if (Tok.is(tok::l_paren)) {
3508 // This might be the parameter list of a requires expression
3509 ConsumeParen();
3510 auto Res = TryParseParameterDeclarationClause();
3511 if (Res != TPResult::False) {
3512 // Skip to the closing parenthesis
3513 // FIXME: Don't traverse these tokens twice (here and in
3514 // TryParseParameterDeclarationClause).
3515 unsigned Depth = 1;
3516 while (Depth != 0) {
3517 if (Tok.is(tok::l_paren))
3518 Depth++;
3519 else if (Tok.is(tok::r_paren))
3520 Depth--;
3521 ConsumeAnyToken();
3522 }
3523 // requires (T t) {
3524 // requires () ?
3525 // ... ^
3526 // - OR -
3527 // requires (int x) ?
3528 // ... ^
3529 // }
3530 if (Tok.is(tok::l_brace))
3531 // requires (...) {
3532 // ^ - a requires expression as a
3533 // simple-requirement.
3534 return false;
3535 }
3536 }
3537 return true;
3538 };
3539 if (IsNestedRequirement()) {
3540 ConsumeToken();
3541 // Nested requirement
3542 // C++ [expr.prim.req.nested]
3543 // nested-requirement:
3544 // 'requires' constraint-expression ';'
3545 ExprResult ConstraintExpr =
3546 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
3547 if (ConstraintExpr.isInvalid() || !ConstraintExpr.isUsable()) {
3548 SkipUntil(tok::semi, tok::r_brace,
3549 SkipUntilFlags::StopBeforeMatch);
3550 break;
3551 }
3552 if (auto *Req =
3553 Actions.ActOnNestedRequirement(ConstraintExpr.get()))
3554 Requirements.push_back(Req);
3555 else {
3556 SkipUntil(tok::semi, tok::r_brace,
3557 SkipUntilFlags::StopBeforeMatch);
3558 break;
3559 }
3560 break;
3561 } else
3562 PossibleRequiresExprInSimpleRequirement = true;
3563 } else if (Tok.is(tok::kw_typename)) {
3564 // This might be 'typename T::value_type;' (a type requirement) or
3565 // 'typename T::value_type{};' (a simple requirement).
3566 TentativeParsingAction TPA(*this);
3567
3568 // We need to consume the typename to allow 'requires { typename a; }'
3569 SourceLocation TypenameKWLoc = ConsumeToken();
3570 if (TryAnnotateCXXScopeToken()) {
3571 TPA.Commit();
3572 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3573 break;
3574 }
3575 CXXScopeSpec SS;
3576 if (Tok.is(tok::annot_cxxscope)) {
3577 Actions.RestoreNestedNameSpecifierAnnotation(
3578 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3579 ConsumeAnnotationToken();
3580 }
3581
3582 if (Tok.isOneOf(tok::identifier, tok::annot_template_id) &&
3583 !NextToken().isOneOf(tok::l_brace, tok::l_paren)) {
3584 TPA.Commit();
3585 SourceLocation NameLoc = Tok.getLocation();
3586 IdentifierInfo *II = nullptr;
3587 TemplateIdAnnotation *TemplateId = nullptr;
3588 if (Tok.is(tok::identifier)) {
3589 II = Tok.getIdentifierInfo();
3590 ConsumeToken();
3591 } else {
3592 TemplateId = takeTemplateIdAnnotation(Tok);
3593 ConsumeAnnotationToken();
3594 if (TemplateId->isInvalid())
3595 break;
3596 }
3597
3598 if (auto *Req = Actions.ActOnTypeRequirement(TypenameKWLoc, SS,
3599 NameLoc, II,
3600 TemplateId)) {
3601 Requirements.push_back(Req);
3602 }
3603 break;
3604 }
3605 TPA.Revert();
3606 }
3607 // Simple requirement
3608 // C++ [expr.prim.req.simple]
3609 // simple-requirement:
3610 // expression ';'
3611 SourceLocation StartLoc = Tok.getLocation();
3612 ExprResult Expression =
3613 Actions.CorrectDelayedTyposInExpr(ParseExpression());
3614 if (!Expression.isUsable()) {
3615 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3616 break;
3617 }
3618 if (!Expression.isInvalid() && PossibleRequiresExprInSimpleRequirement)
3619 Diag(StartLoc, diag::warn_requires_expr_in_simple_requirement)
3620 << FixItHint::CreateInsertion(StartLoc, "requires");
3621 if (auto *Req = Actions.ActOnSimpleRequirement(Expression.get()))
3622 Requirements.push_back(Req);
3623 else {
3624 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3625 break;
3626 }
3627 // User may have tried to put some compound requirement stuff here
3628 if (Tok.is(tok::kw_noexcept)) {
3629 Diag(Tok, diag::err_requires_expr_simple_requirement_noexcept)
3630 << FixItHint::CreateInsertion(StartLoc, "{")
3631 << FixItHint::CreateInsertion(Tok.getLocation(), "}");
3632 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3633 break;
3634 }
3635 break;
3636 }
3637 }
3638 if (ExpectAndConsumeSemi(diag::err_expected_semi_requirement)) {
3639 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3640 TryConsumeToken(tok::semi);
3641 break;
3642 }
3643 }
3644 if (Requirements.empty()) {
3645 // Don't emit an empty requires expr here to avoid confusing the user with
3646 // other diagnostics quoting an empty requires expression they never
3647 // wrote.
3648 Braces.consumeClose();
3649 Actions.ActOnFinishRequiresExpr();
3650 return ExprError();
3651 }
3652 }
3653 Braces.consumeClose();
3654 Actions.ActOnFinishRequiresExpr();
3655 return Actions.ActOnRequiresExpr(RequiresKWLoc, Body, LocalParameterDecls,
3656 Requirements, Braces.getCloseLocation());
3657}
3658
3659static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
3660 switch (kind) {
3661 default: llvm_unreachable("Not a known type trait")::llvm::llvm_unreachable_internal("Not a known type trait", "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3661)
;
3662#define TYPE_TRAIT_1(Spelling, Name, Key) \
3663case tok::kw_ ## Spelling: return UTT_ ## Name;
3664#define TYPE_TRAIT_2(Spelling, Name, Key) \
3665case tok::kw_ ## Spelling: return BTT_ ## Name;
3666#include "clang/Basic/TokenKinds.def"
3667#define TYPE_TRAIT_N(Spelling, Name, Key) \
3668 case tok::kw_ ## Spelling: return TT_ ## Name;
3669#include "clang/Basic/TokenKinds.def"
3670 }
3671}
3672
3673static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
3674 switch (kind) {
3675 default:
3676 llvm_unreachable("Not a known array type trait")::llvm::llvm_unreachable_internal("Not a known array type trait"
, "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3676)
;
3677#define ARRAY_TYPE_TRAIT(Spelling, Name, Key) \
3678 case tok::kw_##Spelling: \
3679 return ATT_##Name;
3680#include "clang/Basic/TokenKinds.def"
3681 }
3682}
3683
3684static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
3685 switch (kind) {
3686 default:
3687 llvm_unreachable("Not a known unary expression trait.")::llvm::llvm_unreachable_internal("Not a known unary expression trait."
, "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3687)
;
3688#define EXPRESSION_TRAIT(Spelling, Name, Key) \
3689 case tok::kw_##Spelling: \
3690 return ET_##Name;
3691#include "clang/Basic/TokenKinds.def"
3692 }
3693}
3694
3695static unsigned TypeTraitArity(tok::TokenKind kind) {
3696 switch (kind) {
3697 default: llvm_unreachable("Not a known type trait")::llvm::llvm_unreachable_internal("Not a known type trait", "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3697)
;
3698#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3699#include "clang/Basic/TokenKinds.def"
3700 }
3701}
3702
3703/// Parse the built-in type-trait pseudo-functions that allow
3704/// implementation of the TR1/C++11 type traits templates.
3705///
3706/// primary-expression:
3707/// unary-type-trait '(' type-id ')'
3708/// binary-type-trait '(' type-id ',' type-id ')'
3709/// type-trait '(' type-id-seq ')'
3710///
3711/// type-id-seq:
3712/// type-id ...[opt] type-id-seq[opt]
3713///
3714ExprResult Parser::ParseTypeTrait() {
3715 tok::TokenKind Kind = Tok.getKind();
3716 unsigned Arity = TypeTraitArity(Kind);
3717
3718 SourceLocation Loc = ConsumeToken();
3719
3720 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3721 if (Parens.expectAndConsume())
3722 return ExprError();
3723
3724 SmallVector<ParsedType, 2> Args;
3725 do {
3726 // Parse the next type.
3727 TypeResult Ty = ParseTypeName();
3728 if (Ty.isInvalid()) {
3729 Parens.skipToEnd();
3730 return ExprError();
3731 }
3732
3733 // Parse the ellipsis, if present.
3734 if (Tok.is(tok::ellipsis)) {
3735 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3736 if (Ty.isInvalid()) {
3737 Parens.skipToEnd();
3738 return ExprError();
3739 }
3740 }
3741
3742 // Add this type to the list of arguments.
3743 Args.push_back(Ty.get());
3744 } while (TryConsumeToken(tok::comma));
3745
3746 if (Parens.consumeClose())
3747 return ExprError();
3748
3749 SourceLocation EndLoc = Parens.getCloseLocation();
3750
3751 if (Arity && Args.size() != Arity) {
3752 Diag(EndLoc, diag::err_type_trait_arity)
3753 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3754 return ExprError();
3755 }
3756
3757 if (!Arity && Args.empty()) {
3758 Diag(EndLoc, diag::err_type_trait_arity)
3759 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3760 return ExprError();
3761 }
3762
3763 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3764}
3765
3766/// ParseArrayTypeTrait - Parse the built-in array type-trait
3767/// pseudo-functions.
3768///
3769/// primary-expression:
3770/// [Embarcadero] '__array_rank' '(' type-id ')'
3771/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3772///
3773ExprResult Parser::ParseArrayTypeTrait() {
3774 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3775 SourceLocation Loc = ConsumeToken();
3776
3777 BalancedDelimiterTracker T(*this, tok::l_paren);
3778 if (T.expectAndConsume())
3779 return ExprError();
3780
3781 TypeResult Ty = ParseTypeName();
3782 if (Ty.isInvalid()) {
3783 SkipUntil(tok::comma, StopAtSemi);
3784 SkipUntil(tok::r_paren, StopAtSemi);
3785 return ExprError();
3786 }
3787
3788 switch (ATT) {
3789 case ATT_ArrayRank: {
3790 T.consumeClose();
3791 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3792 T.getCloseLocation());
3793 }
3794 case ATT_ArrayExtent: {
3795 if (ExpectAndConsume(tok::comma)) {
3796 SkipUntil(tok::r_paren, StopAtSemi);
3797 return ExprError();
3798 }
3799
3800 ExprResult DimExpr = ParseExpression();
3801 T.consumeClose();
3802
3803 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3804 T.getCloseLocation());
3805 }
3806 }
3807 llvm_unreachable("Invalid ArrayTypeTrait!")::llvm::llvm_unreachable_internal("Invalid ArrayTypeTrait!", "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3807)
;
3808}
3809
3810/// ParseExpressionTrait - Parse built-in expression-trait
3811/// pseudo-functions like __is_lvalue_expr( xxx ).
3812///
3813/// primary-expression:
3814/// [Embarcadero] expression-trait '(' expression ')'
3815///
3816ExprResult Parser::ParseExpressionTrait() {
3817 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3818 SourceLocation Loc = ConsumeToken();
3819
3820 BalancedDelimiterTracker T(*this, tok::l_paren);
3821 if (T.expectAndConsume())
3822 return ExprError();
3823
3824 ExprResult Expr = ParseExpression();
3825
3826 T.consumeClose();
3827
3828 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3829 T.getCloseLocation());
3830}
3831
3832
3833/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3834/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3835/// based on the context past the parens.
3836ExprResult
3837Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3838 ParsedType &CastTy,
3839 BalancedDelimiterTracker &Tracker,
3840 ColonProtectionRAIIObject &ColonProt) {
3841 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3841, __PRETTY_FUNCTION__))
;
3842 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3842, __PRETTY_FUNCTION__))
;
3843 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3843, __PRETTY_FUNCTION__))
;
3844
3845 ExprResult Result(true);
3846 CastTy = nullptr;
3847
3848 // We need to disambiguate a very ugly part of the C++ syntax:
3849 //
3850 // (T())x; - type-id
3851 // (T())*x; - type-id
3852 // (T())/x; - expression
3853 // (T()); - expression
3854 //
3855 // The bad news is that we cannot use the specialized tentative parser, since
3856 // it can only verify that the thing inside the parens can be parsed as
3857 // type-id, it is not useful for determining the context past the parens.
3858 //
3859 // The good news is that the parser can disambiguate this part without
3860 // making any unnecessary Action calls.
3861 //
3862 // It uses a scheme similar to parsing inline methods. The parenthesized
3863 // tokens are cached, the context that follows is determined (possibly by
3864 // parsing a cast-expression), and then we re-introduce the cached tokens
3865 // into the token stream and parse them appropriately.
3866
3867 ParenParseOption ParseAs;
3868 CachedTokens Toks;
3869
3870 // Store the tokens of the parentheses. We will parse them after we determine
3871 // the context that follows them.
3872 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3873 // We didn't find the ')' we expected.
3874 Tracker.consumeClose();
3875 return ExprError();
3876 }
3877
3878 if (Tok.is(tok::l_brace)) {
3879 ParseAs = CompoundLiteral;
3880 } else {
3881 bool NotCastExpr;
3882 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3883 NotCastExpr = true;
3884 } else {
3885 // Try parsing the cast-expression that may follow.
3886 // If it is not a cast-expression, NotCastExpr will be true and no token
3887 // will be consumed.
3888 ColonProt.restore();
3889 Result = ParseCastExpression(AnyCastExpr,
3890 false/*isAddressofOperand*/,
3891 NotCastExpr,
3892 // type-id has priority.
3893 IsTypeCast);
3894 }
3895
3896 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3897 // an expression.
3898 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3899 }
3900
3901 // Create a fake EOF to mark end of Toks buffer.
3902 Token AttrEnd;
3903 AttrEnd.startToken();
3904 AttrEnd.setKind(tok::eof);
3905 AttrEnd.setLocation(Tok.getLocation());
3906 AttrEnd.setEofData(Toks.data());
3907 Toks.push_back(AttrEnd);
3908
3909 // The current token should go after the cached tokens.
3910 Toks.push_back(Tok);
3911 // Re-enter the stored parenthesized tokens into the token stream, so we may
3912 // parse them now.
3913 PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true,
3914 /*IsReinject*/ true);
3915 // Drop the current token and bring the first cached one. It's the same token
3916 // as when we entered this function.
3917 ConsumeAnyToken();
3918
3919 if (ParseAs >= CompoundLiteral) {
3920 // Parse the type declarator.
3921 DeclSpec DS(AttrFactory);
3922 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
3923 {
3924 ColonProtectionRAIIObject InnerColonProtection(*this);
3925 ParseSpecifierQualifierList(DS);
3926 ParseDeclarator(DeclaratorInfo);
3927 }
3928
3929 // Match the ')'.
3930 Tracker.consumeClose();
3931 ColonProt.restore();
3932
3933 // Consume EOF marker for Toks buffer.
3934 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3934, __PRETTY_FUNCTION__))
;
3935 ConsumeAnyToken();
3936
3937 if (ParseAs == CompoundLiteral) {
3938 ExprType = CompoundLiteral;
3939 if (DeclaratorInfo.isInvalidType())
3940 return ExprError();
3941
3942 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3943 return ParseCompoundLiteralExpression(Ty.get(),
3944 Tracker.getOpenLocation(),
3945 Tracker.getCloseLocation());
3946 }
3947
3948 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3949 assert(ParseAs == CastExpr)((ParseAs == CastExpr) ? static_cast<void> (0) : __assert_fail
("ParseAs == CastExpr", "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3949, __PRETTY_FUNCTION__))
;
3950
3951 if (DeclaratorInfo.isInvalidType())
3952 return ExprError();
3953
3954 // Result is what ParseCastExpression returned earlier.
3955 if (!Result.isInvalid())
3956 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3957 DeclaratorInfo, CastTy,
3958 Tracker.getCloseLocation(), Result.get());
3959 return Result;
3960 }
3961
3962 // Not a compound literal, and not followed by a cast-expression.
3963 assert(ParseAs == SimpleExpr)((ParseAs == SimpleExpr) ? static_cast<void> (0) : __assert_fail
("ParseAs == SimpleExpr", "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3963, __PRETTY_FUNCTION__))
;
3964
3965 ExprType = SimpleExpr;
3966 Result = ParseExpression();
3967 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3968 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3969 Tok.getLocation(), Result.get());
3970
3971 // Match the ')'.
3972 if (Result.isInvalid()) {
3973 while (Tok.isNot(tok::eof))
3974 ConsumeAnyToken();
3975 assert(Tok.getEofData() == AttrEnd.getEofData())((Tok.getEofData() == AttrEnd.getEofData()) ? static_cast<
void> (0) : __assert_fail ("Tok.getEofData() == AttrEnd.getEofData()"
, "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3975, __PRETTY_FUNCTION__))
;
3976 ConsumeAnyToken();
3977 return ExprError();
3978 }
3979
3980 Tracker.consumeClose();
3981 // Consume EOF marker for Toks buffer.
3982 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-12~++20210124100612+2afaf072f5c1/clang/lib/Parse/ParseExprCXX.cpp"
, 3982, __PRETTY_FUNCTION__))
;
3983 ConsumeAnyToken();
3984 return Result;
3985}
3986
3987/// Parse a __builtin_bit_cast(T, E).
3988ExprResult Parser::ParseBuiltinBitCast() {
3989 SourceLocation KWLoc = ConsumeToken();
3990
3991 BalancedDelimiterTracker T(*this, tok::l_paren);
3992 if (T.expectAndConsume(diag::err_expected_lparen_after, "__builtin_bit_cast"))
3993 return ExprError();
3994
3995 // Parse the common declaration-specifiers piece.
3996 DeclSpec DS(AttrFactory);
3997 ParseSpecifierQualifierList(DS);
3998
3999 // Parse the abstract-declarator, if present.
4000 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
4001 ParseDeclarator(DeclaratorInfo);
4002
4003 if (ExpectAndConsume(tok::comma)) {
4004 Diag(Tok.getLocation(), diag::err_expected) << tok::comma;
4005 SkipUntil(tok::r_paren, StopAtSemi);
4006 return ExprError();
4007 }
4008
4009 ExprResult Operand = ParseExpression();
4010
4011 if (T.consumeClose())
4012 return ExprError();
4013
4014 if (Operand.isInvalid() || DeclaratorInfo.isInvalidType())
4015 return ExprError();
4016
4017 return Actions.ActOnBuiltinBitCastExpr(KWLoc, DeclaratorInfo, Operand,
4018 T.getCloseLocation());
4019}

/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/clang/include/clang/Lex/Token.h"
, 197, __PRETTY_FUNCTION__))
;
198 assert(!PtrData)((!PtrData) ? static_cast<void> (0) : __assert_fail ("!PtrData"
, "/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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-12~++20210124100612+2afaf072f5c1/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