Bug Summary

File:clang/lib/Parse/ParseExprCXX.cpp
Warning:line 2000, 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-10/lib/clang/10.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-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Parse -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Parse -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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-10/lib/clang/10.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-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Parse -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -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-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Parse/ParseExprCXX.cpp

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

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