Bug Summary

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