Bug Summary

File:tools/clang/lib/Parse/ParseExprCXX.cpp
Warning:line 1977, 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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -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~svn374877/build-llvm/tools/clang/lib/Parse -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Parse -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/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~svn374877/build-llvm/tools/clang/lib/Parse -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -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-2019-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Parse/ParseExprCXX.cpp

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

/build/llvm-toolchain-snapshot-10~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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~svn374877/tools/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