Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Parse -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Parse -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Parse -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Parse/ParseExprCXX.cpp

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

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