1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893 |
- #include <stdio.h>
- #include <stdarg.h>
- #include <string.h>
- #include <ctype.h>
- #include <stdlib.h>
- #include <assert.h>
- #define ISSPACE(X) isspace((unsigned char)(X))
- #define ISDIGIT(X) isdigit((unsigned char)(X))
- #define ISALNUM(X) isalnum((unsigned char)(X))
- #define ISALPHA(X) isalpha((unsigned char)(X))
- #define ISUPPER(X) isupper((unsigned char)(X))
- #define ISLOWER(X) islower((unsigned char)(X))
- #ifndef __WIN32__
- # if defined(_WIN32) || defined(WIN32)
- # define __WIN32__
- # endif
- #endif
- #ifdef __WIN32__
- #ifdef __cplusplus
- extern "C" {
- #endif
- extern int access(const char *path, int mode);
- #ifdef __cplusplus
- }
- #endif
- #else
- #include <unistd.h>
- #endif
- #define PRIVATE
- #ifdef TEST
- #define MAXRHS 5
- #else
- #define MAXRHS 1000
- #endif
- extern void memory_error();
- static int showPrecedenceConflict = 0;
- static char *msort(char*,char**,int(*)(const char*,const char*));
- #define lemonStrlen(X) ((int)strlen(X))
- static void lemon_addtext(
- char *zBuf,
- int *pnUsed,
- const char *zIn,
- int nIn,
- int iWidth
- ){
- if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
- while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
- if( nIn==0 ) return;
- memcpy(&zBuf[*pnUsed], zIn, nIn);
- *pnUsed += nIn;
- while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
- zBuf[*pnUsed] = 0;
- }
- static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
- int i, j, k, c;
- int nUsed = 0;
- const char *z;
- char zTemp[50];
- str[0] = 0;
- for(i=j=0; (c = zFormat[i])!=0; i++){
- if( c=='%' ){
- int iWidth = 0;
- lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
- c = zFormat[++i];
- if( ISDIGIT(c) || (c=='-' && ISDIGIT(zFormat[i+1])) ){
- if( c=='-' ) i++;
- while( ISDIGIT(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
- if( c=='-' ) iWidth = -iWidth;
- c = zFormat[i];
- }
- if( c=='d' ){
- int v = va_arg(ap, int);
- if( v<0 ){
- lemon_addtext(str, &nUsed, "-", 1, iWidth);
- v = -v;
- }else if( v==0 ){
- lemon_addtext(str, &nUsed, "0", 1, iWidth);
- }
- k = 0;
- while( v>0 ){
- k++;
- zTemp[sizeof(zTemp)-k] = (v%10) + '0';
- v /= 10;
- }
- lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
- }else if( c=='s' ){
- z = va_arg(ap, const char*);
- lemon_addtext(str, &nUsed, z, -1, iWidth);
- }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
- i += 2;
- k = va_arg(ap, int);
- z = va_arg(ap, const char*);
- lemon_addtext(str, &nUsed, z, k, iWidth);
- }else if( c=='%' ){
- lemon_addtext(str, &nUsed, "%", 1, 0);
- }else{
- fprintf(stderr, "illegal format\n");
- exit(1);
- }
- j = i+1;
- }
- }
- lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
- return nUsed;
- }
- static int lemon_sprintf(char *str, const char *format, ...){
- va_list ap;
- int rc;
- va_start(ap, format);
- rc = lemon_vsprintf(str, format, ap);
- va_end(ap);
- return rc;
- }
- static void lemon_strcpy(char *dest, const char *src){
- while( (*(dest++) = *(src++))!=0 ){}
- }
- static void lemon_strcat(char *dest, const char *src){
- while( *dest ) dest++;
- lemon_strcpy(dest, src);
- }
- struct rule;
- struct lemon;
- struct action;
- static struct action *Action_new(void);
- static struct action *Action_sort(struct action *);
- void FindRulePrecedences(struct lemon*);
- void FindFirstSets(struct lemon*);
- void FindStates(struct lemon*);
- void FindLinks(struct lemon*);
- void FindFollowSets(struct lemon*);
- void FindActions(struct lemon*);
- void Configlist_init(void);
- struct config *Configlist_add(struct rule *, int);
- struct config *Configlist_addbasis(struct rule *, int);
- void Configlist_closure(struct lemon *);
- void Configlist_sort(void);
- void Configlist_sortbasis(void);
- struct config *Configlist_return(void);
- struct config *Configlist_basis(void);
- void Configlist_eat(struct config *);
- void Configlist_reset(void);
- void ErrorMsg(const char *, int,const char *, ...);
- enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
- OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
- struct s_options {
- enum option_type type;
- const char *label;
- char *arg;
- const char *message;
- };
- int OptInit(char**,struct s_options*,FILE*);
- int OptNArgs(void);
- char *OptArg(int);
- void OptErr(int);
- void OptPrint(void);
- void Parse(struct lemon *lemp);
- struct plink *Plink_new(void);
- void Plink_add(struct plink **, struct config *);
- void Plink_copy(struct plink **, struct plink *);
- void Plink_delete(struct plink *);
- void Reprint(struct lemon *);
- void ReportOutput(struct lemon *);
- void ReportTable(struct lemon *, int, int);
- void ReportHeader(struct lemon *);
- void CompressTables(struct lemon *);
- void ResortStates(struct lemon *);
- void SetSize(int);
- char *SetNew(void);
- void SetFree(char*);
- int SetAdd(char*,int);
- int SetUnion(char *,char *);
- #define SetFind(X,Y) (X[Y])
- typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
- enum symbol_type {
- TERMINAL,
- NONTERMINAL,
- MULTITERMINAL
- };
- enum e_assoc {
- LEFT,
- RIGHT,
- NONE,
- UNK
- };
- struct symbol {
- const char *name;
- int index;
- enum symbol_type type;
- struct rule *rule;
- struct symbol *fallback;
- int prec;
- enum e_assoc assoc;
- char *firstset;
- Boolean lambda;
- int useCnt;
- char *destructor;
- int destLineno;
- char *datatype;
- int dtnum;
- int bContent;
-
- int nsubsym;
- struct symbol **subsym;
- };
- struct rule {
- struct symbol *lhs;
- const char *lhsalias;
- int lhsStart;
- int ruleline;
- int nrhs;
- struct symbol **rhs;
- const char **rhsalias;
- int line;
- const char *code;
- const char *codePrefix;
- const char *codeSuffix;
- struct symbol *precsym;
- int index;
- int iRule;
- Boolean noCode;
- Boolean codeEmitted;
- Boolean canReduce;
- Boolean doesReduce;
- Boolean neverReduce;
- struct rule *nextlhs;
- struct rule *next;
- };
- enum cfgstatus {
- COMPLETE,
- INCOMPLETE
- };
- struct config {
- struct rule *rp;
- int dot;
- char *fws;
- struct plink *fplp;
- struct plink *bplp;
- struct state *stp;
- enum cfgstatus status;
- struct config *next;
- struct config *bp;
- };
- enum e_action {
- SHIFT,
- ACCEPT,
- REDUCE,
- ERROR,
- SSCONFLICT,
- SRCONFLICT,
- RRCONFLICT,
- SH_RESOLVED,
- RD_RESOLVED,
- NOT_USED,
- SHIFTREDUCE
- };
- struct action {
- struct symbol *sp;
- enum e_action type;
- union {
- struct state *stp;
- struct rule *rp;
- } x;
- struct symbol *spOpt;
- struct action *next;
- struct action *collide;
- };
- struct state {
- struct config *bp;
- struct config *cfp;
- int statenum;
- struct action *ap;
- int nTknAct, nNtAct;
- int iTknOfst, iNtOfst;
- int iDfltReduce;
- struct rule *pDfltReduce;
- int autoReduce;
- };
- #define NO_OFFSET (-2147483647)
- struct plink {
- struct config *cfp;
- struct plink *next;
- };
- struct lemon {
- struct state **sorted;
- struct rule *rule;
- struct rule *startRule;
- int nstate;
- int nxstate;
- int nrule;
- int nruleWithAction;
- int nsymbol;
- int nterminal;
- int minShiftReduce;
- int errAction;
- int accAction;
- int noAction;
- int minReduce;
- int maxAction;
- struct symbol **symbols;
- int errorcnt;
- struct symbol *errsym;
- struct symbol *wildcard;
- char *name;
- char *arg;
- char *ctx;
- char *tokentype;
- char *vartype;
- char *start;
- char *stacksize;
- char *include;
- char *error;
- char *overflow;
- char *failure;
- char *accept;
- char *extracode;
- char *tokendest;
- char *vardest;
- char *filename;
- char *outname;
- char *tokenprefix;
- int nconflict;
- int nactiontab;
- int nlookaheadtab;
- int tablesize;
- int basisflag;
- int printPreprocessed;
- int has_fallback;
- int nolinenosflag;
- char *argv0;
- };
- #define MemoryCheck(X) if((X)==0){ \
- extern void memory_error(); \
- memory_error(); \
- }
- const char *Strsafe(const char *);
- void Strsafe_init(void);
- int Strsafe_insert(const char *);
- const char *Strsafe_find(const char *);
- struct symbol *Symbol_new(const char *);
- int Symbolcmpp(const void *, const void *);
- void Symbol_init(void);
- int Symbol_insert(struct symbol *, const char *);
- struct symbol *Symbol_find(const char *);
- struct symbol *Symbol_Nth(int);
- int Symbol_count(void);
- struct symbol **Symbol_arrayof(void);
- int Configcmp(const char *, const char *);
- struct state *State_new(void);
- void State_init(void);
- int State_insert(struct state *, struct config *);
- struct state *State_find(struct config *);
- struct state **State_arrayof(void);
- void Configtable_init(void);
- int Configtable_insert(struct config *);
- struct config *Configtable_find(struct config *);
- void Configtable_clear(int(*)(struct config *));
- static struct action *Action_new(void){
- static struct action *actionfreelist = 0;
- struct action *newaction;
- if( actionfreelist==0 ){
- int i;
- int amt = 100;
- actionfreelist = (struct action *)calloc(amt, sizeof(struct action));
- if( actionfreelist==0 ){
- fprintf(stderr,"Unable to allocate memory for a new parser action.");
- exit(1);
- }
- for(i=0; i<amt-1; i++) actionfreelist[i].next = &actionfreelist[i+1];
- actionfreelist[amt-1].next = 0;
- }
- newaction = actionfreelist;
- actionfreelist = actionfreelist->next;
- return newaction;
- }
- static int actioncmp(
- struct action *ap1,
- struct action *ap2
- ){
- int rc;
- rc = ap1->sp->index - ap2->sp->index;
- if( rc==0 ){
- rc = (int)ap1->type - (int)ap2->type;
- }
- if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
- rc = ap1->x.rp->index - ap2->x.rp->index;
- }
- if( rc==0 ){
- rc = (int) (ap2 - ap1);
- }
- return rc;
- }
- static struct action *Action_sort(
- struct action *ap
- ){
- ap = (struct action *)msort((char *)ap,(char **)&ap->next,
- (int(*)(const char*,const char*))actioncmp);
- return ap;
- }
- void Action_add(
- struct action **app,
- enum e_action type,
- struct symbol *sp,
- char *arg
- ){
- struct action *newaction;
- newaction = Action_new();
- newaction->next = *app;
- *app = newaction;
- newaction->type = type;
- newaction->sp = sp;
- newaction->spOpt = 0;
- if( type==SHIFT ){
- newaction->x.stp = (struct state *)arg;
- }else{
- newaction->x.rp = (struct rule *)arg;
- }
- }
- struct lookahead_action {
- int lookahead;
- int action;
- };
- typedef struct acttab acttab;
- struct acttab {
- int nAction;
- int nActionAlloc;
- struct lookahead_action
- *aAction, /* The yy_action[] table under construction */
- *aLookahead;
- int mnLookahead;
- int mnAction;
- int mxLookahead;
- int nLookahead;
- int nLookaheadAlloc;
- int nterminal;
- int nsymbol;
- };
- #define acttab_lookahead_size(X) ((X)->nAction)
- #define acttab_yyaction(X,N) ((X)->aAction[N].action)
- #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
- void acttab_free(acttab *p){
- free( p->aAction );
- free( p->aLookahead );
- free( p );
- }
- acttab *acttab_alloc(int nsymbol, int nterminal){
- acttab *p = (acttab *) calloc( 1, sizeof(*p) );
- if( p==0 ){
- fprintf(stderr,"Unable to allocate memory for a new acttab.");
- exit(1);
- }
- memset(p, 0, sizeof(*p));
- p->nsymbol = nsymbol;
- p->nterminal = nterminal;
- return p;
- }
- void acttab_action(acttab *p, int lookahead, int action){
- if( p->nLookahead>=p->nLookaheadAlloc ){
- p->nLookaheadAlloc += 25;
- p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
- sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
- if( p->aLookahead==0 ){
- fprintf(stderr,"malloc failed\n");
- exit(1);
- }
- }
- if( p->nLookahead==0 ){
- p->mxLookahead = lookahead;
- p->mnLookahead = lookahead;
- p->mnAction = action;
- }else{
- if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
- if( p->mnLookahead>lookahead ){
- p->mnLookahead = lookahead;
- p->mnAction = action;
- }
- }
- p->aLookahead[p->nLookahead].lookahead = lookahead;
- p->aLookahead[p->nLookahead].action = action;
- p->nLookahead++;
- }
- int acttab_insert(acttab *p, int makeItSafe){
- int i, j, k, n, end;
- assert( p->nLookahead>0 );
-
- n = p->nsymbol + 1;
- if( p->nAction + n >= p->nActionAlloc ){
- int oldAlloc = p->nActionAlloc;
- p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
- p->aAction = (struct lookahead_action *) realloc( p->aAction,
- sizeof(p->aAction[0])*p->nActionAlloc);
- if( p->aAction==0 ){
- fprintf(stderr,"malloc failed\n");
- exit(1);
- }
- for(i=oldAlloc; i<p->nActionAlloc; i++){
- p->aAction[i].lookahead = -1;
- p->aAction[i].action = -1;
- }
- }
-
- end = makeItSafe ? p->mnLookahead : 0;
- for(i=p->nAction-1; i>=end; i--){
- if( p->aAction[i].lookahead==p->mnLookahead ){
-
- if( p->aAction[i].action!=p->mnAction ) continue;
- for(j=0; j<p->nLookahead; j++){
- k = p->aLookahead[j].lookahead - p->mnLookahead + i;
- if( k<0 || k>=p->nAction ) break;
- if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
- if( p->aLookahead[j].action!=p->aAction[k].action ) break;
- }
- if( j<p->nLookahead ) continue;
-
- n = 0;
- for(j=0; j<p->nAction; j++){
- if( p->aAction[j].lookahead<0 ) continue;
- if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
- }
- if( n==p->nLookahead ){
- break;
- }
- }
- }
-
- if( i<end ){
-
- i = makeItSafe ? p->mnLookahead : 0;
- for(; i<p->nActionAlloc - p->mxLookahead; i++){
- if( p->aAction[i].lookahead<0 ){
- for(j=0; j<p->nLookahead; j++){
- k = p->aLookahead[j].lookahead - p->mnLookahead + i;
- if( k<0 ) break;
- if( p->aAction[k].lookahead>=0 ) break;
- }
- if( j<p->nLookahead ) continue;
- for(j=0; j<p->nAction; j++){
- if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
- }
- if( j==p->nAction ){
- break;
- }
- }
- }
- }
-
- #if 0
- printf("Acttab:");
- for(j=0; j<p->nLookahead; j++){
- printf(" %d", p->aLookahead[j].lookahead);
- }
- printf(" inserted at %d\n", i);
- #endif
- for(j=0; j<p->nLookahead; j++){
- k = p->aLookahead[j].lookahead - p->mnLookahead + i;
- p->aAction[k] = p->aLookahead[j];
- if( k>=p->nAction ) p->nAction = k+1;
- }
- if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1;
- p->nLookahead = 0;
-
- return i - p->mnLookahead;
- }
- int acttab_action_size(acttab *p){
- int n = p->nAction;
- while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; }
- return n;
- }
- void FindRulePrecedences(struct lemon *xp)
- {
- struct rule *rp;
- for(rp=xp->rule; rp; rp=rp->next){
- if( rp->precsym==0 ){
- int i, j;
- for(i=0; i<rp->nrhs && rp->precsym==0; i++){
- struct symbol *sp = rp->rhs[i];
- if( sp->type==MULTITERMINAL ){
- for(j=0; j<sp->nsubsym; j++){
- if( sp->subsym[j]->prec>=0 ){
- rp->precsym = sp->subsym[j];
- break;
- }
- }
- }else if( sp->prec>=0 ){
- rp->precsym = rp->rhs[i];
- }
- }
- }
- }
- return;
- }
- void FindFirstSets(struct lemon *lemp)
- {
- int i, j;
- struct rule *rp;
- int progress;
- for(i=0; i<lemp->nsymbol; i++){
- lemp->symbols[i]->lambda = LEMON_FALSE;
- }
- for(i=lemp->nterminal; i<lemp->nsymbol; i++){
- lemp->symbols[i]->firstset = SetNew();
- }
-
- do{
- progress = 0;
- for(rp=lemp->rule; rp; rp=rp->next){
- if( rp->lhs->lambda ) continue;
- for(i=0; i<rp->nrhs; i++){
- struct symbol *sp = rp->rhs[i];
- assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
- if( sp->lambda==LEMON_FALSE ) break;
- }
- if( i==rp->nrhs ){
- rp->lhs->lambda = LEMON_TRUE;
- progress = 1;
- }
- }
- }while( progress );
-
- do{
- struct symbol *s1, *s2;
- progress = 0;
- for(rp=lemp->rule; rp; rp=rp->next){
- s1 = rp->lhs;
- for(i=0; i<rp->nrhs; i++){
- s2 = rp->rhs[i];
- if( s2->type==TERMINAL ){
- progress += SetAdd(s1->firstset,s2->index);
- break;
- }else if( s2->type==MULTITERMINAL ){
- for(j=0; j<s2->nsubsym; j++){
- progress += SetAdd(s1->firstset,s2->subsym[j]->index);
- }
- break;
- }else if( s1==s2 ){
- if( s1->lambda==LEMON_FALSE ) break;
- }else{
- progress += SetUnion(s1->firstset,s2->firstset);
- if( s2->lambda==LEMON_FALSE ) break;
- }
- }
- }
- }while( progress );
- return;
- }
- PRIVATE struct state *getstate(struct lemon *);
- void FindStates(struct lemon *lemp)
- {
- struct symbol *sp;
- struct rule *rp;
- Configlist_init();
-
- if( lemp->start ){
- sp = Symbol_find(lemp->start);
- if( sp==0 ){
- ErrorMsg(lemp->filename,0,
- "The specified start symbol \"%s\" is not "
- "in a nonterminal of the grammar. \"%s\" will be used as the start "
- "symbol instead.",lemp->start,lemp->startRule->lhs->name);
- lemp->errorcnt++;
- sp = lemp->startRule->lhs;
- }
- }else if( lemp->startRule ){
- sp = lemp->startRule->lhs;
- }else{
- ErrorMsg(lemp->filename,0,"Internal error - no start rule\n");
- exit(1);
- }
-
- for(rp=lemp->rule; rp; rp=rp->next){
- int i;
- for(i=0; i<rp->nrhs; i++){
- if( rp->rhs[i]==sp ){
- ErrorMsg(lemp->filename,0,
- "The start symbol \"%s\" occurs on the "
- "right-hand side of a rule. This will result in a parser which "
- "does not work properly.",sp->name);
- lemp->errorcnt++;
- }
- }
- }
-
- for(rp=sp->rule; rp; rp=rp->nextlhs){
- struct config *newcfp;
- rp->lhsStart = 1;
- newcfp = Configlist_addbasis(rp,0);
- SetAdd(newcfp->fws,0);
- }
-
- (void)getstate(lemp);
- return;
- }
- PRIVATE void buildshifts(struct lemon *, struct state *);
- PRIVATE struct state *getstate(struct lemon *lemp)
- {
- struct config *cfp, *bp;
- struct state *stp;
-
- Configlist_sortbasis();
- bp = Configlist_basis();
-
- stp = State_find(bp);
- if( stp ){
-
- struct config *x, *y;
- for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
- Plink_copy(&y->bplp,x->bplp);
- Plink_delete(x->fplp);
- x->fplp = x->bplp = 0;
- }
- cfp = Configlist_return();
- Configlist_eat(cfp);
- }else{
-
- Configlist_closure(lemp);
- Configlist_sort();
- cfp = Configlist_return();
- stp = State_new();
- MemoryCheck(stp);
- stp->bp = bp;
- stp->cfp = cfp;
- stp->statenum = lemp->nstate++;
- stp->ap = 0;
- State_insert(stp,stp->bp);
- buildshifts(lemp,stp);
- }
- return stp;
- }
- int same_symbol(struct symbol *a, struct symbol *b)
- {
- int i;
- if( a==b ) return 1;
- if( a->type!=MULTITERMINAL ) return 0;
- if( b->type!=MULTITERMINAL ) return 0;
- if( a->nsubsym!=b->nsubsym ) return 0;
- for(i=0; i<a->nsubsym; i++){
- if( a->subsym[i]!=b->subsym[i] ) return 0;
- }
- return 1;
- }
- PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
- {
- struct config *cfp;
- struct config *bcfp;
- struct config *newcfg;
- struct symbol *sp;
- struct symbol *bsp;
- struct state *newstp;
-
- for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
-
- for(cfp=stp->cfp; cfp; cfp=cfp->next){
- if( cfp->status==COMPLETE ) continue;
- if( cfp->dot>=cfp->rp->nrhs ) continue;
- Configlist_reset();
- sp = cfp->rp->rhs[cfp->dot];
-
- for(bcfp=cfp; bcfp; bcfp=bcfp->next){
- if( bcfp->status==COMPLETE ) continue;
- if( bcfp->dot>=bcfp->rp->nrhs ) continue;
- bsp = bcfp->rp->rhs[bcfp->dot];
- if( !same_symbol(bsp,sp) ) continue;
- bcfp->status = COMPLETE;
- newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
- Plink_add(&newcfg->bplp,bcfp);
- }
-
- newstp = getstate(lemp);
-
- if( sp->type==MULTITERMINAL ){
- int i;
- for(i=0; i<sp->nsubsym; i++){
- Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
- }
- }else{
- Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
- }
- }
- }
- void FindLinks(struct lemon *lemp)
- {
- int i;
- struct config *cfp, *other;
- struct state *stp;
- struct plink *plp;
-
- for(i=0; i<lemp->nstate; i++){
- stp = lemp->sorted[i];
- for(cfp=stp?stp->cfp:0; cfp; cfp=cfp->next){
- cfp->stp = stp;
- }
- }
-
- for(i=0; i<lemp->nstate; i++){
- stp = lemp->sorted[i];
- for(cfp=stp?stp->cfp:0; cfp; cfp=cfp->next){
- for(plp=cfp->bplp; plp; plp=plp->next){
- other = plp->cfp;
- Plink_add(&other->fplp,cfp);
- }
- }
- }
- }
- void FindFollowSets(struct lemon *lemp)
- {
- int i;
- struct config *cfp;
- struct plink *plp;
- int progress;
- int change;
- for(i=0; i<lemp->nstate; i++){
- assert( lemp->sorted[i]!=0 );
- for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
- cfp->status = INCOMPLETE;
- }
- }
- do{
- progress = 0;
- for(i=0; i<lemp->nstate; i++){
- assert( lemp->sorted[i]!=0 );
- for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
- if( cfp->status==COMPLETE ) continue;
- for(plp=cfp->fplp; plp; plp=plp->next){
- change = SetUnion(plp->cfp->fws,cfp->fws);
- if( change ){
- plp->cfp->status = INCOMPLETE;
- progress = 1;
- }
- }
- cfp->status = COMPLETE;
- }
- }
- }while( progress );
- }
- static int resolve_conflict(struct action *,struct action *);
- void FindActions(struct lemon *lemp)
- {
- int i,j;
- struct config *cfp;
- struct state *stp;
- struct symbol *sp;
- struct rule *rp;
-
- for(i=0; i<lemp->nstate; i++){
- stp = lemp->sorted[i];
- for(cfp=stp->cfp; cfp; cfp=cfp->next){
- if( cfp->rp->nrhs==cfp->dot ){
- for(j=0; j<lemp->nterminal; j++){
- if( SetFind(cfp->fws,j) ){
-
- Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
- }
- }
- }
- }
- }
-
- if( lemp->start ){
- sp = Symbol_find(lemp->start);
- if( sp==0 ){
- if( lemp->startRule==0 ){
- fprintf(stderr, "internal error on source line %d: no start rule\n",
- __LINE__);
- exit(1);
- }
- sp = lemp->startRule->lhs;
- }
- }else{
- sp = lemp->startRule->lhs;
- }
-
- Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
-
- for(i=0; i<lemp->nstate; i++){
- struct action *ap, *nap;
- stp = lemp->sorted[i];
-
- stp->ap = Action_sort(stp->ap);
- for(ap=stp->ap; ap && ap->next; ap=ap->next){
- for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
-
- lemp->nconflict += resolve_conflict(ap,nap);
- }
- }
- }
-
- for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
- for(i=0; i<lemp->nstate; i++){
- struct action *ap;
- for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
- if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
- }
- }
- for(rp=lemp->rule; rp; rp=rp->next){
- if( rp->canReduce ) continue;
- ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
- lemp->errorcnt++;
- }
- }
- static int resolve_conflict(
- struct action *apx,
- struct action *apy
- ){
- struct symbol *spx, *spy;
- int errcnt = 0;
- assert( apx->sp==apy->sp );
- if( apx->type==SHIFT && apy->type==SHIFT ){
- apy->type = SSCONFLICT;
- errcnt++;
- }
- if( apx->type==SHIFT && apy->type==REDUCE ){
- spx = apx->sp;
- spy = apy->x.rp->precsym;
- if( spy==0 || spx->prec<0 || spy->prec<0 ){
-
- apy->type = SRCONFLICT;
- errcnt++;
- }else if( spx->prec>spy->prec ){
- apy->type = RD_RESOLVED;
- }else if( spx->prec<spy->prec ){
- apx->type = SH_RESOLVED;
- }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){
- apy->type = RD_RESOLVED;
- }else if( spx->prec==spy->prec && spx->assoc==LEFT ){
- apx->type = SH_RESOLVED;
- }else{
- assert( spx->prec==spy->prec && spx->assoc==NONE );
- apx->type = ERROR;
- }
- }else if( apx->type==REDUCE && apy->type==REDUCE ){
- spx = apx->x.rp->precsym;
- spy = apy->x.rp->precsym;
- if( spx==0 || spy==0 || spx->prec<0 ||
- spy->prec<0 || spx->prec==spy->prec ){
- apy->type = RRCONFLICT;
- errcnt++;
- }else if( spx->prec>spy->prec ){
- apy->type = RD_RESOLVED;
- }else if( spx->prec<spy->prec ){
- apx->type = RD_RESOLVED;
- }
- }else{
- assert(
- apx->type==SH_RESOLVED ||
- apx->type==RD_RESOLVED ||
- apx->type==SSCONFLICT ||
- apx->type==SRCONFLICT ||
- apx->type==RRCONFLICT ||
- apy->type==SH_RESOLVED ||
- apy->type==RD_RESOLVED ||
- apy->type==SSCONFLICT ||
- apy->type==SRCONFLICT ||
- apy->type==RRCONFLICT
- );
-
- }
- return errcnt;
- }
- static struct config *freelist = 0;
- static struct config *current = 0;
- static struct config **currentend = 0;
- static struct config *basis = 0;
- static struct config **basisend = 0;
- PRIVATE struct config *newconfig(void){
- return (struct config*)calloc(1, sizeof(struct config));
- }
- PRIVATE void deleteconfig(struct config *old)
- {
- old->next = freelist;
- freelist = old;
- }
- void Configlist_init(void){
- current = 0;
- currentend = ¤t;
- basis = 0;
- basisend = &basis;
- Configtable_init();
- return;
- }
- void Configlist_reset(void){
- current = 0;
- currentend = ¤t;
- basis = 0;
- basisend = &basis;
- Configtable_clear(0);
- return;
- }
- struct config *Configlist_add(
- struct rule *rp,
- int dot
- ){
- struct config *cfp, model;
- assert( currentend!=0 );
- model.rp = rp;
- model.dot = dot;
- cfp = Configtable_find(&model);
- if( cfp==0 ){
- cfp = newconfig();
- cfp->rp = rp;
- cfp->dot = dot;
- cfp->fws = SetNew();
- cfp->stp = 0;
- cfp->fplp = cfp->bplp = 0;
- cfp->next = 0;
- cfp->bp = 0;
- *currentend = cfp;
- currentend = &cfp->next;
- Configtable_insert(cfp);
- }
- return cfp;
- }
- struct config *Configlist_addbasis(struct rule *rp, int dot)
- {
- struct config *cfp, model;
- assert( basisend!=0 );
- assert( currentend!=0 );
- model.rp = rp;
- model.dot = dot;
- cfp = Configtable_find(&model);
- if( cfp==0 ){
- cfp = newconfig();
- cfp->rp = rp;
- cfp->dot = dot;
- cfp->fws = SetNew();
- cfp->stp = 0;
- cfp->fplp = cfp->bplp = 0;
- cfp->next = 0;
- cfp->bp = 0;
- *currentend = cfp;
- currentend = &cfp->next;
- *basisend = cfp;
- basisend = &cfp->bp;
- Configtable_insert(cfp);
- }
- return cfp;
- }
- void Configlist_closure(struct lemon *lemp)
- {
- struct config *cfp, *newcfp;
- struct rule *rp, *newrp;
- struct symbol *sp, *xsp;
- int i, dot;
- assert( currentend!=0 );
- for(cfp=current; cfp; cfp=cfp->next){
- rp = cfp->rp;
- dot = cfp->dot;
- if( dot>=rp->nrhs ) continue;
- sp = rp->rhs[dot];
- if( sp->type==NONTERMINAL ){
- if( sp->rule==0 && sp!=lemp->errsym ){
- ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
- sp->name);
- lemp->errorcnt++;
- }
- for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
- newcfp = Configlist_add(newrp,0);
- for(i=dot+1; i<rp->nrhs; i++){
- xsp = rp->rhs[i];
- if( xsp->type==TERMINAL ){
- SetAdd(newcfp->fws,xsp->index);
- break;
- }else if( xsp->type==MULTITERMINAL ){
- int k;
- for(k=0; k<xsp->nsubsym; k++){
- SetAdd(newcfp->fws, xsp->subsym[k]->index);
- }
- break;
- }else{
- SetUnion(newcfp->fws,xsp->firstset);
- if( xsp->lambda==LEMON_FALSE ) break;
- }
- }
- if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
- }
- }
- }
- return;
- }
- void Configlist_sort(void){
- current = (struct config*)msort((char*)current,(char**)&(current->next),
- Configcmp);
- currentend = 0;
- return;
- }
- void Configlist_sortbasis(void){
- basis = (struct config*)msort((char*)current,(char**)&(current->bp),
- Configcmp);
- basisend = 0;
- return;
- }
- struct config *Configlist_return(void){
- struct config *old;
- old = current;
- current = 0;
- currentend = 0;
- return old;
- }
- struct config *Configlist_basis(void){
- struct config *old;
- old = basis;
- basis = 0;
- basisend = 0;
- return old;
- }
- void Configlist_eat(struct config *cfp)
- {
- struct config *nextcfp;
- for(; cfp; cfp=nextcfp){
- nextcfp = cfp->next;
- assert( cfp->fplp==0 );
- assert( cfp->bplp==0 );
- if( cfp->fws ) SetFree(cfp->fws);
- deleteconfig(cfp);
- }
- return;
- }
- void ErrorMsg(const char *filename, int lineno, const char *format, ...){
- va_list ap;
- fprintf(stderr, "%s:%d: ", filename, lineno);
- va_start(ap, format);
- vfprintf(stderr,format,ap);
- va_end(ap);
- fprintf(stderr, "\n");
- }
- void memory_error(void){
- fprintf(stderr,"Out of memory. Aborting...\n");
- exit(1);
- }
- static int nDefine = 0;
- static char **azDefine = 0;
- static void handle_D_option(char *z){
- char **paz;
- nDefine++;
- azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
- if( azDefine==0 ){
- fprintf(stderr,"out of memory\n");
- exit(1);
- }
- paz = &azDefine[nDefine-1];
- *paz = (char *) malloc( lemonStrlen(z)+1 );
- if( *paz==0 ){
- fprintf(stderr,"out of memory\n");
- exit(1);
- }
- lemon_strcpy(*paz, z);
- for(z=*paz; *z && *z!='='; z++){}
- *z = 0;
- }
- static char *outputDir = NULL;
- static void handle_d_option(char *z){
- outputDir = (char *) malloc( lemonStrlen(z)+1 );
- if( outputDir==0 ){
- fprintf(stderr,"out of memory\n");
- exit(1);
- }
- lemon_strcpy(outputDir, z);
- }
- static char *user_templatename = NULL;
- static void handle_T_option(char *z){
- user_templatename = (char *) malloc( lemonStrlen(z)+1 );
- if( user_templatename==0 ){
- memory_error();
- }
- lemon_strcpy(user_templatename, z);
- }
- static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
- struct rule *pFirst = 0;
- struct rule **ppPrev = &pFirst;
- while( pA && pB ){
- if( pA->iRule<pB->iRule ){
- *ppPrev = pA;
- ppPrev = &pA->next;
- pA = pA->next;
- }else{
- *ppPrev = pB;
- ppPrev = &pB->next;
- pB = pB->next;
- }
- }
- if( pA ){
- *ppPrev = pA;
- }else{
- *ppPrev = pB;
- }
- return pFirst;
- }
- static struct rule *Rule_sort(struct rule *rp){
- unsigned int i;
- struct rule *pNext;
- struct rule *x[32];
- memset(x, 0, sizeof(x));
- while( rp ){
- pNext = rp->next;
- rp->next = 0;
- for(i=0; i<sizeof(x)/sizeof(x[0])-1 && x[i]; i++){
- rp = Rule_merge(x[i], rp);
- x[i] = 0;
- }
- x[i] = rp;
- rp = pNext;
- }
- rp = 0;
- for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
- rp = Rule_merge(x[i], rp);
- }
- return rp;
- }
- static const char *minimum_size_type(int lwr, int upr, int *pnByte);
- static void stats_line(const char *zLabel, int iValue){
- int nLabel = lemonStrlen(zLabel);
- printf(" %s%.*s %5d\n", zLabel,
- 35-nLabel, "................................",
- iValue);
- }
- int main(int argc, char **argv){
- static int version = 0;
- static int rpflag = 0;
- static int basisflag = 0;
- static int compress = 0;
- static int quiet = 0;
- static int statistics = 0;
- static int mhflag = 0;
- static int nolinenosflag = 0;
- static int noResort = 0;
- static int sqlFlag = 0;
- static int printPP = 0;
-
- static struct s_options options[] = {
- {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
- {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
- {OPT_FSTR, "d", (char*)&handle_d_option, "Output directory. Default '.'"},
- {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
- {OPT_FLAG, "E", (char*)&printPP, "Print input file after preprocessing."},
- {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
- {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
- {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
- {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
- {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
- {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
- {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
- "Show conflicts resolved by precedence rules"},
- {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
- {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
- {OPT_FLAG, "s", (char*)&statistics,
- "Print parser stats to standard output."},
- {OPT_FLAG, "S", (char*)&sqlFlag,
- "Generate the *.sql file describing the parser tables."},
- {OPT_FLAG, "x", (char*)&version, "Print the version number."},
- {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
- {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
- {OPT_FLAG,0,0,0}
- };
- int i;
- int exitcode;
- struct lemon lem;
- struct rule *rp;
- (void)argc;
- OptInit(argv,options,stderr);
- if( version ){
- printf("Lemon version 1.0\n");
- exit(0);
- }
- if( OptNArgs()!=1 ){
- fprintf(stderr,"Exactly one filename argument is required.\n");
- exit(1);
- }
- memset(&lem, 0, sizeof(lem));
- lem.errorcnt = 0;
-
- Strsafe_init();
- Symbol_init();
- State_init();
- lem.argv0 = argv[0];
- lem.filename = OptArg(0);
- lem.basisflag = basisflag;
- lem.nolinenosflag = nolinenosflag;
- lem.printPreprocessed = printPP;
- Symbol_new("$");
-
- Parse(&lem);
- if( lem.printPreprocessed || lem.errorcnt ) exit(lem.errorcnt);
- if( lem.nrule==0 ){
- fprintf(stderr,"Empty grammar.\n");
- exit(1);
- }
- lem.errsym = Symbol_find("error");
-
- Symbol_new("{default}");
- lem.nsymbol = Symbol_count();
- lem.symbols = Symbol_arrayof();
- for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
- qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
- for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
- while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
- assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
- lem.nsymbol = i - 1;
- for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
- lem.nterminal = i;
-
- for(i=0, rp=lem.rule; rp; rp=rp->next){
- rp->iRule = rp->code ? i++ : -1;
- }
- lem.nruleWithAction = i;
- for(rp=lem.rule; rp; rp=rp->next){
- if( rp->iRule<0 ) rp->iRule = i++;
- }
- lem.startRule = lem.rule;
- lem.rule = Rule_sort(lem.rule);
-
- if( rpflag ){
- Reprint(&lem);
- }else{
-
- SetSize(lem.nterminal+1);
-
- FindRulePrecedences(&lem);
-
- FindFirstSets(&lem);
-
- lem.nstate = 0;
- FindStates(&lem);
- lem.sorted = State_arrayof();
-
- FindLinks(&lem);
-
- FindFollowSets(&lem);
-
- FindActions(&lem);
-
- if( compress==0 ) CompressTables(&lem);
-
- if( noResort==0 ) ResortStates(&lem);
-
- if( !quiet ) ReportOutput(&lem);
-
- ReportTable(&lem, mhflag, sqlFlag);
-
- if( !mhflag ) ReportHeader(&lem);
- }
- if( statistics ){
- printf("Parser statistics:\n");
- stats_line("terminal symbols", lem.nterminal);
- stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
- stats_line("total symbols", lem.nsymbol);
- stats_line("rules", lem.nrule);
- stats_line("states", lem.nxstate);
- stats_line("conflicts", lem.nconflict);
- stats_line("action table entries", lem.nactiontab);
- stats_line("lookahead table entries", lem.nlookaheadtab);
- stats_line("total table size (bytes)", lem.tablesize);
- }
- if( lem.nconflict > 0 ){
- fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
- }
-
- exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
- exit(exitcode);
- return (exitcode);
- }
- #define NEXT(A) (*(char**)(((char*)A)+offset))
- static char *merge(
- char *a,
- char *b,
- int (*cmp)(const char*,const char*),
- int offset
- ){
- char *ptr, *head;
- if( a==0 ){
- head = b;
- }else if( b==0 ){
- head = a;
- }else{
- if( (*cmp)(a,b)<=0 ){
- ptr = a;
- a = NEXT(a);
- }else{
- ptr = b;
- b = NEXT(b);
- }
- head = ptr;
- while( a && b ){
- if( (*cmp)(a,b)<=0 ){
- NEXT(ptr) = a;
- ptr = a;
- a = NEXT(a);
- }else{
- NEXT(ptr) = b;
- ptr = b;
- b = NEXT(b);
- }
- }
- if( a ) NEXT(ptr) = a;
- else NEXT(ptr) = b;
- }
- return head;
- }
- #define LISTSIZE 30
- static char *msort(
- char *list,
- char **next,
- int (*cmp)(const char*,const char*)
- ){
- unsigned long offset;
- char *ep;
- char *set[LISTSIZE];
- int i;
- offset = (unsigned long)((char*)next - (char*)list);
- for(i=0; i<LISTSIZE; i++) set[i] = 0;
- while( list ){
- ep = list;
- list = NEXT(list);
- NEXT(ep) = 0;
- for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
- ep = merge(ep,set[i],cmp,offset);
- set[i] = 0;
- }
- set[i] = ep;
- }
- ep = 0;
- for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
- return ep;
- }
- static char **g_argv;
- static struct s_options *op;
- static FILE *errstream;
- #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
- static void errline(int n, int k, FILE *err)
- {
- int spcnt, i;
- if( g_argv[0] ){
- fprintf(err,"%s",g_argv[0]);
- spcnt = lemonStrlen(g_argv[0]) + 1;
- }else{
- spcnt = 0;
- }
- for(i=1; i<n && g_argv[i]; i++){
- fprintf(err," %s",g_argv[i]);
- spcnt += lemonStrlen(g_argv[i])+1;
- }
- spcnt += k;
- for(; g_argv[i]; i++) fprintf(err," %s",g_argv[i]);
- if( spcnt<20 ){
- fprintf(err,"\n%*s^-- here\n",spcnt,"");
- }else{
- fprintf(err,"\n%*shere --^\n",spcnt-7,"");
- }
- }
- static int argindex(int n)
- {
- int i;
- int dashdash = 0;
- if( g_argv!=0 && *g_argv!=0 ){
- for(i=1; g_argv[i]; i++){
- if( dashdash || !ISOPT(g_argv[i]) ){
- if( n==0 ) return i;
- n--;
- }
- if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
- }
- }
- return -1;
- }
- static char emsg[] = "Command line syntax error: ";
- static int handleflags(int i, FILE *err)
- {
- int v;
- int errcnt = 0;
- int j;
- for(j=0; op[j].label; j++){
- if( strncmp(&g_argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
- }
- v = g_argv[i][0]=='-' ? 1 : 0;
- if( op[j].label==0 ){
- if( err ){
- fprintf(err,"%sundefined option.\n",emsg);
- errline(i,1,err);
- }
- errcnt++;
- }else if( op[j].arg==0 ){
-
- }else if( op[j].type==OPT_FLAG ){
- *((int*)op[j].arg) = v;
- }else if( op[j].type==OPT_FFLAG ){
- (*(void(*)(int))(op[j].arg))(v);
- }else if( op[j].type==OPT_FSTR ){
- (*(void(*)(char *))(op[j].arg))(&g_argv[i][2]);
- }else{
- if( err ){
- fprintf(err,"%smissing argument on switch.\n",emsg);
- errline(i,1,err);
- }
- errcnt++;
- }
- return errcnt;
- }
- static int handleswitch(int i, FILE *err)
- {
- int lv = 0;
- double dv = 0.0;
- char *sv = 0, *end;
- char *cp;
- int j;
- int errcnt = 0;
- cp = strchr(g_argv[i],'=');
- assert( cp!=0 );
- *cp = 0;
- for(j=0; op[j].label; j++){
- if( strcmp(g_argv[i],op[j].label)==0 ) break;
- }
- *cp = '=';
- if( op[j].label==0 ){
- if( err ){
- fprintf(err,"%sundefined option.\n",emsg);
- errline(i,0,err);
- }
- errcnt++;
- }else{
- cp++;
- switch( op[j].type ){
- case OPT_FLAG:
- case OPT_FFLAG:
- if( err ){
- fprintf(err,"%soption requires an argument.\n",emsg);
- errline(i,0,err);
- }
- errcnt++;
- break;
- case OPT_DBL:
- case OPT_FDBL:
- dv = strtod(cp,&end);
- if( *end ){
- if( err ){
- fprintf(err,
- "%sillegal character in floating-point argument.\n",emsg);
- errline(i,(int)((char*)end-(char*)g_argv[i]),err);
- }
- errcnt++;
- }
- break;
- case OPT_INT:
- case OPT_FINT:
- lv = strtol(cp,&end,0);
- if( *end ){
- if( err ){
- fprintf(err,"%sillegal character in integer argument.\n",emsg);
- errline(i,(int)((char*)end-(char*)g_argv[i]),err);
- }
- errcnt++;
- }
- break;
- case OPT_STR:
- case OPT_FSTR:
- sv = cp;
- break;
- }
- switch( op[j].type ){
- case OPT_FLAG:
- case OPT_FFLAG:
- break;
- case OPT_DBL:
- *(double*)(op[j].arg) = dv;
- break;
- case OPT_FDBL:
- (*(void(*)(double))(op[j].arg))(dv);
- break;
- case OPT_INT:
- *(int*)(op[j].arg) = lv;
- break;
- case OPT_FINT:
- (*(void(*)(int))(op[j].arg))((int)lv);
- break;
- case OPT_STR:
- *(char**)(op[j].arg) = sv;
- break;
- case OPT_FSTR:
- (*(void(*)(char *))(op[j].arg))(sv);
- break;
- }
- }
- return errcnt;
- }
- int OptInit(char **a, struct s_options *o, FILE *err)
- {
- int errcnt = 0;
- g_argv = a;
- op = o;
- errstream = err;
- if( g_argv && *g_argv && op ){
- int i;
- for(i=1; g_argv[i]; i++){
- if( g_argv[i][0]=='+' || g_argv[i][0]=='-' ){
- errcnt += handleflags(i,err);
- }else if( strchr(g_argv[i],'=') ){
- errcnt += handleswitch(i,err);
- }
- }
- }
- if( errcnt>0 ){
- fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
- OptPrint();
- exit(1);
- }
- return 0;
- }
- int OptNArgs(void){
- int cnt = 0;
- int dashdash = 0;
- int i;
- if( g_argv!=0 && g_argv[0]!=0 ){
- for(i=1; g_argv[i]; i++){
- if( dashdash || !ISOPT(g_argv[i]) ) cnt++;
- if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
- }
- }
- return cnt;
- }
- char *OptArg(int n)
- {
- int i;
- i = argindex(n);
- return i>=0 ? g_argv[i] : 0;
- }
- void OptErr(int n)
- {
- int i;
- i = argindex(n);
- if( i>=0 ) errline(i,0,errstream);
- }
- void OptPrint(void){
- int i;
- int max, len;
- max = 0;
- for(i=0; op[i].label; i++){
- len = lemonStrlen(op[i].label) + 1;
- switch( op[i].type ){
- case OPT_FLAG:
- case OPT_FFLAG:
- break;
- case OPT_INT:
- case OPT_FINT:
- len += 9;
- break;
- case OPT_DBL:
- case OPT_FDBL:
- len += 6;
- break;
- case OPT_STR:
- case OPT_FSTR:
- len += 8;
- break;
- }
- if( len>max ) max = len;
- }
- for(i=0; op[i].label; i++){
- switch( op[i].type ){
- case OPT_FLAG:
- case OPT_FFLAG:
- fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
- break;
- case OPT_INT:
- case OPT_FINT:
- fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
- (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
- break;
- case OPT_DBL:
- case OPT_FDBL:
- fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
- (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
- break;
- case OPT_STR:
- case OPT_FSTR:
- fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
- (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
- break;
- }
- }
- }
- enum e_state {
- INITIALIZE,
- WAITING_FOR_DECL_OR_RULE,
- WAITING_FOR_DECL_KEYWORD,
- WAITING_FOR_DECL_ARG,
- WAITING_FOR_PRECEDENCE_SYMBOL,
- WAITING_FOR_ARROW,
- IN_RHS,
- LHS_ALIAS_1,
- LHS_ALIAS_2,
- LHS_ALIAS_3,
- RHS_ALIAS_1,
- RHS_ALIAS_2,
- PRECEDENCE_MARK_1,
- PRECEDENCE_MARK_2,
- RESYNC_AFTER_RULE_ERROR,
- RESYNC_AFTER_DECL_ERROR,
- WAITING_FOR_DESTRUCTOR_SYMBOL,
- WAITING_FOR_DATATYPE_SYMBOL,
- WAITING_FOR_FALLBACK_ID,
- WAITING_FOR_WILDCARD_ID,
- WAITING_FOR_CLASS_ID,
- WAITING_FOR_CLASS_TOKEN,
- WAITING_FOR_TOKEN_NAME
- };
- struct pstate {
- char *filename;
- int tokenlineno;
- int errorcnt;
- char *tokenstart;
- struct lemon *gp;
- enum e_state state;
- struct symbol *fallback;
- struct symbol *tkclass;
- struct symbol *lhs;
- const char *lhsalias;
- int nrhs;
- struct symbol *rhs[MAXRHS];
- const char *alias[MAXRHS];
- struct rule *prevrule;
- const char *declkeyword;
- char **declargslot;
- int insertLineMacro;
- int *decllinenoslot;
- enum e_assoc declassoc;
- int preccounter;
- struct rule *firstrule;
- struct rule *lastrule;
- };
- static void parseonetoken(struct pstate *psp)
- {
- const char *x;
- x = Strsafe(psp->tokenstart);
- #if 0
- printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
- x,psp->state);
- #endif
- switch( psp->state ){
- case INITIALIZE:
- psp->prevrule = 0;
- psp->preccounter = 0;
- psp->firstrule = psp->lastrule = 0;
- psp->gp->nrule = 0;
-
- case WAITING_FOR_DECL_OR_RULE:
- if( x[0]=='%' ){
- psp->state = WAITING_FOR_DECL_KEYWORD;
- }else if( ISLOWER(x[0]) ){
- psp->lhs = Symbol_new(x);
- psp->nrhs = 0;
- psp->lhsalias = 0;
- psp->state = WAITING_FOR_ARROW;
- }else if( x[0]=='{' ){
- if( psp->prevrule==0 ){
- ErrorMsg(psp->filename,psp->tokenlineno,
- "There is no prior rule upon which to attach the code "
- "fragment which begins on this line.");
- psp->errorcnt++;
- }else if( psp->prevrule->code!=0 ){
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Code fragment beginning on this line is not the first "
- "to follow the previous rule.");
- psp->errorcnt++;
- }else if( strcmp(x, "{NEVER-REDUCE")==0 ){
- psp->prevrule->neverReduce = 1;
- }else{
- psp->prevrule->line = psp->tokenlineno;
- psp->prevrule->code = &x[1];
- psp->prevrule->noCode = 0;
- }
- }else if( x[0]=='[' ){
- psp->state = PRECEDENCE_MARK_1;
- }else{
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Token \"%s\" should be either \"%%\" or a nonterminal name.",
- x);
- psp->errorcnt++;
- }
- break;
- case PRECEDENCE_MARK_1:
- if( !ISUPPER(x[0]) ){
- ErrorMsg(psp->filename,psp->tokenlineno,
- "The precedence symbol must be a terminal.");
- psp->errorcnt++;
- }else if( psp->prevrule==0 ){
- ErrorMsg(psp->filename,psp->tokenlineno,
- "There is no prior rule to assign precedence \"[%s]\".",x);
- psp->errorcnt++;
- }else if( psp->prevrule->precsym!=0 ){
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Precedence mark on this line is not the first "
- "to follow the previous rule.");
- psp->errorcnt++;
- }else{
- psp->prevrule->precsym = Symbol_new(x);
- }
- psp->state = PRECEDENCE_MARK_2;
- break;
- case PRECEDENCE_MARK_2:
- if( x[0]!=']' ){
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Missing \"]\" on precedence mark.");
- psp->errorcnt++;
- }
- psp->state = WAITING_FOR_DECL_OR_RULE;
- break;
- case WAITING_FOR_ARROW:
- if( x[0]==':' && x[1]==':' && x[2]=='=' ){
- psp->state = IN_RHS;
- }else if( x[0]=='(' ){
- psp->state = LHS_ALIAS_1;
- }else{
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Expected to see a \":\" following the LHS symbol \"%s\".",
- psp->lhs->name);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_RULE_ERROR;
- }
- break;
- case LHS_ALIAS_1:
- if( ISALPHA(x[0]) ){
- psp->lhsalias = x;
- psp->state = LHS_ALIAS_2;
- }else{
- ErrorMsg(psp->filename,psp->tokenlineno,
- "\"%s\" is not a valid alias for the LHS \"%s\"\n",
- x,psp->lhs->name);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_RULE_ERROR;
- }
- break;
- case LHS_ALIAS_2:
- if( x[0]==')' ){
- psp->state = LHS_ALIAS_3;
- }else{
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_RULE_ERROR;
- }
- break;
- case LHS_ALIAS_3:
- if( x[0]==':' && x[1]==':' && x[2]=='=' ){
- psp->state = IN_RHS;
- }else{
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Missing \"->\" following: \"%s(%s)\".",
- psp->lhs->name,psp->lhsalias);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_RULE_ERROR;
- }
- break;
- case IN_RHS:
- if( x[0]=='.' ){
- struct rule *rp;
- rp = (struct rule *)calloc( sizeof(struct rule) +
- sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
- if( rp==0 ){
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Can't allocate enough memory for this rule.");
- psp->errorcnt++;
- psp->prevrule = 0;
- }else{
- int i;
- rp->ruleline = psp->tokenlineno;
- rp->rhs = (struct symbol**)&rp[1];
- rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
- for(i=0; i<psp->nrhs; i++){
- rp->rhs[i] = psp->rhs[i];
- rp->rhsalias[i] = psp->alias[i];
- if( rp->rhsalias[i]!=0 ){ rp->rhs[i]->bContent = 1; }
- }
- rp->lhs = psp->lhs;
- rp->lhsalias = psp->lhsalias;
- rp->nrhs = psp->nrhs;
- rp->code = 0;
- rp->noCode = 1;
- rp->precsym = 0;
- rp->index = psp->gp->nrule++;
- rp->nextlhs = rp->lhs->rule;
- rp->lhs->rule = rp;
- rp->next = 0;
- if( psp->firstrule==0 ){
- psp->firstrule = psp->lastrule = rp;
- }else{
- psp->lastrule->next = rp;
- psp->lastrule = rp;
- }
- psp->prevrule = rp;
- }
- psp->state = WAITING_FOR_DECL_OR_RULE;
- }else if( ISALPHA(x[0]) ){
- if( psp->nrhs>=MAXRHS ){
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Too many symbols on RHS of rule beginning at \"%s\".",
- x);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_RULE_ERROR;
- }else{
- psp->rhs[psp->nrhs] = Symbol_new(x);
- psp->alias[psp->nrhs] = 0;
- psp->nrhs++;
- }
- }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 && ISUPPER(x[1]) ){
- struct symbol *msp = psp->rhs[psp->nrhs-1];
- if( msp->type!=MULTITERMINAL ){
- struct symbol *origsp = msp;
- msp = (struct symbol *) calloc(1,sizeof(*msp));
- memset(msp, 0, sizeof(*msp));
- msp->type = MULTITERMINAL;
- msp->nsubsym = 1;
- msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
- msp->subsym[0] = origsp;
- msp->name = origsp->name;
- psp->rhs[psp->nrhs-1] = msp;
- }
- msp->nsubsym++;
- msp->subsym = (struct symbol **) realloc(msp->subsym,
- sizeof(struct symbol*)*msp->nsubsym);
- msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
- if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Cannot form a compound containing a non-terminal");
- psp->errorcnt++;
- }
- }else if( x[0]=='(' && psp->nrhs>0 ){
- psp->state = RHS_ALIAS_1;
- }else{
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Illegal character on RHS of rule: \"%s\".",x);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_RULE_ERROR;
- }
- break;
- case RHS_ALIAS_1:
- if( ISALPHA(x[0]) ){
- psp->alias[psp->nrhs-1] = x;
- psp->state = RHS_ALIAS_2;
- }else{
- ErrorMsg(psp->filename,psp->tokenlineno,
- "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
- x,psp->rhs[psp->nrhs-1]->name);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_RULE_ERROR;
- }
- break;
- case RHS_ALIAS_2:
- if( x[0]==')' ){
- psp->state = IN_RHS;
- }else{
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_RULE_ERROR;
- }
- break;
- case WAITING_FOR_DECL_KEYWORD:
- if( ISALPHA(x[0]) ){
- psp->declkeyword = x;
- psp->declargslot = 0;
- psp->decllinenoslot = 0;
- psp->insertLineMacro = 1;
- psp->state = WAITING_FOR_DECL_ARG;
- if( strcmp(x,"name")==0 ){
- psp->declargslot = &(psp->gp->name);
- psp->insertLineMacro = 0;
- }else if( strcmp(x,"include")==0 ){
- psp->declargslot = &(psp->gp->include);
- }else if( strcmp(x,"code")==0 ){
- psp->declargslot = &(psp->gp->extracode);
- }else if( strcmp(x,"token_destructor")==0 ){
- psp->declargslot = &psp->gp->tokendest;
- }else if( strcmp(x,"default_destructor")==0 ){
- psp->declargslot = &psp->gp->vardest;
- }else if( strcmp(x,"token_prefix")==0 ){
- psp->declargslot = &psp->gp->tokenprefix;
- psp->insertLineMacro = 0;
- }else if( strcmp(x,"syntax_error")==0 ){
- psp->declargslot = &(psp->gp->error);
- }else if( strcmp(x,"parse_accept")==0 ){
- psp->declargslot = &(psp->gp->accept);
- }else if( strcmp(x,"parse_failure")==0 ){
- psp->declargslot = &(psp->gp->failure);
- }else if( strcmp(x,"stack_overflow")==0 ){
- psp->declargslot = &(psp->gp->overflow);
- }else if( strcmp(x,"extra_argument")==0 ){
- psp->declargslot = &(psp->gp->arg);
- psp->insertLineMacro = 0;
- }else if( strcmp(x,"extra_context")==0 ){
- psp->declargslot = &(psp->gp->ctx);
- psp->insertLineMacro = 0;
- }else if( strcmp(x,"token_type")==0 ){
- psp->declargslot = &(psp->gp->tokentype);
- psp->insertLineMacro = 0;
- }else if( strcmp(x,"default_type")==0 ){
- psp->declargslot = &(psp->gp->vartype);
- psp->insertLineMacro = 0;
- }else if( strcmp(x,"stack_size")==0 ){
- psp->declargslot = &(psp->gp->stacksize);
- psp->insertLineMacro = 0;
- }else if( strcmp(x,"start_symbol")==0 ){
- psp->declargslot = &(psp->gp->start);
- psp->insertLineMacro = 0;
- }else if( strcmp(x,"left")==0 ){
- psp->preccounter++;
- psp->declassoc = LEFT;
- psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
- }else if( strcmp(x,"right")==0 ){
- psp->preccounter++;
- psp->declassoc = RIGHT;
- psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
- }else if( strcmp(x,"nonassoc")==0 ){
- psp->preccounter++;
- psp->declassoc = NONE;
- psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
- }else if( strcmp(x,"destructor")==0 ){
- psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
- }else if( strcmp(x,"type")==0 ){
- psp->state = WAITING_FOR_DATATYPE_SYMBOL;
- }else if( strcmp(x,"fallback")==0 ){
- psp->fallback = 0;
- psp->state = WAITING_FOR_FALLBACK_ID;
- }else if( strcmp(x,"token")==0 ){
- psp->state = WAITING_FOR_TOKEN_NAME;
- }else if( strcmp(x,"wildcard")==0 ){
- psp->state = WAITING_FOR_WILDCARD_ID;
- }else if( strcmp(x,"token_class")==0 ){
- psp->state = WAITING_FOR_CLASS_ID;
- }else{
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Unknown declaration keyword: \"%%%s\".",x);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_DECL_ERROR;
- }
- }else{
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Illegal declaration keyword: \"%s\".",x);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_DECL_ERROR;
- }
- break;
- case WAITING_FOR_DESTRUCTOR_SYMBOL:
- if( !ISALPHA(x[0]) ){
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Symbol name missing after %%destructor keyword");
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_DECL_ERROR;
- }else{
- struct symbol *sp = Symbol_new(x);
- psp->declargslot = &sp->destructor;
- psp->decllinenoslot = &sp->destLineno;
- psp->insertLineMacro = 1;
- psp->state = WAITING_FOR_DECL_ARG;
- }
- break;
- case WAITING_FOR_DATATYPE_SYMBOL:
- if( !ISALPHA(x[0]) ){
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Symbol name missing after %%type keyword");
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_DECL_ERROR;
- }else{
- struct symbol *sp = Symbol_find(x);
- if((sp) && (sp->datatype)){
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Symbol %%type \"%s\" already defined", x);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_DECL_ERROR;
- }else{
- if (!sp){
- sp = Symbol_new(x);
- }
- psp->declargslot = &sp->datatype;
- psp->insertLineMacro = 0;
- psp->state = WAITING_FOR_DECL_ARG;
- }
- }
- break;
- case WAITING_FOR_PRECEDENCE_SYMBOL:
- if( x[0]=='.' ){
- psp->state = WAITING_FOR_DECL_OR_RULE;
- }else if( ISUPPER(x[0]) ){
- struct symbol *sp;
- sp = Symbol_new(x);
- if( sp->prec>=0 ){
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Symbol \"%s\" has already be given a precedence.",x);
- psp->errorcnt++;
- }else{
- sp->prec = psp->preccounter;
- sp->assoc = psp->declassoc;
- }
- }else{
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Can't assign a precedence to \"%s\".",x);
- psp->errorcnt++;
- }
- break;
- case WAITING_FOR_DECL_ARG:
- if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
- const char *zOld, *zNew;
- char *zBuf, *z;
- int nOld, n, nLine = 0, nNew, nBack;
- int addLineMacro;
- char zLine[50];
- zNew = x;
- if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
- nNew = lemonStrlen(zNew);
- if( *psp->declargslot ){
- zOld = *psp->declargslot;
- }else{
- zOld = "";
- }
- nOld = lemonStrlen(zOld);
- n = nOld + nNew + 20;
- addLineMacro = !psp->gp->nolinenosflag
- && psp->insertLineMacro
- && psp->tokenlineno>1
- && (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
- if( addLineMacro ){
- for(z=psp->filename, nBack=0; *z; z++){
- if( *z=='\\' ) nBack++;
- }
- lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
- nLine = lemonStrlen(zLine);
- n += nLine + lemonStrlen(psp->filename) + nBack;
- }
- *psp->declargslot = (char *) realloc(*psp->declargslot, n);
- zBuf = *psp->declargslot + nOld;
- if( addLineMacro ){
- if( nOld && zBuf[-1]!='\n' ){
- *(zBuf++) = '\n';
- }
- memcpy(zBuf, zLine, nLine);
- zBuf += nLine;
- *(zBuf++) = '"';
- for(z=psp->filename; *z; z++){
- if( *z=='\\' ){
- *(zBuf++) = '\\';
- }
- *(zBuf++) = *z;
- }
- *(zBuf++) = '"';
- *(zBuf++) = '\n';
- }
- if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
- psp->decllinenoslot[0] = psp->tokenlineno;
- }
- memcpy(zBuf, zNew, nNew);
- zBuf += nNew;
- *zBuf = 0;
- psp->state = WAITING_FOR_DECL_OR_RULE;
- }else{
- ErrorMsg(psp->filename,psp->tokenlineno,
- "Illegal argument to %%%s: %s",psp->declkeyword,x);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_DECL_ERROR;
- }
- break;
- case WAITING_FOR_FALLBACK_ID:
- if( x[0]=='.' ){
- psp->state = WAITING_FOR_DECL_OR_RULE;
- }else if( !ISUPPER(x[0]) ){
- ErrorMsg(psp->filename, psp->tokenlineno,
- "%%fallback argument \"%s\" should be a token", x);
- psp->errorcnt++;
- }else{
- struct symbol *sp = Symbol_new(x);
- if( psp->fallback==0 ){
- psp->fallback = sp;
- }else if( sp->fallback ){
- ErrorMsg(psp->filename, psp->tokenlineno,
- "More than one fallback assigned to token %s", x);
- psp->errorcnt++;
- }else{
- sp->fallback = psp->fallback;
- psp->gp->has_fallback = 1;
- }
- }
- break;
- case WAITING_FOR_TOKEN_NAME:
-
- if( x[0]=='.' ){
- psp->state = WAITING_FOR_DECL_OR_RULE;
- }else if( !ISUPPER(x[0]) ){
- ErrorMsg(psp->filename, psp->tokenlineno,
- "%%token argument \"%s\" should be a token", x);
- psp->errorcnt++;
- }else{
- (void)Symbol_new(x);
- }
- break;
- case WAITING_FOR_WILDCARD_ID:
- if( x[0]=='.' ){
- psp->state = WAITING_FOR_DECL_OR_RULE;
- }else if( !ISUPPER(x[0]) ){
- ErrorMsg(psp->filename, psp->tokenlineno,
- "%%wildcard argument \"%s\" should be a token", x);
- psp->errorcnt++;
- }else{
- struct symbol *sp = Symbol_new(x);
- if( psp->gp->wildcard==0 ){
- psp->gp->wildcard = sp;
- }else{
- ErrorMsg(psp->filename, psp->tokenlineno,
- "Extra wildcard to token: %s", x);
- psp->errorcnt++;
- }
- }
- break;
- case WAITING_FOR_CLASS_ID:
- if( !ISLOWER(x[0]) ){
- ErrorMsg(psp->filename, psp->tokenlineno,
- "%%token_class must be followed by an identifier: %s", x);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_DECL_ERROR;
- }else if( Symbol_find(x) ){
- ErrorMsg(psp->filename, psp->tokenlineno,
- "Symbol \"%s\" already used", x);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_DECL_ERROR;
- }else{
- psp->tkclass = Symbol_new(x);
- psp->tkclass->type = MULTITERMINAL;
- psp->state = WAITING_FOR_CLASS_TOKEN;
- }
- break;
- case WAITING_FOR_CLASS_TOKEN:
- if( x[0]=='.' ){
- psp->state = WAITING_FOR_DECL_OR_RULE;
- }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
- struct symbol *msp = psp->tkclass;
- msp->nsubsym++;
- msp->subsym = (struct symbol **) realloc(msp->subsym,
- sizeof(struct symbol*)*msp->nsubsym);
- if( !ISUPPER(x[0]) ) x++;
- msp->subsym[msp->nsubsym-1] = Symbol_new(x);
- }else{
- ErrorMsg(psp->filename, psp->tokenlineno,
- "%%token_class argument \"%s\" should be a token", x);
- psp->errorcnt++;
- psp->state = RESYNC_AFTER_DECL_ERROR;
- }
- break;
- case RESYNC_AFTER_RULE_ERROR:
- case RESYNC_AFTER_DECL_ERROR:
- if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
- if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
- break;
- }
- }
- static int eval_preprocessor_boolean(char *z, int lineno){
- int neg = 0;
- int res = 0;
- int okTerm = 1;
- int i;
- for(i=0; z[i]!=0; i++){
- if( ISSPACE(z[i]) ) continue;
- if( z[i]=='!' ){
- if( !okTerm ) goto pp_syntax_error;
- neg = !neg;
- continue;
- }
- if( z[i]=='|' && z[i+1]=='|' ){
- if( okTerm ) goto pp_syntax_error;
- if( res ) return 1;
- i++;
- okTerm = 1;
- continue;
- }
- if( z[i]=='&' && z[i+1]=='&' ){
- if( okTerm ) goto pp_syntax_error;
- if( !res ) return 0;
- i++;
- okTerm = 1;
- continue;
- }
- if( z[i]=='(' ){
- int k;
- int n = 1;
- if( !okTerm ) goto pp_syntax_error;
- for(k=i+1; z[k]; k++){
- if( z[k]==')' ){
- n--;
- if( n==0 ){
- z[k] = 0;
- res = eval_preprocessor_boolean(&z[i+1], -1);
- z[k] = ')';
- if( res<0 ){
- i = i-res;
- goto pp_syntax_error;
- }
- i = k;
- break;
- }
- }else if( z[k]=='(' ){
- n++;
- }else if( z[k]==0 ){
- i = k;
- goto pp_syntax_error;
- }
- }
- if( neg ){
- res = !res;
- neg = 0;
- }
- okTerm = 0;
- continue;
- }
- if( ISALPHA(z[i]) ){
- int j, k, n;
- if( !okTerm ) goto pp_syntax_error;
- for(k=i+1; ISALNUM(z[k]) || z[k]=='_'; k++){}
- n = k - i;
- res = 0;
- for(j=0; j<nDefine; j++){
- if( strncmp(azDefine[j],&z[i],n)==0 && azDefine[j][n]==0 ){
- res = 1;
- break;
- }
- }
- i = k-1;
- if( neg ){
- res = !res;
- neg = 0;
- }
- okTerm = 0;
- continue;
- }
- goto pp_syntax_error;
- }
- return res;
- pp_syntax_error:
- if( lineno>0 ){
- fprintf(stderr, "%%if syntax error on line %d.\n", lineno);
- fprintf(stderr, " %.*s <-- syntax error here\n", i+1, z);
- exit(1);
- }else{
- return -(i+1);
- }
- }
- static void preprocess_input(char *z){
- int i, j, k;
- int exclude = 0;
- int start = 0;
- int lineno = 1;
- int start_lineno = 1;
- for(i=0; z[i]; i++){
- if( z[i]=='\n' ) lineno++;
- if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
- if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
- if( exclude ){
- exclude--;
- if( exclude==0 ){
- for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
- }
- }
- for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
- }else if( strncmp(&z[i],"%else",5)==0 && ISSPACE(z[i+5]) ){
- if( exclude==1){
- exclude = 0;
- for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
- }else if( exclude==0 ){
- exclude = 1;
- start = i;
- start_lineno = lineno;
- }
- for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
- }else if( strncmp(&z[i],"%ifdef ",7)==0
- || strncmp(&z[i],"%if ",4)==0
- || strncmp(&z[i],"%ifndef ",8)==0 ){
- if( exclude ){
- exclude++;
- }else{
- int isNot;
- int iBool;
- for(j=i; z[j] && !ISSPACE(z[j]); j++){}
- iBool = j;
- isNot = (j==i+7);
- while( z[j] && z[j]!='\n' ){ j++; }
- k = z[j];
- z[j] = 0;
- exclude = eval_preprocessor_boolean(&z[iBool], lineno);
- z[j] = k;
- if( !isNot ) exclude = !exclude;
- if( exclude ){
- start = i;
- start_lineno = lineno;
- }
- }
- for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
- }
- }
- if( exclude ){
- fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
- exit(1);
- }
- }
- void Parse(struct lemon *gp)
- {
- struct pstate ps;
- FILE *fp;
- char *filebuf;
- unsigned int filesize;
- int lineno;
- int c;
- char *cp, *nextcp;
- int startline = 0;
- memset(&ps, '\0', sizeof(ps));
- ps.gp = gp;
- ps.filename = gp->filename;
- ps.errorcnt = 0;
- ps.state = INITIALIZE;
-
- fp = fopen(ps.filename,"rb");
- if( fp==0 ){
- ErrorMsg(ps.filename,0,"Can't open this file for reading.");
- gp->errorcnt++;
- return;
- }
- fseek(fp,0,2);
- filesize = ftell(fp);
- rewind(fp);
- filebuf = (char *)malloc( filesize+1 );
- if( filesize>100000000 || filebuf==0 ){
- ErrorMsg(ps.filename,0,"Input file too large.");
- free(filebuf);
- gp->errorcnt++;
- fclose(fp);
- return;
- }
- if( fread(filebuf,1,filesize,fp)!=filesize ){
- ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
- filesize);
- free(filebuf);
- gp->errorcnt++;
- fclose(fp);
- return;
- }
- fclose(fp);
- filebuf[filesize] = 0;
-
- preprocess_input(filebuf);
- if( gp->printPreprocessed ){
- printf("%s\n", filebuf);
- return;
- }
-
- lineno = 1;
- for(cp=filebuf; (c= *cp)!=0; ){
- if( c=='\n' ) lineno++;
- if( ISSPACE(c) ){ cp++; continue; }
- if( c=='/' && cp[1]=='/' ){
- cp+=2;
- while( (c= *cp)!=0 && c!='\n' ) cp++;
- continue;
- }
- if( c=='/' && cp[1]=='*' ){
- cp+=2;
- if( (*cp)=='/' ) cp++;
- while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
- if( c=='\n' ) lineno++;
- cp++;
- }
- if( c ) cp++;
- continue;
- }
- ps.tokenstart = cp;
- ps.tokenlineno = lineno;
- if( c=='\"' ){
- cp++;
- while( (c= *cp)!=0 && c!='\"' ){
- if( c=='\n' ) lineno++;
- cp++;
- }
- if( c==0 ){
- ErrorMsg(ps.filename,startline,
- "String starting on this line is not terminated before "
- "the end of the file.");
- ps.errorcnt++;
- nextcp = cp;
- }else{
- nextcp = cp+1;
- }
- }else if( c=='{' ){
- int level;
- cp++;
- for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
- if( c=='\n' ) lineno++;
- else if( c=='{' ) level++;
- else if( c=='}' ) level--;
- else if( c=='/' && cp[1]=='*' ){
- int prevc;
- cp = &cp[2];
- prevc = 0;
- while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
- if( c=='\n' ) lineno++;
- prevc = c;
- cp++;
- }
- }else if( c=='/' && cp[1]=='/' ){
- cp = &cp[2];
- while( (c= *cp)!=0 && c!='\n' ) cp++;
- if( c ) lineno++;
- }else if( c=='\'' || c=='\"' ){
- int startchar, prevc;
- startchar = c;
- prevc = 0;
- for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
- if( c=='\n' ) lineno++;
- if( prevc=='\\' ) prevc = 0;
- else prevc = c;
- }
- }
- }
- if( c==0 ){
- ErrorMsg(ps.filename,ps.tokenlineno,
- "C code starting on this line is not terminated before "
- "the end of the file.");
- ps.errorcnt++;
- nextcp = cp;
- }else{
- nextcp = cp+1;
- }
- }else if( ISALNUM(c) ){
- while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
- nextcp = cp;
- }else if( c==':' && cp[1]==':' && cp[2]=='=' ){
- cp += 3;
- nextcp = cp;
- }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
- cp += 2;
- while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
- nextcp = cp;
- }else{
- cp++;
- nextcp = cp;
- }
- c = *cp;
- *cp = 0;
- parseonetoken(&ps);
- *cp = (char)c;
- cp = nextcp;
- }
- free(filebuf);
- gp->rule = ps.firstrule;
- gp->errorcnt = ps.errorcnt;
- }
- static struct plink *plink_freelist = 0;
- struct plink *Plink_new(void){
- struct plink *newlink;
- if( plink_freelist==0 ){
- int i;
- int amt = 100;
- plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
- if( plink_freelist==0 ){
- fprintf(stderr,
- "Unable to allocate memory for a new follow-set propagation link.\n");
- exit(1);
- }
- for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
- plink_freelist[amt-1].next = 0;
- }
- newlink = plink_freelist;
- plink_freelist = plink_freelist->next;
- return newlink;
- }
- void Plink_add(struct plink **plpp, struct config *cfp)
- {
- struct plink *newlink;
- newlink = Plink_new();
- newlink->next = *plpp;
- *plpp = newlink;
- newlink->cfp = cfp;
- }
- void Plink_copy(struct plink **to, struct plink *from)
- {
- struct plink *nextpl;
- while( from ){
- nextpl = from->next;
- from->next = *to;
- *to = from;
- from = nextpl;
- }
- }
- void Plink_delete(struct plink *plp)
- {
- struct plink *nextpl;
- while( plp ){
- nextpl = plp->next;
- plp->next = plink_freelist;
- plink_freelist = plp;
- plp = nextpl;
- }
- }
- PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
- {
- char *name;
- char *cp;
- char *filename = lemp->filename;
- int sz;
- if( outputDir ){
- cp = strrchr(filename, '/');
- if( cp ) filename = cp + 1;
- }
- sz = lemonStrlen(filename);
- sz += lemonStrlen(suffix);
- if( outputDir ) sz += lemonStrlen(outputDir) + 1;
- sz += 5;
- name = (char*)malloc( sz );
- if( name==0 ){
- fprintf(stderr,"Can't allocate space for a filename.\n");
- exit(1);
- }
- name[0] = 0;
- if( outputDir ){
- lemon_strcpy(name, outputDir);
- lemon_strcat(name, "/");
- }
- lemon_strcat(name,filename);
- cp = strrchr(name,'.');
- if( cp ) *cp = 0;
- lemon_strcat(name,suffix);
- return name;
- }
- PRIVATE FILE *file_open(
- struct lemon *lemp,
- const char *suffix,
- const char *mode
- ){
- FILE *fp;
- if( lemp->outname ) free(lemp->outname);
- lemp->outname = file_makename(lemp, suffix);
- fp = fopen(lemp->outname,mode);
- if( fp==0 && *mode=='w' ){
- fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
- lemp->errorcnt++;
- return 0;
- }
- return fp;
- }
- void rule_print(FILE *out, struct rule *rp){
- int i, j;
- fprintf(out, "%s",rp->lhs->name);
-
- fprintf(out," ::=");
- for(i=0; i<rp->nrhs; i++){
- struct symbol *sp = rp->rhs[i];
- if( sp->type==MULTITERMINAL ){
- fprintf(out," %s", sp->subsym[0]->name);
- for(j=1; j<sp->nsubsym; j++){
- fprintf(out,"|%s", sp->subsym[j]->name);
- }
- }else{
- fprintf(out," %s", sp->name);
- }
-
- }
- }
- void Reprint(struct lemon *lemp)
- {
- struct rule *rp;
- struct symbol *sp;
- int i, j, maxlen, len, ncolumns, skip;
- printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
- maxlen = 10;
- for(i=0; i<lemp->nsymbol; i++){
- sp = lemp->symbols[i];
- len = lemonStrlen(sp->name);
- if( len>maxlen ) maxlen = len;
- }
- ncolumns = 76/(maxlen+5);
- if( ncolumns<1 ) ncolumns = 1;
- skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
- for(i=0; i<skip; i++){
- printf("//");
- for(j=i; j<lemp->nsymbol; j+=skip){
- sp = lemp->symbols[j];
- assert( sp->index==j );
- printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
- }
- printf("\n");
- }
- for(rp=lemp->rule; rp; rp=rp->next){
- rule_print(stdout, rp);
- printf(".");
- if( rp->precsym ) printf(" [%s]",rp->precsym->name);
-
- printf("\n");
- }
- }
- void RulePrint(FILE *fp, struct rule *rp, int iCursor){
- struct symbol *sp;
- int i, j;
- fprintf(fp,"%s ::=",rp->lhs->name);
- for(i=0; i<=rp->nrhs; i++){
- if( i==iCursor ) fprintf(fp," *");
- if( i==rp->nrhs ) break;
- sp = rp->rhs[i];
- if( sp->type==MULTITERMINAL ){
- fprintf(fp," %s", sp->subsym[0]->name);
- for(j=1; j<sp->nsubsym; j++){
- fprintf(fp,"|%s",sp->subsym[j]->name);
- }
- }else{
- fprintf(fp," %s", sp->name);
- }
- }
- }
- void ConfigPrint(FILE *fp, struct config *cfp){
- RulePrint(fp, cfp->rp, cfp->dot);
- }
- #if 0
- PRIVATE void SetPrint(out,set,lemp)
- FILE *out;
- char *set;
- struct lemon *lemp;
- {
- int i;
- char *spacer;
- spacer = "";
- fprintf(out,"%12s[","");
- for(i=0; i<lemp->nterminal; i++){
- if( SetFind(set,i) ){
- fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
- spacer = " ";
- }
- }
- fprintf(out,"]\n");
- }
- PRIVATE void PlinkPrint(out,plp,tag)
- FILE *out;
- struct plink *plp;
- char *tag;
- {
- while( plp ){
- fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
- ConfigPrint(out,plp->cfp);
- fprintf(out,"\n");
- plp = plp->next;
- }
- }
- #endif
- int PrintAction(
- struct action *ap,
- FILE *fp,
- int indent
- ){
- int result = 1;
- switch( ap->type ){
- case SHIFT: {
- struct state *stp = ap->x.stp;
- fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
- break;
- }
- case REDUCE: {
- struct rule *rp = ap->x.rp;
- fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
- RulePrint(fp, rp, -1);
- break;
- }
- case SHIFTREDUCE: {
- struct rule *rp = ap->x.rp;
- fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
- RulePrint(fp, rp, -1);
- break;
- }
- case ACCEPT:
- fprintf(fp,"%*s accept",indent,ap->sp->name);
- break;
- case ERROR:
- fprintf(fp,"%*s error",indent,ap->sp->name);
- break;
- case SRCONFLICT:
- case RRCONFLICT:
- fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
- indent,ap->sp->name,ap->x.rp->iRule);
- break;
- case SSCONFLICT:
- fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
- indent,ap->sp->name,ap->x.stp->statenum);
- break;
- case SH_RESOLVED:
- if( showPrecedenceConflict ){
- fprintf(fp,"%*s shift %-7d -- dropped by precedence",
- indent,ap->sp->name,ap->x.stp->statenum);
- }else{
- result = 0;
- }
- break;
- case RD_RESOLVED:
- if( showPrecedenceConflict ){
- fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
- indent,ap->sp->name,ap->x.rp->iRule);
- }else{
- result = 0;
- }
- break;
- case NOT_USED:
- result = 0;
- break;
- }
- if( result && ap->spOpt ){
- fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
- }
- return result;
- }
- void ReportOutput(struct lemon *lemp)
- {
- int i, n;
- struct state *stp;
- struct config *cfp;
- struct action *ap;
- struct rule *rp;
- FILE *fp;
- fp = file_open(lemp,".out","wb");
- if( fp==0 ) return;
- for(i=0; i<lemp->nxstate; i++){
- stp = lemp->sorted[i];
- fprintf(fp,"State %d:\n",stp->statenum);
- if( lemp->basisflag ) cfp=stp->bp;
- else cfp=stp->cfp;
- while( cfp ){
- char buf[20];
- if( cfp->dot==cfp->rp->nrhs ){
- lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
- fprintf(fp," %5s ",buf);
- }else{
- fprintf(fp," ");
- }
- ConfigPrint(fp,cfp);
- fprintf(fp,"\n");
- #if 0
- SetPrint(fp,cfp->fws,lemp);
- PlinkPrint(fp,cfp->fplp,"To ");
- PlinkPrint(fp,cfp->bplp,"From");
- #endif
- if( lemp->basisflag ) cfp=cfp->bp;
- else cfp=cfp->next;
- }
- fprintf(fp,"\n");
- for(ap=stp->ap; ap; ap=ap->next){
- if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
- }
- fprintf(fp,"\n");
- }
- fprintf(fp, "----------------------------------------------------\n");
- fprintf(fp, "Symbols:\n");
- fprintf(fp, "The first-set of non-terminals is shown after the name.\n\n");
- for(i=0; i<lemp->nsymbol; i++){
- int j;
- struct symbol *sp;
- sp = lemp->symbols[i];
- fprintf(fp, " %3d: %s", i, sp->name);
- if( sp->type==NONTERMINAL ){
- fprintf(fp, ":");
- if( sp->lambda ){
- fprintf(fp, " <lambda>");
- }
- for(j=0; j<lemp->nterminal; j++){
- if( sp->firstset && SetFind(sp->firstset, j) ){
- fprintf(fp, " %s", lemp->symbols[j]->name);
- }
- }
- }
- if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
- fprintf(fp, "\n");
- }
- fprintf(fp, "----------------------------------------------------\n");
- fprintf(fp, "Syntax-only Symbols:\n");
- fprintf(fp, "The following symbols never carry semantic content.\n\n");
- for(i=n=0; i<lemp->nsymbol; i++){
- int w;
- struct symbol *sp = lemp->symbols[i];
- if( sp->bContent ) continue;
- w = (int)strlen(sp->name);
- if( n>0 && n+w>75 ){
- fprintf(fp,"\n");
- n = 0;
- }
- if( n>0 ){
- fprintf(fp, " ");
- n++;
- }
- fprintf(fp, "%s", sp->name);
- n += w;
- }
- if( n>0 ) fprintf(fp, "\n");
- fprintf(fp, "----------------------------------------------------\n");
- fprintf(fp, "Rules:\n");
- for(rp=lemp->rule; rp; rp=rp->next){
- fprintf(fp, "%4d: ", rp->iRule);
- rule_print(fp, rp);
- fprintf(fp,".");
- if( rp->precsym ){
- fprintf(fp," [%s precedence=%d]",
- rp->precsym->name, rp->precsym->prec);
- }
- fprintf(fp,"\n");
- }
- fclose(fp);
- return;
- }
- PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
- {
- const char *pathlist;
- char *pathbufptr = 0;
- char *pathbuf = 0;
- char *path,*cp;
- char c;
- #ifdef __WIN32__
- cp = strrchr(argv0,'\\');
- #else
- cp = strrchr(argv0,'/');
- #endif
- if( cp ){
- c = *cp;
- *cp = 0;
- path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
- if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
- *cp = c;
- }else{
- pathlist = getenv("PATH");
- if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
- pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
- path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
- if( (pathbuf != 0) && (path!=0) ){
- pathbufptr = pathbuf;
- lemon_strcpy(pathbuf, pathlist);
- while( *pathbuf ){
- cp = strchr(pathbuf,':');
- if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
- c = *cp;
- *cp = 0;
- lemon_sprintf(path,"%s/%s",pathbuf,name);
- *cp = c;
- if( c==0 ) pathbuf[0] = 0;
- else pathbuf = &cp[1];
- if( access(path,modemask)==0 ) break;
- }
- }
- free(pathbufptr);
- }
- return path;
- }
- PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
- {
- int act;
- switch( ap->type ){
- case SHIFT: act = ap->x.stp->statenum; break;
- case SHIFTREDUCE: {
-
- if( ap->sp->index>=lemp->nterminal
- && (lemp->errsym==0 || ap->sp->index!=lemp->errsym->index)
- ){
- act = lemp->minReduce + ap->x.rp->iRule;
- }else{
- act = lemp->minShiftReduce + ap->x.rp->iRule;
- }
- break;
- }
- case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
- case ERROR: act = lemp->errAction; break;
- case ACCEPT: act = lemp->accAction; break;
- default: act = -1; break;
- }
- return act;
- }
- #define LINESIZE 1000
- PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
- {
- int i, iStart;
- char line[LINESIZE];
- while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
- (*lineno)++;
- iStart = 0;
- if( name ){
- for(i=0; line[i]; i++){
- if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
- && (i==0 || !ISALPHA(line[i-1]))
- ){
- if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
- fprintf(out,"%s",name);
- i += 4;
- iStart = i+1;
- }
- }
- }
- fprintf(out,"%s",&line[iStart]);
- }
- }
- PRIVATE void tplt_skip_header(FILE *in, int *lineno)
- {
- char line[LINESIZE];
- while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
- (*lineno)++;
- }
- }
- PRIVATE FILE *tplt_open(struct lemon *lemp)
- {
- static char templatename[] = "lempar.c";
- char buf[1000];
- FILE *in;
- char *tpltname;
- char *toFree = 0;
- char *cp;
-
- if (user_templatename != 0) {
- if( access(user_templatename,004)==-1 ){
- fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
- user_templatename);
- lemp->errorcnt++;
- return 0;
- }
- in = fopen(user_templatename,"rb");
- if( in==0 ){
- fprintf(stderr,"Can't open the template file \"%s\".\n",
- user_templatename);
- lemp->errorcnt++;
- return 0;
- }
- return in;
- }
- cp = strrchr(lemp->filename,'.');
- if( cp ){
- lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
- }else{
- lemon_sprintf(buf,"%s.lt",lemp->filename);
- }
- if( access(buf,004)==0 ){
- tpltname = buf;
- }else if( access(templatename,004)==0 ){
- tpltname = templatename;
- }else{
- toFree = tpltname = pathsearch(lemp->argv0,templatename,0);
- }
- if( tpltname==0 ){
- fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
- templatename);
- lemp->errorcnt++;
- return 0;
- }
- in = fopen(tpltname,"rb");
- if( in==0 ){
- fprintf(stderr,"Can't open the template file \"%s\".\n",tpltname);
- lemp->errorcnt++;
- }
- free(toFree);
- return in;
- }
- PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
- {
- fprintf(out,"#line %d \"",lineno);
- while( *filename ){
- if( *filename == '\\' ) putc('\\',out);
- putc(*filename,out);
- filename++;
- }
- fprintf(out,"\"\n");
- }
- PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
- {
- if( str==0 ) return;
- while( *str ){
- putc(*str,out);
- if( *str=='\n' ) (*lineno)++;
- str++;
- }
- if( str[-1]!='\n' ){
- putc('\n',out);
- (*lineno)++;
- }
- if (!lemp->nolinenosflag) {
- (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
- }
- return;
- }
- void emit_destructor_code(
- FILE *out,
- struct symbol *sp,
- struct lemon *lemp,
- int *lineno
- ){
- char *cp = 0;
- if( sp->type==TERMINAL ){
- cp = lemp->tokendest;
- if( cp==0 ) return;
- fprintf(out,"{\n"); (*lineno)++;
- }else if( sp->destructor ){
- cp = sp->destructor;
- fprintf(out,"{\n"); (*lineno)++;
- if( !lemp->nolinenosflag ){
- (*lineno)++;
- tplt_linedir(out,sp->destLineno,lemp->filename);
- }
- }else if( lemp->vardest ){
- cp = lemp->vardest;
- if( cp==0 ) return;
- fprintf(out,"{\n"); (*lineno)++;
- }else{
- assert( 0 );
- }
- for(; *cp; cp++){
- if( *cp=='$' && cp[1]=='$' ){
- fprintf(out,"(yypminor->yy%d)",sp->dtnum);
- cp++;
- continue;
- }
- if( *cp=='\n' ) (*lineno)++;
- fputc(*cp,out);
- }
- fprintf(out,"\n"); (*lineno)++;
- if (!lemp->nolinenosflag) {
- (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
- }
- fprintf(out,"}\n"); (*lineno)++;
- return;
- }
- int has_destructor(struct symbol *sp, struct lemon *lemp)
- {
- int ret;
- if( sp->type==TERMINAL ){
- ret = lemp->tokendest!=0;
- }else{
- ret = lemp->vardest!=0 || sp->destructor!=0;
- }
- return ret;
- }
- PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
- static char empty[1] = { 0 };
- static char *z = 0;
- static int alloced = 0;
- static int used = 0;
- int c;
- char zInt[40];
- if( zText==0 ){
- if( used==0 && z!=0 ) z[0] = 0;
- used = 0;
- return z;
- }
- if( n<=0 ){
- if( n<0 ){
- used += n;
- assert( used>=0 );
- }
- n = lemonStrlen(zText);
- }
- if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
- alloced = n + sizeof(zInt)*2 + used + 200;
- z = (char *) realloc(z, alloced);
- }
- if( z==0 ) return empty;
- while( n-- > 0 ){
- c = *(zText++);
- if( c=='%' && n>0 && zText[0]=='d' ){
- lemon_sprintf(zInt, "%d", p1);
- p1 = p2;
- lemon_strcpy(&z[used], zInt);
- used += lemonStrlen(&z[used]);
- zText++;
- n--;
- }else{
- z[used++] = (char)c;
- }
- }
- z[used] = 0;
- return z;
- }
- PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
- char *cp, *xp;
- int i;
- int rc = 0;
- int dontUseRhs0 = 0;
- const char *zSkip = 0;
- char lhsused = 0;
- char lhsdirect;
- char used[MAXRHS];
- char zLhs[50];
- char zOvwrt[900];
- for(i=0; i<rp->nrhs; i++) used[i] = 0;
- lhsused = 0;
- if( rp->code==0 ){
- static char newlinestr[2] = { '\n', '\0' };
- rp->code = newlinestr;
- rp->line = rp->ruleline;
- rp->noCode = 1;
- }else{
- rp->noCode = 0;
- }
- if( rp->nrhs==0 ){
-
- lhsdirect = 1;
- }else if( rp->rhsalias[0]==0 ){
-
- lhsdirect = 1;
- if( has_destructor(rp->rhs[0],lemp) ){
- append_str(0,0,0,0);
- append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
- rp->rhs[0]->index,1-rp->nrhs);
- rp->codePrefix = Strsafe(append_str(0,0,0,0));
- rp->noCode = 0;
- }
- }else if( rp->lhsalias==0 ){
-
- lhsdirect = 1;
- }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
-
- lhsdirect = 1;
- lhsused = 1;
- used[0] = 1;
- if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
- ErrorMsg(lemp->filename,rp->ruleline,
- "%s(%s) and %s(%s) share the same label but have "
- "different datatypes.",
- rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
- lemp->errorcnt++;
- }
- }else{
- lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
- rp->lhsalias, rp->rhsalias[0]);
- zSkip = strstr(rp->code, zOvwrt);
- if( zSkip!=0 ){
-
- lhsdirect = 1;
- }else{
- lhsdirect = 0;
- }
- }
- if( lhsdirect ){
- sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
- }else{
- rc = 1;
- sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
- }
- append_str(0,0,0,0);
-
- for(cp=(char *)rp->code; *cp; cp++){
- if( cp==zSkip ){
- append_str(zOvwrt,0,0,0);
- cp += lemonStrlen(zOvwrt)-1;
- dontUseRhs0 = 1;
- continue;
- }
- if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
- char saved;
- for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
- saved = *xp;
- *xp = 0;
- if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
- append_str(zLhs,0,0,0);
- cp = xp;
- lhsused = 1;
- }else{
- for(i=0; i<rp->nrhs; i++){
- if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
- if( i==0 && dontUseRhs0 ){
- ErrorMsg(lemp->filename,rp->ruleline,
- "Label %s used after '%s'.",
- rp->rhsalias[0], zOvwrt);
- lemp->errorcnt++;
- }else if( cp!=rp->code && cp[-1]=='@' ){
-
- append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
- }else{
- struct symbol *sp = rp->rhs[i];
- int dtnum;
- if( sp->type==MULTITERMINAL ){
- dtnum = sp->subsym[0]->dtnum;
- }else{
- dtnum = sp->dtnum;
- }
- append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
- }
- cp = xp;
- used[i] = 1;
- break;
- }
- }
- }
- *xp = saved;
- }
- append_str(cp, 1, 0, 0);
- }
-
- cp = append_str(0,0,0,0);
- if( cp && cp[0] ) rp->code = Strsafe(cp);
- append_str(0,0,0,0);
-
- if( rp->lhsalias && !lhsused ){
- ErrorMsg(lemp->filename,rp->ruleline,
- "Label \"%s\" for \"%s(%s)\" is never used.",
- rp->lhsalias,rp->lhs->name,rp->lhsalias);
- lemp->errorcnt++;
- }
-
- for(i=0; i<rp->nrhs; i++){
- if( rp->rhsalias[i] ){
- if( i>0 ){
- int j;
- if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
- ErrorMsg(lemp->filename,rp->ruleline,
- "%s(%s) has the same label as the LHS but is not the left-most "
- "symbol on the RHS.",
- rp->rhs[i]->name, rp->rhsalias[i]);
- lemp->errorcnt++;
- }
- for(j=0; j<i; j++){
- if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
- ErrorMsg(lemp->filename,rp->ruleline,
- "Label %s used for multiple symbols on the RHS of a rule.",
- rp->rhsalias[i]);
- lemp->errorcnt++;
- break;
- }
- }
- }
- if( !used[i] ){
- ErrorMsg(lemp->filename,rp->ruleline,
- "Label %s for \"%s(%s)\" is never used.",
- rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
- lemp->errorcnt++;
- }
- }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
- append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
- rp->rhs[i]->index,i-rp->nrhs+1);
- }
- }
-
- if( lhsdirect==0 ){
- append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
- append_str(zLhs, 0, 0, 0);
- append_str(";\n", 0, 0, 0);
- }
-
- cp = append_str(0,0,0,0);
- if( cp && cp[0] ){
- rp->codeSuffix = Strsafe(cp);
- rp->noCode = 0;
- }
- return rc;
- }
- PRIVATE void emit_code(
- FILE *out,
- struct rule *rp,
- struct lemon *lemp,
- int *lineno
- ){
- const char *cp;
-
- if( rp->codePrefix && rp->codePrefix[0] ){
- fprintf(out, "{%s", rp->codePrefix);
- for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
- }
-
- if( rp->code ){
- if( !lemp->nolinenosflag ){
- (*lineno)++;
- tplt_linedir(out,rp->line,lemp->filename);
- }
- fprintf(out,"{%s",rp->code);
- for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
- fprintf(out,"}\n"); (*lineno)++;
- if( !lemp->nolinenosflag ){
- (*lineno)++;
- tplt_linedir(out,*lineno,lemp->outname);
- }
- }
-
- if( rp->codeSuffix && rp->codeSuffix[0] ){
- fprintf(out, "%s", rp->codeSuffix);
- for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
- }
- if( rp->codePrefix ){
- fprintf(out, "}\n"); (*lineno)++;
- }
- return;
- }
- void print_stack_union(
- FILE *out,
- struct lemon *lemp,
- int *plineno,
- int mhflag
- ){
- int lineno;
- char **types;
- int arraysize;
- int maxdtlength;
- char *stddt;
- int i,j;
- unsigned hash;
- const char *name;
-
- arraysize = lemp->nsymbol * 2;
- types = (char**)calloc( arraysize, sizeof(char*) );
- if( types==0 ){
- fprintf(stderr,"Out of memory.\n");
- exit(1);
- }
- for(i=0; i<arraysize; i++) types[i] = 0;
- maxdtlength = 0;
- if( lemp->vartype ){
- maxdtlength = lemonStrlen(lemp->vartype);
- }
- for(i=0; i<lemp->nsymbol; i++){
- int len;
- struct symbol *sp = lemp->symbols[i];
- if( sp->datatype==0 ) continue;
- len = lemonStrlen(sp->datatype);
- if( len>maxdtlength ) maxdtlength = len;
- }
- stddt = (char*)malloc( maxdtlength*2 + 1 );
- if( stddt==0 ){
- fprintf(stderr,"Out of memory.\n");
- exit(1);
- }
-
- for(i=0; i<lemp->nsymbol; i++){
- struct symbol *sp = lemp->symbols[i];
- char *cp;
- if( sp==lemp->errsym ){
- sp->dtnum = arraysize+1;
- continue;
- }
- if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
- sp->dtnum = 0;
- continue;
- }
- cp = sp->datatype;
- if( cp==0 ) cp = lemp->vartype;
- j = 0;
- while( ISSPACE(*cp) ) cp++;
- while( *cp ) stddt[j++] = *cp++;
- while( j>0 && ISSPACE(stddt[j-1]) ) j--;
- stddt[j] = 0;
- if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
- sp->dtnum = 0;
- continue;
- }
- hash = 0;
- for(j=0; stddt[j]; j++){
- hash = hash*53 + stddt[j];
- }
- hash = (hash & 0x7fffffff)%arraysize;
- while( types[hash] ){
- if( strcmp(types[hash],stddt)==0 ){
- sp->dtnum = hash + 1;
- break;
- }
- hash++;
- if( hash>=(unsigned)arraysize ) hash = 0;
- }
- if( types[hash]==0 ){
- sp->dtnum = hash + 1;
- types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
- if( types[hash]==0 ){
- fprintf(stderr,"Out of memory.\n");
- exit(1);
- }
- lemon_strcpy(types[hash],stddt);
- }
- }
-
- name = lemp->name ? lemp->name : "Parse";
- lineno = *plineno;
- if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
- fprintf(out,"#define %sTOKENTYPE %s\n",name,
- lemp->tokentype?lemp->tokentype:"void*"); lineno++;
- if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
- fprintf(out,"typedef union {\n"); lineno++;
- fprintf(out," int yyinit;\n"); lineno++;
- fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
- for(i=0; i<arraysize; i++){
- if( types[i]==0 ) continue;
- fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
- free(types[i]);
- }
- if( lemp->errsym && lemp->errsym->useCnt ){
- fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
- }
- free(stddt);
- free(types);
- fprintf(out,"} YYMINORTYPE;\n"); lineno++;
- *plineno = lineno;
- }
- static const char *minimum_size_type(int lwr, int upr, int *pnByte){
- const char *zType = "int";
- int nByte = 4;
- if( lwr>=0 ){
- if( upr<=255 ){
- zType = "unsigned char";
- nByte = 1;
- }else if( upr<65535 ){
- zType = "unsigned short int";
- nByte = 2;
- }else{
- zType = "unsigned int";
- nByte = 4;
- }
- }else if( lwr>=-127 && upr<=127 ){
- zType = "signed char";
- nByte = 1;
- }else if( lwr>=-32767 && upr<32767 ){
- zType = "short";
- nByte = 2;
- }
- if( pnByte ) *pnByte = nByte;
- return zType;
- }
- struct axset {
- struct state *stp;
- int isTkn;
- int nAction;
- int iOrder;
- };
- static int axset_compare(const void *a, const void *b){
- struct axset *p1 = (struct axset*)a;
- struct axset *p2 = (struct axset*)b;
- int c;
- c = p2->nAction - p1->nAction;
- if( c==0 ){
- c = p1->iOrder - p2->iOrder;
- }
- assert( c!=0 || p1==p2 );
- return c;
- }
- static void writeRuleText(FILE *out, struct rule *rp){
- int j;
- fprintf(out,"%s ::=", rp->lhs->name);
- for(j=0; j<rp->nrhs; j++){
- struct symbol *sp = rp->rhs[j];
- if( sp->type!=MULTITERMINAL ){
- fprintf(out," %s", sp->name);
- }else{
- int k;
- fprintf(out," %s", sp->subsym[0]->name);
- for(k=1; k<sp->nsubsym; k++){
- fprintf(out,"|%s",sp->subsym[k]->name);
- }
- }
- }
- }
- void ReportTable(
- struct lemon *lemp,
- int mhflag,
- int sqlFlag
- ){
- FILE *out, *in, *sql;
- int lineno;
- struct state *stp;
- struct action *ap;
- struct rule *rp;
- struct acttab *pActtab;
- int i, j, n, sz;
- int nLookAhead;
- int szActionType;
- int szCodeType;
- const char *name;
- int mnTknOfst, mxTknOfst;
- int mnNtOfst, mxNtOfst;
- struct axset *ax;
- char *prefix;
- lemp->minShiftReduce = lemp->nstate;
- lemp->errAction = lemp->minShiftReduce + lemp->nrule;
- lemp->accAction = lemp->errAction + 1;
- lemp->noAction = lemp->accAction + 1;
- lemp->minReduce = lemp->noAction + 1;
- lemp->maxAction = lemp->minReduce + lemp->nrule;
- in = tplt_open(lemp);
- if( in==0 ) return;
- out = file_open(lemp,".c","wb");
- if( out==0 ){
- fclose(in);
- return;
- }
- if( sqlFlag==0 ){
- sql = 0;
- }else{
- sql = file_open(lemp, ".sql", "wb");
- if( sql==0 ){
- fclose(in);
- fclose(out);
- return;
- }
- fprintf(sql,
- "BEGIN;\n"
- "CREATE TABLE symbol(\n"
- " id INTEGER PRIMARY KEY,\n"
- " name TEXT NOT NULL,\n"
- " isTerminal BOOLEAN NOT NULL,\n"
- " fallback INTEGER REFERENCES symbol"
- " DEFERRABLE INITIALLY DEFERRED\n"
- ");\n"
- );
- for(i=0; i<lemp->nsymbol; i++){
- fprintf(sql,
- "INSERT INTO symbol(id,name,isTerminal,fallback)"
- "VALUES(%d,'%s',%s",
- i, lemp->symbols[i]->name,
- i<lemp->nterminal ? "TRUE" : "FALSE"
- );
- if( lemp->symbols[i]->fallback ){
- fprintf(sql, ",%d);\n", lemp->symbols[i]->fallback->index);
- }else{
- fprintf(sql, ",NULL);\n");
- }
- }
- fprintf(sql,
- "CREATE TABLE rule(\n"
- " ruleid INTEGER PRIMARY KEY,\n"
- " lhs INTEGER REFERENCES symbol(id),\n"
- " txt TEXT\n"
- ");\n"
- "CREATE TABLE rulerhs(\n"
- " ruleid INTEGER REFERENCES rule(ruleid),\n"
- " pos INTEGER,\n"
- " sym INTEGER REFERENCES symbol(id)\n"
- ");\n"
- );
- for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
- assert( i==rp->iRule );
- fprintf(sql,
- "INSERT INTO rule(ruleid,lhs,txt)VALUES(%d,%d,'",
- rp->iRule, rp->lhs->index
- );
- writeRuleText(sql, rp);
- fprintf(sql,"');\n");
- for(j=0; j<rp->nrhs; j++){
- struct symbol *sp = rp->rhs[j];
- if( sp->type!=MULTITERMINAL ){
- fprintf(sql,
- "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
- i,j,sp->index
- );
- }else{
- int k;
- for(k=0; k<sp->nsubsym; k++){
- fprintf(sql,
- "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
- i,j,sp->subsym[k]->index
- );
- }
- }
- }
- }
- fprintf(sql, "COMMIT;\n");
- }
- lineno = 1;
- fprintf(out,
- "/* This file is automatically generated by Lemon from input grammar\n"
- "** source file \"%s\". */\n", lemp->filename); lineno += 2;
-
-
- if( lemp->include==0 ) lemp->include = "";
- for(i=0; ISSPACE(lemp->include[i]); i++){
- if( lemp->include[i]=='\n' ){
- lemp->include += i+1;
- i = -1;
- }
- }
- if( lemp->include[0]=='/' ){
- tplt_skip_header(in,&lineno);
- }else{
- tplt_xfer(lemp->name,in,out,&lineno);
- }
-
- tplt_print(out,lemp,lemp->include,&lineno);
- if( mhflag ){
- char *incName = file_makename(lemp, ".h");
- fprintf(out,"#include \"%s\"\n", incName); lineno++;
- free(incName);
- }
- tplt_xfer(lemp->name,in,out,&lineno);
-
- if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
- else prefix = "";
- if( mhflag ){
- fprintf(out,"#if INTERFACE\n"); lineno++;
- }else{
- fprintf(out,"#ifndef %s%s\n", prefix, lemp->symbols[1]->name);
- }
- for(i=1; i<lemp->nterminal; i++){
- fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
- lineno++;
- }
- fprintf(out,"#endif\n"); lineno++;
- tplt_xfer(lemp->name,in,out,&lineno);
-
- fprintf(out,"#define YYCODETYPE %s\n",
- minimum_size_type(0, lemp->nsymbol, &szCodeType)); lineno++;
- fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol); lineno++;
- fprintf(out,"#define YYACTIONTYPE %s\n",
- minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
- if( lemp->wildcard ){
- fprintf(out,"#define YYWILDCARD %d\n",
- lemp->wildcard->index); lineno++;
- }
- print_stack_union(out,lemp,&lineno,mhflag);
- fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
- if( lemp->stacksize ){
- fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
- }else{
- fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
- }
- fprintf(out, "#endif\n"); lineno++;
- if( mhflag ){
- fprintf(out,"#if INTERFACE\n"); lineno++;
- }
- name = lemp->name ? lemp->name : "Parse";
- if( lemp->arg && lemp->arg[0] ){
- i = lemonStrlen(lemp->arg);
- while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
- while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
- fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
- fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
- fprintf(out,"#define %sARG_PARAM ,%s\n",name,&lemp->arg[i]); lineno++;
- fprintf(out,"#define %sARG_FETCH %s=yypParser->%s;\n",
- name,lemp->arg,&lemp->arg[i]); lineno++;
- fprintf(out,"#define %sARG_STORE yypParser->%s=%s;\n",
- name,&lemp->arg[i],&lemp->arg[i]); lineno++;
- }else{
- fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
- fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
- fprintf(out,"#define %sARG_PARAM\n",name); lineno++;
- fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
- fprintf(out,"#define %sARG_STORE\n",name); lineno++;
- }
- if( lemp->ctx && lemp->ctx[0] ){
- i = lemonStrlen(lemp->ctx);
- while( i>=1 && ISSPACE(lemp->ctx[i-1]) ) i--;
- while( i>=1 && (ISALNUM(lemp->ctx[i-1]) || lemp->ctx[i-1]=='_') ) i--;
- fprintf(out,"#define %sCTX_SDECL %s;\n",name,lemp->ctx); lineno++;
- fprintf(out,"#define %sCTX_PDECL ,%s\n",name,lemp->ctx); lineno++;
- fprintf(out,"#define %sCTX_PARAM ,%s\n",name,&lemp->ctx[i]); lineno++;
- fprintf(out,"#define %sCTX_FETCH %s=yypParser->%s;\n",
- name,lemp->ctx,&lemp->ctx[i]); lineno++;
- fprintf(out,"#define %sCTX_STORE yypParser->%s=%s;\n",
- name,&lemp->ctx[i],&lemp->ctx[i]); lineno++;
- }else{
- fprintf(out,"#define %sCTX_SDECL\n",name); lineno++;
- fprintf(out,"#define %sCTX_PDECL\n",name); lineno++;
- fprintf(out,"#define %sCTX_PARAM\n",name); lineno++;
- fprintf(out,"#define %sCTX_FETCH\n",name); lineno++;
- fprintf(out,"#define %sCTX_STORE\n",name); lineno++;
- }
- if( mhflag ){
- fprintf(out,"#endif\n"); lineno++;
- }
- if( lemp->errsym && lemp->errsym->useCnt ){
- fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
- fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
- }
- if( lemp->has_fallback ){
- fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
- }
-
- ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
- if( ax==0 ){
- fprintf(stderr,"malloc failed\n");
- exit(1);
- }
- for(i=0; i<lemp->nxstate; i++){
- stp = lemp->sorted[i];
- ax[i*2].stp = stp;
- ax[i*2].isTkn = 1;
- ax[i*2].nAction = stp->nTknAct;
- ax[i*2+1].stp = stp;
- ax[i*2+1].isTkn = 0;
- ax[i*2+1].nAction = stp->nNtAct;
- }
- mxTknOfst = mnTknOfst = 0;
- mxNtOfst = mnNtOfst = 0;
-
- for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
- qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
- pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal);
- for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
- stp = ax[i].stp;
- if( ax[i].isTkn ){
- for(ap=stp->ap; ap; ap=ap->next){
- int action;
- if( ap->sp->index>=lemp->nterminal ) continue;
- action = compute_action(lemp, ap);
- if( action<0 ) continue;
- acttab_action(pActtab, ap->sp->index, action);
- }
- stp->iTknOfst = acttab_insert(pActtab, 1);
- if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
- if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
- }else{
- for(ap=stp->ap; ap; ap=ap->next){
- int action;
- if( ap->sp->index<lemp->nterminal ) continue;
- if( ap->sp->index==lemp->nsymbol ) continue;
- action = compute_action(lemp, ap);
- if( action<0 ) continue;
- acttab_action(pActtab, ap->sp->index, action);
- }
- stp->iNtOfst = acttab_insert(pActtab, 0);
- if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
- if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
- }
- #if 0
- { int jj, nn;
- for(jj=nn=0; jj<pActtab->nAction; jj++){
- if( pActtab->aAction[jj].action<0 ) nn++;
- }
- printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
- i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
- ax[i].nAction, pActtab->nAction, nn);
- }
- #endif
- }
- free(ax);
-
- for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
- for(i=0; i<lemp->nxstate; i++){
- for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
- if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
- ap->x.rp->doesReduce = 1;
- }
- }
- }
-
- fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
- fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
- fprintf(out,"#define YYNRULE_WITH_ACTION %d\n",lemp->nruleWithAction);
- lineno++;
- fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++;
- fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
- i = lemp->minShiftReduce;
- fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++;
- i += lemp->nrule;
- fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
- fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
- fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
- fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
- fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
- i = lemp->minReduce + lemp->nrule;
- fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
- tplt_xfer(lemp->name,in,out,&lineno);
-
-
- lemp->nactiontab = n = acttab_action_size(pActtab);
- lemp->tablesize += n*szActionType;
- fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
- fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
- for(i=j=0; i<n; i++){
- int action = acttab_yyaction(pActtab, i);
- if( action<0 ) action = lemp->noAction;
- if( j==0 ) fprintf(out," /* %5d */ ", i);
- fprintf(out, " %4d,", action);
- if( j==9 || i==n-1 ){
- fprintf(out, "\n"); lineno++;
- j = 0;
- }else{
- j++;
- }
- }
- fprintf(out, "};\n"); lineno++;
-
- lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab);
- lemp->tablesize += n*szCodeType;
- fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
- for(i=j=0; i<n; i++){
- int la = acttab_yylookahead(pActtab, i);
- if( la<0 ) la = lemp->nsymbol;
- if( j==0 ) fprintf(out," /* %5d */ ", i);
- fprintf(out, " %4d,", la);
- if( j==9 ){
- fprintf(out, "\n"); lineno++;
- j = 0;
- }else{
- j++;
- }
- }
-
- nLookAhead = lemp->nterminal + lemp->nactiontab;
- while( i<nLookAhead ){
- if( j==0 ) fprintf(out," /* %5d */ ", i);
- fprintf(out, " %4d,", lemp->nterminal);
- if( j==9 ){
- fprintf(out, "\n"); lineno++;
- j = 0;
- }else{
- j++;
- }
- i++;
- }
- if( j>0 ){ fprintf(out, "\n"); lineno++; }
- fprintf(out, "};\n"); lineno++;
-
- n = lemp->nxstate;
- while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
- fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
- fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
- fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
- fprintf(out, "static const %s yy_shift_ofst[] = {\n",
- minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
- lineno++;
- lemp->tablesize += n*sz;
- for(i=j=0; i<n; i++){
- int ofst;
- stp = lemp->sorted[i];
- ofst = stp->iTknOfst;
- if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
- if( j==0 ) fprintf(out," /* %5d */ ", i);
- fprintf(out, " %4d,", ofst);
- if( j==9 || i==n-1 ){
- fprintf(out, "\n"); lineno++;
- j = 0;
- }else{
- j++;
- }
- }
- fprintf(out, "};\n"); lineno++;
-
- n = lemp->nxstate;
- while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
- fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
- fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
- fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
- fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
- minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
- lemp->tablesize += n*sz;
- for(i=j=0; i<n; i++){
- int ofst;
- stp = lemp->sorted[i];
- ofst = stp->iNtOfst;
- if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
- if( j==0 ) fprintf(out," /* %5d */ ", i);
- fprintf(out, " %4d,", ofst);
- if( j==9 || i==n-1 ){
- fprintf(out, "\n"); lineno++;
- j = 0;
- }else{
- j++;
- }
- }
- fprintf(out, "};\n"); lineno++;
-
- fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
- n = lemp->nxstate;
- lemp->tablesize += n*szActionType;
- for(i=j=0; i<n; i++){
- stp = lemp->sorted[i];
- if( j==0 ) fprintf(out," /* %5d */ ", i);
- if( stp->iDfltReduce<0 ){
- fprintf(out, " %4d,", lemp->errAction);
- }else{
- fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
- }
- if( j==9 || i==n-1 ){
- fprintf(out, "\n"); lineno++;
- j = 0;
- }else{
- j++;
- }
- }
- fprintf(out, "};\n"); lineno++;
- tplt_xfer(lemp->name,in,out,&lineno);
-
- if( lemp->has_fallback ){
- int mx = lemp->nterminal - 1;
-
-
- lemp->tablesize += (mx+1)*szCodeType;
- for(i=0; i<=mx; i++){
- struct symbol *p = lemp->symbols[i];
- if( p->fallback==0 ){
- fprintf(out, " 0, /* %10s => nothing */\n", p->name);
- }else{
- fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
- p->name, p->fallback->name);
- }
- lineno++;
- }
- }
- tplt_xfer(lemp->name, in, out, &lineno);
-
- for(i=0; i<lemp->nsymbol; i++){
- fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++;
- }
- tplt_xfer(lemp->name,in,out,&lineno);
-
- for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
- assert( rp->iRule==i );
- fprintf(out," /* %3d */ \"", i);
- writeRuleText(out, rp);
- fprintf(out,"\",\n"); lineno++;
- }
- tplt_xfer(lemp->name,in,out,&lineno);
-
- if( lemp->tokendest ){
- int once = 1;
- for(i=0; i<lemp->nsymbol; i++){
- struct symbol *sp = lemp->symbols[i];
- if( sp==0 || sp->type!=TERMINAL ) continue;
- if( once ){
- fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
- once = 0;
- }
- fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
- }
- for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
- if( i<lemp->nsymbol ){
- emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
- fprintf(out," break;\n"); lineno++;
- }
- }
- if( lemp->vardest ){
- struct symbol *dflt_sp = 0;
- int once = 1;
- for(i=0; i<lemp->nsymbol; i++){
- struct symbol *sp = lemp->symbols[i];
- if( sp==0 || sp->type==TERMINAL ||
- sp->index<=0 || sp->destructor!=0 ) continue;
- if( once ){
- fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
- once = 0;
- }
- fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
- dflt_sp = sp;
- }
- if( dflt_sp!=0 ){
- emit_destructor_code(out,dflt_sp,lemp,&lineno);
- }
- fprintf(out," break;\n"); lineno++;
- }
- for(i=0; i<lemp->nsymbol; i++){
- struct symbol *sp = lemp->symbols[i];
- if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
- if( sp->destLineno<0 ) continue;
- fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
-
- for(j=i+1; j<lemp->nsymbol; j++){
- struct symbol *sp2 = lemp->symbols[j];
- if( sp2 && sp2->type!=TERMINAL && sp2->destructor
- && sp2->dtnum==sp->dtnum
- && strcmp(sp->destructor,sp2->destructor)==0 ){
- fprintf(out," case %d: /* %s */\n",
- sp2->index, sp2->name); lineno++;
- sp2->destLineno = -1;
- }
- }
- emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
- fprintf(out," break;\n"); lineno++;
- }
- tplt_xfer(lemp->name,in,out,&lineno);
-
- tplt_print(out,lemp,lemp->overflow,&lineno);
- tplt_xfer(lemp->name,in,out,&lineno);
-
- for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
- fprintf(out," %4d, /* (%d) ", rp->lhs->index, i);
- rule_print(out, rp);
- fprintf(out," */\n"); lineno++;
- }
- tplt_xfer(lemp->name,in,out,&lineno);
- for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
- fprintf(out," %3d, /* (%d) ", -rp->nrhs, i);
- rule_print(out, rp);
- fprintf(out," */\n"); lineno++;
- }
- tplt_xfer(lemp->name,in,out,&lineno);
-
- i = 0;
- for(rp=lemp->rule; rp; rp=rp->next){
- i += translate_code(lemp, rp);
- }
- if( i ){
- fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
- }
-
- for(rp=lemp->rule; rp; rp=rp->next){
- struct rule *rp2;
- if( rp->codeEmitted ) continue;
- if( rp->noCode ){
-
- continue;
- }
- fprintf(out," case %d: /* ", rp->iRule);
- writeRuleText(out, rp);
- fprintf(out, " */\n"); lineno++;
- for(rp2=rp->next; rp2; rp2=rp2->next){
- if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
- && rp2->codeSuffix==rp->codeSuffix ){
- fprintf(out," case %d: /* ", rp2->iRule);
- writeRuleText(out, rp2);
- fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
- rp2->codeEmitted = 1;
- }
- }
- emit_code(out,rp,lemp,&lineno);
- fprintf(out," break;\n"); lineno++;
- rp->codeEmitted = 1;
- }
-
- fprintf(out," default:\n"); lineno++;
- for(rp=lemp->rule; rp; rp=rp->next){
- if( rp->codeEmitted ) continue;
- assert( rp->noCode );
- fprintf(out," /* (%d) ", rp->iRule);
- writeRuleText(out, rp);
- if( rp->neverReduce ){
- fprintf(out, " (NEVER REDUCES) */ assert(yyruleno!=%d);\n",
- rp->iRule); lineno++;
- }else if( rp->doesReduce ){
- fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
- }else{
- fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
- rp->iRule); lineno++;
- }
- }
- fprintf(out," break;\n"); lineno++;
- tplt_xfer(lemp->name,in,out,&lineno);
-
- tplt_print(out,lemp,lemp->failure,&lineno);
- tplt_xfer(lemp->name,in,out,&lineno);
-
- tplt_print(out,lemp,lemp->error,&lineno);
- tplt_xfer(lemp->name,in,out,&lineno);
-
- tplt_print(out,lemp,lemp->accept,&lineno);
- tplt_xfer(lemp->name,in,out,&lineno);
-
- tplt_print(out,lemp,lemp->extracode,&lineno);
- acttab_free(pActtab);
- fclose(in);
- fclose(out);
- if( sql ) fclose(sql);
- return;
- }
- void ReportHeader(struct lemon *lemp)
- {
- FILE *out, *in;
- const char *prefix;
- char line[LINESIZE];
- char pattern[LINESIZE];
- int i;
- if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
- else prefix = "";
- in = file_open(lemp,".h","rb");
- if( in ){
- int nextChar;
- for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
- lemon_sprintf(pattern,"#define %s%-30s %3d\n",
- prefix,lemp->symbols[i]->name,i);
- if( strcmp(line,pattern) ) break;
- }
- nextChar = fgetc(in);
- fclose(in);
- if( i==lemp->nterminal && nextChar==EOF ){
-
- return;
- }
- }
- out = file_open(lemp,".h","wb");
- if( out ){
- for(i=1; i<lemp->nterminal; i++){
- fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
- }
- fclose(out);
- }
- return;
- }
- void CompressTables(struct lemon *lemp)
- {
- struct state *stp;
- struct action *ap, *ap2, *nextap;
- struct rule *rp, *rp2, *rbest;
- int nbest, n;
- int i;
- int usesWildcard;
- for(i=0; i<lemp->nstate; i++){
- stp = lemp->sorted[i];
- nbest = 0;
- rbest = 0;
- usesWildcard = 0;
- for(ap=stp->ap; ap; ap=ap->next){
- if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
- usesWildcard = 1;
- }
- if( ap->type!=REDUCE ) continue;
- rp = ap->x.rp;
- if( rp->lhsStart ) continue;
- if( rp==rbest ) continue;
- n = 1;
- for(ap2=ap->next; ap2; ap2=ap2->next){
- if( ap2->type!=REDUCE ) continue;
- rp2 = ap2->x.rp;
- if( rp2==rbest ) continue;
- if( rp2==rp ) n++;
- }
- if( n>nbest ){
- nbest = n;
- rbest = rp;
- }
- }
-
- if( nbest<1 || usesWildcard ) continue;
-
- for(ap=stp->ap; ap; ap=ap->next){
- if( ap->type==REDUCE && ap->x.rp==rbest ) break;
- }
- assert( ap );
- ap->sp = Symbol_new("{default}");
- for(ap=ap->next; ap; ap=ap->next){
- if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
- }
- stp->ap = Action_sort(stp->ap);
- for(ap=stp->ap; ap; ap=ap->next){
- if( ap->type==SHIFT ) break;
- if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
- }
- if( ap==0 ){
- stp->autoReduce = 1;
- stp->pDfltReduce = rbest;
- }
- }
-
- for(i=0; i<lemp->nstate; i++){
- stp = lemp->sorted[i];
- for(ap=stp->ap; ap; ap=ap->next){
- struct state *pNextState;
- if( ap->type!=SHIFT ) continue;
- pNextState = ap->x.stp;
- if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
- ap->type = SHIFTREDUCE;
- ap->x.rp = pNextState->pDfltReduce;
- }
- }
- }
-
- for(i=0; i<lemp->nstate; i++){
- stp = lemp->sorted[i];
- for(ap=stp->ap; ap; ap=nextap){
- nextap = ap->next;
- if( ap->type!=SHIFTREDUCE ) continue;
- rp = ap->x.rp;
- if( rp->noCode==0 ) continue;
- if( rp->nrhs!=1 ) continue;
- #if 1
-
- if( ap->sp->index<lemp->nterminal ) continue;
- #endif
-
- nextap = ap;
- for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
- assert( ap2!=0 );
- ap->spOpt = ap2->sp;
- ap->type = ap2->type;
- ap->x = ap2->x;
- }
- }
- }
- static int stateResortCompare(const void *a, const void *b){
- const struct state *pA = *(const struct state**)a;
- const struct state *pB = *(const struct state**)b;
- int n;
- n = pB->nNtAct - pA->nNtAct;
- if( n==0 ){
- n = pB->nTknAct - pA->nTknAct;
- if( n==0 ){
- n = pB->statenum - pA->statenum;
- }
- }
- assert( n!=0 );
- return n;
- }
- void ResortStates(struct lemon *lemp)
- {
- int i;
- struct state *stp;
- struct action *ap;
- for(i=0; i<lemp->nstate; i++){
- stp = lemp->sorted[i];
- stp->nTknAct = stp->nNtAct = 0;
- stp->iDfltReduce = -1;
- stp->iTknOfst = NO_OFFSET;
- stp->iNtOfst = NO_OFFSET;
- for(ap=stp->ap; ap; ap=ap->next){
- int iAction = compute_action(lemp,ap);
- if( iAction>=0 ){
- if( ap->sp->index<lemp->nterminal ){
- stp->nTknAct++;
- }else if( ap->sp->index<lemp->nsymbol ){
- stp->nNtAct++;
- }else{
- assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
- stp->iDfltReduce = iAction;
- }
- }
- }
- }
- qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
- stateResortCompare);
- for(i=0; i<lemp->nstate; i++){
- lemp->sorted[i]->statenum = i;
- }
- lemp->nxstate = lemp->nstate;
- while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
- lemp->nxstate--;
- }
- }
- static int size = 0;
- void SetSize(int n)
- {
- size = n+1;
- }
- char *SetNew(void){
- char *s;
- s = (char*)calloc( size, 1);
- if( s==0 ){
- memory_error();
- }
- return s;
- }
- void SetFree(char *s)
- {
- free(s);
- }
- int SetAdd(char *s, int e)
- {
- int rv;
- assert( e>=0 && e<size );
- rv = s[e];
- s[e] = 1;
- return !rv;
- }
- int SetUnion(char *s1, char *s2)
- {
- int i, progress;
- progress = 0;
- for(i=0; i<size; i++){
- if( s2[i]==0 ) continue;
- if( s1[i]==0 ){
- progress = 1;
- s1[i] = 1;
- }
- }
- return progress;
- }
- PRIVATE unsigned strhash(const char *x)
- {
- unsigned h = 0;
- while( *x ) h = h*13 + *(x++);
- return h;
- }
- const char *Strsafe(const char *y)
- {
- const char *z;
- char *cpy;
- if( y==0 ) return 0;
- z = Strsafe_find(y);
- if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
- lemon_strcpy(cpy,y);
- z = cpy;
- Strsafe_insert(z);
- }
- MemoryCheck(z);
- return z;
- }
- struct s_x1 {
- int size;
-
-
- int count;
- struct s_x1node *tbl;
- struct s_x1node **ht;
- };
- typedef struct s_x1node {
- const char *data;
- struct s_x1node *next;
- struct s_x1node **from;
- } x1node;
- static struct s_x1 *x1a;
- void Strsafe_init(void){
- if( x1a ) return;
- x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
- if( x1a ){
- x1a->size = 1024;
- x1a->count = 0;
- x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
- if( x1a->tbl==0 ){
- free(x1a);
- x1a = 0;
- }else{
- int i;
- x1a->ht = (x1node**)&(x1a->tbl[1024]);
- for(i=0; i<1024; i++) x1a->ht[i] = 0;
- }
- }
- }
- int Strsafe_insert(const char *data)
- {
- x1node *np;
- unsigned h;
- unsigned ph;
- if( x1a==0 ) return 0;
- ph = strhash(data);
- h = ph & (x1a->size-1);
- np = x1a->ht[h];
- while( np ){
- if( strcmp(np->data,data)==0 ){
-
-
- return 0;
- }
- np = np->next;
- }
- if( x1a->count>=x1a->size ){
-
- int i,arrSize;
- struct s_x1 array;
- array.size = arrSize = x1a->size*2;
- array.count = x1a->count;
- array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
- if( array.tbl==0 ) return 0;
- array.ht = (x1node**)&(array.tbl[arrSize]);
- for(i=0; i<arrSize; i++) array.ht[i] = 0;
- for(i=0; i<x1a->count; i++){
- x1node *oldnp, *newnp;
- oldnp = &(x1a->tbl[i]);
- h = strhash(oldnp->data) & (arrSize-1);
- newnp = &(array.tbl[i]);
- if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
- newnp->next = array.ht[h];
- newnp->data = oldnp->data;
- newnp->from = &(array.ht[h]);
- array.ht[h] = newnp;
- }
-
- *x1a = array;
- }
-
- h = ph & (x1a->size-1);
- np = &(x1a->tbl[x1a->count++]);
- np->data = data;
- if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
- np->next = x1a->ht[h];
- x1a->ht[h] = np;
- np->from = &(x1a->ht[h]);
- return 1;
- }
- const char *Strsafe_find(const char *key)
- {
- unsigned h;
- x1node *np;
- if( x1a==0 ) return 0;
- h = strhash(key) & (x1a->size-1);
- np = x1a->ht[h];
- while( np ){
- if( strcmp(np->data,key)==0 ) break;
- np = np->next;
- }
- return np ? np->data : 0;
- }
- struct symbol *Symbol_new(const char *x)
- {
- struct symbol *sp;
- sp = Symbol_find(x);
- if( sp==0 ){
- sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
- MemoryCheck(sp);
- sp->name = Strsafe(x);
- sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
- sp->rule = 0;
- sp->fallback = 0;
- sp->prec = -1;
- sp->assoc = UNK;
- sp->firstset = 0;
- sp->lambda = LEMON_FALSE;
- sp->destructor = 0;
- sp->destLineno = 0;
- sp->datatype = 0;
- sp->useCnt = 0;
- Symbol_insert(sp,sp->name);
- }
- sp->useCnt++;
- return sp;
- }
- int Symbolcmpp(const void *_a, const void *_b)
- {
- const struct symbol *a = *(const struct symbol **) _a;
- const struct symbol *b = *(const struct symbol **) _b;
- int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
- int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
- return i1==i2 ? a->index - b->index : i1 - i2;
- }
- struct s_x2 {
- int size;
-
-
- int count;
- struct s_x2node *tbl;
- struct s_x2node **ht;
- };
- typedef struct s_x2node {
- struct symbol *data;
- const char *key;
- struct s_x2node *next;
- struct s_x2node **from;
- } x2node;
- static struct s_x2 *x2a;
- void Symbol_init(void){
- if( x2a ) return;
- x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
- if( x2a ){
- x2a->size = 128;
- x2a->count = 0;
- x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
- if( x2a->tbl==0 ){
- free(x2a);
- x2a = 0;
- }else{
- int i;
- x2a->ht = (x2node**)&(x2a->tbl[128]);
- for(i=0; i<128; i++) x2a->ht[i] = 0;
- }
- }
- }
- int Symbol_insert(struct symbol *data, const char *key)
- {
- x2node *np;
- unsigned h;
- unsigned ph;
- if( x2a==0 ) return 0;
- ph = strhash(key);
- h = ph & (x2a->size-1);
- np = x2a->ht[h];
- while( np ){
- if( strcmp(np->key,key)==0 ){
-
-
- return 0;
- }
- np = np->next;
- }
- if( x2a->count>=x2a->size ){
-
- int i,arrSize;
- struct s_x2 array;
- array.size = arrSize = x2a->size*2;
- array.count = x2a->count;
- array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
- if( array.tbl==0 ) return 0;
- array.ht = (x2node**)&(array.tbl[arrSize]);
- for(i=0; i<arrSize; i++) array.ht[i] = 0;
- for(i=0; i<x2a->count; i++){
- x2node *oldnp, *newnp;
- oldnp = &(x2a->tbl[i]);
- h = strhash(oldnp->key) & (arrSize-1);
- newnp = &(array.tbl[i]);
- if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
- newnp->next = array.ht[h];
- newnp->key = oldnp->key;
- newnp->data = oldnp->data;
- newnp->from = &(array.ht[h]);
- array.ht[h] = newnp;
- }
-
- *x2a = array;
- }
-
- h = ph & (x2a->size-1);
- np = &(x2a->tbl[x2a->count++]);
- np->key = key;
- np->data = data;
- if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
- np->next = x2a->ht[h];
- x2a->ht[h] = np;
- np->from = &(x2a->ht[h]);
- return 1;
- }
- struct symbol *Symbol_find(const char *key)
- {
- unsigned h;
- x2node *np;
- if( x2a==0 ) return 0;
- h = strhash(key) & (x2a->size-1);
- np = x2a->ht[h];
- while( np ){
- if( strcmp(np->key,key)==0 ) break;
- np = np->next;
- }
- return np ? np->data : 0;
- }
- struct symbol *Symbol_Nth(int n)
- {
- struct symbol *data;
- if( x2a && n>0 && n<=x2a->count ){
- data = x2a->tbl[n-1].data;
- }else{
- data = 0;
- }
- return data;
- }
- int Symbol_count()
- {
- return x2a ? x2a->count : 0;
- }
- struct symbol **Symbol_arrayof()
- {
- struct symbol **array;
- int i,arrSize;
- if( x2a==0 ) return 0;
- arrSize = x2a->count;
- array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
- if( array ){
- for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
- }
- return array;
- }
- int Configcmp(const char *_a,const char *_b)
- {
- const struct config *a = (struct config *) _a;
- const struct config *b = (struct config *) _b;
- int x;
- x = a->rp->index - b->rp->index;
- if( x==0 ) x = a->dot - b->dot;
- return x;
- }
- PRIVATE int statecmp(struct config *a, struct config *b)
- {
- int rc;
- for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
- rc = a->rp->index - b->rp->index;
- if( rc==0 ) rc = a->dot - b->dot;
- }
- if( rc==0 ){
- if( a ) rc = 1;
- if( b ) rc = -1;
- }
- return rc;
- }
- PRIVATE unsigned statehash(struct config *a)
- {
- unsigned h=0;
- while( a ){
- h = h*571 + a->rp->index*37 + a->dot;
- a = a->bp;
- }
- return h;
- }
- struct state *State_new()
- {
- struct state *newstate;
- newstate = (struct state *)calloc(1, sizeof(struct state) );
- MemoryCheck(newstate);
- return newstate;
- }
- struct s_x3 {
- int size;
-
-
- int count;
- struct s_x3node *tbl;
- struct s_x3node **ht;
- };
- typedef struct s_x3node {
- struct state *data;
- struct config *key;
- struct s_x3node *next;
- struct s_x3node **from;
- } x3node;
- static struct s_x3 *x3a;
- void State_init(void){
- if( x3a ) return;
- x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
- if( x3a ){
- x3a->size = 128;
- x3a->count = 0;
- x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
- if( x3a->tbl==0 ){
- free(x3a);
- x3a = 0;
- }else{
- int i;
- x3a->ht = (x3node**)&(x3a->tbl[128]);
- for(i=0; i<128; i++) x3a->ht[i] = 0;
- }
- }
- }
- int State_insert(struct state *data, struct config *key)
- {
- x3node *np;
- unsigned h;
- unsigned ph;
- if( x3a==0 ) return 0;
- ph = statehash(key);
- h = ph & (x3a->size-1);
- np = x3a->ht[h];
- while( np ){
- if( statecmp(np->key,key)==0 ){
-
-
- return 0;
- }
- np = np->next;
- }
- if( x3a->count>=x3a->size ){
-
- int i,arrSize;
- struct s_x3 array;
- array.size = arrSize = x3a->size*2;
- array.count = x3a->count;
- array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
- if( array.tbl==0 ) return 0;
- array.ht = (x3node**)&(array.tbl[arrSize]);
- for(i=0; i<arrSize; i++) array.ht[i] = 0;
- for(i=0; i<x3a->count; i++){
- x3node *oldnp, *newnp;
- oldnp = &(x3a->tbl[i]);
- h = statehash(oldnp->key) & (arrSize-1);
- newnp = &(array.tbl[i]);
- if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
- newnp->next = array.ht[h];
- newnp->key = oldnp->key;
- newnp->data = oldnp->data;
- newnp->from = &(array.ht[h]);
- array.ht[h] = newnp;
- }
- free(x3a->tbl);
- *x3a = array;
- }
-
- h = ph & (x3a->size-1);
- np = &(x3a->tbl[x3a->count++]);
- np->key = key;
- np->data = data;
- if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
- np->next = x3a->ht[h];
- x3a->ht[h] = np;
- np->from = &(x3a->ht[h]);
- return 1;
- }
- struct state *State_find(struct config *key)
- {
- unsigned h;
- x3node *np;
- if( x3a==0 ) return 0;
- h = statehash(key) & (x3a->size-1);
- np = x3a->ht[h];
- while( np ){
- if( statecmp(np->key,key)==0 ) break;
- np = np->next;
- }
- return np ? np->data : 0;
- }
- struct state **State_arrayof(void)
- {
- struct state **array;
- int i,arrSize;
- if( x3a==0 ) return 0;
- arrSize = x3a->count;
- array = (struct state **)calloc(arrSize, sizeof(struct state *));
- if( array ){
- for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
- }
- return array;
- }
- PRIVATE unsigned confighash(struct config *a)
- {
- unsigned h=0;
- h = h*571 + a->rp->index*37 + a->dot;
- return h;
- }
- struct s_x4 {
- int size;
-
-
- int count;
- struct s_x4node *tbl;
- struct s_x4node **ht;
- };
- typedef struct s_x4node {
- struct config *data;
- struct s_x4node *next;
- struct s_x4node **from;
- } x4node;
- static struct s_x4 *x4a;
- void Configtable_init(void){
- if( x4a ) return;
- x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
- if( x4a ){
- x4a->size = 64;
- x4a->count = 0;
- x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
- if( x4a->tbl==0 ){
- free(x4a);
- x4a = 0;
- }else{
- int i;
- x4a->ht = (x4node**)&(x4a->tbl[64]);
- for(i=0; i<64; i++) x4a->ht[i] = 0;
- }
- }
- }
- int Configtable_insert(struct config *data)
- {
- x4node *np;
- unsigned h;
- unsigned ph;
- if( x4a==0 ) return 0;
- ph = confighash(data);
- h = ph & (x4a->size-1);
- np = x4a->ht[h];
- while( np ){
- if( Configcmp((const char *) np->data,(const char *) data)==0 ){
-
-
- return 0;
- }
- np = np->next;
- }
- if( x4a->count>=x4a->size ){
-
- int i,arrSize;
- struct s_x4 array;
- array.size = arrSize = x4a->size*2;
- array.count = x4a->count;
- array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
- if( array.tbl==0 ) return 0;
- array.ht = (x4node**)&(array.tbl[arrSize]);
- for(i=0; i<arrSize; i++) array.ht[i] = 0;
- for(i=0; i<x4a->count; i++){
- x4node *oldnp, *newnp;
- oldnp = &(x4a->tbl[i]);
- h = confighash(oldnp->data) & (arrSize-1);
- newnp = &(array.tbl[i]);
- if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
- newnp->next = array.ht[h];
- newnp->data = oldnp->data;
- newnp->from = &(array.ht[h]);
- array.ht[h] = newnp;
- }
-
- *x4a = array;
- }
-
- h = ph & (x4a->size-1);
- np = &(x4a->tbl[x4a->count++]);
- np->data = data;
- if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
- np->next = x4a->ht[h];
- x4a->ht[h] = np;
- np->from = &(x4a->ht[h]);
- return 1;
- }
- struct config *Configtable_find(struct config *key)
- {
- int h;
- x4node *np;
- if( x4a==0 ) return 0;
- h = confighash(key) & (x4a->size-1);
- np = x4a->ht[h];
- while( np ){
- if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
- np = np->next;
- }
- return np ? np->data : 0;
- }
- void Configtable_clear(int(*f)(struct config *))
- {
- int i;
- if( x4a==0 || x4a->count==0 ) return;
- if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
- for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
- x4a->count = 0;
- return;
- }
|