ParseDecl.cpp 191 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396
  1. //===--- ParseDecl.cpp - 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 Declaration portions of the Parser interfaces.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Parse/Parser.h"
  14. #include "RAIIObjectsForParser.h"
  15. #include "clang/Basic/AddressSpaces.h"
  16. #include "clang/Basic/OpenCL.h"
  17. #include "clang/Parse/ParseDiagnostic.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "clang/Sema/ParsedTemplate.h"
  20. #include "clang/Sema/PrettyDeclStackTrace.h"
  21. #include "clang/Sema/Scope.h"
  22. #include "llvm/ADT/SmallSet.h"
  23. #include "llvm/ADT/SmallString.h"
  24. #include "llvm/ADT/StringSwitch.h"
  25. using namespace clang;
  26. //===----------------------------------------------------------------------===//
  27. // C99 6.7: Declarations.
  28. //===----------------------------------------------------------------------===//
  29. /// ParseTypeName
  30. /// type-name: [C99 6.7.6]
  31. /// specifier-qualifier-list abstract-declarator[opt]
  32. ///
  33. /// Called type-id in C++.
  34. TypeResult Parser::ParseTypeName(SourceRange *Range,
  35. Declarator::TheContext Context,
  36. AccessSpecifier AS,
  37. Decl **OwnedType) {
  38. DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
  39. if (DSC == DSC_normal)
  40. DSC = DSC_type_specifier;
  41. // Parse the common declaration-specifiers piece.
  42. DeclSpec DS(AttrFactory);
  43. ParseSpecifierQualifierList(DS, AS, DSC);
  44. if (OwnedType)
  45. *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : 0;
  46. // Parse the abstract-declarator, if present.
  47. Declarator DeclaratorInfo(DS, Context);
  48. ParseDeclarator(DeclaratorInfo);
  49. if (Range)
  50. *Range = DeclaratorInfo.getSourceRange();
  51. if (DeclaratorInfo.isInvalidType())
  52. return true;
  53. return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  54. }
  55. /// isAttributeLateParsed - Return true if the attribute has arguments that
  56. /// require late parsing.
  57. static bool isAttributeLateParsed(const IdentifierInfo &II) {
  58. return llvm::StringSwitch<bool>(II.getName())
  59. #include "clang/Parse/AttrLateParsed.inc"
  60. .Default(false);
  61. }
  62. /// ParseGNUAttributes - Parse a non-empty attributes list.
  63. ///
  64. /// [GNU] attributes:
  65. /// attribute
  66. /// attributes attribute
  67. ///
  68. /// [GNU] attribute:
  69. /// '__attribute__' '(' '(' attribute-list ')' ')'
  70. ///
  71. /// [GNU] attribute-list:
  72. /// attrib
  73. /// attribute_list ',' attrib
  74. ///
  75. /// [GNU] attrib:
  76. /// empty
  77. /// attrib-name
  78. /// attrib-name '(' identifier ')'
  79. /// attrib-name '(' identifier ',' nonempty-expr-list ')'
  80. /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
  81. ///
  82. /// [GNU] attrib-name:
  83. /// identifier
  84. /// typespec
  85. /// typequal
  86. /// storageclass
  87. ///
  88. /// FIXME: The GCC grammar/code for this construct implies we need two
  89. /// token lookahead. Comment from gcc: "If they start with an identifier
  90. /// which is followed by a comma or close parenthesis, then the arguments
  91. /// start with that identifier; otherwise they are an expression list."
  92. ///
  93. /// GCC does not require the ',' between attribs in an attribute-list.
  94. ///
  95. /// At the moment, I am not doing 2 token lookahead. I am also unaware of
  96. /// any attributes that don't work (based on my limited testing). Most
  97. /// attributes are very simple in practice. Until we find a bug, I don't see
  98. /// a pressing need to implement the 2 token lookahead.
  99. void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
  100. SourceLocation *endLoc,
  101. LateParsedAttrList *LateAttrs) {
  102. assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
  103. while (Tok.is(tok::kw___attribute)) {
  104. ConsumeToken();
  105. if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
  106. "attribute")) {
  107. SkipUntil(tok::r_paren, true); // skip until ) or ;
  108. return;
  109. }
  110. if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
  111. SkipUntil(tok::r_paren, true); // skip until ) or ;
  112. return;
  113. }
  114. // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
  115. while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
  116. Tok.is(tok::comma)) {
  117. if (Tok.is(tok::comma)) {
  118. // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
  119. ConsumeToken();
  120. continue;
  121. }
  122. // we have an identifier or declaration specifier (const, int, etc.)
  123. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  124. SourceLocation AttrNameLoc = ConsumeToken();
  125. if (Tok.is(tok::l_paren)) {
  126. // handle "parameterized" attributes
  127. if (LateAttrs && isAttributeLateParsed(*AttrName)) {
  128. LateParsedAttribute *LA =
  129. new LateParsedAttribute(this, *AttrName, AttrNameLoc);
  130. LateAttrs->push_back(LA);
  131. // Attributes in a class are parsed at the end of the class, along
  132. // with other late-parsed declarations.
  133. if (!ClassStack.empty() && !LateAttrs->parseSoon())
  134. getCurrentClass().LateParsedDeclarations.push_back(LA);
  135. // consume everything up to and including the matching right parens
  136. ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
  137. Token Eof;
  138. Eof.startToken();
  139. Eof.setLocation(Tok.getLocation());
  140. LA->Toks.push_back(Eof);
  141. } else {
  142. ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc,
  143. 0, SourceLocation(), AttributeList::AS_GNU);
  144. }
  145. } else {
  146. attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
  147. 0, SourceLocation(), 0, 0, AttributeList::AS_GNU);
  148. }
  149. }
  150. if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
  151. SkipUntil(tok::r_paren, false);
  152. SourceLocation Loc = Tok.getLocation();
  153. if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
  154. SkipUntil(tok::r_paren, false);
  155. }
  156. if (endLoc)
  157. *endLoc = Loc;
  158. }
  159. }
  160. /// Parse the arguments to a parameterized GNU attribute or
  161. /// a C++11 attribute in "gnu" namespace.
  162. void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
  163. SourceLocation AttrNameLoc,
  164. ParsedAttributes &Attrs,
  165. SourceLocation *EndLoc,
  166. IdentifierInfo *ScopeName,
  167. SourceLocation ScopeLoc,
  168. AttributeList::Syntax Syntax) {
  169. assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
  170. // Availability attributes have their own grammar.
  171. if (AttrName->isStr("availability")) {
  172. ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
  173. return;
  174. }
  175. // Thread safety attributes fit into the FIXME case above, so we
  176. // just parse the arguments as a list of expressions
  177. if (IsThreadSafetyAttribute(AttrName->getName())) {
  178. ParseThreadSafetyAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
  179. return;
  180. }
  181. // Type safety attributes have their own grammar.
  182. if (AttrName->isStr("type_tag_for_datatype")) {
  183. ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
  184. return;
  185. }
  186. ConsumeParen(); // ignore the left paren loc for now
  187. IdentifierInfo *ParmName = 0;
  188. SourceLocation ParmLoc;
  189. bool BuiltinType = false;
  190. switch (Tok.getKind()) {
  191. case tok::kw_char:
  192. case tok::kw_wchar_t:
  193. case tok::kw_char16_t:
  194. case tok::kw_char32_t:
  195. case tok::kw_bool:
  196. case tok::kw_short:
  197. case tok::kw_int:
  198. case tok::kw_long:
  199. case tok::kw___int64:
  200. case tok::kw___int128:
  201. case tok::kw_signed:
  202. case tok::kw_unsigned:
  203. case tok::kw_float:
  204. case tok::kw_double:
  205. case tok::kw_void:
  206. case tok::kw_typeof:
  207. // __attribute__(( vec_type_hint(char) ))
  208. // FIXME: Don't just discard the builtin type token.
  209. ConsumeToken();
  210. BuiltinType = true;
  211. break;
  212. case tok::identifier:
  213. ParmName = Tok.getIdentifierInfo();
  214. ParmLoc = ConsumeToken();
  215. break;
  216. default:
  217. break;
  218. }
  219. ExprVector ArgExprs;
  220. if (!BuiltinType &&
  221. (ParmLoc.isValid() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren))) {
  222. // Eat the comma.
  223. if (ParmLoc.isValid())
  224. ConsumeToken();
  225. // Parse the non-empty comma-separated list of expressions.
  226. while (1) {
  227. ExprResult ArgExpr(ParseAssignmentExpression());
  228. if (ArgExpr.isInvalid()) {
  229. SkipUntil(tok::r_paren);
  230. return;
  231. }
  232. ArgExprs.push_back(ArgExpr.release());
  233. if (Tok.isNot(tok::comma))
  234. break;
  235. ConsumeToken(); // Eat the comma, move to the next argument
  236. }
  237. }
  238. else if (Tok.is(tok::less) && AttrName->isStr("iboutletcollection")) {
  239. if (!ExpectAndConsume(tok::less, diag::err_expected_less_after, "<",
  240. tok::greater)) {
  241. while (Tok.is(tok::identifier)) {
  242. ConsumeToken();
  243. if (Tok.is(tok::greater))
  244. break;
  245. if (Tok.is(tok::comma)) {
  246. ConsumeToken();
  247. continue;
  248. }
  249. }
  250. if (Tok.isNot(tok::greater))
  251. Diag(Tok, diag::err_iboutletcollection_with_protocol);
  252. SkipUntil(tok::r_paren, false, true); // skip until ')'
  253. }
  254. }
  255. SourceLocation RParen = Tok.getLocation();
  256. if (!ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
  257. SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
  258. AttributeList *attr =
  259. Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen),
  260. ScopeName, ScopeLoc, ParmName, ParmLoc,
  261. ArgExprs.data(), ArgExprs.size(), Syntax);
  262. if (BuiltinType && attr->getKind() == AttributeList::AT_IBOutletCollection)
  263. Diag(Tok, diag::err_iboutletcollection_builtintype);
  264. }
  265. }
  266. /// \brief Parses a single argument for a declspec, including the
  267. /// surrounding parens.
  268. void Parser::ParseMicrosoftDeclSpecWithSingleArg(IdentifierInfo *AttrName,
  269. SourceLocation AttrNameLoc,
  270. ParsedAttributes &Attrs)
  271. {
  272. BalancedDelimiterTracker T(*this, tok::l_paren);
  273. if (T.expectAndConsume(diag::err_expected_lparen_after,
  274. AttrName->getNameStart(), tok::r_paren))
  275. return;
  276. ExprResult ArgExpr(ParseConstantExpression());
  277. if (ArgExpr.isInvalid()) {
  278. T.skipToEnd();
  279. return;
  280. }
  281. Expr *ExprList = ArgExpr.take();
  282. Attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
  283. &ExprList, 1, AttributeList::AS_Declspec);
  284. T.consumeClose();
  285. }
  286. /// \brief Determines whether a declspec is a "simple" one requiring no
  287. /// arguments.
  288. bool Parser::IsSimpleMicrosoftDeclSpec(IdentifierInfo *Ident) {
  289. return llvm::StringSwitch<bool>(Ident->getName())
  290. .Case("dllimport", true)
  291. .Case("dllexport", true)
  292. .Case("noreturn", true)
  293. .Case("nothrow", true)
  294. .Case("noinline", true)
  295. .Case("naked", true)
  296. .Case("appdomain", true)
  297. .Case("process", true)
  298. .Case("jitintrinsic", true)
  299. .Case("noalias", true)
  300. .Case("restrict", true)
  301. .Case("novtable", true)
  302. .Case("selectany", true)
  303. .Case("thread", true)
  304. .Default(false);
  305. }
  306. /// \brief Attempts to parse a declspec which is not simple (one that takes
  307. /// parameters). Will return false if we properly handled the declspec, or
  308. /// true if it is an unknown declspec.
  309. void Parser::ParseComplexMicrosoftDeclSpec(IdentifierInfo *Ident,
  310. SourceLocation Loc,
  311. ParsedAttributes &Attrs) {
  312. // Try to handle the easy case first -- these declspecs all take a single
  313. // parameter as their argument.
  314. if (llvm::StringSwitch<bool>(Ident->getName())
  315. .Case("uuid", true)
  316. .Case("align", true)
  317. .Case("allocate", true)
  318. .Default(false)) {
  319. ParseMicrosoftDeclSpecWithSingleArg(Ident, Loc, Attrs);
  320. } else if (Ident->getName() == "deprecated") {
  321. // The deprecated declspec has an optional single argument, so we will
  322. // check for a l-paren to decide whether we should parse an argument or
  323. // not.
  324. if (Tok.getKind() == tok::l_paren)
  325. ParseMicrosoftDeclSpecWithSingleArg(Ident, Loc, Attrs);
  326. else
  327. Attrs.addNew(Ident, Loc, 0, Loc, 0, SourceLocation(), 0, 0,
  328. AttributeList::AS_Declspec);
  329. } else if (Ident->getName() == "property") {
  330. // The property declspec is more complex in that it can take one or two
  331. // assignment expressions as a parameter, but the lhs of the assignment
  332. // must be named get or put.
  333. //
  334. // For right now, we will just skip to the closing right paren of the
  335. // property expression.
  336. //
  337. // FIXME: we should deal with __declspec(property) at some point because it
  338. // is used in the platform SDK headers for the Parallel Patterns Library
  339. // and ATL.
  340. BalancedDelimiterTracker T(*this, tok::l_paren);
  341. if (T.expectAndConsume(diag::err_expected_lparen_after,
  342. Ident->getNameStart(), tok::r_paren))
  343. return;
  344. T.skipToEnd();
  345. } else {
  346. // We don't recognize this as a valid declspec, but instead of creating the
  347. // attribute and allowing sema to warn about it, we will warn here instead.
  348. // This is because some attributes have multiple spellings, but we need to
  349. // disallow that for declspecs (such as align vs aligned). If we made the
  350. // attribute, we'd have to split the valid declspec spelling logic into
  351. // both locations.
  352. Diag(Loc, diag::warn_ms_declspec_unknown) << Ident;
  353. // If there's an open paren, we should eat the open and close parens under
  354. // the assumption that this unknown declspec has parameters.
  355. BalancedDelimiterTracker T(*this, tok::l_paren);
  356. if (!T.consumeOpen())
  357. T.skipToEnd();
  358. }
  359. }
  360. /// [MS] decl-specifier:
  361. /// __declspec ( extended-decl-modifier-seq )
  362. ///
  363. /// [MS] extended-decl-modifier-seq:
  364. /// extended-decl-modifier[opt]
  365. /// extended-decl-modifier extended-decl-modifier-seq
  366. void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &Attrs) {
  367. assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
  368. ConsumeToken();
  369. BalancedDelimiterTracker T(*this, tok::l_paren);
  370. if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
  371. tok::r_paren))
  372. return;
  373. // An empty declspec is perfectly legal and should not warn. Additionally,
  374. // you can specify multiple attributes per declspec.
  375. while (Tok.getKind() != tok::r_paren) {
  376. // We expect either a well-known identifier or a generic string. Anything
  377. // else is a malformed declspec.
  378. bool IsString = Tok.getKind() == tok::string_literal ? true : false;
  379. if (!IsString && Tok.getKind() != tok::identifier &&
  380. Tok.getKind() != tok::kw_restrict) {
  381. Diag(Tok, diag::err_ms_declspec_type);
  382. T.skipToEnd();
  383. return;
  384. }
  385. IdentifierInfo *AttrName;
  386. SourceLocation AttrNameLoc;
  387. if (IsString) {
  388. SmallString<8> StrBuffer;
  389. bool Invalid = false;
  390. StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
  391. if (Invalid) {
  392. T.skipToEnd();
  393. return;
  394. }
  395. AttrName = PP.getIdentifierInfo(Str);
  396. AttrNameLoc = ConsumeStringToken();
  397. } else {
  398. AttrName = Tok.getIdentifierInfo();
  399. AttrNameLoc = ConsumeToken();
  400. }
  401. if (IsString || IsSimpleMicrosoftDeclSpec(AttrName))
  402. // If we have a generic string, we will allow it because there is no
  403. // documented list of allowable string declspecs, but we know they exist
  404. // (for instance, SAL declspecs in older versions of MSVC).
  405. //
  406. // Alternatively, if the identifier is a simple one, then it requires no
  407. // arguments and can be turned into an attribute directly.
  408. Attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
  409. 0, 0, AttributeList::AS_Declspec);
  410. else
  411. ParseComplexMicrosoftDeclSpec(AttrName, AttrNameLoc, Attrs);
  412. }
  413. T.consumeClose();
  414. }
  415. void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
  416. // Treat these like attributes
  417. while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
  418. Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl) ||
  419. Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) ||
  420. Tok.is(tok::kw___ptr32) || Tok.is(tok::kw___unaligned)) {
  421. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  422. SourceLocation AttrNameLoc = ConsumeToken();
  423. attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
  424. SourceLocation(), 0, 0, AttributeList::AS_Keyword);
  425. }
  426. }
  427. void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
  428. // Treat these like attributes
  429. while (Tok.is(tok::kw___pascal)) {
  430. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  431. SourceLocation AttrNameLoc = ConsumeToken();
  432. attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
  433. SourceLocation(), 0, 0, AttributeList::AS_Keyword);
  434. }
  435. }
  436. void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
  437. // Treat these like attributes
  438. while (Tok.is(tok::kw___kernel)) {
  439. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  440. SourceLocation AttrNameLoc = ConsumeToken();
  441. attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
  442. SourceLocation(), 0, 0, AttributeList::AS_Keyword);
  443. }
  444. }
  445. void Parser::ParseOpenCLQualifiers(DeclSpec &DS) {
  446. // FIXME: The mapping from attribute spelling to semantics should be
  447. // performed in Sema, not here.
  448. SourceLocation Loc = Tok.getLocation();
  449. switch(Tok.getKind()) {
  450. // OpenCL qualifiers:
  451. case tok::kw___private:
  452. case tok::kw_private:
  453. DS.getAttributes().addNewInteger(
  454. Actions.getASTContext(),
  455. PP.getIdentifierInfo("address_space"), Loc, 0);
  456. break;
  457. case tok::kw___global:
  458. DS.getAttributes().addNewInteger(
  459. Actions.getASTContext(),
  460. PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global);
  461. break;
  462. case tok::kw___local:
  463. DS.getAttributes().addNewInteger(
  464. Actions.getASTContext(),
  465. PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local);
  466. break;
  467. case tok::kw___constant:
  468. DS.getAttributes().addNewInteger(
  469. Actions.getASTContext(),
  470. PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant);
  471. break;
  472. case tok::kw___read_only:
  473. DS.getAttributes().addNewInteger(
  474. Actions.getASTContext(),
  475. PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only);
  476. break;
  477. case tok::kw___write_only:
  478. DS.getAttributes().addNewInteger(
  479. Actions.getASTContext(),
  480. PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only);
  481. break;
  482. case tok::kw___read_write:
  483. DS.getAttributes().addNewInteger(
  484. Actions.getASTContext(),
  485. PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write);
  486. break;
  487. default: break;
  488. }
  489. }
  490. /// \brief Parse a version number.
  491. ///
  492. /// version:
  493. /// simple-integer
  494. /// simple-integer ',' simple-integer
  495. /// simple-integer ',' simple-integer ',' simple-integer
  496. VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
  497. Range = Tok.getLocation();
  498. if (!Tok.is(tok::numeric_constant)) {
  499. Diag(Tok, diag::err_expected_version);
  500. SkipUntil(tok::comma, tok::r_paren, true, true, true);
  501. return VersionTuple();
  502. }
  503. // Parse the major (and possibly minor and subminor) versions, which
  504. // are stored in the numeric constant. We utilize a quirk of the
  505. // lexer, which is that it handles something like 1.2.3 as a single
  506. // numeric constant, rather than two separate tokens.
  507. SmallString<512> Buffer;
  508. Buffer.resize(Tok.getLength()+1);
  509. const char *ThisTokBegin = &Buffer[0];
  510. // Get the spelling of the token, which eliminates trigraphs, etc.
  511. bool Invalid = false;
  512. unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
  513. if (Invalid)
  514. return VersionTuple();
  515. // Parse the major version.
  516. unsigned AfterMajor = 0;
  517. unsigned Major = 0;
  518. while (AfterMajor < ActualLength && isdigit(ThisTokBegin[AfterMajor])) {
  519. Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
  520. ++AfterMajor;
  521. }
  522. if (AfterMajor == 0) {
  523. Diag(Tok, diag::err_expected_version);
  524. SkipUntil(tok::comma, tok::r_paren, true, true, true);
  525. return VersionTuple();
  526. }
  527. if (AfterMajor == ActualLength) {
  528. ConsumeToken();
  529. // We only had a single version component.
  530. if (Major == 0) {
  531. Diag(Tok, diag::err_zero_version);
  532. return VersionTuple();
  533. }
  534. return VersionTuple(Major);
  535. }
  536. if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) {
  537. Diag(Tok, diag::err_expected_version);
  538. SkipUntil(tok::comma, tok::r_paren, true, true, true);
  539. return VersionTuple();
  540. }
  541. // Parse the minor version.
  542. unsigned AfterMinor = AfterMajor + 1;
  543. unsigned Minor = 0;
  544. while (AfterMinor < ActualLength && isdigit(ThisTokBegin[AfterMinor])) {
  545. Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
  546. ++AfterMinor;
  547. }
  548. if (AfterMinor == ActualLength) {
  549. ConsumeToken();
  550. // We had major.minor.
  551. if (Major == 0 && Minor == 0) {
  552. Diag(Tok, diag::err_zero_version);
  553. return VersionTuple();
  554. }
  555. return VersionTuple(Major, Minor);
  556. }
  557. // If what follows is not a '.', we have a problem.
  558. if (ThisTokBegin[AfterMinor] != '.') {
  559. Diag(Tok, diag::err_expected_version);
  560. SkipUntil(tok::comma, tok::r_paren, true, true, true);
  561. return VersionTuple();
  562. }
  563. // Parse the subminor version.
  564. unsigned AfterSubminor = AfterMinor + 1;
  565. unsigned Subminor = 0;
  566. while (AfterSubminor < ActualLength && isdigit(ThisTokBegin[AfterSubminor])) {
  567. Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
  568. ++AfterSubminor;
  569. }
  570. if (AfterSubminor != ActualLength) {
  571. Diag(Tok, diag::err_expected_version);
  572. SkipUntil(tok::comma, tok::r_paren, true, true, true);
  573. return VersionTuple();
  574. }
  575. ConsumeToken();
  576. return VersionTuple(Major, Minor, Subminor);
  577. }
  578. /// \brief Parse the contents of the "availability" attribute.
  579. ///
  580. /// availability-attribute:
  581. /// 'availability' '(' platform ',' version-arg-list, opt-message')'
  582. ///
  583. /// platform:
  584. /// identifier
  585. ///
  586. /// version-arg-list:
  587. /// version-arg
  588. /// version-arg ',' version-arg-list
  589. ///
  590. /// version-arg:
  591. /// 'introduced' '=' version
  592. /// 'deprecated' '=' version
  593. /// 'obsoleted' = version
  594. /// 'unavailable'
  595. /// opt-message:
  596. /// 'message' '=' <string>
  597. void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
  598. SourceLocation AvailabilityLoc,
  599. ParsedAttributes &attrs,
  600. SourceLocation *endLoc) {
  601. SourceLocation PlatformLoc;
  602. IdentifierInfo *Platform = 0;
  603. enum { Introduced, Deprecated, Obsoleted, Unknown };
  604. AvailabilityChange Changes[Unknown];
  605. ExprResult MessageExpr;
  606. // Opening '('.
  607. BalancedDelimiterTracker T(*this, tok::l_paren);
  608. if (T.consumeOpen()) {
  609. Diag(Tok, diag::err_expected_lparen);
  610. return;
  611. }
  612. // Parse the platform name,
  613. if (Tok.isNot(tok::identifier)) {
  614. Diag(Tok, diag::err_availability_expected_platform);
  615. SkipUntil(tok::r_paren);
  616. return;
  617. }
  618. Platform = Tok.getIdentifierInfo();
  619. PlatformLoc = ConsumeToken();
  620. // Parse the ',' following the platform name.
  621. if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren))
  622. return;
  623. // If we haven't grabbed the pointers for the identifiers
  624. // "introduced", "deprecated", and "obsoleted", do so now.
  625. if (!Ident_introduced) {
  626. Ident_introduced = PP.getIdentifierInfo("introduced");
  627. Ident_deprecated = PP.getIdentifierInfo("deprecated");
  628. Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
  629. Ident_unavailable = PP.getIdentifierInfo("unavailable");
  630. Ident_message = PP.getIdentifierInfo("message");
  631. }
  632. // Parse the set of introductions/deprecations/removals.
  633. SourceLocation UnavailableLoc;
  634. do {
  635. if (Tok.isNot(tok::identifier)) {
  636. Diag(Tok, diag::err_availability_expected_change);
  637. SkipUntil(tok::r_paren);
  638. return;
  639. }
  640. IdentifierInfo *Keyword = Tok.getIdentifierInfo();
  641. SourceLocation KeywordLoc = ConsumeToken();
  642. if (Keyword == Ident_unavailable) {
  643. if (UnavailableLoc.isValid()) {
  644. Diag(KeywordLoc, diag::err_availability_redundant)
  645. << Keyword << SourceRange(UnavailableLoc);
  646. }
  647. UnavailableLoc = KeywordLoc;
  648. if (Tok.isNot(tok::comma))
  649. break;
  650. ConsumeToken();
  651. continue;
  652. }
  653. if (Tok.isNot(tok::equal)) {
  654. Diag(Tok, diag::err_expected_equal_after)
  655. << Keyword;
  656. SkipUntil(tok::r_paren);
  657. return;
  658. }
  659. ConsumeToken();
  660. if (Keyword == Ident_message) {
  661. if (!isTokenStringLiteral()) {
  662. Diag(Tok, diag::err_expected_string_literal)
  663. << /*Source='availability attribute'*/2;
  664. SkipUntil(tok::r_paren);
  665. return;
  666. }
  667. MessageExpr = ParseStringLiteralExpression();
  668. break;
  669. }
  670. SourceRange VersionRange;
  671. VersionTuple Version = ParseVersionTuple(VersionRange);
  672. if (Version.empty()) {
  673. SkipUntil(tok::r_paren);
  674. return;
  675. }
  676. unsigned Index;
  677. if (Keyword == Ident_introduced)
  678. Index = Introduced;
  679. else if (Keyword == Ident_deprecated)
  680. Index = Deprecated;
  681. else if (Keyword == Ident_obsoleted)
  682. Index = Obsoleted;
  683. else
  684. Index = Unknown;
  685. if (Index < Unknown) {
  686. if (!Changes[Index].KeywordLoc.isInvalid()) {
  687. Diag(KeywordLoc, diag::err_availability_redundant)
  688. << Keyword
  689. << SourceRange(Changes[Index].KeywordLoc,
  690. Changes[Index].VersionRange.getEnd());
  691. }
  692. Changes[Index].KeywordLoc = KeywordLoc;
  693. Changes[Index].Version = Version;
  694. Changes[Index].VersionRange = VersionRange;
  695. } else {
  696. Diag(KeywordLoc, diag::err_availability_unknown_change)
  697. << Keyword << VersionRange;
  698. }
  699. if (Tok.isNot(tok::comma))
  700. break;
  701. ConsumeToken();
  702. } while (true);
  703. // Closing ')'.
  704. if (T.consumeClose())
  705. return;
  706. if (endLoc)
  707. *endLoc = T.getCloseLocation();
  708. // The 'unavailable' availability cannot be combined with any other
  709. // availability changes. Make sure that hasn't happened.
  710. if (UnavailableLoc.isValid()) {
  711. bool Complained = false;
  712. for (unsigned Index = Introduced; Index != Unknown; ++Index) {
  713. if (Changes[Index].KeywordLoc.isValid()) {
  714. if (!Complained) {
  715. Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
  716. << SourceRange(Changes[Index].KeywordLoc,
  717. Changes[Index].VersionRange.getEnd());
  718. Complained = true;
  719. }
  720. // Clear out the availability.
  721. Changes[Index] = AvailabilityChange();
  722. }
  723. }
  724. }
  725. // Record this attribute
  726. attrs.addNew(&Availability,
  727. SourceRange(AvailabilityLoc, T.getCloseLocation()),
  728. 0, AvailabilityLoc,
  729. Platform, PlatformLoc,
  730. Changes[Introduced],
  731. Changes[Deprecated],
  732. Changes[Obsoleted],
  733. UnavailableLoc, MessageExpr.take(),
  734. AttributeList::AS_GNU);
  735. }
  736. // Late Parsed Attributes:
  737. // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
  738. void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
  739. void Parser::LateParsedClass::ParseLexedAttributes() {
  740. Self->ParseLexedAttributes(*Class);
  741. }
  742. void Parser::LateParsedAttribute::ParseLexedAttributes() {
  743. Self->ParseLexedAttribute(*this, true, false);
  744. }
  745. /// Wrapper class which calls ParseLexedAttribute, after setting up the
  746. /// scope appropriately.
  747. void Parser::ParseLexedAttributes(ParsingClass &Class) {
  748. // Deal with templates
  749. // FIXME: Test cases to make sure this does the right thing for templates.
  750. bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
  751. ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
  752. HasTemplateScope);
  753. if (HasTemplateScope)
  754. Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
  755. // Set or update the scope flags.
  756. bool AlreadyHasClassScope = Class.TopLevelClass;
  757. unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
  758. ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
  759. ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
  760. // Enter the scope of nested classes
  761. if (!AlreadyHasClassScope)
  762. Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
  763. Class.TagOrTemplate);
  764. if (!Class.LateParsedDeclarations.empty()) {
  765. for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
  766. Class.LateParsedDeclarations[i]->ParseLexedAttributes();
  767. }
  768. }
  769. if (!AlreadyHasClassScope)
  770. Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
  771. Class.TagOrTemplate);
  772. }
  773. /// \brief Parse all attributes in LAs, and attach them to Decl D.
  774. void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
  775. bool EnterScope, bool OnDefinition) {
  776. assert(LAs.parseSoon() &&
  777. "Attribute list should be marked for immediate parsing.");
  778. for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
  779. if (D)
  780. LAs[i]->addDecl(D);
  781. ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
  782. delete LAs[i];
  783. }
  784. LAs.clear();
  785. }
  786. /// \brief Finish parsing an attribute for which parsing was delayed.
  787. /// This will be called at the end of parsing a class declaration
  788. /// for each LateParsedAttribute. We consume the saved tokens and
  789. /// create an attribute with the arguments filled in. We add this
  790. /// to the Attribute list for the decl.
  791. void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
  792. bool EnterScope, bool OnDefinition) {
  793. // Save the current token position.
  794. SourceLocation OrigLoc = Tok.getLocation();
  795. // Append the current token at the end of the new token stream so that it
  796. // doesn't get lost.
  797. LA.Toks.push_back(Tok);
  798. PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false);
  799. // Consume the previously pushed token.
  800. ConsumeAnyToken();
  801. if (OnDefinition && !IsThreadSafetyAttribute(LA.AttrName.getName())) {
  802. // FIXME: Do not warn on C++11 attributes, once we start supporting
  803. // them here.
  804. Diag(Tok, diag::warn_attribute_on_function_definition)
  805. << LA.AttrName.getName();
  806. }
  807. ParsedAttributes Attrs(AttrFactory);
  808. SourceLocation endLoc;
  809. if (LA.Decls.size() > 0) {
  810. Decl *D = LA.Decls[0];
  811. NamedDecl *ND = dyn_cast<NamedDecl>(D);
  812. RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
  813. // Allow 'this' within late-parsed attributes.
  814. Sema::CXXThisScopeRAII ThisScope(Actions, RD,
  815. /*TypeQuals=*/0,
  816. ND && RD && ND->isCXXInstanceMember());
  817. if (LA.Decls.size() == 1) {
  818. // If the Decl is templatized, add template parameters to scope.
  819. bool HasTemplateScope = EnterScope && D->isTemplateDecl();
  820. ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
  821. if (HasTemplateScope)
  822. Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
  823. // If the Decl is on a function, add function parameters to the scope.
  824. bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
  825. ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope);
  826. if (HasFunScope)
  827. Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
  828. ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
  829. 0, SourceLocation(), AttributeList::AS_GNU);
  830. if (HasFunScope) {
  831. Actions.ActOnExitFunctionContext();
  832. FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
  833. }
  834. if (HasTemplateScope) {
  835. TempScope.Exit();
  836. }
  837. } else {
  838. // If there are multiple decls, then the decl cannot be within the
  839. // function scope.
  840. ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
  841. 0, SourceLocation(), AttributeList::AS_GNU);
  842. }
  843. } else {
  844. Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
  845. }
  846. for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) {
  847. Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
  848. }
  849. if (Tok.getLocation() != OrigLoc) {
  850. // Due to a parsing error, we either went over the cached tokens or
  851. // there are still cached tokens left, so we skip the leftover tokens.
  852. // Since this is an uncommon situation that should be avoided, use the
  853. // expensive isBeforeInTranslationUnit call.
  854. if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
  855. OrigLoc))
  856. while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
  857. ConsumeAnyToken();
  858. }
  859. }
  860. /// \brief Wrapper around a case statement checking if AttrName is
  861. /// one of the thread safety attributes
  862. bool Parser::IsThreadSafetyAttribute(StringRef AttrName) {
  863. return llvm::StringSwitch<bool>(AttrName)
  864. .Case("guarded_by", true)
  865. .Case("guarded_var", true)
  866. .Case("pt_guarded_by", true)
  867. .Case("pt_guarded_var", true)
  868. .Case("lockable", true)
  869. .Case("scoped_lockable", true)
  870. .Case("no_thread_safety_analysis", true)
  871. .Case("acquired_after", true)
  872. .Case("acquired_before", true)
  873. .Case("exclusive_lock_function", true)
  874. .Case("shared_lock_function", true)
  875. .Case("exclusive_trylock_function", true)
  876. .Case("shared_trylock_function", true)
  877. .Case("unlock_function", true)
  878. .Case("lock_returned", true)
  879. .Case("locks_excluded", true)
  880. .Case("exclusive_locks_required", true)
  881. .Case("shared_locks_required", true)
  882. .Default(false);
  883. }
  884. /// \brief Parse the contents of thread safety attributes. These
  885. /// should always be parsed as an expression list.
  886. ///
  887. /// We need to special case the parsing due to the fact that if the first token
  888. /// of the first argument is an identifier, the main parse loop will store
  889. /// that token as a "parameter" and the rest of
  890. /// the arguments will be added to a list of "arguments". However,
  891. /// subsequent tokens in the first argument are lost. We instead parse each
  892. /// argument as an expression and add all arguments to the list of "arguments".
  893. /// In future, we will take advantage of this special case to also
  894. /// deal with some argument scoping issues here (for example, referring to a
  895. /// function parameter in the attribute on that function).
  896. void Parser::ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
  897. SourceLocation AttrNameLoc,
  898. ParsedAttributes &Attrs,
  899. SourceLocation *EndLoc) {
  900. assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
  901. BalancedDelimiterTracker T(*this, tok::l_paren);
  902. T.consumeOpen();
  903. ExprVector ArgExprs;
  904. bool ArgExprsOk = true;
  905. // now parse the list of expressions
  906. while (Tok.isNot(tok::r_paren)) {
  907. ExprResult ArgExpr(ParseAssignmentExpression());
  908. if (ArgExpr.isInvalid()) {
  909. ArgExprsOk = false;
  910. T.consumeClose();
  911. break;
  912. } else {
  913. ArgExprs.push_back(ArgExpr.release());
  914. }
  915. if (Tok.isNot(tok::comma))
  916. break;
  917. ConsumeToken(); // Eat the comma, move to the next argument
  918. }
  919. // Match the ')'.
  920. if (ArgExprsOk && !T.consumeClose()) {
  921. Attrs.addNew(&AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
  922. ArgExprs.data(), ArgExprs.size(), AttributeList::AS_GNU);
  923. }
  924. if (EndLoc)
  925. *EndLoc = T.getCloseLocation();
  926. }
  927. void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
  928. SourceLocation AttrNameLoc,
  929. ParsedAttributes &Attrs,
  930. SourceLocation *EndLoc) {
  931. assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
  932. BalancedDelimiterTracker T(*this, tok::l_paren);
  933. T.consumeOpen();
  934. if (Tok.isNot(tok::identifier)) {
  935. Diag(Tok, diag::err_expected_ident);
  936. T.skipToEnd();
  937. return;
  938. }
  939. IdentifierInfo *ArgumentKind = Tok.getIdentifierInfo();
  940. SourceLocation ArgumentKindLoc = ConsumeToken();
  941. if (Tok.isNot(tok::comma)) {
  942. Diag(Tok, diag::err_expected_comma);
  943. T.skipToEnd();
  944. return;
  945. }
  946. ConsumeToken();
  947. SourceRange MatchingCTypeRange;
  948. TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
  949. if (MatchingCType.isInvalid()) {
  950. T.skipToEnd();
  951. return;
  952. }
  953. bool LayoutCompatible = false;
  954. bool MustBeNull = false;
  955. while (Tok.is(tok::comma)) {
  956. ConsumeToken();
  957. if (Tok.isNot(tok::identifier)) {
  958. Diag(Tok, diag::err_expected_ident);
  959. T.skipToEnd();
  960. return;
  961. }
  962. IdentifierInfo *Flag = Tok.getIdentifierInfo();
  963. if (Flag->isStr("layout_compatible"))
  964. LayoutCompatible = true;
  965. else if (Flag->isStr("must_be_null"))
  966. MustBeNull = true;
  967. else {
  968. Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
  969. T.skipToEnd();
  970. return;
  971. }
  972. ConsumeToken(); // consume flag
  973. }
  974. if (!T.consumeClose()) {
  975. Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, 0, AttrNameLoc,
  976. ArgumentKind, ArgumentKindLoc,
  977. MatchingCType.release(), LayoutCompatible,
  978. MustBeNull, AttributeList::AS_GNU);
  979. }
  980. if (EndLoc)
  981. *EndLoc = T.getCloseLocation();
  982. }
  983. /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
  984. /// of a C++11 attribute-specifier in a location where an attribute is not
  985. /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
  986. /// situation.
  987. ///
  988. /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
  989. /// this doesn't appear to actually be an attribute-specifier, and the caller
  990. /// should try to parse it.
  991. bool Parser::DiagnoseProhibitedCXX11Attribute() {
  992. assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
  993. switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
  994. case CAK_NotAttributeSpecifier:
  995. // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
  996. return false;
  997. case CAK_InvalidAttributeSpecifier:
  998. Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
  999. return false;
  1000. case CAK_AttributeSpecifier:
  1001. // Parse and discard the attributes.
  1002. SourceLocation BeginLoc = ConsumeBracket();
  1003. ConsumeBracket();
  1004. SkipUntil(tok::r_square, /*StopAtSemi*/ false);
  1005. assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
  1006. SourceLocation EndLoc = ConsumeBracket();
  1007. Diag(BeginLoc, diag::err_attributes_not_allowed)
  1008. << SourceRange(BeginLoc, EndLoc);
  1009. return true;
  1010. }
  1011. llvm_unreachable("All cases handled above.");
  1012. }
  1013. void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
  1014. Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
  1015. << attrs.Range;
  1016. }
  1017. void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs) {
  1018. AttributeList *AttrList = attrs.getList();
  1019. while (AttrList) {
  1020. if (AttrList->isCXX11Attribute()) {
  1021. Diag(AttrList->getLoc(), diag::err_attribute_not_type_attr)
  1022. << AttrList->getName();
  1023. AttrList->setInvalid();
  1024. }
  1025. AttrList = AttrList->getNext();
  1026. }
  1027. }
  1028. /// ParseDeclaration - Parse a full 'declaration', which consists of
  1029. /// declaration-specifiers, some number of declarators, and a semicolon.
  1030. /// 'Context' should be a Declarator::TheContext value. This returns the
  1031. /// location of the semicolon in DeclEnd.
  1032. ///
  1033. /// declaration: [C99 6.7]
  1034. /// block-declaration ->
  1035. /// simple-declaration
  1036. /// others [FIXME]
  1037. /// [C++] template-declaration
  1038. /// [C++] namespace-definition
  1039. /// [C++] using-directive
  1040. /// [C++] using-declaration
  1041. /// [C++11/C11] static_assert-declaration
  1042. /// others... [FIXME]
  1043. ///
  1044. Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
  1045. unsigned Context,
  1046. SourceLocation &DeclEnd,
  1047. ParsedAttributesWithRange &attrs) {
  1048. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  1049. // Must temporarily exit the objective-c container scope for
  1050. // parsing c none objective-c decls.
  1051. ObjCDeclContextSwitch ObjCDC(*this);
  1052. Decl *SingleDecl = 0;
  1053. Decl *OwnedType = 0;
  1054. switch (Tok.getKind()) {
  1055. case tok::kw_template:
  1056. case tok::kw_export:
  1057. ProhibitAttributes(attrs);
  1058. SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
  1059. break;
  1060. case tok::kw_inline:
  1061. // Could be the start of an inline namespace. Allowed as an ext in C++03.
  1062. if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
  1063. ProhibitAttributes(attrs);
  1064. SourceLocation InlineLoc = ConsumeToken();
  1065. SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
  1066. break;
  1067. }
  1068. return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs,
  1069. true);
  1070. case tok::kw_namespace:
  1071. ProhibitAttributes(attrs);
  1072. SingleDecl = ParseNamespace(Context, DeclEnd);
  1073. break;
  1074. case tok::kw_using:
  1075. SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
  1076. DeclEnd, attrs, &OwnedType);
  1077. break;
  1078. case tok::kw_static_assert:
  1079. case tok::kw__Static_assert:
  1080. ProhibitAttributes(attrs);
  1081. SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
  1082. break;
  1083. default:
  1084. return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true);
  1085. }
  1086. // This routine returns a DeclGroup, if the thing we parsed only contains a
  1087. // single decl, convert it now. Alias declarations can also declare a type;
  1088. // include that too if it is present.
  1089. return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
  1090. }
  1091. /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
  1092. /// declaration-specifiers init-declarator-list[opt] ';'
  1093. /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
  1094. /// init-declarator-list ';'
  1095. ///[C90/C++]init-declarator-list ';' [TODO]
  1096. /// [OMP] threadprivate-directive [TODO]
  1097. ///
  1098. /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
  1099. /// attribute-specifier-seq[opt] type-specifier-seq declarator
  1100. ///
  1101. /// If RequireSemi is false, this does not check for a ';' at the end of the
  1102. /// declaration. If it is true, it checks for and eats it.
  1103. ///
  1104. /// If FRI is non-null, we might be parsing a for-range-declaration instead
  1105. /// of a simple-declaration. If we find that we are, we also parse the
  1106. /// for-range-initializer, and place it here.
  1107. Parser::DeclGroupPtrTy
  1108. Parser::ParseSimpleDeclaration(StmtVector &Stmts, unsigned Context,
  1109. SourceLocation &DeclEnd,
  1110. ParsedAttributesWithRange &attrs,
  1111. bool RequireSemi, ForRangeInit *FRI) {
  1112. // Parse the common declaration-specifiers piece.
  1113. ParsingDeclSpec DS(*this);
  1114. DS.takeAttributesFrom(attrs);
  1115. ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
  1116. getDeclSpecContextFromDeclaratorContext(Context));
  1117. // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
  1118. // declaration-specifiers init-declarator-list[opt] ';'
  1119. if (Tok.is(tok::semi)) {
  1120. DeclEnd = Tok.getLocation();
  1121. if (RequireSemi) ConsumeToken();
  1122. Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
  1123. DS);
  1124. DS.complete(TheDecl);
  1125. return Actions.ConvertDeclToDeclGroup(TheDecl);
  1126. }
  1127. return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI);
  1128. }
  1129. /// Returns true if this might be the start of a declarator, or a common typo
  1130. /// for a declarator.
  1131. bool Parser::MightBeDeclarator(unsigned Context) {
  1132. switch (Tok.getKind()) {
  1133. case tok::annot_cxxscope:
  1134. case tok::annot_template_id:
  1135. case tok::caret:
  1136. case tok::code_completion:
  1137. case tok::coloncolon:
  1138. case tok::ellipsis:
  1139. case tok::kw___attribute:
  1140. case tok::kw_operator:
  1141. case tok::l_paren:
  1142. case tok::star:
  1143. return true;
  1144. case tok::amp:
  1145. case tok::ampamp:
  1146. return getLangOpts().CPlusPlus;
  1147. case tok::l_square: // Might be an attribute on an unnamed bit-field.
  1148. return Context == Declarator::MemberContext && getLangOpts().CPlusPlus11 &&
  1149. NextToken().is(tok::l_square);
  1150. case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
  1151. return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
  1152. case tok::identifier:
  1153. switch (NextToken().getKind()) {
  1154. case tok::code_completion:
  1155. case tok::coloncolon:
  1156. case tok::comma:
  1157. case tok::equal:
  1158. case tok::equalequal: // Might be a typo for '='.
  1159. case tok::kw_alignas:
  1160. case tok::kw_asm:
  1161. case tok::kw___attribute:
  1162. case tok::l_brace:
  1163. case tok::l_paren:
  1164. case tok::l_square:
  1165. case tok::less:
  1166. case tok::r_brace:
  1167. case tok::r_paren:
  1168. case tok::r_square:
  1169. case tok::semi:
  1170. return true;
  1171. case tok::colon:
  1172. // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
  1173. // and in block scope it's probably a label. Inside a class definition,
  1174. // this is a bit-field.
  1175. return Context == Declarator::MemberContext ||
  1176. (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
  1177. case tok::identifier: // Possible virt-specifier.
  1178. return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
  1179. default:
  1180. return false;
  1181. }
  1182. default:
  1183. return false;
  1184. }
  1185. }
  1186. /// Skip until we reach something which seems like a sensible place to pick
  1187. /// up parsing after a malformed declaration. This will sometimes stop sooner
  1188. /// than SkipUntil(tok::r_brace) would, but will never stop later.
  1189. void Parser::SkipMalformedDecl() {
  1190. while (true) {
  1191. switch (Tok.getKind()) {
  1192. case tok::l_brace:
  1193. // Skip until matching }, then stop. We've probably skipped over
  1194. // a malformed class or function definition or similar.
  1195. ConsumeBrace();
  1196. SkipUntil(tok::r_brace, /*StopAtSemi*/false);
  1197. if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try)) {
  1198. // This declaration isn't over yet. Keep skipping.
  1199. continue;
  1200. }
  1201. if (Tok.is(tok::semi))
  1202. ConsumeToken();
  1203. return;
  1204. case tok::l_square:
  1205. ConsumeBracket();
  1206. SkipUntil(tok::r_square, /*StopAtSemi*/false);
  1207. continue;
  1208. case tok::l_paren:
  1209. ConsumeParen();
  1210. SkipUntil(tok::r_paren, /*StopAtSemi*/false);
  1211. continue;
  1212. case tok::r_brace:
  1213. return;
  1214. case tok::semi:
  1215. ConsumeToken();
  1216. return;
  1217. case tok::kw_inline:
  1218. // 'inline namespace' at the start of a line is almost certainly
  1219. // a good place to pick back up parsing, except in an Objective-C
  1220. // @interface context.
  1221. if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
  1222. (!ParsingInObjCContainer || CurParsedObjCImpl))
  1223. return;
  1224. break;
  1225. case tok::kw_namespace:
  1226. // 'namespace' at the start of a line is almost certainly a good
  1227. // place to pick back up parsing, except in an Objective-C
  1228. // @interface context.
  1229. if (Tok.isAtStartOfLine() &&
  1230. (!ParsingInObjCContainer || CurParsedObjCImpl))
  1231. return;
  1232. break;
  1233. case tok::at:
  1234. // @end is very much like } in Objective-C contexts.
  1235. if (NextToken().isObjCAtKeyword(tok::objc_end) &&
  1236. ParsingInObjCContainer)
  1237. return;
  1238. break;
  1239. case tok::minus:
  1240. case tok::plus:
  1241. // - and + probably start new method declarations in Objective-C contexts.
  1242. if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
  1243. return;
  1244. break;
  1245. case tok::eof:
  1246. return;
  1247. default:
  1248. break;
  1249. }
  1250. ConsumeAnyToken();
  1251. }
  1252. }
  1253. /// ParseDeclGroup - Having concluded that this is either a function
  1254. /// definition or a group of object declarations, actually parse the
  1255. /// result.
  1256. Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
  1257. unsigned Context,
  1258. bool AllowFunctionDefinitions,
  1259. SourceLocation *DeclEnd,
  1260. ForRangeInit *FRI) {
  1261. // Parse the first declarator.
  1262. ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
  1263. ParseDeclarator(D);
  1264. // Bail out if the first declarator didn't seem well-formed.
  1265. if (!D.hasName() && !D.mayOmitIdentifier()) {
  1266. SkipMalformedDecl();
  1267. return DeclGroupPtrTy();
  1268. }
  1269. // Save late-parsed attributes for now; they need to be parsed in the
  1270. // appropriate function scope after the function Decl has been constructed.
  1271. // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
  1272. LateParsedAttrList LateParsedAttrs(true);
  1273. if (D.isFunctionDeclarator())
  1274. MaybeParseGNUAttributes(D, &LateParsedAttrs);
  1275. // Check to see if we have a function *definition* which must have a body.
  1276. if (AllowFunctionDefinitions && D.isFunctionDeclarator() &&
  1277. // Look at the next token to make sure that this isn't a function
  1278. // declaration. We have to check this because __attribute__ might be the
  1279. // start of a function definition in GCC-extended K&R C.
  1280. !isDeclarationAfterDeclarator()) {
  1281. if (isStartOfFunctionDefinition(D)) {
  1282. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
  1283. Diag(Tok, diag::err_function_declared_typedef);
  1284. // Recover by treating the 'typedef' as spurious.
  1285. DS.ClearStorageClassSpecs();
  1286. }
  1287. Decl *TheDecl =
  1288. ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
  1289. return Actions.ConvertDeclToDeclGroup(TheDecl);
  1290. }
  1291. if (isDeclarationSpecifier()) {
  1292. // If there is an invalid declaration specifier right after the function
  1293. // prototype, then we must be in a missing semicolon case where this isn't
  1294. // actually a body. Just fall through into the code that handles it as a
  1295. // prototype, and let the top-level code handle the erroneous declspec
  1296. // where it would otherwise expect a comma or semicolon.
  1297. } else {
  1298. Diag(Tok, diag::err_expected_fn_body);
  1299. SkipUntil(tok::semi);
  1300. return DeclGroupPtrTy();
  1301. }
  1302. }
  1303. if (ParseAsmAttributesAfterDeclarator(D))
  1304. return DeclGroupPtrTy();
  1305. // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
  1306. // must parse and analyze the for-range-initializer before the declaration is
  1307. // analyzed.
  1308. if (FRI && Tok.is(tok::colon)) {
  1309. FRI->ColonLoc = ConsumeToken();
  1310. if (Tok.is(tok::l_brace))
  1311. FRI->RangeExpr = ParseBraceInitializer();
  1312. else
  1313. FRI->RangeExpr = ParseExpression();
  1314. Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
  1315. Actions.ActOnCXXForRangeDecl(ThisDecl);
  1316. Actions.FinalizeDeclaration(ThisDecl);
  1317. D.complete(ThisDecl);
  1318. return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, &ThisDecl, 1);
  1319. }
  1320. SmallVector<Decl *, 8> DeclsInGroup;
  1321. Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D);
  1322. if (LateParsedAttrs.size() > 0)
  1323. ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
  1324. D.complete(FirstDecl);
  1325. if (FirstDecl)
  1326. DeclsInGroup.push_back(FirstDecl);
  1327. bool ExpectSemi = Context != Declarator::ForContext;
  1328. // If we don't have a comma, it is either the end of the list (a ';') or an
  1329. // error, bail out.
  1330. while (Tok.is(tok::comma)) {
  1331. SourceLocation CommaLoc = ConsumeToken();
  1332. if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
  1333. // This comma was followed by a line-break and something which can't be
  1334. // the start of a declarator. The comma was probably a typo for a
  1335. // semicolon.
  1336. Diag(CommaLoc, diag::err_expected_semi_declaration)
  1337. << FixItHint::CreateReplacement(CommaLoc, ";");
  1338. ExpectSemi = false;
  1339. break;
  1340. }
  1341. // Parse the next declarator.
  1342. D.clear();
  1343. D.setCommaLoc(CommaLoc);
  1344. // Accept attributes in an init-declarator. In the first declarator in a
  1345. // declaration, these would be part of the declspec. In subsequent
  1346. // declarators, they become part of the declarator itself, so that they
  1347. // don't apply to declarators after *this* one. Examples:
  1348. // short __attribute__((common)) var; -> declspec
  1349. // short var __attribute__((common)); -> declarator
  1350. // short x, __attribute__((common)) var; -> declarator
  1351. MaybeParseGNUAttributes(D);
  1352. ParseDeclarator(D);
  1353. if (!D.isInvalidType()) {
  1354. Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
  1355. D.complete(ThisDecl);
  1356. if (ThisDecl)
  1357. DeclsInGroup.push_back(ThisDecl);
  1358. }
  1359. }
  1360. if (DeclEnd)
  1361. *DeclEnd = Tok.getLocation();
  1362. if (ExpectSemi &&
  1363. ExpectAndConsumeSemi(Context == Declarator::FileContext
  1364. ? diag::err_invalid_token_after_toplevel_declarator
  1365. : diag::err_expected_semi_declaration)) {
  1366. // Okay, there was no semicolon and one was expected. If we see a
  1367. // declaration specifier, just assume it was missing and continue parsing.
  1368. // Otherwise things are very confused and we skip to recover.
  1369. if (!isDeclarationSpecifier()) {
  1370. SkipUntil(tok::r_brace, true, true);
  1371. if (Tok.is(tok::semi))
  1372. ConsumeToken();
  1373. }
  1374. }
  1375. return Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
  1376. DeclsInGroup.data(),
  1377. DeclsInGroup.size());
  1378. }
  1379. /// Parse an optional simple-asm-expr and attributes, and attach them to a
  1380. /// declarator. Returns true on an error.
  1381. bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
  1382. // If a simple-asm-expr is present, parse it.
  1383. if (Tok.is(tok::kw_asm)) {
  1384. SourceLocation Loc;
  1385. ExprResult AsmLabel(ParseSimpleAsm(&Loc));
  1386. if (AsmLabel.isInvalid()) {
  1387. SkipUntil(tok::semi, true, true);
  1388. return true;
  1389. }
  1390. D.setAsmLabel(AsmLabel.release());
  1391. D.SetRangeEnd(Loc);
  1392. }
  1393. MaybeParseGNUAttributes(D);
  1394. return false;
  1395. }
  1396. /// \brief Parse 'declaration' after parsing 'declaration-specifiers
  1397. /// declarator'. This method parses the remainder of the declaration
  1398. /// (including any attributes or initializer, among other things) and
  1399. /// finalizes the declaration.
  1400. ///
  1401. /// init-declarator: [C99 6.7]
  1402. /// declarator
  1403. /// declarator '=' initializer
  1404. /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
  1405. /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
  1406. /// [C++] declarator initializer[opt]
  1407. ///
  1408. /// [C++] initializer:
  1409. /// [C++] '=' initializer-clause
  1410. /// [C++] '(' expression-list ')'
  1411. /// [C++0x] '=' 'default' [TODO]
  1412. /// [C++0x] '=' 'delete'
  1413. /// [C++0x] braced-init-list
  1414. ///
  1415. /// According to the standard grammar, =default and =delete are function
  1416. /// definitions, but that definitely doesn't fit with the parser here.
  1417. ///
  1418. Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D,
  1419. const ParsedTemplateInfo &TemplateInfo) {
  1420. if (ParseAsmAttributesAfterDeclarator(D))
  1421. return 0;
  1422. return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
  1423. }
  1424. Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
  1425. const ParsedTemplateInfo &TemplateInfo) {
  1426. // Inform the current actions module that we just parsed this declarator.
  1427. Decl *ThisDecl = 0;
  1428. switch (TemplateInfo.Kind) {
  1429. case ParsedTemplateInfo::NonTemplate:
  1430. ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
  1431. break;
  1432. case ParsedTemplateInfo::Template:
  1433. case ParsedTemplateInfo::ExplicitSpecialization:
  1434. ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
  1435. *TemplateInfo.TemplateParams,
  1436. D);
  1437. break;
  1438. case ParsedTemplateInfo::ExplicitInstantiation: {
  1439. DeclResult ThisRes
  1440. = Actions.ActOnExplicitInstantiation(getCurScope(),
  1441. TemplateInfo.ExternLoc,
  1442. TemplateInfo.TemplateLoc,
  1443. D);
  1444. if (ThisRes.isInvalid()) {
  1445. SkipUntil(tok::semi, true, true);
  1446. return 0;
  1447. }
  1448. ThisDecl = ThisRes.get();
  1449. break;
  1450. }
  1451. }
  1452. bool TypeContainsAuto =
  1453. D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
  1454. // Parse declarator '=' initializer.
  1455. // If a '==' or '+=' is found, suggest a fixit to '='.
  1456. if (isTokenEqualOrEqualTypo()) {
  1457. ConsumeToken();
  1458. if (Tok.is(tok::kw_delete)) {
  1459. if (D.isFunctionDeclarator())
  1460. Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
  1461. << 1 /* delete */;
  1462. else
  1463. Diag(ConsumeToken(), diag::err_deleted_non_function);
  1464. } else if (Tok.is(tok::kw_default)) {
  1465. if (D.isFunctionDeclarator())
  1466. Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
  1467. << 0 /* default */;
  1468. else
  1469. Diag(ConsumeToken(), diag::err_default_special_members);
  1470. } else {
  1471. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  1472. EnterScope(0);
  1473. Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
  1474. }
  1475. if (Tok.is(tok::code_completion)) {
  1476. Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
  1477. Actions.FinalizeDeclaration(ThisDecl);
  1478. cutOffParsing();
  1479. return 0;
  1480. }
  1481. ExprResult Init(ParseInitializer());
  1482. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  1483. Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
  1484. ExitScope();
  1485. }
  1486. if (Init.isInvalid()) {
  1487. SkipUntil(tok::comma, true, true);
  1488. Actions.ActOnInitializerError(ThisDecl);
  1489. } else
  1490. Actions.AddInitializerToDecl(ThisDecl, Init.take(),
  1491. /*DirectInit=*/false, TypeContainsAuto);
  1492. }
  1493. } else if (Tok.is(tok::l_paren)) {
  1494. // Parse C++ direct initializer: '(' expression-list ')'
  1495. BalancedDelimiterTracker T(*this, tok::l_paren);
  1496. T.consumeOpen();
  1497. ExprVector Exprs;
  1498. CommaLocsTy CommaLocs;
  1499. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  1500. EnterScope(0);
  1501. Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
  1502. }
  1503. if (ParseExpressionList(Exprs, CommaLocs)) {
  1504. Actions.ActOnInitializerError(ThisDecl);
  1505. SkipUntil(tok::r_paren);
  1506. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  1507. Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
  1508. ExitScope();
  1509. }
  1510. } else {
  1511. // Match the ')'.
  1512. T.consumeClose();
  1513. assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
  1514. "Unexpected number of commas!");
  1515. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  1516. Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
  1517. ExitScope();
  1518. }
  1519. ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
  1520. T.getCloseLocation(),
  1521. Exprs);
  1522. Actions.AddInitializerToDecl(ThisDecl, Initializer.take(),
  1523. /*DirectInit=*/true, TypeContainsAuto);
  1524. }
  1525. } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
  1526. (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
  1527. // Parse C++0x braced-init-list.
  1528. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  1529. if (D.getCXXScopeSpec().isSet()) {
  1530. EnterScope(0);
  1531. Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
  1532. }
  1533. ExprResult Init(ParseBraceInitializer());
  1534. if (D.getCXXScopeSpec().isSet()) {
  1535. Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
  1536. ExitScope();
  1537. }
  1538. if (Init.isInvalid()) {
  1539. Actions.ActOnInitializerError(ThisDecl);
  1540. } else
  1541. Actions.AddInitializerToDecl(ThisDecl, Init.take(),
  1542. /*DirectInit=*/true, TypeContainsAuto);
  1543. } else {
  1544. Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
  1545. }
  1546. Actions.FinalizeDeclaration(ThisDecl);
  1547. return ThisDecl;
  1548. }
  1549. /// ParseSpecifierQualifierList
  1550. /// specifier-qualifier-list:
  1551. /// type-specifier specifier-qualifier-list[opt]
  1552. /// type-qualifier specifier-qualifier-list[opt]
  1553. /// [GNU] attributes specifier-qualifier-list[opt]
  1554. ///
  1555. void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
  1556. DeclSpecContext DSC) {
  1557. /// specifier-qualifier-list is a subset of declaration-specifiers. Just
  1558. /// parse declaration-specifiers and complain about extra stuff.
  1559. /// TODO: diagnose attribute-specifiers and alignment-specifiers.
  1560. ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
  1561. // Validate declspec for type-name.
  1562. unsigned Specs = DS.getParsedSpecifiers();
  1563. if ((DSC == DSC_type_specifier || DSC == DSC_trailing) &&
  1564. !DS.hasTypeSpecifier()) {
  1565. Diag(Tok, diag::err_expected_type);
  1566. DS.SetTypeSpecError();
  1567. } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
  1568. !DS.hasAttributes()) {
  1569. Diag(Tok, diag::err_typename_requires_specqual);
  1570. if (!DS.hasTypeSpecifier())
  1571. DS.SetTypeSpecError();
  1572. }
  1573. // Issue diagnostic and remove storage class if present.
  1574. if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
  1575. if (DS.getStorageClassSpecLoc().isValid())
  1576. Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
  1577. else
  1578. Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
  1579. DS.ClearStorageClassSpecs();
  1580. }
  1581. // Issue diagnostic and remove function specfier if present.
  1582. if (Specs & DeclSpec::PQ_FunctionSpecifier) {
  1583. if (DS.isInlineSpecified())
  1584. Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
  1585. if (DS.isVirtualSpecified())
  1586. Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
  1587. if (DS.isExplicitSpecified())
  1588. Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
  1589. DS.ClearFunctionSpecs();
  1590. }
  1591. // Issue diagnostic and remove constexpr specfier if present.
  1592. if (DS.isConstexprSpecified()) {
  1593. Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
  1594. DS.ClearConstexprSpec();
  1595. }
  1596. }
  1597. /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
  1598. /// specified token is valid after the identifier in a declarator which
  1599. /// immediately follows the declspec. For example, these things are valid:
  1600. ///
  1601. /// int x [ 4]; // direct-declarator
  1602. /// int x ( int y); // direct-declarator
  1603. /// int(int x ) // direct-declarator
  1604. /// int x ; // simple-declaration
  1605. /// int x = 17; // init-declarator-list
  1606. /// int x , y; // init-declarator-list
  1607. /// int x __asm__ ("foo"); // init-declarator-list
  1608. /// int x : 4; // struct-declarator
  1609. /// int x { 5}; // C++'0x unified initializers
  1610. ///
  1611. /// This is not, because 'x' does not immediately follow the declspec (though
  1612. /// ')' happens to be valid anyway).
  1613. /// int (x)
  1614. ///
  1615. static bool isValidAfterIdentifierInDeclarator(const Token &T) {
  1616. return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
  1617. T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
  1618. T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
  1619. }
  1620. /// ParseImplicitInt - This method is called when we have an non-typename
  1621. /// identifier in a declspec (which normally terminates the decl spec) when
  1622. /// the declspec has no type specifier. In this case, the declspec is either
  1623. /// malformed or is "implicit int" (in K&R and C89).
  1624. ///
  1625. /// This method handles diagnosing this prettily and returns false if the
  1626. /// declspec is done being processed. If it recovers and thinks there may be
  1627. /// other pieces of declspec after it, it returns true.
  1628. ///
  1629. bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
  1630. const ParsedTemplateInfo &TemplateInfo,
  1631. AccessSpecifier AS, DeclSpecContext DSC,
  1632. ParsedAttributesWithRange &Attrs) {
  1633. assert(Tok.is(tok::identifier) && "should have identifier");
  1634. SourceLocation Loc = Tok.getLocation();
  1635. // If we see an identifier that is not a type name, we normally would
  1636. // parse it as the identifer being declared. However, when a typename
  1637. // is typo'd or the definition is not included, this will incorrectly
  1638. // parse the typename as the identifier name and fall over misparsing
  1639. // later parts of the diagnostic.
  1640. //
  1641. // As such, we try to do some look-ahead in cases where this would
  1642. // otherwise be an "implicit-int" case to see if this is invalid. For
  1643. // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
  1644. // an identifier with implicit int, we'd get a parse error because the
  1645. // next token is obviously invalid for a type. Parse these as a case
  1646. // with an invalid type specifier.
  1647. assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
  1648. // Since we know that this either implicit int (which is rare) or an
  1649. // error, do lookahead to try to do better recovery. This never applies
  1650. // within a type specifier. Outside of C++, we allow this even if the
  1651. // language doesn't "officially" support implicit int -- we support
  1652. // implicit int as an extension in C99 and C11. Allegedly, MS also
  1653. // supports implicit int in C++ mode.
  1654. if (DSC != DSC_type_specifier && DSC != DSC_trailing &&
  1655. (!getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt) &&
  1656. isValidAfterIdentifierInDeclarator(NextToken())) {
  1657. // If this token is valid for implicit int, e.g. "static x = 4", then
  1658. // we just avoid eating the identifier, so it will be parsed as the
  1659. // identifier in the declarator.
  1660. return false;
  1661. }
  1662. if (getLangOpts().CPlusPlus &&
  1663. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  1664. // Don't require a type specifier if we have the 'auto' storage class
  1665. // specifier in C++98 -- we'll promote it to a type specifier.
  1666. return false;
  1667. }
  1668. // Otherwise, if we don't consume this token, we are going to emit an
  1669. // error anyway. Try to recover from various common problems. Check
  1670. // to see if this was a reference to a tag name without a tag specified.
  1671. // This is a common problem in C (saying 'foo' instead of 'struct foo').
  1672. //
  1673. // C++ doesn't need this, and isTagName doesn't take SS.
  1674. if (SS == 0) {
  1675. const char *TagName = 0, *FixitTagName = 0;
  1676. tok::TokenKind TagKind = tok::unknown;
  1677. switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
  1678. default: break;
  1679. case DeclSpec::TST_enum:
  1680. TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
  1681. case DeclSpec::TST_union:
  1682. TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
  1683. case DeclSpec::TST_struct:
  1684. TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
  1685. case DeclSpec::TST_interface:
  1686. TagName="__interface"; FixitTagName = "__interface ";
  1687. TagKind=tok::kw___interface;break;
  1688. case DeclSpec::TST_class:
  1689. TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
  1690. }
  1691. if (TagName) {
  1692. IdentifierInfo *TokenName = Tok.getIdentifierInfo();
  1693. LookupResult R(Actions, TokenName, SourceLocation(),
  1694. Sema::LookupOrdinaryName);
  1695. Diag(Loc, diag::err_use_of_tag_name_without_tag)
  1696. << TokenName << TagName << getLangOpts().CPlusPlus
  1697. << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
  1698. if (Actions.LookupParsedName(R, getCurScope(), SS)) {
  1699. for (LookupResult::iterator I = R.begin(), IEnd = R.end();
  1700. I != IEnd; ++I)
  1701. Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  1702. << TokenName << TagName;
  1703. }
  1704. // Parse this as a tag as if the missing tag were present.
  1705. if (TagKind == tok::kw_enum)
  1706. ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
  1707. else
  1708. ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
  1709. /*EnteringContext*/ false, DSC_normal, Attrs);
  1710. return true;
  1711. }
  1712. }
  1713. // Determine whether this identifier could plausibly be the name of something
  1714. // being declared (with a missing type).
  1715. if (DSC != DSC_type_specifier && DSC != DSC_trailing &&
  1716. (!SS || DSC == DSC_top_level || DSC == DSC_class)) {
  1717. // Look ahead to the next token to try to figure out what this declaration
  1718. // was supposed to be.
  1719. switch (NextToken().getKind()) {
  1720. case tok::comma:
  1721. case tok::equal:
  1722. case tok::kw_asm:
  1723. case tok::l_brace:
  1724. case tok::l_square:
  1725. case tok::semi:
  1726. // This looks like a variable declaration. The type is probably missing.
  1727. // We're done parsing decl-specifiers.
  1728. return false;
  1729. case tok::l_paren: {
  1730. // static x(4); // 'x' is not a type
  1731. // x(int n); // 'x' is not a type
  1732. // x (*p)[]; // 'x' is a type
  1733. //
  1734. // Since we're in an error case (or the rare 'implicit int in C++' MS
  1735. // extension), we can afford to perform a tentative parse to determine
  1736. // which case we're in.
  1737. TentativeParsingAction PA(*this);
  1738. ConsumeToken();
  1739. TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
  1740. PA.Revert();
  1741. if (TPR == TPResult::False())
  1742. return false;
  1743. // The identifier is followed by a parenthesized declarator.
  1744. // It's supposed to be a type.
  1745. break;
  1746. }
  1747. default:
  1748. // This is probably supposed to be a type. This includes cases like:
  1749. // int f(itn);
  1750. // struct S { unsinged : 4; };
  1751. break;
  1752. }
  1753. }
  1754. // This is almost certainly an invalid type name. Let the action emit a
  1755. // diagnostic and attempt to recover.
  1756. ParsedType T;
  1757. IdentifierInfo *II = Tok.getIdentifierInfo();
  1758. if (Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T)) {
  1759. // The action emitted a diagnostic, so we don't have to.
  1760. if (T) {
  1761. // The action has suggested that the type T could be used. Set that as
  1762. // the type in the declaration specifiers, consume the would-be type
  1763. // name token, and we're done.
  1764. const char *PrevSpec;
  1765. unsigned DiagID;
  1766. DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
  1767. DS.SetRangeEnd(Tok.getLocation());
  1768. ConsumeToken();
  1769. // There may be other declaration specifiers after this.
  1770. return true;
  1771. } else if (II != Tok.getIdentifierInfo()) {
  1772. // If no type was suggested, the correction is to a keyword
  1773. Tok.setKind(II->getTokenID());
  1774. // There may be other declaration specifiers after this.
  1775. return true;
  1776. }
  1777. // Fall through; the action had no suggestion for us.
  1778. } else {
  1779. // The action did not emit a diagnostic, so emit one now.
  1780. SourceRange R;
  1781. if (SS) R = SS->getRange();
  1782. Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
  1783. }
  1784. // Mark this as an error.
  1785. DS.SetTypeSpecError();
  1786. DS.SetRangeEnd(Tok.getLocation());
  1787. ConsumeToken();
  1788. // TODO: Could inject an invalid typedef decl in an enclosing scope to
  1789. // avoid rippling error messages on subsequent uses of the same type,
  1790. // could be useful if #include was forgotten.
  1791. return false;
  1792. }
  1793. /// \brief Determine the declaration specifier context from the declarator
  1794. /// context.
  1795. ///
  1796. /// \param Context the declarator context, which is one of the
  1797. /// Declarator::TheContext enumerator values.
  1798. Parser::DeclSpecContext
  1799. Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
  1800. if (Context == Declarator::MemberContext)
  1801. return DSC_class;
  1802. if (Context == Declarator::FileContext)
  1803. return DSC_top_level;
  1804. if (Context == Declarator::TrailingReturnContext)
  1805. return DSC_trailing;
  1806. return DSC_normal;
  1807. }
  1808. /// ParseAlignArgument - Parse the argument to an alignment-specifier.
  1809. ///
  1810. /// FIXME: Simply returns an alignof() expression if the argument is a
  1811. /// type. Ideally, the type should be propagated directly into Sema.
  1812. ///
  1813. /// [C11] type-id
  1814. /// [C11] constant-expression
  1815. /// [C++0x] type-id ...[opt]
  1816. /// [C++0x] assignment-expression ...[opt]
  1817. ExprResult Parser::ParseAlignArgument(SourceLocation Start,
  1818. SourceLocation &EllipsisLoc) {
  1819. ExprResult ER;
  1820. if (isTypeIdInParens()) {
  1821. SourceLocation TypeLoc = Tok.getLocation();
  1822. ParsedType Ty = ParseTypeName().get();
  1823. SourceRange TypeRange(Start, Tok.getLocation());
  1824. ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
  1825. Ty.getAsOpaquePtr(), TypeRange);
  1826. } else
  1827. ER = ParseConstantExpression();
  1828. if (getLangOpts().CPlusPlus11 && Tok.is(tok::ellipsis))
  1829. EllipsisLoc = ConsumeToken();
  1830. return ER;
  1831. }
  1832. /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
  1833. /// attribute to Attrs.
  1834. ///
  1835. /// alignment-specifier:
  1836. /// [C11] '_Alignas' '(' type-id ')'
  1837. /// [C11] '_Alignas' '(' constant-expression ')'
  1838. /// [C++11] 'alignas' '(' type-id ...[opt] ')'
  1839. /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
  1840. void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
  1841. SourceLocation *endLoc) {
  1842. assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) &&
  1843. "Not an alignment-specifier!");
  1844. IdentifierInfo *KWName = Tok.getIdentifierInfo();
  1845. SourceLocation KWLoc = ConsumeToken();
  1846. BalancedDelimiterTracker T(*this, tok::l_paren);
  1847. if (T.expectAndConsume(diag::err_expected_lparen))
  1848. return;
  1849. SourceLocation EllipsisLoc;
  1850. ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
  1851. if (ArgExpr.isInvalid()) {
  1852. SkipUntil(tok::r_paren);
  1853. return;
  1854. }
  1855. T.consumeClose();
  1856. if (endLoc)
  1857. *endLoc = T.getCloseLocation();
  1858. // FIXME: Handle pack-expansions here.
  1859. if (EllipsisLoc.isValid()) {
  1860. Diag(EllipsisLoc, diag::err_alignas_pack_exp_unsupported);
  1861. return;
  1862. }
  1863. ExprVector ArgExprs;
  1864. ArgExprs.push_back(ArgExpr.release());
  1865. Attrs.addNew(KWName, KWLoc, 0, KWLoc, 0, T.getOpenLocation(),
  1866. ArgExprs.data(), 1, AttributeList::AS_Keyword);
  1867. }
  1868. /// ParseDeclarationSpecifiers
  1869. /// declaration-specifiers: [C99 6.7]
  1870. /// storage-class-specifier declaration-specifiers[opt]
  1871. /// type-specifier declaration-specifiers[opt]
  1872. /// [C99] function-specifier declaration-specifiers[opt]
  1873. /// [C11] alignment-specifier declaration-specifiers[opt]
  1874. /// [GNU] attributes declaration-specifiers[opt]
  1875. /// [Clang] '__module_private__' declaration-specifiers[opt]
  1876. ///
  1877. /// storage-class-specifier: [C99 6.7.1]
  1878. /// 'typedef'
  1879. /// 'extern'
  1880. /// 'static'
  1881. /// 'auto'
  1882. /// 'register'
  1883. /// [C++] 'mutable'
  1884. /// [GNU] '__thread'
  1885. /// function-specifier: [C99 6.7.4]
  1886. /// [C99] 'inline'
  1887. /// [C++] 'virtual'
  1888. /// [C++] 'explicit'
  1889. /// [OpenCL] '__kernel'
  1890. /// 'friend': [C++ dcl.friend]
  1891. /// 'constexpr': [C++0x dcl.constexpr]
  1892. ///
  1893. void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
  1894. const ParsedTemplateInfo &TemplateInfo,
  1895. AccessSpecifier AS,
  1896. DeclSpecContext DSContext,
  1897. LateParsedAttrList *LateAttrs) {
  1898. if (DS.getSourceRange().isInvalid()) {
  1899. DS.SetRangeStart(Tok.getLocation());
  1900. DS.SetRangeEnd(Tok.getLocation());
  1901. }
  1902. bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
  1903. bool AttrsLastTime = false;
  1904. ParsedAttributesWithRange attrs(AttrFactory);
  1905. while (1) {
  1906. bool isInvalid = false;
  1907. const char *PrevSpec = 0;
  1908. unsigned DiagID = 0;
  1909. SourceLocation Loc = Tok.getLocation();
  1910. switch (Tok.getKind()) {
  1911. default:
  1912. DoneWithDeclSpec:
  1913. if (!AttrsLastTime)
  1914. ProhibitAttributes(attrs);
  1915. else {
  1916. // Reject C++11 attributes that appertain to decl specifiers as
  1917. // we don't support any C++11 attributes that appertain to decl
  1918. // specifiers. This also conforms to what g++ 4.8 is doing.
  1919. ProhibitCXX11Attributes(attrs);
  1920. DS.takeAttributesFrom(attrs);
  1921. }
  1922. // If this is not a declaration specifier token, we're done reading decl
  1923. // specifiers. First verify that DeclSpec's are consistent.
  1924. DS.Finish(Diags, PP);
  1925. return;
  1926. case tok::l_square:
  1927. case tok::kw_alignas:
  1928. if (!isCXX11AttributeSpecifier())
  1929. goto DoneWithDeclSpec;
  1930. ProhibitAttributes(attrs);
  1931. // FIXME: It would be good to recover by accepting the attributes,
  1932. // but attempting to do that now would cause serious
  1933. // madness in terms of diagnostics.
  1934. attrs.clear();
  1935. attrs.Range = SourceRange();
  1936. ParseCXX11Attributes(attrs);
  1937. AttrsLastTime = true;
  1938. continue;
  1939. case tok::code_completion: {
  1940. Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
  1941. if (DS.hasTypeSpecifier()) {
  1942. bool AllowNonIdentifiers
  1943. = (getCurScope()->getFlags() & (Scope::ControlScope |
  1944. Scope::BlockScope |
  1945. Scope::TemplateParamScope |
  1946. Scope::FunctionPrototypeScope |
  1947. Scope::AtCatchScope)) == 0;
  1948. bool AllowNestedNameSpecifiers
  1949. = DSContext == DSC_top_level ||
  1950. (DSContext == DSC_class && DS.isFriendSpecified());
  1951. Actions.CodeCompleteDeclSpec(getCurScope(), DS,
  1952. AllowNonIdentifiers,
  1953. AllowNestedNameSpecifiers);
  1954. return cutOffParsing();
  1955. }
  1956. if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
  1957. CCC = Sema::PCC_LocalDeclarationSpecifiers;
  1958. else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
  1959. CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
  1960. : Sema::PCC_Template;
  1961. else if (DSContext == DSC_class)
  1962. CCC = Sema::PCC_Class;
  1963. else if (CurParsedObjCImpl)
  1964. CCC = Sema::PCC_ObjCImplementation;
  1965. Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
  1966. return cutOffParsing();
  1967. }
  1968. case tok::coloncolon: // ::foo::bar
  1969. // C++ scope specifier. Annotate and loop, or bail out on error.
  1970. if (TryAnnotateCXXScopeToken(true)) {
  1971. if (!DS.hasTypeSpecifier())
  1972. DS.SetTypeSpecError();
  1973. goto DoneWithDeclSpec;
  1974. }
  1975. if (Tok.is(tok::coloncolon)) // ::new or ::delete
  1976. goto DoneWithDeclSpec;
  1977. continue;
  1978. case tok::annot_cxxscope: {
  1979. if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
  1980. goto DoneWithDeclSpec;
  1981. CXXScopeSpec SS;
  1982. Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
  1983. Tok.getAnnotationRange(),
  1984. SS);
  1985. // We are looking for a qualified typename.
  1986. Token Next = NextToken();
  1987. if (Next.is(tok::annot_template_id) &&
  1988. static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
  1989. ->Kind == TNK_Type_template) {
  1990. // We have a qualified template-id, e.g., N::A<int>
  1991. // C++ [class.qual]p2:
  1992. // In a lookup in which the constructor is an acceptable lookup
  1993. // result and the nested-name-specifier nominates a class C:
  1994. //
  1995. // - if the name specified after the
  1996. // nested-name-specifier, when looked up in C, is the
  1997. // injected-class-name of C (Clause 9), or
  1998. //
  1999. // - if the name specified after the nested-name-specifier
  2000. // is the same as the identifier or the
  2001. // simple-template-id's template-name in the last
  2002. // component of the nested-name-specifier,
  2003. //
  2004. // the name is instead considered to name the constructor of
  2005. // class C.
  2006. //
  2007. // Thus, if the template-name is actually the constructor
  2008. // name, then the code is ill-formed; this interpretation is
  2009. // reinforced by the NAD status of core issue 635.
  2010. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
  2011. if ((DSContext == DSC_top_level ||
  2012. (DSContext == DSC_class && DS.isFriendSpecified())) &&
  2013. TemplateId->Name &&
  2014. Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
  2015. if (isConstructorDeclarator()) {
  2016. // The user meant this to be an out-of-line constructor
  2017. // definition, but template arguments are not allowed
  2018. // there. Just allow this as a constructor; we'll
  2019. // complain about it later.
  2020. goto DoneWithDeclSpec;
  2021. }
  2022. // The user meant this to name a type, but it actually names
  2023. // a constructor with some extraneous template
  2024. // arguments. Complain, then parse it as a type as the user
  2025. // intended.
  2026. Diag(TemplateId->TemplateNameLoc,
  2027. diag::err_out_of_line_template_id_names_constructor)
  2028. << TemplateId->Name;
  2029. }
  2030. DS.getTypeSpecScope() = SS;
  2031. ConsumeToken(); // The C++ scope.
  2032. assert(Tok.is(tok::annot_template_id) &&
  2033. "ParseOptionalCXXScopeSpecifier not working");
  2034. AnnotateTemplateIdTokenAsType();
  2035. continue;
  2036. }
  2037. if (Next.is(tok::annot_typename)) {
  2038. DS.getTypeSpecScope() = SS;
  2039. ConsumeToken(); // The C++ scope.
  2040. if (Tok.getAnnotationValue()) {
  2041. ParsedType T = getTypeAnnotation(Tok);
  2042. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
  2043. Tok.getAnnotationEndLoc(),
  2044. PrevSpec, DiagID, T);
  2045. if (isInvalid)
  2046. break;
  2047. }
  2048. else
  2049. DS.SetTypeSpecError();
  2050. DS.SetRangeEnd(Tok.getAnnotationEndLoc());
  2051. ConsumeToken(); // The typename
  2052. }
  2053. if (Next.isNot(tok::identifier))
  2054. goto DoneWithDeclSpec;
  2055. // If we're in a context where the identifier could be a class name,
  2056. // check whether this is a constructor declaration.
  2057. if ((DSContext == DSC_top_level ||
  2058. (DSContext == DSC_class && DS.isFriendSpecified())) &&
  2059. Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
  2060. &SS)) {
  2061. if (isConstructorDeclarator())
  2062. goto DoneWithDeclSpec;
  2063. // As noted in C++ [class.qual]p2 (cited above), when the name
  2064. // of the class is qualified in a context where it could name
  2065. // a constructor, its a constructor name. However, we've
  2066. // looked at the declarator, and the user probably meant this
  2067. // to be a type. Complain that it isn't supposed to be treated
  2068. // as a type, then proceed to parse it as a type.
  2069. Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
  2070. << Next.getIdentifierInfo();
  2071. }
  2072. ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
  2073. Next.getLocation(),
  2074. getCurScope(), &SS,
  2075. false, false, ParsedType(),
  2076. /*IsCtorOrDtorName=*/false,
  2077. /*NonTrivialSourceInfo=*/true);
  2078. // If the referenced identifier is not a type, then this declspec is
  2079. // erroneous: We already checked about that it has no type specifier, and
  2080. // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
  2081. // typename.
  2082. if (TypeRep == 0) {
  2083. ConsumeToken(); // Eat the scope spec so the identifier is current.
  2084. ParsedAttributesWithRange Attrs(AttrFactory);
  2085. if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
  2086. if (!Attrs.empty()) {
  2087. AttrsLastTime = true;
  2088. attrs.takeAllFrom(Attrs);
  2089. }
  2090. continue;
  2091. }
  2092. goto DoneWithDeclSpec;
  2093. }
  2094. DS.getTypeSpecScope() = SS;
  2095. ConsumeToken(); // The C++ scope.
  2096. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
  2097. DiagID, TypeRep);
  2098. if (isInvalid)
  2099. break;
  2100. DS.SetRangeEnd(Tok.getLocation());
  2101. ConsumeToken(); // The typename.
  2102. continue;
  2103. }
  2104. case tok::annot_typename: {
  2105. if (Tok.getAnnotationValue()) {
  2106. ParsedType T = getTypeAnnotation(Tok);
  2107. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
  2108. DiagID, T);
  2109. } else
  2110. DS.SetTypeSpecError();
  2111. if (isInvalid)
  2112. break;
  2113. DS.SetRangeEnd(Tok.getAnnotationEndLoc());
  2114. ConsumeToken(); // The typename
  2115. // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
  2116. // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
  2117. // Objective-C interface.
  2118. if (Tok.is(tok::less) && getLangOpts().ObjC1)
  2119. ParseObjCProtocolQualifiers(DS);
  2120. continue;
  2121. }
  2122. case tok::kw___is_signed:
  2123. // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
  2124. // typically treats it as a trait. If we see __is_signed as it appears
  2125. // in libstdc++, e.g.,
  2126. //
  2127. // static const bool __is_signed;
  2128. //
  2129. // then treat __is_signed as an identifier rather than as a keyword.
  2130. if (DS.getTypeSpecType() == TST_bool &&
  2131. DS.getTypeQualifiers() == DeclSpec::TQ_const &&
  2132. DS.getStorageClassSpec() == DeclSpec::SCS_static) {
  2133. Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
  2134. Tok.setKind(tok::identifier);
  2135. }
  2136. // We're done with the declaration-specifiers.
  2137. goto DoneWithDeclSpec;
  2138. // typedef-name
  2139. case tok::kw_decltype:
  2140. case tok::identifier: {
  2141. // In C++, check to see if this is a scope specifier like foo::bar::, if
  2142. // so handle it as such. This is important for ctor parsing.
  2143. if (getLangOpts().CPlusPlus) {
  2144. if (TryAnnotateCXXScopeToken(true)) {
  2145. if (!DS.hasTypeSpecifier())
  2146. DS.SetTypeSpecError();
  2147. goto DoneWithDeclSpec;
  2148. }
  2149. if (!Tok.is(tok::identifier))
  2150. continue;
  2151. }
  2152. // This identifier can only be a typedef name if we haven't already seen
  2153. // a type-specifier. Without this check we misparse:
  2154. // typedef int X; struct Y { short X; }; as 'short int'.
  2155. if (DS.hasTypeSpecifier())
  2156. goto DoneWithDeclSpec;
  2157. // Check for need to substitute AltiVec keyword tokens.
  2158. if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
  2159. break;
  2160. // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
  2161. // allow the use of a typedef name as a type specifier.
  2162. if (DS.isTypeAltiVecVector())
  2163. goto DoneWithDeclSpec;
  2164. ParsedType TypeRep =
  2165. Actions.getTypeName(*Tok.getIdentifierInfo(),
  2166. Tok.getLocation(), getCurScope());
  2167. // If this is not a typedef name, don't parse it as part of the declspec,
  2168. // it must be an implicit int or an error.
  2169. if (!TypeRep) {
  2170. ParsedAttributesWithRange Attrs(AttrFactory);
  2171. if (ParseImplicitInt(DS, 0, TemplateInfo, AS, DSContext, Attrs)) {
  2172. if (!Attrs.empty()) {
  2173. AttrsLastTime = true;
  2174. attrs.takeAllFrom(Attrs);
  2175. }
  2176. continue;
  2177. }
  2178. goto DoneWithDeclSpec;
  2179. }
  2180. // If we're in a context where the identifier could be a class name,
  2181. // check whether this is a constructor declaration.
  2182. if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
  2183. Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
  2184. isConstructorDeclarator())
  2185. goto DoneWithDeclSpec;
  2186. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
  2187. DiagID, TypeRep);
  2188. if (isInvalid)
  2189. break;
  2190. DS.SetRangeEnd(Tok.getLocation());
  2191. ConsumeToken(); // The identifier
  2192. // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
  2193. // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
  2194. // Objective-C interface.
  2195. if (Tok.is(tok::less) && getLangOpts().ObjC1)
  2196. ParseObjCProtocolQualifiers(DS);
  2197. // Need to support trailing type qualifiers (e.g. "id<p> const").
  2198. // If a type specifier follows, it will be diagnosed elsewhere.
  2199. continue;
  2200. }
  2201. // type-name
  2202. case tok::annot_template_id: {
  2203. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  2204. if (TemplateId->Kind != TNK_Type_template) {
  2205. // This template-id does not refer to a type name, so we're
  2206. // done with the type-specifiers.
  2207. goto DoneWithDeclSpec;
  2208. }
  2209. // If we're in a context where the template-id could be a
  2210. // constructor name or specialization, check whether this is a
  2211. // constructor declaration.
  2212. if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
  2213. Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
  2214. isConstructorDeclarator())
  2215. goto DoneWithDeclSpec;
  2216. // Turn the template-id annotation token into a type annotation
  2217. // token, then try again to parse it as a type-specifier.
  2218. AnnotateTemplateIdTokenAsType();
  2219. continue;
  2220. }
  2221. // GNU attributes support.
  2222. case tok::kw___attribute:
  2223. ParseGNUAttributes(DS.getAttributes(), 0, LateAttrs);
  2224. continue;
  2225. // Microsoft declspec support.
  2226. case tok::kw___declspec:
  2227. ParseMicrosoftDeclSpec(DS.getAttributes());
  2228. continue;
  2229. // Microsoft single token adornments.
  2230. case tok::kw___forceinline: {
  2231. isInvalid = DS.setFunctionSpecInline(Loc);
  2232. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  2233. SourceLocation AttrNameLoc = Tok.getLocation();
  2234. // FIXME: This does not work correctly if it is set to be a declspec
  2235. // attribute, and a GNU attribute is simply incorrect.
  2236. DS.getAttributes().addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
  2237. SourceLocation(), 0, 0, AttributeList::AS_GNU);
  2238. break;
  2239. }
  2240. case tok::kw___ptr64:
  2241. case tok::kw___ptr32:
  2242. case tok::kw___w64:
  2243. case tok::kw___cdecl:
  2244. case tok::kw___stdcall:
  2245. case tok::kw___fastcall:
  2246. case tok::kw___thiscall:
  2247. case tok::kw___unaligned:
  2248. ParseMicrosoftTypeAttributes(DS.getAttributes());
  2249. continue;
  2250. // Borland single token adornments.
  2251. case tok::kw___pascal:
  2252. ParseBorlandTypeAttributes(DS.getAttributes());
  2253. continue;
  2254. // OpenCL single token adornments.
  2255. case tok::kw___kernel:
  2256. ParseOpenCLAttributes(DS.getAttributes());
  2257. continue;
  2258. // storage-class-specifier
  2259. case tok::kw_typedef:
  2260. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
  2261. PrevSpec, DiagID);
  2262. break;
  2263. case tok::kw_extern:
  2264. if (DS.isThreadSpecified())
  2265. Diag(Tok, diag::ext_thread_before) << "extern";
  2266. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
  2267. PrevSpec, DiagID);
  2268. break;
  2269. case tok::kw___private_extern__:
  2270. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
  2271. Loc, PrevSpec, DiagID);
  2272. break;
  2273. case tok::kw_static:
  2274. if (DS.isThreadSpecified())
  2275. Diag(Tok, diag::ext_thread_before) << "static";
  2276. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
  2277. PrevSpec, DiagID);
  2278. break;
  2279. case tok::kw_auto:
  2280. if (getLangOpts().CPlusPlus11) {
  2281. if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
  2282. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
  2283. PrevSpec, DiagID);
  2284. if (!isInvalid)
  2285. Diag(Tok, diag::ext_auto_storage_class)
  2286. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  2287. } else
  2288. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
  2289. DiagID);
  2290. } else
  2291. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
  2292. PrevSpec, DiagID);
  2293. break;
  2294. case tok::kw_register:
  2295. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
  2296. PrevSpec, DiagID);
  2297. break;
  2298. case tok::kw_mutable:
  2299. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
  2300. PrevSpec, DiagID);
  2301. break;
  2302. case tok::kw___thread:
  2303. isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
  2304. break;
  2305. // function-specifier
  2306. case tok::kw_inline:
  2307. isInvalid = DS.setFunctionSpecInline(Loc);
  2308. break;
  2309. case tok::kw_virtual:
  2310. isInvalid = DS.setFunctionSpecVirtual(Loc);
  2311. break;
  2312. case tok::kw_explicit:
  2313. isInvalid = DS.setFunctionSpecExplicit(Loc);
  2314. break;
  2315. case tok::kw__Noreturn:
  2316. if (!getLangOpts().C11)
  2317. Diag(Loc, diag::ext_c11_noreturn);
  2318. isInvalid = DS.setFunctionSpecNoreturn(Loc);
  2319. break;
  2320. // alignment-specifier
  2321. case tok::kw__Alignas:
  2322. if (!getLangOpts().C11)
  2323. Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
  2324. ParseAlignmentSpecifier(DS.getAttributes());
  2325. continue;
  2326. // friend
  2327. case tok::kw_friend:
  2328. if (DSContext == DSC_class)
  2329. isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
  2330. else {
  2331. PrevSpec = ""; // not actually used by the diagnostic
  2332. DiagID = diag::err_friend_invalid_in_context;
  2333. isInvalid = true;
  2334. }
  2335. break;
  2336. // Modules
  2337. case tok::kw___module_private__:
  2338. isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
  2339. break;
  2340. // constexpr
  2341. case tok::kw_constexpr:
  2342. isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
  2343. break;
  2344. // type-specifier
  2345. case tok::kw_short:
  2346. isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
  2347. DiagID);
  2348. break;
  2349. case tok::kw_long:
  2350. if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
  2351. isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
  2352. DiagID);
  2353. else
  2354. isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
  2355. DiagID);
  2356. break;
  2357. case tok::kw___int64:
  2358. isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
  2359. DiagID);
  2360. break;
  2361. case tok::kw_signed:
  2362. isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
  2363. DiagID);
  2364. break;
  2365. case tok::kw_unsigned:
  2366. isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
  2367. DiagID);
  2368. break;
  2369. case tok::kw__Complex:
  2370. isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
  2371. DiagID);
  2372. break;
  2373. case tok::kw__Imaginary:
  2374. isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
  2375. DiagID);
  2376. break;
  2377. case tok::kw_void:
  2378. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
  2379. DiagID);
  2380. break;
  2381. case tok::kw_char:
  2382. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
  2383. DiagID);
  2384. break;
  2385. case tok::kw_int:
  2386. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
  2387. DiagID);
  2388. break;
  2389. case tok::kw___int128:
  2390. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
  2391. DiagID);
  2392. break;
  2393. case tok::kw_half:
  2394. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
  2395. DiagID);
  2396. break;
  2397. case tok::kw_float:
  2398. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
  2399. DiagID);
  2400. break;
  2401. case tok::kw_double:
  2402. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
  2403. DiagID);
  2404. break;
  2405. case tok::kw_wchar_t:
  2406. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
  2407. DiagID);
  2408. break;
  2409. case tok::kw_char16_t:
  2410. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
  2411. DiagID);
  2412. break;
  2413. case tok::kw_char32_t:
  2414. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
  2415. DiagID);
  2416. break;
  2417. case tok::kw_bool:
  2418. case tok::kw__Bool:
  2419. if (Tok.is(tok::kw_bool) &&
  2420. DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
  2421. DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
  2422. PrevSpec = ""; // Not used by the diagnostic.
  2423. DiagID = diag::err_bool_redeclaration;
  2424. // For better error recovery.
  2425. Tok.setKind(tok::identifier);
  2426. isInvalid = true;
  2427. } else {
  2428. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
  2429. DiagID);
  2430. }
  2431. break;
  2432. case tok::kw__Decimal32:
  2433. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
  2434. DiagID);
  2435. break;
  2436. case tok::kw__Decimal64:
  2437. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
  2438. DiagID);
  2439. break;
  2440. case tok::kw__Decimal128:
  2441. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
  2442. DiagID);
  2443. break;
  2444. case tok::kw___vector:
  2445. isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
  2446. break;
  2447. case tok::kw___pixel:
  2448. isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
  2449. break;
  2450. case tok::kw_image1d_t:
  2451. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_t, Loc,
  2452. PrevSpec, DiagID);
  2453. break;
  2454. case tok::kw_image1d_array_t:
  2455. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_array_t, Loc,
  2456. PrevSpec, DiagID);
  2457. break;
  2458. case tok::kw_image1d_buffer_t:
  2459. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_buffer_t, Loc,
  2460. PrevSpec, DiagID);
  2461. break;
  2462. case tok::kw_image2d_t:
  2463. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image2d_t, Loc,
  2464. PrevSpec, DiagID);
  2465. break;
  2466. case tok::kw_image2d_array_t:
  2467. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image2d_array_t, Loc,
  2468. PrevSpec, DiagID);
  2469. break;
  2470. case tok::kw_image3d_t:
  2471. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image3d_t, Loc,
  2472. PrevSpec, DiagID);
  2473. break;
  2474. case tok::kw_sampler_t:
  2475. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_sampler_t, Loc,
  2476. PrevSpec, DiagID);
  2477. break;
  2478. case tok::kw_event_t:
  2479. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_event_t, Loc,
  2480. PrevSpec, DiagID);
  2481. break;
  2482. case tok::kw___unknown_anytype:
  2483. isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
  2484. PrevSpec, DiagID);
  2485. break;
  2486. // class-specifier:
  2487. case tok::kw_class:
  2488. case tok::kw_struct:
  2489. case tok::kw___interface:
  2490. case tok::kw_union: {
  2491. tok::TokenKind Kind = Tok.getKind();
  2492. ConsumeToken();
  2493. // These are attributes following class specifiers.
  2494. // To produce better diagnostic, we parse them when
  2495. // parsing class specifier.
  2496. ParsedAttributesWithRange Attributes(AttrFactory);
  2497. ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
  2498. EnteringContext, DSContext, Attributes);
  2499. // If there are attributes following class specifier,
  2500. // take them over and handle them here.
  2501. if (!Attributes.empty()) {
  2502. AttrsLastTime = true;
  2503. attrs.takeAllFrom(Attributes);
  2504. }
  2505. continue;
  2506. }
  2507. // enum-specifier:
  2508. case tok::kw_enum:
  2509. ConsumeToken();
  2510. ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
  2511. continue;
  2512. // cv-qualifier:
  2513. case tok::kw_const:
  2514. isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
  2515. getLangOpts());
  2516. break;
  2517. case tok::kw_volatile:
  2518. isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
  2519. getLangOpts());
  2520. break;
  2521. case tok::kw_restrict:
  2522. isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
  2523. getLangOpts());
  2524. break;
  2525. // C++ typename-specifier:
  2526. case tok::kw_typename:
  2527. if (TryAnnotateTypeOrScopeToken()) {
  2528. DS.SetTypeSpecError();
  2529. goto DoneWithDeclSpec;
  2530. }
  2531. if (!Tok.is(tok::kw_typename))
  2532. continue;
  2533. break;
  2534. // GNU typeof support.
  2535. case tok::kw_typeof:
  2536. ParseTypeofSpecifier(DS);
  2537. continue;
  2538. case tok::annot_decltype:
  2539. ParseDecltypeSpecifier(DS);
  2540. continue;
  2541. case tok::kw___underlying_type:
  2542. ParseUnderlyingTypeSpecifier(DS);
  2543. continue;
  2544. case tok::kw__Atomic:
  2545. ParseAtomicSpecifier(DS);
  2546. continue;
  2547. // OpenCL qualifiers:
  2548. case tok::kw_private:
  2549. if (!getLangOpts().OpenCL)
  2550. goto DoneWithDeclSpec;
  2551. case tok::kw___private:
  2552. case tok::kw___global:
  2553. case tok::kw___local:
  2554. case tok::kw___constant:
  2555. case tok::kw___read_only:
  2556. case tok::kw___write_only:
  2557. case tok::kw___read_write:
  2558. ParseOpenCLQualifiers(DS);
  2559. break;
  2560. case tok::less:
  2561. // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
  2562. // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
  2563. // but we support it.
  2564. if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
  2565. goto DoneWithDeclSpec;
  2566. if (!ParseObjCProtocolQualifiers(DS))
  2567. Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
  2568. << FixItHint::CreateInsertion(Loc, "id")
  2569. << SourceRange(Loc, DS.getSourceRange().getEnd());
  2570. // Need to support trailing type qualifiers (e.g. "id<p> const").
  2571. // If a type specifier follows, it will be diagnosed elsewhere.
  2572. continue;
  2573. }
  2574. // If the specifier wasn't legal, issue a diagnostic.
  2575. if (isInvalid) {
  2576. assert(PrevSpec && "Method did not return previous specifier!");
  2577. assert(DiagID);
  2578. if (DiagID == diag::ext_duplicate_declspec)
  2579. Diag(Tok, DiagID)
  2580. << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
  2581. else
  2582. Diag(Tok, DiagID) << PrevSpec;
  2583. }
  2584. DS.SetRangeEnd(Tok.getLocation());
  2585. if (DiagID != diag::err_bool_redeclaration)
  2586. ConsumeToken();
  2587. AttrsLastTime = false;
  2588. }
  2589. }
  2590. /// ParseStructDeclaration - Parse a struct declaration without the terminating
  2591. /// semicolon.
  2592. ///
  2593. /// struct-declaration:
  2594. /// specifier-qualifier-list struct-declarator-list
  2595. /// [GNU] __extension__ struct-declaration
  2596. /// [GNU] specifier-qualifier-list
  2597. /// struct-declarator-list:
  2598. /// struct-declarator
  2599. /// struct-declarator-list ',' struct-declarator
  2600. /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
  2601. /// struct-declarator:
  2602. /// declarator
  2603. /// [GNU] declarator attributes[opt]
  2604. /// declarator[opt] ':' constant-expression
  2605. /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
  2606. ///
  2607. void Parser::
  2608. ParseStructDeclaration(ParsingDeclSpec &DS, FieldCallback &Fields) {
  2609. if (Tok.is(tok::kw___extension__)) {
  2610. // __extension__ silences extension warnings in the subexpression.
  2611. ExtensionRAIIObject O(Diags); // Use RAII to do this.
  2612. ConsumeToken();
  2613. return ParseStructDeclaration(DS, Fields);
  2614. }
  2615. // Parse the common specifier-qualifiers-list piece.
  2616. ParseSpecifierQualifierList(DS);
  2617. // If there are no declarators, this is a free-standing declaration
  2618. // specifier. Let the actions module cope with it.
  2619. if (Tok.is(tok::semi)) {
  2620. Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
  2621. DS);
  2622. DS.complete(TheDecl);
  2623. return;
  2624. }
  2625. // Read struct-declarators until we find the semicolon.
  2626. bool FirstDeclarator = true;
  2627. SourceLocation CommaLoc;
  2628. while (1) {
  2629. ParsingFieldDeclarator DeclaratorInfo(*this, DS);
  2630. DeclaratorInfo.D.setCommaLoc(CommaLoc);
  2631. // Attributes are only allowed here on successive declarators.
  2632. if (!FirstDeclarator)
  2633. MaybeParseGNUAttributes(DeclaratorInfo.D);
  2634. /// struct-declarator: declarator
  2635. /// struct-declarator: declarator[opt] ':' constant-expression
  2636. if (Tok.isNot(tok::colon)) {
  2637. // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
  2638. ColonProtectionRAIIObject X(*this);
  2639. ParseDeclarator(DeclaratorInfo.D);
  2640. }
  2641. if (Tok.is(tok::colon)) {
  2642. ConsumeToken();
  2643. ExprResult Res(ParseConstantExpression());
  2644. if (Res.isInvalid())
  2645. SkipUntil(tok::semi, true, true);
  2646. else
  2647. DeclaratorInfo.BitfieldSize = Res.release();
  2648. }
  2649. // If attributes exist after the declarator, parse them.
  2650. MaybeParseGNUAttributes(DeclaratorInfo.D);
  2651. // We're done with this declarator; invoke the callback.
  2652. Fields.invoke(DeclaratorInfo);
  2653. // If we don't have a comma, it is either the end of the list (a ';')
  2654. // or an error, bail out.
  2655. if (Tok.isNot(tok::comma))
  2656. return;
  2657. // Consume the comma.
  2658. CommaLoc = ConsumeToken();
  2659. FirstDeclarator = false;
  2660. }
  2661. }
  2662. /// ParseStructUnionBody
  2663. /// struct-contents:
  2664. /// struct-declaration-list
  2665. /// [EXT] empty
  2666. /// [GNU] "struct-declaration-list" without terminatoring ';'
  2667. /// struct-declaration-list:
  2668. /// struct-declaration
  2669. /// struct-declaration-list struct-declaration
  2670. /// [OBC] '@' 'defs' '(' class-name ')'
  2671. ///
  2672. void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
  2673. unsigned TagType, Decl *TagDecl) {
  2674. PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
  2675. "parsing struct/union body");
  2676. BalancedDelimiterTracker T(*this, tok::l_brace);
  2677. if (T.consumeOpen())
  2678. return;
  2679. ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
  2680. Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
  2681. // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
  2682. // C++.
  2683. if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) {
  2684. Diag(Tok, diag::ext_empty_struct_union) << (TagType == TST_union);
  2685. Diag(Tok, diag::warn_empty_struct_union_compat) << (TagType == TST_union);
  2686. }
  2687. SmallVector<Decl *, 32> FieldDecls;
  2688. // While we still have something to read, read the declarations in the struct.
  2689. while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
  2690. // Each iteration of this loop reads one struct-declaration.
  2691. // Check for extraneous top-level semicolon.
  2692. if (Tok.is(tok::semi)) {
  2693. ConsumeExtraSemi(InsideStruct, TagType);
  2694. continue;
  2695. }
  2696. if (!Tok.is(tok::at)) {
  2697. struct CFieldCallback : FieldCallback {
  2698. Parser &P;
  2699. Decl *TagDecl;
  2700. SmallVectorImpl<Decl *> &FieldDecls;
  2701. CFieldCallback(Parser &P, Decl *TagDecl,
  2702. SmallVectorImpl<Decl *> &FieldDecls) :
  2703. P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
  2704. void invoke(ParsingFieldDeclarator &FD) {
  2705. // Install the declarator into the current TagDecl.
  2706. Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
  2707. FD.D.getDeclSpec().getSourceRange().getBegin(),
  2708. FD.D, FD.BitfieldSize);
  2709. FieldDecls.push_back(Field);
  2710. FD.complete(Field);
  2711. }
  2712. } Callback(*this, TagDecl, FieldDecls);
  2713. // Parse all the comma separated declarators.
  2714. ParsingDeclSpec DS(*this);
  2715. ParseStructDeclaration(DS, Callback);
  2716. } else { // Handle @defs
  2717. ConsumeToken();
  2718. if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
  2719. Diag(Tok, diag::err_unexpected_at);
  2720. SkipUntil(tok::semi, true);
  2721. continue;
  2722. }
  2723. ConsumeToken();
  2724. ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
  2725. if (!Tok.is(tok::identifier)) {
  2726. Diag(Tok, diag::err_expected_ident);
  2727. SkipUntil(tok::semi, true);
  2728. continue;
  2729. }
  2730. SmallVector<Decl *, 16> Fields;
  2731. Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
  2732. Tok.getIdentifierInfo(), Fields);
  2733. FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
  2734. ConsumeToken();
  2735. ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
  2736. }
  2737. if (Tok.is(tok::semi)) {
  2738. ConsumeToken();
  2739. } else if (Tok.is(tok::r_brace)) {
  2740. ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
  2741. break;
  2742. } else {
  2743. ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
  2744. // Skip to end of block or statement to avoid ext-warning on extra ';'.
  2745. SkipUntil(tok::r_brace, true, true);
  2746. // If we stopped at a ';', eat it.
  2747. if (Tok.is(tok::semi)) ConsumeToken();
  2748. }
  2749. }
  2750. T.consumeClose();
  2751. ParsedAttributes attrs(AttrFactory);
  2752. // If attributes exist after struct contents, parse them.
  2753. MaybeParseGNUAttributes(attrs);
  2754. Actions.ActOnFields(getCurScope(),
  2755. RecordLoc, TagDecl, FieldDecls,
  2756. T.getOpenLocation(), T.getCloseLocation(),
  2757. attrs.getList());
  2758. StructScope.Exit();
  2759. Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
  2760. T.getCloseLocation());
  2761. }
  2762. /// ParseEnumSpecifier
  2763. /// enum-specifier: [C99 6.7.2.2]
  2764. /// 'enum' identifier[opt] '{' enumerator-list '}'
  2765. ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
  2766. /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
  2767. /// '}' attributes[opt]
  2768. /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
  2769. /// '}'
  2770. /// 'enum' identifier
  2771. /// [GNU] 'enum' attributes[opt] identifier
  2772. ///
  2773. /// [C++11] enum-head '{' enumerator-list[opt] '}'
  2774. /// [C++11] enum-head '{' enumerator-list ',' '}'
  2775. ///
  2776. /// enum-head: [C++11]
  2777. /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
  2778. /// enum-key attribute-specifier-seq[opt] nested-name-specifier
  2779. /// identifier enum-base[opt]
  2780. ///
  2781. /// enum-key: [C++11]
  2782. /// 'enum'
  2783. /// 'enum' 'class'
  2784. /// 'enum' 'struct'
  2785. ///
  2786. /// enum-base: [C++11]
  2787. /// ':' type-specifier-seq
  2788. ///
  2789. /// [C++] elaborated-type-specifier:
  2790. /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
  2791. ///
  2792. void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
  2793. const ParsedTemplateInfo &TemplateInfo,
  2794. AccessSpecifier AS, DeclSpecContext DSC) {
  2795. // Parse the tag portion of this.
  2796. if (Tok.is(tok::code_completion)) {
  2797. // Code completion for an enum name.
  2798. Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
  2799. return cutOffParsing();
  2800. }
  2801. // If attributes exist after tag, parse them.
  2802. ParsedAttributesWithRange attrs(AttrFactory);
  2803. MaybeParseGNUAttributes(attrs);
  2804. MaybeParseCXX11Attributes(attrs);
  2805. // If declspecs exist after tag, parse them.
  2806. while (Tok.is(tok::kw___declspec))
  2807. ParseMicrosoftDeclSpec(attrs);
  2808. SourceLocation ScopedEnumKWLoc;
  2809. bool IsScopedUsingClassTag = false;
  2810. // In C++11, recognize 'enum class' and 'enum struct'.
  2811. if (getLangOpts().CPlusPlus11 &&
  2812. (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) {
  2813. Diag(Tok, diag::warn_cxx98_compat_scoped_enum);
  2814. IsScopedUsingClassTag = Tok.is(tok::kw_class);
  2815. ScopedEnumKWLoc = ConsumeToken();
  2816. // Attributes are not allowed between these keywords. Diagnose,
  2817. // but then just treat them like they appeared in the right place.
  2818. ProhibitAttributes(attrs);
  2819. // They are allowed afterwards, though.
  2820. MaybeParseGNUAttributes(attrs);
  2821. MaybeParseCXX11Attributes(attrs);
  2822. while (Tok.is(tok::kw___declspec))
  2823. ParseMicrosoftDeclSpec(attrs);
  2824. }
  2825. // C++11 [temp.explicit]p12:
  2826. // The usual access controls do not apply to names used to specify
  2827. // explicit instantiations.
  2828. // We extend this to also cover explicit specializations. Note that
  2829. // we don't suppress if this turns out to be an elaborated type
  2830. // specifier.
  2831. bool shouldDelayDiagsInTag =
  2832. (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
  2833. TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
  2834. SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
  2835. // Enum definitions should not be parsed in a trailing-return-type.
  2836. bool AllowDeclaration = DSC != DSC_trailing;
  2837. bool AllowFixedUnderlyingType = AllowDeclaration &&
  2838. (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
  2839. getLangOpts().ObjC2);
  2840. CXXScopeSpec &SS = DS.getTypeSpecScope();
  2841. if (getLangOpts().CPlusPlus) {
  2842. // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
  2843. // if a fixed underlying type is allowed.
  2844. ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
  2845. if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
  2846. /*EnteringContext=*/false))
  2847. return;
  2848. if (SS.isSet() && Tok.isNot(tok::identifier)) {
  2849. Diag(Tok, diag::err_expected_ident);
  2850. if (Tok.isNot(tok::l_brace)) {
  2851. // Has no name and is not a definition.
  2852. // Skip the rest of this declarator, up until the comma or semicolon.
  2853. SkipUntil(tok::comma, true);
  2854. return;
  2855. }
  2856. }
  2857. }
  2858. // Must have either 'enum name' or 'enum {...}'.
  2859. if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
  2860. !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
  2861. Diag(Tok, diag::err_expected_ident_lbrace);
  2862. // Skip the rest of this declarator, up until the comma or semicolon.
  2863. SkipUntil(tok::comma, true);
  2864. return;
  2865. }
  2866. // If an identifier is present, consume and remember it.
  2867. IdentifierInfo *Name = 0;
  2868. SourceLocation NameLoc;
  2869. if (Tok.is(tok::identifier)) {
  2870. Name = Tok.getIdentifierInfo();
  2871. NameLoc = ConsumeToken();
  2872. }
  2873. if (!Name && ScopedEnumKWLoc.isValid()) {
  2874. // C++0x 7.2p2: The optional identifier shall not be omitted in the
  2875. // declaration of a scoped enumeration.
  2876. Diag(Tok, diag::err_scoped_enum_missing_identifier);
  2877. ScopedEnumKWLoc = SourceLocation();
  2878. IsScopedUsingClassTag = false;
  2879. }
  2880. // Okay, end the suppression area. We'll decide whether to emit the
  2881. // diagnostics in a second.
  2882. if (shouldDelayDiagsInTag)
  2883. diagsFromTag.done();
  2884. TypeResult BaseType;
  2885. // Parse the fixed underlying type.
  2886. bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
  2887. if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
  2888. bool PossibleBitfield = false;
  2889. if (CanBeBitfield) {
  2890. // If we're in class scope, this can either be an enum declaration with
  2891. // an underlying type, or a declaration of a bitfield member. We try to
  2892. // use a simple disambiguation scheme first to catch the common cases
  2893. // (integer literal, sizeof); if it's still ambiguous, we then consider
  2894. // anything that's a simple-type-specifier followed by '(' as an
  2895. // expression. This suffices because function types are not valid
  2896. // underlying types anyway.
  2897. EnterExpressionEvaluationContext Unevaluated(Actions,
  2898. Sema::ConstantEvaluated);
  2899. TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
  2900. // If the next token starts an expression, we know we're parsing a
  2901. // bit-field. This is the common case.
  2902. if (TPR == TPResult::True())
  2903. PossibleBitfield = true;
  2904. // If the next token starts a type-specifier-seq, it may be either a
  2905. // a fixed underlying type or the start of a function-style cast in C++;
  2906. // lookahead one more token to see if it's obvious that we have a
  2907. // fixed underlying type.
  2908. else if (TPR == TPResult::False() &&
  2909. GetLookAheadToken(2).getKind() == tok::semi) {
  2910. // Consume the ':'.
  2911. ConsumeToken();
  2912. } else {
  2913. // We have the start of a type-specifier-seq, so we have to perform
  2914. // tentative parsing to determine whether we have an expression or a
  2915. // type.
  2916. TentativeParsingAction TPA(*this);
  2917. // Consume the ':'.
  2918. ConsumeToken();
  2919. // If we see a type specifier followed by an open-brace, we have an
  2920. // ambiguity between an underlying type and a C++11 braced
  2921. // function-style cast. Resolve this by always treating it as an
  2922. // underlying type.
  2923. // FIXME: The standard is not entirely clear on how to disambiguate in
  2924. // this case.
  2925. if ((getLangOpts().CPlusPlus &&
  2926. isCXXDeclarationSpecifier(TPResult::True()) != TPResult::True()) ||
  2927. (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
  2928. // We'll parse this as a bitfield later.
  2929. PossibleBitfield = true;
  2930. TPA.Revert();
  2931. } else {
  2932. // We have a type-specifier-seq.
  2933. TPA.Commit();
  2934. }
  2935. }
  2936. } else {
  2937. // Consume the ':'.
  2938. ConsumeToken();
  2939. }
  2940. if (!PossibleBitfield) {
  2941. SourceRange Range;
  2942. BaseType = ParseTypeName(&Range);
  2943. if (getLangOpts().CPlusPlus11) {
  2944. Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
  2945. } else if (!getLangOpts().ObjC2) {
  2946. if (getLangOpts().CPlusPlus)
  2947. Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
  2948. else
  2949. Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
  2950. }
  2951. }
  2952. }
  2953. // There are four options here. If we have 'friend enum foo;' then this is a
  2954. // friend declaration, and cannot have an accompanying definition. If we have
  2955. // 'enum foo;', then this is a forward declaration. If we have
  2956. // 'enum foo {...' then this is a definition. Otherwise we have something
  2957. // like 'enum foo xyz', a reference.
  2958. //
  2959. // This is needed to handle stuff like this right (C99 6.7.2.3p11):
  2960. // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
  2961. // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
  2962. //
  2963. Sema::TagUseKind TUK;
  2964. if (!AllowDeclaration) {
  2965. TUK = Sema::TUK_Reference;
  2966. } else if (Tok.is(tok::l_brace)) {
  2967. if (DS.isFriendSpecified()) {
  2968. Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
  2969. << SourceRange(DS.getFriendSpecLoc());
  2970. ConsumeBrace();
  2971. SkipUntil(tok::r_brace);
  2972. TUK = Sema::TUK_Friend;
  2973. } else {
  2974. TUK = Sema::TUK_Definition;
  2975. }
  2976. } else if (DSC != DSC_type_specifier &&
  2977. (Tok.is(tok::semi) ||
  2978. (Tok.isAtStartOfLine() &&
  2979. !isValidAfterTypeSpecifier(CanBeBitfield)))) {
  2980. TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
  2981. if (Tok.isNot(tok::semi)) {
  2982. // A semicolon was missing after this declaration. Diagnose and recover.
  2983. ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
  2984. "enum");
  2985. PP.EnterToken(Tok);
  2986. Tok.setKind(tok::semi);
  2987. }
  2988. } else {
  2989. TUK = Sema::TUK_Reference;
  2990. }
  2991. // If this is an elaborated type specifier, and we delayed
  2992. // diagnostics before, just merge them into the current pool.
  2993. if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
  2994. diagsFromTag.redelay();
  2995. }
  2996. MultiTemplateParamsArg TParams;
  2997. if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
  2998. TUK != Sema::TUK_Reference) {
  2999. if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
  3000. // Skip the rest of this declarator, up until the comma or semicolon.
  3001. Diag(Tok, diag::err_enum_template);
  3002. SkipUntil(tok::comma, true);
  3003. return;
  3004. }
  3005. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
  3006. // Enumerations can't be explicitly instantiated.
  3007. DS.SetTypeSpecError();
  3008. Diag(StartLoc, diag::err_explicit_instantiation_enum);
  3009. return;
  3010. }
  3011. assert(TemplateInfo.TemplateParams && "no template parameters");
  3012. TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
  3013. TemplateInfo.TemplateParams->size());
  3014. }
  3015. if (TUK == Sema::TUK_Reference)
  3016. ProhibitAttributes(attrs);
  3017. if (!Name && TUK != Sema::TUK_Definition) {
  3018. Diag(Tok, diag::err_enumerator_unnamed_no_def);
  3019. // Skip the rest of this declarator, up until the comma or semicolon.
  3020. SkipUntil(tok::comma, true);
  3021. return;
  3022. }
  3023. bool Owned = false;
  3024. bool IsDependent = false;
  3025. const char *PrevSpec = 0;
  3026. unsigned DiagID;
  3027. Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
  3028. StartLoc, SS, Name, NameLoc, attrs.getList(),
  3029. AS, DS.getModulePrivateSpecLoc(), TParams,
  3030. Owned, IsDependent, ScopedEnumKWLoc,
  3031. IsScopedUsingClassTag, BaseType);
  3032. if (IsDependent) {
  3033. // This enum has a dependent nested-name-specifier. Handle it as a
  3034. // dependent tag.
  3035. if (!Name) {
  3036. DS.SetTypeSpecError();
  3037. Diag(Tok, diag::err_expected_type_name_after_typename);
  3038. return;
  3039. }
  3040. TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
  3041. TUK, SS, Name, StartLoc,
  3042. NameLoc);
  3043. if (Type.isInvalid()) {
  3044. DS.SetTypeSpecError();
  3045. return;
  3046. }
  3047. if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
  3048. NameLoc.isValid() ? NameLoc : StartLoc,
  3049. PrevSpec, DiagID, Type.get()))
  3050. Diag(StartLoc, DiagID) << PrevSpec;
  3051. return;
  3052. }
  3053. if (!TagDecl) {
  3054. // The action failed to produce an enumeration tag. If this is a
  3055. // definition, consume the entire definition.
  3056. if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
  3057. ConsumeBrace();
  3058. SkipUntil(tok::r_brace);
  3059. }
  3060. DS.SetTypeSpecError();
  3061. return;
  3062. }
  3063. if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference)
  3064. ParseEnumBody(StartLoc, TagDecl);
  3065. if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
  3066. NameLoc.isValid() ? NameLoc : StartLoc,
  3067. PrevSpec, DiagID, TagDecl, Owned))
  3068. Diag(StartLoc, DiagID) << PrevSpec;
  3069. }
  3070. /// ParseEnumBody - Parse a {} enclosed enumerator-list.
  3071. /// enumerator-list:
  3072. /// enumerator
  3073. /// enumerator-list ',' enumerator
  3074. /// enumerator:
  3075. /// enumeration-constant
  3076. /// enumeration-constant '=' constant-expression
  3077. /// enumeration-constant:
  3078. /// identifier
  3079. ///
  3080. void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
  3081. // Enter the scope of the enum body and start the definition.
  3082. ParseScope EnumScope(this, Scope::DeclScope);
  3083. Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
  3084. BalancedDelimiterTracker T(*this, tok::l_brace);
  3085. T.consumeOpen();
  3086. // C does not allow an empty enumerator-list, C++ does [dcl.enum].
  3087. if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
  3088. Diag(Tok, diag::error_empty_enum);
  3089. SmallVector<Decl *, 32> EnumConstantDecls;
  3090. Decl *LastEnumConstDecl = 0;
  3091. // Parse the enumerator-list.
  3092. while (Tok.is(tok::identifier)) {
  3093. IdentifierInfo *Ident = Tok.getIdentifierInfo();
  3094. SourceLocation IdentLoc = ConsumeToken();
  3095. // If attributes exist after the enumerator, parse them.
  3096. ParsedAttributesWithRange attrs(AttrFactory);
  3097. MaybeParseGNUAttributes(attrs);
  3098. MaybeParseCXX11Attributes(attrs);
  3099. ProhibitAttributes(attrs);
  3100. SourceLocation EqualLoc;
  3101. ExprResult AssignedVal;
  3102. ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
  3103. if (Tok.is(tok::equal)) {
  3104. EqualLoc = ConsumeToken();
  3105. AssignedVal = ParseConstantExpression();
  3106. if (AssignedVal.isInvalid())
  3107. SkipUntil(tok::comma, tok::r_brace, true, true);
  3108. }
  3109. // Install the enumerator constant into EnumDecl.
  3110. Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
  3111. LastEnumConstDecl,
  3112. IdentLoc, Ident,
  3113. attrs.getList(), EqualLoc,
  3114. AssignedVal.release());
  3115. PD.complete(EnumConstDecl);
  3116. EnumConstantDecls.push_back(EnumConstDecl);
  3117. LastEnumConstDecl = EnumConstDecl;
  3118. if (Tok.is(tok::identifier)) {
  3119. // We're missing a comma between enumerators.
  3120. SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
  3121. Diag(Loc, diag::err_enumerator_list_missing_comma)
  3122. << FixItHint::CreateInsertion(Loc, ", ");
  3123. continue;
  3124. }
  3125. if (Tok.isNot(tok::comma))
  3126. break;
  3127. SourceLocation CommaLoc = ConsumeToken();
  3128. if (Tok.isNot(tok::identifier)) {
  3129. if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
  3130. Diag(CommaLoc, getLangOpts().CPlusPlus ?
  3131. diag::ext_enumerator_list_comma_cxx :
  3132. diag::ext_enumerator_list_comma_c)
  3133. << FixItHint::CreateRemoval(CommaLoc);
  3134. else if (getLangOpts().CPlusPlus11)
  3135. Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
  3136. << FixItHint::CreateRemoval(CommaLoc);
  3137. }
  3138. }
  3139. // Eat the }.
  3140. T.consumeClose();
  3141. // If attributes exist after the identifier list, parse them.
  3142. ParsedAttributes attrs(AttrFactory);
  3143. MaybeParseGNUAttributes(attrs);
  3144. Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(),
  3145. EnumDecl, EnumConstantDecls.data(),
  3146. EnumConstantDecls.size(), getCurScope(),
  3147. attrs.getList());
  3148. EnumScope.Exit();
  3149. Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl,
  3150. T.getCloseLocation());
  3151. // The next token must be valid after an enum definition. If not, a ';'
  3152. // was probably forgotten.
  3153. bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
  3154. if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
  3155. ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, "enum");
  3156. // Push this token back into the preprocessor and change our current token
  3157. // to ';' so that the rest of the code recovers as though there were an
  3158. // ';' after the definition.
  3159. PP.EnterToken(Tok);
  3160. Tok.setKind(tok::semi);
  3161. }
  3162. }
  3163. /// isTypeSpecifierQualifier - Return true if the current token could be the
  3164. /// start of a type-qualifier-list.
  3165. bool Parser::isTypeQualifier() const {
  3166. switch (Tok.getKind()) {
  3167. default: return false;
  3168. // type-qualifier only in OpenCL
  3169. case tok::kw_private:
  3170. return getLangOpts().OpenCL;
  3171. // type-qualifier
  3172. case tok::kw_const:
  3173. case tok::kw_volatile:
  3174. case tok::kw_restrict:
  3175. case tok::kw___private:
  3176. case tok::kw___local:
  3177. case tok::kw___global:
  3178. case tok::kw___constant:
  3179. case tok::kw___read_only:
  3180. case tok::kw___read_write:
  3181. case tok::kw___write_only:
  3182. return true;
  3183. }
  3184. }
  3185. /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
  3186. /// is definitely a type-specifier. Return false if it isn't part of a type
  3187. /// specifier or if we're not sure.
  3188. bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
  3189. switch (Tok.getKind()) {
  3190. default: return false;
  3191. // type-specifiers
  3192. case tok::kw_short:
  3193. case tok::kw_long:
  3194. case tok::kw___int64:
  3195. case tok::kw___int128:
  3196. case tok::kw_signed:
  3197. case tok::kw_unsigned:
  3198. case tok::kw__Complex:
  3199. case tok::kw__Imaginary:
  3200. case tok::kw_void:
  3201. case tok::kw_char:
  3202. case tok::kw_wchar_t:
  3203. case tok::kw_char16_t:
  3204. case tok::kw_char32_t:
  3205. case tok::kw_int:
  3206. case tok::kw_half:
  3207. case tok::kw_float:
  3208. case tok::kw_double:
  3209. case tok::kw_bool:
  3210. case tok::kw__Bool:
  3211. case tok::kw__Decimal32:
  3212. case tok::kw__Decimal64:
  3213. case tok::kw__Decimal128:
  3214. case tok::kw___vector:
  3215. // OpenCL specific types:
  3216. case tok::kw_image1d_t:
  3217. case tok::kw_image1d_array_t:
  3218. case tok::kw_image1d_buffer_t:
  3219. case tok::kw_image2d_t:
  3220. case tok::kw_image2d_array_t:
  3221. case tok::kw_image3d_t:
  3222. case tok::kw_sampler_t:
  3223. case tok::kw_event_t:
  3224. // struct-or-union-specifier (C99) or class-specifier (C++)
  3225. case tok::kw_class:
  3226. case tok::kw_struct:
  3227. case tok::kw___interface:
  3228. case tok::kw_union:
  3229. // enum-specifier
  3230. case tok::kw_enum:
  3231. // typedef-name
  3232. case tok::annot_typename:
  3233. return true;
  3234. }
  3235. }
  3236. /// isTypeSpecifierQualifier - Return true if the current token could be the
  3237. /// start of a specifier-qualifier-list.
  3238. bool Parser::isTypeSpecifierQualifier() {
  3239. switch (Tok.getKind()) {
  3240. default: return false;
  3241. case tok::identifier: // foo::bar
  3242. if (TryAltiVecVectorToken())
  3243. return true;
  3244. // Fall through.
  3245. case tok::kw_typename: // typename T::type
  3246. // Annotate typenames and C++ scope specifiers. If we get one, just
  3247. // recurse to handle whatever we get.
  3248. if (TryAnnotateTypeOrScopeToken())
  3249. return true;
  3250. if (Tok.is(tok::identifier))
  3251. return false;
  3252. return isTypeSpecifierQualifier();
  3253. case tok::coloncolon: // ::foo::bar
  3254. if (NextToken().is(tok::kw_new) || // ::new
  3255. NextToken().is(tok::kw_delete)) // ::delete
  3256. return false;
  3257. if (TryAnnotateTypeOrScopeToken())
  3258. return true;
  3259. return isTypeSpecifierQualifier();
  3260. // GNU attributes support.
  3261. case tok::kw___attribute:
  3262. // GNU typeof support.
  3263. case tok::kw_typeof:
  3264. // type-specifiers
  3265. case tok::kw_short:
  3266. case tok::kw_long:
  3267. case tok::kw___int64:
  3268. case tok::kw___int128:
  3269. case tok::kw_signed:
  3270. case tok::kw_unsigned:
  3271. case tok::kw__Complex:
  3272. case tok::kw__Imaginary:
  3273. case tok::kw_void:
  3274. case tok::kw_char:
  3275. case tok::kw_wchar_t:
  3276. case tok::kw_char16_t:
  3277. case tok::kw_char32_t:
  3278. case tok::kw_int:
  3279. case tok::kw_half:
  3280. case tok::kw_float:
  3281. case tok::kw_double:
  3282. case tok::kw_bool:
  3283. case tok::kw__Bool:
  3284. case tok::kw__Decimal32:
  3285. case tok::kw__Decimal64:
  3286. case tok::kw__Decimal128:
  3287. case tok::kw___vector:
  3288. // OpenCL specific types:
  3289. case tok::kw_image1d_t:
  3290. case tok::kw_image1d_array_t:
  3291. case tok::kw_image1d_buffer_t:
  3292. case tok::kw_image2d_t:
  3293. case tok::kw_image2d_array_t:
  3294. case tok::kw_image3d_t:
  3295. case tok::kw_sampler_t:
  3296. case tok::kw_event_t:
  3297. // struct-or-union-specifier (C99) or class-specifier (C++)
  3298. case tok::kw_class:
  3299. case tok::kw_struct:
  3300. case tok::kw___interface:
  3301. case tok::kw_union:
  3302. // enum-specifier
  3303. case tok::kw_enum:
  3304. // type-qualifier
  3305. case tok::kw_const:
  3306. case tok::kw_volatile:
  3307. case tok::kw_restrict:
  3308. // Debugger support.
  3309. case tok::kw___unknown_anytype:
  3310. // typedef-name
  3311. case tok::annot_typename:
  3312. return true;
  3313. // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
  3314. case tok::less:
  3315. return getLangOpts().ObjC1;
  3316. case tok::kw___cdecl:
  3317. case tok::kw___stdcall:
  3318. case tok::kw___fastcall:
  3319. case tok::kw___thiscall:
  3320. case tok::kw___w64:
  3321. case tok::kw___ptr64:
  3322. case tok::kw___ptr32:
  3323. case tok::kw___pascal:
  3324. case tok::kw___unaligned:
  3325. case tok::kw___private:
  3326. case tok::kw___local:
  3327. case tok::kw___global:
  3328. case tok::kw___constant:
  3329. case tok::kw___read_only:
  3330. case tok::kw___read_write:
  3331. case tok::kw___write_only:
  3332. return true;
  3333. case tok::kw_private:
  3334. return getLangOpts().OpenCL;
  3335. // C11 _Atomic()
  3336. case tok::kw__Atomic:
  3337. return true;
  3338. }
  3339. }
  3340. /// isDeclarationSpecifier() - Return true if the current token is part of a
  3341. /// declaration specifier.
  3342. ///
  3343. /// \param DisambiguatingWithExpression True to indicate that the purpose of
  3344. /// this check is to disambiguate between an expression and a declaration.
  3345. bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
  3346. switch (Tok.getKind()) {
  3347. default: return false;
  3348. case tok::kw_private:
  3349. return getLangOpts().OpenCL;
  3350. case tok::identifier: // foo::bar
  3351. // Unfortunate hack to support "Class.factoryMethod" notation.
  3352. if (getLangOpts().ObjC1 && NextToken().is(tok::period))
  3353. return false;
  3354. if (TryAltiVecVectorToken())
  3355. return true;
  3356. // Fall through.
  3357. case tok::kw_decltype: // decltype(T())::type
  3358. case tok::kw_typename: // typename T::type
  3359. // Annotate typenames and C++ scope specifiers. If we get one, just
  3360. // recurse to handle whatever we get.
  3361. if (TryAnnotateTypeOrScopeToken())
  3362. return true;
  3363. if (Tok.is(tok::identifier))
  3364. return false;
  3365. // If we're in Objective-C and we have an Objective-C class type followed
  3366. // by an identifier and then either ':' or ']', in a place where an
  3367. // expression is permitted, then this is probably a class message send
  3368. // missing the initial '['. In this case, we won't consider this to be
  3369. // the start of a declaration.
  3370. if (DisambiguatingWithExpression &&
  3371. isStartOfObjCClassMessageMissingOpenBracket())
  3372. return false;
  3373. return isDeclarationSpecifier();
  3374. case tok::coloncolon: // ::foo::bar
  3375. if (NextToken().is(tok::kw_new) || // ::new
  3376. NextToken().is(tok::kw_delete)) // ::delete
  3377. return false;
  3378. // Annotate typenames and C++ scope specifiers. If we get one, just
  3379. // recurse to handle whatever we get.
  3380. if (TryAnnotateTypeOrScopeToken())
  3381. return true;
  3382. return isDeclarationSpecifier();
  3383. // storage-class-specifier
  3384. case tok::kw_typedef:
  3385. case tok::kw_extern:
  3386. case tok::kw___private_extern__:
  3387. case tok::kw_static:
  3388. case tok::kw_auto:
  3389. case tok::kw_register:
  3390. case tok::kw___thread:
  3391. // Modules
  3392. case tok::kw___module_private__:
  3393. // Debugger support
  3394. case tok::kw___unknown_anytype:
  3395. // type-specifiers
  3396. case tok::kw_short:
  3397. case tok::kw_long:
  3398. case tok::kw___int64:
  3399. case tok::kw___int128:
  3400. case tok::kw_signed:
  3401. case tok::kw_unsigned:
  3402. case tok::kw__Complex:
  3403. case tok::kw__Imaginary:
  3404. case tok::kw_void:
  3405. case tok::kw_char:
  3406. case tok::kw_wchar_t:
  3407. case tok::kw_char16_t:
  3408. case tok::kw_char32_t:
  3409. case tok::kw_int:
  3410. case tok::kw_half:
  3411. case tok::kw_float:
  3412. case tok::kw_double:
  3413. case tok::kw_bool:
  3414. case tok::kw__Bool:
  3415. case tok::kw__Decimal32:
  3416. case tok::kw__Decimal64:
  3417. case tok::kw__Decimal128:
  3418. case tok::kw___vector:
  3419. // OpenCL specific types:
  3420. case tok::kw_image1d_t:
  3421. case tok::kw_image1d_array_t:
  3422. case tok::kw_image1d_buffer_t:
  3423. case tok::kw_image2d_t:
  3424. case tok::kw_image2d_array_t:
  3425. case tok::kw_image3d_t:
  3426. case tok::kw_sampler_t:
  3427. case tok::kw_event_t:
  3428. // struct-or-union-specifier (C99) or class-specifier (C++)
  3429. case tok::kw_class:
  3430. case tok::kw_struct:
  3431. case tok::kw_union:
  3432. case tok::kw___interface:
  3433. // enum-specifier
  3434. case tok::kw_enum:
  3435. // type-qualifier
  3436. case tok::kw_const:
  3437. case tok::kw_volatile:
  3438. case tok::kw_restrict:
  3439. // function-specifier
  3440. case tok::kw_inline:
  3441. case tok::kw_virtual:
  3442. case tok::kw_explicit:
  3443. case tok::kw__Noreturn:
  3444. // alignment-specifier
  3445. case tok::kw__Alignas:
  3446. // friend keyword.
  3447. case tok::kw_friend:
  3448. // static_assert-declaration
  3449. case tok::kw__Static_assert:
  3450. // GNU typeof support.
  3451. case tok::kw_typeof:
  3452. // GNU attributes.
  3453. case tok::kw___attribute:
  3454. // C++11 decltype and constexpr.
  3455. case tok::annot_decltype:
  3456. case tok::kw_constexpr:
  3457. // C11 _Atomic()
  3458. case tok::kw__Atomic:
  3459. return true;
  3460. // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
  3461. case tok::less:
  3462. return getLangOpts().ObjC1;
  3463. // typedef-name
  3464. case tok::annot_typename:
  3465. return !DisambiguatingWithExpression ||
  3466. !isStartOfObjCClassMessageMissingOpenBracket();
  3467. case tok::kw___declspec:
  3468. case tok::kw___cdecl:
  3469. case tok::kw___stdcall:
  3470. case tok::kw___fastcall:
  3471. case tok::kw___thiscall:
  3472. case tok::kw___w64:
  3473. case tok::kw___ptr64:
  3474. case tok::kw___ptr32:
  3475. case tok::kw___forceinline:
  3476. case tok::kw___pascal:
  3477. case tok::kw___unaligned:
  3478. case tok::kw___private:
  3479. case tok::kw___local:
  3480. case tok::kw___global:
  3481. case tok::kw___constant:
  3482. case tok::kw___read_only:
  3483. case tok::kw___read_write:
  3484. case tok::kw___write_only:
  3485. return true;
  3486. }
  3487. }
  3488. bool Parser::isConstructorDeclarator() {
  3489. TentativeParsingAction TPA(*this);
  3490. // Parse the C++ scope specifier.
  3491. CXXScopeSpec SS;
  3492. if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
  3493. /*EnteringContext=*/true)) {
  3494. TPA.Revert();
  3495. return false;
  3496. }
  3497. // Parse the constructor name.
  3498. if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
  3499. // We already know that we have a constructor name; just consume
  3500. // the token.
  3501. ConsumeToken();
  3502. } else {
  3503. TPA.Revert();
  3504. return false;
  3505. }
  3506. // Current class name must be followed by a left parenthesis.
  3507. if (Tok.isNot(tok::l_paren)) {
  3508. TPA.Revert();
  3509. return false;
  3510. }
  3511. ConsumeParen();
  3512. // A right parenthesis, or ellipsis followed by a right parenthesis signals
  3513. // that we have a constructor.
  3514. if (Tok.is(tok::r_paren) ||
  3515. (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
  3516. TPA.Revert();
  3517. return true;
  3518. }
  3519. // If we need to, enter the specified scope.
  3520. DeclaratorScopeObj DeclScopeObj(*this, SS);
  3521. if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
  3522. DeclScopeObj.EnterDeclaratorScope();
  3523. // Optionally skip Microsoft attributes.
  3524. ParsedAttributes Attrs(AttrFactory);
  3525. MaybeParseMicrosoftAttributes(Attrs);
  3526. // Check whether the next token(s) are part of a declaration
  3527. // specifier, in which case we have the start of a parameter and,
  3528. // therefore, we know that this is a constructor.
  3529. bool IsConstructor = false;
  3530. if (isDeclarationSpecifier())
  3531. IsConstructor = true;
  3532. else if (Tok.is(tok::identifier) ||
  3533. (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
  3534. // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
  3535. // This might be a parenthesized member name, but is more likely to
  3536. // be a constructor declaration with an invalid argument type. Keep
  3537. // looking.
  3538. if (Tok.is(tok::annot_cxxscope))
  3539. ConsumeToken();
  3540. ConsumeToken();
  3541. // If this is not a constructor, we must be parsing a declarator,
  3542. // which must have one of the following syntactic forms (see the
  3543. // grammar extract at the start of ParseDirectDeclarator):
  3544. switch (Tok.getKind()) {
  3545. case tok::l_paren:
  3546. // C(X ( int));
  3547. case tok::l_square:
  3548. // C(X [ 5]);
  3549. // C(X [ [attribute]]);
  3550. case tok::coloncolon:
  3551. // C(X :: Y);
  3552. // C(X :: *p);
  3553. case tok::r_paren:
  3554. // C(X )
  3555. // Assume this isn't a constructor, rather than assuming it's a
  3556. // constructor with an unnamed parameter of an ill-formed type.
  3557. break;
  3558. default:
  3559. IsConstructor = true;
  3560. break;
  3561. }
  3562. }
  3563. TPA.Revert();
  3564. return IsConstructor;
  3565. }
  3566. /// ParseTypeQualifierListOpt
  3567. /// type-qualifier-list: [C99 6.7.5]
  3568. /// type-qualifier
  3569. /// [vendor] attributes
  3570. /// [ only if VendorAttributesAllowed=true ]
  3571. /// type-qualifier-list type-qualifier
  3572. /// [vendor] type-qualifier-list attributes
  3573. /// [ only if VendorAttributesAllowed=true ]
  3574. /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
  3575. /// [ only if CXX11AttributesAllowed=true ]
  3576. /// Note: vendor can be GNU, MS, etc.
  3577. ///
  3578. void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
  3579. bool VendorAttributesAllowed,
  3580. bool CXX11AttributesAllowed) {
  3581. if (getLangOpts().CPlusPlus11 && CXX11AttributesAllowed &&
  3582. isCXX11AttributeSpecifier()) {
  3583. ParsedAttributesWithRange attrs(AttrFactory);
  3584. ParseCXX11Attributes(attrs);
  3585. DS.takeAttributesFrom(attrs);
  3586. }
  3587. SourceLocation EndLoc;
  3588. while (1) {
  3589. bool isInvalid = false;
  3590. const char *PrevSpec = 0;
  3591. unsigned DiagID = 0;
  3592. SourceLocation Loc = Tok.getLocation();
  3593. switch (Tok.getKind()) {
  3594. case tok::code_completion:
  3595. Actions.CodeCompleteTypeQualifiers(DS);
  3596. return cutOffParsing();
  3597. case tok::kw_const:
  3598. isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
  3599. getLangOpts());
  3600. break;
  3601. case tok::kw_volatile:
  3602. isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
  3603. getLangOpts());
  3604. break;
  3605. case tok::kw_restrict:
  3606. isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
  3607. getLangOpts());
  3608. break;
  3609. // OpenCL qualifiers:
  3610. case tok::kw_private:
  3611. if (!getLangOpts().OpenCL)
  3612. goto DoneWithTypeQuals;
  3613. case tok::kw___private:
  3614. case tok::kw___global:
  3615. case tok::kw___local:
  3616. case tok::kw___constant:
  3617. case tok::kw___read_only:
  3618. case tok::kw___write_only:
  3619. case tok::kw___read_write:
  3620. ParseOpenCLQualifiers(DS);
  3621. break;
  3622. case tok::kw___w64:
  3623. case tok::kw___ptr64:
  3624. case tok::kw___ptr32:
  3625. case tok::kw___cdecl:
  3626. case tok::kw___stdcall:
  3627. case tok::kw___fastcall:
  3628. case tok::kw___thiscall:
  3629. case tok::kw___unaligned:
  3630. if (VendorAttributesAllowed) {
  3631. ParseMicrosoftTypeAttributes(DS.getAttributes());
  3632. continue;
  3633. }
  3634. goto DoneWithTypeQuals;
  3635. case tok::kw___pascal:
  3636. if (VendorAttributesAllowed) {
  3637. ParseBorlandTypeAttributes(DS.getAttributes());
  3638. continue;
  3639. }
  3640. goto DoneWithTypeQuals;
  3641. case tok::kw___attribute:
  3642. if (VendorAttributesAllowed) {
  3643. ParseGNUAttributes(DS.getAttributes());
  3644. continue; // do *not* consume the next token!
  3645. }
  3646. // otherwise, FALL THROUGH!
  3647. default:
  3648. DoneWithTypeQuals:
  3649. // If this is not a type-qualifier token, we're done reading type
  3650. // qualifiers. First verify that DeclSpec's are consistent.
  3651. DS.Finish(Diags, PP);
  3652. if (EndLoc.isValid())
  3653. DS.SetRangeEnd(EndLoc);
  3654. return;
  3655. }
  3656. // If the specifier combination wasn't legal, issue a diagnostic.
  3657. if (isInvalid) {
  3658. assert(PrevSpec && "Method did not return previous specifier!");
  3659. Diag(Tok, DiagID) << PrevSpec;
  3660. }
  3661. EndLoc = ConsumeToken();
  3662. }
  3663. }
  3664. /// ParseDeclarator - Parse and verify a newly-initialized declarator.
  3665. ///
  3666. void Parser::ParseDeclarator(Declarator &D) {
  3667. /// This implements the 'declarator' production in the C grammar, then checks
  3668. /// for well-formedness and issues diagnostics.
  3669. ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
  3670. }
  3671. static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang) {
  3672. if (Kind == tok::star || Kind == tok::caret)
  3673. return true;
  3674. // We parse rvalue refs in C++03, because otherwise the errors are scary.
  3675. if (!Lang.CPlusPlus)
  3676. return false;
  3677. return Kind == tok::amp || Kind == tok::ampamp;
  3678. }
  3679. /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
  3680. /// is parsed by the function passed to it. Pass null, and the direct-declarator
  3681. /// isn't parsed at all, making this function effectively parse the C++
  3682. /// ptr-operator production.
  3683. ///
  3684. /// If the grammar of this construct is extended, matching changes must also be
  3685. /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
  3686. /// isConstructorDeclarator.
  3687. ///
  3688. /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
  3689. /// [C] pointer[opt] direct-declarator
  3690. /// [C++] direct-declarator
  3691. /// [C++] ptr-operator declarator
  3692. ///
  3693. /// pointer: [C99 6.7.5]
  3694. /// '*' type-qualifier-list[opt]
  3695. /// '*' type-qualifier-list[opt] pointer
  3696. ///
  3697. /// ptr-operator:
  3698. /// '*' cv-qualifier-seq[opt]
  3699. /// '&'
  3700. /// [C++0x] '&&'
  3701. /// [GNU] '&' restrict[opt] attributes[opt]
  3702. /// [GNU?] '&&' restrict[opt] attributes[opt]
  3703. /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
  3704. void Parser::ParseDeclaratorInternal(Declarator &D,
  3705. DirectDeclParseFunction DirectDeclParser) {
  3706. if (Diags.hasAllExtensionsSilenced())
  3707. D.setExtension();
  3708. // C++ member pointers start with a '::' or a nested-name.
  3709. // Member pointers get special handling, since there's no place for the
  3710. // scope spec in the generic path below.
  3711. if (getLangOpts().CPlusPlus &&
  3712. (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
  3713. Tok.is(tok::annot_cxxscope))) {
  3714. bool EnteringContext = D.getContext() == Declarator::FileContext ||
  3715. D.getContext() == Declarator::MemberContext;
  3716. CXXScopeSpec SS;
  3717. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext);
  3718. if (SS.isNotEmpty()) {
  3719. if (Tok.isNot(tok::star)) {
  3720. // The scope spec really belongs to the direct-declarator.
  3721. if (D.mayHaveIdentifier())
  3722. D.getCXXScopeSpec() = SS;
  3723. else
  3724. AnnotateScopeToken(SS, true);
  3725. if (DirectDeclParser)
  3726. (this->*DirectDeclParser)(D);
  3727. return;
  3728. }
  3729. SourceLocation Loc = ConsumeToken();
  3730. D.SetRangeEnd(Loc);
  3731. DeclSpec DS(AttrFactory);
  3732. ParseTypeQualifierListOpt(DS);
  3733. D.ExtendWithDeclSpec(DS);
  3734. // Recurse to parse whatever is left.
  3735. ParseDeclaratorInternal(D, DirectDeclParser);
  3736. // Sema will have to catch (syntactically invalid) pointers into global
  3737. // scope. It has to catch pointers into namespace scope anyway.
  3738. D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
  3739. Loc),
  3740. DS.getAttributes(),
  3741. /* Don't replace range end. */SourceLocation());
  3742. return;
  3743. }
  3744. }
  3745. tok::TokenKind Kind = Tok.getKind();
  3746. // Not a pointer, C++ reference, or block.
  3747. if (!isPtrOperatorToken(Kind, getLangOpts())) {
  3748. if (DirectDeclParser)
  3749. (this->*DirectDeclParser)(D);
  3750. return;
  3751. }
  3752. // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
  3753. // '&&' -> rvalue reference
  3754. SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
  3755. D.SetRangeEnd(Loc);
  3756. if (Kind == tok::star || Kind == tok::caret) {
  3757. // Is a pointer.
  3758. DeclSpec DS(AttrFactory);
  3759. // FIXME: GNU attributes are not allowed here in a new-type-id.
  3760. ParseTypeQualifierListOpt(DS);
  3761. D.ExtendWithDeclSpec(DS);
  3762. // Recursively parse the declarator.
  3763. ParseDeclaratorInternal(D, DirectDeclParser);
  3764. if (Kind == tok::star)
  3765. // Remember that we parsed a pointer type, and remember the type-quals.
  3766. D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
  3767. DS.getConstSpecLoc(),
  3768. DS.getVolatileSpecLoc(),
  3769. DS.getRestrictSpecLoc()),
  3770. DS.getAttributes(),
  3771. SourceLocation());
  3772. else
  3773. // Remember that we parsed a Block type, and remember the type-quals.
  3774. D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
  3775. Loc),
  3776. DS.getAttributes(),
  3777. SourceLocation());
  3778. } else {
  3779. // Is a reference
  3780. DeclSpec DS(AttrFactory);
  3781. // Complain about rvalue references in C++03, but then go on and build
  3782. // the declarator.
  3783. if (Kind == tok::ampamp)
  3784. Diag(Loc, getLangOpts().CPlusPlus11 ?
  3785. diag::warn_cxx98_compat_rvalue_reference :
  3786. diag::ext_rvalue_reference);
  3787. // GNU-style and C++11 attributes are allowed here, as is restrict.
  3788. ParseTypeQualifierListOpt(DS);
  3789. D.ExtendWithDeclSpec(DS);
  3790. // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
  3791. // cv-qualifiers are introduced through the use of a typedef or of a
  3792. // template type argument, in which case the cv-qualifiers are ignored.
  3793. if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
  3794. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3795. Diag(DS.getConstSpecLoc(),
  3796. diag::err_invalid_reference_qualifier_application) << "const";
  3797. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3798. Diag(DS.getVolatileSpecLoc(),
  3799. diag::err_invalid_reference_qualifier_application) << "volatile";
  3800. }
  3801. // Recursively parse the declarator.
  3802. ParseDeclaratorInternal(D, DirectDeclParser);
  3803. if (D.getNumTypeObjects() > 0) {
  3804. // C++ [dcl.ref]p4: There shall be no references to references.
  3805. DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
  3806. if (InnerChunk.Kind == DeclaratorChunk::Reference) {
  3807. if (const IdentifierInfo *II = D.getIdentifier())
  3808. Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
  3809. << II;
  3810. else
  3811. Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
  3812. << "type name";
  3813. // Once we've complained about the reference-to-reference, we
  3814. // can go ahead and build the (technically ill-formed)
  3815. // declarator: reference collapsing will take care of it.
  3816. }
  3817. }
  3818. // Remember that we parsed a reference type. It doesn't have type-quals.
  3819. D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
  3820. Kind == tok::amp),
  3821. DS.getAttributes(),
  3822. SourceLocation());
  3823. }
  3824. }
  3825. static void diagnoseMisplacedEllipsis(Parser &P, Declarator &D,
  3826. SourceLocation EllipsisLoc) {
  3827. if (EllipsisLoc.isValid()) {
  3828. FixItHint Insertion;
  3829. if (!D.getEllipsisLoc().isValid()) {
  3830. Insertion = FixItHint::CreateInsertion(D.getIdentifierLoc(), "...");
  3831. D.setEllipsisLoc(EllipsisLoc);
  3832. }
  3833. P.Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
  3834. << FixItHint::CreateRemoval(EllipsisLoc) << Insertion << !D.hasName();
  3835. }
  3836. }
  3837. /// ParseDirectDeclarator
  3838. /// direct-declarator: [C99 6.7.5]
  3839. /// [C99] identifier
  3840. /// '(' declarator ')'
  3841. /// [GNU] '(' attributes declarator ')'
  3842. /// [C90] direct-declarator '[' constant-expression[opt] ']'
  3843. /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
  3844. /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
  3845. /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
  3846. /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
  3847. /// [C++11] direct-declarator '[' constant-expression[opt] ']'
  3848. /// attribute-specifier-seq[opt]
  3849. /// direct-declarator '(' parameter-type-list ')'
  3850. /// direct-declarator '(' identifier-list[opt] ')'
  3851. /// [GNU] direct-declarator '(' parameter-forward-declarations
  3852. /// parameter-type-list[opt] ')'
  3853. /// [C++] direct-declarator '(' parameter-declaration-clause ')'
  3854. /// cv-qualifier-seq[opt] exception-specification[opt]
  3855. /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
  3856. /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
  3857. /// ref-qualifier[opt] exception-specification[opt]
  3858. /// [C++] declarator-id
  3859. /// [C++11] declarator-id attribute-specifier-seq[opt]
  3860. ///
  3861. /// declarator-id: [C++ 8]
  3862. /// '...'[opt] id-expression
  3863. /// '::'[opt] nested-name-specifier[opt] type-name
  3864. ///
  3865. /// id-expression: [C++ 5.1]
  3866. /// unqualified-id
  3867. /// qualified-id
  3868. ///
  3869. /// unqualified-id: [C++ 5.1]
  3870. /// identifier
  3871. /// operator-function-id
  3872. /// conversion-function-id
  3873. /// '~' class-name
  3874. /// template-id
  3875. ///
  3876. /// Note, any additional constructs added here may need corresponding changes
  3877. /// in isConstructorDeclarator.
  3878. void Parser::ParseDirectDeclarator(Declarator &D) {
  3879. DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
  3880. if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
  3881. // ParseDeclaratorInternal might already have parsed the scope.
  3882. if (D.getCXXScopeSpec().isEmpty()) {
  3883. bool EnteringContext = D.getContext() == Declarator::FileContext ||
  3884. D.getContext() == Declarator::MemberContext;
  3885. ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(),
  3886. EnteringContext);
  3887. }
  3888. if (D.getCXXScopeSpec().isValid()) {
  3889. if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
  3890. // Change the declaration context for name lookup, until this function
  3891. // is exited (and the declarator has been parsed).
  3892. DeclScopeObj.EnterDeclaratorScope();
  3893. }
  3894. // C++0x [dcl.fct]p14:
  3895. // There is a syntactic ambiguity when an ellipsis occurs at the end
  3896. // of a parameter-declaration-clause without a preceding comma. In
  3897. // this case, the ellipsis is parsed as part of the
  3898. // abstract-declarator if the type of the parameter names a template
  3899. // parameter pack that has not been expanded; otherwise, it is parsed
  3900. // as part of the parameter-declaration-clause.
  3901. if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
  3902. !((D.getContext() == Declarator::PrototypeContext ||
  3903. D.getContext() == Declarator::BlockLiteralContext) &&
  3904. NextToken().is(tok::r_paren) &&
  3905. !Actions.containsUnexpandedParameterPacks(D))) {
  3906. SourceLocation EllipsisLoc = ConsumeToken();
  3907. if (isPtrOperatorToken(Tok.getKind(), getLangOpts())) {
  3908. // The ellipsis was put in the wrong place. Recover, and explain to
  3909. // the user what they should have done.
  3910. ParseDeclarator(D);
  3911. diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
  3912. return;
  3913. } else
  3914. D.setEllipsisLoc(EllipsisLoc);
  3915. // The ellipsis can't be followed by a parenthesized declarator. We
  3916. // check for that in ParseParenDeclarator, after we have disambiguated
  3917. // the l_paren token.
  3918. }
  3919. if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
  3920. Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
  3921. // We found something that indicates the start of an unqualified-id.
  3922. // Parse that unqualified-id.
  3923. bool AllowConstructorName;
  3924. if (D.getDeclSpec().hasTypeSpecifier())
  3925. AllowConstructorName = false;
  3926. else if (D.getCXXScopeSpec().isSet())
  3927. AllowConstructorName =
  3928. (D.getContext() == Declarator::FileContext ||
  3929. (D.getContext() == Declarator::MemberContext &&
  3930. D.getDeclSpec().isFriendSpecified()));
  3931. else
  3932. AllowConstructorName = (D.getContext() == Declarator::MemberContext);
  3933. SourceLocation TemplateKWLoc;
  3934. if (ParseUnqualifiedId(D.getCXXScopeSpec(),
  3935. /*EnteringContext=*/true,
  3936. /*AllowDestructorName=*/true,
  3937. AllowConstructorName,
  3938. ParsedType(),
  3939. TemplateKWLoc,
  3940. D.getName()) ||
  3941. // Once we're past the identifier, if the scope was bad, mark the
  3942. // whole declarator bad.
  3943. D.getCXXScopeSpec().isInvalid()) {
  3944. D.SetIdentifier(0, Tok.getLocation());
  3945. D.setInvalidType(true);
  3946. } else {
  3947. // Parsed the unqualified-id; update range information and move along.
  3948. if (D.getSourceRange().getBegin().isInvalid())
  3949. D.SetRangeBegin(D.getName().getSourceRange().getBegin());
  3950. D.SetRangeEnd(D.getName().getSourceRange().getEnd());
  3951. }
  3952. goto PastIdentifier;
  3953. }
  3954. } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
  3955. assert(!getLangOpts().CPlusPlus &&
  3956. "There's a C++-specific check for tok::identifier above");
  3957. assert(Tok.getIdentifierInfo() && "Not an identifier?");
  3958. D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
  3959. ConsumeToken();
  3960. goto PastIdentifier;
  3961. }
  3962. if (Tok.is(tok::l_paren)) {
  3963. // direct-declarator: '(' declarator ')'
  3964. // direct-declarator: '(' attributes declarator ')'
  3965. // Example: 'char (*X)' or 'int (*XX)(void)'
  3966. ParseParenDeclarator(D);
  3967. // If the declarator was parenthesized, we entered the declarator
  3968. // scope when parsing the parenthesized declarator, then exited
  3969. // the scope already. Re-enter the scope, if we need to.
  3970. if (D.getCXXScopeSpec().isSet()) {
  3971. // If there was an error parsing parenthesized declarator, declarator
  3972. // scope may have been entered before. Don't do it again.
  3973. if (!D.isInvalidType() &&
  3974. Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
  3975. // Change the declaration context for name lookup, until this function
  3976. // is exited (and the declarator has been parsed).
  3977. DeclScopeObj.EnterDeclaratorScope();
  3978. }
  3979. } else if (D.mayOmitIdentifier()) {
  3980. // This could be something simple like "int" (in which case the declarator
  3981. // portion is empty), if an abstract-declarator is allowed.
  3982. D.SetIdentifier(0, Tok.getLocation());
  3983. } else {
  3984. if (Tok.getKind() == tok::annot_pragma_parser_crash)
  3985. LLVM_BUILTIN_TRAP;
  3986. if (D.getContext() == Declarator::MemberContext)
  3987. Diag(Tok, diag::err_expected_member_name_or_semi)
  3988. << D.getDeclSpec().getSourceRange();
  3989. else if (getLangOpts().CPlusPlus) {
  3990. if (Tok.is(tok::period) || Tok.is(tok::arrow))
  3991. Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
  3992. else
  3993. Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus;
  3994. } else
  3995. Diag(Tok, diag::err_expected_ident_lparen);
  3996. D.SetIdentifier(0, Tok.getLocation());
  3997. D.setInvalidType(true);
  3998. }
  3999. PastIdentifier:
  4000. assert(D.isPastIdentifier() &&
  4001. "Haven't past the location of the identifier yet?");
  4002. // Don't parse attributes unless we have parsed an unparenthesized name.
  4003. if (D.hasName() && !D.getNumTypeObjects())
  4004. MaybeParseCXX11Attributes(D);
  4005. while (1) {
  4006. if (Tok.is(tok::l_paren)) {
  4007. // Enter function-declaration scope, limiting any declarators to the
  4008. // function prototype scope, including parameter declarators.
  4009. ParseScope PrototypeScope(this,
  4010. Scope::FunctionPrototypeScope|Scope::DeclScope|
  4011. (D.isFunctionDeclaratorAFunctionDeclaration()
  4012. ? Scope::FunctionDeclarationScope : 0));
  4013. // The paren may be part of a C++ direct initializer, eg. "int x(1);".
  4014. // In such a case, check if we actually have a function declarator; if it
  4015. // is not, the declarator has been fully parsed.
  4016. bool IsAmbiguous = false;
  4017. if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
  4018. // The name of the declarator, if any, is tentatively declared within
  4019. // a possible direct initializer.
  4020. TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
  4021. bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
  4022. TentativelyDeclaredIdentifiers.pop_back();
  4023. if (!IsFunctionDecl)
  4024. break;
  4025. }
  4026. ParsedAttributes attrs(AttrFactory);
  4027. BalancedDelimiterTracker T(*this, tok::l_paren);
  4028. T.consumeOpen();
  4029. ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
  4030. PrototypeScope.Exit();
  4031. } else if (Tok.is(tok::l_square)) {
  4032. ParseBracketDeclarator(D);
  4033. } else {
  4034. break;
  4035. }
  4036. }
  4037. }
  4038. /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
  4039. /// only called before the identifier, so these are most likely just grouping
  4040. /// parens for precedence. If we find that these are actually function
  4041. /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
  4042. ///
  4043. /// direct-declarator:
  4044. /// '(' declarator ')'
  4045. /// [GNU] '(' attributes declarator ')'
  4046. /// direct-declarator '(' parameter-type-list ')'
  4047. /// direct-declarator '(' identifier-list[opt] ')'
  4048. /// [GNU] direct-declarator '(' parameter-forward-declarations
  4049. /// parameter-type-list[opt] ')'
  4050. ///
  4051. void Parser::ParseParenDeclarator(Declarator &D) {
  4052. BalancedDelimiterTracker T(*this, tok::l_paren);
  4053. T.consumeOpen();
  4054. assert(!D.isPastIdentifier() && "Should be called before passing identifier");
  4055. // Eat any attributes before we look at whether this is a grouping or function
  4056. // declarator paren. If this is a grouping paren, the attribute applies to
  4057. // the type being built up, for example:
  4058. // int (__attribute__(()) *x)(long y)
  4059. // If this ends up not being a grouping paren, the attribute applies to the
  4060. // first argument, for example:
  4061. // int (__attribute__(()) int x)
  4062. // In either case, we need to eat any attributes to be able to determine what
  4063. // sort of paren this is.
  4064. //
  4065. ParsedAttributes attrs(AttrFactory);
  4066. bool RequiresArg = false;
  4067. if (Tok.is(tok::kw___attribute)) {
  4068. ParseGNUAttributes(attrs);
  4069. // We require that the argument list (if this is a non-grouping paren) be
  4070. // present even if the attribute list was empty.
  4071. RequiresArg = true;
  4072. }
  4073. // Eat any Microsoft extensions.
  4074. ParseMicrosoftTypeAttributes(attrs);
  4075. // Eat any Borland extensions.
  4076. if (Tok.is(tok::kw___pascal))
  4077. ParseBorlandTypeAttributes(attrs);
  4078. // If we haven't past the identifier yet (or where the identifier would be
  4079. // stored, if this is an abstract declarator), then this is probably just
  4080. // grouping parens. However, if this could be an abstract-declarator, then
  4081. // this could also be the start of function arguments (consider 'void()').
  4082. bool isGrouping;
  4083. if (!D.mayOmitIdentifier()) {
  4084. // If this can't be an abstract-declarator, this *must* be a grouping
  4085. // paren, because we haven't seen the identifier yet.
  4086. isGrouping = true;
  4087. } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
  4088. (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
  4089. NextToken().is(tok::r_paren)) || // C++ int(...)
  4090. isDeclarationSpecifier() || // 'int(int)' is a function.
  4091. isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
  4092. // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
  4093. // considered to be a type, not a K&R identifier-list.
  4094. isGrouping = false;
  4095. } else {
  4096. // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
  4097. isGrouping = true;
  4098. }
  4099. // If this is a grouping paren, handle:
  4100. // direct-declarator: '(' declarator ')'
  4101. // direct-declarator: '(' attributes declarator ')'
  4102. if (isGrouping) {
  4103. SourceLocation EllipsisLoc = D.getEllipsisLoc();
  4104. D.setEllipsisLoc(SourceLocation());
  4105. bool hadGroupingParens = D.hasGroupingParens();
  4106. D.setGroupingParens(true);
  4107. ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
  4108. // Match the ')'.
  4109. T.consumeClose();
  4110. D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
  4111. T.getCloseLocation()),
  4112. attrs, T.getCloseLocation());
  4113. D.setGroupingParens(hadGroupingParens);
  4114. // An ellipsis cannot be placed outside parentheses.
  4115. if (EllipsisLoc.isValid())
  4116. diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
  4117. return;
  4118. }
  4119. // Okay, if this wasn't a grouping paren, it must be the start of a function
  4120. // argument list. Recognize that this declarator will never have an
  4121. // identifier (and remember where it would have been), then call into
  4122. // ParseFunctionDeclarator to handle of argument list.
  4123. D.SetIdentifier(0, Tok.getLocation());
  4124. // Enter function-declaration scope, limiting any declarators to the
  4125. // function prototype scope, including parameter declarators.
  4126. ParseScope PrototypeScope(this,
  4127. Scope::FunctionPrototypeScope | Scope::DeclScope |
  4128. (D.isFunctionDeclaratorAFunctionDeclaration()
  4129. ? Scope::FunctionDeclarationScope : 0));
  4130. ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
  4131. PrototypeScope.Exit();
  4132. }
  4133. /// ParseFunctionDeclarator - We are after the identifier and have parsed the
  4134. /// declarator D up to a paren, which indicates that we are parsing function
  4135. /// arguments.
  4136. ///
  4137. /// If FirstArgAttrs is non-null, then the caller parsed those arguments
  4138. /// immediately after the open paren - they should be considered to be the
  4139. /// first argument of a parameter.
  4140. ///
  4141. /// If RequiresArg is true, then the first argument of the function is required
  4142. /// to be present and required to not be an identifier list.
  4143. ///
  4144. /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
  4145. /// (C++11) ref-qualifier[opt], exception-specification[opt],
  4146. /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
  4147. ///
  4148. /// [C++11] exception-specification:
  4149. /// dynamic-exception-specification
  4150. /// noexcept-specification
  4151. ///
  4152. void Parser::ParseFunctionDeclarator(Declarator &D,
  4153. ParsedAttributes &FirstArgAttrs,
  4154. BalancedDelimiterTracker &Tracker,
  4155. bool IsAmbiguous,
  4156. bool RequiresArg) {
  4157. assert(getCurScope()->isFunctionPrototypeScope() &&
  4158. "Should call from a Function scope");
  4159. // lparen is already consumed!
  4160. assert(D.isPastIdentifier() && "Should not call before identifier!");
  4161. // This should be true when the function has typed arguments.
  4162. // Otherwise, it is treated as a K&R-style function.
  4163. bool HasProto = false;
  4164. // Build up an array of information about the parsed arguments.
  4165. SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
  4166. // Remember where we see an ellipsis, if any.
  4167. SourceLocation EllipsisLoc;
  4168. DeclSpec DS(AttrFactory);
  4169. bool RefQualifierIsLValueRef = true;
  4170. SourceLocation RefQualifierLoc;
  4171. SourceLocation ConstQualifierLoc;
  4172. SourceLocation VolatileQualifierLoc;
  4173. ExceptionSpecificationType ESpecType = EST_None;
  4174. SourceRange ESpecRange;
  4175. SmallVector<ParsedType, 2> DynamicExceptions;
  4176. SmallVector<SourceRange, 2> DynamicExceptionRanges;
  4177. ExprResult NoexceptExpr;
  4178. ParsedAttributes FnAttrs(AttrFactory);
  4179. TypeResult TrailingReturnType;
  4180. Actions.ActOnStartFunctionDeclarator();
  4181. /* LocalEndLoc is the end location for the local FunctionTypeLoc.
  4182. EndLoc is the end location for the function declarator.
  4183. They differ for trailing return types. */
  4184. SourceLocation StartLoc, LocalEndLoc, EndLoc;
  4185. SourceLocation LParenLoc, RParenLoc;
  4186. LParenLoc = Tracker.getOpenLocation();
  4187. StartLoc = LParenLoc;
  4188. if (isFunctionDeclaratorIdentifierList()) {
  4189. if (RequiresArg)
  4190. Diag(Tok, diag::err_argument_required_after_attribute);
  4191. ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
  4192. Tracker.consumeClose();
  4193. RParenLoc = Tracker.getCloseLocation();
  4194. LocalEndLoc = RParenLoc;
  4195. EndLoc = RParenLoc;
  4196. } else {
  4197. if (Tok.isNot(tok::r_paren))
  4198. ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc);
  4199. else if (RequiresArg)
  4200. Diag(Tok, diag::err_argument_required_after_attribute);
  4201. HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
  4202. // If we have the closing ')', eat it.
  4203. Tracker.consumeClose();
  4204. RParenLoc = Tracker.getCloseLocation();
  4205. LocalEndLoc = RParenLoc;
  4206. EndLoc = RParenLoc;
  4207. if (getLangOpts().CPlusPlus) {
  4208. // FIXME: Accept these components in any order, and produce fixits to
  4209. // correct the order if the user gets it wrong. Ideally we should deal
  4210. // with the virt-specifier-seq and pure-specifier in the same way.
  4211. // Parse cv-qualifier-seq[opt].
  4212. ParseTypeQualifierListOpt(DS, false /*no attributes*/, false);
  4213. if (!DS.getSourceRange().getEnd().isInvalid()) {
  4214. EndLoc = DS.getSourceRange().getEnd();
  4215. ConstQualifierLoc = DS.getConstSpecLoc();
  4216. VolatileQualifierLoc = DS.getVolatileSpecLoc();
  4217. }
  4218. // Parse ref-qualifier[opt].
  4219. if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
  4220. Diag(Tok, getLangOpts().CPlusPlus11 ?
  4221. diag::warn_cxx98_compat_ref_qualifier :
  4222. diag::ext_ref_qualifier);
  4223. RefQualifierIsLValueRef = Tok.is(tok::amp);
  4224. RefQualifierLoc = ConsumeToken();
  4225. EndLoc = RefQualifierLoc;
  4226. }
  4227. // C++11 [expr.prim.general]p3:
  4228. // If a declaration declares a member function or member function
  4229. // template of a class X, the expression this is a prvalue of type
  4230. // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
  4231. // and the end of the function-definition, member-declarator, or
  4232. // declarator.
  4233. bool IsCXX11MemberFunction =
  4234. getLangOpts().CPlusPlus11 &&
  4235. (D.getContext() == Declarator::MemberContext ||
  4236. (D.getContext() == Declarator::FileContext &&
  4237. D.getCXXScopeSpec().isValid() &&
  4238. Actions.CurContext->isRecord()));
  4239. Sema::CXXThisScopeRAII ThisScope(Actions,
  4240. dyn_cast<CXXRecordDecl>(Actions.CurContext),
  4241. DS.getTypeQualifiers() |
  4242. (D.getDeclSpec().isConstexprSpecified()
  4243. ? Qualifiers::Const : 0),
  4244. IsCXX11MemberFunction);
  4245. // Parse exception-specification[opt].
  4246. ESpecType = tryParseExceptionSpecification(ESpecRange,
  4247. DynamicExceptions,
  4248. DynamicExceptionRanges,
  4249. NoexceptExpr);
  4250. if (ESpecType != EST_None)
  4251. EndLoc = ESpecRange.getEnd();
  4252. // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
  4253. // after the exception-specification.
  4254. MaybeParseCXX11Attributes(FnAttrs);
  4255. // Parse trailing-return-type[opt].
  4256. LocalEndLoc = EndLoc;
  4257. if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
  4258. Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
  4259. if (D.getDeclSpec().getTypeSpecType() == TST_auto)
  4260. StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
  4261. LocalEndLoc = Tok.getLocation();
  4262. SourceRange Range;
  4263. TrailingReturnType = ParseTrailingReturnType(Range);
  4264. EndLoc = Range.getEnd();
  4265. }
  4266. }
  4267. }
  4268. // Remember that we parsed a function type, and remember the attributes.
  4269. D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
  4270. IsAmbiguous,
  4271. LParenLoc,
  4272. ParamInfo.data(), ParamInfo.size(),
  4273. EllipsisLoc, RParenLoc,
  4274. DS.getTypeQualifiers(),
  4275. RefQualifierIsLValueRef,
  4276. RefQualifierLoc, ConstQualifierLoc,
  4277. VolatileQualifierLoc,
  4278. /*MutableLoc=*/SourceLocation(),
  4279. ESpecType, ESpecRange.getBegin(),
  4280. DynamicExceptions.data(),
  4281. DynamicExceptionRanges.data(),
  4282. DynamicExceptions.size(),
  4283. NoexceptExpr.isUsable() ?
  4284. NoexceptExpr.get() : 0,
  4285. StartLoc, LocalEndLoc, D,
  4286. TrailingReturnType),
  4287. FnAttrs, EndLoc);
  4288. Actions.ActOnEndFunctionDeclarator();
  4289. }
  4290. /// isFunctionDeclaratorIdentifierList - This parameter list may have an
  4291. /// identifier list form for a K&R-style function: void foo(a,b,c)
  4292. ///
  4293. /// Note that identifier-lists are only allowed for normal declarators, not for
  4294. /// abstract-declarators.
  4295. bool Parser::isFunctionDeclaratorIdentifierList() {
  4296. return !getLangOpts().CPlusPlus
  4297. && Tok.is(tok::identifier)
  4298. && !TryAltiVecVectorToken()
  4299. // K&R identifier lists can't have typedefs as identifiers, per C99
  4300. // 6.7.5.3p11.
  4301. && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
  4302. // Identifier lists follow a really simple grammar: the identifiers can
  4303. // be followed *only* by a ", identifier" or ")". However, K&R
  4304. // identifier lists are really rare in the brave new modern world, and
  4305. // it is very common for someone to typo a type in a non-K&R style
  4306. // list. If we are presented with something like: "void foo(intptr x,
  4307. // float y)", we don't want to start parsing the function declarator as
  4308. // though it is a K&R style declarator just because intptr is an
  4309. // invalid type.
  4310. //
  4311. // To handle this, we check to see if the token after the first
  4312. // identifier is a "," or ")". Only then do we parse it as an
  4313. // identifier list.
  4314. && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
  4315. }
  4316. /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
  4317. /// we found a K&R-style identifier list instead of a typed parameter list.
  4318. ///
  4319. /// After returning, ParamInfo will hold the parsed parameters.
  4320. ///
  4321. /// identifier-list: [C99 6.7.5]
  4322. /// identifier
  4323. /// identifier-list ',' identifier
  4324. ///
  4325. void Parser::ParseFunctionDeclaratorIdentifierList(
  4326. Declarator &D,
  4327. SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo) {
  4328. // If there was no identifier specified for the declarator, either we are in
  4329. // an abstract-declarator, or we are in a parameter declarator which was found
  4330. // to be abstract. In abstract-declarators, identifier lists are not valid:
  4331. // diagnose this.
  4332. if (!D.getIdentifier())
  4333. Diag(Tok, diag::ext_ident_list_in_param);
  4334. // Maintain an efficient lookup of params we have seen so far.
  4335. llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
  4336. while (1) {
  4337. // If this isn't an identifier, report the error and skip until ')'.
  4338. if (Tok.isNot(tok::identifier)) {
  4339. Diag(Tok, diag::err_expected_ident);
  4340. SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true);
  4341. // Forget we parsed anything.
  4342. ParamInfo.clear();
  4343. return;
  4344. }
  4345. IdentifierInfo *ParmII = Tok.getIdentifierInfo();
  4346. // Reject 'typedef int y; int test(x, y)', but continue parsing.
  4347. if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
  4348. Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
  4349. // Verify that the argument identifier has not already been mentioned.
  4350. if (!ParamsSoFar.insert(ParmII)) {
  4351. Diag(Tok, diag::err_param_redefinition) << ParmII;
  4352. } else {
  4353. // Remember this identifier in ParamInfo.
  4354. ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
  4355. Tok.getLocation(),
  4356. 0));
  4357. }
  4358. // Eat the identifier.
  4359. ConsumeToken();
  4360. // The list continues if we see a comma.
  4361. if (Tok.isNot(tok::comma))
  4362. break;
  4363. ConsumeToken();
  4364. }
  4365. }
  4366. /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
  4367. /// after the opening parenthesis. This function will not parse a K&R-style
  4368. /// identifier list.
  4369. ///
  4370. /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
  4371. /// caller parsed those arguments immediately after the open paren - they should
  4372. /// be considered to be part of the first parameter.
  4373. ///
  4374. /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
  4375. /// be the location of the ellipsis, if any was parsed.
  4376. ///
  4377. /// parameter-type-list: [C99 6.7.5]
  4378. /// parameter-list
  4379. /// parameter-list ',' '...'
  4380. /// [C++] parameter-list '...'
  4381. ///
  4382. /// parameter-list: [C99 6.7.5]
  4383. /// parameter-declaration
  4384. /// parameter-list ',' parameter-declaration
  4385. ///
  4386. /// parameter-declaration: [C99 6.7.5]
  4387. /// declaration-specifiers declarator
  4388. /// [C++] declaration-specifiers declarator '=' assignment-expression
  4389. /// [C++11] initializer-clause
  4390. /// [GNU] declaration-specifiers declarator attributes
  4391. /// declaration-specifiers abstract-declarator[opt]
  4392. /// [C++] declaration-specifiers abstract-declarator[opt]
  4393. /// '=' assignment-expression
  4394. /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
  4395. /// [C++11] attribute-specifier-seq parameter-declaration
  4396. ///
  4397. void Parser::ParseParameterDeclarationClause(
  4398. Declarator &D,
  4399. ParsedAttributes &FirstArgAttrs,
  4400. SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo,
  4401. SourceLocation &EllipsisLoc) {
  4402. while (1) {
  4403. if (Tok.is(tok::ellipsis)) {
  4404. // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
  4405. // before deciding this was a parameter-declaration-clause.
  4406. EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
  4407. break;
  4408. }
  4409. // Parse the declaration-specifiers.
  4410. // Just use the ParsingDeclaration "scope" of the declarator.
  4411. DeclSpec DS(AttrFactory);
  4412. // Parse any C++11 attributes.
  4413. MaybeParseCXX11Attributes(DS.getAttributes());
  4414. // Skip any Microsoft attributes before a param.
  4415. MaybeParseMicrosoftAttributes(DS.getAttributes());
  4416. SourceLocation DSStart = Tok.getLocation();
  4417. // If the caller parsed attributes for the first argument, add them now.
  4418. // Take them so that we only apply the attributes to the first parameter.
  4419. // FIXME: If we can leave the attributes in the token stream somehow, we can
  4420. // get rid of a parameter (FirstArgAttrs) and this statement. It might be
  4421. // too much hassle.
  4422. DS.takeAttributesFrom(FirstArgAttrs);
  4423. ParseDeclarationSpecifiers(DS);
  4424. // Parse the declarator. This is "PrototypeContext", because we must
  4425. // accept either 'declarator' or 'abstract-declarator' here.
  4426. Declarator ParmDecl(DS, Declarator::PrototypeContext);
  4427. ParseDeclarator(ParmDecl);
  4428. // Parse GNU attributes, if present.
  4429. MaybeParseGNUAttributes(ParmDecl);
  4430. // Remember this parsed parameter in ParamInfo.
  4431. IdentifierInfo *ParmII = ParmDecl.getIdentifier();
  4432. // DefArgToks is used when the parsing of default arguments needs
  4433. // to be delayed.
  4434. CachedTokens *DefArgToks = 0;
  4435. // If no parameter was specified, verify that *something* was specified,
  4436. // otherwise we have a missing type and identifier.
  4437. if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
  4438. ParmDecl.getNumTypeObjects() == 0) {
  4439. // Completely missing, emit error.
  4440. Diag(DSStart, diag::err_missing_param);
  4441. } else {
  4442. // Otherwise, we have something. Add it and let semantic analysis try
  4443. // to grok it and add the result to the ParamInfo we are building.
  4444. // Inform the actions module about the parameter declarator, so it gets
  4445. // added to the current scope.
  4446. Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
  4447. // Parse the default argument, if any. We parse the default
  4448. // arguments in all dialects; the semantic analysis in
  4449. // ActOnParamDefaultArgument will reject the default argument in
  4450. // C.
  4451. if (Tok.is(tok::equal)) {
  4452. SourceLocation EqualLoc = Tok.getLocation();
  4453. // Parse the default argument
  4454. if (D.getContext() == Declarator::MemberContext) {
  4455. // If we're inside a class definition, cache the tokens
  4456. // corresponding to the default argument. We'll actually parse
  4457. // them when we see the end of the class definition.
  4458. // FIXME: Can we use a smart pointer for Toks?
  4459. DefArgToks = new CachedTokens;
  4460. if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
  4461. /*StopAtSemi=*/true,
  4462. /*ConsumeFinalToken=*/false)) {
  4463. delete DefArgToks;
  4464. DefArgToks = 0;
  4465. Actions.ActOnParamDefaultArgumentError(Param);
  4466. } else {
  4467. // Mark the end of the default argument so that we know when to
  4468. // stop when we parse it later on.
  4469. Token DefArgEnd;
  4470. DefArgEnd.startToken();
  4471. DefArgEnd.setKind(tok::cxx_defaultarg_end);
  4472. DefArgEnd.setLocation(Tok.getLocation());
  4473. DefArgToks->push_back(DefArgEnd);
  4474. Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
  4475. (*DefArgToks)[1].getLocation());
  4476. }
  4477. } else {
  4478. // Consume the '='.
  4479. ConsumeToken();
  4480. // The argument isn't actually potentially evaluated unless it is
  4481. // used.
  4482. EnterExpressionEvaluationContext Eval(Actions,
  4483. Sema::PotentiallyEvaluatedIfUsed,
  4484. Param);
  4485. ExprResult DefArgResult;
  4486. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  4487. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  4488. DefArgResult = ParseBraceInitializer();
  4489. } else
  4490. DefArgResult = ParseAssignmentExpression();
  4491. if (DefArgResult.isInvalid()) {
  4492. Actions.ActOnParamDefaultArgumentError(Param);
  4493. SkipUntil(tok::comma, tok::r_paren, true, true);
  4494. } else {
  4495. // Inform the actions module about the default argument
  4496. Actions.ActOnParamDefaultArgument(Param, EqualLoc,
  4497. DefArgResult.take());
  4498. }
  4499. }
  4500. }
  4501. ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
  4502. ParmDecl.getIdentifierLoc(), Param,
  4503. DefArgToks));
  4504. }
  4505. // If the next token is a comma, consume it and keep reading arguments.
  4506. if (Tok.isNot(tok::comma)) {
  4507. if (Tok.is(tok::ellipsis)) {
  4508. EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
  4509. if (!getLangOpts().CPlusPlus) {
  4510. // We have ellipsis without a preceding ',', which is ill-formed
  4511. // in C. Complain and provide the fix.
  4512. Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
  4513. << FixItHint::CreateInsertion(EllipsisLoc, ", ");
  4514. }
  4515. }
  4516. break;
  4517. }
  4518. // Consume the comma.
  4519. ConsumeToken();
  4520. }
  4521. }
  4522. /// [C90] direct-declarator '[' constant-expression[opt] ']'
  4523. /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
  4524. /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
  4525. /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
  4526. /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
  4527. /// [C++11] direct-declarator '[' constant-expression[opt] ']'
  4528. /// attribute-specifier-seq[opt]
  4529. void Parser::ParseBracketDeclarator(Declarator &D) {
  4530. if (CheckProhibitedCXX11Attribute())
  4531. return;
  4532. BalancedDelimiterTracker T(*this, tok::l_square);
  4533. T.consumeOpen();
  4534. // C array syntax has many features, but by-far the most common is [] and [4].
  4535. // This code does a fast path to handle some of the most obvious cases.
  4536. if (Tok.getKind() == tok::r_square) {
  4537. T.consumeClose();
  4538. ParsedAttributes attrs(AttrFactory);
  4539. MaybeParseCXX11Attributes(attrs);
  4540. // Remember that we parsed the empty array type.
  4541. ExprResult NumElements;
  4542. D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
  4543. T.getOpenLocation(),
  4544. T.getCloseLocation()),
  4545. attrs, T.getCloseLocation());
  4546. return;
  4547. } else if (Tok.getKind() == tok::numeric_constant &&
  4548. GetLookAheadToken(1).is(tok::r_square)) {
  4549. // [4] is very common. Parse the numeric constant expression.
  4550. ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
  4551. ConsumeToken();
  4552. T.consumeClose();
  4553. ParsedAttributes attrs(AttrFactory);
  4554. MaybeParseCXX11Attributes(attrs);
  4555. // Remember that we parsed a array type, and remember its features.
  4556. D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
  4557. ExprRes.release(),
  4558. T.getOpenLocation(),
  4559. T.getCloseLocation()),
  4560. attrs, T.getCloseLocation());
  4561. return;
  4562. }
  4563. // If valid, this location is the position where we read the 'static' keyword.
  4564. SourceLocation StaticLoc;
  4565. if (Tok.is(tok::kw_static))
  4566. StaticLoc = ConsumeToken();
  4567. // If there is a type-qualifier-list, read it now.
  4568. // Type qualifiers in an array subscript are a C99 feature.
  4569. DeclSpec DS(AttrFactory);
  4570. ParseTypeQualifierListOpt(DS, false /*no attributes*/);
  4571. // If we haven't already read 'static', check to see if there is one after the
  4572. // type-qualifier-list.
  4573. if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
  4574. StaticLoc = ConsumeToken();
  4575. // Handle "direct-declarator [ type-qual-list[opt] * ]".
  4576. bool isStar = false;
  4577. ExprResult NumElements;
  4578. // Handle the case where we have '[*]' as the array size. However, a leading
  4579. // star could be the start of an expression, for example 'X[*p + 4]'. Verify
  4580. // the token after the star is a ']'. Since stars in arrays are
  4581. // infrequent, use of lookahead is not costly here.
  4582. if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
  4583. ConsumeToken(); // Eat the '*'.
  4584. if (StaticLoc.isValid()) {
  4585. Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
  4586. StaticLoc = SourceLocation(); // Drop the static.
  4587. }
  4588. isStar = true;
  4589. } else if (Tok.isNot(tok::r_square)) {
  4590. // Note, in C89, this production uses the constant-expr production instead
  4591. // of assignment-expr. The only difference is that assignment-expr allows
  4592. // things like '=' and '*='. Sema rejects these in C89 mode because they
  4593. // are not i-c-e's, so we don't need to distinguish between the two here.
  4594. // Parse the constant-expression or assignment-expression now (depending
  4595. // on dialect).
  4596. if (getLangOpts().CPlusPlus) {
  4597. NumElements = ParseConstantExpression();
  4598. } else {
  4599. EnterExpressionEvaluationContext Unevaluated(Actions,
  4600. Sema::ConstantEvaluated);
  4601. NumElements = ParseAssignmentExpression();
  4602. }
  4603. }
  4604. // If there was an error parsing the assignment-expression, recover.
  4605. if (NumElements.isInvalid()) {
  4606. D.setInvalidType(true);
  4607. // If the expression was invalid, skip it.
  4608. SkipUntil(tok::r_square);
  4609. return;
  4610. }
  4611. T.consumeClose();
  4612. ParsedAttributes attrs(AttrFactory);
  4613. MaybeParseCXX11Attributes(attrs);
  4614. // Remember that we parsed a array type, and remember its features.
  4615. D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
  4616. StaticLoc.isValid(), isStar,
  4617. NumElements.release(),
  4618. T.getOpenLocation(),
  4619. T.getCloseLocation()),
  4620. attrs, T.getCloseLocation());
  4621. }
  4622. /// [GNU] typeof-specifier:
  4623. /// typeof ( expressions )
  4624. /// typeof ( type-name )
  4625. /// [GNU/C++] typeof unary-expression
  4626. ///
  4627. void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
  4628. assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
  4629. Token OpTok = Tok;
  4630. SourceLocation StartLoc = ConsumeToken();
  4631. const bool hasParens = Tok.is(tok::l_paren);
  4632. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
  4633. Sema::ReuseLambdaContextDecl);
  4634. bool isCastExpr;
  4635. ParsedType CastTy;
  4636. SourceRange CastRange;
  4637. ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
  4638. CastTy, CastRange);
  4639. if (hasParens)
  4640. DS.setTypeofParensRange(CastRange);
  4641. if (CastRange.getEnd().isInvalid())
  4642. // FIXME: Not accurate, the range gets one token more than it should.
  4643. DS.SetRangeEnd(Tok.getLocation());
  4644. else
  4645. DS.SetRangeEnd(CastRange.getEnd());
  4646. if (isCastExpr) {
  4647. if (!CastTy) {
  4648. DS.SetTypeSpecError();
  4649. return;
  4650. }
  4651. const char *PrevSpec = 0;
  4652. unsigned DiagID;
  4653. // Check for duplicate type specifiers (e.g. "int typeof(int)").
  4654. if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
  4655. DiagID, CastTy))
  4656. Diag(StartLoc, DiagID) << PrevSpec;
  4657. return;
  4658. }
  4659. // If we get here, the operand to the typeof was an expresion.
  4660. if (Operand.isInvalid()) {
  4661. DS.SetTypeSpecError();
  4662. return;
  4663. }
  4664. // We might need to transform the operand if it is potentially evaluated.
  4665. Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
  4666. if (Operand.isInvalid()) {
  4667. DS.SetTypeSpecError();
  4668. return;
  4669. }
  4670. const char *PrevSpec = 0;
  4671. unsigned DiagID;
  4672. // Check for duplicate type specifiers (e.g. "int typeof(int)").
  4673. if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
  4674. DiagID, Operand.get()))
  4675. Diag(StartLoc, DiagID) << PrevSpec;
  4676. }
  4677. /// [C11] atomic-specifier:
  4678. /// _Atomic ( type-name )
  4679. ///
  4680. void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
  4681. assert(Tok.is(tok::kw__Atomic) && "Not an atomic specifier");
  4682. SourceLocation StartLoc = ConsumeToken();
  4683. BalancedDelimiterTracker T(*this, tok::l_paren);
  4684. if (T.expectAndConsume(diag::err_expected_lparen_after, "_Atomic")) {
  4685. SkipUntil(tok::r_paren);
  4686. return;
  4687. }
  4688. TypeResult Result = ParseTypeName();
  4689. if (Result.isInvalid()) {
  4690. SkipUntil(tok::r_paren);
  4691. return;
  4692. }
  4693. // Match the ')'
  4694. T.consumeClose();
  4695. if (T.getCloseLocation().isInvalid())
  4696. return;
  4697. DS.setTypeofParensRange(T.getRange());
  4698. DS.SetRangeEnd(T.getCloseLocation());
  4699. const char *PrevSpec = 0;
  4700. unsigned DiagID;
  4701. if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
  4702. DiagID, Result.release()))
  4703. Diag(StartLoc, DiagID) << PrevSpec;
  4704. }
  4705. /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
  4706. /// from TryAltiVecVectorToken.
  4707. bool Parser::TryAltiVecVectorTokenOutOfLine() {
  4708. Token Next = NextToken();
  4709. switch (Next.getKind()) {
  4710. default: return false;
  4711. case tok::kw_short:
  4712. case tok::kw_long:
  4713. case tok::kw_signed:
  4714. case tok::kw_unsigned:
  4715. case tok::kw_void:
  4716. case tok::kw_char:
  4717. case tok::kw_int:
  4718. case tok::kw_float:
  4719. case tok::kw_double:
  4720. case tok::kw_bool:
  4721. case tok::kw___pixel:
  4722. Tok.setKind(tok::kw___vector);
  4723. return true;
  4724. case tok::identifier:
  4725. if (Next.getIdentifierInfo() == Ident_pixel) {
  4726. Tok.setKind(tok::kw___vector);
  4727. return true;
  4728. }
  4729. return false;
  4730. }
  4731. }
  4732. bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
  4733. const char *&PrevSpec, unsigned &DiagID,
  4734. bool &isInvalid) {
  4735. if (Tok.getIdentifierInfo() == Ident_vector) {
  4736. Token Next = NextToken();
  4737. switch (Next.getKind()) {
  4738. case tok::kw_short:
  4739. case tok::kw_long:
  4740. case tok::kw_signed:
  4741. case tok::kw_unsigned:
  4742. case tok::kw_void:
  4743. case tok::kw_char:
  4744. case tok::kw_int:
  4745. case tok::kw_float:
  4746. case tok::kw_double:
  4747. case tok::kw_bool:
  4748. case tok::kw___pixel:
  4749. isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
  4750. return true;
  4751. case tok::identifier:
  4752. if (Next.getIdentifierInfo() == Ident_pixel) {
  4753. isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
  4754. return true;
  4755. }
  4756. break;
  4757. default:
  4758. break;
  4759. }
  4760. } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
  4761. DS.isTypeAltiVecVector()) {
  4762. isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
  4763. return true;
  4764. }
  4765. return false;
  4766. }