Bug Summary

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