Bug Summary

File:clang/lib/Parse/ParseExprCXX.cpp
Warning:line 2037, 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 -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 CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/lib/Parse -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Parse -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/lib/Parse -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191=. -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-2020-11-21-121427-42170-1 -x c++ /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Parse/ParseExprCXX.cpp

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

/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/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