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