ParseDeclCXX.cpp 149 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034
  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/Parse/Parser.h"
  14. #include "RAIIObjectsForParser.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/DeclTemplate.h"
  17. #include "clang/Basic/Attributes.h"
  18. #include "clang/Basic/CharInfo.h"
  19. #include "clang/Basic/OperatorKinds.h"
  20. #include "clang/Basic/TargetInfo.h"
  21. #include "clang/Parse/ParseDiagnostic.h"
  22. #include "clang/Sema/DeclSpec.h"
  23. #include "clang/Sema/ParsedTemplate.h"
  24. #include "clang/Sema/PrettyDeclStackTrace.h"
  25. #include "clang/Sema/Scope.h"
  26. #include "clang/Sema/SemaDiagnostic.h"
  27. #include "llvm/ADT/SmallString.h"
  28. using namespace clang;
  29. /// ParseNamespace - We know that the current token is a namespace keyword. This
  30. /// may either be a top level namespace or a block-level namespace alias. If
  31. /// there was an inline keyword, it has already been parsed.
  32. ///
  33. /// namespace-definition: [C++ 7.3: basic.namespace]
  34. /// named-namespace-definition
  35. /// unnamed-namespace-definition
  36. ///
  37. /// unnamed-namespace-definition:
  38. /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
  39. ///
  40. /// named-namespace-definition:
  41. /// original-namespace-definition
  42. /// extension-namespace-definition
  43. ///
  44. /// original-namespace-definition:
  45. /// 'inline'[opt] 'namespace' identifier attributes[opt]
  46. /// '{' namespace-body '}'
  47. ///
  48. /// extension-namespace-definition:
  49. /// 'inline'[opt] 'namespace' original-namespace-name
  50. /// '{' namespace-body '}'
  51. ///
  52. /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
  53. /// 'namespace' identifier '=' qualified-namespace-specifier ';'
  54. ///
  55. Decl *Parser::ParseNamespace(unsigned Context,
  56. SourceLocation &DeclEnd,
  57. SourceLocation InlineLoc) {
  58. assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
  59. SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
  60. ObjCDeclContextSwitch ObjCDC(*this);
  61. if (Tok.is(tok::code_completion)) {
  62. Actions.CodeCompleteNamespaceDecl(getCurScope());
  63. cutOffParsing();
  64. return nullptr;
  65. }
  66. SourceLocation IdentLoc;
  67. IdentifierInfo *Ident = nullptr;
  68. std::vector<SourceLocation> ExtraIdentLoc;
  69. std::vector<IdentifierInfo*> ExtraIdent;
  70. std::vector<SourceLocation> ExtraNamespaceLoc;
  71. ParsedAttributesWithRange attrs(AttrFactory);
  72. SourceLocation attrLoc;
  73. if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
  74. if (!getLangOpts().CPlusPlus1z)
  75. Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
  76. << 0 /*namespace*/;
  77. attrLoc = Tok.getLocation();
  78. ParseCXX11Attributes(attrs);
  79. }
  80. if (Tok.is(tok::identifier)) {
  81. Ident = Tok.getIdentifierInfo();
  82. IdentLoc = ConsumeToken(); // eat the identifier.
  83. while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
  84. ExtraNamespaceLoc.push_back(ConsumeToken());
  85. ExtraIdent.push_back(Tok.getIdentifierInfo());
  86. ExtraIdentLoc.push_back(ConsumeToken());
  87. }
  88. }
  89. // HLSL Change Starts
  90. else if (getLangOpts().HLSL) {
  91. Diag(Tok, diag::err_expected) << tok::identifier;
  92. }
  93. // HLSL Change Ends
  94. // A nested namespace definition cannot have attributes.
  95. if (!ExtraNamespaceLoc.empty() && attrLoc.isValid())
  96. Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
  97. // Read label attributes, if present.
  98. if (Tok.is(tok::kw___attribute)) {
  99. attrLoc = Tok.getLocation();
  100. ParseGNUAttributes(attrs);
  101. }
  102. if (Tok.is(tok::equal)) {
  103. if (!Ident || getLangOpts().HLSL) { // HLSL Change: HLSL disallows namespace aliases
  104. Diag(Tok, diag::err_expected) << tok::identifier;
  105. // Skip to end of the definition and eat the ';'.
  106. SkipUntil(tok::semi);
  107. return nullptr;
  108. }
  109. if (attrLoc.isValid())
  110. Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
  111. if (InlineLoc.isValid())
  112. Diag(InlineLoc, diag::err_inline_namespace_alias)
  113. << FixItHint::CreateRemoval(InlineLoc);
  114. return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
  115. }
  116. BalancedDelimiterTracker T(*this, tok::l_brace);
  117. if (T.consumeOpen()) {
  118. if (Ident)
  119. Diag(Tok, diag::err_expected) << tok::l_brace;
  120. else
  121. Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
  122. return nullptr;
  123. }
  124. if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
  125. getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
  126. getCurScope()->getFnParent()) {
  127. Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
  128. SkipUntil(tok::r_brace);
  129. return nullptr;
  130. }
  131. if (ExtraIdent.empty()) {
  132. // Normal namespace definition, not a nested-namespace-definition.
  133. } else if (InlineLoc.isValid()) {
  134. Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
  135. } else if (getLangOpts().CPlusPlus1z) {
  136. Diag(ExtraNamespaceLoc[0],
  137. diag::warn_cxx14_compat_nested_namespace_definition);
  138. } else {
  139. TentativeParsingAction TPA(*this);
  140. SkipUntil(tok::r_brace, StopBeforeMatch);
  141. Token rBraceToken = Tok;
  142. TPA.Revert();
  143. if (!rBraceToken.is(tok::r_brace)) {
  144. Diag(ExtraNamespaceLoc[0],
  145. getLangOpts().HLSL ? diag::err_hlsl_nested_namespace_definition : // HLSL Change
  146. diag::ext_nested_namespace_definition)
  147. << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
  148. } else {
  149. std::string NamespaceFix;
  150. for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
  151. E = ExtraIdent.end(); I != E; ++I) {
  152. NamespaceFix += " { namespace ";
  153. NamespaceFix += (*I)->getName();
  154. }
  155. std::string RBraces;
  156. for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
  157. RBraces += "} ";
  158. Diag(ExtraNamespaceLoc[0],
  159. getLangOpts().HLSL ? diag::err_hlsl_nested_namespace_definition : // HLSL Change
  160. diag::ext_nested_namespace_definition)
  161. << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
  162. ExtraIdentLoc.back()),
  163. NamespaceFix)
  164. << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
  165. }
  166. }
  167. // If we're still good, complain about inline namespaces in non-C++0x now.
  168. if (InlineLoc.isValid())
  169. Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
  170. diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
  171. // Enter a scope for the namespace.
  172. ParseScope NamespaceScope(this, Scope::DeclScope);
  173. Decl *NamespcDecl =
  174. Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
  175. IdentLoc, Ident, T.getOpenLocation(),
  176. attrs.getList());
  177. PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
  178. "parsing namespace");
  179. // Parse the contents of the namespace. This includes parsing recovery on
  180. // any improperly nested namespaces.
  181. ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
  182. InlineLoc, attrs, T);
  183. // Leave the namespace scope.
  184. NamespaceScope.Exit();
  185. DeclEnd = T.getCloseLocation();
  186. Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
  187. return NamespcDecl;
  188. }
  189. /// ParseInnerNamespace - Parse the contents of a namespace.
  190. void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
  191. std::vector<IdentifierInfo *> &Ident,
  192. std::vector<SourceLocation> &NamespaceLoc,
  193. unsigned int index, SourceLocation &InlineLoc,
  194. ParsedAttributes &attrs,
  195. BalancedDelimiterTracker &Tracker) {
  196. if (index == Ident.size()) {
  197. while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
  198. ParsedAttributesWithRange attrs(AttrFactory);
  199. MaybeParseCXX11Attributes(attrs);
  200. MaybeParseMicrosoftAttributes(attrs);
  201. ParseExternalDeclaration(attrs);
  202. }
  203. // The caller is what called check -- we are simply calling
  204. // the close for it.
  205. Tracker.consumeClose();
  206. return;
  207. }
  208. // Handle a nested namespace definition.
  209. // FIXME: Preserve the source information through to the AST rather than
  210. // desugaring it here.
  211. ParseScope NamespaceScope(this, Scope::DeclScope);
  212. Decl *NamespcDecl =
  213. Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
  214. NamespaceLoc[index], IdentLoc[index],
  215. Ident[index], Tracker.getOpenLocation(),
  216. attrs.getList());
  217. ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
  218. attrs, Tracker);
  219. NamespaceScope.Exit();
  220. Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
  221. }
  222. /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
  223. /// alias definition.
  224. ///
  225. Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
  226. SourceLocation AliasLoc,
  227. IdentifierInfo *Alias,
  228. SourceLocation &DeclEnd) {
  229. assert(Tok.is(tok::equal) && "Not equal token");
  230. ConsumeToken(); // eat the '='.
  231. if (Tok.is(tok::code_completion)) {
  232. Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
  233. cutOffParsing();
  234. return nullptr;
  235. }
  236. CXXScopeSpec SS;
  237. // Parse (optional) nested-name-specifier.
  238. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
  239. if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
  240. Diag(Tok, diag::err_expected_namespace_name);
  241. // Skip to end of the definition and eat the ';'.
  242. SkipUntil(tok::semi);
  243. return nullptr;
  244. }
  245. // Parse identifier.
  246. IdentifierInfo *Ident = Tok.getIdentifierInfo();
  247. SourceLocation IdentLoc = ConsumeToken();
  248. // Eat the ';'.
  249. DeclEnd = Tok.getLocation();
  250. if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
  251. SkipUntil(tok::semi);
  252. return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias,
  253. SS, IdentLoc, Ident);
  254. }
  255. /// ParseLinkage - We know that the current token is a string_literal
  256. /// and just before that, that extern was seen.
  257. ///
  258. /// linkage-specification: [C++ 7.5p2: dcl.link]
  259. /// 'extern' string-literal '{' declaration-seq[opt] '}'
  260. /// 'extern' string-literal declaration
  261. ///
  262. Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
  263. assert(isTokenStringLiteral() && "Not a string literal!");
  264. ExprResult Lang = ParseStringLiteralExpression(false);
  265. ParseScope LinkageScope(this, Scope::DeclScope);
  266. Decl *LinkageSpec =
  267. Lang.isInvalid()
  268. ? nullptr
  269. : Actions.ActOnStartLinkageSpecification(
  270. getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
  271. Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
  272. ParsedAttributesWithRange attrs(AttrFactory);
  273. MaybeParseCXX11Attributes(attrs);
  274. MaybeParseHLSLAttributes(attrs); // HLSL Change
  275. MaybeParseMicrosoftAttributes(attrs);
  276. if (Tok.isNot(tok::l_brace)) {
  277. // Reset the source range in DS, as the leading "extern"
  278. // does not really belong to the inner declaration ...
  279. DS.SetRangeStart(SourceLocation());
  280. DS.SetRangeEnd(SourceLocation());
  281. // ... but anyway remember that such an "extern" was seen.
  282. DS.setExternInLinkageSpec(true);
  283. ParseExternalDeclaration(attrs, &DS);
  284. return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
  285. getCurScope(), LinkageSpec, SourceLocation())
  286. : nullptr;
  287. }
  288. DS.abort();
  289. ProhibitAttributes(attrs);
  290. BalancedDelimiterTracker T(*this, tok::l_brace);
  291. T.consumeOpen();
  292. unsigned NestedModules = 0;
  293. while (true) {
  294. switch (Tok.getKind()) {
  295. case tok::annot_module_begin:
  296. ++NestedModules;
  297. ParseTopLevelDecl();
  298. continue;
  299. case tok::annot_module_end:
  300. if (!NestedModules)
  301. break;
  302. --NestedModules;
  303. ParseTopLevelDecl();
  304. continue;
  305. case tok::annot_module_include:
  306. ParseTopLevelDecl();
  307. continue;
  308. case tok::eof:
  309. break;
  310. case tok::r_brace:
  311. if (!NestedModules)
  312. break;
  313. // Fall through.
  314. default:
  315. ParsedAttributesWithRange attrs(AttrFactory);
  316. MaybeParseCXX11Attributes(attrs);
  317. MaybeParseHLSLAttributes(attrs); // HLSL Change
  318. MaybeParseMicrosoftAttributes(attrs);
  319. ParseExternalDeclaration(attrs);
  320. continue;
  321. }
  322. break;
  323. }
  324. T.consumeClose();
  325. return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
  326. getCurScope(), LinkageSpec, T.getCloseLocation())
  327. : nullptr;
  328. }
  329. /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
  330. /// using-directive. Assumes that current token is 'using'.
  331. Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
  332. const ParsedTemplateInfo &TemplateInfo,
  333. SourceLocation &DeclEnd,
  334. ParsedAttributesWithRange &attrs,
  335. Decl **OwnedType) {
  336. assert(Tok.is(tok::kw_using) && "Not using token");
  337. ObjCDeclContextSwitch ObjCDC(*this);
  338. // Eat 'using'.
  339. SourceLocation UsingLoc = ConsumeToken();
  340. if (Tok.is(tok::code_completion)) {
  341. Actions.CodeCompleteUsing(getCurScope());
  342. cutOffParsing();
  343. return nullptr;
  344. }
  345. // 'using namespace' means this is a using-directive.
  346. if (Tok.is(tok::kw_namespace)) {
  347. // Template parameters are always an error here.
  348. if (TemplateInfo.Kind) {
  349. SourceRange R = TemplateInfo.getSourceRange();
  350. Diag(UsingLoc, diag::err_templated_using_directive)
  351. << R << FixItHint::CreateRemoval(R);
  352. }
  353. return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
  354. }
  355. // Otherwise, it must be a using-declaration or an alias-declaration.
  356. // Using declarations can't have attributes.
  357. ProhibitAttributes(attrs);
  358. return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
  359. AS_none, OwnedType);
  360. }
  361. /// ParseUsingDirective - Parse C++ using-directive, assumes
  362. /// that current token is 'namespace' and 'using' was already parsed.
  363. ///
  364. /// using-directive: [C++ 7.3.p4: namespace.udir]
  365. /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
  366. /// namespace-name ;
  367. /// [GNU] using-directive:
  368. /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
  369. /// namespace-name attributes[opt] ;
  370. ///
  371. Decl *Parser::ParseUsingDirective(unsigned Context,
  372. SourceLocation UsingLoc,
  373. SourceLocation &DeclEnd,
  374. ParsedAttributes &attrs) {
  375. assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
  376. // Eat 'namespace'.
  377. SourceLocation NamespcLoc = ConsumeToken();
  378. if (Tok.is(tok::code_completion)) {
  379. Actions.CodeCompleteUsingDirective(getCurScope());
  380. cutOffParsing();
  381. return nullptr;
  382. }
  383. CXXScopeSpec SS;
  384. // Parse (optional) nested-name-specifier.
  385. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
  386. IdentifierInfo *NamespcName = nullptr;
  387. SourceLocation IdentLoc = SourceLocation();
  388. // Parse namespace-name.
  389. if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
  390. Diag(Tok, diag::err_expected_namespace_name);
  391. // If there was invalid namespace name, skip to end of decl, and eat ';'.
  392. SkipUntil(tok::semi);
  393. // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
  394. return nullptr;
  395. }
  396. // Parse identifier.
  397. NamespcName = Tok.getIdentifierInfo();
  398. IdentLoc = ConsumeToken();
  399. // Parse (optional) attributes (most likely GNU strong-using extension).
  400. bool GNUAttr = false;
  401. if (Tok.is(tok::kw___attribute)) {
  402. GNUAttr = true;
  403. ParseGNUAttributes(attrs);
  404. }
  405. // Eat ';'.
  406. DeclEnd = Tok.getLocation();
  407. if (ExpectAndConsume(tok::semi,
  408. GNUAttr ? diag::err_expected_semi_after_attribute_list
  409. : diag::err_expected_semi_after_namespace_name))
  410. SkipUntil(tok::semi);
  411. return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
  412. IdentLoc, NamespcName, attrs.getList());
  413. }
  414. /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
  415. /// Assumes that 'using' was already seen.
  416. ///
  417. /// using-declaration: [C++ 7.3.p3: namespace.udecl]
  418. /// 'using' 'typename'[opt] ::[opt] nested-name-specifier
  419. /// unqualified-id
  420. /// 'using' :: unqualified-id
  421. ///
  422. /// alias-declaration: C++11 [dcl.dcl]p1
  423. /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
  424. ///
  425. Decl *Parser::ParseUsingDeclaration(unsigned Context,
  426. const ParsedTemplateInfo &TemplateInfo,
  427. SourceLocation UsingLoc,
  428. SourceLocation &DeclEnd,
  429. AccessSpecifier AS,
  430. Decl **OwnedType) {
  431. CXXScopeSpec SS;
  432. SourceLocation TypenameLoc;
  433. bool HasTypenameKeyword = false;
  434. // Check for misplaced attributes before the identifier in an
  435. // alias-declaration.
  436. ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
  437. MaybeParseCXX11Attributes(MisplacedAttrs);
  438. assert(!getLangOpts().HLSL); // HLSL Change: in lieu of MaybeParseHLSLAttributes - using not allowed
  439. // Ignore optional 'typename'.
  440. // FIXME: This is wrong; we should parse this as a typename-specifier.
  441. if (TryConsumeToken(tok::kw_typename, TypenameLoc))
  442. HasTypenameKeyword = true;
  443. if (Tok.is(tok::kw___super)) {
  444. Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
  445. SkipUntil(tok::semi);
  446. return nullptr;
  447. }
  448. // Parse nested-name-specifier.
  449. IdentifierInfo *LastII = nullptr;
  450. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false,
  451. /*MayBePseudoDtor=*/nullptr,
  452. /*IsTypename=*/false,
  453. /*LastII=*/&LastII);
  454. // Check nested-name specifier.
  455. if (SS.isInvalid()) {
  456. SkipUntil(tok::semi);
  457. return nullptr;
  458. }
  459. SourceLocation TemplateKWLoc;
  460. UnqualifiedId Name;
  461. // Parse the unqualified-id. We allow parsing of both constructor and
  462. // destructor names and allow the action module to diagnose any semantic
  463. // errors.
  464. //
  465. // C++11 [class.qual]p2:
  466. // [...] in a using-declaration that is a member-declaration, if the name
  467. // specified after the nested-name-specifier is the same as the identifier
  468. // or the simple-template-id's template-name in the last component of the
  469. // nested-name-specifier, the name is [...] considered to name the
  470. // constructor.
  471. if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
  472. Tok.is(tok::identifier) && NextToken().is(tok::semi) &&
  473. SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
  474. !SS.getScopeRep()->getAsNamespace() &&
  475. !SS.getScopeRep()->getAsNamespaceAlias()) {
  476. SourceLocation IdLoc = ConsumeToken();
  477. ParsedType Type = Actions.getInheritingConstructorName(SS, IdLoc, *LastII);
  478. Name.setConstructorName(Type, IdLoc, IdLoc);
  479. } else if (ParseUnqualifiedId(
  480. SS, /*EnteringContext=*/false,
  481. /*AllowDestructorName=*/true,
  482. /*AllowConstructorName=*/NextToken().isNot(tok::equal),
  483. ParsedType(), TemplateKWLoc, Name)) {
  484. SkipUntil(tok::semi);
  485. return nullptr;
  486. }
  487. ParsedAttributesWithRange Attrs(AttrFactory);
  488. MaybeParseGNUAttributes(Attrs);
  489. MaybeParseCXX11Attributes(Attrs);
  490. assert(!getLangOpts().HLSL); // HLSL Change: in lieu of MaybeParseHLSLAttributes - using not allowed
  491. // Maybe this is an alias-declaration.
  492. TypeResult TypeAlias;
  493. bool IsAliasDecl = Tok.is(tok::equal);
  494. Decl *DeclFromDeclSpec = nullptr;
  495. if (IsAliasDecl) {
  496. // If we had any misplaced attributes from earlier, this is where they
  497. // should have been written.
  498. if (MisplacedAttrs.Range.isValid()) {
  499. Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
  500. << FixItHint::CreateInsertionFromRange(
  501. Tok.getLocation(),
  502. CharSourceRange::getTokenRange(MisplacedAttrs.Range))
  503. << FixItHint::CreateRemoval(MisplacedAttrs.Range);
  504. Attrs.takeAllFrom(MisplacedAttrs);
  505. }
  506. ConsumeToken();
  507. Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
  508. diag::warn_cxx98_compat_alias_declaration :
  509. diag::ext_alias_declaration);
  510. // Type alias templates cannot be specialized.
  511. int SpecKind = -1;
  512. if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
  513. Name.getKind() == UnqualifiedId::IK_TemplateId)
  514. SpecKind = 0;
  515. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
  516. SpecKind = 1;
  517. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
  518. SpecKind = 2;
  519. if (SpecKind != -1) {
  520. SourceRange Range;
  521. if (SpecKind == 0)
  522. Range = SourceRange(Name.TemplateId->LAngleLoc,
  523. Name.TemplateId->RAngleLoc);
  524. else
  525. Range = TemplateInfo.getSourceRange();
  526. Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
  527. << SpecKind << Range;
  528. SkipUntil(tok::semi);
  529. return nullptr;
  530. }
  531. // Name must be an identifier.
  532. if (Name.getKind() != UnqualifiedId::IK_Identifier) {
  533. Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
  534. // No removal fixit: can't recover from this.
  535. SkipUntil(tok::semi);
  536. return nullptr;
  537. } else if (HasTypenameKeyword)
  538. Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
  539. << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
  540. SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
  541. else if (SS.isNotEmpty())
  542. Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
  543. << FixItHint::CreateRemoval(SS.getRange());
  544. TypeAlias = ParseTypeName(nullptr, TemplateInfo.Kind
  545. ? Declarator::AliasTemplateContext
  546. : Declarator::AliasDeclContext,
  547. AS, &DeclFromDeclSpec, &Attrs);
  548. if (OwnedType)
  549. *OwnedType = DeclFromDeclSpec;
  550. } else {
  551. // C++11 attributes are not allowed on a using-declaration, but GNU ones
  552. // are.
  553. ProhibitAttributes(MisplacedAttrs);
  554. ProhibitAttributes(Attrs);
  555. // Parse (optional) attributes (most likely GNU strong-using extension).
  556. MaybeParseGNUAttributes(Attrs);
  557. }
  558. // Eat ';'.
  559. DeclEnd = Tok.getLocation();
  560. if (ExpectAndConsume(tok::semi, diag::err_expected_after,
  561. !Attrs.empty() ? "attributes list"
  562. : IsAliasDecl ? "alias declaration"
  563. : "using declaration"))
  564. SkipUntil(tok::semi);
  565. // Diagnose an attempt to declare a templated using-declaration.
  566. // In C++11, alias-declarations can be templates:
  567. // template <...> using id = type;
  568. if (TemplateInfo.Kind && !IsAliasDecl) {
  569. SourceRange R = TemplateInfo.getSourceRange();
  570. Diag(UsingLoc, diag::err_templated_using_declaration)
  571. << R << FixItHint::CreateRemoval(R);
  572. // Unfortunately, we have to bail out instead of recovering by
  573. // ignoring the parameters, just in case the nested name specifier
  574. // depends on the parameters.
  575. return nullptr;
  576. }
  577. // "typename" keyword is allowed for identifiers only,
  578. // because it may be a type definition.
  579. if (HasTypenameKeyword && Name.getKind() != UnqualifiedId::IK_Identifier) {
  580. Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
  581. << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
  582. // Proceed parsing, but reset the HasTypenameKeyword flag.
  583. HasTypenameKeyword = false;
  584. }
  585. if (IsAliasDecl) {
  586. TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
  587. MultiTemplateParamsArg TemplateParamsArg(
  588. TemplateParams ? TemplateParams->data() : nullptr,
  589. TemplateParams ? TemplateParams->size() : 0);
  590. return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
  591. UsingLoc, Name, Attrs.getList(),
  592. TypeAlias, DeclFromDeclSpec);
  593. }
  594. return Actions.ActOnUsingDeclaration(getCurScope(), AS,
  595. /* HasUsingKeyword */ true, UsingLoc,
  596. SS, Name, Attrs.getList(),
  597. HasTypenameKeyword, TypenameLoc);
  598. }
  599. /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
  600. ///
  601. /// [C++0x] static_assert-declaration:
  602. /// static_assert ( constant-expression , string-literal ) ;
  603. ///
  604. /// [C11] static_assert-declaration:
  605. /// _Static_assert ( constant-expression , string-literal ) ;
  606. ///
  607. Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
  608. assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
  609. "Not a static_assert declaration");
  610. if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11 && !getLangOpts().HLSL) // HLSL Change - support enabled
  611. Diag(Tok, diag::ext_c11_static_assert);
  612. if (Tok.is(tok::kw_static_assert) && !getLangOpts().HLSL) // HLSL Change - support enabled
  613. Diag(Tok, diag::warn_cxx98_compat_static_assert);
  614. SourceLocation StaticAssertLoc = ConsumeToken();
  615. BalancedDelimiterTracker T(*this, tok::l_paren);
  616. if (T.consumeOpen()) {
  617. Diag(Tok, diag::err_expected) << tok::l_paren;
  618. SkipMalformedDecl();
  619. return nullptr;
  620. }
  621. ExprResult AssertExpr(ParseConstantExpression());
  622. if (AssertExpr.isInvalid()) {
  623. SkipMalformedDecl();
  624. return nullptr;
  625. }
  626. ExprResult AssertMessage;
  627. if (Tok.is(tok::r_paren)) {
  628. Diag(Tok, getLangOpts().CPlusPlus1z
  629. ? diag::warn_cxx14_compat_static_assert_no_message
  630. : diag::ext_static_assert_no_message)
  631. << (getLangOpts().CPlusPlus1z
  632. ? FixItHint()
  633. : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
  634. } else {
  635. if (ExpectAndConsume(tok::comma)) {
  636. SkipUntil(tok::semi);
  637. return nullptr;
  638. }
  639. if (!isTokenStringLiteral()) {
  640. Diag(Tok, diag::err_expected_string_literal)
  641. << /*Source='static_assert'*/1;
  642. SkipMalformedDecl();
  643. return nullptr;
  644. }
  645. AssertMessage = ParseStringLiteralExpression();
  646. if (AssertMessage.isInvalid()) {
  647. SkipMalformedDecl();
  648. return nullptr;
  649. }
  650. }
  651. T.consumeClose();
  652. DeclEnd = Tok.getLocation();
  653. ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
  654. return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
  655. AssertExpr.get(),
  656. AssertMessage.get(),
  657. T.getCloseLocation());
  658. }
  659. /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
  660. ///
  661. /// 'decltype' ( expression )
  662. /// 'decltype' ( 'auto' ) [C++1y]
  663. ///
  664. SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
  665. assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
  666. && "Not a decltype specifier");
  667. ExprResult Result;
  668. SourceLocation StartLoc = Tok.getLocation();
  669. SourceLocation EndLoc;
  670. if (Tok.is(tok::annot_decltype)) {
  671. Result = getExprAnnotation(Tok);
  672. EndLoc = Tok.getAnnotationEndLoc();
  673. ConsumeToken();
  674. if (Result.isInvalid()) {
  675. DS.SetTypeSpecError();
  676. return EndLoc;
  677. }
  678. } else {
  679. if (Tok.getIdentifierInfo()->isStr("decltype"))
  680. Diag(Tok, diag::warn_cxx98_compat_decltype);
  681. ConsumeToken();
  682. BalancedDelimiterTracker T(*this, tok::l_paren);
  683. if (T.expectAndConsume(diag::err_expected_lparen_after,
  684. "decltype", tok::r_paren)) {
  685. DS.SetTypeSpecError();
  686. return T.getOpenLocation() == Tok.getLocation() ?
  687. StartLoc : T.getOpenLocation();
  688. }
  689. // Check for C++1y 'decltype(auto)'.
  690. if (Tok.is(tok::kw_auto)) {
  691. // No need to disambiguate here: an expression can't start with 'auto',
  692. // because the typename-specifier in a function-style cast operation can't
  693. // be 'auto'.
  694. Diag(Tok.getLocation(),
  695. getLangOpts().CPlusPlus14
  696. ? diag::warn_cxx11_compat_decltype_auto_type_specifier
  697. : diag::ext_decltype_auto_type_specifier);
  698. ConsumeToken();
  699. } else {
  700. // Parse the expression
  701. // C++11 [dcl.type.simple]p4:
  702. // The operand of the decltype specifier is an unevaluated operand.
  703. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
  704. nullptr,/*IsDecltype=*/true);
  705. Result =
  706. Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
  707. return E->hasPlaceholderType() ? ExprError() : E;
  708. });
  709. if (Result.isInvalid()) {
  710. DS.SetTypeSpecError();
  711. if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
  712. EndLoc = ConsumeParen();
  713. } else {
  714. if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
  715. // Backtrack to get the location of the last token before the semi.
  716. PP.RevertCachedTokens(2);
  717. ConsumeToken(); // the semi.
  718. EndLoc = ConsumeAnyToken();
  719. assert(Tok.is(tok::semi));
  720. } else {
  721. EndLoc = Tok.getLocation();
  722. }
  723. }
  724. return EndLoc;
  725. }
  726. Result = Actions.ActOnDecltypeExpression(Result.get());
  727. }
  728. // Match the ')'
  729. T.consumeClose();
  730. if (T.getCloseLocation().isInvalid()) {
  731. DS.SetTypeSpecError();
  732. // FIXME: this should return the location of the last token
  733. // that was consumed (by "consumeClose()")
  734. return T.getCloseLocation();
  735. }
  736. if (Result.isInvalid()) {
  737. DS.SetTypeSpecError();
  738. return T.getCloseLocation();
  739. }
  740. EndLoc = T.getCloseLocation();
  741. }
  742. assert(!Result.isInvalid());
  743. const char *PrevSpec = nullptr;
  744. unsigned DiagID;
  745. const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
  746. // Check for duplicate type specifiers (e.g. "int decltype(a)").
  747. if (Result.get()
  748. ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
  749. DiagID, Result.get(), Policy)
  750. : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
  751. DiagID, Policy)) {
  752. Diag(StartLoc, DiagID) << PrevSpec;
  753. DS.SetTypeSpecError();
  754. }
  755. return EndLoc;
  756. }
  757. void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
  758. SourceLocation StartLoc,
  759. SourceLocation EndLoc) {
  760. // make sure we have a token we can turn into an annotation token
  761. if (PP.isBacktrackEnabled())
  762. PP.RevertCachedTokens(1);
  763. else
  764. PP.EnterToken(Tok);
  765. Tok.setKind(tok::annot_decltype);
  766. setExprAnnotation(Tok,
  767. DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
  768. DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
  769. ExprError());
  770. Tok.setAnnotationEndLoc(EndLoc);
  771. Tok.setLocation(StartLoc);
  772. PP.AnnotateCachedTokens(Tok);
  773. }
  774. void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
  775. // HLSL Change Starts
  776. if (getLangOpts().HLSL) {
  777. Diag(Tok, diag::err_hlsl_unsupported_construct) << Tok.getName();
  778. DS.SetTypeSpecError();
  779. ConsumeToken();
  780. if (Tok.is(tok::l_paren)) {
  781. BalancedDelimiterTracker T(*this, tok::l_paren);
  782. T.consumeOpen();
  783. T.skipToEnd();
  784. }
  785. return;
  786. }
  787. // HLSL Change Ends
  788. assert(Tok.is(tok::kw___underlying_type) &&
  789. "Not an underlying type specifier");
  790. SourceLocation StartLoc = ConsumeToken();
  791. BalancedDelimiterTracker T(*this, tok::l_paren);
  792. if (T.expectAndConsume(diag::err_expected_lparen_after,
  793. "__underlying_type", tok::r_paren)) {
  794. return;
  795. }
  796. TypeResult Result = ParseTypeName();
  797. if (Result.isInvalid()) {
  798. SkipUntil(tok::r_paren, StopAtSemi);
  799. return;
  800. }
  801. // Match the ')'
  802. T.consumeClose();
  803. if (T.getCloseLocation().isInvalid())
  804. return;
  805. const char *PrevSpec = nullptr;
  806. unsigned DiagID;
  807. if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
  808. DiagID, Result.get(),
  809. Actions.getASTContext().getPrintingPolicy()))
  810. Diag(StartLoc, DiagID) << PrevSpec;
  811. DS.setTypeofParensRange(T.getRange());
  812. }
  813. /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
  814. /// class name or decltype-specifier. Note that we only check that the result
  815. /// names a type; semantic analysis will need to verify that the type names a
  816. /// class. The result is either a type or null, depending on whether a type
  817. /// name was found.
  818. ///
  819. /// base-type-specifier: [C++11 class.derived]
  820. /// class-or-decltype
  821. /// class-or-decltype: [C++11 class.derived]
  822. /// nested-name-specifier[opt] class-name
  823. /// decltype-specifier
  824. /// class-name: [C++ class.name]
  825. /// identifier
  826. /// simple-template-id
  827. ///
  828. /// In C++98, instead of base-type-specifier, we have:
  829. ///
  830. /// ::[opt] nested-name-specifier[opt] class-name
  831. TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
  832. SourceLocation &EndLocation) {
  833. // Ignore attempts to use typename
  834. if (Tok.is(tok::kw_typename)) {
  835. Diag(Tok, diag::err_expected_class_name_not_template)
  836. << FixItHint::CreateRemoval(Tok.getLocation());
  837. ConsumeToken();
  838. }
  839. // Parse optional nested-name-specifier
  840. CXXScopeSpec SS;
  841. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
  842. BaseLoc = Tok.getLocation();
  843. // Parse decltype-specifier
  844. // tok == kw_decltype is just error recovery, it can only happen when SS
  845. // isn't empty
  846. if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
  847. if (SS.isNotEmpty())
  848. Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
  849. << FixItHint::CreateRemoval(SS.getRange());
  850. // Fake up a Declarator to use with ActOnTypeName.
  851. DeclSpec DS(AttrFactory);
  852. EndLocation = ParseDecltypeSpecifier(DS);
  853. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  854. return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  855. }
  856. // Check whether we have a template-id that names a type.
  857. if (Tok.is(tok::annot_template_id)) {
  858. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  859. if (TemplateId->Kind == TNK_Type_template ||
  860. TemplateId->Kind == TNK_Dependent_template_name) {
  861. AnnotateTemplateIdTokenAsType();
  862. assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
  863. ParsedType Type = getTypeAnnotation(Tok);
  864. EndLocation = Tok.getAnnotationEndLoc();
  865. ConsumeToken();
  866. if (Type)
  867. return Type;
  868. return true;
  869. }
  870. // Fall through to produce an error below.
  871. }
  872. if (Tok.isNot(tok::identifier)) {
  873. Diag(Tok, diag::err_expected_class_name);
  874. return true;
  875. }
  876. IdentifierInfo *Id = Tok.getIdentifierInfo();
  877. SourceLocation IdLoc = ConsumeToken();
  878. if (Tok.is(tok::less) && !getLangOpts().HLSL) { // HLSL Change - do not fix for HLSL
  879. // It looks the user intended to write a template-id here, but the
  880. // template-name was wrong. Try to fix that.
  881. TemplateNameKind TNK = TNK_Type_template;
  882. TemplateTy Template;
  883. if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
  884. &SS, Template, TNK)) {
  885. Diag(IdLoc, diag::err_unknown_template_name)
  886. << Id;
  887. }
  888. if (!Template) {
  889. TemplateArgList TemplateArgs;
  890. SourceLocation LAngleLoc, RAngleLoc;
  891. ParseTemplateIdAfterTemplateName(TemplateTy(), IdLoc, SS,
  892. true, LAngleLoc, TemplateArgs, RAngleLoc);
  893. return true;
  894. }
  895. // Form the template name
  896. UnqualifiedId TemplateName;
  897. TemplateName.setIdentifier(Id, IdLoc);
  898. // Parse the full template-id, then turn it into a type.
  899. if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
  900. TemplateName, true))
  901. return true;
  902. if (TNK == TNK_Dependent_template_name)
  903. AnnotateTemplateIdTokenAsType();
  904. // If we didn't end up with a typename token, there's nothing more we
  905. // can do.
  906. if (Tok.isNot(tok::annot_typename))
  907. return true;
  908. // Retrieve the type from the annotation token, consume that token, and
  909. // return.
  910. EndLocation = Tok.getAnnotationEndLoc();
  911. ParsedType Type = getTypeAnnotation(Tok);
  912. ConsumeToken();
  913. return Type;
  914. }
  915. // We have an identifier; check whether it is actually a type.
  916. IdentifierInfo *CorrectedII = nullptr;
  917. ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true,
  918. false, ParsedType(),
  919. /*IsCtorOrDtorName=*/false,
  920. /*NonTrivialTypeSourceInfo=*/true,
  921. &CorrectedII);
  922. if (!Type) {
  923. Diag(IdLoc, diag::err_expected_class_name);
  924. return true;
  925. }
  926. // Consume the identifier.
  927. EndLocation = IdLoc;
  928. // Fake up a Declarator to use with ActOnTypeName.
  929. DeclSpec DS(AttrFactory);
  930. DS.SetRangeStart(IdLoc);
  931. DS.SetRangeEnd(EndLocation);
  932. DS.getTypeSpecScope() = SS;
  933. const char *PrevSpec = nullptr;
  934. unsigned DiagID;
  935. DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
  936. Actions.getASTContext().getPrintingPolicy());
  937. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  938. return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  939. }
  940. void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
  941. while (Tok.isOneOf(tok::kw___single_inheritance,
  942. tok::kw___multiple_inheritance,
  943. tok::kw___virtual_inheritance)) {
  944. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  945. SourceLocation AttrNameLoc = ConsumeToken();
  946. attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
  947. AttributeList::AS_Keyword);
  948. }
  949. }
  950. /// Determine whether the following tokens are valid after a type-specifier
  951. /// which could be a standalone declaration. This will conservatively return
  952. /// true if there's any doubt, and is appropriate for insert-';' fixits.
  953. bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
  954. // HLSL Change Starts - abridged version of the table below
  955. if (getLangOpts().HLSL) {
  956. switch (Tok.getKind()) {
  957. case tok::semi:
  958. case tok::identifier:
  959. return true;
  960. case tok::colon:
  961. return CouldBeBitfield;
  962. default:
  963. return false;
  964. }
  965. }
  966. // HLSL Change Ends
  967. // This switch enumerates the valid "follow" set for type-specifiers.
  968. switch (Tok.getKind()) {
  969. default: break;
  970. case tok::semi: // struct foo {...} ;
  971. case tok::star: // struct foo {...} * P;
  972. case tok::amp: // struct foo {...} & R = ...
  973. case tok::ampamp: // struct foo {...} && R = ...
  974. case tok::identifier: // struct foo {...} V ;
  975. case tok::r_paren: //(struct foo {...} ) {4}
  976. case tok::annot_cxxscope: // struct foo {...} a:: b;
  977. case tok::annot_typename: // struct foo {...} a ::b;
  978. case tok::annot_template_id: // struct foo {...} a<int> ::b;
  979. case tok::l_paren: // struct foo {...} ( x);
  980. case tok::comma: // __builtin_offsetof(struct foo{...} ,
  981. case tok::kw_operator: // struct foo operator ++() {...}
  982. case tok::kw___declspec: // struct foo {...} __declspec(...)
  983. case tok::l_square: // void f(struct f [ 3])
  984. case tok::ellipsis: // void f(struct f ... [Ns])
  985. // FIXME: we should emit semantic diagnostic when declaration
  986. // attribute is in type attribute position.
  987. case tok::kw___attribute: // struct foo __attribute__((used)) x;
  988. return true;
  989. case tok::colon:
  990. return CouldBeBitfield; // enum E { ... } : 2;
  991. // Type qualifiers
  992. case tok::kw_const: // struct foo {...} const x;
  993. case tok::kw_volatile: // struct foo {...} volatile x;
  994. case tok::kw_restrict: // struct foo {...} restrict x;
  995. case tok::kw__Atomic: // struct foo {...} _Atomic x;
  996. case tok::kw___unaligned: // struct foo {...} __unaligned *x;
  997. // Function specifiers
  998. // Note, no 'explicit'. An explicit function must be either a conversion
  999. // operator or a constructor. Either way, it can't have a return type.
  1000. case tok::kw_inline: // struct foo inline f();
  1001. case tok::kw_virtual: // struct foo virtual f();
  1002. case tok::kw_friend: // struct foo friend f();
  1003. // Storage-class specifiers
  1004. case tok::kw_static: // struct foo {...} static x;
  1005. case tok::kw_extern: // struct foo {...} extern x;
  1006. case tok::kw_typedef: // struct foo {...} typedef x;
  1007. case tok::kw_register: // struct foo {...} register x;
  1008. case tok::kw_auto: // struct foo {...} auto x;
  1009. case tok::kw_mutable: // struct foo {...} mutable x;
  1010. case tok::kw_thread_local: // struct foo {...} thread_local x;
  1011. case tok::kw_constexpr: // struct foo {...} constexpr x;
  1012. // As shown above, type qualifiers and storage class specifiers absolutely
  1013. // can occur after class specifiers according to the grammar. However,
  1014. // almost no one actually writes code like this. If we see one of these,
  1015. // it is much more likely that someone missed a semi colon and the
  1016. // type/storage class specifier we're seeing is part of the *next*
  1017. // intended declaration, as in:
  1018. //
  1019. // struct foo { ... }
  1020. // typedef int X;
  1021. //
  1022. // We'd really like to emit a missing semicolon error instead of emitting
  1023. // an error on the 'int' saying that you can't have two type specifiers in
  1024. // the same declaration of X. Because of this, we look ahead past this
  1025. // token to see if it's a type specifier. If so, we know the code is
  1026. // otherwise invalid, so we can produce the expected semi error.
  1027. if (!isKnownToBeTypeSpecifier(NextToken()))
  1028. return true;
  1029. break;
  1030. case tok::r_brace: // struct bar { struct foo {...} }
  1031. // Missing ';' at end of struct is accepted as an extension in C mode.
  1032. if (!getLangOpts().CPlusPlus)
  1033. return true;
  1034. break;
  1035. case tok::greater:
  1036. // template<class T = class X>
  1037. return getLangOpts().CPlusPlus;
  1038. }
  1039. return false;
  1040. }
  1041. /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
  1042. /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
  1043. /// until we reach the start of a definition or see a token that
  1044. /// cannot start a definition.
  1045. ///
  1046. /// class-specifier: [C++ class]
  1047. /// class-head '{' member-specification[opt] '}'
  1048. /// class-head '{' member-specification[opt] '}' attributes[opt]
  1049. /// class-head:
  1050. /// class-key identifier[opt] base-clause[opt]
  1051. /// class-key nested-name-specifier identifier base-clause[opt]
  1052. /// class-key nested-name-specifier[opt] simple-template-id
  1053. /// base-clause[opt]
  1054. /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
  1055. /// [GNU] class-key attributes[opt] nested-name-specifier
  1056. /// identifier base-clause[opt]
  1057. /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
  1058. /// simple-template-id base-clause[opt]
  1059. /// class-key:
  1060. /// 'class'
  1061. /// 'struct'
  1062. /// 'union'
  1063. ///
  1064. /// elaborated-type-specifier: [C++ dcl.type.elab]
  1065. /// class-key ::[opt] nested-name-specifier[opt] identifier
  1066. /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
  1067. /// simple-template-id
  1068. ///
  1069. /// Note that the C++ class-specifier and elaborated-type-specifier,
  1070. /// together, subsume the C99 struct-or-union-specifier:
  1071. ///
  1072. /// struct-or-union-specifier: [C99 6.7.2.1]
  1073. /// struct-or-union identifier[opt] '{' struct-contents '}'
  1074. /// struct-or-union identifier
  1075. /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
  1076. /// '}' attributes[opt]
  1077. /// [GNU] struct-or-union attributes[opt] identifier
  1078. /// struct-or-union:
  1079. /// 'struct'
  1080. /// 'union'
  1081. void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
  1082. SourceLocation StartLoc, DeclSpec &DS,
  1083. const ParsedTemplateInfo &TemplateInfo,
  1084. AccessSpecifier AS,
  1085. bool EnteringContext, DeclSpecContext DSC,
  1086. ParsedAttributesWithRange &Attributes) {
  1087. DeclSpec::TST TagType;
  1088. if (TagTokKind == tok::kw_struct)
  1089. TagType = DeclSpec::TST_struct;
  1090. else if (TagTokKind == tok::kw___interface || TagTokKind == tok::kw_interface) // HLSL Change - support 'interface'
  1091. TagType = DeclSpec::TST_interface;
  1092. else if (TagTokKind == tok::kw_class)
  1093. TagType = DeclSpec::TST_class;
  1094. else {
  1095. assert(TagTokKind == tok::kw_union && "Not a class specifier");
  1096. TagType = DeclSpec::TST_union;
  1097. }
  1098. if (Tok.is(tok::code_completion)) {
  1099. // Code completion for a struct, class, or union name.
  1100. Actions.CodeCompleteTag(getCurScope(), TagType);
  1101. return cutOffParsing();
  1102. }
  1103. // C++03 [temp.explicit] 14.7.2/8:
  1104. // The usual access checking rules do not apply to names used to specify
  1105. // explicit instantiations.
  1106. //
  1107. // As an extension we do not perform access checking on the names used to
  1108. // specify explicit specializations either. This is important to allow
  1109. // specializing traits classes for private types.
  1110. //
  1111. // Note that we don't suppress if this turns out to be an elaborated
  1112. // type specifier.
  1113. bool shouldDelayDiagsInTag =
  1114. (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
  1115. TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
  1116. SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
  1117. ParsedAttributesWithRange attrs(AttrFactory);
  1118. // If attributes exist after tag, parse them.
  1119. MaybeParseGNUAttributes(attrs);
  1120. MaybeParseMicrosoftDeclSpecs(attrs);
  1121. // Parse inheritance specifiers.
  1122. // HLSL Change Starts - these keywords are only defined for Microsoft Extensions
  1123. assert(!getLangOpts().HLSL ||
  1124. (!Tok.is(tok::kw___single_inheritance) && !Tok.is(tok::kw___multiple_inheritance) && !Tok.is(tok::kw___virtual_inheritance))); // HLSL Change
  1125. if (!getLangOpts().HLSL) {
  1126. // HLSL Change Ends - succeeding block is now conditional
  1127. if (Tok.isOneOf(tok::kw___single_inheritance,
  1128. tok::kw___multiple_inheritance,
  1129. tok::kw___virtual_inheritance))
  1130. ParseMicrosoftInheritanceClassAttributes(attrs);
  1131. } // HLSL Change - close conditional block
  1132. // If C++0x attributes exist here, parse them.
  1133. // FIXME: Are we consistent with the ordering of parsing of different
  1134. // styles of attributes?
  1135. MaybeParseCXX11Attributes(attrs);
  1136. MaybeParseHLSLAttributes(attrs); // HLSL Change
  1137. // Source location used by FIXIT to insert misplaced
  1138. // C++11 attributes
  1139. SourceLocation AttrFixitLoc = Tok.getLocation();
  1140. if (!getLangOpts().HLSL) { // HLSL Change - skip fixes for GNU libstdc++ - succeeding block is now conditional
  1141. if (TagType == DeclSpec::TST_struct &&
  1142. Tok.isNot(tok::identifier) &&
  1143. !Tok.isAnnotation() &&
  1144. Tok.getIdentifierInfo() &&
  1145. Tok.isOneOf(tok::kw___is_abstract,
  1146. tok::kw___is_arithmetic,
  1147. tok::kw___is_array,
  1148. tok::kw___is_base_of,
  1149. tok::kw___is_class,
  1150. tok::kw___is_complete_type,
  1151. tok::kw___is_compound,
  1152. tok::kw___is_const,
  1153. tok::kw___is_constructible,
  1154. tok::kw___is_convertible,
  1155. tok::kw___is_convertible_to,
  1156. tok::kw___is_destructible,
  1157. tok::kw___is_empty,
  1158. tok::kw___is_enum,
  1159. tok::kw___is_floating_point,
  1160. tok::kw___is_final,
  1161. tok::kw___is_function,
  1162. tok::kw___is_fundamental,
  1163. tok::kw___is_integral,
  1164. tok::kw___is_interface_class,
  1165. tok::kw___is_literal,
  1166. tok::kw___is_lvalue_expr,
  1167. tok::kw___is_lvalue_reference,
  1168. tok::kw___is_member_function_pointer,
  1169. tok::kw___is_member_object_pointer,
  1170. tok::kw___is_member_pointer,
  1171. tok::kw___is_nothrow_assignable,
  1172. tok::kw___is_nothrow_constructible,
  1173. tok::kw___is_nothrow_destructible,
  1174. tok::kw___is_object,
  1175. tok::kw___is_pod,
  1176. tok::kw___is_pointer,
  1177. tok::kw___is_polymorphic,
  1178. tok::kw___is_reference,
  1179. tok::kw___is_rvalue_expr,
  1180. tok::kw___is_rvalue_reference,
  1181. tok::kw___is_same,
  1182. tok::kw___is_scalar,
  1183. tok::kw___is_sealed,
  1184. tok::kw___is_signed,
  1185. tok::kw___is_standard_layout,
  1186. tok::kw___is_trivial,
  1187. tok::kw___is_trivially_assignable,
  1188. tok::kw___is_trivially_constructible,
  1189. tok::kw___is_trivially_copyable,
  1190. tok::kw___is_union,
  1191. tok::kw___is_unsigned,
  1192. tok::kw___is_void,
  1193. tok::kw___is_volatile))
  1194. // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
  1195. // name of struct templates, but some are keywords in GCC >= 4.3
  1196. // and Clang. Therefore, when we see the token sequence "struct
  1197. // X", make X into a normal identifier rather than a keyword, to
  1198. // allow libstdc++ 4.2 and libc++ to work properly.
  1199. TryKeywordIdentFallback(true);
  1200. } // HLSL Change - close conditional block
  1201. // Parse the (optional) nested-name-specifier.
  1202. CXXScopeSpec &SS = DS.getTypeSpecScope();
  1203. if (getLangOpts().CPlusPlus) {
  1204. // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
  1205. // is a base-specifier-list.
  1206. ColonProtectionRAIIObject X(*this);
  1207. CXXScopeSpec Spec;
  1208. bool HasValidSpec = true;
  1209. if (ParseOptionalCXXScopeSpecifier(Spec, ParsedType(), EnteringContext)) {
  1210. DS.SetTypeSpecError();
  1211. HasValidSpec = false;
  1212. }
  1213. if (Spec.isSet())
  1214. if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
  1215. Diag(Tok, diag::err_expected) << tok::identifier;
  1216. HasValidSpec = false;
  1217. }
  1218. if (HasValidSpec)
  1219. SS = Spec;
  1220. }
  1221. TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
  1222. // Parse the (optional) class name or simple-template-id.
  1223. IdentifierInfo *Name = nullptr;
  1224. SourceLocation NameLoc;
  1225. TemplateIdAnnotation *TemplateId = nullptr;
  1226. if (Tok.is(tok::identifier)) {
  1227. Name = Tok.getIdentifierInfo();
  1228. NameLoc = ConsumeToken();
  1229. if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
  1230. // The name was supposed to refer to a template, but didn't.
  1231. // Eat the template argument list and try to continue parsing this as
  1232. // a class (or template thereof).
  1233. TemplateArgList TemplateArgs;
  1234. SourceLocation LAngleLoc, RAngleLoc;
  1235. if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS,
  1236. true, LAngleLoc,
  1237. TemplateArgs, RAngleLoc)) {
  1238. // We couldn't parse the template argument list at all, so don't
  1239. // try to give any location information for the list.
  1240. LAngleLoc = RAngleLoc = SourceLocation();
  1241. }
  1242. Diag(NameLoc, diag::err_explicit_spec_non_template)
  1243. << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
  1244. << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
  1245. // Strip off the last template parameter list if it was empty, since
  1246. // we've removed its template argument list.
  1247. if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
  1248. if (TemplateParams && TemplateParams->size() > 1) {
  1249. TemplateParams->pop_back();
  1250. } else {
  1251. TemplateParams = nullptr;
  1252. const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
  1253. = ParsedTemplateInfo::NonTemplate;
  1254. }
  1255. } else if (TemplateInfo.Kind
  1256. == ParsedTemplateInfo::ExplicitInstantiation) {
  1257. // Pretend this is just a forward declaration.
  1258. TemplateParams = nullptr;
  1259. const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
  1260. = ParsedTemplateInfo::NonTemplate;
  1261. const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
  1262. = SourceLocation();
  1263. const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
  1264. = SourceLocation();
  1265. }
  1266. }
  1267. } else if (Tok.is(tok::annot_template_id)) {
  1268. TemplateId = takeTemplateIdAnnotation(Tok);
  1269. NameLoc = ConsumeToken();
  1270. if (TemplateId->Kind != TNK_Type_template &&
  1271. TemplateId->Kind != TNK_Dependent_template_name) {
  1272. // The template-name in the simple-template-id refers to
  1273. // something other than a class template. Give an appropriate
  1274. // error message and skip to the ';'.
  1275. SourceRange Range(NameLoc);
  1276. if (SS.isNotEmpty())
  1277. Range.setBegin(SS.getBeginLoc());
  1278. // FIXME: Name may be null here.
  1279. Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
  1280. << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
  1281. DS.SetTypeSpecError();
  1282. SkipUntil(tok::semi, StopBeforeMatch);
  1283. return;
  1284. }
  1285. }
  1286. // There are four options here.
  1287. // - If we are in a trailing return type, this is always just a reference,
  1288. // and we must not try to parse a definition. For instance,
  1289. // [] () -> struct S { };
  1290. // does not define a type.
  1291. // - If we have 'struct foo {...', 'struct foo :...',
  1292. // 'struct foo final :' or 'struct foo final {', then this is a definition.
  1293. // - If we have 'struct foo;', then this is either a forward declaration
  1294. // or a friend declaration, which have to be treated differently.
  1295. // - Otherwise we have something like 'struct foo xyz', a reference.
  1296. //
  1297. // We also detect these erroneous cases to provide better diagnostic for
  1298. // C++11 attributes parsing.
  1299. // - attributes follow class name:
  1300. // struct foo [[]] {};
  1301. // - attributes appear before or after 'final':
  1302. // struct foo [[]] final [[]] {};
  1303. //
  1304. // However, in type-specifier-seq's, things look like declarations but are
  1305. // just references, e.g.
  1306. // new struct s;
  1307. // or
  1308. // &T::operator struct s;
  1309. // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
  1310. // If there are attributes after class name, parse them.
  1311. MaybeParseCXX11Attributes(Attributes);
  1312. MaybeParseHLSLAttributes(Attributes); // HLSL Change
  1313. const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
  1314. Sema::TagUseKind TUK;
  1315. if (DSC == DSC_trailing)
  1316. TUK = Sema::TUK_Reference;
  1317. else if (Tok.is(tok::l_brace) ||
  1318. (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
  1319. (isCXX11FinalKeyword() &&
  1320. (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
  1321. if (DS.isFriendSpecified()) {
  1322. // C++ [class.friend]p2:
  1323. // A class shall not be defined in a friend declaration.
  1324. Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
  1325. << SourceRange(DS.getFriendSpecLoc());
  1326. // Skip everything up to the semicolon, so that this looks like a proper
  1327. // friend class (or template thereof) declaration.
  1328. SkipUntil(tok::semi, StopBeforeMatch);
  1329. TUK = Sema::TUK_Friend;
  1330. } else {
  1331. // Okay, this is a class definition.
  1332. TUK = Sema::TUK_Definition;
  1333. }
  1334. } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
  1335. NextToken().is(tok::kw_alignas))) {
  1336. // We can't tell if this is a definition or reference
  1337. // until we skipped the 'final' and C++11 attribute specifiers.
  1338. TentativeParsingAction PA(*this);
  1339. // Skip the 'final' keyword.
  1340. ConsumeToken();
  1341. // Skip C++11 attribute specifiers.
  1342. while (true) {
  1343. if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
  1344. ConsumeBracket();
  1345. if (!SkipUntil(tok::r_square, StopAtSemi))
  1346. break;
  1347. } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
  1348. ConsumeToken();
  1349. ConsumeParen();
  1350. if (!SkipUntil(tok::r_paren, StopAtSemi))
  1351. break;
  1352. } else {
  1353. break;
  1354. }
  1355. }
  1356. if (Tok.isOneOf(tok::l_brace, tok::colon))
  1357. TUK = Sema::TUK_Definition;
  1358. else
  1359. TUK = Sema::TUK_Reference;
  1360. PA.Revert();
  1361. } else if (!isTypeSpecifier(DSC) &&
  1362. (Tok.is(tok::semi) ||
  1363. (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
  1364. TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
  1365. if (Tok.isNot(tok::semi)) {
  1366. const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
  1367. // A semicolon was missing after this declaration. Diagnose and recover.
  1368. ExpectAndConsume(tok::semi, diag::err_expected_after,
  1369. DeclSpec::getSpecifierName(TagType, PPol));
  1370. PP.EnterToken(Tok);
  1371. Tok.setKind(tok::semi);
  1372. }
  1373. } else
  1374. TUK = Sema::TUK_Reference;
  1375. // Forbid misplaced attributes. In cases of a reference, we pass attributes
  1376. // to caller to handle.
  1377. if (TUK != Sema::TUK_Reference) {
  1378. // If this is not a reference, then the only possible
  1379. // valid place for C++11 attributes to appear here
  1380. // is between class-key and class-name. If there are
  1381. // any attributes after class-name, we try a fixit to move
  1382. // them to the right place.
  1383. SourceRange AttrRange = Attributes.Range;
  1384. if (AttrRange.isValid()) {
  1385. Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
  1386. << AttrRange
  1387. << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
  1388. CharSourceRange(AttrRange, true))
  1389. << FixItHint::CreateRemoval(AttrRange);
  1390. // Recover by adding misplaced attributes to the attribute list
  1391. // of the class so they can be applied on the class later.
  1392. attrs.takeAllFrom(Attributes);
  1393. }
  1394. }
  1395. // If this is an elaborated type specifier, and we delayed
  1396. // diagnostics before, just merge them into the current pool.
  1397. if (shouldDelayDiagsInTag) {
  1398. diagsFromTag.done();
  1399. if (TUK == Sema::TUK_Reference)
  1400. diagsFromTag.redelay();
  1401. }
  1402. if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
  1403. TUK != Sema::TUK_Definition)) {
  1404. if (DS.getTypeSpecType() != DeclSpec::TST_error) {
  1405. // We have a declaration or reference to an anonymous class.
  1406. Diag(StartLoc, diag::err_anon_type_definition)
  1407. << DeclSpec::getSpecifierName(TagType, Policy);
  1408. }
  1409. // If we are parsing a definition and stop at a base-clause, continue on
  1410. // until the semicolon. Continuing from the comma will just trick us into
  1411. // thinking we are seeing a variable declaration.
  1412. if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
  1413. SkipUntil(tok::semi, StopBeforeMatch);
  1414. else
  1415. SkipUntil(tok::comma, StopAtSemi);
  1416. return;
  1417. }
  1418. // Create the tag portion of the class or class template.
  1419. DeclResult TagOrTempResult = true; // invalid
  1420. TypeResult TypeResult = true; // invalid
  1421. bool Owned = false;
  1422. Sema::SkipBodyInfo SkipBody;
  1423. if (TemplateId) {
  1424. // Explicit specialization, class template partial specialization,
  1425. // or explicit instantiation.
  1426. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  1427. TemplateId->NumArgs);
  1428. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
  1429. TUK == Sema::TUK_Declaration) {
  1430. // This is an explicit instantiation of a class template.
  1431. ProhibitAttributes(attrs);
  1432. TagOrTempResult
  1433. = Actions.ActOnExplicitInstantiation(getCurScope(),
  1434. TemplateInfo.ExternLoc,
  1435. TemplateInfo.TemplateLoc,
  1436. TagType,
  1437. StartLoc,
  1438. SS,
  1439. TemplateId->Template,
  1440. TemplateId->TemplateNameLoc,
  1441. TemplateId->LAngleLoc,
  1442. TemplateArgsPtr,
  1443. TemplateId->RAngleLoc,
  1444. attrs.getList());
  1445. // Friend template-ids are treated as references unless
  1446. // they have template headers, in which case they're ill-formed
  1447. // (FIXME: "template <class T> friend class A<T>::B<int>;").
  1448. // We diagnose this error in ActOnClassTemplateSpecialization.
  1449. } else if (TUK == Sema::TUK_Reference ||
  1450. (TUK == Sema::TUK_Friend &&
  1451. TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
  1452. ProhibitAttributes(attrs);
  1453. TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
  1454. TemplateId->SS,
  1455. TemplateId->TemplateKWLoc,
  1456. TemplateId->Template,
  1457. TemplateId->TemplateNameLoc,
  1458. TemplateId->LAngleLoc,
  1459. TemplateArgsPtr,
  1460. TemplateId->RAngleLoc);
  1461. } else {
  1462. // This is an explicit specialization or a class template
  1463. // partial specialization.
  1464. TemplateParameterLists FakedParamLists;
  1465. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
  1466. // This looks like an explicit instantiation, because we have
  1467. // something like
  1468. //
  1469. // template class Foo<X>
  1470. //
  1471. // but it actually has a definition. Most likely, this was
  1472. // meant to be an explicit specialization, but the user forgot
  1473. // the '<>' after 'template'.
  1474. // It this is friend declaration however, since it cannot have a
  1475. // template header, it is most likely that the user meant to
  1476. // remove the 'template' keyword.
  1477. assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
  1478. "Expected a definition here");
  1479. if (TUK == Sema::TUK_Friend) {
  1480. Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
  1481. TemplateParams = nullptr;
  1482. } else {
  1483. SourceLocation LAngleLoc =
  1484. PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
  1485. Diag(TemplateId->TemplateNameLoc,
  1486. diag::err_explicit_instantiation_with_definition)
  1487. << SourceRange(TemplateInfo.TemplateLoc)
  1488. << FixItHint::CreateInsertion(LAngleLoc, "<>");
  1489. // Create a fake template parameter list that contains only
  1490. // "template<>", so that we treat this construct as a class
  1491. // template specialization.
  1492. FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
  1493. 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
  1494. 0, LAngleLoc));
  1495. TemplateParams = &FakedParamLists;
  1496. }
  1497. }
  1498. // Build the class template specialization.
  1499. TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
  1500. getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
  1501. *TemplateId, attrs.getList(),
  1502. MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
  1503. : nullptr,
  1504. TemplateParams ? TemplateParams->size() : 0),
  1505. &SkipBody);
  1506. }
  1507. } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
  1508. TUK == Sema::TUK_Declaration) {
  1509. // Explicit instantiation of a member of a class template
  1510. // specialization, e.g.,
  1511. //
  1512. // template struct Outer<int>::Inner;
  1513. //
  1514. ProhibitAttributes(attrs);
  1515. TagOrTempResult
  1516. = Actions.ActOnExplicitInstantiation(getCurScope(),
  1517. TemplateInfo.ExternLoc,
  1518. TemplateInfo.TemplateLoc,
  1519. TagType, StartLoc, SS, Name,
  1520. NameLoc, attrs.getList());
  1521. } else if (TUK == Sema::TUK_Friend &&
  1522. TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
  1523. ProhibitAttributes(attrs);
  1524. TagOrTempResult =
  1525. Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
  1526. TagType, StartLoc, SS,
  1527. Name, NameLoc, attrs.getList(),
  1528. MultiTemplateParamsArg(
  1529. TemplateParams? &(*TemplateParams)[0]
  1530. : nullptr,
  1531. TemplateParams? TemplateParams->size() : 0));
  1532. } else {
  1533. if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
  1534. ProhibitAttributes(attrs);
  1535. if (TUK == Sema::TUK_Definition &&
  1536. TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
  1537. // If the declarator-id is not a template-id, issue a diagnostic and
  1538. // recover by ignoring the 'template' keyword.
  1539. Diag(Tok, diag::err_template_defn_explicit_instantiation)
  1540. << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
  1541. TemplateParams = nullptr;
  1542. }
  1543. bool IsDependent = false;
  1544. // Don't pass down template parameter lists if this is just a tag
  1545. // reference. For example, we don't need the template parameters here:
  1546. // template <class T> class A *makeA(T t);
  1547. MultiTemplateParamsArg TParams;
  1548. if (TUK != Sema::TUK_Reference && TemplateParams)
  1549. TParams =
  1550. MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
  1551. handleDeclspecAlignBeforeClassKey(attrs, DS, TUK);
  1552. // Declaration or definition of a class type
  1553. TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
  1554. SS, Name, NameLoc, attrs.getList(), AS,
  1555. DS.getModulePrivateSpecLoc(),
  1556. TParams, Owned, IsDependent,
  1557. SourceLocation(), false,
  1558. clang::TypeResult(),
  1559. DSC == DSC_type_specifier,
  1560. &SkipBody);
  1561. // If ActOnTag said the type was dependent, try again with the
  1562. // less common call.
  1563. if (IsDependent) {
  1564. assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
  1565. TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
  1566. SS, Name, StartLoc, NameLoc);
  1567. }
  1568. }
  1569. // If there is a body, parse it and inform the actions module.
  1570. if (TUK == Sema::TUK_Definition) {
  1571. assert(Tok.is(tok::l_brace) ||
  1572. (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
  1573. isCXX11FinalKeyword());
  1574. if (SkipBody.ShouldSkip)
  1575. SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
  1576. TagOrTempResult.get());
  1577. else if (getLangOpts().CPlusPlus)
  1578. ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
  1579. TagOrTempResult.get());
  1580. else
  1581. ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
  1582. }
  1583. const char *PrevSpec = nullptr;
  1584. unsigned DiagID;
  1585. bool Result;
  1586. if (!TypeResult.isInvalid()) {
  1587. Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
  1588. NameLoc.isValid() ? NameLoc : StartLoc,
  1589. PrevSpec, DiagID, TypeResult.get(), Policy);
  1590. } else if (!TagOrTempResult.isInvalid()) {
  1591. Result = DS.SetTypeSpecType(TagType, StartLoc,
  1592. NameLoc.isValid() ? NameLoc : StartLoc,
  1593. PrevSpec, DiagID, TagOrTempResult.get(), Owned,
  1594. Policy);
  1595. } else {
  1596. DS.SetTypeSpecError();
  1597. return;
  1598. }
  1599. if (Result)
  1600. Diag(StartLoc, DiagID) << PrevSpec;
  1601. // At this point, we've successfully parsed a class-specifier in 'definition'
  1602. // form (e.g. "struct foo { int x; }". While we could just return here, we're
  1603. // going to look at what comes after it to improve error recovery. If an
  1604. // impossible token occurs next, we assume that the programmer forgot a ; at
  1605. // the end of the declaration and recover that way.
  1606. //
  1607. // Also enforce C++ [temp]p3:
  1608. // In a template-declaration which defines a class, no declarator
  1609. // is permitted.
  1610. //
  1611. // After a type-specifier, we don't expect a semicolon. This only happens in
  1612. // C, since definitions are not permitted in this context in C++.
  1613. if (TUK == Sema::TUK_Definition &&
  1614. (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
  1615. (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
  1616. if (Tok.isNot(tok::semi)) {
  1617. const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
  1618. ExpectAndConsume(tok::semi, diag::err_expected_after,
  1619. DeclSpec::getSpecifierName(TagType, PPol));
  1620. // Push this token back into the preprocessor and change our current token
  1621. // to ';' so that the rest of the code recovers as though there were an
  1622. // ';' after the definition.
  1623. PP.EnterToken(Tok);
  1624. Tok.setKind(tok::semi);
  1625. }
  1626. }
  1627. }
  1628. /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
  1629. ///
  1630. /// base-clause : [C++ class.derived]
  1631. /// ':' base-specifier-list
  1632. /// base-specifier-list:
  1633. /// base-specifier '...'[opt]
  1634. /// base-specifier-list ',' base-specifier '...'[opt]
  1635. void Parser::ParseBaseClause(Decl *ClassDecl) {
  1636. assert(Tok.is(tok::colon) && "Not a base clause");
  1637. ConsumeToken();
  1638. // Build up an array of parsed base specifiers.
  1639. SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
  1640. while (true) {
  1641. // Parse a base-specifier.
  1642. BaseResult Result = ParseBaseSpecifier(ClassDecl);
  1643. if (Result.isInvalid()) {
  1644. // Skip the rest of this base specifier, up until the comma or
  1645. // opening brace.
  1646. SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
  1647. } else {
  1648. // Add this to our array of base specifiers.
  1649. BaseInfo.push_back(Result.get());
  1650. }
  1651. // If the next token is a comma, consume it and keep reading
  1652. // base-specifiers.
  1653. if (!TryConsumeToken(tok::comma))
  1654. break;
  1655. }
  1656. // Attach the base specifiers
  1657. Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
  1658. }
  1659. /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
  1660. /// one entry in the base class list of a class specifier, for example:
  1661. /// class foo : public bar, virtual private baz {
  1662. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  1663. ///
  1664. /// base-specifier: [C++ class.derived]
  1665. /// attribute-specifier-seq[opt] base-type-specifier
  1666. /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
  1667. /// base-type-specifier
  1668. /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
  1669. /// base-type-specifier
  1670. BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
  1671. bool IsVirtual = false;
  1672. SourceLocation StartLoc = Tok.getLocation();
  1673. ParsedAttributesWithRange Attributes(AttrFactory);
  1674. MaybeParseCXX11Attributes(Attributes);
  1675. // Parse the 'virtual' keyword.
  1676. if (TryConsumeToken(tok::kw_virtual)) {
  1677. if (getLangOpts().HLSL) Diag(Tok, diag::err_hlsl_unsupported_construct) << "virtual base type"; // HLSL Change
  1678. IsVirtual = true;
  1679. }
  1680. CheckMisplacedCXX11Attribute(Attributes, StartLoc);
  1681. // Parse an (optional) access specifier.
  1682. AccessSpecifier Access = getAccessSpecifierIfPresent();
  1683. if (Access != AS_none) Diag(Tok, diag::err_hlsl_unsupported_construct) << "base type access specifier"; // HLSL Change
  1684. if (Access != AS_none)
  1685. ConsumeToken();
  1686. if (getLangOpts().HLSL) Access = AS_public; // HLSL Change - always use public for hlsl.
  1687. CheckMisplacedCXX11Attribute(Attributes, StartLoc);
  1688. // Parse the 'virtual' keyword (again!), in case it came after the
  1689. // access specifier.
  1690. if (Tok.is(tok::kw_virtual)) {
  1691. if (getLangOpts().HLSL) Diag(Tok, diag::err_hlsl_unsupported_construct) << "virtual base type"; // HLSL Change
  1692. SourceLocation VirtualLoc = ConsumeToken();
  1693. if (IsVirtual) {
  1694. // Complain about duplicate 'virtual'
  1695. Diag(VirtualLoc, diag::err_dup_virtual)
  1696. << FixItHint::CreateRemoval(VirtualLoc);
  1697. }
  1698. IsVirtual = true;
  1699. }
  1700. CheckMisplacedCXX11Attribute(Attributes, StartLoc);
  1701. // Parse the class-name.
  1702. SourceLocation EndLocation;
  1703. SourceLocation BaseLoc;
  1704. TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
  1705. if (BaseType.isInvalid())
  1706. return true;
  1707. // Parse the optional ellipsis (for a pack expansion). The ellipsis is
  1708. // actually part of the base-specifier-list grammar productions, but we
  1709. // parse it here for convenience.
  1710. SourceLocation EllipsisLoc;
  1711. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  1712. if (getLangOpts().HLSL && EllipsisLoc != SourceLocation()) Diag(Tok, diag::err_hlsl_unsupported_construct) << "base type ellipsis"; // HLSL Change
  1713. // Find the complete source range for the base-specifier.
  1714. SourceRange Range(StartLoc, EndLocation);
  1715. // Notify semantic analysis that we have parsed a complete
  1716. // base-specifier.
  1717. return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
  1718. Access, BaseType.get(), BaseLoc,
  1719. EllipsisLoc);
  1720. }
  1721. /// getAccessSpecifierIfPresent - Determine whether the next token is
  1722. /// a C++ access-specifier.
  1723. ///
  1724. /// access-specifier: [C++ class.derived]
  1725. /// 'private'
  1726. /// 'protected'
  1727. /// 'public'
  1728. AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
  1729. switch (Tok.getKind()) {
  1730. default: return AS_none;
  1731. case tok::kw_private: return AS_private;
  1732. case tok::kw_protected: return AS_protected;
  1733. case tok::kw_public: return AS_public;
  1734. }
  1735. }
  1736. /// \brief If the given declarator has any parts for which parsing has to be
  1737. /// delayed, e.g., default arguments or an exception-specification, create a
  1738. /// late-parsed method declaration record to handle the parsing at the end of
  1739. /// the class definition.
  1740. void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
  1741. Decl *ThisDecl) {
  1742. DeclaratorChunk::FunctionTypeInfo &FTI
  1743. = DeclaratorInfo.getFunctionTypeInfo();
  1744. // If there was a late-parsed exception-specification, we'll need a
  1745. // late parse
  1746. bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
  1747. if (!NeedLateParse) {
  1748. // Look ahead to see if there are any default args
  1749. for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
  1750. auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
  1751. if (Param->hasUnparsedDefaultArg()) {
  1752. NeedLateParse = true;
  1753. break;
  1754. }
  1755. }
  1756. }
  1757. if (NeedLateParse) {
  1758. // Push this method onto the stack of late-parsed method
  1759. // declarations.
  1760. auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
  1761. getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
  1762. LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
  1763. // Stash the exception-specification tokens in the late-pased method.
  1764. LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
  1765. FTI.ExceptionSpecTokens = 0;
  1766. // Push tokens for each parameter. Those that do not have
  1767. // defaults will be NULL.
  1768. LateMethod->DefaultArgs.reserve(FTI.NumParams);
  1769. for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
  1770. LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
  1771. FTI.Params[ParamIdx].Param, FTI.Params[ParamIdx].DefaultArgTokens));
  1772. }
  1773. }
  1774. /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
  1775. /// virt-specifier.
  1776. ///
  1777. /// virt-specifier:
  1778. /// override
  1779. /// final
  1780. VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
  1781. if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier) || getLangOpts().HLSL) // HLSL Change: remove support for override and final
  1782. return VirtSpecifiers::VS_None;
  1783. IdentifierInfo *II = Tok.getIdentifierInfo();
  1784. // Initialize the contextual keywords.
  1785. if (!Ident_final) {
  1786. Ident_final = &PP.getIdentifierTable().get("final");
  1787. if (getLangOpts().MicrosoftExt)
  1788. Ident_sealed = &PP.getIdentifierTable().get("sealed");
  1789. Ident_override = &PP.getIdentifierTable().get("override");
  1790. }
  1791. if (II == Ident_override)
  1792. return VirtSpecifiers::VS_Override;
  1793. if (II == Ident_sealed)
  1794. return VirtSpecifiers::VS_Sealed;
  1795. if (II == Ident_final)
  1796. return VirtSpecifiers::VS_Final;
  1797. return VirtSpecifiers::VS_None;
  1798. }
  1799. /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
  1800. ///
  1801. /// virt-specifier-seq:
  1802. /// virt-specifier
  1803. /// virt-specifier-seq virt-specifier
  1804. void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
  1805. bool IsInterface,
  1806. SourceLocation FriendLoc) {
  1807. while (true) {
  1808. VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
  1809. if (Specifier == VirtSpecifiers::VS_None)
  1810. return;
  1811. if (FriendLoc.isValid()) {
  1812. Diag(Tok.getLocation(), diag::err_friend_decl_spec)
  1813. << VirtSpecifiers::getSpecifierName(Specifier)
  1814. << FixItHint::CreateRemoval(Tok.getLocation())
  1815. << SourceRange(FriendLoc, FriendLoc);
  1816. ConsumeToken();
  1817. continue;
  1818. }
  1819. // C++ [class.mem]p8:
  1820. // A virt-specifier-seq shall contain at most one of each virt-specifier.
  1821. const char *PrevSpec = nullptr;
  1822. if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
  1823. Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
  1824. << PrevSpec
  1825. << FixItHint::CreateRemoval(Tok.getLocation());
  1826. if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
  1827. Specifier == VirtSpecifiers::VS_Sealed)) {
  1828. Diag(Tok.getLocation(), diag::err_override_control_interface)
  1829. << VirtSpecifiers::getSpecifierName(Specifier);
  1830. } else if (Specifier == VirtSpecifiers::VS_Sealed) {
  1831. Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
  1832. } else {
  1833. Diag(Tok.getLocation(),
  1834. getLangOpts().CPlusPlus11
  1835. ? diag::warn_cxx98_compat_override_control_keyword
  1836. : diag::ext_override_control_keyword)
  1837. << VirtSpecifiers::getSpecifierName(Specifier);
  1838. }
  1839. ConsumeToken();
  1840. }
  1841. }
  1842. /// isCXX11FinalKeyword - Determine whether the next token is a C++11
  1843. /// 'final' or Microsoft 'sealed' contextual keyword.
  1844. bool Parser::isCXX11FinalKeyword() const {
  1845. if (getLangOpts().HLSL) return false; // HLSL Change - HLSL does not support final/sealed/override.
  1846. VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
  1847. return Specifier == VirtSpecifiers::VS_Final ||
  1848. Specifier == VirtSpecifiers::VS_Sealed;
  1849. }
  1850. /// \brief Parse a C++ member-declarator up to, but not including, the optional
  1851. /// brace-or-equal-initializer or pure-specifier.
  1852. bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
  1853. Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
  1854. LateParsedAttrList &LateParsedAttrs) {
  1855. // member-declarator:
  1856. // declarator pure-specifier[opt]
  1857. // declarator brace-or-equal-initializer[opt]
  1858. // identifier[opt] ':' constant-expression
  1859. if (Tok.isNot(tok::colon))
  1860. ParseDeclarator(DeclaratorInfo);
  1861. else
  1862. DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
  1863. if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
  1864. assert(DeclaratorInfo.isPastIdentifier() &&
  1865. "don't know where identifier would go yet?");
  1866. BitfieldSize = ParseConstantExpression();
  1867. if (BitfieldSize.isInvalid())
  1868. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  1869. } else {
  1870. ParseOptionalCXX11VirtSpecifierSeq(
  1871. VS, getCurrentClass().IsInterface,
  1872. DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
  1873. if (!VS.isUnset())
  1874. MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
  1875. }
  1876. // If a simple-asm-expr is present, parse it.
  1877. if (Tok.is(tok::kw_asm)) {
  1878. // HLSL Change Starts - disallow asm
  1879. if (getLangOpts().HLSL) {
  1880. Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName();
  1881. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  1882. return true;
  1883. }
  1884. // HLSL Change Ends
  1885. SourceLocation Loc;
  1886. ExprResult AsmLabel(ParseSimpleAsm(&Loc));
  1887. if (AsmLabel.isInvalid())
  1888. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  1889. DeclaratorInfo.setAsmLabel(AsmLabel.get());
  1890. DeclaratorInfo.SetRangeEnd(Loc);
  1891. }
  1892. // If attributes exist after the declarator, but before an '{', parse them.
  1893. MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
  1894. MaybeParseHLSLAttributes(DeclaratorInfo); // HLSL Change: Parse semantic on struct members
  1895. // For compatibility with code written to older Clang, also accept a
  1896. // virt-specifier *after* the GNU attributes.
  1897. if (!getLangOpts().HLSL && BitfieldSize.isUnset() && VS.isUnset()) { // HLSL Change - disallowed
  1898. ParseOptionalCXX11VirtSpecifierSeq(
  1899. VS, getCurrentClass().IsInterface,
  1900. DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
  1901. if (!VS.isUnset()) {
  1902. // If we saw any GNU-style attributes that are known to GCC followed by a
  1903. // virt-specifier, issue a GCC-compat warning.
  1904. const AttributeList *Attr = DeclaratorInfo.getAttributes();
  1905. while (Attr) {
  1906. if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
  1907. Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
  1908. Attr = Attr->getNext();
  1909. }
  1910. MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
  1911. }
  1912. }
  1913. // If this has neither a name nor a bit width, something has gone seriously
  1914. // wrong. Skip until the semi-colon or }.
  1915. if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
  1916. // If so, skip until the semi-colon or a }.
  1917. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
  1918. return true;
  1919. }
  1920. return false;
  1921. }
  1922. /// \brief Look for declaration specifiers possibly occurring after C++11
  1923. /// virt-specifier-seq and diagnose them.
  1924. void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
  1925. Declarator &D,
  1926. VirtSpecifiers &VS) {
  1927. DeclSpec DS(AttrFactory);
  1928. // GNU-style and C++11 attributes are not allowed here, but they will be
  1929. // handled by the caller. Diagnose everything else.
  1930. ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, false);
  1931. D.ExtendWithDeclSpec(DS);
  1932. if (D.isFunctionDeclarator()) {
  1933. auto &Function = D.getFunctionTypeInfo();
  1934. if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
  1935. auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
  1936. const char *FixItName,
  1937. SourceLocation SpecLoc,
  1938. unsigned* QualifierLoc) {
  1939. FixItHint Insertion;
  1940. if (DS.getTypeQualifiers() & TypeQual) {
  1941. if (!(Function.TypeQuals & TypeQual)) {
  1942. std::string Name(FixItName);
  1943. Name += " ";
  1944. Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name.c_str());
  1945. Function.TypeQuals |= TypeQual;
  1946. *QualifierLoc = SpecLoc.getRawEncoding();
  1947. }
  1948. Diag(SpecLoc, diag::err_declspec_after_virtspec)
  1949. << FixItName
  1950. << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
  1951. << FixItHint::CreateRemoval(SpecLoc)
  1952. << Insertion;
  1953. }
  1954. };
  1955. DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
  1956. &Function.ConstQualifierLoc);
  1957. DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
  1958. &Function.VolatileQualifierLoc);
  1959. DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
  1960. &Function.RestrictQualifierLoc);
  1961. }
  1962. // Parse ref-qualifiers.
  1963. bool RefQualifierIsLValueRef = true;
  1964. SourceLocation RefQualifierLoc;
  1965. if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
  1966. const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
  1967. FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
  1968. Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
  1969. Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
  1970. Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
  1971. << (RefQualifierIsLValueRef ? "&" : "&&")
  1972. << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
  1973. << FixItHint::CreateRemoval(RefQualifierLoc)
  1974. << Insertion;
  1975. D.SetRangeEnd(RefQualifierLoc);
  1976. }
  1977. }
  1978. }
  1979. /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
  1980. ///
  1981. /// member-declaration:
  1982. /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
  1983. /// function-definition ';'[opt]
  1984. /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
  1985. /// using-declaration [TODO]
  1986. /// [C++0x] static_assert-declaration
  1987. /// template-declaration
  1988. /// [GNU] '__extension__' member-declaration
  1989. ///
  1990. /// member-declarator-list:
  1991. /// member-declarator
  1992. /// member-declarator-list ',' member-declarator
  1993. ///
  1994. /// member-declarator:
  1995. /// declarator virt-specifier-seq[opt] pure-specifier[opt]
  1996. /// declarator constant-initializer[opt]
  1997. /// [C++11] declarator brace-or-equal-initializer[opt]
  1998. /// identifier[opt] ':' constant-expression
  1999. ///
  2000. /// virt-specifier-seq:
  2001. /// virt-specifier
  2002. /// virt-specifier-seq virt-specifier
  2003. ///
  2004. /// virt-specifier:
  2005. /// override
  2006. /// final
  2007. /// [MS] sealed
  2008. ///
  2009. /// pure-specifier:
  2010. /// '= 0'
  2011. ///
  2012. /// constant-initializer:
  2013. /// '=' constant-expression
  2014. ///
  2015. void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
  2016. AttributeList *AccessAttrs,
  2017. const ParsedTemplateInfo &TemplateInfo,
  2018. ParsingDeclRAIIObject *TemplateDiags) {
  2019. if (Tok.is(tok::at)) {
  2020. if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
  2021. Diag(Tok, diag::err_at_defs_cxx);
  2022. else
  2023. Diag(Tok, diag::err_at_in_class);
  2024. ConsumeToken();
  2025. SkipUntil(tok::r_brace, StopAtSemi);
  2026. return;
  2027. }
  2028. // Turn on colon protection early, while parsing declspec, although there is
  2029. // nothing to protect there. It prevents from false errors if error recovery
  2030. // incorrectly determines where the declspec ends, as in the example:
  2031. // struct A { enum class B { C }; };
  2032. // const int C = 4;
  2033. // struct D { A::B : C; };
  2034. ColonProtectionRAIIObject X(*this);
  2035. // Access declarations.
  2036. bool MalformedTypeSpec = false;
  2037. if (!TemplateInfo.Kind &&
  2038. Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
  2039. if (TryAnnotateCXXScopeToken())
  2040. MalformedTypeSpec = true;
  2041. bool isAccessDecl;
  2042. if (Tok.isNot(tok::annot_cxxscope))
  2043. isAccessDecl = false;
  2044. else if (NextToken().is(tok::identifier))
  2045. isAccessDecl = GetLookAheadToken(2).is(tok::semi);
  2046. else
  2047. isAccessDecl = NextToken().is(tok::kw_operator);
  2048. if (isAccessDecl) {
  2049. // Collect the scope specifier token we annotated earlier.
  2050. CXXScopeSpec SS;
  2051. ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
  2052. /*EnteringContext=*/false);
  2053. if (SS.isInvalid()) {
  2054. SkipUntil(tok::semi);
  2055. return;
  2056. }
  2057. // Try to parse an unqualified-id.
  2058. SourceLocation TemplateKWLoc;
  2059. UnqualifiedId Name;
  2060. if (ParseUnqualifiedId(SS, false, true, true, ParsedType(),
  2061. TemplateKWLoc, Name)) {
  2062. SkipUntil(tok::semi);
  2063. return;
  2064. }
  2065. // TODO: recover from mistakenly-qualified operator declarations.
  2066. if (ExpectAndConsume(tok::semi, diag::err_expected_after,
  2067. "access declaration")) {
  2068. SkipUntil(tok::semi);
  2069. return;
  2070. }
  2071. Actions.ActOnUsingDeclaration(getCurScope(), AS,
  2072. /* HasUsingKeyword */ false,
  2073. SourceLocation(),
  2074. SS, Name,
  2075. /* AttrList */ nullptr,
  2076. /* HasTypenameKeyword */ false,
  2077. SourceLocation());
  2078. return;
  2079. }
  2080. }
  2081. // static_assert-declaration. A templated static_assert declaration is
  2082. // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
  2083. if (!TemplateInfo.Kind &&
  2084. Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
  2085. SourceLocation DeclEnd;
  2086. ParseStaticAssertDeclaration(DeclEnd);
  2087. return;
  2088. }
  2089. if (Tok.is(tok::kw_template)) {
  2090. assert(!TemplateInfo.TemplateParams &&
  2091. "Nested template improperly parsed?");
  2092. // HLSL Change Start - disallow template members
  2093. if (getLangOpts().HLSL) {
  2094. Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName();
  2095. SkipUntil(tok::r_brace, StopAtSemi);
  2096. return;
  2097. }
  2098. // HLSL Change End
  2099. SourceLocation DeclEnd;
  2100. ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
  2101. AS, AccessAttrs);
  2102. return;
  2103. }
  2104. // Handle: member-declaration ::= '__extension__' member-declaration
  2105. if (Tok.is(tok::kw___extension__)) {
  2106. // __extension__ silences extension warnings in the subexpression.
  2107. ExtensionRAIIObject O(Diags); // Use RAII to do this.
  2108. ConsumeToken();
  2109. return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
  2110. TemplateInfo, TemplateDiags);
  2111. }
  2112. ParsedAttributesWithRange attrs(AttrFactory);
  2113. ParsedAttributesWithRange FnAttrs(AttrFactory);
  2114. // Optional C++11 attribute-specifier
  2115. MaybeParseCXX11Attributes(attrs);
  2116. MaybeParseHLSLAttributes(attrs); // HLSL Change
  2117. // We need to keep these attributes for future diagnostic
  2118. // before they are taken over by declaration specifier.
  2119. FnAttrs.addAll(attrs.getList());
  2120. FnAttrs.Range = attrs.Range;
  2121. MaybeParseMicrosoftAttributes(attrs);
  2122. if (Tok.is(tok::kw_using)) {
  2123. // HLSL Change Starts
  2124. if (getLangOpts().HLSL) {
  2125. Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName();
  2126. SkipUntil(tok::semi, StopBeforeMatch);
  2127. return;
  2128. }
  2129. // HLSL Change Ends
  2130. ProhibitAttributes(attrs);
  2131. // Eat 'using'.
  2132. SourceLocation UsingLoc = ConsumeToken();
  2133. if (Tok.is(tok::kw_namespace)) {
  2134. Diag(UsingLoc, diag::err_using_namespace_in_class);
  2135. SkipUntil(tok::semi, StopBeforeMatch);
  2136. } else {
  2137. SourceLocation DeclEnd;
  2138. // Otherwise, it must be a using-declaration or an alias-declaration.
  2139. ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
  2140. UsingLoc, DeclEnd, AS);
  2141. }
  2142. return;
  2143. }
  2144. // Hold late-parsed attributes so we can attach a Decl to them later.
  2145. LateParsedAttrList CommonLateParsedAttrs;
  2146. // decl-specifier-seq:
  2147. // Parse the common declaration-specifiers piece.
  2148. ParsingDeclSpec DS(*this, TemplateDiags);
  2149. DS.takeAttributesFrom(attrs);
  2150. if (MalformedTypeSpec)
  2151. DS.SetTypeSpecError();
  2152. ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
  2153. &CommonLateParsedAttrs);
  2154. // Turn off colon protection that was set for declspec.
  2155. X.restore();
  2156. // If we had a free-standing type definition with a missing semicolon, we
  2157. // may get this far before the problem becomes obvious.
  2158. if (DS.hasTagDefinition() &&
  2159. TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
  2160. DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
  2161. &CommonLateParsedAttrs))
  2162. return;
  2163. MultiTemplateParamsArg TemplateParams(
  2164. TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
  2165. : nullptr,
  2166. TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
  2167. if (TryConsumeToken(tok::semi)) {
  2168. if (DS.isFriendSpecified())
  2169. ProhibitAttributes(FnAttrs);
  2170. Decl *TheDecl =
  2171. Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams);
  2172. DS.complete(TheDecl);
  2173. return;
  2174. }
  2175. ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
  2176. VirtSpecifiers VS;
  2177. // Hold late-parsed attributes so we can attach a Decl to them later.
  2178. LateParsedAttrList LateParsedAttrs;
  2179. SourceLocation EqualLoc;
  2180. SourceLocation PureSpecLoc;
  2181. auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
  2182. if (Tok.isNot(tok::equal))
  2183. return false;
  2184. auto &Zero = NextToken();
  2185. SmallString<8> Buffer;
  2186. if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
  2187. PP.getSpelling(Zero, Buffer) != "0")
  2188. return false;
  2189. auto &After = GetLookAheadToken(2);
  2190. if (!After.isOneOf(tok::semi, tok::comma) &&
  2191. !(AllowDefinition &&
  2192. After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
  2193. return false;
  2194. EqualLoc = ConsumeToken();
  2195. PureSpecLoc = ConsumeToken();
  2196. return true;
  2197. };
  2198. SmallVector<Decl *, 8> DeclsInGroup;
  2199. ExprResult BitfieldSize;
  2200. bool ExpectSemi = true;
  2201. // Parse the first declarator.
  2202. if (ParseCXXMemberDeclaratorBeforeInitializer(
  2203. DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
  2204. TryConsumeToken(tok::semi);
  2205. return;
  2206. }
  2207. // Check for a member function definition.
  2208. if (BitfieldSize.isUnset()) {
  2209. // MSVC permits pure specifier on inline functions defined at class scope.
  2210. // Hence check for =0 before checking for function definition.
  2211. if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
  2212. TryConsumePureSpecifier(/*AllowDefinition*/ true);
  2213. FunctionDefinitionKind DefinitionKind = FDK_Declaration;
  2214. // function-definition:
  2215. //
  2216. // In C++11, a non-function declarator followed by an open brace is a
  2217. // braced-init-list for an in-class member initialization, not an
  2218. // erroneous function definition.
  2219. if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
  2220. DefinitionKind = FDK_Definition;
  2221. } else if (DeclaratorInfo.isFunctionDeclarator()) {
  2222. if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
  2223. DefinitionKind = FDK_Definition;
  2224. } else if (Tok.is(tok::equal)) {
  2225. const Token &KW = NextToken();
  2226. if (KW.is(tok::kw_default))
  2227. DefinitionKind = FDK_Defaulted;
  2228. else if (KW.is(tok::kw_delete))
  2229. DefinitionKind = FDK_Deleted;
  2230. }
  2231. }
  2232. DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
  2233. // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
  2234. // to a friend declaration, that declaration shall be a definition.
  2235. if (DeclaratorInfo.isFunctionDeclarator() &&
  2236. DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
  2237. // Diagnose attributes that appear before decl specifier:
  2238. // [[]] friend int foo();
  2239. ProhibitAttributes(FnAttrs);
  2240. }
  2241. if (DefinitionKind != FDK_Declaration) {
  2242. if (!DeclaratorInfo.isFunctionDeclarator()) {
  2243. Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
  2244. ConsumeBrace();
  2245. SkipUntil(tok::r_brace);
  2246. // Consume the optional ';'
  2247. TryConsumeToken(tok::semi);
  2248. return;
  2249. }
  2250. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
  2251. Diag(DeclaratorInfo.getIdentifierLoc(),
  2252. diag::err_function_declared_typedef);
  2253. // Recover by treating the 'typedef' as spurious.
  2254. DS.ClearStorageClassSpecs();
  2255. }
  2256. Decl *FunDecl =
  2257. ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
  2258. VS, PureSpecLoc);
  2259. if (FunDecl) {
  2260. for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
  2261. CommonLateParsedAttrs[i]->addDecl(FunDecl);
  2262. }
  2263. for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
  2264. LateParsedAttrs[i]->addDecl(FunDecl);
  2265. }
  2266. }
  2267. LateParsedAttrs.clear();
  2268. // Consume the ';' - it's optional unless we have a delete or default
  2269. if (Tok.is(tok::semi))
  2270. ConsumeExtraSemi(AfterMemberFunctionDefinition);
  2271. return;
  2272. }
  2273. }
  2274. // member-declarator-list:
  2275. // member-declarator
  2276. // member-declarator-list ',' member-declarator
  2277. while (1) {
  2278. InClassInitStyle HasInClassInit = ICIS_NoInit;
  2279. bool HasStaticInitializer = false;
  2280. if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
  2281. // HLSL Change Begin - only allow member default for static const.
  2282. if (DS.getStorageClassSpec() != DeclSpec::SCS_static ||
  2283. !(DS.getTypeQualifiers() & Qualifiers::Const))
  2284. Diag(Tok, diag::err_hlsl_unsupported_member_default);
  2285. // HLSL Change End
  2286. if (BitfieldSize.get()) {
  2287. Diag(Tok, diag::err_bitfield_member_init);
  2288. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  2289. } else if (DeclaratorInfo.isDeclarationOfFunction()) {
  2290. // It's a pure-specifier.
  2291. if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
  2292. // Parse it as an expression so that Sema can diagnose it.
  2293. HasStaticInitializer = true;
  2294. } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
  2295. DeclSpec::SCS_static &&
  2296. DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
  2297. DeclSpec::SCS_typedef &&
  2298. !DS.isFriendSpecified()) {
  2299. // It's a default member initializer.
  2300. HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
  2301. } else {
  2302. HasStaticInitializer = true;
  2303. }
  2304. }
  2305. // NOTE: If Sema is the Action module and declarator is an instance field,
  2306. // this call will *not* return the created decl; It will return null.
  2307. // See Sema::ActOnCXXMemberDeclarator for details.
  2308. NamedDecl *ThisDecl = nullptr;
  2309. if (DS.isFriendSpecified()) {
  2310. assert(!getLangOpts().HLSL && "unreachable in HLSL"); // HLSL Change
  2311. // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
  2312. // to a friend declaration, that declaration shall be a definition.
  2313. //
  2314. // Diagnose attributes that appear in a friend member function declarator:
  2315. // friend int foo [[]] ();
  2316. SmallVector<SourceRange, 4> Ranges;
  2317. DeclaratorInfo.getCXX11AttributeRanges(Ranges);
  2318. for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
  2319. E = Ranges.end(); I != E; ++I)
  2320. Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
  2321. ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
  2322. TemplateParams);
  2323. } else {
  2324. ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
  2325. DeclaratorInfo,
  2326. TemplateParams,
  2327. BitfieldSize.get(),
  2328. VS, HasInClassInit);
  2329. if (VarTemplateDecl *VT =
  2330. ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
  2331. // Re-direct this decl to refer to the templated decl so that we can
  2332. // initialize it.
  2333. ThisDecl = VT->getTemplatedDecl();
  2334. if (ThisDecl && AccessAttrs)
  2335. Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
  2336. }
  2337. // Error recovery might have converted a non-static member into a static
  2338. // member.
  2339. if (HasInClassInit != ICIS_NoInit &&
  2340. DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
  2341. DeclSpec::SCS_static) {
  2342. HasInClassInit = ICIS_NoInit;
  2343. HasStaticInitializer = true;
  2344. }
  2345. if (ThisDecl && PureSpecLoc.isValid())
  2346. Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
  2347. // Handle the initializer.
  2348. if (HasInClassInit != ICIS_NoInit) {
  2349. // The initializer was deferred; parse it and cache the tokens.
  2350. Diag(Tok, getLangOpts().CPlusPlus11
  2351. ? diag::warn_cxx98_compat_nonstatic_member_init
  2352. : diag::ext_nonstatic_member_init);
  2353. if (DeclaratorInfo.isArrayOfUnknownBound()) {
  2354. // C++11 [dcl.array]p3: An array bound may also be omitted when the
  2355. // declarator is followed by an initializer.
  2356. //
  2357. // A brace-or-equal-initializer for a member-declarator is not an
  2358. // initializer in the grammar, so this is ill-formed.
  2359. Diag(Tok, diag::err_incomplete_array_member_init);
  2360. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  2361. // Avoid later warnings about a class member of incomplete type.
  2362. if (ThisDecl)
  2363. ThisDecl->setInvalidDecl();
  2364. } else
  2365. ParseCXXNonStaticMemberInitializer(ThisDecl);
  2366. } else if (HasStaticInitializer) {
  2367. // Normal initializer.
  2368. ExprResult Init = ParseCXXMemberInitializer(
  2369. ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
  2370. if (Init.isInvalid())
  2371. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  2372. else if (ThisDecl)
  2373. Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
  2374. DS.containsPlaceholderType());
  2375. } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
  2376. // No initializer.
  2377. Actions.ActOnUninitializedDecl(ThisDecl, DS.containsPlaceholderType());
  2378. if (ThisDecl) {
  2379. if (!ThisDecl->isInvalidDecl()) {
  2380. // Set the Decl for any late parsed attributes
  2381. for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
  2382. CommonLateParsedAttrs[i]->addDecl(ThisDecl);
  2383. for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
  2384. LateParsedAttrs[i]->addDecl(ThisDecl);
  2385. }
  2386. Actions.FinalizeDeclaration(ThisDecl);
  2387. DeclsInGroup.push_back(ThisDecl);
  2388. if (DeclaratorInfo.isFunctionDeclarator() &&
  2389. DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
  2390. DeclSpec::SCS_typedef)
  2391. HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
  2392. }
  2393. LateParsedAttrs.clear();
  2394. DeclaratorInfo.complete(ThisDecl);
  2395. // If we don't have a comma, it is either the end of the list (a ';')
  2396. // or an error, bail out.
  2397. SourceLocation CommaLoc;
  2398. if (!TryConsumeToken(tok::comma, CommaLoc))
  2399. break;
  2400. if (Tok.isAtStartOfLine() &&
  2401. !MightBeDeclarator(Declarator::MemberContext)) {
  2402. // This comma was followed by a line-break and something which can't be
  2403. // the start of a declarator. The comma was probably a typo for a
  2404. // semicolon.
  2405. Diag(CommaLoc, diag::err_expected_semi_declaration)
  2406. << FixItHint::CreateReplacement(CommaLoc, ";");
  2407. ExpectSemi = false;
  2408. break;
  2409. }
  2410. // Parse the next declarator.
  2411. DeclaratorInfo.clear();
  2412. VS.clear();
  2413. BitfieldSize = ExprResult(/*Invalid=*/false);
  2414. EqualLoc = PureSpecLoc = SourceLocation();
  2415. DeclaratorInfo.setCommaLoc(CommaLoc);
  2416. // GNU attributes are allowed before the second and subsequent declarator.
  2417. MaybeParseGNUAttributes(DeclaratorInfo);
  2418. MaybeParseHLSLAttributes(DeclaratorInfo); // HLSL Change
  2419. if (ParseCXXMemberDeclaratorBeforeInitializer(
  2420. DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
  2421. break;
  2422. }
  2423. if (ExpectSemi &&
  2424. ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
  2425. // Skip to end of block or statement.
  2426. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
  2427. // If we stopped at a ';', eat it.
  2428. TryConsumeToken(tok::semi);
  2429. return;
  2430. }
  2431. Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
  2432. }
  2433. /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
  2434. /// Also detect and reject any attempted defaulted/deleted function definition.
  2435. /// The location of the '=', if any, will be placed in EqualLoc.
  2436. ///
  2437. /// This does not check for a pure-specifier; that's handled elsewhere.
  2438. ///
  2439. /// brace-or-equal-initializer:
  2440. /// '=' initializer-expression
  2441. /// braced-init-list
  2442. ///
  2443. /// initializer-clause:
  2444. /// assignment-expression
  2445. /// braced-init-list
  2446. ///
  2447. /// defaulted/deleted function-definition:
  2448. /// '=' 'default'
  2449. /// '=' 'delete'
  2450. ///
  2451. /// Prior to C++0x, the assignment-expression in an initializer-clause must
  2452. /// be a constant-expression.
  2453. ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
  2454. SourceLocation &EqualLoc) {
  2455. assert(Tok.isOneOf(tok::equal, tok::l_brace)
  2456. && "Data member initializer not starting with '=' or '{'");
  2457. EnterExpressionEvaluationContext Context(Actions,
  2458. Sema::PotentiallyEvaluated,
  2459. D);
  2460. if (TryConsumeToken(tok::equal, EqualLoc)) {
  2461. if (Tok.is(tok::kw_delete)) {
  2462. // In principle, an initializer of '= delete p;' is legal, but it will
  2463. // never type-check. It's better to diagnose it as an ill-formed expression
  2464. // than as an ill-formed deleted non-function member.
  2465. // An initializer of '= delete p, foo' will never be parsed, because
  2466. // a top-level comma always ends the initializer expression.
  2467. const Token &Next = NextToken();
  2468. if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
  2469. if (IsFunction)
  2470. Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
  2471. << 1 /* delete */;
  2472. else
  2473. Diag(ConsumeToken(), diag::err_deleted_non_function);
  2474. return ExprError();
  2475. }
  2476. } else if (Tok.is(tok::kw_default)) {
  2477. if (IsFunction)
  2478. Diag(Tok, diag::err_default_delete_in_multiple_declaration)
  2479. << 0 /* default */;
  2480. else
  2481. Diag(ConsumeToken(), diag::err_default_special_members);
  2482. return ExprError();
  2483. }
  2484. }
  2485. if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
  2486. Diag(Tok, diag::err_ms_property_initializer) << PD;
  2487. return ExprError();
  2488. }
  2489. return ParseInitializer();
  2490. }
  2491. void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
  2492. SourceLocation AttrFixitLoc,
  2493. unsigned TagType, Decl *TagDecl) {
  2494. // Skip the optional 'final' keyword.
  2495. if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
  2496. assert(isCXX11FinalKeyword() && "not a class definition");
  2497. ConsumeToken();
  2498. // Diagnose any C++11 attributes after 'final' keyword.
  2499. // We deliberately discard these attributes.
  2500. ParsedAttributesWithRange Attrs(AttrFactory);
  2501. CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
  2502. // This can only happen if we had malformed misplaced attributes;
  2503. // we only get called if there is a colon or left-brace after the
  2504. // attributes.
  2505. if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
  2506. return;
  2507. }
  2508. // Skip the base clauses. This requires actually parsing them, because
  2509. // otherwise we can't be sure where they end (a left brace may appear
  2510. // within a template argument).
  2511. if (Tok.is(tok::colon)) {
  2512. // Enter the scope of the class so that we can correctly parse its bases.
  2513. ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
  2514. ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
  2515. TagType == DeclSpec::TST_interface);
  2516. auto OldContext =
  2517. Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
  2518. // Parse the bases but don't attach them to the class.
  2519. ParseBaseClause(nullptr);
  2520. Actions.ActOnTagFinishSkippedDefinition(OldContext);
  2521. if (!Tok.is(tok::l_brace)) {
  2522. Diag(PP.getLocForEndOfToken(PrevTokLocation),
  2523. diag::err_expected_lbrace_after_base_specifiers);
  2524. return;
  2525. }
  2526. }
  2527. // Skip the body.
  2528. assert(Tok.is(tok::l_brace));
  2529. BalancedDelimiterTracker T(*this, tok::l_brace);
  2530. T.consumeOpen();
  2531. T.skipToEnd();
  2532. // Parse and discard any trailing attributes.
  2533. ParsedAttributes Attrs(AttrFactory);
  2534. if (Tok.is(tok::kw___attribute))
  2535. MaybeParseGNUAttributes(Attrs);
  2536. }
  2537. /// ParseCXXMemberSpecification - Parse the class definition.
  2538. ///
  2539. /// member-specification:
  2540. /// member-declaration member-specification[opt]
  2541. /// access-specifier ':' member-specification[opt]
  2542. ///
  2543. void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
  2544. SourceLocation AttrFixitLoc,
  2545. ParsedAttributesWithRange &Attrs,
  2546. unsigned TagType, Decl *TagDecl) {
  2547. assert((TagType == DeclSpec::TST_struct ||
  2548. TagType == DeclSpec::TST_interface ||
  2549. TagType == DeclSpec::TST_union ||
  2550. TagType == DeclSpec::TST_class) && "Invalid TagType!");
  2551. PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
  2552. "parsing struct/union/class body");
  2553. // Determine whether this is a non-nested class. Note that local
  2554. // classes are *not* considered to be nested classes.
  2555. bool NonNestedClass = true;
  2556. if (!ClassStack.empty()) {
  2557. for (const Scope *S = getCurScope(); S; S = S->getParent()) {
  2558. if (S->isClassScope()) {
  2559. // We're inside a class scope, so this is a nested class.
  2560. NonNestedClass = false;
  2561. // HLSL Change Starts
  2562. if (getLangOpts().HLSL) {
  2563. Diag(RecordLoc, diag::err_hlsl_unsupported_construct) << "nested class";
  2564. break;
  2565. } else {
  2566. // HLSL Change Ends - succeeding block is now conditional
  2567. // The Microsoft extension __interface does not permit nested classes.
  2568. if (getCurrentClass().IsInterface) {
  2569. Diag(RecordLoc, diag::err_invalid_member_in_interface)
  2570. << /*ErrorType=*/6
  2571. << (isa<NamedDecl>(TagDecl)
  2572. ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
  2573. : "(anonymous)");
  2574. }
  2575. } // HLSL Change - close conditional
  2576. break;
  2577. }
  2578. if ((S->getFlags() & Scope::FnScope))
  2579. // If we're in a function or function template then this is a local
  2580. // class rather than a nested class.
  2581. break;
  2582. }
  2583. }
  2584. // Enter a scope for the class.
  2585. ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
  2586. // Note that we are parsing a new (potentially-nested) class definition.
  2587. ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
  2588. TagType == DeclSpec::TST_interface);
  2589. if (TagDecl)
  2590. Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
  2591. SourceLocation FinalLoc;
  2592. bool IsFinalSpelledSealed = false;
  2593. // Parse the optional 'final' keyword.
  2594. if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
  2595. VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
  2596. assert((Specifier == VirtSpecifiers::VS_Final ||
  2597. Specifier == VirtSpecifiers::VS_Sealed) &&
  2598. "not a class definition");
  2599. FinalLoc = ConsumeToken();
  2600. IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
  2601. if (TagType == DeclSpec::TST_interface)
  2602. Diag(FinalLoc, diag::err_override_control_interface)
  2603. << VirtSpecifiers::getSpecifierName(Specifier);
  2604. else if (Specifier == VirtSpecifiers::VS_Final)
  2605. Diag(FinalLoc, getLangOpts().CPlusPlus11
  2606. ? diag::warn_cxx98_compat_override_control_keyword
  2607. : diag::ext_override_control_keyword)
  2608. << VirtSpecifiers::getSpecifierName(Specifier);
  2609. else if (Specifier == VirtSpecifiers::VS_Sealed)
  2610. Diag(FinalLoc, diag::ext_ms_sealed_keyword);
  2611. // Parse any C++11 attributes after 'final' keyword.
  2612. // These attributes are not allowed to appear here,
  2613. // and the only possible place for them to appertain
  2614. // to the class would be between class-key and class-name.
  2615. CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
  2616. // ParseClassSpecifier() does only a superficial check for attributes before
  2617. // deciding to call this method. For example, for
  2618. // `class C final alignas ([l) {` it will decide that this looks like a
  2619. // misplaced attribute since it sees `alignas '(' ')'`. But the actual
  2620. // attribute parsing code will try to parse the '[' as a constexpr lambda
  2621. // and consume enough tokens that the alignas parsing code will eat the
  2622. // opening '{'. So bail out if the next token isn't one we expect.
  2623. if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
  2624. if (TagDecl)
  2625. Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
  2626. return;
  2627. }
  2628. }
  2629. if (Tok.is(tok::colon)) {
  2630. ParseBaseClause(TagDecl);
  2631. if (!Tok.is(tok::l_brace)) {
  2632. bool SuggestFixIt = false;
  2633. SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
  2634. if (Tok.isAtStartOfLine()) {
  2635. switch (Tok.getKind()) {
  2636. case tok::kw_private:
  2637. case tok::kw_protected:
  2638. case tok::kw_public:
  2639. SuggestFixIt = NextToken().getKind() == tok::colon;
  2640. break;
  2641. case tok::kw_static_assert:
  2642. case tok::r_brace:
  2643. case tok::kw_using:
  2644. // base-clause can have simple-template-id; 'template' can't be there
  2645. case tok::kw_template:
  2646. SuggestFixIt = true;
  2647. break;
  2648. case tok::identifier:
  2649. SuggestFixIt = isConstructorDeclarator(true);
  2650. break;
  2651. default:
  2652. SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
  2653. break;
  2654. }
  2655. }
  2656. DiagnosticBuilder LBraceDiag =
  2657. Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
  2658. if (SuggestFixIt) {
  2659. LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
  2660. // Try recovering from missing { after base-clause.
  2661. PP.EnterToken(Tok);
  2662. Tok.setKind(tok::l_brace);
  2663. } else {
  2664. if (TagDecl)
  2665. Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
  2666. return;
  2667. }
  2668. }
  2669. }
  2670. assert(Tok.is(tok::l_brace));
  2671. BalancedDelimiterTracker T(*this, tok::l_brace);
  2672. T.consumeOpen();
  2673. if (TagDecl)
  2674. Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
  2675. IsFinalSpelledSealed,
  2676. T.getOpenLocation());
  2677. // C++ 11p3: Members of a class defined with the keyword class are private
  2678. // by default. Members of a class defined with the keywords struct or union
  2679. // are public by default.
  2680. AccessSpecifier CurAS;
  2681. if (TagType == DeclSpec::TST_class)
  2682. CurAS = AS_private;
  2683. else
  2684. CurAS = AS_public;
  2685. // HLSL Change Starts
  2686. if (getLangOpts().HLSL)
  2687. CurAS = AS_public; // HLSL only has public
  2688. // HLSL Change Ends
  2689. ParsedAttributes AccessAttrs(AttrFactory);
  2690. if (TagDecl) {
  2691. // While we still have something to read, read the member-declarations.
  2692. while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
  2693. // Each iteration of this loop reads one member-declaration.
  2694. if (!getLangOpts().HLSL && getLangOpts().MicrosoftExt && Tok.isOneOf(tok::kw___if_exists, // HLSL Change - remove support
  2695. tok::kw___if_not_exists)) {
  2696. ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
  2697. continue;
  2698. }
  2699. // Check for extraneous top-level semicolon.
  2700. if (Tok.is(tok::semi)) {
  2701. ConsumeExtraSemi(InsideStruct, TagType);
  2702. continue;
  2703. }
  2704. if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_vis)) { // HLSL Change - remove support
  2705. HandlePragmaVisibility();
  2706. continue;
  2707. }
  2708. if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_pack)) { // HLSL Change - remove support
  2709. HandlePragmaPack();
  2710. continue;
  2711. }
  2712. if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_align)) { // HLSL Change - remove support
  2713. HandlePragmaAlign();
  2714. continue;
  2715. }
  2716. if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_openmp)) { // HLSL Change - remove support
  2717. ParseOpenMPDeclarativeDirective();
  2718. continue;
  2719. }
  2720. if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_ms_pointers_to_members)) { // HLSL Change - remove support
  2721. HandlePragmaMSPointersToMembers();
  2722. continue;
  2723. }
  2724. if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_ms_pragma)) { // HLSL Change - remove support
  2725. HandlePragmaMSPragma();
  2726. continue;
  2727. }
  2728. // If we see a namespace here, a close brace was missing somewhere.
  2729. if (Tok.is(tok::kw_namespace)) {
  2730. DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
  2731. break;
  2732. }
  2733. AccessSpecifier AS = getAccessSpecifierIfPresent();
  2734. if (AS != AS_none) {
  2735. // HLSL Change Starts
  2736. if (getLangOpts().HLSL) {
  2737. Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName();
  2738. ConsumeToken();
  2739. if (Tok.is(tok::colon))
  2740. ConsumeToken();
  2741. continue;
  2742. }
  2743. // HLSL Change Ends
  2744. // Current token is a C++ access specifier.
  2745. CurAS = AS;
  2746. SourceLocation ASLoc = Tok.getLocation();
  2747. unsigned TokLength = Tok.getLength();
  2748. ConsumeToken();
  2749. AccessAttrs.clear();
  2750. MaybeParseGNUAttributes(AccessAttrs);
  2751. SourceLocation EndLoc;
  2752. if (TryConsumeToken(tok::colon, EndLoc)) {
  2753. } else if (TryConsumeToken(tok::semi, EndLoc)) {
  2754. Diag(EndLoc, diag::err_expected)
  2755. << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
  2756. } else {
  2757. EndLoc = ASLoc.getLocWithOffset(TokLength);
  2758. Diag(EndLoc, diag::err_expected)
  2759. << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
  2760. }
  2761. // The Microsoft extension __interface does not permit non-public
  2762. // access specifiers.
  2763. if (TagType == DeclSpec::TST_interface && CurAS != AS_public) {
  2764. Diag(ASLoc, diag::err_access_specifier_interface)
  2765. << (CurAS == AS_protected);
  2766. }
  2767. if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc,
  2768. AccessAttrs.getList())) {
  2769. // found another attribute than only annotations
  2770. AccessAttrs.clear();
  2771. }
  2772. continue;
  2773. }
  2774. // Parse all the comma separated declarators.
  2775. ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList());
  2776. }
  2777. T.consumeClose();
  2778. } else {
  2779. SkipUntil(tok::r_brace);
  2780. }
  2781. // If attributes exist after class contents, parse them.
  2782. ParsedAttributes attrs(AttrFactory);
  2783. MaybeParseGNUAttributes(attrs);
  2784. if (TagDecl)
  2785. Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
  2786. T.getOpenLocation(),
  2787. T.getCloseLocation(),
  2788. attrs.getList());
  2789. // C++11 [class.mem]p2:
  2790. // Within the class member-specification, the class is regarded as complete
  2791. // within function bodies, default arguments, exception-specifications, and
  2792. // brace-or-equal-initializers for non-static data members (including such
  2793. // things in nested classes).
  2794. if (TagDecl && NonNestedClass) {
  2795. // We are not inside a nested class. This class and its nested classes
  2796. // are complete and we can parse the delayed portions of method
  2797. // declarations and the lexed inline method definitions, along with any
  2798. // delayed attributes.
  2799. SourceLocation SavedPrevTokLocation = PrevTokLocation;
  2800. ParseLexedAttributes(getCurrentClass());
  2801. ParseLexedMethodDeclarations(getCurrentClass());
  2802. // We've finished with all pending member declarations.
  2803. Actions.ActOnFinishCXXMemberDecls();
  2804. ParseLexedMemberInitializers(getCurrentClass());
  2805. ParseLexedMethodDefs(getCurrentClass());
  2806. PrevTokLocation = SavedPrevTokLocation;
  2807. // We've finished parsing everything, including default argument
  2808. // initializers.
  2809. Actions.ActOnFinishCXXMemberDefaultArgs(TagDecl);
  2810. }
  2811. if (TagDecl)
  2812. Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
  2813. T.getCloseLocation());
  2814. // Leave the class scope.
  2815. ParsingDef.Pop();
  2816. ClassScope.Exit();
  2817. }
  2818. void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
  2819. assert(Tok.is(tok::kw_namespace));
  2820. // FIXME: Suggest where the close brace should have gone by looking
  2821. // at indentation changes within the definition body.
  2822. Diag(D->getLocation(),
  2823. diag::err_missing_end_of_definition) << D;
  2824. Diag(Tok.getLocation(),
  2825. diag::note_missing_end_of_definition_before) << D;
  2826. // Push '};' onto the token stream to recover.
  2827. PP.EnterToken(Tok);
  2828. Tok.startToken();
  2829. Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
  2830. Tok.setKind(tok::semi);
  2831. PP.EnterToken(Tok);
  2832. Tok.setKind(tok::r_brace);
  2833. }
  2834. /// ParseConstructorInitializer - Parse a C++ constructor initializer,
  2835. /// which explicitly initializes the members or base classes of a
  2836. /// class (C++ [class.base.init]). For example, the three initializers
  2837. /// after the ':' in the Derived constructor below:
  2838. ///
  2839. /// @code
  2840. /// class Base { };
  2841. /// class Derived : Base {
  2842. /// int x;
  2843. /// float f;
  2844. /// public:
  2845. /// Derived(float f) : Base(), x(17), f(f) { }
  2846. /// };
  2847. /// @endcode
  2848. ///
  2849. /// [C++] ctor-initializer:
  2850. /// ':' mem-initializer-list
  2851. ///
  2852. /// [C++] mem-initializer-list:
  2853. /// mem-initializer ...[opt]
  2854. /// mem-initializer ...[opt] , mem-initializer-list
  2855. void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
  2856. assert(Tok.is(tok::colon) &&
  2857. "Constructor initializer always starts with ':'");
  2858. // HLSL Change Starts
  2859. if (getLangOpts().HLSL) {
  2860. Diag(Tok, diag::err_hlsl_unsupported_construct) << "constructor initializer";
  2861. return;
  2862. }
  2863. // HLSL Change Ends
  2864. // Poison the SEH identifiers so they are flagged as illegal in constructor
  2865. // initializers.
  2866. PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
  2867. SourceLocation ColonLoc = ConsumeToken();
  2868. SmallVector<CXXCtorInitializer*, 4> MemInitializers;
  2869. bool AnyErrors = false;
  2870. do {
  2871. if (Tok.is(tok::code_completion)) {
  2872. Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
  2873. MemInitializers);
  2874. return cutOffParsing();
  2875. } else {
  2876. MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
  2877. if (!MemInit.isInvalid())
  2878. MemInitializers.push_back(MemInit.get());
  2879. else
  2880. AnyErrors = true;
  2881. }
  2882. if (Tok.is(tok::comma))
  2883. ConsumeToken();
  2884. else if (Tok.is(tok::l_brace))
  2885. break;
  2886. // If the next token looks like a base or member initializer, assume that
  2887. // we're just missing a comma.
  2888. else if (Tok.isOneOf(tok::identifier, tok::coloncolon)) {
  2889. SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
  2890. Diag(Loc, diag::err_ctor_init_missing_comma)
  2891. << FixItHint::CreateInsertion(Loc, ", ");
  2892. } else {
  2893. // Skip over garbage, until we get to '{'. Don't eat the '{'.
  2894. Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
  2895. << tok::comma;
  2896. SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
  2897. break;
  2898. }
  2899. } while (true);
  2900. Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
  2901. AnyErrors);
  2902. }
  2903. /// ParseMemInitializer - Parse a C++ member initializer, which is
  2904. /// part of a constructor initializer that explicitly initializes one
  2905. /// member or base class (C++ [class.base.init]). See
  2906. /// ParseConstructorInitializer for an example.
  2907. ///
  2908. /// [C++] mem-initializer:
  2909. /// mem-initializer-id '(' expression-list[opt] ')'
  2910. /// [C++0x] mem-initializer-id braced-init-list
  2911. ///
  2912. /// [C++] mem-initializer-id:
  2913. /// '::'[opt] nested-name-specifier[opt] class-name
  2914. /// identifier
  2915. MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
  2916. assert(!getLangOpts().HLSL && "unreachable from HLSL - without constructors, no mem initializers"); // HLSL Change
  2917. // parse '::'[opt] nested-name-specifier[opt]
  2918. CXXScopeSpec SS;
  2919. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
  2920. ParsedType TemplateTypeTy;
  2921. if (Tok.is(tok::annot_template_id)) {
  2922. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  2923. if (TemplateId->Kind == TNK_Type_template ||
  2924. TemplateId->Kind == TNK_Dependent_template_name) {
  2925. AnnotateTemplateIdTokenAsType();
  2926. assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
  2927. TemplateTypeTy = getTypeAnnotation(Tok);
  2928. }
  2929. }
  2930. // Uses of decltype will already have been converted to annot_decltype by
  2931. // ParseOptionalCXXScopeSpecifier at this point.
  2932. if (!TemplateTypeTy && Tok.isNot(tok::identifier)
  2933. && Tok.isNot(tok::annot_decltype)) {
  2934. Diag(Tok, diag::err_expected_member_or_base_name);
  2935. return true;
  2936. }
  2937. IdentifierInfo *II = nullptr;
  2938. DeclSpec DS(AttrFactory);
  2939. SourceLocation IdLoc = Tok.getLocation();
  2940. if (Tok.is(tok::annot_decltype)) {
  2941. // Get the decltype expression, if there is one.
  2942. ParseDecltypeSpecifier(DS);
  2943. } else {
  2944. if (Tok.is(tok::identifier))
  2945. // Get the identifier. This may be a member name or a class name,
  2946. // but we'll let the semantic analysis determine which it is.
  2947. II = Tok.getIdentifierInfo();
  2948. ConsumeToken();
  2949. }
  2950. // Parse the '('.
  2951. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  2952. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  2953. ExprResult InitList = ParseBraceInitializer();
  2954. if (InitList.isInvalid())
  2955. return true;
  2956. SourceLocation EllipsisLoc;
  2957. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  2958. return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
  2959. TemplateTypeTy, DS, IdLoc,
  2960. InitList.get(), EllipsisLoc);
  2961. } else if(Tok.is(tok::l_paren)) {
  2962. BalancedDelimiterTracker T(*this, tok::l_paren);
  2963. T.consumeOpen();
  2964. // Parse the optional expression-list.
  2965. ExprVector ArgExprs;
  2966. CommaLocsTy CommaLocs;
  2967. if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
  2968. SkipUntil(tok::r_paren, StopAtSemi);
  2969. return true;
  2970. }
  2971. T.consumeClose();
  2972. SourceLocation EllipsisLoc;
  2973. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  2974. return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
  2975. TemplateTypeTy, DS, IdLoc,
  2976. T.getOpenLocation(), ArgExprs,
  2977. T.getCloseLocation(), EllipsisLoc);
  2978. }
  2979. if (getLangOpts().CPlusPlus11)
  2980. return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
  2981. else
  2982. return Diag(Tok, diag::err_expected) << tok::l_paren;
  2983. }
  2984. /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
  2985. ///
  2986. /// exception-specification:
  2987. /// dynamic-exception-specification
  2988. /// noexcept-specification
  2989. ///
  2990. /// noexcept-specification:
  2991. /// 'noexcept'
  2992. /// 'noexcept' '(' constant-expression ')'
  2993. ExceptionSpecificationType
  2994. Parser::tryParseExceptionSpecification(bool Delayed,
  2995. SourceRange &SpecificationRange,
  2996. SmallVectorImpl<ParsedType> &DynamicExceptions,
  2997. SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
  2998. ExprResult &NoexceptExpr,
  2999. CachedTokens *&ExceptionSpecTokens) {
  3000. ExceptionSpecificationType Result = EST_None;
  3001. ExceptionSpecTokens = 0;
  3002. // Handle delayed parsing of exception-specifications.
  3003. if (Delayed) {
  3004. if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
  3005. return EST_None;
  3006. // HLSL Change Starts
  3007. if (getLangOpts().HLSL) {
  3008. assert(Tok.isNot(tok::kw_noexcept)); // not a keyword in the language.
  3009. Diag(SpecificationRange.getBegin(), diag::err_hlsl_unsupported_construct) << "exception specification";
  3010. return Result;
  3011. }
  3012. // HLSL Change Ends
  3013. // Consume and cache the starting token.
  3014. bool IsNoexcept = Tok.is(tok::kw_noexcept);
  3015. Token StartTok = Tok;
  3016. SpecificationRange = SourceRange(ConsumeToken());
  3017. // Check for a '('.
  3018. if (!Tok.is(tok::l_paren)) {
  3019. // If this is a bare 'noexcept', we're done.
  3020. if (IsNoexcept) {
  3021. Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
  3022. NoexceptExpr = 0;
  3023. return EST_BasicNoexcept;
  3024. }
  3025. Diag(Tok, diag::err_expected_lparen_after) << "throw";
  3026. return EST_DynamicNone;
  3027. }
  3028. // Cache the tokens for the exception-specification.
  3029. ExceptionSpecTokens = new CachedTokens;
  3030. ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
  3031. ExceptionSpecTokens->push_back(Tok); // '('
  3032. SpecificationRange.setEnd(ConsumeParen()); // '('
  3033. ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
  3034. /*StopAtSemi=*/true,
  3035. /*ConsumeFinalToken=*/true);
  3036. SpecificationRange.setEnd(Tok.getLocation());
  3037. return EST_Unparsed;
  3038. }
  3039. // See if there's a dynamic specification.
  3040. if (Tok.is(tok::kw_throw)) {
  3041. Result = ParseDynamicExceptionSpecification(SpecificationRange,
  3042. DynamicExceptions,
  3043. DynamicExceptionRanges);
  3044. assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
  3045. "Produced different number of exception types and ranges.");
  3046. // HLSL Change Starts
  3047. if (getLangOpts().HLSL) {
  3048. assert(Tok.isNot(tok::kw_noexcept)); // not a keyword in the language.
  3049. Diag(SpecificationRange.getBegin(), diag::err_hlsl_unsupported_construct) << "exception specification";
  3050. return Result;
  3051. }
  3052. // HLSL Change Ends
  3053. }
  3054. // HLSL Change Starts
  3055. if (getLangOpts().HLSL) {
  3056. assert(Tok.isNot(tok::kw_noexcept)); // not a keyword in the language.
  3057. return Result;
  3058. }
  3059. // HLSL Change Ends
  3060. // If there's no noexcept specification, we're done.
  3061. if (Tok.isNot(tok::kw_noexcept))
  3062. return Result;
  3063. Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
  3064. // If we already had a dynamic specification, parse the noexcept for,
  3065. // recovery, but emit a diagnostic and don't store the results.
  3066. SourceRange NoexceptRange;
  3067. ExceptionSpecificationType NoexceptType = EST_None;
  3068. SourceLocation KeywordLoc = ConsumeToken();
  3069. if (Tok.is(tok::l_paren)) {
  3070. // There is an argument.
  3071. BalancedDelimiterTracker T(*this, tok::l_paren);
  3072. T.consumeOpen();
  3073. NoexceptType = EST_ComputedNoexcept;
  3074. NoexceptExpr = ParseConstantExpression();
  3075. T.consumeClose();
  3076. // The argument must be contextually convertible to bool. We use
  3077. // ActOnBooleanCondition for this purpose.
  3078. if (!NoexceptExpr.isInvalid()) {
  3079. NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc,
  3080. NoexceptExpr.get());
  3081. NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
  3082. } else {
  3083. NoexceptType = EST_None;
  3084. }
  3085. } else {
  3086. // There is no argument.
  3087. NoexceptType = EST_BasicNoexcept;
  3088. NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
  3089. }
  3090. if (Result == EST_None) {
  3091. SpecificationRange = NoexceptRange;
  3092. Result = NoexceptType;
  3093. // If there's a dynamic specification after a noexcept specification,
  3094. // parse that and ignore the results.
  3095. if (Tok.is(tok::kw_throw)) {
  3096. Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
  3097. ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
  3098. DynamicExceptionRanges);
  3099. }
  3100. } else {
  3101. Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
  3102. }
  3103. return Result;
  3104. }
  3105. static void diagnoseDynamicExceptionSpecification(
  3106. Parser &P, const SourceRange &Range, bool IsNoexcept) {
  3107. if (P.getLangOpts().CPlusPlus11 && !P.getLangOpts().HLSL) { // HLSL Change - don't try to fix this for HLSL
  3108. const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
  3109. P.Diag(Range.getBegin(), diag::warn_exception_spec_deprecated) << Range;
  3110. P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
  3111. << Replacement << FixItHint::CreateReplacement(Range, Replacement);
  3112. }
  3113. }
  3114. /// ParseDynamicExceptionSpecification - Parse a C++
  3115. /// dynamic-exception-specification (C++ [except.spec]).
  3116. ///
  3117. /// dynamic-exception-specification:
  3118. /// 'throw' '(' type-id-list [opt] ')'
  3119. /// [MS] 'throw' '(' '...' ')'
  3120. ///
  3121. /// type-id-list:
  3122. /// type-id ... [opt]
  3123. /// type-id-list ',' type-id ... [opt]
  3124. ///
  3125. ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
  3126. SourceRange &SpecificationRange,
  3127. SmallVectorImpl<ParsedType> &Exceptions,
  3128. SmallVectorImpl<SourceRange> &Ranges) {
  3129. assert(Tok.is(tok::kw_throw) && "expected throw");
  3130. SpecificationRange.setBegin(ConsumeToken());
  3131. BalancedDelimiterTracker T(*this, tok::l_paren);
  3132. if (T.consumeOpen()) {
  3133. Diag(Tok, diag::err_expected_lparen_after) << "throw";
  3134. SpecificationRange.setEnd(SpecificationRange.getBegin());
  3135. return EST_DynamicNone;
  3136. }
  3137. // Parse throw(...), a Microsoft extension that means "this function
  3138. // can throw anything".
  3139. if (Tok.is(tok::ellipsis)) {
  3140. SourceLocation EllipsisLoc = ConsumeToken();
  3141. if (!getLangOpts().MicrosoftExt)
  3142. Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
  3143. T.consumeClose();
  3144. SpecificationRange.setEnd(T.getCloseLocation());
  3145. diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
  3146. return EST_MSAny;
  3147. }
  3148. // Parse the sequence of type-ids.
  3149. SourceRange Range;
  3150. while (Tok.isNot(tok::r_paren)) {
  3151. TypeResult Res(ParseTypeName(&Range));
  3152. if (Tok.is(tok::ellipsis)) {
  3153. // C++0x [temp.variadic]p5:
  3154. // - In a dynamic-exception-specification (15.4); the pattern is a
  3155. // type-id.
  3156. SourceLocation Ellipsis = ConsumeToken();
  3157. Range.setEnd(Ellipsis);
  3158. if (!Res.isInvalid())
  3159. Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
  3160. }
  3161. if (!Res.isInvalid()) {
  3162. Exceptions.push_back(Res.get());
  3163. Ranges.push_back(Range);
  3164. }
  3165. if (!TryConsumeToken(tok::comma))
  3166. break;
  3167. }
  3168. T.consumeClose();
  3169. SpecificationRange.setEnd(T.getCloseLocation());
  3170. diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
  3171. Exceptions.empty());
  3172. return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
  3173. }
  3174. /// ParseTrailingReturnType - Parse a trailing return type on a new-style
  3175. /// function declaration.
  3176. TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
  3177. assert(!getLangOpts().HLSL && "unreachable from HLSL, no lambda or new-style function declaration support"); // HLSL Change
  3178. assert(Tok.is(tok::arrow) && "expected arrow");
  3179. ConsumeToken();
  3180. return ParseTypeName(&Range, Declarator::TrailingReturnContext);
  3181. }
  3182. /// \brief We have just started parsing the definition of a new class,
  3183. /// so push that class onto our stack of classes that is currently
  3184. /// being parsed.
  3185. Sema::ParsingClassState
  3186. Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
  3187. bool IsInterface) {
  3188. assert((NonNestedClass || !ClassStack.empty()) &&
  3189. "Nested class without outer class");
  3190. ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
  3191. return Actions.PushParsingClass();
  3192. }
  3193. /// \brief Deallocate the given parsed class and all of its nested
  3194. /// classes.
  3195. void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
  3196. for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
  3197. delete Class->LateParsedDeclarations[I];
  3198. delete Class;
  3199. }
  3200. /// \brief Pop the top class of the stack of classes that are
  3201. /// currently being parsed.
  3202. ///
  3203. /// This routine should be called when we have finished parsing the
  3204. /// definition of a class, but have not yet popped the Scope
  3205. /// associated with the class's definition.
  3206. void Parser::PopParsingClass(Sema::ParsingClassState state) {
  3207. assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
  3208. Actions.PopParsingClass(state);
  3209. ParsingClass *Victim = ClassStack.top();
  3210. ClassStack.pop();
  3211. if (Victim->TopLevelClass) {
  3212. // Deallocate all of the nested classes of this class,
  3213. // recursively: we don't need to keep any of this information.
  3214. DeallocateParsedClasses(Victim);
  3215. return;
  3216. }
  3217. assert(!ClassStack.empty() && "Missing top-level class?");
  3218. if (Victim->LateParsedDeclarations.empty()) {
  3219. // The victim is a nested class, but we will not need to perform
  3220. // any processing after the definition of this class since it has
  3221. // no members whose handling was delayed. Therefore, we can just
  3222. // remove this nested class.
  3223. DeallocateParsedClasses(Victim);
  3224. return;
  3225. }
  3226. // This nested class has some members that will need to be processed
  3227. // after the top-level class is completely defined. Therefore, add
  3228. // it to the list of nested classes within its parent.
  3229. assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
  3230. ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
  3231. Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
  3232. }
  3233. /// \brief Try to parse an 'identifier' which appears within an attribute-token.
  3234. ///
  3235. /// \return the parsed identifier on success, and 0 if the next token is not an
  3236. /// attribute-token.
  3237. ///
  3238. /// C++11 [dcl.attr.grammar]p3:
  3239. /// If a keyword or an alternative token that satisfies the syntactic
  3240. /// requirements of an identifier is contained in an attribute-token,
  3241. /// it is considered an identifier.
  3242. IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
  3243. switch (Tok.getKind()) {
  3244. default:
  3245. // Identifiers and keywords have identifier info attached.
  3246. if (!Tok.isAnnotation()) {
  3247. if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
  3248. Loc = ConsumeToken();
  3249. return II;
  3250. }
  3251. }
  3252. return nullptr;
  3253. case tok::ampamp: // 'and'
  3254. case tok::pipe: // 'bitor'
  3255. case tok::pipepipe: // 'or'
  3256. case tok::caret: // 'xor'
  3257. case tok::tilde: // 'compl'
  3258. case tok::amp: // 'bitand'
  3259. case tok::ampequal: // 'and_eq'
  3260. case tok::pipeequal: // 'or_eq'
  3261. case tok::caretequal: // 'xor_eq'
  3262. case tok::exclaim: // 'not'
  3263. case tok::exclaimequal: // 'not_eq'
  3264. // Alternative tokens do not have identifier info, but their spelling
  3265. // starts with an alphabetical character.
  3266. SmallString<8> SpellingBuf;
  3267. SourceLocation SpellingLoc =
  3268. PP.getSourceManager().getSpellingLoc(Tok.getLocation());
  3269. StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
  3270. if (isLetter(Spelling[0])) {
  3271. Loc = ConsumeToken();
  3272. return &PP.getIdentifierTable().get(Spelling);
  3273. }
  3274. return nullptr;
  3275. }
  3276. }
  3277. static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
  3278. IdentifierInfo *ScopeName) {
  3279. switch (AttributeList::getKind(AttrName, ScopeName,
  3280. AttributeList::AS_CXX11)) {
  3281. case AttributeList::AT_CarriesDependency:
  3282. case AttributeList::AT_Deprecated:
  3283. case AttributeList::AT_FallThrough:
  3284. case AttributeList::AT_CXX11NoReturn: {
  3285. return true;
  3286. }
  3287. default:
  3288. return false;
  3289. }
  3290. }
  3291. /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
  3292. ///
  3293. /// [C++11] attribute-argument-clause:
  3294. /// '(' balanced-token-seq ')'
  3295. ///
  3296. /// [C++11] balanced-token-seq:
  3297. /// balanced-token
  3298. /// balanced-token-seq balanced-token
  3299. ///
  3300. /// [C++11] balanced-token:
  3301. /// '(' balanced-token-seq ')'
  3302. /// '[' balanced-token-seq ']'
  3303. /// '{' balanced-token-seq '}'
  3304. /// any token but '(', ')', '[', ']', '{', or '}'
  3305. bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
  3306. SourceLocation AttrNameLoc,
  3307. ParsedAttributes &Attrs,
  3308. SourceLocation *EndLoc,
  3309. IdentifierInfo *ScopeName,
  3310. SourceLocation ScopeLoc) {
  3311. assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
  3312. SourceLocation LParenLoc = Tok.getLocation();
  3313. // If the attribute isn't known, we will not attempt to parse any
  3314. // arguments.
  3315. if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
  3316. getTargetInfo().getTriple(), getLangOpts())) {
  3317. // Eat the left paren, then skip to the ending right paren.
  3318. ConsumeParen();
  3319. SkipUntil(tok::r_paren);
  3320. return false;
  3321. }
  3322. if (ScopeName && ScopeName->getName() == "gnu")
  3323. // GNU-scoped attributes have some special cases to handle GNU-specific
  3324. // behaviors.
  3325. ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
  3326. ScopeLoc, AttributeList::AS_CXX11, nullptr);
  3327. else {
  3328. unsigned NumArgs =
  3329. ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
  3330. ScopeName, ScopeLoc, AttributeList::AS_CXX11);
  3331. const AttributeList *Attr = Attrs.getList();
  3332. if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
  3333. // If the attribute is a standard or built-in attribute and we are
  3334. // parsing an argument list, we need to determine whether this attribute
  3335. // was allowed to have an argument list (such as [[deprecated]]), and how
  3336. // many arguments were parsed (so we can diagnose on [[deprecated()]]).
  3337. if (Attr->getMaxArgs() && !NumArgs) {
  3338. // The attribute was allowed to have arguments, but none were provided
  3339. // even though the attribute parsed successfully. This is an error.
  3340. Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
  3341. } else if (!Attr->getMaxArgs()) {
  3342. // The attribute parsed successfully, but was not allowed to have any
  3343. // arguments. It doesn't matter whether any were provided -- the
  3344. // presence of the argument list (even if empty) is diagnosed.
  3345. Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
  3346. << AttrName
  3347. << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
  3348. }
  3349. }
  3350. }
  3351. return true;
  3352. }
  3353. /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
  3354. ///
  3355. /// [C++11] attribute-specifier:
  3356. /// '[' '[' attribute-list ']' ']'
  3357. /// alignment-specifier
  3358. ///
  3359. /// [C++11] attribute-list:
  3360. /// attribute[opt]
  3361. /// attribute-list ',' attribute[opt]
  3362. /// attribute '...'
  3363. /// attribute-list ',' attribute '...'
  3364. ///
  3365. /// [C++11] attribute:
  3366. /// attribute-token attribute-argument-clause[opt]
  3367. ///
  3368. /// [C++11] attribute-token:
  3369. /// identifier
  3370. /// attribute-scoped-token
  3371. ///
  3372. /// [C++11] attribute-scoped-token:
  3373. /// attribute-namespace '::' identifier
  3374. ///
  3375. /// [C++11] attribute-namespace:
  3376. /// identifier
  3377. void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
  3378. SourceLocation *endLoc) {
  3379. if (Tok.is(tok::kw_alignas)) {
  3380. Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
  3381. ParseAlignmentSpecifier(attrs, endLoc);
  3382. return;
  3383. }
  3384. assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
  3385. && "Not a C++11 attribute list");
  3386. Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
  3387. ConsumeBracket();
  3388. ConsumeBracket();
  3389. llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
  3390. while (Tok.isNot(tok::r_square)) {
  3391. // attribute not present
  3392. if (TryConsumeToken(tok::comma))
  3393. continue;
  3394. SourceLocation ScopeLoc, AttrLoc;
  3395. IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
  3396. AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
  3397. if (!AttrName)
  3398. // Break out to the "expected ']'" diagnostic.
  3399. break;
  3400. // scoped attribute
  3401. if (TryConsumeToken(tok::coloncolon)) {
  3402. ScopeName = AttrName;
  3403. ScopeLoc = AttrLoc;
  3404. AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
  3405. if (!AttrName) {
  3406. Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
  3407. SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
  3408. continue;
  3409. }
  3410. }
  3411. bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
  3412. bool AttrParsed = false;
  3413. if (StandardAttr &&
  3414. !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
  3415. Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
  3416. << AttrName << SourceRange(SeenAttrs[AttrName]);
  3417. // Parse attribute arguments
  3418. if (Tok.is(tok::l_paren))
  3419. AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
  3420. ScopeName, ScopeLoc);
  3421. if (!AttrParsed)
  3422. attrs.addNew(AttrName,
  3423. SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
  3424. AttrLoc),
  3425. ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
  3426. if (TryConsumeToken(tok::ellipsis))
  3427. Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
  3428. << AttrName->getName();
  3429. }
  3430. if (ExpectAndConsume(tok::r_square))
  3431. SkipUntil(tok::r_square);
  3432. if (endLoc)
  3433. *endLoc = Tok.getLocation();
  3434. if (ExpectAndConsume(tok::r_square))
  3435. SkipUntil(tok::r_square);
  3436. }
  3437. /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
  3438. ///
  3439. /// attribute-specifier-seq:
  3440. /// attribute-specifier-seq[opt] attribute-specifier
  3441. void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
  3442. SourceLocation *endLoc) {
  3443. assert(getLangOpts().CPlusPlus11 || getLangOpts().HLSL); // HLSL Change
  3444. SourceLocation StartLoc = Tok.getLocation(), Loc;
  3445. if (!endLoc)
  3446. endLoc = &Loc;
  3447. do {
  3448. ParseCXX11AttributeSpecifier(attrs, endLoc);
  3449. } while (isCXX11AttributeSpecifier());
  3450. attrs.Range = SourceRange(StartLoc, *endLoc);
  3451. }
  3452. void Parser::DiagnoseAndSkipCXX11Attributes() {
  3453. // Start and end location of an attribute or an attribute list.
  3454. SourceLocation StartLoc = Tok.getLocation();
  3455. SourceLocation EndLoc = SkipCXX11Attributes();
  3456. if (EndLoc.isValid()) {
  3457. SourceRange Range(StartLoc, EndLoc);
  3458. Diag(StartLoc, diag::err_attributes_not_allowed)
  3459. << Range;
  3460. }
  3461. }
  3462. SourceLocation Parser::SkipCXX11Attributes() {
  3463. SourceLocation EndLoc;
  3464. if (!isCXX11AttributeSpecifier())
  3465. return EndLoc;
  3466. do {
  3467. if (Tok.is(tok::l_square)) {
  3468. BalancedDelimiterTracker T(*this, tok::l_square);
  3469. T.consumeOpen();
  3470. T.skipToEnd();
  3471. EndLoc = T.getCloseLocation();
  3472. } else {
  3473. assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
  3474. ConsumeToken();
  3475. BalancedDelimiterTracker T(*this, tok::l_paren);
  3476. if (!T.consumeOpen())
  3477. T.skipToEnd();
  3478. EndLoc = T.getCloseLocation();
  3479. }
  3480. } while (isCXX11AttributeSpecifier());
  3481. return EndLoc;
  3482. }
  3483. /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
  3484. ///
  3485. /// [MS] ms-attribute:
  3486. /// '[' token-seq ']'
  3487. ///
  3488. /// [MS] ms-attribute-seq:
  3489. /// ms-attribute[opt]
  3490. /// ms-attribute ms-attribute-seq
  3491. void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
  3492. SourceLocation *endLoc) {
  3493. assert(!getLangOpts().HLSL && "unreachable code for HLSL - Microsoft extension parsing is disabled"); // HLSL Change
  3494. assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
  3495. do {
  3496. // FIXME: If this is actually a C++11 attribute, parse it as one.
  3497. BalancedDelimiterTracker T(*this, tok::l_square);
  3498. T.consumeOpen();
  3499. SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch);
  3500. T.consumeClose();
  3501. if (endLoc)
  3502. *endLoc = T.getCloseLocation();
  3503. } while (Tok.is(tok::l_square));
  3504. }
  3505. void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
  3506. AccessSpecifier& CurAS) {
  3507. assert(!getLangOpts().HLSL && "unreachable code for HLSL - if-exists extension parsing skipped"); // HLSL Change
  3508. IfExistsCondition Result;
  3509. if (ParseMicrosoftIfExistsCondition(Result))
  3510. return;
  3511. BalancedDelimiterTracker Braces(*this, tok::l_brace);
  3512. if (Braces.consumeOpen()) {
  3513. Diag(Tok, diag::err_expected) << tok::l_brace;
  3514. return;
  3515. }
  3516. switch (Result.Behavior) {
  3517. case IEB_Parse:
  3518. // Parse the declarations below.
  3519. break;
  3520. case IEB_Dependent:
  3521. Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
  3522. << Result.IsIfExists;
  3523. // Fall through to skip.
  3524. case IEB_Skip:
  3525. Braces.skipToEnd();
  3526. return;
  3527. }
  3528. while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
  3529. // __if_exists, __if_not_exists can nest.
  3530. if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
  3531. ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
  3532. continue;
  3533. }
  3534. // Check for extraneous top-level semicolon.
  3535. if (Tok.is(tok::semi)) {
  3536. ConsumeExtraSemi(InsideStruct, TagType);
  3537. continue;
  3538. }
  3539. AccessSpecifier AS = getAccessSpecifierIfPresent();
  3540. if (AS != AS_none) {
  3541. // Current token is a C++ access specifier.
  3542. CurAS = AS;
  3543. SourceLocation ASLoc = Tok.getLocation();
  3544. ConsumeToken();
  3545. if (Tok.is(tok::colon))
  3546. Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
  3547. else
  3548. Diag(Tok, diag::err_expected) << tok::colon;
  3549. ConsumeToken();
  3550. continue;
  3551. }
  3552. // Parse all the comma separated declarators.
  3553. ParseCXXClassMemberDeclaration(CurAS, nullptr);
  3554. }
  3555. Braces.consumeClose();
  3556. }