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