Bug Summary

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

Annotated Source Code

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