clang API Documentation
00001 //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the Expression parsing implementation for C++. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Parse/ParseDiagnostic.h" 00015 #include "clang/Parse/Parser.h" 00016 #include "RAIIObjectsForParser.h" 00017 #include "clang/Basic/PrettyStackTrace.h" 00018 #include "clang/Lex/LiteralSupport.h" 00019 #include "clang/Sema/DeclSpec.h" 00020 #include "clang/Sema/Scope.h" 00021 #include "clang/Sema/ParsedTemplate.h" 00022 #include "llvm/Support/ErrorHandling.h" 00023 00024 using namespace clang; 00025 00026 static int SelectDigraphErrorMessage(tok::TokenKind Kind) { 00027 switch (Kind) { 00028 case tok::kw_template: return 0; 00029 case tok::kw_const_cast: return 1; 00030 case tok::kw_dynamic_cast: return 2; 00031 case tok::kw_reinterpret_cast: return 3; 00032 case tok::kw_static_cast: return 4; 00033 default: 00034 llvm_unreachable("Unknown type for digraph error message."); 00035 } 00036 } 00037 00038 // Are the two tokens adjacent in the same source file? 00039 static bool AreTokensAdjacent(Preprocessor &PP, Token &First, Token &Second) { 00040 SourceManager &SM = PP.getSourceManager(); 00041 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation()); 00042 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength()); 00043 return FirstEnd == SM.getSpellingLoc(Second.getLocation()); 00044 } 00045 00046 // Suggest fixit for "<::" after a cast. 00047 static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken, 00048 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) { 00049 // Pull '<:' and ':' off token stream. 00050 if (!AtDigraph) 00051 PP.Lex(DigraphToken); 00052 PP.Lex(ColonToken); 00053 00054 SourceRange Range; 00055 Range.setBegin(DigraphToken.getLocation()); 00056 Range.setEnd(ColonToken.getLocation()); 00057 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph) 00058 << SelectDigraphErrorMessage(Kind) 00059 << FixItHint::CreateReplacement(Range, "< ::"); 00060 00061 // Update token information to reflect their change in token type. 00062 ColonToken.setKind(tok::coloncolon); 00063 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1)); 00064 ColonToken.setLength(2); 00065 DigraphToken.setKind(tok::less); 00066 DigraphToken.setLength(1); 00067 00068 // Push new tokens back to token stream. 00069 PP.EnterToken(ColonToken); 00070 if (!AtDigraph) 00071 PP.EnterToken(DigraphToken); 00072 } 00073 00074 // Check for '<::' which should be '< ::' instead of '[:' when following 00075 // a template name. 00076 void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType, 00077 bool EnteringContext, 00078 IdentifierInfo &II, CXXScopeSpec &SS) { 00079 if (!Next.is(tok::l_square) || Next.getLength() != 2) 00080 return; 00081 00082 Token SecondToken = GetLookAheadToken(2); 00083 if (!SecondToken.is(tok::colon) || !AreTokensAdjacent(PP, Next, SecondToken)) 00084 return; 00085 00086 TemplateTy Template; 00087 UnqualifiedId TemplateName; 00088 TemplateName.setIdentifier(&II, Tok.getLocation()); 00089 bool MemberOfUnknownSpecialization; 00090 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false, 00091 TemplateName, ObjectType, EnteringContext, 00092 Template, MemberOfUnknownSpecialization)) 00093 return; 00094 00095 FixDigraph(*this, PP, Next, SecondToken, tok::kw_template, 00096 /*AtDigraph*/false); 00097 } 00098 00099 /// \brief Parse global scope or nested-name-specifier if present. 00100 /// 00101 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which 00102 /// may be preceded by '::'). Note that this routine will not parse ::new or 00103 /// ::delete; it will just leave them in the token stream. 00104 /// 00105 /// '::'[opt] nested-name-specifier 00106 /// '::' 00107 /// 00108 /// nested-name-specifier: 00109 /// type-name '::' 00110 /// namespace-name '::' 00111 /// nested-name-specifier identifier '::' 00112 /// nested-name-specifier 'template'[opt] simple-template-id '::' 00113 /// 00114 /// 00115 /// \param SS the scope specifier that will be set to the parsed 00116 /// nested-name-specifier (or empty) 00117 /// 00118 /// \param ObjectType if this nested-name-specifier is being parsed following 00119 /// the "." or "->" of a member access expression, this parameter provides the 00120 /// type of the object whose members are being accessed. 00121 /// 00122 /// \param EnteringContext whether we will be entering into the context of 00123 /// the nested-name-specifier after parsing it. 00124 /// 00125 /// \param MayBePseudoDestructor When non-NULL, points to a flag that 00126 /// indicates whether this nested-name-specifier may be part of a 00127 /// pseudo-destructor name. In this case, the flag will be set false 00128 /// if we don't actually end up parsing a destructor name. Moreorover, 00129 /// if we do end up determining that we are parsing a destructor name, 00130 /// the last component of the nested-name-specifier is not parsed as 00131 /// part of the scope specifier. 00132 00133 /// member access expression, e.g., the \p T:: in \p p->T::m. 00134 /// 00135 /// \returns true if there was an error parsing a scope specifier 00136 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, 00137 ParsedType ObjectType, 00138 bool EnteringContext, 00139 bool *MayBePseudoDestructor, 00140 bool IsTypename) { 00141 assert(getLangOpts().CPlusPlus && 00142 "Call sites of this function should be guarded by checking for C++"); 00143 00144 if (Tok.is(tok::annot_cxxscope)) { 00145 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 00146 Tok.getAnnotationRange(), 00147 SS); 00148 ConsumeToken(); 00149 return false; 00150 } 00151 00152 bool HasScopeSpecifier = false; 00153 00154 if (Tok.is(tok::coloncolon)) { 00155 // ::new and ::delete aren't nested-name-specifiers. 00156 tok::TokenKind NextKind = NextToken().getKind(); 00157 if (NextKind == tok::kw_new || NextKind == tok::kw_delete) 00158 return false; 00159 00160 // '::' - Global scope qualifier. 00161 if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS)) 00162 return true; 00163 00164 HasScopeSpecifier = true; 00165 } 00166 00167 bool CheckForDestructor = false; 00168 if (MayBePseudoDestructor && *MayBePseudoDestructor) { 00169 CheckForDestructor = true; 00170 *MayBePseudoDestructor = false; 00171 } 00172 00173 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) { 00174 DeclSpec DS(AttrFactory); 00175 SourceLocation DeclLoc = Tok.getLocation(); 00176 SourceLocation EndLoc = ParseDecltypeSpecifier(DS); 00177 if (Tok.isNot(tok::coloncolon)) { 00178 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc); 00179 return false; 00180 } 00181 00182 SourceLocation CCLoc = ConsumeToken(); 00183 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc)) 00184 SS.SetInvalid(SourceRange(DeclLoc, CCLoc)); 00185 00186 HasScopeSpecifier = true; 00187 } 00188 00189 while (true) { 00190 if (HasScopeSpecifier) { 00191 // C++ [basic.lookup.classref]p5: 00192 // If the qualified-id has the form 00193 // 00194 // ::class-name-or-namespace-name::... 00195 // 00196 // the class-name-or-namespace-name is looked up in global scope as a 00197 // class-name or namespace-name. 00198 // 00199 // To implement this, we clear out the object type as soon as we've 00200 // seen a leading '::' or part of a nested-name-specifier. 00201 ObjectType = ParsedType(); 00202 00203 if (Tok.is(tok::code_completion)) { 00204 // Code completion for a nested-name-specifier, where the code 00205 // code completion token follows the '::'. 00206 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext); 00207 // Include code completion token into the range of the scope otherwise 00208 // when we try to annotate the scope tokens the dangling code completion 00209 // token will cause assertion in 00210 // Preprocessor::AnnotatePreviousCachedTokens. 00211 SS.setEndLoc(Tok.getLocation()); 00212 cutOffParsing(); 00213 return true; 00214 } 00215 } 00216 00217 // nested-name-specifier: 00218 // nested-name-specifier 'template'[opt] simple-template-id '::' 00219 00220 // Parse the optional 'template' keyword, then make sure we have 00221 // 'identifier <' after it. 00222 if (Tok.is(tok::kw_template)) { 00223 // If we don't have a scope specifier or an object type, this isn't a 00224 // nested-name-specifier, since they aren't allowed to start with 00225 // 'template'. 00226 if (!HasScopeSpecifier && !ObjectType) 00227 break; 00228 00229 TentativeParsingAction TPA(*this); 00230 SourceLocation TemplateKWLoc = ConsumeToken(); 00231 00232 UnqualifiedId TemplateName; 00233 if (Tok.is(tok::identifier)) { 00234 // Consume the identifier. 00235 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 00236 ConsumeToken(); 00237 } else if (Tok.is(tok::kw_operator)) { 00238 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, 00239 TemplateName)) { 00240 TPA.Commit(); 00241 break; 00242 } 00243 00244 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId && 00245 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) { 00246 Diag(TemplateName.getSourceRange().getBegin(), 00247 diag::err_id_after_template_in_nested_name_spec) 00248 << TemplateName.getSourceRange(); 00249 TPA.Commit(); 00250 break; 00251 } 00252 } else { 00253 TPA.Revert(); 00254 break; 00255 } 00256 00257 // If the next token is not '<', we have a qualified-id that refers 00258 // to a template name, such as T::template apply, but is not a 00259 // template-id. 00260 if (Tok.isNot(tok::less)) { 00261 TPA.Revert(); 00262 break; 00263 } 00264 00265 // Commit to parsing the template-id. 00266 TPA.Commit(); 00267 TemplateTy Template; 00268 if (TemplateNameKind TNK 00269 = Actions.ActOnDependentTemplateName(getCurScope(), 00270 SS, TemplateKWLoc, TemplateName, 00271 ObjectType, EnteringContext, 00272 Template)) { 00273 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc, 00274 TemplateName, false)) 00275 return true; 00276 } else 00277 return true; 00278 00279 continue; 00280 } 00281 00282 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) { 00283 // We have 00284 // 00285 // simple-template-id '::' 00286 // 00287 // So we need to check whether the simple-template-id is of the 00288 // right kind (it should name a type or be dependent), and then 00289 // convert it into a type within the nested-name-specifier. 00290 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 00291 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) { 00292 *MayBePseudoDestructor = true; 00293 return false; 00294 } 00295 00296 // Consume the template-id token. 00297 ConsumeToken(); 00298 00299 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!"); 00300 SourceLocation CCLoc = ConsumeToken(); 00301 00302 HasScopeSpecifier = true; 00303 00304 ASTTemplateArgsPtr TemplateArgsPtr(Actions, 00305 TemplateId->getTemplateArgs(), 00306 TemplateId->NumArgs); 00307 00308 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), 00309 SS, 00310 TemplateId->TemplateKWLoc, 00311 TemplateId->Template, 00312 TemplateId->TemplateNameLoc, 00313 TemplateId->LAngleLoc, 00314 TemplateArgsPtr, 00315 TemplateId->RAngleLoc, 00316 CCLoc, 00317 EnteringContext)) { 00318 SourceLocation StartLoc 00319 = SS.getBeginLoc().isValid()? SS.getBeginLoc() 00320 : TemplateId->TemplateNameLoc; 00321 SS.SetInvalid(SourceRange(StartLoc, CCLoc)); 00322 } 00323 00324 continue; 00325 } 00326 00327 00328 // The rest of the nested-name-specifier possibilities start with 00329 // tok::identifier. 00330 if (Tok.isNot(tok::identifier)) 00331 break; 00332 00333 IdentifierInfo &II = *Tok.getIdentifierInfo(); 00334 00335 // nested-name-specifier: 00336 // type-name '::' 00337 // namespace-name '::' 00338 // nested-name-specifier identifier '::' 00339 Token Next = NextToken(); 00340 00341 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover 00342 // and emit a fixit hint for it. 00343 if (Next.is(tok::colon) && !ColonIsSacred) { 00344 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II, 00345 Tok.getLocation(), 00346 Next.getLocation(), ObjectType, 00347 EnteringContext) && 00348 // If the token after the colon isn't an identifier, it's still an 00349 // error, but they probably meant something else strange so don't 00350 // recover like this. 00351 PP.LookAhead(1).is(tok::identifier)) { 00352 Diag(Next, diag::err_unexected_colon_in_nested_name_spec) 00353 << FixItHint::CreateReplacement(Next.getLocation(), "::"); 00354 00355 // Recover as if the user wrote '::'. 00356 Next.setKind(tok::coloncolon); 00357 } 00358 } 00359 00360 if (Next.is(tok::coloncolon)) { 00361 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) && 00362 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(), 00363 II, ObjectType)) { 00364 *MayBePseudoDestructor = true; 00365 return false; 00366 } 00367 00368 // We have an identifier followed by a '::'. Lookup this name 00369 // as the name in a nested-name-specifier. 00370 SourceLocation IdLoc = ConsumeToken(); 00371 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) && 00372 "NextToken() not working properly!"); 00373 SourceLocation CCLoc = ConsumeToken(); 00374 00375 HasScopeSpecifier = true; 00376 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc, 00377 ObjectType, EnteringContext, SS)) 00378 SS.SetInvalid(SourceRange(IdLoc, CCLoc)); 00379 00380 continue; 00381 } 00382 00383 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS); 00384 00385 // nested-name-specifier: 00386 // type-name '<' 00387 if (Next.is(tok::less)) { 00388 TemplateTy Template; 00389 UnqualifiedId TemplateName; 00390 TemplateName.setIdentifier(&II, Tok.getLocation()); 00391 bool MemberOfUnknownSpecialization; 00392 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS, 00393 /*hasTemplateKeyword=*/false, 00394 TemplateName, 00395 ObjectType, 00396 EnteringContext, 00397 Template, 00398 MemberOfUnknownSpecialization)) { 00399 // We have found a template name, so annotate this token 00400 // with a template-id annotation. We do not permit the 00401 // template-id to be translated into a type annotation, 00402 // because some clients (e.g., the parsing of class template 00403 // specializations) still want to see the original template-id 00404 // token. 00405 ConsumeToken(); 00406 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), 00407 TemplateName, false)) 00408 return true; 00409 continue; 00410 } 00411 00412 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) && 00413 (IsTypename || IsTemplateArgumentList(1))) { 00414 // We have something like t::getAs<T>, where getAs is a 00415 // member of an unknown specialization. However, this will only 00416 // parse correctly as a template, so suggest the keyword 'template' 00417 // before 'getAs' and treat this as a dependent template name. 00418 unsigned DiagID = diag::err_missing_dependent_template_keyword; 00419 if (getLangOpts().MicrosoftExt) 00420 DiagID = diag::warn_missing_dependent_template_keyword; 00421 00422 Diag(Tok.getLocation(), DiagID) 00423 << II.getName() 00424 << FixItHint::CreateInsertion(Tok.getLocation(), "template "); 00425 00426 if (TemplateNameKind TNK 00427 = Actions.ActOnDependentTemplateName(getCurScope(), 00428 SS, SourceLocation(), 00429 TemplateName, ObjectType, 00430 EnteringContext, Template)) { 00431 // Consume the identifier. 00432 ConsumeToken(); 00433 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), 00434 TemplateName, false)) 00435 return true; 00436 } 00437 else 00438 return true; 00439 00440 continue; 00441 } 00442 } 00443 00444 // We don't have any tokens that form the beginning of a 00445 // nested-name-specifier, so we're done. 00446 break; 00447 } 00448 00449 // Even if we didn't see any pieces of a nested-name-specifier, we 00450 // still check whether there is a tilde in this position, which 00451 // indicates a potential pseudo-destructor. 00452 if (CheckForDestructor && Tok.is(tok::tilde)) 00453 *MayBePseudoDestructor = true; 00454 00455 return false; 00456 } 00457 00458 /// ParseCXXIdExpression - Handle id-expression. 00459 /// 00460 /// id-expression: 00461 /// unqualified-id 00462 /// qualified-id 00463 /// 00464 /// qualified-id: 00465 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id 00466 /// '::' identifier 00467 /// '::' operator-function-id 00468 /// '::' template-id 00469 /// 00470 /// NOTE: The standard specifies that, for qualified-id, the parser does not 00471 /// expect: 00472 /// 00473 /// '::' conversion-function-id 00474 /// '::' '~' class-name 00475 /// 00476 /// This may cause a slight inconsistency on diagnostics: 00477 /// 00478 /// class C {}; 00479 /// namespace A {} 00480 /// void f() { 00481 /// :: A :: ~ C(); // Some Sema error about using destructor with a 00482 /// // namespace. 00483 /// :: ~ C(); // Some Parser error like 'unexpected ~'. 00484 /// } 00485 /// 00486 /// We simplify the parser a bit and make it work like: 00487 /// 00488 /// qualified-id: 00489 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id 00490 /// '::' unqualified-id 00491 /// 00492 /// That way Sema can handle and report similar errors for namespaces and the 00493 /// global scope. 00494 /// 00495 /// The isAddressOfOperand parameter indicates that this id-expression is a 00496 /// direct operand of the address-of operator. This is, besides member contexts, 00497 /// the only place where a qualified-id naming a non-static class member may 00498 /// appear. 00499 /// 00500 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) { 00501 // qualified-id: 00502 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id 00503 // '::' unqualified-id 00504 // 00505 CXXScopeSpec SS; 00506 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 00507 00508 SourceLocation TemplateKWLoc; 00509 UnqualifiedId Name; 00510 if (ParseUnqualifiedId(SS, 00511 /*EnteringContext=*/false, 00512 /*AllowDestructorName=*/false, 00513 /*AllowConstructorName=*/false, 00514 /*ObjectType=*/ ParsedType(), 00515 TemplateKWLoc, 00516 Name)) 00517 return ExprError(); 00518 00519 // This is only the direct operand of an & operator if it is not 00520 // followed by a postfix-expression suffix. 00521 if (isAddressOfOperand && isPostfixExpressionSuffixStart()) 00522 isAddressOfOperand = false; 00523 00524 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name, 00525 Tok.is(tok::l_paren), isAddressOfOperand); 00526 } 00527 00528 /// ParseLambdaExpression - Parse a C++0x lambda expression. 00529 /// 00530 /// lambda-expression: 00531 /// lambda-introducer lambda-declarator[opt] compound-statement 00532 /// 00533 /// lambda-introducer: 00534 /// '[' lambda-capture[opt] ']' 00535 /// 00536 /// lambda-capture: 00537 /// capture-default 00538 /// capture-list 00539 /// capture-default ',' capture-list 00540 /// 00541 /// capture-default: 00542 /// '&' 00543 /// '=' 00544 /// 00545 /// capture-list: 00546 /// capture 00547 /// capture-list ',' capture 00548 /// 00549 /// capture: 00550 /// identifier 00551 /// '&' identifier 00552 /// 'this' 00553 /// 00554 /// lambda-declarator: 00555 /// '(' parameter-declaration-clause ')' attribute-specifier[opt] 00556 /// 'mutable'[opt] exception-specification[opt] 00557 /// trailing-return-type[opt] 00558 /// 00559 ExprResult Parser::ParseLambdaExpression() { 00560 // Parse lambda-introducer. 00561 LambdaIntroducer Intro; 00562 00563 llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro)); 00564 if (DiagID) { 00565 Diag(Tok, DiagID.getValue()); 00566 SkipUntil(tok::r_square); 00567 SkipUntil(tok::l_brace); 00568 SkipUntil(tok::r_brace); 00569 return ExprError(); 00570 } 00571 00572 return ParseLambdaExpressionAfterIntroducer(Intro); 00573 } 00574 00575 /// TryParseLambdaExpression - Use lookahead and potentially tentative 00576 /// parsing to determine if we are looking at a C++0x lambda expression, and parse 00577 /// it if we are. 00578 /// 00579 /// If we are not looking at a lambda expression, returns ExprError(). 00580 ExprResult Parser::TryParseLambdaExpression() { 00581 assert(getLangOpts().CPlusPlus0x 00582 && Tok.is(tok::l_square) 00583 && "Not at the start of a possible lambda expression."); 00584 00585 const Token Next = NextToken(), After = GetLookAheadToken(2); 00586 00587 // If lookahead indicates this is a lambda... 00588 if (Next.is(tok::r_square) || // [] 00589 Next.is(tok::equal) || // [= 00590 (Next.is(tok::amp) && // [&] or [&, 00591 (After.is(tok::r_square) || 00592 After.is(tok::comma))) || 00593 (Next.is(tok::identifier) && // [identifier] 00594 After.is(tok::r_square))) { 00595 return ParseLambdaExpression(); 00596 } 00597 00598 // If lookahead indicates an ObjC message send... 00599 // [identifier identifier 00600 if (Next.is(tok::identifier) && After.is(tok::identifier)) { 00601 return ExprEmpty(); 00602 } 00603 00604 // Here, we're stuck: lambda introducers and Objective-C message sends are 00605 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a 00606 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of 00607 // writing two routines to parse a lambda introducer, just try to parse 00608 // a lambda introducer first, and fall back if that fails. 00609 // (TryParseLambdaIntroducer never produces any diagnostic output.) 00610 LambdaIntroducer Intro; 00611 if (TryParseLambdaIntroducer(Intro)) 00612 return ExprEmpty(); 00613 return ParseLambdaExpressionAfterIntroducer(Intro); 00614 } 00615 00616 /// ParseLambdaExpression - Parse a lambda introducer. 00617 /// 00618 /// Returns a DiagnosticID if it hit something unexpected. 00619 llvm::Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro){ 00620 typedef llvm::Optional<unsigned> DiagResult; 00621 00622 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['."); 00623 BalancedDelimiterTracker T(*this, tok::l_square); 00624 T.consumeOpen(); 00625 00626 Intro.Range.setBegin(T.getOpenLocation()); 00627 00628 bool first = true; 00629 00630 // Parse capture-default. 00631 if (Tok.is(tok::amp) && 00632 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) { 00633 Intro.Default = LCD_ByRef; 00634 Intro.DefaultLoc = ConsumeToken(); 00635 first = false; 00636 } else if (Tok.is(tok::equal)) { 00637 Intro.Default = LCD_ByCopy; 00638 Intro.DefaultLoc = ConsumeToken(); 00639 first = false; 00640 } 00641 00642 while (Tok.isNot(tok::r_square)) { 00643 if (!first) { 00644 if (Tok.isNot(tok::comma)) { 00645 if (Tok.is(tok::code_completion)) { 00646 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, 00647 /*AfterAmpersand=*/false); 00648 ConsumeCodeCompletionToken(); 00649 break; 00650 } 00651 00652 return DiagResult(diag::err_expected_comma_or_rsquare); 00653 } 00654 ConsumeToken(); 00655 } 00656 00657 if (Tok.is(tok::code_completion)) { 00658 // If we're in Objective-C++ and we have a bare '[', then this is more 00659 // likely to be a message receiver. 00660 if (getLangOpts().ObjC1 && first) 00661 Actions.CodeCompleteObjCMessageReceiver(getCurScope()); 00662 else 00663 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, 00664 /*AfterAmpersand=*/false); 00665 ConsumeCodeCompletionToken(); 00666 break; 00667 } 00668 00669 first = false; 00670 00671 // Parse capture. 00672 LambdaCaptureKind Kind = LCK_ByCopy; 00673 SourceLocation Loc; 00674 IdentifierInfo* Id = 0; 00675 SourceLocation EllipsisLoc; 00676 00677 if (Tok.is(tok::kw_this)) { 00678 Kind = LCK_This; 00679 Loc = ConsumeToken(); 00680 } else { 00681 if (Tok.is(tok::amp)) { 00682 Kind = LCK_ByRef; 00683 ConsumeToken(); 00684 00685 if (Tok.is(tok::code_completion)) { 00686 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, 00687 /*AfterAmpersand=*/true); 00688 ConsumeCodeCompletionToken(); 00689 break; 00690 } 00691 } 00692 00693 if (Tok.is(tok::identifier)) { 00694 Id = Tok.getIdentifierInfo(); 00695 Loc = ConsumeToken(); 00696 00697 if (Tok.is(tok::ellipsis)) 00698 EllipsisLoc = ConsumeToken(); 00699 } else if (Tok.is(tok::kw_this)) { 00700 // FIXME: If we want to suggest a fixit here, will need to return more 00701 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be 00702 // Clear()ed to prevent emission in case of tentative parsing? 00703 return DiagResult(diag::err_this_captured_by_reference); 00704 } else { 00705 return DiagResult(diag::err_expected_capture); 00706 } 00707 } 00708 00709 Intro.addCapture(Kind, Loc, Id, EllipsisLoc); 00710 } 00711 00712 T.consumeClose(); 00713 Intro.Range.setEnd(T.getCloseLocation()); 00714 00715 return DiagResult(); 00716 } 00717 00718 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer. 00719 /// 00720 /// Returns true if it hit something unexpected. 00721 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) { 00722 TentativeParsingAction PA(*this); 00723 00724 llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro)); 00725 00726 if (DiagID) { 00727 PA.Revert(); 00728 return true; 00729 } 00730 00731 PA.Commit(); 00732 return false; 00733 } 00734 00735 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda 00736 /// expression. 00737 ExprResult Parser::ParseLambdaExpressionAfterIntroducer( 00738 LambdaIntroducer &Intro) { 00739 SourceLocation LambdaBeginLoc = Intro.Range.getBegin(); 00740 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda); 00741 00742 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc, 00743 "lambda expression parsing"); 00744 00745 // Parse lambda-declarator[opt]. 00746 DeclSpec DS(AttrFactory); 00747 Declarator D(DS, Declarator::LambdaExprContext); 00748 00749 if (Tok.is(tok::l_paren)) { 00750 ParseScope PrototypeScope(this, 00751 Scope::FunctionPrototypeScope | 00752 Scope::DeclScope); 00753 00754 SourceLocation DeclLoc, DeclEndLoc; 00755 BalancedDelimiterTracker T(*this, tok::l_paren); 00756 T.consumeOpen(); 00757 DeclLoc = T.getOpenLocation(); 00758 00759 // Parse parameter-declaration-clause. 00760 ParsedAttributes Attr(AttrFactory); 00761 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 00762 SourceLocation EllipsisLoc; 00763 00764 if (Tok.isNot(tok::r_paren)) 00765 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc); 00766 00767 T.consumeClose(); 00768 DeclEndLoc = T.getCloseLocation(); 00769 00770 // Parse 'mutable'[opt]. 00771 SourceLocation MutableLoc; 00772 if (Tok.is(tok::kw_mutable)) { 00773 MutableLoc = ConsumeToken(); 00774 DeclEndLoc = MutableLoc; 00775 } 00776 00777 // Parse exception-specification[opt]. 00778 ExceptionSpecificationType ESpecType = EST_None; 00779 SourceRange ESpecRange; 00780 llvm::SmallVector<ParsedType, 2> DynamicExceptions; 00781 llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges; 00782 ExprResult NoexceptExpr; 00783 ESpecType = tryParseExceptionSpecification(ESpecRange, 00784 DynamicExceptions, 00785 DynamicExceptionRanges, 00786 NoexceptExpr); 00787 00788 if (ESpecType != EST_None) 00789 DeclEndLoc = ESpecRange.getEnd(); 00790 00791 // Parse attribute-specifier[opt]. 00792 MaybeParseCXX0XAttributes(Attr, &DeclEndLoc); 00793 00794 // Parse trailing-return-type[opt]. 00795 ParsedType TrailingReturnType; 00796 if (Tok.is(tok::arrow)) { 00797 SourceRange Range; 00798 TrailingReturnType = ParseTrailingReturnType(Range).get(); 00799 if (Range.getEnd().isValid()) 00800 DeclEndLoc = Range.getEnd(); 00801 } 00802 00803 PrototypeScope.Exit(); 00804 00805 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true, 00806 /*isVariadic=*/EllipsisLoc.isValid(), 00807 EllipsisLoc, 00808 ParamInfo.data(), ParamInfo.size(), 00809 DS.getTypeQualifiers(), 00810 /*RefQualifierIsLValueRef=*/true, 00811 /*RefQualifierLoc=*/SourceLocation(), 00812 /*ConstQualifierLoc=*/SourceLocation(), 00813 /*VolatileQualifierLoc=*/SourceLocation(), 00814 MutableLoc, 00815 ESpecType, ESpecRange.getBegin(), 00816 DynamicExceptions.data(), 00817 DynamicExceptionRanges.data(), 00818 DynamicExceptions.size(), 00819 NoexceptExpr.isUsable() ? 00820 NoexceptExpr.get() : 0, 00821 DeclLoc, DeclEndLoc, D, 00822 TrailingReturnType), 00823 Attr, DeclEndLoc); 00824 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow)) { 00825 // It's common to forget that one needs '()' before 'mutable' or the 00826 // result type. Deal with this. 00827 Diag(Tok, diag::err_lambda_missing_parens) 00828 << Tok.is(tok::arrow) 00829 << FixItHint::CreateInsertion(Tok.getLocation(), "() "); 00830 SourceLocation DeclLoc = Tok.getLocation(); 00831 SourceLocation DeclEndLoc = DeclLoc; 00832 00833 // Parse 'mutable', if it's there. 00834 SourceLocation MutableLoc; 00835 if (Tok.is(tok::kw_mutable)) { 00836 MutableLoc = ConsumeToken(); 00837 DeclEndLoc = MutableLoc; 00838 } 00839 00840 // Parse the return type, if there is one. 00841 ParsedType TrailingReturnType; 00842 if (Tok.is(tok::arrow)) { 00843 SourceRange Range; 00844 TrailingReturnType = ParseTrailingReturnType(Range).get(); 00845 if (Range.getEnd().isValid()) 00846 DeclEndLoc = Range.getEnd(); 00847 } 00848 00849 ParsedAttributes Attr(AttrFactory); 00850 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true, 00851 /*isVariadic=*/false, 00852 /*EllipsisLoc=*/SourceLocation(), 00853 /*Params=*/0, /*NumParams=*/0, 00854 /*TypeQuals=*/0, 00855 /*RefQualifierIsLValueRef=*/true, 00856 /*RefQualifierLoc=*/SourceLocation(), 00857 /*ConstQualifierLoc=*/SourceLocation(), 00858 /*VolatileQualifierLoc=*/SourceLocation(), 00859 MutableLoc, 00860 EST_None, 00861 /*ESpecLoc=*/SourceLocation(), 00862 /*Exceptions=*/0, 00863 /*ExceptionRanges=*/0, 00864 /*NumExceptions=*/0, 00865 /*NoexceptExpr=*/0, 00866 DeclLoc, DeclEndLoc, D, 00867 TrailingReturnType), 00868 Attr, DeclEndLoc); 00869 } 00870 00871 00872 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using 00873 // it. 00874 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope; 00875 ParseScope BodyScope(this, ScopeFlags); 00876 00877 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope()); 00878 00879 // Parse compound-statement. 00880 if (!Tok.is(tok::l_brace)) { 00881 Diag(Tok, diag::err_expected_lambda_body); 00882 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope()); 00883 return ExprError(); 00884 } 00885 00886 StmtResult Stmt(ParseCompoundStatementBody()); 00887 BodyScope.Exit(); 00888 00889 if (!Stmt.isInvalid()) 00890 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.take(), getCurScope()); 00891 00892 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope()); 00893 return ExprError(); 00894 } 00895 00896 /// ParseCXXCasts - This handles the various ways to cast expressions to another 00897 /// type. 00898 /// 00899 /// postfix-expression: [C++ 5.2p1] 00900 /// 'dynamic_cast' '<' type-name '>' '(' expression ')' 00901 /// 'static_cast' '<' type-name '>' '(' expression ')' 00902 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')' 00903 /// 'const_cast' '<' type-name '>' '(' expression ')' 00904 /// 00905 ExprResult Parser::ParseCXXCasts() { 00906 tok::TokenKind Kind = Tok.getKind(); 00907 const char *CastName = 0; // For error messages 00908 00909 switch (Kind) { 00910 default: llvm_unreachable("Unknown C++ cast!"); 00911 case tok::kw_const_cast: CastName = "const_cast"; break; 00912 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break; 00913 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break; 00914 case tok::kw_static_cast: CastName = "static_cast"; break; 00915 } 00916 00917 SourceLocation OpLoc = ConsumeToken(); 00918 SourceLocation LAngleBracketLoc = Tok.getLocation(); 00919 00920 // Check for "<::" which is parsed as "[:". If found, fix token stream, 00921 // diagnose error, suggest fix, and recover parsing. 00922 Token Next = NextToken(); 00923 if (Tok.is(tok::l_square) && Tok.getLength() == 2 && Next.is(tok::colon) && 00924 AreTokensAdjacent(PP, Tok, Next)) 00925 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true); 00926 00927 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName)) 00928 return ExprError(); 00929 00930 // Parse the common declaration-specifiers piece. 00931 DeclSpec DS(AttrFactory); 00932 ParseSpecifierQualifierList(DS); 00933 00934 // Parse the abstract-declarator, if present. 00935 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 00936 ParseDeclarator(DeclaratorInfo); 00937 00938 SourceLocation RAngleBracketLoc = Tok.getLocation(); 00939 00940 if (ExpectAndConsume(tok::greater, diag::err_expected_greater)) 00941 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<"); 00942 00943 SourceLocation LParenLoc, RParenLoc; 00944 BalancedDelimiterTracker T(*this, tok::l_paren); 00945 00946 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName)) 00947 return ExprError(); 00948 00949 ExprResult Result = ParseExpression(); 00950 00951 // Match the ')'. 00952 T.consumeClose(); 00953 00954 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType()) 00955 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind, 00956 LAngleBracketLoc, DeclaratorInfo, 00957 RAngleBracketLoc, 00958 T.getOpenLocation(), Result.take(), 00959 T.getCloseLocation()); 00960 00961 return move(Result); 00962 } 00963 00964 /// ParseCXXTypeid - This handles the C++ typeid expression. 00965 /// 00966 /// postfix-expression: [C++ 5.2p1] 00967 /// 'typeid' '(' expression ')' 00968 /// 'typeid' '(' type-id ')' 00969 /// 00970 ExprResult Parser::ParseCXXTypeid() { 00971 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!"); 00972 00973 SourceLocation OpLoc = ConsumeToken(); 00974 SourceLocation LParenLoc, RParenLoc; 00975 BalancedDelimiterTracker T(*this, tok::l_paren); 00976 00977 // typeid expressions are always parenthesized. 00978 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid")) 00979 return ExprError(); 00980 LParenLoc = T.getOpenLocation(); 00981 00982 ExprResult Result; 00983 00984 if (isTypeIdInParens()) { 00985 TypeResult Ty = ParseTypeName(); 00986 00987 // Match the ')'. 00988 T.consumeClose(); 00989 RParenLoc = T.getCloseLocation(); 00990 if (Ty.isInvalid() || RParenLoc.isInvalid()) 00991 return ExprError(); 00992 00993 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true, 00994 Ty.get().getAsOpaquePtr(), RParenLoc); 00995 } else { 00996 // C++0x [expr.typeid]p3: 00997 // When typeid is applied to an expression other than an lvalue of a 00998 // polymorphic class type [...] The expression is an unevaluated 00999 // operand (Clause 5). 01000 // 01001 // Note that we can't tell whether the expression is an lvalue of a 01002 // polymorphic class type until after we've parsed the expression; we 01003 // speculatively assume the subexpression is unevaluated, and fix it up 01004 // later. 01005 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 01006 Result = ParseExpression(); 01007 01008 // Match the ')'. 01009 if (Result.isInvalid()) 01010 SkipUntil(tok::r_paren); 01011 else { 01012 T.consumeClose(); 01013 RParenLoc = T.getCloseLocation(); 01014 if (RParenLoc.isInvalid()) 01015 return ExprError(); 01016 01017 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false, 01018 Result.release(), RParenLoc); 01019 } 01020 } 01021 01022 return move(Result); 01023 } 01024 01025 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression. 01026 /// 01027 /// '__uuidof' '(' expression ')' 01028 /// '__uuidof' '(' type-id ')' 01029 /// 01030 ExprResult Parser::ParseCXXUuidof() { 01031 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!"); 01032 01033 SourceLocation OpLoc = ConsumeToken(); 01034 BalancedDelimiterTracker T(*this, tok::l_paren); 01035 01036 // __uuidof expressions are always parenthesized. 01037 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof")) 01038 return ExprError(); 01039 01040 ExprResult Result; 01041 01042 if (isTypeIdInParens()) { 01043 TypeResult Ty = ParseTypeName(); 01044 01045 // Match the ')'. 01046 T.consumeClose(); 01047 01048 if (Ty.isInvalid()) 01049 return ExprError(); 01050 01051 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true, 01052 Ty.get().getAsOpaquePtr(), 01053 T.getCloseLocation()); 01054 } else { 01055 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 01056 Result = ParseExpression(); 01057 01058 // Match the ')'. 01059 if (Result.isInvalid()) 01060 SkipUntil(tok::r_paren); 01061 else { 01062 T.consumeClose(); 01063 01064 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), 01065 /*isType=*/false, 01066 Result.release(), T.getCloseLocation()); 01067 } 01068 } 01069 01070 return move(Result); 01071 } 01072 01073 /// \brief Parse a C++ pseudo-destructor expression after the base, 01074 /// . or -> operator, and nested-name-specifier have already been 01075 /// parsed. 01076 /// 01077 /// postfix-expression: [C++ 5.2] 01078 /// postfix-expression . pseudo-destructor-name 01079 /// postfix-expression -> pseudo-destructor-name 01080 /// 01081 /// pseudo-destructor-name: 01082 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name 01083 /// ::[opt] nested-name-specifier template simple-template-id :: 01084 /// ~type-name 01085 /// ::[opt] nested-name-specifier[opt] ~type-name 01086 /// 01087 ExprResult 01088 Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc, 01089 tok::TokenKind OpKind, 01090 CXXScopeSpec &SS, 01091 ParsedType ObjectType) { 01092 // We're parsing either a pseudo-destructor-name or a dependent 01093 // member access that has the same form as a 01094 // pseudo-destructor-name. We parse both in the same way and let 01095 // the action model sort them out. 01096 // 01097 // Note that the ::[opt] nested-name-specifier[opt] has already 01098 // been parsed, and if there was a simple-template-id, it has 01099 // been coalesced into a template-id annotation token. 01100 UnqualifiedId FirstTypeName; 01101 SourceLocation CCLoc; 01102 if (Tok.is(tok::identifier)) { 01103 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 01104 ConsumeToken(); 01105 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"); 01106 CCLoc = ConsumeToken(); 01107 } else if (Tok.is(tok::annot_template_id)) { 01108 // FIXME: retrieve TemplateKWLoc from template-id annotation and 01109 // store it in the pseudo-dtor node (to be used when instantiating it). 01110 FirstTypeName.setTemplateId( 01111 (TemplateIdAnnotation *)Tok.getAnnotationValue()); 01112 ConsumeToken(); 01113 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"); 01114 CCLoc = ConsumeToken(); 01115 } else { 01116 FirstTypeName.setIdentifier(0, SourceLocation()); 01117 } 01118 01119 // Parse the tilde. 01120 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail"); 01121 SourceLocation TildeLoc = ConsumeToken(); 01122 01123 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) { 01124 DeclSpec DS(AttrFactory); 01125 ParseDecltypeSpecifier(DS); 01126 if (DS.getTypeSpecType() == TST_error) 01127 return ExprError(); 01128 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, 01129 OpKind, TildeLoc, DS, 01130 Tok.is(tok::l_paren)); 01131 } 01132 01133 if (!Tok.is(tok::identifier)) { 01134 Diag(Tok, diag::err_destructor_tilde_identifier); 01135 return ExprError(); 01136 } 01137 01138 // Parse the second type. 01139 UnqualifiedId SecondTypeName; 01140 IdentifierInfo *Name = Tok.getIdentifierInfo(); 01141 SourceLocation NameLoc = ConsumeToken(); 01142 SecondTypeName.setIdentifier(Name, NameLoc); 01143 01144 // If there is a '<', the second type name is a template-id. Parse 01145 // it as such. 01146 if (Tok.is(tok::less) && 01147 ParseUnqualifiedIdTemplateId(SS, SourceLocation(), 01148 Name, NameLoc, 01149 false, ObjectType, SecondTypeName, 01150 /*AssumeTemplateName=*/true)) 01151 return ExprError(); 01152 01153 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, 01154 OpLoc, OpKind, 01155 SS, FirstTypeName, CCLoc, 01156 TildeLoc, SecondTypeName, 01157 Tok.is(tok::l_paren)); 01158 } 01159 01160 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals. 01161 /// 01162 /// boolean-literal: [C++ 2.13.5] 01163 /// 'true' 01164 /// 'false' 01165 ExprResult Parser::ParseCXXBoolLiteral() { 01166 tok::TokenKind Kind = Tok.getKind(); 01167 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind); 01168 } 01169 01170 /// ParseThrowExpression - This handles the C++ throw expression. 01171 /// 01172 /// throw-expression: [C++ 15] 01173 /// 'throw' assignment-expression[opt] 01174 ExprResult Parser::ParseThrowExpression() { 01175 assert(Tok.is(tok::kw_throw) && "Not throw!"); 01176 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token. 01177 01178 // If the current token isn't the start of an assignment-expression, 01179 // then the expression is not present. This handles things like: 01180 // "C ? throw : (void)42", which is crazy but legal. 01181 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common. 01182 case tok::semi: 01183 case tok::r_paren: 01184 case tok::r_square: 01185 case tok::r_brace: 01186 case tok::colon: 01187 case tok::comma: 01188 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0); 01189 01190 default: 01191 ExprResult Expr(ParseAssignmentExpression()); 01192 if (Expr.isInvalid()) return move(Expr); 01193 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take()); 01194 } 01195 } 01196 01197 /// ParseCXXThis - This handles the C++ 'this' pointer. 01198 /// 01199 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is 01200 /// a non-lvalue expression whose value is the address of the object for which 01201 /// the function is called. 01202 ExprResult Parser::ParseCXXThis() { 01203 assert(Tok.is(tok::kw_this) && "Not 'this'!"); 01204 SourceLocation ThisLoc = ConsumeToken(); 01205 return Actions.ActOnCXXThis(ThisLoc); 01206 } 01207 01208 /// ParseCXXTypeConstructExpression - Parse construction of a specified type. 01209 /// Can be interpreted either as function-style casting ("int(x)") 01210 /// or class type construction ("ClassType(x,y,z)") 01211 /// or creation of a value-initialized type ("int()"). 01212 /// See [C++ 5.2.3]. 01213 /// 01214 /// postfix-expression: [C++ 5.2p1] 01215 /// simple-type-specifier '(' expression-list[opt] ')' 01216 /// [C++0x] simple-type-specifier braced-init-list 01217 /// typename-specifier '(' expression-list[opt] ')' 01218 /// [C++0x] typename-specifier braced-init-list 01219 /// 01220 ExprResult 01221 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) { 01222 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 01223 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get(); 01224 01225 assert((Tok.is(tok::l_paren) || 01226 (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace))) 01227 && "Expected '(' or '{'!"); 01228 01229 if (Tok.is(tok::l_brace)) { 01230 ExprResult Init = ParseBraceInitializer(); 01231 if (Init.isInvalid()) 01232 return Init; 01233 Expr *InitList = Init.take(); 01234 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(), 01235 MultiExprArg(&InitList, 1), 01236 SourceLocation()); 01237 } else { 01238 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true); 01239 01240 BalancedDelimiterTracker T(*this, tok::l_paren); 01241 T.consumeOpen(); 01242 01243 ExprVector Exprs(Actions); 01244 CommaLocsTy CommaLocs; 01245 01246 if (Tok.isNot(tok::r_paren)) { 01247 if (ParseExpressionList(Exprs, CommaLocs)) { 01248 SkipUntil(tok::r_paren); 01249 return ExprError(); 01250 } 01251 } 01252 01253 // Match the ')'. 01254 T.consumeClose(); 01255 01256 // TypeRep could be null, if it references an invalid typedef. 01257 if (!TypeRep) 01258 return ExprError(); 01259 01260 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&& 01261 "Unexpected number of commas!"); 01262 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(), 01263 move_arg(Exprs), 01264 T.getCloseLocation()); 01265 } 01266 } 01267 01268 /// ParseCXXCondition - if/switch/while condition expression. 01269 /// 01270 /// condition: 01271 /// expression 01272 /// type-specifier-seq declarator '=' assignment-expression 01273 /// [C++11] type-specifier-seq declarator '=' initializer-clause 01274 /// [C++11] type-specifier-seq declarator braced-init-list 01275 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt] 01276 /// '=' assignment-expression 01277 /// 01278 /// \param ExprResult if the condition was parsed as an expression, the 01279 /// parsed expression. 01280 /// 01281 /// \param DeclResult if the condition was parsed as a declaration, the 01282 /// parsed declaration. 01283 /// 01284 /// \param Loc The location of the start of the statement that requires this 01285 /// condition, e.g., the "for" in a for loop. 01286 /// 01287 /// \param ConvertToBoolean Whether the condition expression should be 01288 /// converted to a boolean value. 01289 /// 01290 /// \returns true if there was a parsing, false otherwise. 01291 bool Parser::ParseCXXCondition(ExprResult &ExprOut, 01292 Decl *&DeclOut, 01293 SourceLocation Loc, 01294 bool ConvertToBoolean) { 01295 if (Tok.is(tok::code_completion)) { 01296 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition); 01297 cutOffParsing(); 01298 return true; 01299 } 01300 01301 if (!isCXXConditionDeclaration()) { 01302 // Parse the expression. 01303 ExprOut = ParseExpression(); // expression 01304 DeclOut = 0; 01305 if (ExprOut.isInvalid()) 01306 return true; 01307 01308 // If required, convert to a boolean value. 01309 if (ConvertToBoolean) 01310 ExprOut 01311 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get()); 01312 return ExprOut.isInvalid(); 01313 } 01314 01315 // type-specifier-seq 01316 DeclSpec DS(AttrFactory); 01317 ParseSpecifierQualifierList(DS); 01318 01319 // declarator 01320 Declarator DeclaratorInfo(DS, Declarator::ConditionContext); 01321 ParseDeclarator(DeclaratorInfo); 01322 01323 // simple-asm-expr[opt] 01324 if (Tok.is(tok::kw_asm)) { 01325 SourceLocation Loc; 01326 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 01327 if (AsmLabel.isInvalid()) { 01328 SkipUntil(tok::semi); 01329 return true; 01330 } 01331 DeclaratorInfo.setAsmLabel(AsmLabel.release()); 01332 DeclaratorInfo.SetRangeEnd(Loc); 01333 } 01334 01335 // If attributes are present, parse them. 01336 MaybeParseGNUAttributes(DeclaratorInfo); 01337 01338 // Type-check the declaration itself. 01339 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(), 01340 DeclaratorInfo); 01341 DeclOut = Dcl.get(); 01342 ExprOut = ExprError(); 01343 01344 // '=' assignment-expression 01345 // If a '==' or '+=' is found, suggest a fixit to '='. 01346 bool CopyInitialization = isTokenEqualOrEqualTypo(); 01347 if (CopyInitialization) 01348 ConsumeToken(); 01349 01350 ExprResult InitExpr = ExprError(); 01351 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) { 01352 Diag(Tok.getLocation(), 01353 diag::warn_cxx98_compat_generalized_initializer_lists); 01354 InitExpr = ParseBraceInitializer(); 01355 } else if (CopyInitialization) { 01356 InitExpr = ParseAssignmentExpression(); 01357 } else if (Tok.is(tok::l_paren)) { 01358 // This was probably an attempt to initialize the variable. 01359 SourceLocation LParen = ConsumeParen(), RParen = LParen; 01360 if (SkipUntil(tok::r_paren, true, /*DontConsume=*/true)) 01361 RParen = ConsumeParen(); 01362 Diag(DeclOut ? DeclOut->getLocation() : LParen, 01363 diag::err_expected_init_in_condition_lparen) 01364 << SourceRange(LParen, RParen); 01365 } else { 01366 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(), 01367 diag::err_expected_init_in_condition); 01368 } 01369 01370 if (!InitExpr.isInvalid()) 01371 Actions.AddInitializerToDecl(DeclOut, InitExpr.take(), !CopyInitialization, 01372 DS.getTypeSpecType() == DeclSpec::TST_auto); 01373 01374 // FIXME: Build a reference to this declaration? Convert it to bool? 01375 // (This is currently handled by Sema). 01376 01377 Actions.FinalizeDeclaration(DeclOut); 01378 01379 return false; 01380 } 01381 01382 /// \brief Determine whether the current token starts a C++ 01383 /// simple-type-specifier. 01384 bool Parser::isCXXSimpleTypeSpecifier() const { 01385 switch (Tok.getKind()) { 01386 case tok::annot_typename: 01387 case tok::kw_short: 01388 case tok::kw_long: 01389 case tok::kw___int64: 01390 case tok::kw___int128: 01391 case tok::kw_signed: 01392 case tok::kw_unsigned: 01393 case tok::kw_void: 01394 case tok::kw_char: 01395 case tok::kw_int: 01396 case tok::kw_half: 01397 case tok::kw_float: 01398 case tok::kw_double: 01399 case tok::kw_wchar_t: 01400 case tok::kw_char16_t: 01401 case tok::kw_char32_t: 01402 case tok::kw_bool: 01403 case tok::kw_decltype: 01404 case tok::kw_typeof: 01405 case tok::kw___underlying_type: 01406 return true; 01407 01408 default: 01409 break; 01410 } 01411 01412 return false; 01413 } 01414 01415 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. 01416 /// This should only be called when the current token is known to be part of 01417 /// simple-type-specifier. 01418 /// 01419 /// simple-type-specifier: 01420 /// '::'[opt] nested-name-specifier[opt] type-name 01421 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO] 01422 /// char 01423 /// wchar_t 01424 /// bool 01425 /// short 01426 /// int 01427 /// long 01428 /// signed 01429 /// unsigned 01430 /// float 01431 /// double 01432 /// void 01433 /// [GNU] typeof-specifier 01434 /// [C++0x] auto [TODO] 01435 /// 01436 /// type-name: 01437 /// class-name 01438 /// enum-name 01439 /// typedef-name 01440 /// 01441 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { 01442 DS.SetRangeStart(Tok.getLocation()); 01443 const char *PrevSpec; 01444 unsigned DiagID; 01445 SourceLocation Loc = Tok.getLocation(); 01446 01447 switch (Tok.getKind()) { 01448 case tok::identifier: // foo::bar 01449 case tok::coloncolon: // ::foo::bar 01450 llvm_unreachable("Annotation token should already be formed!"); 01451 default: 01452 llvm_unreachable("Not a simple-type-specifier token!"); 01453 01454 // type-name 01455 case tok::annot_typename: { 01456 if (getTypeAnnotation(Tok)) 01457 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, 01458 getTypeAnnotation(Tok)); 01459 else 01460 DS.SetTypeSpecError(); 01461 01462 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 01463 ConsumeToken(); 01464 01465 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 01466 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 01467 // Objective-C interface. If we don't have Objective-C or a '<', this is 01468 // just a normal reference to a typedef name. 01469 if (Tok.is(tok::less) && getLangOpts().ObjC1) 01470 ParseObjCProtocolQualifiers(DS); 01471 01472 DS.Finish(Diags, PP); 01473 return; 01474 } 01475 01476 // builtin types 01477 case tok::kw_short: 01478 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID); 01479 break; 01480 case tok::kw_long: 01481 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID); 01482 break; 01483 case tok::kw___int64: 01484 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID); 01485 break; 01486 case tok::kw_signed: 01487 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID); 01488 break; 01489 case tok::kw_unsigned: 01490 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID); 01491 break; 01492 case tok::kw_void: 01493 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID); 01494 break; 01495 case tok::kw_char: 01496 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID); 01497 break; 01498 case tok::kw_int: 01499 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID); 01500 break; 01501 case tok::kw___int128: 01502 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID); 01503 break; 01504 case tok::kw_half: 01505 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID); 01506 break; 01507 case tok::kw_float: 01508 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID); 01509 break; 01510 case tok::kw_double: 01511 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID); 01512 break; 01513 case tok::kw_wchar_t: 01514 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID); 01515 break; 01516 case tok::kw_char16_t: 01517 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID); 01518 break; 01519 case tok::kw_char32_t: 01520 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID); 01521 break; 01522 case tok::kw_bool: 01523 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID); 01524 break; 01525 case tok::annot_decltype: 01526 case tok::kw_decltype: 01527 DS.SetRangeEnd(ParseDecltypeSpecifier(DS)); 01528 return DS.Finish(Diags, PP); 01529 01530 // GNU typeof support. 01531 case tok::kw_typeof: 01532 ParseTypeofSpecifier(DS); 01533 DS.Finish(Diags, PP); 01534 return; 01535 } 01536 if (Tok.is(tok::annot_typename)) 01537 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 01538 else 01539 DS.SetRangeEnd(Tok.getLocation()); 01540 ConsumeToken(); 01541 DS.Finish(Diags, PP); 01542 } 01543 01544 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++ 01545 /// [dcl.name]), which is a non-empty sequence of type-specifiers, 01546 /// e.g., "const short int". Note that the DeclSpec is *not* finished 01547 /// by parsing the type-specifier-seq, because these sequences are 01548 /// typically followed by some form of declarator. Returns true and 01549 /// emits diagnostics if this is not a type-specifier-seq, false 01550 /// otherwise. 01551 /// 01552 /// type-specifier-seq: [C++ 8.1] 01553 /// type-specifier type-specifier-seq[opt] 01554 /// 01555 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { 01556 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier); 01557 DS.Finish(Diags, PP); 01558 return false; 01559 } 01560 01561 /// \brief Finish parsing a C++ unqualified-id that is a template-id of 01562 /// some form. 01563 /// 01564 /// This routine is invoked when a '<' is encountered after an identifier or 01565 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine 01566 /// whether the unqualified-id is actually a template-id. This routine will 01567 /// then parse the template arguments and form the appropriate template-id to 01568 /// return to the caller. 01569 /// 01570 /// \param SS the nested-name-specifier that precedes this template-id, if 01571 /// we're actually parsing a qualified-id. 01572 /// 01573 /// \param Name for constructor and destructor names, this is the actual 01574 /// identifier that may be a template-name. 01575 /// 01576 /// \param NameLoc the location of the class-name in a constructor or 01577 /// destructor. 01578 /// 01579 /// \param EnteringContext whether we're entering the scope of the 01580 /// nested-name-specifier. 01581 /// 01582 /// \param ObjectType if this unqualified-id occurs within a member access 01583 /// expression, the type of the base object whose member is being accessed. 01584 /// 01585 /// \param Id as input, describes the template-name or operator-function-id 01586 /// that precedes the '<'. If template arguments were parsed successfully, 01587 /// will be updated with the template-id. 01588 /// 01589 /// \param AssumeTemplateId When true, this routine will assume that the name 01590 /// refers to a template without performing name lookup to verify. 01591 /// 01592 /// \returns true if a parse error occurred, false otherwise. 01593 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, 01594 SourceLocation TemplateKWLoc, 01595 IdentifierInfo *Name, 01596 SourceLocation NameLoc, 01597 bool EnteringContext, 01598 ParsedType ObjectType, 01599 UnqualifiedId &Id, 01600 bool AssumeTemplateId) { 01601 assert((AssumeTemplateId || Tok.is(tok::less)) && 01602 "Expected '<' to finish parsing a template-id"); 01603 01604 TemplateTy Template; 01605 TemplateNameKind TNK = TNK_Non_template; 01606 switch (Id.getKind()) { 01607 case UnqualifiedId::IK_Identifier: 01608 case UnqualifiedId::IK_OperatorFunctionId: 01609 case UnqualifiedId::IK_LiteralOperatorId: 01610 if (AssumeTemplateId) { 01611 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc, 01612 Id, ObjectType, EnteringContext, 01613 Template); 01614 if (TNK == TNK_Non_template) 01615 return true; 01616 } else { 01617 bool MemberOfUnknownSpecialization; 01618 TNK = Actions.isTemplateName(getCurScope(), SS, 01619 TemplateKWLoc.isValid(), Id, 01620 ObjectType, EnteringContext, Template, 01621 MemberOfUnknownSpecialization); 01622 01623 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization && 01624 ObjectType && IsTemplateArgumentList()) { 01625 // We have something like t->getAs<T>(), where getAs is a 01626 // member of an unknown specialization. However, this will only 01627 // parse correctly as a template, so suggest the keyword 'template' 01628 // before 'getAs' and treat this as a dependent template name. 01629 std::string Name; 01630 if (Id.getKind() == UnqualifiedId::IK_Identifier) 01631 Name = Id.Identifier->getName(); 01632 else { 01633 Name = "operator "; 01634 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId) 01635 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator); 01636 else 01637 Name += Id.Identifier->getName(); 01638 } 01639 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword) 01640 << Name 01641 << FixItHint::CreateInsertion(Id.StartLocation, "template "); 01642 TNK = Actions.ActOnDependentTemplateName(getCurScope(), 01643 SS, TemplateKWLoc, Id, 01644 ObjectType, EnteringContext, 01645 Template); 01646 if (TNK == TNK_Non_template) 01647 return true; 01648 } 01649 } 01650 break; 01651 01652 case UnqualifiedId::IK_ConstructorName: { 01653 UnqualifiedId TemplateName; 01654 bool MemberOfUnknownSpecialization; 01655 TemplateName.setIdentifier(Name, NameLoc); 01656 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), 01657 TemplateName, ObjectType, 01658 EnteringContext, Template, 01659 MemberOfUnknownSpecialization); 01660 break; 01661 } 01662 01663 case UnqualifiedId::IK_DestructorName: { 01664 UnqualifiedId TemplateName; 01665 bool MemberOfUnknownSpecialization; 01666 TemplateName.setIdentifier(Name, NameLoc); 01667 if (ObjectType) { 01668 TNK = Actions.ActOnDependentTemplateName(getCurScope(), 01669 SS, TemplateKWLoc, TemplateName, 01670 ObjectType, EnteringContext, 01671 Template); 01672 if (TNK == TNK_Non_template) 01673 return true; 01674 } else { 01675 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), 01676 TemplateName, ObjectType, 01677 EnteringContext, Template, 01678 MemberOfUnknownSpecialization); 01679 01680 if (TNK == TNK_Non_template && !Id.DestructorName.get()) { 01681 Diag(NameLoc, diag::err_destructor_template_id) 01682 << Name << SS.getRange(); 01683 return true; 01684 } 01685 } 01686 break; 01687 } 01688 01689 default: 01690 return false; 01691 } 01692 01693 if (TNK == TNK_Non_template) 01694 return false; 01695 01696 // Parse the enclosed template argument list. 01697 SourceLocation LAngleLoc, RAngleLoc; 01698 TemplateArgList TemplateArgs; 01699 if (Tok.is(tok::less) && 01700 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation, 01701 SS, true, LAngleLoc, 01702 TemplateArgs, 01703 RAngleLoc)) 01704 return true; 01705 01706 if (Id.getKind() == UnqualifiedId::IK_Identifier || 01707 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId || 01708 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) { 01709 // Form a parsed representation of the template-id to be stored in the 01710 // UnqualifiedId. 01711 TemplateIdAnnotation *TemplateId 01712 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds); 01713 01714 if (Id.getKind() == UnqualifiedId::IK_Identifier) { 01715 TemplateId->Name = Id.Identifier; 01716 TemplateId->Operator = OO_None; 01717 TemplateId->TemplateNameLoc = Id.StartLocation; 01718 } else { 01719 TemplateId->Name = 0; 01720 TemplateId->Operator = Id.OperatorFunctionId.Operator; 01721 TemplateId->TemplateNameLoc = Id.StartLocation; 01722 } 01723 01724 TemplateId->SS = SS; 01725 TemplateId->TemplateKWLoc = TemplateKWLoc; 01726 TemplateId->Template = Template; 01727 TemplateId->Kind = TNK; 01728 TemplateId->LAngleLoc = LAngleLoc; 01729 TemplateId->RAngleLoc = RAngleLoc; 01730 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs(); 01731 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); 01732 Arg != ArgEnd; ++Arg) 01733 Args[Arg] = TemplateArgs[Arg]; 01734 01735 Id.setTemplateId(TemplateId); 01736 return false; 01737 } 01738 01739 // Bundle the template arguments together. 01740 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(), 01741 TemplateArgs.size()); 01742 01743 // Constructor and destructor names. 01744 TypeResult Type 01745 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc, 01746 Template, NameLoc, 01747 LAngleLoc, TemplateArgsPtr, RAngleLoc, 01748 /*IsCtorOrDtorName=*/true); 01749 if (Type.isInvalid()) 01750 return true; 01751 01752 if (Id.getKind() == UnqualifiedId::IK_ConstructorName) 01753 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc); 01754 else 01755 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc); 01756 01757 return false; 01758 } 01759 01760 /// \brief Parse an operator-function-id or conversion-function-id as part 01761 /// of a C++ unqualified-id. 01762 /// 01763 /// This routine is responsible only for parsing the operator-function-id or 01764 /// conversion-function-id; it does not handle template arguments in any way. 01765 /// 01766 /// \code 01767 /// operator-function-id: [C++ 13.5] 01768 /// 'operator' operator 01769 /// 01770 /// operator: one of 01771 /// new delete new[] delete[] 01772 /// + - * / % ^ & | ~ 01773 /// ! = < > += -= *= /= %= 01774 /// ^= &= |= << >> >>= <<= == != 01775 /// <= >= && || ++ -- , ->* -> 01776 /// () [] 01777 /// 01778 /// conversion-function-id: [C++ 12.3.2] 01779 /// operator conversion-type-id 01780 /// 01781 /// conversion-type-id: 01782 /// type-specifier-seq conversion-declarator[opt] 01783 /// 01784 /// conversion-declarator: 01785 /// ptr-operator conversion-declarator[opt] 01786 /// \endcode 01787 /// 01788 /// \param The nested-name-specifier that preceded this unqualified-id. If 01789 /// non-empty, then we are parsing the unqualified-id of a qualified-id. 01790 /// 01791 /// \param EnteringContext whether we are entering the scope of the 01792 /// nested-name-specifier. 01793 /// 01794 /// \param ObjectType if this unqualified-id occurs within a member access 01795 /// expression, the type of the base object whose member is being accessed. 01796 /// 01797 /// \param Result on a successful parse, contains the parsed unqualified-id. 01798 /// 01799 /// \returns true if parsing fails, false otherwise. 01800 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, 01801 ParsedType ObjectType, 01802 UnqualifiedId &Result) { 01803 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword"); 01804 01805 // Consume the 'operator' keyword. 01806 SourceLocation KeywordLoc = ConsumeToken(); 01807 01808 // Determine what kind of operator name we have. 01809 unsigned SymbolIdx = 0; 01810 SourceLocation SymbolLocations[3]; 01811 OverloadedOperatorKind Op = OO_None; 01812 switch (Tok.getKind()) { 01813 case tok::kw_new: 01814 case tok::kw_delete: { 01815 bool isNew = Tok.getKind() == tok::kw_new; 01816 // Consume the 'new' or 'delete'. 01817 SymbolLocations[SymbolIdx++] = ConsumeToken(); 01818 // Check for array new/delete. 01819 if (Tok.is(tok::l_square) && 01820 (!getLangOpts().CPlusPlus0x || NextToken().isNot(tok::l_square))) { 01821 // Consume the '[' and ']'. 01822 BalancedDelimiterTracker T(*this, tok::l_square); 01823 T.consumeOpen(); 01824 T.consumeClose(); 01825 if (T.getCloseLocation().isInvalid()) 01826 return true; 01827 01828 SymbolLocations[SymbolIdx++] = T.getOpenLocation(); 01829 SymbolLocations[SymbolIdx++] = T.getCloseLocation(); 01830 Op = isNew? OO_Array_New : OO_Array_Delete; 01831 } else { 01832 Op = isNew? OO_New : OO_Delete; 01833 } 01834 break; 01835 } 01836 01837 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 01838 case tok::Token: \ 01839 SymbolLocations[SymbolIdx++] = ConsumeToken(); \ 01840 Op = OO_##Name; \ 01841 break; 01842 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly) 01843 #include "clang/Basic/OperatorKinds.def" 01844 01845 case tok::l_paren: { 01846 // Consume the '(' and ')'. 01847 BalancedDelimiterTracker T(*this, tok::l_paren); 01848 T.consumeOpen(); 01849 T.consumeClose(); 01850 if (T.getCloseLocation().isInvalid()) 01851 return true; 01852 01853 SymbolLocations[SymbolIdx++] = T.getOpenLocation(); 01854 SymbolLocations[SymbolIdx++] = T.getCloseLocation(); 01855 Op = OO_Call; 01856 break; 01857 } 01858 01859 case tok::l_square: { 01860 // Consume the '[' and ']'. 01861 BalancedDelimiterTracker T(*this, tok::l_square); 01862 T.consumeOpen(); 01863 T.consumeClose(); 01864 if (T.getCloseLocation().isInvalid()) 01865 return true; 01866 01867 SymbolLocations[SymbolIdx++] = T.getOpenLocation(); 01868 SymbolLocations[SymbolIdx++] = T.getCloseLocation(); 01869 Op = OO_Subscript; 01870 break; 01871 } 01872 01873 case tok::code_completion: { 01874 // Code completion for the operator name. 01875 Actions.CodeCompleteOperatorName(getCurScope()); 01876 cutOffParsing(); 01877 // Don't try to parse any further. 01878 return true; 01879 } 01880 01881 default: 01882 break; 01883 } 01884 01885 if (Op != OO_None) { 01886 // We have parsed an operator-function-id. 01887 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations); 01888 return false; 01889 } 01890 01891 // Parse a literal-operator-id. 01892 // 01893 // literal-operator-id: [C++0x 13.5.8] 01894 // operator "" identifier 01895 01896 if (getLangOpts().CPlusPlus0x && isTokenStringLiteral()) { 01897 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator); 01898 01899 SourceLocation DiagLoc; 01900 unsigned DiagId = 0; 01901 01902 // We're past translation phase 6, so perform string literal concatenation 01903 // before checking for "". 01904 llvm::SmallVector<Token, 4> Toks; 01905 llvm::SmallVector<SourceLocation, 4> TokLocs; 01906 while (isTokenStringLiteral()) { 01907 if (!Tok.is(tok::string_literal) && !DiagId) { 01908 DiagLoc = Tok.getLocation(); 01909 DiagId = diag::err_literal_operator_string_prefix; 01910 } 01911 Toks.push_back(Tok); 01912 TokLocs.push_back(ConsumeStringToken()); 01913 } 01914 01915 StringLiteralParser Literal(Toks.data(), Toks.size(), PP); 01916 if (Literal.hadError) 01917 return true; 01918 01919 // Grab the literal operator's suffix, which will be either the next token 01920 // or a ud-suffix from the string literal. 01921 IdentifierInfo *II = 0; 01922 SourceLocation SuffixLoc; 01923 if (!Literal.getUDSuffix().empty()) { 01924 II = &PP.getIdentifierTable().get(Literal.getUDSuffix()); 01925 SuffixLoc = 01926 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()], 01927 Literal.getUDSuffixOffset(), 01928 PP.getSourceManager(), getLangOpts()); 01929 // This form is not permitted by the standard (yet). 01930 DiagLoc = SuffixLoc; 01931 DiagId = diag::err_literal_operator_missing_space; 01932 } else if (Tok.is(tok::identifier)) { 01933 II = Tok.getIdentifierInfo(); 01934 SuffixLoc = ConsumeToken(); 01935 TokLocs.push_back(SuffixLoc); 01936 } else { 01937 Diag(Tok.getLocation(), diag::err_expected_ident); 01938 return true; 01939 } 01940 01941 // The string literal must be empty. 01942 if (!Literal.GetString().empty() || Literal.Pascal) { 01943 DiagLoc = TokLocs.front(); 01944 DiagId = diag::err_literal_operator_string_not_empty; 01945 } 01946 01947 if (DiagId) { 01948 // This isn't a valid literal-operator-id, but we think we know 01949 // what the user meant. Tell them what they should have written. 01950 llvm::SmallString<32> Str; 01951 Str += "\"\" "; 01952 Str += II->getName(); 01953 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement( 01954 SourceRange(TokLocs.front(), TokLocs.back()), Str); 01955 } 01956 01957 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc); 01958 return false; 01959 } 01960 01961 // Parse a conversion-function-id. 01962 // 01963 // conversion-function-id: [C++ 12.3.2] 01964 // operator conversion-type-id 01965 // 01966 // conversion-type-id: 01967 // type-specifier-seq conversion-declarator[opt] 01968 // 01969 // conversion-declarator: 01970 // ptr-operator conversion-declarator[opt] 01971 01972 // Parse the type-specifier-seq. 01973 DeclSpec DS(AttrFactory); 01974 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType? 01975 return true; 01976 01977 // Parse the conversion-declarator, which is merely a sequence of 01978 // ptr-operators. 01979 Declarator D(DS, Declarator::TypeNameContext); 01980 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0); 01981 01982 // Finish up the type. 01983 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D); 01984 if (Ty.isInvalid()) 01985 return true; 01986 01987 // Note that this is a conversion-function-id. 01988 Result.setConversionFunctionId(KeywordLoc, Ty.get(), 01989 D.getSourceRange().getEnd()); 01990 return false; 01991 } 01992 01993 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the 01994 /// name of an entity. 01995 /// 01996 /// \code 01997 /// unqualified-id: [C++ expr.prim.general] 01998 /// identifier 01999 /// operator-function-id 02000 /// conversion-function-id 02001 /// [C++0x] literal-operator-id [TODO] 02002 /// ~ class-name 02003 /// template-id 02004 /// 02005 /// \endcode 02006 /// 02007 /// \param The nested-name-specifier that preceded this unqualified-id. If 02008 /// non-empty, then we are parsing the unqualified-id of a qualified-id. 02009 /// 02010 /// \param EnteringContext whether we are entering the scope of the 02011 /// nested-name-specifier. 02012 /// 02013 /// \param AllowDestructorName whether we allow parsing of a destructor name. 02014 /// 02015 /// \param AllowConstructorName whether we allow parsing a constructor name. 02016 /// 02017 /// \param ObjectType if this unqualified-id occurs within a member access 02018 /// expression, the type of the base object whose member is being accessed. 02019 /// 02020 /// \param Result on a successful parse, contains the parsed unqualified-id. 02021 /// 02022 /// \returns true if parsing fails, false otherwise. 02023 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, 02024 bool AllowDestructorName, 02025 bool AllowConstructorName, 02026 ParsedType ObjectType, 02027 SourceLocation& TemplateKWLoc, 02028 UnqualifiedId &Result) { 02029 02030 // Handle 'A::template B'. This is for template-ids which have not 02031 // already been annotated by ParseOptionalCXXScopeSpecifier(). 02032 bool TemplateSpecified = false; 02033 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) && 02034 (ObjectType || SS.isSet())) { 02035 TemplateSpecified = true; 02036 TemplateKWLoc = ConsumeToken(); 02037 } 02038 02039 // unqualified-id: 02040 // identifier 02041 // template-id (when it hasn't already been annotated) 02042 if (Tok.is(tok::identifier)) { 02043 // Consume the identifier. 02044 IdentifierInfo *Id = Tok.getIdentifierInfo(); 02045 SourceLocation IdLoc = ConsumeToken(); 02046 02047 if (!getLangOpts().CPlusPlus) { 02048 // If we're not in C++, only identifiers matter. Record the 02049 // identifier and return. 02050 Result.setIdentifier(Id, IdLoc); 02051 return false; 02052 } 02053 02054 if (AllowConstructorName && 02055 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) { 02056 // We have parsed a constructor name. 02057 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(), 02058 &SS, false, false, 02059 ParsedType(), 02060 /*IsCtorOrDtorName=*/true, 02061 /*NonTrivialTypeSourceInfo=*/true); 02062 Result.setConstructorName(Ty, IdLoc, IdLoc); 02063 } else { 02064 // We have parsed an identifier. 02065 Result.setIdentifier(Id, IdLoc); 02066 } 02067 02068 // If the next token is a '<', we may have a template. 02069 if (TemplateSpecified || Tok.is(tok::less)) 02070 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc, 02071 EnteringContext, ObjectType, 02072 Result, TemplateSpecified); 02073 02074 return false; 02075 } 02076 02077 // unqualified-id: 02078 // template-id (already parsed and annotated) 02079 if (Tok.is(tok::annot_template_id)) { 02080 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 02081 02082 // If the template-name names the current class, then this is a constructor 02083 if (AllowConstructorName && TemplateId->Name && 02084 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { 02085 if (SS.isSet()) { 02086 // C++ [class.qual]p2 specifies that a qualified template-name 02087 // is taken as the constructor name where a constructor can be 02088 // declared. Thus, the template arguments are extraneous, so 02089 // complain about them and remove them entirely. 02090 Diag(TemplateId->TemplateNameLoc, 02091 diag::err_out_of_line_constructor_template_id) 02092 << TemplateId->Name 02093 << FixItHint::CreateRemoval( 02094 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)); 02095 ParsedType Ty = Actions.getTypeName(*TemplateId->Name, 02096 TemplateId->TemplateNameLoc, 02097 getCurScope(), 02098 &SS, false, false, 02099 ParsedType(), 02100 /*IsCtorOrDtorName=*/true, 02101 /*NontrivialTypeSourceInfo=*/true); 02102 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc, 02103 TemplateId->RAngleLoc); 02104 ConsumeToken(); 02105 return false; 02106 } 02107 02108 Result.setConstructorTemplateId(TemplateId); 02109 ConsumeToken(); 02110 return false; 02111 } 02112 02113 // We have already parsed a template-id; consume the annotation token as 02114 // our unqualified-id. 02115 Result.setTemplateId(TemplateId); 02116 TemplateKWLoc = TemplateId->TemplateKWLoc; 02117 ConsumeToken(); 02118 return false; 02119 } 02120 02121 // unqualified-id: 02122 // operator-function-id 02123 // conversion-function-id 02124 if (Tok.is(tok::kw_operator)) { 02125 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result)) 02126 return true; 02127 02128 // If we have an operator-function-id or a literal-operator-id and the next 02129 // token is a '<', we may have a 02130 // 02131 // template-id: 02132 // operator-function-id < template-argument-list[opt] > 02133 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId || 02134 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) && 02135 (TemplateSpecified || Tok.is(tok::less))) 02136 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, 02137 0, SourceLocation(), 02138 EnteringContext, ObjectType, 02139 Result, TemplateSpecified); 02140 02141 return false; 02142 } 02143 02144 if (getLangOpts().CPlusPlus && 02145 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) { 02146 // C++ [expr.unary.op]p10: 02147 // There is an ambiguity in the unary-expression ~X(), where X is a 02148 // class-name. The ambiguity is resolved in favor of treating ~ as a 02149 // unary complement rather than treating ~X as referring to a destructor. 02150 02151 // Parse the '~'. 02152 SourceLocation TildeLoc = ConsumeToken(); 02153 02154 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) { 02155 DeclSpec DS(AttrFactory); 02156 SourceLocation EndLoc = ParseDecltypeSpecifier(DS); 02157 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) { 02158 Result.setDestructorName(TildeLoc, Type, EndLoc); 02159 return false; 02160 } 02161 return true; 02162 } 02163 02164 // Parse the class-name. 02165 if (Tok.isNot(tok::identifier)) { 02166 Diag(Tok, diag::err_destructor_tilde_identifier); 02167 return true; 02168 } 02169 02170 // Parse the class-name (or template-name in a simple-template-id). 02171 IdentifierInfo *ClassName = Tok.getIdentifierInfo(); 02172 SourceLocation ClassNameLoc = ConsumeToken(); 02173 02174 if (TemplateSpecified || Tok.is(tok::less)) { 02175 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc); 02176 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, 02177 ClassName, ClassNameLoc, 02178 EnteringContext, ObjectType, 02179 Result, TemplateSpecified); 02180 } 02181 02182 // Note that this is a destructor name. 02183 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName, 02184 ClassNameLoc, getCurScope(), 02185 SS, ObjectType, 02186 EnteringContext); 02187 if (!Ty) 02188 return true; 02189 02190 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc); 02191 return false; 02192 } 02193 02194 Diag(Tok, diag::err_expected_unqualified_id) 02195 << getLangOpts().CPlusPlus; 02196 return true; 02197 } 02198 02199 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate 02200 /// memory in a typesafe manner and call constructors. 02201 /// 02202 /// This method is called to parse the new expression after the optional :: has 02203 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start" 02204 /// is its location. Otherwise, "Start" is the location of the 'new' token. 02205 /// 02206 /// new-expression: 02207 /// '::'[opt] 'new' new-placement[opt] new-type-id 02208 /// new-initializer[opt] 02209 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 02210 /// new-initializer[opt] 02211 /// 02212 /// new-placement: 02213 /// '(' expression-list ')' 02214 /// 02215 /// new-type-id: 02216 /// type-specifier-seq new-declarator[opt] 02217 /// [GNU] attributes type-specifier-seq new-declarator[opt] 02218 /// 02219 /// new-declarator: 02220 /// ptr-operator new-declarator[opt] 02221 /// direct-new-declarator 02222 /// 02223 /// new-initializer: 02224 /// '(' expression-list[opt] ')' 02225 /// [C++0x] braced-init-list 02226 /// 02227 ExprResult 02228 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) { 02229 assert(Tok.is(tok::kw_new) && "expected 'new' token"); 02230 ConsumeToken(); // Consume 'new' 02231 02232 // A '(' now can be a new-placement or the '(' wrapping the type-id in the 02233 // second form of new-expression. It can't be a new-type-id. 02234 02235 ExprVector PlacementArgs(Actions); 02236 SourceLocation PlacementLParen, PlacementRParen; 02237 02238 SourceRange TypeIdParens; 02239 DeclSpec DS(AttrFactory); 02240 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext); 02241 if (Tok.is(tok::l_paren)) { 02242 // If it turns out to be a placement, we change the type location. 02243 BalancedDelimiterTracker T(*this, tok::l_paren); 02244 T.consumeOpen(); 02245 PlacementLParen = T.getOpenLocation(); 02246 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) { 02247 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 02248 return ExprError(); 02249 } 02250 02251 T.consumeClose(); 02252 PlacementRParen = T.getCloseLocation(); 02253 if (PlacementRParen.isInvalid()) { 02254 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 02255 return ExprError(); 02256 } 02257 02258 if (PlacementArgs.empty()) { 02259 // Reset the placement locations. There was no placement. 02260 TypeIdParens = T.getRange(); 02261 PlacementLParen = PlacementRParen = SourceLocation(); 02262 } else { 02263 // We still need the type. 02264 if (Tok.is(tok::l_paren)) { 02265 BalancedDelimiterTracker T(*this, tok::l_paren); 02266 T.consumeOpen(); 02267 MaybeParseGNUAttributes(DeclaratorInfo); 02268 ParseSpecifierQualifierList(DS); 02269 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 02270 ParseDeclarator(DeclaratorInfo); 02271 T.consumeClose(); 02272 TypeIdParens = T.getRange(); 02273 } else { 02274 MaybeParseGNUAttributes(DeclaratorInfo); 02275 if (ParseCXXTypeSpecifierSeq(DS)) 02276 DeclaratorInfo.setInvalidType(true); 02277 else { 02278 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 02279 ParseDeclaratorInternal(DeclaratorInfo, 02280 &Parser::ParseDirectNewDeclarator); 02281 } 02282 } 02283 } 02284 } else { 02285 // A new-type-id is a simplified type-id, where essentially the 02286 // direct-declarator is replaced by a direct-new-declarator. 02287 MaybeParseGNUAttributes(DeclaratorInfo); 02288 if (ParseCXXTypeSpecifierSeq(DS)) 02289 DeclaratorInfo.setInvalidType(true); 02290 else { 02291 DeclaratorInfo.SetSourceRange(DS.getSourceRange()); 02292 ParseDeclaratorInternal(DeclaratorInfo, 02293 &Parser::ParseDirectNewDeclarator); 02294 } 02295 } 02296 if (DeclaratorInfo.isInvalidType()) { 02297 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 02298 return ExprError(); 02299 } 02300 02301 ExprResult Initializer; 02302 02303 if (Tok.is(tok::l_paren)) { 02304 SourceLocation ConstructorLParen, ConstructorRParen; 02305 ExprVector ConstructorArgs(Actions); 02306 BalancedDelimiterTracker T(*this, tok::l_paren); 02307 T.consumeOpen(); 02308 ConstructorLParen = T.getOpenLocation(); 02309 if (Tok.isNot(tok::r_paren)) { 02310 CommaLocsTy CommaLocs; 02311 if (ParseExpressionList(ConstructorArgs, CommaLocs)) { 02312 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 02313 return ExprError(); 02314 } 02315 } 02316 T.consumeClose(); 02317 ConstructorRParen = T.getCloseLocation(); 02318 if (ConstructorRParen.isInvalid()) { 02319 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); 02320 return ExprError(); 02321 } 02322 Initializer = Actions.ActOnParenListExpr(ConstructorLParen, 02323 ConstructorRParen, 02324 move_arg(ConstructorArgs)); 02325 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus0x) { 02326 Diag(Tok.getLocation(), 02327 diag::warn_cxx98_compat_generalized_initializer_lists); 02328 Initializer = ParseBraceInitializer(); 02329 } 02330 if (Initializer.isInvalid()) 02331 return Initializer; 02332 02333 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen, 02334 move_arg(PlacementArgs), PlacementRParen, 02335 TypeIdParens, DeclaratorInfo, Initializer.take()); 02336 } 02337 02338 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be 02339 /// passed to ParseDeclaratorInternal. 02340 /// 02341 /// direct-new-declarator: 02342 /// '[' expression ']' 02343 /// direct-new-declarator '[' constant-expression ']' 02344 /// 02345 void Parser::ParseDirectNewDeclarator(Declarator &D) { 02346 // Parse the array dimensions. 02347 bool first = true; 02348 while (Tok.is(tok::l_square)) { 02349 // An array-size expression can't start with a lambda. 02350 if (CheckProhibitedCXX11Attribute()) 02351 continue; 02352 02353 BalancedDelimiterTracker T(*this, tok::l_square); 02354 T.consumeOpen(); 02355 02356 ExprResult Size(first ? ParseExpression() 02357 : ParseConstantExpression()); 02358 if (Size.isInvalid()) { 02359 // Recover 02360 SkipUntil(tok::r_square); 02361 return; 02362 } 02363 first = false; 02364 02365 T.consumeClose(); 02366 02367 // Attributes here appertain to the array type. C++11 [expr.new]p5. 02368 ParsedAttributes Attrs(AttrFactory); 02369 MaybeParseCXX0XAttributes(Attrs); 02370 02371 D.AddTypeInfo(DeclaratorChunk::getArray(0, 02372 /*static=*/false, /*star=*/false, 02373 Size.release(), 02374 T.getOpenLocation(), 02375 T.getCloseLocation()), 02376 Attrs, T.getCloseLocation()); 02377 02378 if (T.getCloseLocation().isInvalid()) 02379 return; 02380 } 02381 } 02382 02383 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id. 02384 /// This ambiguity appears in the syntax of the C++ new operator. 02385 /// 02386 /// new-expression: 02387 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 02388 /// new-initializer[opt] 02389 /// 02390 /// new-placement: 02391 /// '(' expression-list ')' 02392 /// 02393 bool Parser::ParseExpressionListOrTypeId( 02394 SmallVectorImpl<Expr*> &PlacementArgs, 02395 Declarator &D) { 02396 // The '(' was already consumed. 02397 if (isTypeIdInParens()) { 02398 ParseSpecifierQualifierList(D.getMutableDeclSpec()); 02399 D.SetSourceRange(D.getDeclSpec().getSourceRange()); 02400 ParseDeclarator(D); 02401 return D.isInvalidType(); 02402 } 02403 02404 // It's not a type, it has to be an expression list. 02405 // Discard the comma locations - ActOnCXXNew has enough parameters. 02406 CommaLocsTy CommaLocs; 02407 return ParseExpressionList(PlacementArgs, CommaLocs); 02408 } 02409 02410 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used 02411 /// to free memory allocated by new. 02412 /// 02413 /// This method is called to parse the 'delete' expression after the optional 02414 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true 02415 /// and "Start" is its location. Otherwise, "Start" is the location of the 02416 /// 'delete' token. 02417 /// 02418 /// delete-expression: 02419 /// '::'[opt] 'delete' cast-expression 02420 /// '::'[opt] 'delete' '[' ']' cast-expression 02421 ExprResult 02422 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) { 02423 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword"); 02424 ConsumeToken(); // Consume 'delete' 02425 02426 // Array delete? 02427 bool ArrayDelete = false; 02428 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) { 02429 // FIXME: This could be the start of a lambda-expression. We should 02430 // disambiguate this, but that will require arbitrary lookahead if 02431 // the next token is '(': 02432 // delete [](int*){ /* ... */ 02433 ArrayDelete = true; 02434 BalancedDelimiterTracker T(*this, tok::l_square); 02435 02436 T.consumeOpen(); 02437 T.consumeClose(); 02438 if (T.getCloseLocation().isInvalid()) 02439 return ExprError(); 02440 } 02441 02442 ExprResult Operand(ParseCastExpression(false)); 02443 if (Operand.isInvalid()) 02444 return move(Operand); 02445 02446 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take()); 02447 } 02448 02449 static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) { 02450 switch(kind) { 02451 default: llvm_unreachable("Not a known unary type trait."); 02452 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign; 02453 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor; 02454 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy; 02455 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign; 02456 case tok::kw___has_trivial_constructor: 02457 return UTT_HasTrivialDefaultConstructor; 02458 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy; 02459 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor; 02460 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor; 02461 case tok::kw___is_abstract: return UTT_IsAbstract; 02462 case tok::kw___is_arithmetic: return UTT_IsArithmetic; 02463 case tok::kw___is_array: return UTT_IsArray; 02464 case tok::kw___is_class: return UTT_IsClass; 02465 case tok::kw___is_complete_type: return UTT_IsCompleteType; 02466 case tok::kw___is_compound: return UTT_IsCompound; 02467 case tok::kw___is_const: return UTT_IsConst; 02468 case tok::kw___is_empty: return UTT_IsEmpty; 02469 case tok::kw___is_enum: return UTT_IsEnum; 02470 case tok::kw___is_final: return UTT_IsFinal; 02471 case tok::kw___is_floating_point: return UTT_IsFloatingPoint; 02472 case tok::kw___is_function: return UTT_IsFunction; 02473 case tok::kw___is_fundamental: return UTT_IsFundamental; 02474 case tok::kw___is_integral: return UTT_IsIntegral; 02475 case tok::kw___is_lvalue_reference: return UTT_IsLvalueReference; 02476 case tok::kw___is_member_function_pointer: return UTT_IsMemberFunctionPointer; 02477 case tok::kw___is_member_object_pointer: return UTT_IsMemberObjectPointer; 02478 case tok::kw___is_member_pointer: return UTT_IsMemberPointer; 02479 case tok::kw___is_object: return UTT_IsObject; 02480 case tok::kw___is_literal: return UTT_IsLiteral; 02481 case tok::kw___is_literal_type: return UTT_IsLiteral; 02482 case tok::kw___is_pod: return UTT_IsPOD; 02483 case tok::kw___is_pointer: return UTT_IsPointer; 02484 case tok::kw___is_polymorphic: return UTT_IsPolymorphic; 02485 case tok::kw___is_reference: return UTT_IsReference; 02486 case tok::kw___is_rvalue_reference: return UTT_IsRvalueReference; 02487 case tok::kw___is_scalar: return UTT_IsScalar; 02488 case tok::kw___is_signed: return UTT_IsSigned; 02489 case tok::kw___is_standard_layout: return UTT_IsStandardLayout; 02490 case tok::kw___is_trivial: return UTT_IsTrivial; 02491 case tok::kw___is_trivially_copyable: return UTT_IsTriviallyCopyable; 02492 case tok::kw___is_union: return UTT_IsUnion; 02493 case tok::kw___is_unsigned: return UTT_IsUnsigned; 02494 case tok::kw___is_void: return UTT_IsVoid; 02495 case tok::kw___is_volatile: return UTT_IsVolatile; 02496 } 02497 } 02498 02499 static BinaryTypeTrait BinaryTypeTraitFromTokKind(tok::TokenKind kind) { 02500 switch(kind) { 02501 default: llvm_unreachable("Not a known binary type trait"); 02502 case tok::kw___is_base_of: return BTT_IsBaseOf; 02503 case tok::kw___is_convertible: return BTT_IsConvertible; 02504 case tok::kw___is_same: return BTT_IsSame; 02505 case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible; 02506 case tok::kw___is_convertible_to: return BTT_IsConvertibleTo; 02507 case tok::kw___is_trivially_assignable: return BTT_IsTriviallyAssignable; 02508 } 02509 } 02510 02511 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) { 02512 switch (kind) { 02513 default: llvm_unreachable("Not a known type trait"); 02514 case tok::kw___is_trivially_constructible: 02515 return TT_IsTriviallyConstructible; 02516 } 02517 } 02518 02519 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) { 02520 switch(kind) { 02521 default: llvm_unreachable("Not a known binary type trait"); 02522 case tok::kw___array_rank: return ATT_ArrayRank; 02523 case tok::kw___array_extent: return ATT_ArrayExtent; 02524 } 02525 } 02526 02527 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) { 02528 switch(kind) { 02529 default: llvm_unreachable("Not a known unary expression trait."); 02530 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr; 02531 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr; 02532 } 02533 } 02534 02535 /// ParseUnaryTypeTrait - Parse the built-in unary type-trait 02536 /// pseudo-functions that allow implementation of the TR1/C++0x type traits 02537 /// templates. 02538 /// 02539 /// primary-expression: 02540 /// [GNU] unary-type-trait '(' type-id ')' 02541 /// 02542 ExprResult Parser::ParseUnaryTypeTrait() { 02543 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind()); 02544 SourceLocation Loc = ConsumeToken(); 02545 02546 BalancedDelimiterTracker T(*this, tok::l_paren); 02547 if (T.expectAndConsume(diag::err_expected_lparen)) 02548 return ExprError(); 02549 02550 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type 02551 // there will be cryptic errors about mismatched parentheses and missing 02552 // specifiers. 02553 TypeResult Ty = ParseTypeName(); 02554 02555 T.consumeClose(); 02556 02557 if (Ty.isInvalid()) 02558 return ExprError(); 02559 02560 return Actions.ActOnUnaryTypeTrait(UTT, Loc, Ty.get(), T.getCloseLocation()); 02561 } 02562 02563 /// ParseBinaryTypeTrait - Parse the built-in binary type-trait 02564 /// pseudo-functions that allow implementation of the TR1/C++0x type traits 02565 /// templates. 02566 /// 02567 /// primary-expression: 02568 /// [GNU] binary-type-trait '(' type-id ',' type-id ')' 02569 /// 02570 ExprResult Parser::ParseBinaryTypeTrait() { 02571 BinaryTypeTrait BTT = BinaryTypeTraitFromTokKind(Tok.getKind()); 02572 SourceLocation Loc = ConsumeToken(); 02573 02574 BalancedDelimiterTracker T(*this, tok::l_paren); 02575 if (T.expectAndConsume(diag::err_expected_lparen)) 02576 return ExprError(); 02577 02578 TypeResult LhsTy = ParseTypeName(); 02579 if (LhsTy.isInvalid()) { 02580 SkipUntil(tok::r_paren); 02581 return ExprError(); 02582 } 02583 02584 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) { 02585 SkipUntil(tok::r_paren); 02586 return ExprError(); 02587 } 02588 02589 TypeResult RhsTy = ParseTypeName(); 02590 if (RhsTy.isInvalid()) { 02591 SkipUntil(tok::r_paren); 02592 return ExprError(); 02593 } 02594 02595 T.consumeClose(); 02596 02597 return Actions.ActOnBinaryTypeTrait(BTT, Loc, LhsTy.get(), RhsTy.get(), 02598 T.getCloseLocation()); 02599 } 02600 02601 /// \brief Parse the built-in type-trait pseudo-functions that allow 02602 /// implementation of the TR1/C++11 type traits templates. 02603 /// 02604 /// primary-expression: 02605 /// type-trait '(' type-id-seq ')' 02606 /// 02607 /// type-id-seq: 02608 /// type-id ...[opt] type-id-seq[opt] 02609 /// 02610 ExprResult Parser::ParseTypeTrait() { 02611 TypeTrait Kind = TypeTraitFromTokKind(Tok.getKind()); 02612 SourceLocation Loc = ConsumeToken(); 02613 02614 BalancedDelimiterTracker Parens(*this, tok::l_paren); 02615 if (Parens.expectAndConsume(diag::err_expected_lparen)) 02616 return ExprError(); 02617 02618 llvm::SmallVector<ParsedType, 2> Args; 02619 do { 02620 // Parse the next type. 02621 TypeResult Ty = ParseTypeName(); 02622 if (Ty.isInvalid()) { 02623 Parens.skipToEnd(); 02624 return ExprError(); 02625 } 02626 02627 // Parse the ellipsis, if present. 02628 if (Tok.is(tok::ellipsis)) { 02629 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken()); 02630 if (Ty.isInvalid()) { 02631 Parens.skipToEnd(); 02632 return ExprError(); 02633 } 02634 } 02635 02636 // Add this type to the list of arguments. 02637 Args.push_back(Ty.get()); 02638 02639 if (Tok.is(tok::comma)) { 02640 ConsumeToken(); 02641 continue; 02642 } 02643 02644 break; 02645 } while (true); 02646 02647 if (Parens.consumeClose()) 02648 return ExprError(); 02649 02650 return Actions.ActOnTypeTrait(Kind, Loc, Args, Parens.getCloseLocation()); 02651 } 02652 02653 /// ParseArrayTypeTrait - Parse the built-in array type-trait 02654 /// pseudo-functions. 02655 /// 02656 /// primary-expression: 02657 /// [Embarcadero] '__array_rank' '(' type-id ')' 02658 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')' 02659 /// 02660 ExprResult Parser::ParseArrayTypeTrait() { 02661 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind()); 02662 SourceLocation Loc = ConsumeToken(); 02663 02664 BalancedDelimiterTracker T(*this, tok::l_paren); 02665 if (T.expectAndConsume(diag::err_expected_lparen)) 02666 return ExprError(); 02667 02668 TypeResult Ty = ParseTypeName(); 02669 if (Ty.isInvalid()) { 02670 SkipUntil(tok::comma); 02671 SkipUntil(tok::r_paren); 02672 return ExprError(); 02673 } 02674 02675 switch (ATT) { 02676 case ATT_ArrayRank: { 02677 T.consumeClose(); 02678 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL, 02679 T.getCloseLocation()); 02680 } 02681 case ATT_ArrayExtent: { 02682 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) { 02683 SkipUntil(tok::r_paren); 02684 return ExprError(); 02685 } 02686 02687 ExprResult DimExpr = ParseExpression(); 02688 T.consumeClose(); 02689 02690 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(), 02691 T.getCloseLocation()); 02692 } 02693 } 02694 llvm_unreachable("Invalid ArrayTypeTrait!"); 02695 } 02696 02697 /// ParseExpressionTrait - Parse built-in expression-trait 02698 /// pseudo-functions like __is_lvalue_expr( xxx ). 02699 /// 02700 /// primary-expression: 02701 /// [Embarcadero] expression-trait '(' expression ')' 02702 /// 02703 ExprResult Parser::ParseExpressionTrait() { 02704 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind()); 02705 SourceLocation Loc = ConsumeToken(); 02706 02707 BalancedDelimiterTracker T(*this, tok::l_paren); 02708 if (T.expectAndConsume(diag::err_expected_lparen)) 02709 return ExprError(); 02710 02711 ExprResult Expr = ParseExpression(); 02712 02713 T.consumeClose(); 02714 02715 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(), 02716 T.getCloseLocation()); 02717 } 02718 02719 02720 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a 02721 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate 02722 /// based on the context past the parens. 02723 ExprResult 02724 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, 02725 ParsedType &CastTy, 02726 BalancedDelimiterTracker &Tracker) { 02727 assert(getLangOpts().CPlusPlus && "Should only be called for C++!"); 02728 assert(ExprType == CastExpr && "Compound literals are not ambiguous!"); 02729 assert(isTypeIdInParens() && "Not a type-id!"); 02730 02731 ExprResult Result(true); 02732 CastTy = ParsedType(); 02733 02734 // We need to disambiguate a very ugly part of the C++ syntax: 02735 // 02736 // (T())x; - type-id 02737 // (T())*x; - type-id 02738 // (T())/x; - expression 02739 // (T()); - expression 02740 // 02741 // The bad news is that we cannot use the specialized tentative parser, since 02742 // it can only verify that the thing inside the parens can be parsed as 02743 // type-id, it is not useful for determining the context past the parens. 02744 // 02745 // The good news is that the parser can disambiguate this part without 02746 // making any unnecessary Action calls. 02747 // 02748 // It uses a scheme similar to parsing inline methods. The parenthesized 02749 // tokens are cached, the context that follows is determined (possibly by 02750 // parsing a cast-expression), and then we re-introduce the cached tokens 02751 // into the token stream and parse them appropriately. 02752 02753 ParenParseOption ParseAs; 02754 CachedTokens Toks; 02755 02756 // Store the tokens of the parentheses. We will parse them after we determine 02757 // the context that follows them. 02758 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) { 02759 // We didn't find the ')' we expected. 02760 Tracker.consumeClose(); 02761 return ExprError(); 02762 } 02763 02764 if (Tok.is(tok::l_brace)) { 02765 ParseAs = CompoundLiteral; 02766 } else { 02767 bool NotCastExpr; 02768 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression 02769 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) { 02770 NotCastExpr = true; 02771 } else { 02772 // Try parsing the cast-expression that may follow. 02773 // If it is not a cast-expression, NotCastExpr will be true and no token 02774 // will be consumed. 02775 Result = ParseCastExpression(false/*isUnaryExpression*/, 02776 false/*isAddressofOperand*/, 02777 NotCastExpr, 02778 // type-id has priority. 02779 IsTypeCast); 02780 } 02781 02782 // If we parsed a cast-expression, it's really a type-id, otherwise it's 02783 // an expression. 02784 ParseAs = NotCastExpr ? SimpleExpr : CastExpr; 02785 } 02786 02787 // The current token should go after the cached tokens. 02788 Toks.push_back(Tok); 02789 // Re-enter the stored parenthesized tokens into the token stream, so we may 02790 // parse them now. 02791 PP.EnterTokenStream(Toks.data(), Toks.size(), 02792 true/*DisableMacroExpansion*/, false/*OwnsTokens*/); 02793 // Drop the current token and bring the first cached one. It's the same token 02794 // as when we entered this function. 02795 ConsumeAnyToken(); 02796 02797 if (ParseAs >= CompoundLiteral) { 02798 // Parse the type declarator. 02799 DeclSpec DS(AttrFactory); 02800 ParseSpecifierQualifierList(DS); 02801 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 02802 ParseDeclarator(DeclaratorInfo); 02803 02804 // Match the ')'. 02805 Tracker.consumeClose(); 02806 02807 if (ParseAs == CompoundLiteral) { 02808 ExprType = CompoundLiteral; 02809 TypeResult Ty = ParseTypeName(); 02810 return ParseCompoundLiteralExpression(Ty.get(), 02811 Tracker.getOpenLocation(), 02812 Tracker.getCloseLocation()); 02813 } 02814 02815 // We parsed '(' type-id ')' and the thing after it wasn't a '{'. 02816 assert(ParseAs == CastExpr); 02817 02818 if (DeclaratorInfo.isInvalidType()) 02819 return ExprError(); 02820 02821 // Result is what ParseCastExpression returned earlier. 02822 if (!Result.isInvalid()) 02823 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(), 02824 DeclaratorInfo, CastTy, 02825 Tracker.getCloseLocation(), Result.take()); 02826 return move(Result); 02827 } 02828 02829 // Not a compound literal, and not followed by a cast-expression. 02830 assert(ParseAs == SimpleExpr); 02831 02832 ExprType = SimpleExpr; 02833 Result = ParseExpression(); 02834 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 02835 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(), 02836 Tok.getLocation(), Result.take()); 02837 02838 // Match the ')'. 02839 if (Result.isInvalid()) { 02840 SkipUntil(tok::r_paren); 02841 return ExprError(); 02842 } 02843 02844 Tracker.consumeClose(); 02845 return move(Result); 02846 }