ParseDeclCXX.cpp 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973
  1. //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the C++ Declaration portions of the Parser interfaces.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Basic/OperatorKinds.h"
  14. #include "clang/Parse/Parser.h"
  15. #include "clang/Parse/ParseDiagnostic.h"
  16. #include "clang/Sema/DeclSpec.h"
  17. #include "clang/Sema/Scope.h"
  18. #include "clang/Sema/ParsedTemplate.h"
  19. #include "clang/Sema/PrettyDeclStackTrace.h"
  20. #include "llvm/ADT/SmallString.h"
  21. #include "RAIIObjectsForParser.h"
  22. using namespace clang;
  23. /// ParseNamespace - We know that the current token is a namespace keyword. This
  24. /// may either be a top level namespace or a block-level namespace alias. If
  25. /// there was an inline keyword, it has already been parsed.
  26. ///
  27. /// namespace-definition: [C++ 7.3: basic.namespace]
  28. /// named-namespace-definition
  29. /// unnamed-namespace-definition
  30. ///
  31. /// unnamed-namespace-definition:
  32. /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
  33. ///
  34. /// named-namespace-definition:
  35. /// original-namespace-definition
  36. /// extension-namespace-definition
  37. ///
  38. /// original-namespace-definition:
  39. /// 'inline'[opt] 'namespace' identifier attributes[opt]
  40. /// '{' namespace-body '}'
  41. ///
  42. /// extension-namespace-definition:
  43. /// 'inline'[opt] 'namespace' original-namespace-name
  44. /// '{' namespace-body '}'
  45. ///
  46. /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
  47. /// 'namespace' identifier '=' qualified-namespace-specifier ';'
  48. ///
  49. Decl *Parser::ParseNamespace(unsigned Context,
  50. SourceLocation &DeclEnd,
  51. SourceLocation InlineLoc) {
  52. assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
  53. SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
  54. ObjCDeclContextSwitch ObjCDC(*this);
  55. if (Tok.is(tok::code_completion)) {
  56. Actions.CodeCompleteNamespaceDecl(getCurScope());
  57. cutOffParsing();
  58. return 0;
  59. }
  60. SourceLocation IdentLoc;
  61. IdentifierInfo *Ident = 0;
  62. std::vector<SourceLocation> ExtraIdentLoc;
  63. std::vector<IdentifierInfo*> ExtraIdent;
  64. std::vector<SourceLocation> ExtraNamespaceLoc;
  65. Token attrTok;
  66. if (Tok.is(tok::identifier)) {
  67. Ident = Tok.getIdentifierInfo();
  68. IdentLoc = ConsumeToken(); // eat the identifier.
  69. while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
  70. ExtraNamespaceLoc.push_back(ConsumeToken());
  71. ExtraIdent.push_back(Tok.getIdentifierInfo());
  72. ExtraIdentLoc.push_back(ConsumeToken());
  73. }
  74. }
  75. // Read label attributes, if present.
  76. ParsedAttributes attrs(AttrFactory);
  77. if (Tok.is(tok::kw___attribute)) {
  78. attrTok = Tok;
  79. ParseGNUAttributes(attrs);
  80. }
  81. if (Tok.is(tok::equal)) {
  82. if (!attrs.empty())
  83. Diag(attrTok, diag::err_unexpected_namespace_attributes_alias);
  84. if (InlineLoc.isValid())
  85. Diag(InlineLoc, diag::err_inline_namespace_alias)
  86. << FixItHint::CreateRemoval(InlineLoc);
  87. return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
  88. }
  89. BalancedDelimiterTracker T(*this, tok::l_brace);
  90. if (T.consumeOpen()) {
  91. if (!ExtraIdent.empty()) {
  92. Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
  93. << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
  94. }
  95. Diag(Tok, Ident ? diag::err_expected_lbrace :
  96. diag::err_expected_ident_lbrace);
  97. return 0;
  98. }
  99. if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
  100. getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
  101. getCurScope()->getFnParent()) {
  102. if (!ExtraIdent.empty()) {
  103. Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
  104. << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
  105. }
  106. Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
  107. SkipUntil(tok::r_brace, false);
  108. return 0;
  109. }
  110. if (!ExtraIdent.empty()) {
  111. TentativeParsingAction TPA(*this);
  112. SkipUntil(tok::r_brace, /*StopAtSemi*/false, /*DontConsume*/true);
  113. Token rBraceToken = Tok;
  114. TPA.Revert();
  115. if (!rBraceToken.is(tok::r_brace)) {
  116. Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
  117. << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
  118. } else {
  119. std::string NamespaceFix;
  120. for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
  121. E = ExtraIdent.end(); I != E; ++I) {
  122. NamespaceFix += " { namespace ";
  123. NamespaceFix += (*I)->getName();
  124. }
  125. std::string RBraces;
  126. for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
  127. RBraces += "} ";
  128. Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
  129. << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
  130. ExtraIdentLoc.back()),
  131. NamespaceFix)
  132. << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
  133. }
  134. }
  135. // If we're still good, complain about inline namespaces in non-C++0x now.
  136. if (InlineLoc.isValid())
  137. Diag(InlineLoc, getLangOpts().CPlusPlus0x ?
  138. diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
  139. // Enter a scope for the namespace.
  140. ParseScope NamespaceScope(this, Scope::DeclScope);
  141. Decl *NamespcDecl =
  142. Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
  143. IdentLoc, Ident, T.getOpenLocation(),
  144. attrs.getList());
  145. PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
  146. "parsing namespace");
  147. // Parse the contents of the namespace. This includes parsing recovery on
  148. // any improperly nested namespaces.
  149. ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
  150. InlineLoc, attrs, T);
  151. // Leave the namespace scope.
  152. NamespaceScope.Exit();
  153. DeclEnd = T.getCloseLocation();
  154. Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
  155. return NamespcDecl;
  156. }
  157. /// ParseInnerNamespace - Parse the contents of a namespace.
  158. void Parser::ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
  159. std::vector<IdentifierInfo*>& Ident,
  160. std::vector<SourceLocation>& NamespaceLoc,
  161. unsigned int index, SourceLocation& InlineLoc,
  162. ParsedAttributes& attrs,
  163. BalancedDelimiterTracker &Tracker) {
  164. if (index == Ident.size()) {
  165. while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
  166. ParsedAttributesWithRange attrs(AttrFactory);
  167. MaybeParseCXX0XAttributes(attrs);
  168. MaybeParseMicrosoftAttributes(attrs);
  169. ParseExternalDeclaration(attrs);
  170. }
  171. // The caller is what called check -- we are simply calling
  172. // the close for it.
  173. Tracker.consumeClose();
  174. return;
  175. }
  176. // Parse improperly nested namespaces.
  177. ParseScope NamespaceScope(this, Scope::DeclScope);
  178. Decl *NamespcDecl =
  179. Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
  180. NamespaceLoc[index], IdentLoc[index],
  181. Ident[index], Tracker.getOpenLocation(),
  182. attrs.getList());
  183. ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
  184. attrs, Tracker);
  185. NamespaceScope.Exit();
  186. Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
  187. }
  188. /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
  189. /// alias definition.
  190. ///
  191. Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
  192. SourceLocation AliasLoc,
  193. IdentifierInfo *Alias,
  194. SourceLocation &DeclEnd) {
  195. assert(Tok.is(tok::equal) && "Not equal token");
  196. ConsumeToken(); // eat the '='.
  197. if (Tok.is(tok::code_completion)) {
  198. Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
  199. cutOffParsing();
  200. return 0;
  201. }
  202. CXXScopeSpec SS;
  203. // Parse (optional) nested-name-specifier.
  204. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
  205. if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
  206. Diag(Tok, diag::err_expected_namespace_name);
  207. // Skip to end of the definition and eat the ';'.
  208. SkipUntil(tok::semi);
  209. return 0;
  210. }
  211. // Parse identifier.
  212. IdentifierInfo *Ident = Tok.getIdentifierInfo();
  213. SourceLocation IdentLoc = ConsumeToken();
  214. // Eat the ';'.
  215. DeclEnd = Tok.getLocation();
  216. ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name,
  217. "", tok::semi);
  218. return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias,
  219. SS, IdentLoc, Ident);
  220. }
  221. /// ParseLinkage - We know that the current token is a string_literal
  222. /// and just before that, that extern was seen.
  223. ///
  224. /// linkage-specification: [C++ 7.5p2: dcl.link]
  225. /// 'extern' string-literal '{' declaration-seq[opt] '}'
  226. /// 'extern' string-literal declaration
  227. ///
  228. Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
  229. assert(Tok.is(tok::string_literal) && "Not a string literal!");
  230. SmallString<8> LangBuffer;
  231. bool Invalid = false;
  232. StringRef Lang = PP.getSpelling(Tok, LangBuffer, &Invalid);
  233. if (Invalid)
  234. return 0;
  235. // FIXME: This is incorrect: linkage-specifiers are parsed in translation
  236. // phase 7, so string-literal concatenation is supposed to occur.
  237. // extern "" "C" "" "+" "+" { } is legal.
  238. if (Tok.hasUDSuffix())
  239. Diag(Tok, diag::err_invalid_string_udl);
  240. SourceLocation Loc = ConsumeStringToken();
  241. ParseScope LinkageScope(this, Scope::DeclScope);
  242. Decl *LinkageSpec
  243. = Actions.ActOnStartLinkageSpecification(getCurScope(),
  244. DS.getSourceRange().getBegin(),
  245. Loc, Lang,
  246. Tok.is(tok::l_brace) ? Tok.getLocation()
  247. : SourceLocation());
  248. ParsedAttributesWithRange attrs(AttrFactory);
  249. MaybeParseCXX0XAttributes(attrs);
  250. MaybeParseMicrosoftAttributes(attrs);
  251. if (Tok.isNot(tok::l_brace)) {
  252. // Reset the source range in DS, as the leading "extern"
  253. // does not really belong to the inner declaration ...
  254. DS.SetRangeStart(SourceLocation());
  255. DS.SetRangeEnd(SourceLocation());
  256. // ... but anyway remember that such an "extern" was seen.
  257. DS.setExternInLinkageSpec(true);
  258. ParseExternalDeclaration(attrs, &DS);
  259. return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
  260. SourceLocation());
  261. }
  262. DS.abort();
  263. ProhibitAttributes(attrs);
  264. BalancedDelimiterTracker T(*this, tok::l_brace);
  265. T.consumeOpen();
  266. while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
  267. ParsedAttributesWithRange attrs(AttrFactory);
  268. MaybeParseCXX0XAttributes(attrs);
  269. MaybeParseMicrosoftAttributes(attrs);
  270. ParseExternalDeclaration(attrs);
  271. }
  272. T.consumeClose();
  273. return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
  274. T.getCloseLocation());
  275. }
  276. /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
  277. /// using-directive. Assumes that current token is 'using'.
  278. Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
  279. const ParsedTemplateInfo &TemplateInfo,
  280. SourceLocation &DeclEnd,
  281. ParsedAttributesWithRange &attrs,
  282. Decl **OwnedType) {
  283. assert(Tok.is(tok::kw_using) && "Not using token");
  284. ObjCDeclContextSwitch ObjCDC(*this);
  285. // Eat 'using'.
  286. SourceLocation UsingLoc = ConsumeToken();
  287. if (Tok.is(tok::code_completion)) {
  288. Actions.CodeCompleteUsing(getCurScope());
  289. cutOffParsing();
  290. return 0;
  291. }
  292. // 'using namespace' means this is a using-directive.
  293. if (Tok.is(tok::kw_namespace)) {
  294. // Template parameters are always an error here.
  295. if (TemplateInfo.Kind) {
  296. SourceRange R = TemplateInfo.getSourceRange();
  297. Diag(UsingLoc, diag::err_templated_using_directive)
  298. << R << FixItHint::CreateRemoval(R);
  299. }
  300. return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
  301. }
  302. // Otherwise, it must be a using-declaration or an alias-declaration.
  303. // Using declarations can't have attributes.
  304. ProhibitAttributes(attrs);
  305. return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
  306. AS_none, OwnedType);
  307. }
  308. /// ParseUsingDirective - Parse C++ using-directive, assumes
  309. /// that current token is 'namespace' and 'using' was already parsed.
  310. ///
  311. /// using-directive: [C++ 7.3.p4: namespace.udir]
  312. /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
  313. /// namespace-name ;
  314. /// [GNU] using-directive:
  315. /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
  316. /// namespace-name attributes[opt] ;
  317. ///
  318. Decl *Parser::ParseUsingDirective(unsigned Context,
  319. SourceLocation UsingLoc,
  320. SourceLocation &DeclEnd,
  321. ParsedAttributes &attrs) {
  322. assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
  323. // Eat 'namespace'.
  324. SourceLocation NamespcLoc = ConsumeToken();
  325. if (Tok.is(tok::code_completion)) {
  326. Actions.CodeCompleteUsingDirective(getCurScope());
  327. cutOffParsing();
  328. return 0;
  329. }
  330. CXXScopeSpec SS;
  331. // Parse (optional) nested-name-specifier.
  332. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
  333. IdentifierInfo *NamespcName = 0;
  334. SourceLocation IdentLoc = SourceLocation();
  335. // Parse namespace-name.
  336. if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
  337. Diag(Tok, diag::err_expected_namespace_name);
  338. // If there was invalid namespace name, skip to end of decl, and eat ';'.
  339. SkipUntil(tok::semi);
  340. // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
  341. return 0;
  342. }
  343. // Parse identifier.
  344. NamespcName = Tok.getIdentifierInfo();
  345. IdentLoc = ConsumeToken();
  346. // Parse (optional) attributes (most likely GNU strong-using extension).
  347. bool GNUAttr = false;
  348. if (Tok.is(tok::kw___attribute)) {
  349. GNUAttr = true;
  350. ParseGNUAttributes(attrs);
  351. }
  352. // Eat ';'.
  353. DeclEnd = Tok.getLocation();
  354. ExpectAndConsume(tok::semi,
  355. GNUAttr ? diag::err_expected_semi_after_attribute_list
  356. : diag::err_expected_semi_after_namespace_name,
  357. "", tok::semi);
  358. return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
  359. IdentLoc, NamespcName, attrs.getList());
  360. }
  361. /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
  362. /// Assumes that 'using' was already seen.
  363. ///
  364. /// using-declaration: [C++ 7.3.p3: namespace.udecl]
  365. /// 'using' 'typename'[opt] ::[opt] nested-name-specifier
  366. /// unqualified-id
  367. /// 'using' :: unqualified-id
  368. ///
  369. /// alias-declaration: C++0x [decl.typedef]p2
  370. /// 'using' identifier = type-id ;
  371. ///
  372. Decl *Parser::ParseUsingDeclaration(unsigned Context,
  373. const ParsedTemplateInfo &TemplateInfo,
  374. SourceLocation UsingLoc,
  375. SourceLocation &DeclEnd,
  376. AccessSpecifier AS,
  377. Decl **OwnedType) {
  378. CXXScopeSpec SS;
  379. SourceLocation TypenameLoc;
  380. bool IsTypeName;
  381. // Ignore optional 'typename'.
  382. // FIXME: This is wrong; we should parse this as a typename-specifier.
  383. if (Tok.is(tok::kw_typename)) {
  384. TypenameLoc = Tok.getLocation();
  385. ConsumeToken();
  386. IsTypeName = true;
  387. }
  388. else
  389. IsTypeName = false;
  390. // Parse nested-name-specifier.
  391. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
  392. // Check nested-name specifier.
  393. if (SS.isInvalid()) {
  394. SkipUntil(tok::semi);
  395. return 0;
  396. }
  397. // Parse the unqualified-id. We allow parsing of both constructor and
  398. // destructor names and allow the action module to diagnose any semantic
  399. // errors.
  400. SourceLocation TemplateKWLoc;
  401. UnqualifiedId Name;
  402. if (ParseUnqualifiedId(SS,
  403. /*EnteringContext=*/false,
  404. /*AllowDestructorName=*/true,
  405. /*AllowConstructorName=*/true,
  406. ParsedType(),
  407. TemplateKWLoc,
  408. Name)) {
  409. SkipUntil(tok::semi);
  410. return 0;
  411. }
  412. ParsedAttributes attrs(AttrFactory);
  413. // Maybe this is an alias-declaration.
  414. bool IsAliasDecl = Tok.is(tok::equal);
  415. TypeResult TypeAlias;
  416. if (IsAliasDecl) {
  417. // TODO: Attribute support. C++0x attributes may appear before the equals.
  418. // Where can GNU attributes appear?
  419. ConsumeToken();
  420. Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
  421. diag::warn_cxx98_compat_alias_declaration :
  422. diag::ext_alias_declaration);
  423. // Type alias templates cannot be specialized.
  424. int SpecKind = -1;
  425. if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
  426. Name.getKind() == UnqualifiedId::IK_TemplateId)
  427. SpecKind = 0;
  428. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
  429. SpecKind = 1;
  430. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
  431. SpecKind = 2;
  432. if (SpecKind != -1) {
  433. SourceRange Range;
  434. if (SpecKind == 0)
  435. Range = SourceRange(Name.TemplateId->LAngleLoc,
  436. Name.TemplateId->RAngleLoc);
  437. else
  438. Range = TemplateInfo.getSourceRange();
  439. Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
  440. << SpecKind << Range;
  441. SkipUntil(tok::semi);
  442. return 0;
  443. }
  444. // Name must be an identifier.
  445. if (Name.getKind() != UnqualifiedId::IK_Identifier) {
  446. Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
  447. // No removal fixit: can't recover from this.
  448. SkipUntil(tok::semi);
  449. return 0;
  450. } else if (IsTypeName)
  451. Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
  452. << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
  453. SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
  454. else if (SS.isNotEmpty())
  455. Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
  456. << FixItHint::CreateRemoval(SS.getRange());
  457. TypeAlias = ParseTypeName(0, TemplateInfo.Kind ?
  458. Declarator::AliasTemplateContext :
  459. Declarator::AliasDeclContext, AS, OwnedType);
  460. } else
  461. // Parse (optional) attributes (most likely GNU strong-using extension).
  462. MaybeParseGNUAttributes(attrs);
  463. // Eat ';'.
  464. DeclEnd = Tok.getLocation();
  465. ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
  466. !attrs.empty() ? "attributes list" :
  467. IsAliasDecl ? "alias declaration" : "using declaration",
  468. tok::semi);
  469. // Diagnose an attempt to declare a templated using-declaration.
  470. // In C++0x, alias-declarations can be templates:
  471. // template <...> using id = type;
  472. if (TemplateInfo.Kind && !IsAliasDecl) {
  473. SourceRange R = TemplateInfo.getSourceRange();
  474. Diag(UsingLoc, diag::err_templated_using_declaration)
  475. << R << FixItHint::CreateRemoval(R);
  476. // Unfortunately, we have to bail out instead of recovering by
  477. // ignoring the parameters, just in case the nested name specifier
  478. // depends on the parameters.
  479. return 0;
  480. }
  481. // "typename" keyword is allowed for identifiers only,
  482. // because it may be a type definition.
  483. if (IsTypeName && Name.getKind() != UnqualifiedId::IK_Identifier) {
  484. Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
  485. << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
  486. // Proceed parsing, but reset the IsTypeName flag.
  487. IsTypeName = false;
  488. }
  489. if (IsAliasDecl) {
  490. TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
  491. MultiTemplateParamsArg TemplateParamsArg(Actions,
  492. TemplateParams ? TemplateParams->data() : 0,
  493. TemplateParams ? TemplateParams->size() : 0);
  494. return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
  495. UsingLoc, Name, TypeAlias);
  496. }
  497. return Actions.ActOnUsingDeclaration(getCurScope(), AS, true, UsingLoc, SS,
  498. Name, attrs.getList(),
  499. IsTypeName, TypenameLoc);
  500. }
  501. /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
  502. ///
  503. /// [C++0x] static_assert-declaration:
  504. /// static_assert ( constant-expression , string-literal ) ;
  505. ///
  506. /// [C11] static_assert-declaration:
  507. /// _Static_assert ( constant-expression , string-literal ) ;
  508. ///
  509. Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
  510. assert((Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) &&
  511. "Not a static_assert declaration");
  512. if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
  513. Diag(Tok, diag::ext_c11_static_assert);
  514. if (Tok.is(tok::kw_static_assert))
  515. Diag(Tok, diag::warn_cxx98_compat_static_assert);
  516. SourceLocation StaticAssertLoc = ConsumeToken();
  517. BalancedDelimiterTracker T(*this, tok::l_paren);
  518. if (T.consumeOpen()) {
  519. Diag(Tok, diag::err_expected_lparen);
  520. return 0;
  521. }
  522. ExprResult AssertExpr(ParseConstantExpression());
  523. if (AssertExpr.isInvalid()) {
  524. SkipUntil(tok::semi);
  525. return 0;
  526. }
  527. if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi))
  528. return 0;
  529. if (!isTokenStringLiteral()) {
  530. Diag(Tok, diag::err_expected_string_literal);
  531. SkipUntil(tok::semi);
  532. return 0;
  533. }
  534. ExprResult AssertMessage(ParseStringLiteralExpression());
  535. if (AssertMessage.isInvalid()) {
  536. SkipUntil(tok::semi);
  537. return 0;
  538. }
  539. T.consumeClose();
  540. DeclEnd = Tok.getLocation();
  541. ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
  542. return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
  543. AssertExpr.take(),
  544. AssertMessage.take(),
  545. T.getCloseLocation());
  546. }
  547. /// ParseDecltypeSpecifier - Parse a C++0x decltype specifier.
  548. ///
  549. /// 'decltype' ( expression )
  550. ///
  551. SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
  552. assert((Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))
  553. && "Not a decltype specifier");
  554. ExprResult Result;
  555. SourceLocation StartLoc = Tok.getLocation();
  556. SourceLocation EndLoc;
  557. if (Tok.is(tok::annot_decltype)) {
  558. Result = getExprAnnotation(Tok);
  559. EndLoc = Tok.getAnnotationEndLoc();
  560. ConsumeToken();
  561. if (Result.isInvalid()) {
  562. DS.SetTypeSpecError();
  563. return EndLoc;
  564. }
  565. } else {
  566. if (Tok.getIdentifierInfo()->isStr("decltype"))
  567. Diag(Tok, diag::warn_cxx98_compat_decltype);
  568. ConsumeToken();
  569. BalancedDelimiterTracker T(*this, tok::l_paren);
  570. if (T.expectAndConsume(diag::err_expected_lparen_after,
  571. "decltype", tok::r_paren)) {
  572. DS.SetTypeSpecError();
  573. return T.getOpenLocation() == Tok.getLocation() ?
  574. StartLoc : T.getOpenLocation();
  575. }
  576. // Parse the expression
  577. // C++0x [dcl.type.simple]p4:
  578. // The operand of the decltype specifier is an unevaluated operand.
  579. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
  580. 0, /*IsDecltype=*/true);
  581. Result = ParseExpression();
  582. if (Result.isInvalid()) {
  583. SkipUntil(tok::r_paren);
  584. DS.SetTypeSpecError();
  585. return StartLoc;
  586. }
  587. // Match the ')'
  588. T.consumeClose();
  589. if (T.getCloseLocation().isInvalid()) {
  590. DS.SetTypeSpecError();
  591. // FIXME: this should return the location of the last token
  592. // that was consumed (by "consumeClose()")
  593. return T.getCloseLocation();
  594. }
  595. Result = Actions.ActOnDecltypeExpression(Result.take());
  596. if (Result.isInvalid()) {
  597. DS.SetTypeSpecError();
  598. return T.getCloseLocation();
  599. }
  600. EndLoc = T.getCloseLocation();
  601. }
  602. const char *PrevSpec = 0;
  603. unsigned DiagID;
  604. // Check for duplicate type specifiers (e.g. "int decltype(a)").
  605. if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
  606. DiagID, Result.release())) {
  607. Diag(StartLoc, DiagID) << PrevSpec;
  608. DS.SetTypeSpecError();
  609. }
  610. return EndLoc;
  611. }
  612. void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
  613. SourceLocation StartLoc,
  614. SourceLocation EndLoc) {
  615. // make sure we have a token we can turn into an annotation token
  616. if (PP.isBacktrackEnabled())
  617. PP.RevertCachedTokens(1);
  618. else
  619. PP.EnterToken(Tok);
  620. Tok.setKind(tok::annot_decltype);
  621. setExprAnnotation(Tok, DS.getTypeSpecType() == TST_decltype ?
  622. DS.getRepAsExpr() : ExprResult());
  623. Tok.setAnnotationEndLoc(EndLoc);
  624. Tok.setLocation(StartLoc);
  625. PP.AnnotateCachedTokens(Tok);
  626. }
  627. void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
  628. assert(Tok.is(tok::kw___underlying_type) &&
  629. "Not an underlying type specifier");
  630. SourceLocation StartLoc = ConsumeToken();
  631. BalancedDelimiterTracker T(*this, tok::l_paren);
  632. if (T.expectAndConsume(diag::err_expected_lparen_after,
  633. "__underlying_type", tok::r_paren)) {
  634. return;
  635. }
  636. TypeResult Result = ParseTypeName();
  637. if (Result.isInvalid()) {
  638. SkipUntil(tok::r_paren);
  639. return;
  640. }
  641. // Match the ')'
  642. T.consumeClose();
  643. if (T.getCloseLocation().isInvalid())
  644. return;
  645. const char *PrevSpec = 0;
  646. unsigned DiagID;
  647. if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
  648. DiagID, Result.release()))
  649. Diag(StartLoc, DiagID) << PrevSpec;
  650. }
  651. /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
  652. /// class name or decltype-specifier. Note that we only check that the result
  653. /// names a type; semantic analysis will need to verify that the type names a
  654. /// class. The result is either a type or null, depending on whether a type
  655. /// name was found.
  656. ///
  657. /// base-type-specifier: [C++ 10.1]
  658. /// class-or-decltype
  659. /// class-or-decltype: [C++ 10.1]
  660. /// nested-name-specifier[opt] class-name
  661. /// decltype-specifier
  662. /// class-name: [C++ 9.1]
  663. /// identifier
  664. /// simple-template-id
  665. ///
  666. Parser::TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
  667. SourceLocation &EndLocation) {
  668. // Ignore attempts to use typename
  669. if (Tok.is(tok::kw_typename)) {
  670. Diag(Tok, diag::err_expected_class_name_not_template)
  671. << FixItHint::CreateRemoval(Tok.getLocation());
  672. ConsumeToken();
  673. }
  674. // Parse optional nested-name-specifier
  675. CXXScopeSpec SS;
  676. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
  677. BaseLoc = Tok.getLocation();
  678. // Parse decltype-specifier
  679. // tok == kw_decltype is just error recovery, it can only happen when SS
  680. // isn't empty
  681. if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
  682. if (SS.isNotEmpty())
  683. Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
  684. << FixItHint::CreateRemoval(SS.getRange());
  685. // Fake up a Declarator to use with ActOnTypeName.
  686. DeclSpec DS(AttrFactory);
  687. EndLocation = ParseDecltypeSpecifier(DS);
  688. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  689. return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  690. }
  691. // Check whether we have a template-id that names a type.
  692. if (Tok.is(tok::annot_template_id)) {
  693. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  694. if (TemplateId->Kind == TNK_Type_template ||
  695. TemplateId->Kind == TNK_Dependent_template_name) {
  696. AnnotateTemplateIdTokenAsType();
  697. assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
  698. ParsedType Type = getTypeAnnotation(Tok);
  699. EndLocation = Tok.getAnnotationEndLoc();
  700. ConsumeToken();
  701. if (Type)
  702. return Type;
  703. return true;
  704. }
  705. // Fall through to produce an error below.
  706. }
  707. if (Tok.isNot(tok::identifier)) {
  708. Diag(Tok, diag::err_expected_class_name);
  709. return true;
  710. }
  711. IdentifierInfo *Id = Tok.getIdentifierInfo();
  712. SourceLocation IdLoc = ConsumeToken();
  713. if (Tok.is(tok::less)) {
  714. // It looks the user intended to write a template-id here, but the
  715. // template-name was wrong. Try to fix that.
  716. TemplateNameKind TNK = TNK_Type_template;
  717. TemplateTy Template;
  718. if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
  719. &SS, Template, TNK)) {
  720. Diag(IdLoc, diag::err_unknown_template_name)
  721. << Id;
  722. }
  723. if (!Template)
  724. return true;
  725. // Form the template name
  726. UnqualifiedId TemplateName;
  727. TemplateName.setIdentifier(Id, IdLoc);
  728. // Parse the full template-id, then turn it into a type.
  729. if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
  730. TemplateName, true))
  731. return true;
  732. if (TNK == TNK_Dependent_template_name)
  733. AnnotateTemplateIdTokenAsType();
  734. // If we didn't end up with a typename token, there's nothing more we
  735. // can do.
  736. if (Tok.isNot(tok::annot_typename))
  737. return true;
  738. // Retrieve the type from the annotation token, consume that token, and
  739. // return.
  740. EndLocation = Tok.getAnnotationEndLoc();
  741. ParsedType Type = getTypeAnnotation(Tok);
  742. ConsumeToken();
  743. return Type;
  744. }
  745. // We have an identifier; check whether it is actually a type.
  746. ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true,
  747. false, ParsedType(),
  748. /*IsCtorOrDtorName=*/false,
  749. /*NonTrivialTypeSourceInfo=*/true);
  750. if (!Type) {
  751. Diag(IdLoc, diag::err_expected_class_name);
  752. return true;
  753. }
  754. // Consume the identifier.
  755. EndLocation = IdLoc;
  756. // Fake up a Declarator to use with ActOnTypeName.
  757. DeclSpec DS(AttrFactory);
  758. DS.SetRangeStart(IdLoc);
  759. DS.SetRangeEnd(EndLocation);
  760. DS.getTypeSpecScope() = SS;
  761. const char *PrevSpec = 0;
  762. unsigned DiagID;
  763. DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type);
  764. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  765. return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  766. }
  767. /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
  768. /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
  769. /// until we reach the start of a definition or see a token that
  770. /// cannot start a definition. If SuppressDeclarations is true, we do know.
  771. ///
  772. /// class-specifier: [C++ class]
  773. /// class-head '{' member-specification[opt] '}'
  774. /// class-head '{' member-specification[opt] '}' attributes[opt]
  775. /// class-head:
  776. /// class-key identifier[opt] base-clause[opt]
  777. /// class-key nested-name-specifier identifier base-clause[opt]
  778. /// class-key nested-name-specifier[opt] simple-template-id
  779. /// base-clause[opt]
  780. /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
  781. /// [GNU] class-key attributes[opt] nested-name-specifier
  782. /// identifier base-clause[opt]
  783. /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
  784. /// simple-template-id base-clause[opt]
  785. /// class-key:
  786. /// 'class'
  787. /// 'struct'
  788. /// 'union'
  789. ///
  790. /// elaborated-type-specifier: [C++ dcl.type.elab]
  791. /// class-key ::[opt] nested-name-specifier[opt] identifier
  792. /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
  793. /// simple-template-id
  794. ///
  795. /// Note that the C++ class-specifier and elaborated-type-specifier,
  796. /// together, subsume the C99 struct-or-union-specifier:
  797. ///
  798. /// struct-or-union-specifier: [C99 6.7.2.1]
  799. /// struct-or-union identifier[opt] '{' struct-contents '}'
  800. /// struct-or-union identifier
  801. /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
  802. /// '}' attributes[opt]
  803. /// [GNU] struct-or-union attributes[opt] identifier
  804. /// struct-or-union:
  805. /// 'struct'
  806. /// 'union'
  807. void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
  808. SourceLocation StartLoc, DeclSpec &DS,
  809. const ParsedTemplateInfo &TemplateInfo,
  810. AccessSpecifier AS,
  811. bool EnteringContext,
  812. bool SuppressDeclarations){
  813. DeclSpec::TST TagType;
  814. if (TagTokKind == tok::kw_struct)
  815. TagType = DeclSpec::TST_struct;
  816. else if (TagTokKind == tok::kw_class)
  817. TagType = DeclSpec::TST_class;
  818. else {
  819. assert(TagTokKind == tok::kw_union && "Not a class specifier");
  820. TagType = DeclSpec::TST_union;
  821. }
  822. if (Tok.is(tok::code_completion)) {
  823. // Code completion for a struct, class, or union name.
  824. Actions.CodeCompleteTag(getCurScope(), TagType);
  825. return cutOffParsing();
  826. }
  827. // C++03 [temp.explicit] 14.7.2/8:
  828. // The usual access checking rules do not apply to names used to specify
  829. // explicit instantiations.
  830. //
  831. // As an extension we do not perform access checking on the names used to
  832. // specify explicit specializations either. This is important to allow
  833. // specializing traits classes for private types.
  834. bool SuppressingAccessChecks = false;
  835. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
  836. TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization) {
  837. Actions.ActOnStartSuppressingAccessChecks();
  838. SuppressingAccessChecks = true;
  839. }
  840. ParsedAttributes attrs(AttrFactory);
  841. // If attributes exist after tag, parse them.
  842. if (Tok.is(tok::kw___attribute))
  843. ParseGNUAttributes(attrs);
  844. // If declspecs exist after tag, parse them.
  845. while (Tok.is(tok::kw___declspec))
  846. ParseMicrosoftDeclSpec(attrs);
  847. // If C++0x attributes exist here, parse them.
  848. // FIXME: Are we consistent with the ordering of parsing of different
  849. // styles of attributes?
  850. MaybeParseCXX0XAttributes(attrs);
  851. if (TagType == DeclSpec::TST_struct &&
  852. !Tok.is(tok::identifier) &&
  853. Tok.getIdentifierInfo() &&
  854. (Tok.is(tok::kw___is_arithmetic) ||
  855. Tok.is(tok::kw___is_convertible) ||
  856. Tok.is(tok::kw___is_empty) ||
  857. Tok.is(tok::kw___is_floating_point) ||
  858. Tok.is(tok::kw___is_function) ||
  859. Tok.is(tok::kw___is_fundamental) ||
  860. Tok.is(tok::kw___is_integral) ||
  861. Tok.is(tok::kw___is_member_function_pointer) ||
  862. Tok.is(tok::kw___is_member_pointer) ||
  863. Tok.is(tok::kw___is_pod) ||
  864. Tok.is(tok::kw___is_pointer) ||
  865. Tok.is(tok::kw___is_same) ||
  866. Tok.is(tok::kw___is_scalar) ||
  867. Tok.is(tok::kw___is_signed) ||
  868. Tok.is(tok::kw___is_unsigned) ||
  869. Tok.is(tok::kw___is_void))) {
  870. // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
  871. // name of struct templates, but some are keywords in GCC >= 4.3
  872. // and Clang. Therefore, when we see the token sequence "struct
  873. // X", make X into a normal identifier rather than a keyword, to
  874. // allow libstdc++ 4.2 and libc++ to work properly.
  875. Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
  876. Tok.setKind(tok::identifier);
  877. }
  878. // Parse the (optional) nested-name-specifier.
  879. CXXScopeSpec &SS = DS.getTypeSpecScope();
  880. if (getLangOpts().CPlusPlus) {
  881. // "FOO : BAR" is not a potential typo for "FOO::BAR".
  882. ColonProtectionRAIIObject X(*this);
  883. if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
  884. DS.SetTypeSpecError();
  885. if (SS.isSet())
  886. if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
  887. Diag(Tok, diag::err_expected_ident);
  888. }
  889. TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
  890. // Parse the (optional) class name or simple-template-id.
  891. IdentifierInfo *Name = 0;
  892. SourceLocation NameLoc;
  893. TemplateIdAnnotation *TemplateId = 0;
  894. if (Tok.is(tok::identifier)) {
  895. Name = Tok.getIdentifierInfo();
  896. NameLoc = ConsumeToken();
  897. if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
  898. // The name was supposed to refer to a template, but didn't.
  899. // Eat the template argument list and try to continue parsing this as
  900. // a class (or template thereof).
  901. TemplateArgList TemplateArgs;
  902. SourceLocation LAngleLoc, RAngleLoc;
  903. if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS,
  904. true, LAngleLoc,
  905. TemplateArgs, RAngleLoc)) {
  906. // We couldn't parse the template argument list at all, so don't
  907. // try to give any location information for the list.
  908. LAngleLoc = RAngleLoc = SourceLocation();
  909. }
  910. Diag(NameLoc, diag::err_explicit_spec_non_template)
  911. << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
  912. << (TagType == DeclSpec::TST_class? 0
  913. : TagType == DeclSpec::TST_struct? 1
  914. : 2)
  915. << Name
  916. << SourceRange(LAngleLoc, RAngleLoc);
  917. // Strip off the last template parameter list if it was empty, since
  918. // we've removed its template argument list.
  919. if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
  920. if (TemplateParams && TemplateParams->size() > 1) {
  921. TemplateParams->pop_back();
  922. } else {
  923. TemplateParams = 0;
  924. const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
  925. = ParsedTemplateInfo::NonTemplate;
  926. }
  927. } else if (TemplateInfo.Kind
  928. == ParsedTemplateInfo::ExplicitInstantiation) {
  929. // Pretend this is just a forward declaration.
  930. TemplateParams = 0;
  931. const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
  932. = ParsedTemplateInfo::NonTemplate;
  933. const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
  934. = SourceLocation();
  935. const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
  936. = SourceLocation();
  937. }
  938. }
  939. } else if (Tok.is(tok::annot_template_id)) {
  940. TemplateId = takeTemplateIdAnnotation(Tok);
  941. NameLoc = ConsumeToken();
  942. if (TemplateId->Kind != TNK_Type_template &&
  943. TemplateId->Kind != TNK_Dependent_template_name) {
  944. // The template-name in the simple-template-id refers to
  945. // something other than a class template. Give an appropriate
  946. // error message and skip to the ';'.
  947. SourceRange Range(NameLoc);
  948. if (SS.isNotEmpty())
  949. Range.setBegin(SS.getBeginLoc());
  950. Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
  951. << Name << static_cast<int>(TemplateId->Kind) << Range;
  952. DS.SetTypeSpecError();
  953. SkipUntil(tok::semi, false, true);
  954. if (SuppressingAccessChecks)
  955. Actions.ActOnStopSuppressingAccessChecks();
  956. return;
  957. }
  958. }
  959. // As soon as we're finished parsing the class's template-id, turn access
  960. // checking back on.
  961. if (SuppressingAccessChecks)
  962. Actions.ActOnStopSuppressingAccessChecks();
  963. // There are four options here. If we have 'struct foo;', then this
  964. // is either a forward declaration or a friend declaration, which
  965. // have to be treated differently. If we have 'struct foo {...',
  966. // 'struct foo :...' or 'struct foo final[opt]' then this is a
  967. // definition. Otherwise we have something like 'struct foo xyz', a reference.
  968. // However, in some contexts, things look like declarations but are just
  969. // references, e.g.
  970. // new struct s;
  971. // or
  972. // &T::operator struct s;
  973. // For these, SuppressDeclarations is true.
  974. Sema::TagUseKind TUK;
  975. if (SuppressDeclarations)
  976. TUK = Sema::TUK_Reference;
  977. else if (Tok.is(tok::l_brace) ||
  978. (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
  979. isCXX0XFinalKeyword()) {
  980. if (DS.isFriendSpecified()) {
  981. // C++ [class.friend]p2:
  982. // A class shall not be defined in a friend declaration.
  983. Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
  984. << SourceRange(DS.getFriendSpecLoc());
  985. // Skip everything up to the semicolon, so that this looks like a proper
  986. // friend class (or template thereof) declaration.
  987. SkipUntil(tok::semi, true, true);
  988. TUK = Sema::TUK_Friend;
  989. } else {
  990. // Okay, this is a class definition.
  991. TUK = Sema::TUK_Definition;
  992. }
  993. } else if (Tok.is(tok::semi))
  994. TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
  995. else
  996. TUK = Sema::TUK_Reference;
  997. if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
  998. TUK != Sema::TUK_Definition)) {
  999. if (DS.getTypeSpecType() != DeclSpec::TST_error) {
  1000. // We have a declaration or reference to an anonymous class.
  1001. Diag(StartLoc, diag::err_anon_type_definition)
  1002. << DeclSpec::getSpecifierName(TagType);
  1003. }
  1004. SkipUntil(tok::comma, true);
  1005. return;
  1006. }
  1007. // Create the tag portion of the class or class template.
  1008. DeclResult TagOrTempResult = true; // invalid
  1009. TypeResult TypeResult = true; // invalid
  1010. bool Owned = false;
  1011. if (TemplateId) {
  1012. // Explicit specialization, class template partial specialization,
  1013. // or explicit instantiation.
  1014. ASTTemplateArgsPtr TemplateArgsPtr(Actions,
  1015. TemplateId->getTemplateArgs(),
  1016. TemplateId->NumArgs);
  1017. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
  1018. TUK == Sema::TUK_Declaration) {
  1019. // This is an explicit instantiation of a class template.
  1020. TagOrTempResult
  1021. = Actions.ActOnExplicitInstantiation(getCurScope(),
  1022. TemplateInfo.ExternLoc,
  1023. TemplateInfo.TemplateLoc,
  1024. TagType,
  1025. StartLoc,
  1026. SS,
  1027. TemplateId->Template,
  1028. TemplateId->TemplateNameLoc,
  1029. TemplateId->LAngleLoc,
  1030. TemplateArgsPtr,
  1031. TemplateId->RAngleLoc,
  1032. attrs.getList());
  1033. // Friend template-ids are treated as references unless
  1034. // they have template headers, in which case they're ill-formed
  1035. // (FIXME: "template <class T> friend class A<T>::B<int>;").
  1036. // We diagnose this error in ActOnClassTemplateSpecialization.
  1037. } else if (TUK == Sema::TUK_Reference ||
  1038. (TUK == Sema::TUK_Friend &&
  1039. TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
  1040. TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
  1041. TemplateId->SS,
  1042. TemplateId->TemplateKWLoc,
  1043. TemplateId->Template,
  1044. TemplateId->TemplateNameLoc,
  1045. TemplateId->LAngleLoc,
  1046. TemplateArgsPtr,
  1047. TemplateId->RAngleLoc);
  1048. } else {
  1049. // This is an explicit specialization or a class template
  1050. // partial specialization.
  1051. TemplateParameterLists FakedParamLists;
  1052. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
  1053. // This looks like an explicit instantiation, because we have
  1054. // something like
  1055. //
  1056. // template class Foo<X>
  1057. //
  1058. // but it actually has a definition. Most likely, this was
  1059. // meant to be an explicit specialization, but the user forgot
  1060. // the '<>' after 'template'.
  1061. assert(TUK == Sema::TUK_Definition && "Expected a definition here");
  1062. SourceLocation LAngleLoc
  1063. = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
  1064. Diag(TemplateId->TemplateNameLoc,
  1065. diag::err_explicit_instantiation_with_definition)
  1066. << SourceRange(TemplateInfo.TemplateLoc)
  1067. << FixItHint::CreateInsertion(LAngleLoc, "<>");
  1068. // Create a fake template parameter list that contains only
  1069. // "template<>", so that we treat this construct as a class
  1070. // template specialization.
  1071. FakedParamLists.push_back(
  1072. Actions.ActOnTemplateParameterList(0, SourceLocation(),
  1073. TemplateInfo.TemplateLoc,
  1074. LAngleLoc,
  1075. 0, 0,
  1076. LAngleLoc));
  1077. TemplateParams = &FakedParamLists;
  1078. }
  1079. // Build the class template specialization.
  1080. TagOrTempResult
  1081. = Actions.ActOnClassTemplateSpecialization(getCurScope(), TagType, TUK,
  1082. StartLoc, DS.getModulePrivateSpecLoc(), SS,
  1083. TemplateId->Template,
  1084. TemplateId->TemplateNameLoc,
  1085. TemplateId->LAngleLoc,
  1086. TemplateArgsPtr,
  1087. TemplateId->RAngleLoc,
  1088. attrs.getList(),
  1089. MultiTemplateParamsArg(Actions,
  1090. TemplateParams? &(*TemplateParams)[0] : 0,
  1091. TemplateParams? TemplateParams->size() : 0));
  1092. }
  1093. } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
  1094. TUK == Sema::TUK_Declaration) {
  1095. // Explicit instantiation of a member of a class template
  1096. // specialization, e.g.,
  1097. //
  1098. // template struct Outer<int>::Inner;
  1099. //
  1100. TagOrTempResult
  1101. = Actions.ActOnExplicitInstantiation(getCurScope(),
  1102. TemplateInfo.ExternLoc,
  1103. TemplateInfo.TemplateLoc,
  1104. TagType, StartLoc, SS, Name,
  1105. NameLoc, attrs.getList());
  1106. } else if (TUK == Sema::TUK_Friend &&
  1107. TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
  1108. TagOrTempResult =
  1109. Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
  1110. TagType, StartLoc, SS,
  1111. Name, NameLoc, attrs.getList(),
  1112. MultiTemplateParamsArg(Actions,
  1113. TemplateParams? &(*TemplateParams)[0] : 0,
  1114. TemplateParams? TemplateParams->size() : 0));
  1115. } else {
  1116. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
  1117. TUK == Sema::TUK_Definition) {
  1118. // FIXME: Diagnose this particular error.
  1119. }
  1120. bool IsDependent = false;
  1121. // Don't pass down template parameter lists if this is just a tag
  1122. // reference. For example, we don't need the template parameters here:
  1123. // template <class T> class A *makeA(T t);
  1124. MultiTemplateParamsArg TParams;
  1125. if (TUK != Sema::TUK_Reference && TemplateParams)
  1126. TParams =
  1127. MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
  1128. // Declaration or definition of a class type
  1129. TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
  1130. SS, Name, NameLoc, attrs.getList(), AS,
  1131. DS.getModulePrivateSpecLoc(),
  1132. TParams, Owned, IsDependent,
  1133. SourceLocation(), false,
  1134. clang::TypeResult());
  1135. // If ActOnTag said the type was dependent, try again with the
  1136. // less common call.
  1137. if (IsDependent) {
  1138. assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
  1139. TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
  1140. SS, Name, StartLoc, NameLoc);
  1141. }
  1142. }
  1143. // If there is a body, parse it and inform the actions module.
  1144. if (TUK == Sema::TUK_Definition) {
  1145. assert(Tok.is(tok::l_brace) ||
  1146. (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
  1147. isCXX0XFinalKeyword());
  1148. if (getLangOpts().CPlusPlus)
  1149. ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get());
  1150. else
  1151. ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
  1152. }
  1153. const char *PrevSpec = 0;
  1154. unsigned DiagID;
  1155. bool Result;
  1156. if (!TypeResult.isInvalid()) {
  1157. Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
  1158. NameLoc.isValid() ? NameLoc : StartLoc,
  1159. PrevSpec, DiagID, TypeResult.get());
  1160. } else if (!TagOrTempResult.isInvalid()) {
  1161. Result = DS.SetTypeSpecType(TagType, StartLoc,
  1162. NameLoc.isValid() ? NameLoc : StartLoc,
  1163. PrevSpec, DiagID, TagOrTempResult.get(), Owned);
  1164. } else {
  1165. DS.SetTypeSpecError();
  1166. return;
  1167. }
  1168. if (Result)
  1169. Diag(StartLoc, DiagID) << PrevSpec;
  1170. // At this point, we've successfully parsed a class-specifier in 'definition'
  1171. // form (e.g. "struct foo { int x; }". While we could just return here, we're
  1172. // going to look at what comes after it to improve error recovery. If an
  1173. // impossible token occurs next, we assume that the programmer forgot a ; at
  1174. // the end of the declaration and recover that way.
  1175. //
  1176. // This switch enumerates the valid "follow" set for definition.
  1177. if (TUK == Sema::TUK_Definition) {
  1178. bool ExpectedSemi = true;
  1179. switch (Tok.getKind()) {
  1180. default: break;
  1181. case tok::semi: // struct foo {...} ;
  1182. case tok::star: // struct foo {...} * P;
  1183. case tok::amp: // struct foo {...} & R = ...
  1184. case tok::identifier: // struct foo {...} V ;
  1185. case tok::r_paren: //(struct foo {...} ) {4}
  1186. case tok::annot_cxxscope: // struct foo {...} a:: b;
  1187. case tok::annot_typename: // struct foo {...} a ::b;
  1188. case tok::annot_template_id: // struct foo {...} a<int> ::b;
  1189. case tok::l_paren: // struct foo {...} ( x);
  1190. case tok::comma: // __builtin_offsetof(struct foo{...} ,
  1191. ExpectedSemi = false;
  1192. break;
  1193. // Type qualifiers
  1194. case tok::kw_const: // struct foo {...} const x;
  1195. case tok::kw_volatile: // struct foo {...} volatile x;
  1196. case tok::kw_restrict: // struct foo {...} restrict x;
  1197. case tok::kw_inline: // struct foo {...} inline foo() {};
  1198. // Storage-class specifiers
  1199. case tok::kw_static: // struct foo {...} static x;
  1200. case tok::kw_extern: // struct foo {...} extern x;
  1201. case tok::kw_typedef: // struct foo {...} typedef x;
  1202. case tok::kw_register: // struct foo {...} register x;
  1203. case tok::kw_auto: // struct foo {...} auto x;
  1204. case tok::kw_mutable: // struct foo {...} mutable x;
  1205. case tok::kw_constexpr: // struct foo {...} constexpr x;
  1206. // As shown above, type qualifiers and storage class specifiers absolutely
  1207. // can occur after class specifiers according to the grammar. However,
  1208. // almost no one actually writes code like this. If we see one of these,
  1209. // it is much more likely that someone missed a semi colon and the
  1210. // type/storage class specifier we're seeing is part of the *next*
  1211. // intended declaration, as in:
  1212. //
  1213. // struct foo { ... }
  1214. // typedef int X;
  1215. //
  1216. // We'd really like to emit a missing semicolon error instead of emitting
  1217. // an error on the 'int' saying that you can't have two type specifiers in
  1218. // the same declaration of X. Because of this, we look ahead past this
  1219. // token to see if it's a type specifier. If so, we know the code is
  1220. // otherwise invalid, so we can produce the expected semi error.
  1221. if (!isKnownToBeTypeSpecifier(NextToken()))
  1222. ExpectedSemi = false;
  1223. break;
  1224. case tok::r_brace: // struct bar { struct foo {...} }
  1225. // Missing ';' at end of struct is accepted as an extension in C mode.
  1226. if (!getLangOpts().CPlusPlus)
  1227. ExpectedSemi = false;
  1228. break;
  1229. }
  1230. // C++ [temp]p3 In a template-declaration which defines a class, no
  1231. // declarator is permitted.
  1232. if (TemplateInfo.Kind)
  1233. ExpectedSemi = true;
  1234. if (ExpectedSemi) {
  1235. ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
  1236. TagType == DeclSpec::TST_class ? "class"
  1237. : TagType == DeclSpec::TST_struct? "struct" : "union");
  1238. // Push this token back into the preprocessor and change our current token
  1239. // to ';' so that the rest of the code recovers as though there were an
  1240. // ';' after the definition.
  1241. PP.EnterToken(Tok);
  1242. Tok.setKind(tok::semi);
  1243. }
  1244. }
  1245. }
  1246. /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
  1247. ///
  1248. /// base-clause : [C++ class.derived]
  1249. /// ':' base-specifier-list
  1250. /// base-specifier-list:
  1251. /// base-specifier '...'[opt]
  1252. /// base-specifier-list ',' base-specifier '...'[opt]
  1253. void Parser::ParseBaseClause(Decl *ClassDecl) {
  1254. assert(Tok.is(tok::colon) && "Not a base clause");
  1255. ConsumeToken();
  1256. // Build up an array of parsed base specifiers.
  1257. SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
  1258. while (true) {
  1259. // Parse a base-specifier.
  1260. BaseResult Result = ParseBaseSpecifier(ClassDecl);
  1261. if (Result.isInvalid()) {
  1262. // Skip the rest of this base specifier, up until the comma or
  1263. // opening brace.
  1264. SkipUntil(tok::comma, tok::l_brace, true, true);
  1265. } else {
  1266. // Add this to our array of base specifiers.
  1267. BaseInfo.push_back(Result.get());
  1268. }
  1269. // If the next token is a comma, consume it and keep reading
  1270. // base-specifiers.
  1271. if (Tok.isNot(tok::comma)) break;
  1272. // Consume the comma.
  1273. ConsumeToken();
  1274. }
  1275. // Attach the base specifiers
  1276. Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
  1277. }
  1278. /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
  1279. /// one entry in the base class list of a class specifier, for example:
  1280. /// class foo : public bar, virtual private baz {
  1281. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  1282. ///
  1283. /// base-specifier: [C++ class.derived]
  1284. /// ::[opt] nested-name-specifier[opt] class-name
  1285. /// 'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
  1286. /// base-type-specifier
  1287. /// access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
  1288. /// base-type-specifier
  1289. Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
  1290. bool IsVirtual = false;
  1291. SourceLocation StartLoc = Tok.getLocation();
  1292. // Parse the 'virtual' keyword.
  1293. if (Tok.is(tok::kw_virtual)) {
  1294. ConsumeToken();
  1295. IsVirtual = true;
  1296. }
  1297. // Parse an (optional) access specifier.
  1298. AccessSpecifier Access = getAccessSpecifierIfPresent();
  1299. if (Access != AS_none)
  1300. ConsumeToken();
  1301. // Parse the 'virtual' keyword (again!), in case it came after the
  1302. // access specifier.
  1303. if (Tok.is(tok::kw_virtual)) {
  1304. SourceLocation VirtualLoc = ConsumeToken();
  1305. if (IsVirtual) {
  1306. // Complain about duplicate 'virtual'
  1307. Diag(VirtualLoc, diag::err_dup_virtual)
  1308. << FixItHint::CreateRemoval(VirtualLoc);
  1309. }
  1310. IsVirtual = true;
  1311. }
  1312. // Parse the class-name.
  1313. SourceLocation EndLocation;
  1314. SourceLocation BaseLoc;
  1315. TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
  1316. if (BaseType.isInvalid())
  1317. return true;
  1318. // Parse the optional ellipsis (for a pack expansion). The ellipsis is
  1319. // actually part of the base-specifier-list grammar productions, but we
  1320. // parse it here for convenience.
  1321. SourceLocation EllipsisLoc;
  1322. if (Tok.is(tok::ellipsis))
  1323. EllipsisLoc = ConsumeToken();
  1324. // Find the complete source range for the base-specifier.
  1325. SourceRange Range(StartLoc, EndLocation);
  1326. // Notify semantic analysis that we have parsed a complete
  1327. // base-specifier.
  1328. return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
  1329. BaseType.get(), BaseLoc, EllipsisLoc);
  1330. }
  1331. /// getAccessSpecifierIfPresent - Determine whether the next token is
  1332. /// a C++ access-specifier.
  1333. ///
  1334. /// access-specifier: [C++ class.derived]
  1335. /// 'private'
  1336. /// 'protected'
  1337. /// 'public'
  1338. AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
  1339. switch (Tok.getKind()) {
  1340. default: return AS_none;
  1341. case tok::kw_private: return AS_private;
  1342. case tok::kw_protected: return AS_protected;
  1343. case tok::kw_public: return AS_public;
  1344. }
  1345. }
  1346. void Parser::HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo,
  1347. Decl *ThisDecl) {
  1348. // We just declared a member function. If this member function
  1349. // has any default arguments, we'll need to parse them later.
  1350. LateParsedMethodDeclaration *LateMethod = 0;
  1351. DeclaratorChunk::FunctionTypeInfo &FTI
  1352. = DeclaratorInfo.getFunctionTypeInfo();
  1353. for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
  1354. if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
  1355. if (!LateMethod) {
  1356. // Push this method onto the stack of late-parsed method
  1357. // declarations.
  1358. LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
  1359. getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
  1360. LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
  1361. // Add all of the parameters prior to this one (they don't
  1362. // have default arguments).
  1363. LateMethod->DefaultArgs.reserve(FTI.NumArgs);
  1364. for (unsigned I = 0; I < ParamIdx; ++I)
  1365. LateMethod->DefaultArgs.push_back(
  1366. LateParsedDefaultArgument(FTI.ArgInfo[I].Param));
  1367. }
  1368. // Add this parameter to the list of parameters (it or may
  1369. // not have a default argument).
  1370. LateMethod->DefaultArgs.push_back(
  1371. LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
  1372. FTI.ArgInfo[ParamIdx].DefaultArgTokens));
  1373. }
  1374. }
  1375. }
  1376. /// isCXX0XVirtSpecifier - Determine whether the given token is a C++0x
  1377. /// virt-specifier.
  1378. ///
  1379. /// virt-specifier:
  1380. /// override
  1381. /// final
  1382. VirtSpecifiers::Specifier Parser::isCXX0XVirtSpecifier(const Token &Tok) const {
  1383. if (!getLangOpts().CPlusPlus)
  1384. return VirtSpecifiers::VS_None;
  1385. if (Tok.is(tok::identifier)) {
  1386. IdentifierInfo *II = Tok.getIdentifierInfo();
  1387. // Initialize the contextual keywords.
  1388. if (!Ident_final) {
  1389. Ident_final = &PP.getIdentifierTable().get("final");
  1390. Ident_override = &PP.getIdentifierTable().get("override");
  1391. }
  1392. if (II == Ident_override)
  1393. return VirtSpecifiers::VS_Override;
  1394. if (II == Ident_final)
  1395. return VirtSpecifiers::VS_Final;
  1396. }
  1397. return VirtSpecifiers::VS_None;
  1398. }
  1399. /// ParseOptionalCXX0XVirtSpecifierSeq - Parse a virt-specifier-seq.
  1400. ///
  1401. /// virt-specifier-seq:
  1402. /// virt-specifier
  1403. /// virt-specifier-seq virt-specifier
  1404. void Parser::ParseOptionalCXX0XVirtSpecifierSeq(VirtSpecifiers &VS) {
  1405. while (true) {
  1406. VirtSpecifiers::Specifier Specifier = isCXX0XVirtSpecifier();
  1407. if (Specifier == VirtSpecifiers::VS_None)
  1408. return;
  1409. // C++ [class.mem]p8:
  1410. // A virt-specifier-seq shall contain at most one of each virt-specifier.
  1411. const char *PrevSpec = 0;
  1412. if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
  1413. Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
  1414. << PrevSpec
  1415. << FixItHint::CreateRemoval(Tok.getLocation());
  1416. Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
  1417. diag::warn_cxx98_compat_override_control_keyword :
  1418. diag::ext_override_control_keyword)
  1419. << VirtSpecifiers::getSpecifierName(Specifier);
  1420. ConsumeToken();
  1421. }
  1422. }
  1423. /// isCXX0XFinalKeyword - Determine whether the next token is a C++0x
  1424. /// contextual 'final' keyword.
  1425. bool Parser::isCXX0XFinalKeyword() const {
  1426. if (!getLangOpts().CPlusPlus)
  1427. return false;
  1428. if (!Tok.is(tok::identifier))
  1429. return false;
  1430. // Initialize the contextual keywords.
  1431. if (!Ident_final) {
  1432. Ident_final = &PP.getIdentifierTable().get("final");
  1433. Ident_override = &PP.getIdentifierTable().get("override");
  1434. }
  1435. return Tok.getIdentifierInfo() == Ident_final;
  1436. }
  1437. /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
  1438. ///
  1439. /// member-declaration:
  1440. /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
  1441. /// function-definition ';'[opt]
  1442. /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
  1443. /// using-declaration [TODO]
  1444. /// [C++0x] static_assert-declaration
  1445. /// template-declaration
  1446. /// [GNU] '__extension__' member-declaration
  1447. ///
  1448. /// member-declarator-list:
  1449. /// member-declarator
  1450. /// member-declarator-list ',' member-declarator
  1451. ///
  1452. /// member-declarator:
  1453. /// declarator virt-specifier-seq[opt] pure-specifier[opt]
  1454. /// declarator constant-initializer[opt]
  1455. /// [C++11] declarator brace-or-equal-initializer[opt]
  1456. /// identifier[opt] ':' constant-expression
  1457. ///
  1458. /// virt-specifier-seq:
  1459. /// virt-specifier
  1460. /// virt-specifier-seq virt-specifier
  1461. ///
  1462. /// virt-specifier:
  1463. /// override
  1464. /// final
  1465. ///
  1466. /// pure-specifier:
  1467. /// '= 0'
  1468. ///
  1469. /// constant-initializer:
  1470. /// '=' constant-expression
  1471. ///
  1472. void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
  1473. AttributeList *AccessAttrs,
  1474. const ParsedTemplateInfo &TemplateInfo,
  1475. ParsingDeclRAIIObject *TemplateDiags) {
  1476. if (Tok.is(tok::at)) {
  1477. if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
  1478. Diag(Tok, diag::err_at_defs_cxx);
  1479. else
  1480. Diag(Tok, diag::err_at_in_class);
  1481. ConsumeToken();
  1482. SkipUntil(tok::r_brace);
  1483. return;
  1484. }
  1485. // Access declarations.
  1486. if (!TemplateInfo.Kind &&
  1487. (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) &&
  1488. !TryAnnotateCXXScopeToken() &&
  1489. Tok.is(tok::annot_cxxscope)) {
  1490. bool isAccessDecl = false;
  1491. if (NextToken().is(tok::identifier))
  1492. isAccessDecl = GetLookAheadToken(2).is(tok::semi);
  1493. else
  1494. isAccessDecl = NextToken().is(tok::kw_operator);
  1495. if (isAccessDecl) {
  1496. // Collect the scope specifier token we annotated earlier.
  1497. CXXScopeSpec SS;
  1498. ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
  1499. /*EnteringContext=*/false);
  1500. // Try to parse an unqualified-id.
  1501. SourceLocation TemplateKWLoc;
  1502. UnqualifiedId Name;
  1503. if (ParseUnqualifiedId(SS, false, true, true, ParsedType(),
  1504. TemplateKWLoc, Name)) {
  1505. SkipUntil(tok::semi);
  1506. return;
  1507. }
  1508. // TODO: recover from mistakenly-qualified operator declarations.
  1509. if (ExpectAndConsume(tok::semi,
  1510. diag::err_expected_semi_after,
  1511. "access declaration",
  1512. tok::semi))
  1513. return;
  1514. Actions.ActOnUsingDeclaration(getCurScope(), AS,
  1515. false, SourceLocation(),
  1516. SS, Name,
  1517. /* AttrList */ 0,
  1518. /* IsTypeName */ false,
  1519. SourceLocation());
  1520. return;
  1521. }
  1522. }
  1523. // static_assert-declaration
  1524. if (Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) {
  1525. // FIXME: Check for templates
  1526. SourceLocation DeclEnd;
  1527. ParseStaticAssertDeclaration(DeclEnd);
  1528. return;
  1529. }
  1530. if (Tok.is(tok::kw_template)) {
  1531. assert(!TemplateInfo.TemplateParams &&
  1532. "Nested template improperly parsed?");
  1533. SourceLocation DeclEnd;
  1534. ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
  1535. AS, AccessAttrs);
  1536. return;
  1537. }
  1538. // Handle: member-declaration ::= '__extension__' member-declaration
  1539. if (Tok.is(tok::kw___extension__)) {
  1540. // __extension__ silences extension warnings in the subexpression.
  1541. ExtensionRAIIObject O(Diags); // Use RAII to do this.
  1542. ConsumeToken();
  1543. return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
  1544. TemplateInfo, TemplateDiags);
  1545. }
  1546. // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it
  1547. // is a bitfield.
  1548. ColonProtectionRAIIObject X(*this);
  1549. ParsedAttributesWithRange attrs(AttrFactory);
  1550. // Optional C++0x attribute-specifier
  1551. MaybeParseCXX0XAttributes(attrs);
  1552. MaybeParseMicrosoftAttributes(attrs);
  1553. if (Tok.is(tok::kw_using)) {
  1554. ProhibitAttributes(attrs);
  1555. // Eat 'using'.
  1556. SourceLocation UsingLoc = ConsumeToken();
  1557. if (Tok.is(tok::kw_namespace)) {
  1558. Diag(UsingLoc, diag::err_using_namespace_in_class);
  1559. SkipUntil(tok::semi, true, true);
  1560. } else {
  1561. SourceLocation DeclEnd;
  1562. // Otherwise, it must be a using-declaration or an alias-declaration.
  1563. ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
  1564. UsingLoc, DeclEnd, AS);
  1565. }
  1566. return;
  1567. }
  1568. // Hold late-parsed attributes so we can attach a Decl to them later.
  1569. LateParsedAttrList CommonLateParsedAttrs;
  1570. // decl-specifier-seq:
  1571. // Parse the common declaration-specifiers piece.
  1572. ParsingDeclSpec DS(*this, TemplateDiags);
  1573. DS.takeAttributesFrom(attrs);
  1574. ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
  1575. &CommonLateParsedAttrs);
  1576. MultiTemplateParamsArg TemplateParams(Actions,
  1577. TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0,
  1578. TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
  1579. if (Tok.is(tok::semi)) {
  1580. ConsumeToken();
  1581. Decl *TheDecl =
  1582. Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams);
  1583. DS.complete(TheDecl);
  1584. return;
  1585. }
  1586. ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
  1587. VirtSpecifiers VS;
  1588. // Hold late-parsed attributes so we can attach a Decl to them later.
  1589. LateParsedAttrList LateParsedAttrs;
  1590. SourceLocation EqualLoc;
  1591. bool HasInitializer = false;
  1592. ExprResult Init;
  1593. if (Tok.isNot(tok::colon)) {
  1594. // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
  1595. ColonProtectionRAIIObject X(*this);
  1596. // Parse the first declarator.
  1597. ParseDeclarator(DeclaratorInfo);
  1598. // Error parsing the declarator?
  1599. if (!DeclaratorInfo.hasName()) {
  1600. // If so, skip until the semi-colon or a }.
  1601. SkipUntil(tok::r_brace, true, true);
  1602. if (Tok.is(tok::semi))
  1603. ConsumeToken();
  1604. return;
  1605. }
  1606. ParseOptionalCXX0XVirtSpecifierSeq(VS);
  1607. // If attributes exist after the declarator, but before an '{', parse them.
  1608. MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
  1609. // MSVC permits pure specifier on inline functions declared at class scope.
  1610. // Hence check for =0 before checking for function definition.
  1611. if (getLangOpts().MicrosoftExt && Tok.is(tok::equal) &&
  1612. DeclaratorInfo.isFunctionDeclarator() &&
  1613. NextToken().is(tok::numeric_constant)) {
  1614. EqualLoc = ConsumeToken();
  1615. Init = ParseInitializer();
  1616. if (Init.isInvalid())
  1617. SkipUntil(tok::comma, true, true);
  1618. else
  1619. HasInitializer = true;
  1620. }
  1621. FunctionDefinitionKind DefinitionKind = FDK_Declaration;
  1622. // function-definition:
  1623. //
  1624. // In C++11, a non-function declarator followed by an open brace is a
  1625. // braced-init-list for an in-class member initialization, not an
  1626. // erroneous function definition.
  1627. if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus0x) {
  1628. DefinitionKind = FDK_Definition;
  1629. } else if (DeclaratorInfo.isFunctionDeclarator()) {
  1630. if (Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
  1631. DefinitionKind = FDK_Definition;
  1632. } else if (Tok.is(tok::equal)) {
  1633. const Token &KW = NextToken();
  1634. if (KW.is(tok::kw_default))
  1635. DefinitionKind = FDK_Defaulted;
  1636. else if (KW.is(tok::kw_delete))
  1637. DefinitionKind = FDK_Deleted;
  1638. }
  1639. }
  1640. if (DefinitionKind) {
  1641. if (!DeclaratorInfo.isFunctionDeclarator()) {
  1642. Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
  1643. ConsumeBrace();
  1644. SkipUntil(tok::r_brace, /*StopAtSemi*/false);
  1645. // Consume the optional ';'
  1646. if (Tok.is(tok::semi))
  1647. ConsumeToken();
  1648. return;
  1649. }
  1650. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
  1651. Diag(DeclaratorInfo.getIdentifierLoc(),
  1652. diag::err_function_declared_typedef);
  1653. // This recovery skips the entire function body. It would be nice
  1654. // to simply call ParseCXXInlineMethodDef() below, however Sema
  1655. // assumes the declarator represents a function, not a typedef.
  1656. ConsumeBrace();
  1657. SkipUntil(tok::r_brace, /*StopAtSemi*/false);
  1658. // Consume the optional ';'
  1659. if (Tok.is(tok::semi))
  1660. ConsumeToken();
  1661. return;
  1662. }
  1663. Decl *FunDecl =
  1664. ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
  1665. VS, DefinitionKind, Init);
  1666. for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
  1667. CommonLateParsedAttrs[i]->addDecl(FunDecl);
  1668. }
  1669. for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
  1670. LateParsedAttrs[i]->addDecl(FunDecl);
  1671. }
  1672. LateParsedAttrs.clear();
  1673. // Consume the ';' - it's optional unless we have a delete or default
  1674. if (Tok.is(tok::semi)) {
  1675. ConsumeToken();
  1676. }
  1677. return;
  1678. }
  1679. }
  1680. // member-declarator-list:
  1681. // member-declarator
  1682. // member-declarator-list ',' member-declarator
  1683. SmallVector<Decl *, 8> DeclsInGroup;
  1684. ExprResult BitfieldSize;
  1685. bool ExpectSemi = true;
  1686. while (1) {
  1687. // member-declarator:
  1688. // declarator pure-specifier[opt]
  1689. // declarator brace-or-equal-initializer[opt]
  1690. // identifier[opt] ':' constant-expression
  1691. if (Tok.is(tok::colon)) {
  1692. ConsumeToken();
  1693. BitfieldSize = ParseConstantExpression();
  1694. if (BitfieldSize.isInvalid())
  1695. SkipUntil(tok::comma, true, true);
  1696. }
  1697. // If a simple-asm-expr is present, parse it.
  1698. if (Tok.is(tok::kw_asm)) {
  1699. SourceLocation Loc;
  1700. ExprResult AsmLabel(ParseSimpleAsm(&Loc));
  1701. if (AsmLabel.isInvalid())
  1702. SkipUntil(tok::comma, true, true);
  1703. DeclaratorInfo.setAsmLabel(AsmLabel.release());
  1704. DeclaratorInfo.SetRangeEnd(Loc);
  1705. }
  1706. // If attributes exist after the declarator, parse them.
  1707. MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
  1708. // FIXME: When g++ adds support for this, we'll need to check whether it
  1709. // goes before or after the GNU attributes and __asm__.
  1710. ParseOptionalCXX0XVirtSpecifierSeq(VS);
  1711. bool HasDeferredInitializer = false;
  1712. if ((Tok.is(tok::equal) || Tok.is(tok::l_brace)) && !HasInitializer) {
  1713. if (BitfieldSize.get()) {
  1714. Diag(Tok, diag::err_bitfield_member_init);
  1715. SkipUntil(tok::comma, true, true);
  1716. } else {
  1717. HasInitializer = true;
  1718. HasDeferredInitializer = !DeclaratorInfo.isDeclarationOfFunction() &&
  1719. DeclaratorInfo.getDeclSpec().getStorageClassSpec()
  1720. != DeclSpec::SCS_static &&
  1721. DeclaratorInfo.getDeclSpec().getStorageClassSpec()
  1722. != DeclSpec::SCS_typedef;
  1723. }
  1724. }
  1725. // NOTE: If Sema is the Action module and declarator is an instance field,
  1726. // this call will *not* return the created decl; It will return null.
  1727. // See Sema::ActOnCXXMemberDeclarator for details.
  1728. Decl *ThisDecl = 0;
  1729. if (DS.isFriendSpecified()) {
  1730. // TODO: handle initializers, bitfields, 'delete'
  1731. ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
  1732. move(TemplateParams));
  1733. } else {
  1734. ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
  1735. DeclaratorInfo,
  1736. move(TemplateParams),
  1737. BitfieldSize.release(),
  1738. VS, HasDeferredInitializer);
  1739. if (AccessAttrs)
  1740. Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs,
  1741. false, true);
  1742. }
  1743. // Set the Decl for any late parsed attributes
  1744. for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
  1745. CommonLateParsedAttrs[i]->addDecl(ThisDecl);
  1746. }
  1747. for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
  1748. LateParsedAttrs[i]->addDecl(ThisDecl);
  1749. }
  1750. LateParsedAttrs.clear();
  1751. // Handle the initializer.
  1752. if (HasDeferredInitializer) {
  1753. // The initializer was deferred; parse it and cache the tokens.
  1754. Diag(Tok, getLangOpts().CPlusPlus0x ?
  1755. diag::warn_cxx98_compat_nonstatic_member_init :
  1756. diag::ext_nonstatic_member_init);
  1757. if (DeclaratorInfo.isArrayOfUnknownBound()) {
  1758. // C++0x [dcl.array]p3: An array bound may also be omitted when the
  1759. // declarator is followed by an initializer.
  1760. //
  1761. // A brace-or-equal-initializer for a member-declarator is not an
  1762. // initializer in the grammar, so this is ill-formed.
  1763. Diag(Tok, diag::err_incomplete_array_member_init);
  1764. SkipUntil(tok::comma, true, true);
  1765. if (ThisDecl)
  1766. // Avoid later warnings about a class member of incomplete type.
  1767. ThisDecl->setInvalidDecl();
  1768. } else
  1769. ParseCXXNonStaticMemberInitializer(ThisDecl);
  1770. } else if (HasInitializer) {
  1771. // Normal initializer.
  1772. if (!Init.isUsable())
  1773. Init = ParseCXXMemberInitializer(ThisDecl,
  1774. DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
  1775. if (Init.isInvalid())
  1776. SkipUntil(tok::comma, true, true);
  1777. else if (ThisDecl)
  1778. Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
  1779. DS.getTypeSpecType() == DeclSpec::TST_auto);
  1780. } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static) {
  1781. // No initializer.
  1782. Actions.ActOnUninitializedDecl(ThisDecl,
  1783. DS.getTypeSpecType() == DeclSpec::TST_auto);
  1784. }
  1785. if (ThisDecl) {
  1786. Actions.FinalizeDeclaration(ThisDecl);
  1787. DeclsInGroup.push_back(ThisDecl);
  1788. }
  1789. if (DeclaratorInfo.isFunctionDeclarator() &&
  1790. DeclaratorInfo.getDeclSpec().getStorageClassSpec()
  1791. != DeclSpec::SCS_typedef) {
  1792. HandleMemberFunctionDefaultArgs(DeclaratorInfo, ThisDecl);
  1793. }
  1794. DeclaratorInfo.complete(ThisDecl);
  1795. // If we don't have a comma, it is either the end of the list (a ';')
  1796. // or an error, bail out.
  1797. if (Tok.isNot(tok::comma))
  1798. break;
  1799. // Consume the comma.
  1800. SourceLocation CommaLoc = ConsumeToken();
  1801. if (Tok.isAtStartOfLine() &&
  1802. !MightBeDeclarator(Declarator::MemberContext)) {
  1803. // This comma was followed by a line-break and something which can't be
  1804. // the start of a declarator. The comma was probably a typo for a
  1805. // semicolon.
  1806. Diag(CommaLoc, diag::err_expected_semi_declaration)
  1807. << FixItHint::CreateReplacement(CommaLoc, ";");
  1808. ExpectSemi = false;
  1809. break;
  1810. }
  1811. // Parse the next declarator.
  1812. DeclaratorInfo.clear();
  1813. VS.clear();
  1814. BitfieldSize = true;
  1815. Init = true;
  1816. HasInitializer = false;
  1817. DeclaratorInfo.setCommaLoc(CommaLoc);
  1818. // Attributes are only allowed on the second declarator.
  1819. MaybeParseGNUAttributes(DeclaratorInfo);
  1820. if (Tok.isNot(tok::colon))
  1821. ParseDeclarator(DeclaratorInfo);
  1822. }
  1823. if (ExpectSemi &&
  1824. ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
  1825. // Skip to end of block or statement.
  1826. SkipUntil(tok::r_brace, true, true);
  1827. // If we stopped at a ';', eat it.
  1828. if (Tok.is(tok::semi)) ConsumeToken();
  1829. return;
  1830. }
  1831. Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup.data(),
  1832. DeclsInGroup.size());
  1833. }
  1834. /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer or
  1835. /// pure-specifier. Also detect and reject any attempted defaulted/deleted
  1836. /// function definition. The location of the '=', if any, will be placed in
  1837. /// EqualLoc.
  1838. ///
  1839. /// pure-specifier:
  1840. /// '= 0'
  1841. ///
  1842. /// brace-or-equal-initializer:
  1843. /// '=' initializer-expression
  1844. /// braced-init-list
  1845. ///
  1846. /// initializer-clause:
  1847. /// assignment-expression
  1848. /// braced-init-list
  1849. ///
  1850. /// defaulted/deleted function-definition:
  1851. /// '=' 'default'
  1852. /// '=' 'delete'
  1853. ///
  1854. /// Prior to C++0x, the assignment-expression in an initializer-clause must
  1855. /// be a constant-expression.
  1856. ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
  1857. SourceLocation &EqualLoc) {
  1858. assert((Tok.is(tok::equal) || Tok.is(tok::l_brace))
  1859. && "Data member initializer not starting with '=' or '{'");
  1860. EnterExpressionEvaluationContext Context(Actions,
  1861. Sema::PotentiallyEvaluated,
  1862. D);
  1863. if (Tok.is(tok::equal)) {
  1864. EqualLoc = ConsumeToken();
  1865. if (Tok.is(tok::kw_delete)) {
  1866. // In principle, an initializer of '= delete p;' is legal, but it will
  1867. // never type-check. It's better to diagnose it as an ill-formed expression
  1868. // than as an ill-formed deleted non-function member.
  1869. // An initializer of '= delete p, foo' will never be parsed, because
  1870. // a top-level comma always ends the initializer expression.
  1871. const Token &Next = NextToken();
  1872. if (IsFunction || Next.is(tok::semi) || Next.is(tok::comma) ||
  1873. Next.is(tok::eof)) {
  1874. if (IsFunction)
  1875. Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
  1876. << 1 /* delete */;
  1877. else
  1878. Diag(ConsumeToken(), diag::err_deleted_non_function);
  1879. return ExprResult();
  1880. }
  1881. } else if (Tok.is(tok::kw_default)) {
  1882. if (IsFunction)
  1883. Diag(Tok, diag::err_default_delete_in_multiple_declaration)
  1884. << 0 /* default */;
  1885. else
  1886. Diag(ConsumeToken(), diag::err_default_special_members);
  1887. return ExprResult();
  1888. }
  1889. }
  1890. return ParseInitializer();
  1891. }
  1892. /// ParseCXXMemberSpecification - Parse the class definition.
  1893. ///
  1894. /// member-specification:
  1895. /// member-declaration member-specification[opt]
  1896. /// access-specifier ':' member-specification[opt]
  1897. ///
  1898. void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
  1899. unsigned TagType, Decl *TagDecl) {
  1900. assert((TagType == DeclSpec::TST_struct ||
  1901. TagType == DeclSpec::TST_union ||
  1902. TagType == DeclSpec::TST_class) && "Invalid TagType!");
  1903. PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
  1904. "parsing struct/union/class body");
  1905. // Determine whether this is a non-nested class. Note that local
  1906. // classes are *not* considered to be nested classes.
  1907. bool NonNestedClass = true;
  1908. if (!ClassStack.empty()) {
  1909. for (const Scope *S = getCurScope(); S; S = S->getParent()) {
  1910. if (S->isClassScope()) {
  1911. // We're inside a class scope, so this is a nested class.
  1912. NonNestedClass = false;
  1913. break;
  1914. }
  1915. if ((S->getFlags() & Scope::FnScope)) {
  1916. // If we're in a function or function template declared in the
  1917. // body of a class, then this is a local class rather than a
  1918. // nested class.
  1919. const Scope *Parent = S->getParent();
  1920. if (Parent->isTemplateParamScope())
  1921. Parent = Parent->getParent();
  1922. if (Parent->isClassScope())
  1923. break;
  1924. }
  1925. }
  1926. }
  1927. // Enter a scope for the class.
  1928. ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
  1929. // Note that we are parsing a new (potentially-nested) class definition.
  1930. ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass);
  1931. if (TagDecl)
  1932. Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
  1933. SourceLocation FinalLoc;
  1934. // Parse the optional 'final' keyword.
  1935. if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
  1936. assert(isCXX0XFinalKeyword() && "not a class definition");
  1937. FinalLoc = ConsumeToken();
  1938. Diag(FinalLoc, getLangOpts().CPlusPlus0x ?
  1939. diag::warn_cxx98_compat_override_control_keyword :
  1940. diag::ext_override_control_keyword) << "final";
  1941. }
  1942. if (Tok.is(tok::colon)) {
  1943. ParseBaseClause(TagDecl);
  1944. if (!Tok.is(tok::l_brace)) {
  1945. Diag(Tok, diag::err_expected_lbrace_after_base_specifiers);
  1946. if (TagDecl)
  1947. Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
  1948. return;
  1949. }
  1950. }
  1951. assert(Tok.is(tok::l_brace));
  1952. BalancedDelimiterTracker T(*this, tok::l_brace);
  1953. T.consumeOpen();
  1954. if (TagDecl)
  1955. Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
  1956. T.getOpenLocation());
  1957. // C++ 11p3: Members of a class defined with the keyword class are private
  1958. // by default. Members of a class defined with the keywords struct or union
  1959. // are public by default.
  1960. AccessSpecifier CurAS;
  1961. if (TagType == DeclSpec::TST_class)
  1962. CurAS = AS_private;
  1963. else
  1964. CurAS = AS_public;
  1965. ParsedAttributes AccessAttrs(AttrFactory);
  1966. if (TagDecl) {
  1967. // While we still have something to read, read the member-declarations.
  1968. while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
  1969. // Each iteration of this loop reads one member-declaration.
  1970. if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
  1971. Tok.is(tok::kw___if_not_exists))) {
  1972. ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
  1973. continue;
  1974. }
  1975. // Check for extraneous top-level semicolon.
  1976. if (Tok.is(tok::semi)) {
  1977. Diag(Tok, diag::ext_extra_struct_semi)
  1978. << DeclSpec::getSpecifierName((DeclSpec::TST)TagType)
  1979. << FixItHint::CreateRemoval(Tok.getLocation());
  1980. ConsumeToken();
  1981. continue;
  1982. }
  1983. if (Tok.is(tok::annot_pragma_vis)) {
  1984. HandlePragmaVisibility();
  1985. continue;
  1986. }
  1987. if (Tok.is(tok::annot_pragma_pack)) {
  1988. HandlePragmaPack();
  1989. continue;
  1990. }
  1991. AccessSpecifier AS = getAccessSpecifierIfPresent();
  1992. if (AS != AS_none) {
  1993. // Current token is a C++ access specifier.
  1994. CurAS = AS;
  1995. SourceLocation ASLoc = Tok.getLocation();
  1996. unsigned TokLength = Tok.getLength();
  1997. ConsumeToken();
  1998. AccessAttrs.clear();
  1999. MaybeParseGNUAttributes(AccessAttrs);
  2000. SourceLocation EndLoc;
  2001. if (Tok.is(tok::colon)) {
  2002. EndLoc = Tok.getLocation();
  2003. ConsumeToken();
  2004. } else if (Tok.is(tok::semi)) {
  2005. EndLoc = Tok.getLocation();
  2006. ConsumeToken();
  2007. Diag(EndLoc, diag::err_expected_colon)
  2008. << FixItHint::CreateReplacement(EndLoc, ":");
  2009. } else {
  2010. EndLoc = ASLoc.getLocWithOffset(TokLength);
  2011. Diag(EndLoc, diag::err_expected_colon)
  2012. << FixItHint::CreateInsertion(EndLoc, ":");
  2013. }
  2014. if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc,
  2015. AccessAttrs.getList())) {
  2016. // found another attribute than only annotations
  2017. AccessAttrs.clear();
  2018. }
  2019. continue;
  2020. }
  2021. // FIXME: Make sure we don't have a template here.
  2022. // Parse all the comma separated declarators.
  2023. ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList());
  2024. }
  2025. T.consumeClose();
  2026. } else {
  2027. SkipUntil(tok::r_brace, false, false);
  2028. }
  2029. // If attributes exist after class contents, parse them.
  2030. ParsedAttributes attrs(AttrFactory);
  2031. MaybeParseGNUAttributes(attrs);
  2032. if (TagDecl)
  2033. Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
  2034. T.getOpenLocation(),
  2035. T.getCloseLocation(),
  2036. attrs.getList());
  2037. // C++0x [class.mem]p2: Within the class member-specification, the class is
  2038. // regarded as complete within function bodies, default arguments, exception-
  2039. // specifications, and brace-or-equal-initializers for non-static data
  2040. // members (including such things in nested classes).
  2041. //
  2042. // FIXME: Only function bodies and brace-or-equal-initializers are currently
  2043. // handled. Fix the others!
  2044. if (TagDecl && NonNestedClass) {
  2045. // We are not inside a nested class. This class and its nested classes
  2046. // are complete and we can parse the delayed portions of method
  2047. // declarations and the lexed inline method definitions, along with any
  2048. // delayed attributes.
  2049. SourceLocation SavedPrevTokLocation = PrevTokLocation;
  2050. ParseLexedAttributes(getCurrentClass());
  2051. ParseLexedMethodDeclarations(getCurrentClass());
  2052. ParseLexedMemberInitializers(getCurrentClass());
  2053. ParseLexedMethodDefs(getCurrentClass());
  2054. PrevTokLocation = SavedPrevTokLocation;
  2055. }
  2056. if (TagDecl)
  2057. Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
  2058. T.getCloseLocation());
  2059. // Leave the class scope.
  2060. ParsingDef.Pop();
  2061. ClassScope.Exit();
  2062. }
  2063. /// ParseConstructorInitializer - Parse a C++ constructor initializer,
  2064. /// which explicitly initializes the members or base classes of a
  2065. /// class (C++ [class.base.init]). For example, the three initializers
  2066. /// after the ':' in the Derived constructor below:
  2067. ///
  2068. /// @code
  2069. /// class Base { };
  2070. /// class Derived : Base {
  2071. /// int x;
  2072. /// float f;
  2073. /// public:
  2074. /// Derived(float f) : Base(), x(17), f(f) { }
  2075. /// };
  2076. /// @endcode
  2077. ///
  2078. /// [C++] ctor-initializer:
  2079. /// ':' mem-initializer-list
  2080. ///
  2081. /// [C++] mem-initializer-list:
  2082. /// mem-initializer ...[opt]
  2083. /// mem-initializer ...[opt] , mem-initializer-list
  2084. void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
  2085. assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
  2086. // Poison the SEH identifiers so they are flagged as illegal in constructor initializers
  2087. PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
  2088. SourceLocation ColonLoc = ConsumeToken();
  2089. SmallVector<CXXCtorInitializer*, 4> MemInitializers;
  2090. bool AnyErrors = false;
  2091. do {
  2092. if (Tok.is(tok::code_completion)) {
  2093. Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
  2094. MemInitializers.data(),
  2095. MemInitializers.size());
  2096. return cutOffParsing();
  2097. } else {
  2098. MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
  2099. if (!MemInit.isInvalid())
  2100. MemInitializers.push_back(MemInit.get());
  2101. else
  2102. AnyErrors = true;
  2103. }
  2104. if (Tok.is(tok::comma))
  2105. ConsumeToken();
  2106. else if (Tok.is(tok::l_brace))
  2107. break;
  2108. // If the next token looks like a base or member initializer, assume that
  2109. // we're just missing a comma.
  2110. else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) {
  2111. SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
  2112. Diag(Loc, diag::err_ctor_init_missing_comma)
  2113. << FixItHint::CreateInsertion(Loc, ", ");
  2114. } else {
  2115. // Skip over garbage, until we get to '{'. Don't eat the '{'.
  2116. Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
  2117. SkipUntil(tok::l_brace, true, true);
  2118. break;
  2119. }
  2120. } while (true);
  2121. Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
  2122. MemInitializers.data(), MemInitializers.size(),
  2123. AnyErrors);
  2124. }
  2125. /// ParseMemInitializer - Parse a C++ member initializer, which is
  2126. /// part of a constructor initializer that explicitly initializes one
  2127. /// member or base class (C++ [class.base.init]). See
  2128. /// ParseConstructorInitializer for an example.
  2129. ///
  2130. /// [C++] mem-initializer:
  2131. /// mem-initializer-id '(' expression-list[opt] ')'
  2132. /// [C++0x] mem-initializer-id braced-init-list
  2133. ///
  2134. /// [C++] mem-initializer-id:
  2135. /// '::'[opt] nested-name-specifier[opt] class-name
  2136. /// identifier
  2137. Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
  2138. // parse '::'[opt] nested-name-specifier[opt]
  2139. CXXScopeSpec SS;
  2140. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
  2141. ParsedType TemplateTypeTy;
  2142. if (Tok.is(tok::annot_template_id)) {
  2143. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  2144. if (TemplateId->Kind == TNK_Type_template ||
  2145. TemplateId->Kind == TNK_Dependent_template_name) {
  2146. AnnotateTemplateIdTokenAsType();
  2147. assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
  2148. TemplateTypeTy = getTypeAnnotation(Tok);
  2149. }
  2150. }
  2151. // Uses of decltype will already have been converted to annot_decltype by
  2152. // ParseOptionalCXXScopeSpecifier at this point.
  2153. if (!TemplateTypeTy && Tok.isNot(tok::identifier)
  2154. && Tok.isNot(tok::annot_decltype)) {
  2155. Diag(Tok, diag::err_expected_member_or_base_name);
  2156. return true;
  2157. }
  2158. IdentifierInfo *II = 0;
  2159. DeclSpec DS(AttrFactory);
  2160. SourceLocation IdLoc = Tok.getLocation();
  2161. if (Tok.is(tok::annot_decltype)) {
  2162. // Get the decltype expression, if there is one.
  2163. ParseDecltypeSpecifier(DS);
  2164. } else {
  2165. if (Tok.is(tok::identifier))
  2166. // Get the identifier. This may be a member name or a class name,
  2167. // but we'll let the semantic analysis determine which it is.
  2168. II = Tok.getIdentifierInfo();
  2169. ConsumeToken();
  2170. }
  2171. // Parse the '('.
  2172. if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
  2173. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  2174. ExprResult InitList = ParseBraceInitializer();
  2175. if (InitList.isInvalid())
  2176. return true;
  2177. SourceLocation EllipsisLoc;
  2178. if (Tok.is(tok::ellipsis))
  2179. EllipsisLoc = ConsumeToken();
  2180. return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
  2181. TemplateTypeTy, DS, IdLoc,
  2182. InitList.take(), EllipsisLoc);
  2183. } else if(Tok.is(tok::l_paren)) {
  2184. BalancedDelimiterTracker T(*this, tok::l_paren);
  2185. T.consumeOpen();
  2186. // Parse the optional expression-list.
  2187. ExprVector ArgExprs(Actions);
  2188. CommaLocsTy CommaLocs;
  2189. if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
  2190. SkipUntil(tok::r_paren);
  2191. return true;
  2192. }
  2193. T.consumeClose();
  2194. SourceLocation EllipsisLoc;
  2195. if (Tok.is(tok::ellipsis))
  2196. EllipsisLoc = ConsumeToken();
  2197. return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
  2198. TemplateTypeTy, DS, IdLoc,
  2199. T.getOpenLocation(), ArgExprs.take(),
  2200. ArgExprs.size(), T.getCloseLocation(),
  2201. EllipsisLoc);
  2202. }
  2203. Diag(Tok, getLangOpts().CPlusPlus0x ? diag::err_expected_lparen_or_lbrace
  2204. : diag::err_expected_lparen);
  2205. return true;
  2206. }
  2207. /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
  2208. ///
  2209. /// exception-specification:
  2210. /// dynamic-exception-specification
  2211. /// noexcept-specification
  2212. ///
  2213. /// noexcept-specification:
  2214. /// 'noexcept'
  2215. /// 'noexcept' '(' constant-expression ')'
  2216. ExceptionSpecificationType
  2217. Parser::MaybeParseExceptionSpecification(SourceRange &SpecificationRange,
  2218. SmallVectorImpl<ParsedType> &DynamicExceptions,
  2219. SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
  2220. ExprResult &NoexceptExpr) {
  2221. ExceptionSpecificationType Result = EST_None;
  2222. // See if there's a dynamic specification.
  2223. if (Tok.is(tok::kw_throw)) {
  2224. Result = ParseDynamicExceptionSpecification(SpecificationRange,
  2225. DynamicExceptions,
  2226. DynamicExceptionRanges);
  2227. assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
  2228. "Produced different number of exception types and ranges.");
  2229. }
  2230. // If there's no noexcept specification, we're done.
  2231. if (Tok.isNot(tok::kw_noexcept))
  2232. return Result;
  2233. Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
  2234. // If we already had a dynamic specification, parse the noexcept for,
  2235. // recovery, but emit a diagnostic and don't store the results.
  2236. SourceRange NoexceptRange;
  2237. ExceptionSpecificationType NoexceptType = EST_None;
  2238. SourceLocation KeywordLoc = ConsumeToken();
  2239. if (Tok.is(tok::l_paren)) {
  2240. // There is an argument.
  2241. BalancedDelimiterTracker T(*this, tok::l_paren);
  2242. T.consumeOpen();
  2243. NoexceptType = EST_ComputedNoexcept;
  2244. NoexceptExpr = ParseConstantExpression();
  2245. // The argument must be contextually convertible to bool. We use
  2246. // ActOnBooleanCondition for this purpose.
  2247. if (!NoexceptExpr.isInvalid())
  2248. NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc,
  2249. NoexceptExpr.get());
  2250. T.consumeClose();
  2251. NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
  2252. } else {
  2253. // There is no argument.
  2254. NoexceptType = EST_BasicNoexcept;
  2255. NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
  2256. }
  2257. if (Result == EST_None) {
  2258. SpecificationRange = NoexceptRange;
  2259. Result = NoexceptType;
  2260. // If there's a dynamic specification after a noexcept specification,
  2261. // parse that and ignore the results.
  2262. if (Tok.is(tok::kw_throw)) {
  2263. Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
  2264. ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
  2265. DynamicExceptionRanges);
  2266. }
  2267. } else {
  2268. Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
  2269. }
  2270. return Result;
  2271. }
  2272. /// ParseDynamicExceptionSpecification - Parse a C++
  2273. /// dynamic-exception-specification (C++ [except.spec]).
  2274. ///
  2275. /// dynamic-exception-specification:
  2276. /// 'throw' '(' type-id-list [opt] ')'
  2277. /// [MS] 'throw' '(' '...' ')'
  2278. ///
  2279. /// type-id-list:
  2280. /// type-id ... [opt]
  2281. /// type-id-list ',' type-id ... [opt]
  2282. ///
  2283. ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
  2284. SourceRange &SpecificationRange,
  2285. SmallVectorImpl<ParsedType> &Exceptions,
  2286. SmallVectorImpl<SourceRange> &Ranges) {
  2287. assert(Tok.is(tok::kw_throw) && "expected throw");
  2288. SpecificationRange.setBegin(ConsumeToken());
  2289. BalancedDelimiterTracker T(*this, tok::l_paren);
  2290. if (T.consumeOpen()) {
  2291. Diag(Tok, diag::err_expected_lparen_after) << "throw";
  2292. SpecificationRange.setEnd(SpecificationRange.getBegin());
  2293. return EST_DynamicNone;
  2294. }
  2295. // Parse throw(...), a Microsoft extension that means "this function
  2296. // can throw anything".
  2297. if (Tok.is(tok::ellipsis)) {
  2298. SourceLocation EllipsisLoc = ConsumeToken();
  2299. if (!getLangOpts().MicrosoftExt)
  2300. Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
  2301. T.consumeClose();
  2302. SpecificationRange.setEnd(T.getCloseLocation());
  2303. return EST_MSAny;
  2304. }
  2305. // Parse the sequence of type-ids.
  2306. SourceRange Range;
  2307. while (Tok.isNot(tok::r_paren)) {
  2308. TypeResult Res(ParseTypeName(&Range));
  2309. if (Tok.is(tok::ellipsis)) {
  2310. // C++0x [temp.variadic]p5:
  2311. // - In a dynamic-exception-specification (15.4); the pattern is a
  2312. // type-id.
  2313. SourceLocation Ellipsis = ConsumeToken();
  2314. Range.setEnd(Ellipsis);
  2315. if (!Res.isInvalid())
  2316. Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
  2317. }
  2318. if (!Res.isInvalid()) {
  2319. Exceptions.push_back(Res.get());
  2320. Ranges.push_back(Range);
  2321. }
  2322. if (Tok.is(tok::comma))
  2323. ConsumeToken();
  2324. else
  2325. break;
  2326. }
  2327. T.consumeClose();
  2328. SpecificationRange.setEnd(T.getCloseLocation());
  2329. return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
  2330. }
  2331. /// ParseTrailingReturnType - Parse a trailing return type on a new-style
  2332. /// function declaration.
  2333. TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
  2334. assert(Tok.is(tok::arrow) && "expected arrow");
  2335. ConsumeToken();
  2336. // FIXME: Need to suppress declarations when parsing this typename.
  2337. // Otherwise in this function definition:
  2338. //
  2339. // auto f() -> struct X {}
  2340. //
  2341. // struct X is parsed as class definition because of the trailing
  2342. // brace.
  2343. return ParseTypeName(&Range);
  2344. }
  2345. /// \brief We have just started parsing the definition of a new class,
  2346. /// so push that class onto our stack of classes that is currently
  2347. /// being parsed.
  2348. Sema::ParsingClassState
  2349. Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass) {
  2350. assert((NonNestedClass || !ClassStack.empty()) &&
  2351. "Nested class without outer class");
  2352. ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass));
  2353. return Actions.PushParsingClass();
  2354. }
  2355. /// \brief Deallocate the given parsed class and all of its nested
  2356. /// classes.
  2357. void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
  2358. for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
  2359. delete Class->LateParsedDeclarations[I];
  2360. delete Class;
  2361. }
  2362. /// \brief Pop the top class of the stack of classes that are
  2363. /// currently being parsed.
  2364. ///
  2365. /// This routine should be called when we have finished parsing the
  2366. /// definition of a class, but have not yet popped the Scope
  2367. /// associated with the class's definition.
  2368. ///
  2369. /// \returns true if the class we've popped is a top-level class,
  2370. /// false otherwise.
  2371. void Parser::PopParsingClass(Sema::ParsingClassState state) {
  2372. assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
  2373. Actions.PopParsingClass(state);
  2374. ParsingClass *Victim = ClassStack.top();
  2375. ClassStack.pop();
  2376. if (Victim->TopLevelClass) {
  2377. // Deallocate all of the nested classes of this class,
  2378. // recursively: we don't need to keep any of this information.
  2379. DeallocateParsedClasses(Victim);
  2380. return;
  2381. }
  2382. assert(!ClassStack.empty() && "Missing top-level class?");
  2383. if (Victim->LateParsedDeclarations.empty()) {
  2384. // The victim is a nested class, but we will not need to perform
  2385. // any processing after the definition of this class since it has
  2386. // no members whose handling was delayed. Therefore, we can just
  2387. // remove this nested class.
  2388. DeallocateParsedClasses(Victim);
  2389. return;
  2390. }
  2391. // This nested class has some members that will need to be processed
  2392. // after the top-level class is completely defined. Therefore, add
  2393. // it to the list of nested classes within its parent.
  2394. assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
  2395. ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
  2396. Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
  2397. }
  2398. /// ParseCXX0XAttributeSpecifier - Parse a C++0x attribute-specifier. Currently
  2399. /// only parses standard attributes.
  2400. ///
  2401. /// [C++0x] attribute-specifier:
  2402. /// '[' '[' attribute-list ']' ']'
  2403. /// alignment-specifier
  2404. ///
  2405. /// [C++0x] attribute-list:
  2406. /// attribute[opt]
  2407. /// attribute-list ',' attribute[opt]
  2408. ///
  2409. /// [C++0x] attribute:
  2410. /// attribute-token attribute-argument-clause[opt]
  2411. ///
  2412. /// [C++0x] attribute-token:
  2413. /// identifier
  2414. /// attribute-scoped-token
  2415. ///
  2416. /// [C++0x] attribute-scoped-token:
  2417. /// attribute-namespace '::' identifier
  2418. ///
  2419. /// [C++0x] attribute-namespace:
  2420. /// identifier
  2421. ///
  2422. /// [C++0x] attribute-argument-clause:
  2423. /// '(' balanced-token-seq ')'
  2424. ///
  2425. /// [C++0x] balanced-token-seq:
  2426. /// balanced-token
  2427. /// balanced-token-seq balanced-token
  2428. ///
  2429. /// [C++0x] balanced-token:
  2430. /// '(' balanced-token-seq ')'
  2431. /// '[' balanced-token-seq ']'
  2432. /// '{' balanced-token-seq '}'
  2433. /// any token but '(', ')', '[', ']', '{', or '}'
  2434. void Parser::ParseCXX0XAttributeSpecifier(ParsedAttributes &attrs,
  2435. SourceLocation *endLoc) {
  2436. if (Tok.is(tok::kw_alignas)) {
  2437. Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
  2438. ParseAlignmentSpecifier(attrs, endLoc);
  2439. return;
  2440. }
  2441. assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
  2442. && "Not a C++0x attribute list");
  2443. Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
  2444. ConsumeBracket();
  2445. ConsumeBracket();
  2446. if (Tok.is(tok::comma)) {
  2447. Diag(Tok.getLocation(), diag::err_expected_ident);
  2448. ConsumeToken();
  2449. }
  2450. while (Tok.is(tok::identifier) || Tok.is(tok::comma)) {
  2451. // attribute not present
  2452. if (Tok.is(tok::comma)) {
  2453. ConsumeToken();
  2454. continue;
  2455. }
  2456. IdentifierInfo *ScopeName = 0, *AttrName = Tok.getIdentifierInfo();
  2457. SourceLocation ScopeLoc, AttrLoc = ConsumeToken();
  2458. // scoped attribute
  2459. if (Tok.is(tok::coloncolon)) {
  2460. ConsumeToken();
  2461. if (!Tok.is(tok::identifier)) {
  2462. Diag(Tok.getLocation(), diag::err_expected_ident);
  2463. SkipUntil(tok::r_square, tok::comma, true, true);
  2464. continue;
  2465. }
  2466. ScopeName = AttrName;
  2467. ScopeLoc = AttrLoc;
  2468. AttrName = Tok.getIdentifierInfo();
  2469. AttrLoc = ConsumeToken();
  2470. }
  2471. bool AttrParsed = false;
  2472. // No scoped names are supported; ideally we could put all non-standard
  2473. // attributes into namespaces.
  2474. if (!ScopeName) {
  2475. switch(AttributeList::getKind(AttrName))
  2476. {
  2477. // No arguments
  2478. case AttributeList::AT_carries_dependency:
  2479. case AttributeList::AT_noreturn: {
  2480. if (Tok.is(tok::l_paren)) {
  2481. Diag(Tok.getLocation(), diag::err_cxx0x_attribute_forbids_arguments)
  2482. << AttrName->getName();
  2483. break;
  2484. }
  2485. attrs.addNew(AttrName, AttrLoc, 0, AttrLoc, 0,
  2486. SourceLocation(), 0, 0, false, true);
  2487. AttrParsed = true;
  2488. break;
  2489. }
  2490. // Silence warnings
  2491. default: break;
  2492. }
  2493. }
  2494. // Skip the entire parameter clause, if any
  2495. if (!AttrParsed && Tok.is(tok::l_paren)) {
  2496. ConsumeParen();
  2497. // SkipUntil maintains the balancedness of tokens.
  2498. SkipUntil(tok::r_paren, false);
  2499. }
  2500. }
  2501. if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
  2502. SkipUntil(tok::r_square, false);
  2503. if (endLoc)
  2504. *endLoc = Tok.getLocation();
  2505. if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
  2506. SkipUntil(tok::r_square, false);
  2507. }
  2508. /// ParseCXX0XAttributes - Parse a C++0x attribute-specifier-seq.
  2509. ///
  2510. /// attribute-specifier-seq:
  2511. /// attribute-specifier-seq[opt] attribute-specifier
  2512. void Parser::ParseCXX0XAttributes(ParsedAttributesWithRange &attrs,
  2513. SourceLocation *endLoc) {
  2514. SourceLocation StartLoc = Tok.getLocation(), Loc;
  2515. if (!endLoc)
  2516. endLoc = &Loc;
  2517. do {
  2518. ParseCXX0XAttributeSpecifier(attrs, endLoc);
  2519. } while (isCXX0XAttributeSpecifier());
  2520. attrs.Range = SourceRange(StartLoc, *endLoc);
  2521. }
  2522. /// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr]
  2523. ///
  2524. /// [MS] ms-attribute:
  2525. /// '[' token-seq ']'
  2526. ///
  2527. /// [MS] ms-attribute-seq:
  2528. /// ms-attribute[opt]
  2529. /// ms-attribute ms-attribute-seq
  2530. void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
  2531. SourceLocation *endLoc) {
  2532. assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
  2533. while (Tok.is(tok::l_square)) {
  2534. ConsumeBracket();
  2535. SkipUntil(tok::r_square, true, true);
  2536. if (endLoc) *endLoc = Tok.getLocation();
  2537. ExpectAndConsume(tok::r_square, diag::err_expected_rsquare);
  2538. }
  2539. }
  2540. void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
  2541. AccessSpecifier& CurAS) {
  2542. IfExistsCondition Result;
  2543. if (ParseMicrosoftIfExistsCondition(Result))
  2544. return;
  2545. BalancedDelimiterTracker Braces(*this, tok::l_brace);
  2546. if (Braces.consumeOpen()) {
  2547. Diag(Tok, diag::err_expected_lbrace);
  2548. return;
  2549. }
  2550. switch (Result.Behavior) {
  2551. case IEB_Parse:
  2552. // Parse the declarations below.
  2553. break;
  2554. case IEB_Dependent:
  2555. Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
  2556. << Result.IsIfExists;
  2557. // Fall through to skip.
  2558. case IEB_Skip:
  2559. Braces.skipToEnd();
  2560. return;
  2561. }
  2562. while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
  2563. // __if_exists, __if_not_exists can nest.
  2564. if ((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists))) {
  2565. ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
  2566. continue;
  2567. }
  2568. // Check for extraneous top-level semicolon.
  2569. if (Tok.is(tok::semi)) {
  2570. Diag(Tok, diag::ext_extra_struct_semi)
  2571. << DeclSpec::getSpecifierName((DeclSpec::TST)TagType)
  2572. << FixItHint::CreateRemoval(Tok.getLocation());
  2573. ConsumeToken();
  2574. continue;
  2575. }
  2576. AccessSpecifier AS = getAccessSpecifierIfPresent();
  2577. if (AS != AS_none) {
  2578. // Current token is a C++ access specifier.
  2579. CurAS = AS;
  2580. SourceLocation ASLoc = Tok.getLocation();
  2581. ConsumeToken();
  2582. if (Tok.is(tok::colon))
  2583. Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
  2584. else
  2585. Diag(Tok, diag::err_expected_colon);
  2586. ConsumeToken();
  2587. continue;
  2588. }
  2589. // Parse all the comma separated declarators.
  2590. ParseCXXClassMemberDeclaration(CurAS, 0);
  2591. }
  2592. Braces.consumeClose();
  2593. }