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