Bug Summary

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