lemon.c 177 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893
  1. /*
  2. ** This file contains all sources (including headers) to the LEMON
  3. ** LALR(1) parser generator. The sources have been combined into a
  4. ** single file to make it easy to include LEMON in the source tree
  5. ** and Makefile of another program.
  6. **
  7. ** The author of this program disclaims copyright.
  8. */
  9. #include <stdio.h>
  10. #include <stdarg.h>
  11. #include <string.h>
  12. #include <ctype.h>
  13. #include <stdlib.h>
  14. #include <assert.h>
  15. #define ISSPACE(X) isspace((unsigned char)(X))
  16. #define ISDIGIT(X) isdigit((unsigned char)(X))
  17. #define ISALNUM(X) isalnum((unsigned char)(X))
  18. #define ISALPHA(X) isalpha((unsigned char)(X))
  19. #define ISUPPER(X) isupper((unsigned char)(X))
  20. #define ISLOWER(X) islower((unsigned char)(X))
  21. #ifndef __WIN32__
  22. # if defined(_WIN32) || defined(WIN32)
  23. # define __WIN32__
  24. # endif
  25. #endif
  26. #ifdef __WIN32__
  27. #ifdef __cplusplus
  28. extern "C" {
  29. #endif
  30. extern int access(const char *path, int mode);
  31. #ifdef __cplusplus
  32. }
  33. #endif
  34. #else
  35. #include <unistd.h>
  36. #endif
  37. /* #define PRIVATE static */
  38. #define PRIVATE
  39. #ifdef TEST
  40. #define MAXRHS 5 /* Set low to exercise exception code */
  41. #else
  42. #define MAXRHS 1000
  43. #endif
  44. extern void memory_error();
  45. static int showPrecedenceConflict = 0;
  46. static char *msort(char*,char**,int(*)(const char*,const char*));
  47. /*
  48. ** Compilers are getting increasingly pedantic about type conversions
  49. ** as C evolves ever closer to Ada.... To work around the latest problems
  50. ** we have to define the following variant of strlen().
  51. */
  52. #define lemonStrlen(X) ((int)strlen(X))
  53. /*
  54. ** Compilers are starting to complain about the use of sprintf() and strcpy(),
  55. ** saying they are unsafe. So we define our own versions of those routines too.
  56. **
  57. ** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
  58. ** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
  59. ** The third is a helper routine for vsnprintf() that adds texts to the end of a
  60. ** buffer, making sure the buffer is always zero-terminated.
  61. **
  62. ** The string formatter is a minimal subset of stdlib sprintf() supporting only
  63. ** a few simply conversions:
  64. **
  65. ** %d
  66. ** %s
  67. ** %.*s
  68. **
  69. */
  70. static void lemon_addtext(
  71. char *zBuf, /* The buffer to which text is added */
  72. int *pnUsed, /* Slots of the buffer used so far */
  73. const char *zIn, /* Text to add */
  74. int nIn, /* Bytes of text to add. -1 to use strlen() */
  75. int iWidth /* Field width. Negative to left justify */
  76. ){
  77. if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
  78. while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
  79. if( nIn==0 ) return;
  80. memcpy(&zBuf[*pnUsed], zIn, nIn);
  81. *pnUsed += nIn;
  82. while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
  83. zBuf[*pnUsed] = 0;
  84. }
  85. static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
  86. int i, j, k, c;
  87. int nUsed = 0;
  88. const char *z;
  89. char zTemp[50];
  90. str[0] = 0;
  91. for(i=j=0; (c = zFormat[i])!=0; i++){
  92. if( c=='%' ){
  93. int iWidth = 0;
  94. lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
  95. c = zFormat[++i];
  96. if( ISDIGIT(c) || (c=='-' && ISDIGIT(zFormat[i+1])) ){
  97. if( c=='-' ) i++;
  98. while( ISDIGIT(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
  99. if( c=='-' ) iWidth = -iWidth;
  100. c = zFormat[i];
  101. }
  102. if( c=='d' ){
  103. int v = va_arg(ap, int);
  104. if( v<0 ){
  105. lemon_addtext(str, &nUsed, "-", 1, iWidth);
  106. v = -v;
  107. }else if( v==0 ){
  108. lemon_addtext(str, &nUsed, "0", 1, iWidth);
  109. }
  110. k = 0;
  111. while( v>0 ){
  112. k++;
  113. zTemp[sizeof(zTemp)-k] = (v%10) + '0';
  114. v /= 10;
  115. }
  116. lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
  117. }else if( c=='s' ){
  118. z = va_arg(ap, const char*);
  119. lemon_addtext(str, &nUsed, z, -1, iWidth);
  120. }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
  121. i += 2;
  122. k = va_arg(ap, int);
  123. z = va_arg(ap, const char*);
  124. lemon_addtext(str, &nUsed, z, k, iWidth);
  125. }else if( c=='%' ){
  126. lemon_addtext(str, &nUsed, "%", 1, 0);
  127. }else{
  128. fprintf(stderr, "illegal format\n");
  129. exit(1);
  130. }
  131. j = i+1;
  132. }
  133. }
  134. lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
  135. return nUsed;
  136. }
  137. static int lemon_sprintf(char *str, const char *format, ...){
  138. va_list ap;
  139. int rc;
  140. va_start(ap, format);
  141. rc = lemon_vsprintf(str, format, ap);
  142. va_end(ap);
  143. return rc;
  144. }
  145. static void lemon_strcpy(char *dest, const char *src){
  146. while( (*(dest++) = *(src++))!=0 ){}
  147. }
  148. static void lemon_strcat(char *dest, const char *src){
  149. while( *dest ) dest++;
  150. lemon_strcpy(dest, src);
  151. }
  152. /* a few forward declarations... */
  153. struct rule;
  154. struct lemon;
  155. struct action;
  156. static struct action *Action_new(void);
  157. static struct action *Action_sort(struct action *);
  158. /********** From the file "build.h" ************************************/
  159. void FindRulePrecedences(struct lemon*);
  160. void FindFirstSets(struct lemon*);
  161. void FindStates(struct lemon*);
  162. void FindLinks(struct lemon*);
  163. void FindFollowSets(struct lemon*);
  164. void FindActions(struct lemon*);
  165. /********* From the file "configlist.h" *********************************/
  166. void Configlist_init(void);
  167. struct config *Configlist_add(struct rule *, int);
  168. struct config *Configlist_addbasis(struct rule *, int);
  169. void Configlist_closure(struct lemon *);
  170. void Configlist_sort(void);
  171. void Configlist_sortbasis(void);
  172. struct config *Configlist_return(void);
  173. struct config *Configlist_basis(void);
  174. void Configlist_eat(struct config *);
  175. void Configlist_reset(void);
  176. /********* From the file "error.h" ***************************************/
  177. void ErrorMsg(const char *, int,const char *, ...);
  178. /****** From the file "option.h" ******************************************/
  179. enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
  180. OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
  181. struct s_options {
  182. enum option_type type;
  183. const char *label;
  184. char *arg;
  185. const char *message;
  186. };
  187. int OptInit(char**,struct s_options*,FILE*);
  188. int OptNArgs(void);
  189. char *OptArg(int);
  190. void OptErr(int);
  191. void OptPrint(void);
  192. /******** From the file "parse.h" *****************************************/
  193. void Parse(struct lemon *lemp);
  194. /********* From the file "plink.h" ***************************************/
  195. struct plink *Plink_new(void);
  196. void Plink_add(struct plink **, struct config *);
  197. void Plink_copy(struct plink **, struct plink *);
  198. void Plink_delete(struct plink *);
  199. /********** From the file "report.h" *************************************/
  200. void Reprint(struct lemon *);
  201. void ReportOutput(struct lemon *);
  202. void ReportTable(struct lemon *, int, int);
  203. void ReportHeader(struct lemon *);
  204. void CompressTables(struct lemon *);
  205. void ResortStates(struct lemon *);
  206. /********** From the file "set.h" ****************************************/
  207. void SetSize(int); /* All sets will be of size N */
  208. char *SetNew(void); /* A new set for element 0..N */
  209. void SetFree(char*); /* Deallocate a set */
  210. int SetAdd(char*,int); /* Add element to a set */
  211. int SetUnion(char *,char *); /* A <- A U B, thru element N */
  212. #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
  213. /********** From the file "struct.h" *************************************/
  214. /*
  215. ** Principal data structures for the LEMON parser generator.
  216. */
  217. typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
  218. /* Symbols (terminals and nonterminals) of the grammar are stored
  219. ** in the following: */
  220. enum symbol_type {
  221. TERMINAL,
  222. NONTERMINAL,
  223. MULTITERMINAL
  224. };
  225. enum e_assoc {
  226. LEFT,
  227. RIGHT,
  228. NONE,
  229. UNK
  230. };
  231. struct symbol {
  232. const char *name; /* Name of the symbol */
  233. int index; /* Index number for this symbol */
  234. enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
  235. struct rule *rule; /* Linked list of rules of this (if an NT) */
  236. struct symbol *fallback; /* fallback token in case this token doesn't parse */
  237. int prec; /* Precedence if defined (-1 otherwise) */
  238. enum e_assoc assoc; /* Associativity if precedence is defined */
  239. char *firstset; /* First-set for all rules of this symbol */
  240. Boolean lambda; /* True if NT and can generate an empty string */
  241. int useCnt; /* Number of times used */
  242. char *destructor; /* Code which executes whenever this symbol is
  243. ** popped from the stack during error processing */
  244. int destLineno; /* Line number for start of destructor. Set to
  245. ** -1 for duplicate destructors. */
  246. char *datatype; /* The data type of information held by this
  247. ** object. Only used if type==NONTERMINAL */
  248. int dtnum; /* The data type number. In the parser, the value
  249. ** stack is a union. The .yy%d element of this
  250. ** union is the correct data type for this object */
  251. int bContent; /* True if this symbol ever carries content - if
  252. ** it is ever more than just syntax */
  253. /* The following fields are used by MULTITERMINALs only */
  254. int nsubsym; /* Number of constituent symbols in the MULTI */
  255. struct symbol **subsym; /* Array of constituent symbols */
  256. };
  257. /* Each production rule in the grammar is stored in the following
  258. ** structure. */
  259. struct rule {
  260. struct symbol *lhs; /* Left-hand side of the rule */
  261. const char *lhsalias; /* Alias for the LHS (NULL if none) */
  262. int lhsStart; /* True if left-hand side is the start symbol */
  263. int ruleline; /* Line number for the rule */
  264. int nrhs; /* Number of RHS symbols */
  265. struct symbol **rhs; /* The RHS symbols */
  266. const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
  267. int line; /* Line number at which code begins */
  268. const char *code; /* The code executed when this rule is reduced */
  269. const char *codePrefix; /* Setup code before code[] above */
  270. const char *codeSuffix; /* Breakdown code after code[] above */
  271. struct symbol *precsym; /* Precedence symbol for this rule */
  272. int index; /* An index number for this rule */
  273. int iRule; /* Rule number as used in the generated tables */
  274. Boolean noCode; /* True if this rule has no associated C code */
  275. Boolean codeEmitted; /* True if the code has been emitted already */
  276. Boolean canReduce; /* True if this rule is ever reduced */
  277. Boolean doesReduce; /* Reduce actions occur after optimization */
  278. Boolean neverReduce; /* Reduce is theoretically possible, but prevented
  279. ** by actions or other outside implementation */
  280. struct rule *nextlhs; /* Next rule with the same LHS */
  281. struct rule *next; /* Next rule in the global list */
  282. };
  283. /* A configuration is a production rule of the grammar together with
  284. ** a mark (dot) showing how much of that rule has been processed so far.
  285. ** Configurations also contain a follow-set which is a list of terminal
  286. ** symbols which are allowed to immediately follow the end of the rule.
  287. ** Every configuration is recorded as an instance of the following: */
  288. enum cfgstatus {
  289. COMPLETE,
  290. INCOMPLETE
  291. };
  292. struct config {
  293. struct rule *rp; /* The rule upon which the configuration is based */
  294. int dot; /* The parse point */
  295. char *fws; /* Follow-set for this configuration only */
  296. struct plink *fplp; /* Follow-set forward propagation links */
  297. struct plink *bplp; /* Follow-set backwards propagation links */
  298. struct state *stp; /* Pointer to state which contains this */
  299. enum cfgstatus status; /* used during followset and shift computations */
  300. struct config *next; /* Next configuration in the state */
  301. struct config *bp; /* The next basis configuration */
  302. };
  303. enum e_action {
  304. SHIFT,
  305. ACCEPT,
  306. REDUCE,
  307. ERROR,
  308. SSCONFLICT, /* A shift/shift conflict */
  309. SRCONFLICT, /* Was a reduce, but part of a conflict */
  310. RRCONFLICT, /* Was a reduce, but part of a conflict */
  311. SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
  312. RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
  313. NOT_USED, /* Deleted by compression */
  314. SHIFTREDUCE /* Shift first, then reduce */
  315. };
  316. /* Every shift or reduce operation is stored as one of the following */
  317. struct action {
  318. struct symbol *sp; /* The look-ahead symbol */
  319. enum e_action type;
  320. union {
  321. struct state *stp; /* The new state, if a shift */
  322. struct rule *rp; /* The rule, if a reduce */
  323. } x;
  324. struct symbol *spOpt; /* SHIFTREDUCE optimization to this symbol */
  325. struct action *next; /* Next action for this state */
  326. struct action *collide; /* Next action with the same hash */
  327. };
  328. /* Each state of the generated parser's finite state machine
  329. ** is encoded as an instance of the following structure. */
  330. struct state {
  331. struct config *bp; /* The basis configurations for this state */
  332. struct config *cfp; /* All configurations in this set */
  333. int statenum; /* Sequential number for this state */
  334. struct action *ap; /* List of actions for this state */
  335. int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
  336. int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
  337. int iDfltReduce; /* Default action is to REDUCE by this rule */
  338. struct rule *pDfltReduce;/* The default REDUCE rule. */
  339. int autoReduce; /* True if this is an auto-reduce state */
  340. };
  341. #define NO_OFFSET (-2147483647)
  342. /* A followset propagation link indicates that the contents of one
  343. ** configuration followset should be propagated to another whenever
  344. ** the first changes. */
  345. struct plink {
  346. struct config *cfp; /* The configuration to which linked */
  347. struct plink *next; /* The next propagate link */
  348. };
  349. /* The state vector for the entire parser generator is recorded as
  350. ** follows. (LEMON uses no global variables and makes little use of
  351. ** static variables. Fields in the following structure can be thought
  352. ** of as begin global variables in the program.) */
  353. struct lemon {
  354. struct state **sorted; /* Table of states sorted by state number */
  355. struct rule *rule; /* List of all rules */
  356. struct rule *startRule; /* First rule */
  357. int nstate; /* Number of states */
  358. int nxstate; /* nstate with tail degenerate states removed */
  359. int nrule; /* Number of rules */
  360. int nruleWithAction; /* Number of rules with actions */
  361. int nsymbol; /* Number of terminal and nonterminal symbols */
  362. int nterminal; /* Number of terminal symbols */
  363. int minShiftReduce; /* Minimum shift-reduce action value */
  364. int errAction; /* Error action value */
  365. int accAction; /* Accept action value */
  366. int noAction; /* No-op action value */
  367. int minReduce; /* Minimum reduce action */
  368. int maxAction; /* Maximum action value of any kind */
  369. struct symbol **symbols; /* Sorted array of pointers to symbols */
  370. int errorcnt; /* Number of errors */
  371. struct symbol *errsym; /* The error symbol */
  372. struct symbol *wildcard; /* Token that matches anything */
  373. char *name; /* Name of the generated parser */
  374. char *arg; /* Declaration of the 3rd argument to parser */
  375. char *ctx; /* Declaration of 2nd argument to constructor */
  376. char *tokentype; /* Type of terminal symbols in the parser stack */
  377. char *vartype; /* The default type of non-terminal symbols */
  378. char *start; /* Name of the start symbol for the grammar */
  379. char *stacksize; /* Size of the parser stack */
  380. char *include; /* Code to put at the start of the C file */
  381. char *error; /* Code to execute when an error is seen */
  382. char *overflow; /* Code to execute on a stack overflow */
  383. char *failure; /* Code to execute on parser failure */
  384. char *accept; /* Code to execute when the parser excepts */
  385. char *extracode; /* Code appended to the generated file */
  386. char *tokendest; /* Code to execute to destroy token data */
  387. char *vardest; /* Code for the default non-terminal destructor */
  388. char *filename; /* Name of the input file */
  389. char *outname; /* Name of the current output file */
  390. char *tokenprefix; /* A prefix added to token names in the .h file */
  391. int nconflict; /* Number of parsing conflicts */
  392. int nactiontab; /* Number of entries in the yy_action[] table */
  393. int nlookaheadtab; /* Number of entries in yy_lookahead[] */
  394. int tablesize; /* Total table size of all tables in bytes */
  395. int basisflag; /* Print only basis configurations */
  396. int printPreprocessed; /* Show preprocessor output on stdout */
  397. int has_fallback; /* True if any %fallback is seen in the grammar */
  398. int nolinenosflag; /* True if #line statements should not be printed */
  399. char *argv0; /* Name of the program */
  400. };
  401. #define MemoryCheck(X) if((X)==0){ \
  402. extern void memory_error(); \
  403. memory_error(); \
  404. }
  405. /**************** From the file "table.h" *********************************/
  406. /*
  407. ** All code in this file has been automatically generated
  408. ** from a specification in the file
  409. ** "table.q"
  410. ** by the associative array code building program "aagen".
  411. ** Do not edit this file! Instead, edit the specification
  412. ** file, then rerun aagen.
  413. */
  414. /*
  415. ** Code for processing tables in the LEMON parser generator.
  416. */
  417. /* Routines for handling a strings */
  418. const char *Strsafe(const char *);
  419. void Strsafe_init(void);
  420. int Strsafe_insert(const char *);
  421. const char *Strsafe_find(const char *);
  422. /* Routines for handling symbols of the grammar */
  423. struct symbol *Symbol_new(const char *);
  424. int Symbolcmpp(const void *, const void *);
  425. void Symbol_init(void);
  426. int Symbol_insert(struct symbol *, const char *);
  427. struct symbol *Symbol_find(const char *);
  428. struct symbol *Symbol_Nth(int);
  429. int Symbol_count(void);
  430. struct symbol **Symbol_arrayof(void);
  431. /* Routines to manage the state table */
  432. int Configcmp(const char *, const char *);
  433. struct state *State_new(void);
  434. void State_init(void);
  435. int State_insert(struct state *, struct config *);
  436. struct state *State_find(struct config *);
  437. struct state **State_arrayof(void);
  438. /* Routines used for efficiency in Configlist_add */
  439. void Configtable_init(void);
  440. int Configtable_insert(struct config *);
  441. struct config *Configtable_find(struct config *);
  442. void Configtable_clear(int(*)(struct config *));
  443. /****************** From the file "action.c" *******************************/
  444. /*
  445. ** Routines processing parser actions in the LEMON parser generator.
  446. */
  447. /* Allocate a new parser action */
  448. static struct action *Action_new(void){
  449. static struct action *actionfreelist = 0;
  450. struct action *newaction;
  451. if( actionfreelist==0 ){
  452. int i;
  453. int amt = 100;
  454. actionfreelist = (struct action *)calloc(amt, sizeof(struct action));
  455. if( actionfreelist==0 ){
  456. fprintf(stderr,"Unable to allocate memory for a new parser action.");
  457. exit(1);
  458. }
  459. for(i=0; i<amt-1; i++) actionfreelist[i].next = &actionfreelist[i+1];
  460. actionfreelist[amt-1].next = 0;
  461. }
  462. newaction = actionfreelist;
  463. actionfreelist = actionfreelist->next;
  464. return newaction;
  465. }
  466. /* Compare two actions for sorting purposes. Return negative, zero, or
  467. ** positive if the first action is less than, equal to, or greater than
  468. ** the first
  469. */
  470. static int actioncmp(
  471. struct action *ap1,
  472. struct action *ap2
  473. ){
  474. int rc;
  475. rc = ap1->sp->index - ap2->sp->index;
  476. if( rc==0 ){
  477. rc = (int)ap1->type - (int)ap2->type;
  478. }
  479. if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
  480. rc = ap1->x.rp->index - ap2->x.rp->index;
  481. }
  482. if( rc==0 ){
  483. rc = (int) (ap2 - ap1);
  484. }
  485. return rc;
  486. }
  487. /* Sort parser actions */
  488. static struct action *Action_sort(
  489. struct action *ap
  490. ){
  491. ap = (struct action *)msort((char *)ap,(char **)&ap->next,
  492. (int(*)(const char*,const char*))actioncmp);
  493. return ap;
  494. }
  495. void Action_add(
  496. struct action **app,
  497. enum e_action type,
  498. struct symbol *sp,
  499. char *arg
  500. ){
  501. struct action *newaction;
  502. newaction = Action_new();
  503. newaction->next = *app;
  504. *app = newaction;
  505. newaction->type = type;
  506. newaction->sp = sp;
  507. newaction->spOpt = 0;
  508. if( type==SHIFT ){
  509. newaction->x.stp = (struct state *)arg;
  510. }else{
  511. newaction->x.rp = (struct rule *)arg;
  512. }
  513. }
  514. /********************** New code to implement the "acttab" module ***********/
  515. /*
  516. ** This module implements routines use to construct the yy_action[] table.
  517. */
  518. /*
  519. ** The state of the yy_action table under construction is an instance of
  520. ** the following structure.
  521. **
  522. ** The yy_action table maps the pair (state_number, lookahead) into an
  523. ** action_number. The table is an array of integers pairs. The state_number
  524. ** determines an initial offset into the yy_action array. The lookahead
  525. ** value is then added to this initial offset to get an index X into the
  526. ** yy_action array. If the aAction[X].lookahead equals the value of the
  527. ** of the lookahead input, then the value of the action_number output is
  528. ** aAction[X].action. If the lookaheads do not match then the
  529. ** default action for the state_number is returned.
  530. **
  531. ** All actions associated with a single state_number are first entered
  532. ** into aLookahead[] using multiple calls to acttab_action(). Then the
  533. ** actions for that single state_number are placed into the aAction[]
  534. ** array with a single call to acttab_insert(). The acttab_insert() call
  535. ** also resets the aLookahead[] array in preparation for the next
  536. ** state number.
  537. */
  538. struct lookahead_action {
  539. int lookahead; /* Value of the lookahead token */
  540. int action; /* Action to take on the given lookahead */
  541. };
  542. typedef struct acttab acttab;
  543. struct acttab {
  544. int nAction; /* Number of used slots in aAction[] */
  545. int nActionAlloc; /* Slots allocated for aAction[] */
  546. struct lookahead_action
  547. *aAction, /* The yy_action[] table under construction */
  548. *aLookahead; /* A single new transaction set */
  549. int mnLookahead; /* Minimum aLookahead[].lookahead */
  550. int mnAction; /* Action associated with mnLookahead */
  551. int mxLookahead; /* Maximum aLookahead[].lookahead */
  552. int nLookahead; /* Used slots in aLookahead[] */
  553. int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
  554. int nterminal; /* Number of terminal symbols */
  555. int nsymbol; /* total number of symbols */
  556. };
  557. /* Return the number of entries in the yy_action table */
  558. #define acttab_lookahead_size(X) ((X)->nAction)
  559. /* The value for the N-th entry in yy_action */
  560. #define acttab_yyaction(X,N) ((X)->aAction[N].action)
  561. /* The value for the N-th entry in yy_lookahead */
  562. #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
  563. /* Free all memory associated with the given acttab */
  564. void acttab_free(acttab *p){
  565. free( p->aAction );
  566. free( p->aLookahead );
  567. free( p );
  568. }
  569. /* Allocate a new acttab structure */
  570. acttab *acttab_alloc(int nsymbol, int nterminal){
  571. acttab *p = (acttab *) calloc( 1, sizeof(*p) );
  572. if( p==0 ){
  573. fprintf(stderr,"Unable to allocate memory for a new acttab.");
  574. exit(1);
  575. }
  576. memset(p, 0, sizeof(*p));
  577. p->nsymbol = nsymbol;
  578. p->nterminal = nterminal;
  579. return p;
  580. }
  581. /* Add a new action to the current transaction set.
  582. **
  583. ** This routine is called once for each lookahead for a particular
  584. ** state.
  585. */
  586. void acttab_action(acttab *p, int lookahead, int action){
  587. if( p->nLookahead>=p->nLookaheadAlloc ){
  588. p->nLookaheadAlloc += 25;
  589. p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
  590. sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
  591. if( p->aLookahead==0 ){
  592. fprintf(stderr,"malloc failed\n");
  593. exit(1);
  594. }
  595. }
  596. if( p->nLookahead==0 ){
  597. p->mxLookahead = lookahead;
  598. p->mnLookahead = lookahead;
  599. p->mnAction = action;
  600. }else{
  601. if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
  602. if( p->mnLookahead>lookahead ){
  603. p->mnLookahead = lookahead;
  604. p->mnAction = action;
  605. }
  606. }
  607. p->aLookahead[p->nLookahead].lookahead = lookahead;
  608. p->aLookahead[p->nLookahead].action = action;
  609. p->nLookahead++;
  610. }
  611. /*
  612. ** Add the transaction set built up with prior calls to acttab_action()
  613. ** into the current action table. Then reset the transaction set back
  614. ** to an empty set in preparation for a new round of acttab_action() calls.
  615. **
  616. ** Return the offset into the action table of the new transaction.
  617. **
  618. ** If the makeItSafe parameter is true, then the offset is chosen so that
  619. ** it is impossible to overread the yy_lookaside[] table regardless of
  620. ** the lookaside token. This is done for the terminal symbols, as they
  621. ** come from external inputs and can contain syntax errors. When makeItSafe
  622. ** is false, there is more flexibility in selecting offsets, resulting in
  623. ** a smaller table. For non-terminal symbols, which are never syntax errors,
  624. ** makeItSafe can be false.
  625. */
  626. int acttab_insert(acttab *p, int makeItSafe){
  627. int i, j, k, n, end;
  628. assert( p->nLookahead>0 );
  629. /* Make sure we have enough space to hold the expanded action table
  630. ** in the worst case. The worst case occurs if the transaction set
  631. ** must be appended to the current action table
  632. */
  633. n = p->nsymbol + 1;
  634. if( p->nAction + n >= p->nActionAlloc ){
  635. int oldAlloc = p->nActionAlloc;
  636. p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
  637. p->aAction = (struct lookahead_action *) realloc( p->aAction,
  638. sizeof(p->aAction[0])*p->nActionAlloc);
  639. if( p->aAction==0 ){
  640. fprintf(stderr,"malloc failed\n");
  641. exit(1);
  642. }
  643. for(i=oldAlloc; i<p->nActionAlloc; i++){
  644. p->aAction[i].lookahead = -1;
  645. p->aAction[i].action = -1;
  646. }
  647. }
  648. /* Scan the existing action table looking for an offset that is a
  649. ** duplicate of the current transaction set. Fall out of the loop
  650. ** if and when the duplicate is found.
  651. **
  652. ** i is the index in p->aAction[] where p->mnLookahead is inserted.
  653. */
  654. end = makeItSafe ? p->mnLookahead : 0;
  655. for(i=p->nAction-1; i>=end; i--){
  656. if( p->aAction[i].lookahead==p->mnLookahead ){
  657. /* All lookaheads and actions in the aLookahead[] transaction
  658. ** must match against the candidate aAction[i] entry. */
  659. if( p->aAction[i].action!=p->mnAction ) continue;
  660. for(j=0; j<p->nLookahead; j++){
  661. k = p->aLookahead[j].lookahead - p->mnLookahead + i;
  662. if( k<0 || k>=p->nAction ) break;
  663. if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
  664. if( p->aLookahead[j].action!=p->aAction[k].action ) break;
  665. }
  666. if( j<p->nLookahead ) continue;
  667. /* No possible lookahead value that is not in the aLookahead[]
  668. ** transaction is allowed to match aAction[i] */
  669. n = 0;
  670. for(j=0; j<p->nAction; j++){
  671. if( p->aAction[j].lookahead<0 ) continue;
  672. if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
  673. }
  674. if( n==p->nLookahead ){
  675. break; /* An exact match is found at offset i */
  676. }
  677. }
  678. }
  679. /* If no existing offsets exactly match the current transaction, find an
  680. ** an empty offset in the aAction[] table in which we can add the
  681. ** aLookahead[] transaction.
  682. */
  683. if( i<end ){
  684. /* Look for holes in the aAction[] table that fit the current
  685. ** aLookahead[] transaction. Leave i set to the offset of the hole.
  686. ** If no holes are found, i is left at p->nAction, which means the
  687. ** transaction will be appended. */
  688. i = makeItSafe ? p->mnLookahead : 0;
  689. for(; i<p->nActionAlloc - p->mxLookahead; i++){
  690. if( p->aAction[i].lookahead<0 ){
  691. for(j=0; j<p->nLookahead; j++){
  692. k = p->aLookahead[j].lookahead - p->mnLookahead + i;
  693. if( k<0 ) break;
  694. if( p->aAction[k].lookahead>=0 ) break;
  695. }
  696. if( j<p->nLookahead ) continue;
  697. for(j=0; j<p->nAction; j++){
  698. if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
  699. }
  700. if( j==p->nAction ){
  701. break; /* Fits in empty slots */
  702. }
  703. }
  704. }
  705. }
  706. /* Insert transaction set at index i. */
  707. #if 0
  708. printf("Acttab:");
  709. for(j=0; j<p->nLookahead; j++){
  710. printf(" %d", p->aLookahead[j].lookahead);
  711. }
  712. printf(" inserted at %d\n", i);
  713. #endif
  714. for(j=0; j<p->nLookahead; j++){
  715. k = p->aLookahead[j].lookahead - p->mnLookahead + i;
  716. p->aAction[k] = p->aLookahead[j];
  717. if( k>=p->nAction ) p->nAction = k+1;
  718. }
  719. if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1;
  720. p->nLookahead = 0;
  721. /* Return the offset that is added to the lookahead in order to get the
  722. ** index into yy_action of the action */
  723. return i - p->mnLookahead;
  724. }
  725. /*
  726. ** Return the size of the action table without the trailing syntax error
  727. ** entries.
  728. */
  729. int acttab_action_size(acttab *p){
  730. int n = p->nAction;
  731. while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; }
  732. return n;
  733. }
  734. /********************** From the file "build.c" *****************************/
  735. /*
  736. ** Routines to construction the finite state machine for the LEMON
  737. ** parser generator.
  738. */
  739. /* Find a precedence symbol of every rule in the grammar.
  740. **
  741. ** Those rules which have a precedence symbol coded in the input
  742. ** grammar using the "[symbol]" construct will already have the
  743. ** rp->precsym field filled. Other rules take as their precedence
  744. ** symbol the first RHS symbol with a defined precedence. If there
  745. ** are not RHS symbols with a defined precedence, the precedence
  746. ** symbol field is left blank.
  747. */
  748. void FindRulePrecedences(struct lemon *xp)
  749. {
  750. struct rule *rp;
  751. for(rp=xp->rule; rp; rp=rp->next){
  752. if( rp->precsym==0 ){
  753. int i, j;
  754. for(i=0; i<rp->nrhs && rp->precsym==0; i++){
  755. struct symbol *sp = rp->rhs[i];
  756. if( sp->type==MULTITERMINAL ){
  757. for(j=0; j<sp->nsubsym; j++){
  758. if( sp->subsym[j]->prec>=0 ){
  759. rp->precsym = sp->subsym[j];
  760. break;
  761. }
  762. }
  763. }else if( sp->prec>=0 ){
  764. rp->precsym = rp->rhs[i];
  765. }
  766. }
  767. }
  768. }
  769. return;
  770. }
  771. /* Find all nonterminals which will generate the empty string.
  772. ** Then go back and compute the first sets of every nonterminal.
  773. ** The first set is the set of all terminal symbols which can begin
  774. ** a string generated by that nonterminal.
  775. */
  776. void FindFirstSets(struct lemon *lemp)
  777. {
  778. int i, j;
  779. struct rule *rp;
  780. int progress;
  781. for(i=0; i<lemp->nsymbol; i++){
  782. lemp->symbols[i]->lambda = LEMON_FALSE;
  783. }
  784. for(i=lemp->nterminal; i<lemp->nsymbol; i++){
  785. lemp->symbols[i]->firstset = SetNew();
  786. }
  787. /* First compute all lambdas */
  788. do{
  789. progress = 0;
  790. for(rp=lemp->rule; rp; rp=rp->next){
  791. if( rp->lhs->lambda ) continue;
  792. for(i=0; i<rp->nrhs; i++){
  793. struct symbol *sp = rp->rhs[i];
  794. assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
  795. if( sp->lambda==LEMON_FALSE ) break;
  796. }
  797. if( i==rp->nrhs ){
  798. rp->lhs->lambda = LEMON_TRUE;
  799. progress = 1;
  800. }
  801. }
  802. }while( progress );
  803. /* Now compute all first sets */
  804. do{
  805. struct symbol *s1, *s2;
  806. progress = 0;
  807. for(rp=lemp->rule; rp; rp=rp->next){
  808. s1 = rp->lhs;
  809. for(i=0; i<rp->nrhs; i++){
  810. s2 = rp->rhs[i];
  811. if( s2->type==TERMINAL ){
  812. progress += SetAdd(s1->firstset,s2->index);
  813. break;
  814. }else if( s2->type==MULTITERMINAL ){
  815. for(j=0; j<s2->nsubsym; j++){
  816. progress += SetAdd(s1->firstset,s2->subsym[j]->index);
  817. }
  818. break;
  819. }else if( s1==s2 ){
  820. if( s1->lambda==LEMON_FALSE ) break;
  821. }else{
  822. progress += SetUnion(s1->firstset,s2->firstset);
  823. if( s2->lambda==LEMON_FALSE ) break;
  824. }
  825. }
  826. }
  827. }while( progress );
  828. return;
  829. }
  830. /* Compute all LR(0) states for the grammar. Links
  831. ** are added to between some states so that the LR(1) follow sets
  832. ** can be computed later.
  833. */
  834. PRIVATE struct state *getstate(struct lemon *); /* forward reference */
  835. void FindStates(struct lemon *lemp)
  836. {
  837. struct symbol *sp;
  838. struct rule *rp;
  839. Configlist_init();
  840. /* Find the start symbol */
  841. if( lemp->start ){
  842. sp = Symbol_find(lemp->start);
  843. if( sp==0 ){
  844. ErrorMsg(lemp->filename,0,
  845. "The specified start symbol \"%s\" is not "
  846. "in a nonterminal of the grammar. \"%s\" will be used as the start "
  847. "symbol instead.",lemp->start,lemp->startRule->lhs->name);
  848. lemp->errorcnt++;
  849. sp = lemp->startRule->lhs;
  850. }
  851. }else if( lemp->startRule ){
  852. sp = lemp->startRule->lhs;
  853. }else{
  854. ErrorMsg(lemp->filename,0,"Internal error - no start rule\n");
  855. exit(1);
  856. }
  857. /* Make sure the start symbol doesn't occur on the right-hand side of
  858. ** any rule. Report an error if it does. (YACC would generate a new
  859. ** start symbol in this case.) */
  860. for(rp=lemp->rule; rp; rp=rp->next){
  861. int i;
  862. for(i=0; i<rp->nrhs; i++){
  863. if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
  864. ErrorMsg(lemp->filename,0,
  865. "The start symbol \"%s\" occurs on the "
  866. "right-hand side of a rule. This will result in a parser which "
  867. "does not work properly.",sp->name);
  868. lemp->errorcnt++;
  869. }
  870. }
  871. }
  872. /* The basis configuration set for the first state
  873. ** is all rules which have the start symbol as their
  874. ** left-hand side */
  875. for(rp=sp->rule; rp; rp=rp->nextlhs){
  876. struct config *newcfp;
  877. rp->lhsStart = 1;
  878. newcfp = Configlist_addbasis(rp,0);
  879. SetAdd(newcfp->fws,0);
  880. }
  881. /* Compute the first state. All other states will be
  882. ** computed automatically during the computation of the first one.
  883. ** The returned pointer to the first state is not used. */
  884. (void)getstate(lemp);
  885. return;
  886. }
  887. /* Return a pointer to a state which is described by the configuration
  888. ** list which has been built from calls to Configlist_add.
  889. */
  890. PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
  891. PRIVATE struct state *getstate(struct lemon *lemp)
  892. {
  893. struct config *cfp, *bp;
  894. struct state *stp;
  895. /* Extract the sorted basis of the new state. The basis was constructed
  896. ** by prior calls to "Configlist_addbasis()". */
  897. Configlist_sortbasis();
  898. bp = Configlist_basis();
  899. /* Get a state with the same basis */
  900. stp = State_find(bp);
  901. if( stp ){
  902. /* A state with the same basis already exists! Copy all the follow-set
  903. ** propagation links from the state under construction into the
  904. ** preexisting state, then return a pointer to the preexisting state */
  905. struct config *x, *y;
  906. for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
  907. Plink_copy(&y->bplp,x->bplp);
  908. Plink_delete(x->fplp);
  909. x->fplp = x->bplp = 0;
  910. }
  911. cfp = Configlist_return();
  912. Configlist_eat(cfp);
  913. }else{
  914. /* This really is a new state. Construct all the details */
  915. Configlist_closure(lemp); /* Compute the configuration closure */
  916. Configlist_sort(); /* Sort the configuration closure */
  917. cfp = Configlist_return(); /* Get a pointer to the config list */
  918. stp = State_new(); /* A new state structure */
  919. MemoryCheck(stp);
  920. stp->bp = bp; /* Remember the configuration basis */
  921. stp->cfp = cfp; /* Remember the configuration closure */
  922. stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
  923. stp->ap = 0; /* No actions, yet. */
  924. State_insert(stp,stp->bp); /* Add to the state table */
  925. buildshifts(lemp,stp); /* Recursively compute successor states */
  926. }
  927. return stp;
  928. }
  929. /*
  930. ** Return true if two symbols are the same.
  931. */
  932. int same_symbol(struct symbol *a, struct symbol *b)
  933. {
  934. int i;
  935. if( a==b ) return 1;
  936. if( a->type!=MULTITERMINAL ) return 0;
  937. if( b->type!=MULTITERMINAL ) return 0;
  938. if( a->nsubsym!=b->nsubsym ) return 0;
  939. for(i=0; i<a->nsubsym; i++){
  940. if( a->subsym[i]!=b->subsym[i] ) return 0;
  941. }
  942. return 1;
  943. }
  944. /* Construct all successor states to the given state. A "successor"
  945. ** state is any state which can be reached by a shift action.
  946. */
  947. PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
  948. {
  949. struct config *cfp; /* For looping thru the config closure of "stp" */
  950. struct config *bcfp; /* For the inner loop on config closure of "stp" */
  951. struct config *newcfg; /* */
  952. struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
  953. struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
  954. struct state *newstp; /* A pointer to a successor state */
  955. /* Each configuration becomes complete after it contributes to a successor
  956. ** state. Initially, all configurations are incomplete */
  957. for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
  958. /* Loop through all configurations of the state "stp" */
  959. for(cfp=stp->cfp; cfp; cfp=cfp->next){
  960. if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
  961. if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
  962. Configlist_reset(); /* Reset the new config set */
  963. sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
  964. /* For every configuration in the state "stp" which has the symbol "sp"
  965. ** following its dot, add the same configuration to the basis set under
  966. ** construction but with the dot shifted one symbol to the right. */
  967. for(bcfp=cfp; bcfp; bcfp=bcfp->next){
  968. if( bcfp->status==COMPLETE ) continue; /* Already used */
  969. if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
  970. bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
  971. if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
  972. bcfp->status = COMPLETE; /* Mark this config as used */
  973. newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
  974. Plink_add(&newcfg->bplp,bcfp);
  975. }
  976. /* Get a pointer to the state described by the basis configuration set
  977. ** constructed in the preceding loop */
  978. newstp = getstate(lemp);
  979. /* The state "newstp" is reached from the state "stp" by a shift action
  980. ** on the symbol "sp" */
  981. if( sp->type==MULTITERMINAL ){
  982. int i;
  983. for(i=0; i<sp->nsubsym; i++){
  984. Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
  985. }
  986. }else{
  987. Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
  988. }
  989. }
  990. }
  991. /*
  992. ** Construct the propagation links
  993. */
  994. void FindLinks(struct lemon *lemp)
  995. {
  996. int i;
  997. struct config *cfp, *other;
  998. struct state *stp;
  999. struct plink *plp;
  1000. /* Housekeeping detail:
  1001. ** Add to every propagate link a pointer back to the state to
  1002. ** which the link is attached. */
  1003. for(i=0; i<lemp->nstate; i++){
  1004. stp = lemp->sorted[i];
  1005. for(cfp=stp?stp->cfp:0; cfp; cfp=cfp->next){
  1006. cfp->stp = stp;
  1007. }
  1008. }
  1009. /* Convert all backlinks into forward links. Only the forward
  1010. ** links are used in the follow-set computation. */
  1011. for(i=0; i<lemp->nstate; i++){
  1012. stp = lemp->sorted[i];
  1013. for(cfp=stp?stp->cfp:0; cfp; cfp=cfp->next){
  1014. for(plp=cfp->bplp; plp; plp=plp->next){
  1015. other = plp->cfp;
  1016. Plink_add(&other->fplp,cfp);
  1017. }
  1018. }
  1019. }
  1020. }
  1021. /* Compute all followsets.
  1022. **
  1023. ** A followset is the set of all symbols which can come immediately
  1024. ** after a configuration.
  1025. */
  1026. void FindFollowSets(struct lemon *lemp)
  1027. {
  1028. int i;
  1029. struct config *cfp;
  1030. struct plink *plp;
  1031. int progress;
  1032. int change;
  1033. for(i=0; i<lemp->nstate; i++){
  1034. assert( lemp->sorted[i]!=0 );
  1035. for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
  1036. cfp->status = INCOMPLETE;
  1037. }
  1038. }
  1039. do{
  1040. progress = 0;
  1041. for(i=0; i<lemp->nstate; i++){
  1042. assert( lemp->sorted[i]!=0 );
  1043. for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
  1044. if( cfp->status==COMPLETE ) continue;
  1045. for(plp=cfp->fplp; plp; plp=plp->next){
  1046. change = SetUnion(plp->cfp->fws,cfp->fws);
  1047. if( change ){
  1048. plp->cfp->status = INCOMPLETE;
  1049. progress = 1;
  1050. }
  1051. }
  1052. cfp->status = COMPLETE;
  1053. }
  1054. }
  1055. }while( progress );
  1056. }
  1057. static int resolve_conflict(struct action *,struct action *);
  1058. /* Compute the reduce actions, and resolve conflicts.
  1059. */
  1060. void FindActions(struct lemon *lemp)
  1061. {
  1062. int i,j;
  1063. struct config *cfp;
  1064. struct state *stp;
  1065. struct symbol *sp;
  1066. struct rule *rp;
  1067. /* Add all of the reduce actions
  1068. ** A reduce action is added for each element of the followset of
  1069. ** a configuration which has its dot at the extreme right.
  1070. */
  1071. for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
  1072. stp = lemp->sorted[i];
  1073. for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
  1074. if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
  1075. for(j=0; j<lemp->nterminal; j++){
  1076. if( SetFind(cfp->fws,j) ){
  1077. /* Add a reduce action to the state "stp" which will reduce by the
  1078. ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
  1079. Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
  1080. }
  1081. }
  1082. }
  1083. }
  1084. }
  1085. /* Add the accepting token */
  1086. if( lemp->start ){
  1087. sp = Symbol_find(lemp->start);
  1088. if( sp==0 ){
  1089. if( lemp->startRule==0 ){
  1090. fprintf(stderr, "internal error on source line %d: no start rule\n",
  1091. __LINE__);
  1092. exit(1);
  1093. }
  1094. sp = lemp->startRule->lhs;
  1095. }
  1096. }else{
  1097. sp = lemp->startRule->lhs;
  1098. }
  1099. /* Add to the first state (which is always the starting state of the
  1100. ** finite state machine) an action to ACCEPT if the lookahead is the
  1101. ** start nonterminal. */
  1102. Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
  1103. /* Resolve conflicts */
  1104. for(i=0; i<lemp->nstate; i++){
  1105. struct action *ap, *nap;
  1106. stp = lemp->sorted[i];
  1107. /* assert( stp->ap ); */
  1108. stp->ap = Action_sort(stp->ap);
  1109. for(ap=stp->ap; ap && ap->next; ap=ap->next){
  1110. for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
  1111. /* The two actions "ap" and "nap" have the same lookahead.
  1112. ** Figure out which one should be used */
  1113. lemp->nconflict += resolve_conflict(ap,nap);
  1114. }
  1115. }
  1116. }
  1117. /* Report an error for each rule that can never be reduced. */
  1118. for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
  1119. for(i=0; i<lemp->nstate; i++){
  1120. struct action *ap;
  1121. for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
  1122. if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
  1123. }
  1124. }
  1125. for(rp=lemp->rule; rp; rp=rp->next){
  1126. if( rp->canReduce ) continue;
  1127. ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
  1128. lemp->errorcnt++;
  1129. }
  1130. }
  1131. /* Resolve a conflict between the two given actions. If the
  1132. ** conflict can't be resolved, return non-zero.
  1133. **
  1134. ** NO LONGER TRUE:
  1135. ** To resolve a conflict, first look to see if either action
  1136. ** is on an error rule. In that case, take the action which
  1137. ** is not associated with the error rule. If neither or both
  1138. ** actions are associated with an error rule, then try to
  1139. ** use precedence to resolve the conflict.
  1140. **
  1141. ** If either action is a SHIFT, then it must be apx. This
  1142. ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
  1143. */
  1144. static int resolve_conflict(
  1145. struct action *apx,
  1146. struct action *apy
  1147. ){
  1148. struct symbol *spx, *spy;
  1149. int errcnt = 0;
  1150. assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
  1151. if( apx->type==SHIFT && apy->type==SHIFT ){
  1152. apy->type = SSCONFLICT;
  1153. errcnt++;
  1154. }
  1155. if( apx->type==SHIFT && apy->type==REDUCE ){
  1156. spx = apx->sp;
  1157. spy = apy->x.rp->precsym;
  1158. if( spy==0 || spx->prec<0 || spy->prec<0 ){
  1159. /* Not enough precedence information. */
  1160. apy->type = SRCONFLICT;
  1161. errcnt++;
  1162. }else if( spx->prec>spy->prec ){ /* higher precedence wins */
  1163. apy->type = RD_RESOLVED;
  1164. }else if( spx->prec<spy->prec ){
  1165. apx->type = SH_RESOLVED;
  1166. }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
  1167. apy->type = RD_RESOLVED; /* associativity */
  1168. }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
  1169. apx->type = SH_RESOLVED;
  1170. }else{
  1171. assert( spx->prec==spy->prec && spx->assoc==NONE );
  1172. apx->type = ERROR;
  1173. }
  1174. }else if( apx->type==REDUCE && apy->type==REDUCE ){
  1175. spx = apx->x.rp->precsym;
  1176. spy = apy->x.rp->precsym;
  1177. if( spx==0 || spy==0 || spx->prec<0 ||
  1178. spy->prec<0 || spx->prec==spy->prec ){
  1179. apy->type = RRCONFLICT;
  1180. errcnt++;
  1181. }else if( spx->prec>spy->prec ){
  1182. apy->type = RD_RESOLVED;
  1183. }else if( spx->prec<spy->prec ){
  1184. apx->type = RD_RESOLVED;
  1185. }
  1186. }else{
  1187. assert(
  1188. apx->type==SH_RESOLVED ||
  1189. apx->type==RD_RESOLVED ||
  1190. apx->type==SSCONFLICT ||
  1191. apx->type==SRCONFLICT ||
  1192. apx->type==RRCONFLICT ||
  1193. apy->type==SH_RESOLVED ||
  1194. apy->type==RD_RESOLVED ||
  1195. apy->type==SSCONFLICT ||
  1196. apy->type==SRCONFLICT ||
  1197. apy->type==RRCONFLICT
  1198. );
  1199. /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
  1200. ** REDUCEs on the list. If we reach this point it must be because
  1201. ** the parser conflict had already been resolved. */
  1202. }
  1203. return errcnt;
  1204. }
  1205. /********************* From the file "configlist.c" *************************/
  1206. /*
  1207. ** Routines to processing a configuration list and building a state
  1208. ** in the LEMON parser generator.
  1209. */
  1210. static struct config *freelist = 0; /* List of free configurations */
  1211. static struct config *current = 0; /* Top of list of configurations */
  1212. static struct config **currentend = 0; /* Last on list of configs */
  1213. static struct config *basis = 0; /* Top of list of basis configs */
  1214. static struct config **basisend = 0; /* End of list of basis configs */
  1215. /* Return a pointer to a new configuration */
  1216. PRIVATE struct config *newconfig(void){
  1217. return (struct config*)calloc(1, sizeof(struct config));
  1218. }
  1219. /* The configuration "old" is no longer used */
  1220. PRIVATE void deleteconfig(struct config *old)
  1221. {
  1222. old->next = freelist;
  1223. freelist = old;
  1224. }
  1225. /* Initialized the configuration list builder */
  1226. void Configlist_init(void){
  1227. current = 0;
  1228. currentend = &current;
  1229. basis = 0;
  1230. basisend = &basis;
  1231. Configtable_init();
  1232. return;
  1233. }
  1234. /* Initialized the configuration list builder */
  1235. void Configlist_reset(void){
  1236. current = 0;
  1237. currentend = &current;
  1238. basis = 0;
  1239. basisend = &basis;
  1240. Configtable_clear(0);
  1241. return;
  1242. }
  1243. /* Add another configuration to the configuration list */
  1244. struct config *Configlist_add(
  1245. struct rule *rp, /* The rule */
  1246. int dot /* Index into the RHS of the rule where the dot goes */
  1247. ){
  1248. struct config *cfp, model;
  1249. assert( currentend!=0 );
  1250. model.rp = rp;
  1251. model.dot = dot;
  1252. cfp = Configtable_find(&model);
  1253. if( cfp==0 ){
  1254. cfp = newconfig();
  1255. cfp->rp = rp;
  1256. cfp->dot = dot;
  1257. cfp->fws = SetNew();
  1258. cfp->stp = 0;
  1259. cfp->fplp = cfp->bplp = 0;
  1260. cfp->next = 0;
  1261. cfp->bp = 0;
  1262. *currentend = cfp;
  1263. currentend = &cfp->next;
  1264. Configtable_insert(cfp);
  1265. }
  1266. return cfp;
  1267. }
  1268. /* Add a basis configuration to the configuration list */
  1269. struct config *Configlist_addbasis(struct rule *rp, int dot)
  1270. {
  1271. struct config *cfp, model;
  1272. assert( basisend!=0 );
  1273. assert( currentend!=0 );
  1274. model.rp = rp;
  1275. model.dot = dot;
  1276. cfp = Configtable_find(&model);
  1277. if( cfp==0 ){
  1278. cfp = newconfig();
  1279. cfp->rp = rp;
  1280. cfp->dot = dot;
  1281. cfp->fws = SetNew();
  1282. cfp->stp = 0;
  1283. cfp->fplp = cfp->bplp = 0;
  1284. cfp->next = 0;
  1285. cfp->bp = 0;
  1286. *currentend = cfp;
  1287. currentend = &cfp->next;
  1288. *basisend = cfp;
  1289. basisend = &cfp->bp;
  1290. Configtable_insert(cfp);
  1291. }
  1292. return cfp;
  1293. }
  1294. /* Compute the closure of the configuration list */
  1295. void Configlist_closure(struct lemon *lemp)
  1296. {
  1297. struct config *cfp, *newcfp;
  1298. struct rule *rp, *newrp;
  1299. struct symbol *sp, *xsp;
  1300. int i, dot;
  1301. assert( currentend!=0 );
  1302. for(cfp=current; cfp; cfp=cfp->next){
  1303. rp = cfp->rp;
  1304. dot = cfp->dot;
  1305. if( dot>=rp->nrhs ) continue;
  1306. sp = rp->rhs[dot];
  1307. if( sp->type==NONTERMINAL ){
  1308. if( sp->rule==0 && sp!=lemp->errsym ){
  1309. ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
  1310. sp->name);
  1311. lemp->errorcnt++;
  1312. }
  1313. for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
  1314. newcfp = Configlist_add(newrp,0);
  1315. for(i=dot+1; i<rp->nrhs; i++){
  1316. xsp = rp->rhs[i];
  1317. if( xsp->type==TERMINAL ){
  1318. SetAdd(newcfp->fws,xsp->index);
  1319. break;
  1320. }else if( xsp->type==MULTITERMINAL ){
  1321. int k;
  1322. for(k=0; k<xsp->nsubsym; k++){
  1323. SetAdd(newcfp->fws, xsp->subsym[k]->index);
  1324. }
  1325. break;
  1326. }else{
  1327. SetUnion(newcfp->fws,xsp->firstset);
  1328. if( xsp->lambda==LEMON_FALSE ) break;
  1329. }
  1330. }
  1331. if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
  1332. }
  1333. }
  1334. }
  1335. return;
  1336. }
  1337. /* Sort the configuration list */
  1338. void Configlist_sort(void){
  1339. current = (struct config*)msort((char*)current,(char**)&(current->next),
  1340. Configcmp);
  1341. currentend = 0;
  1342. return;
  1343. }
  1344. /* Sort the basis configuration list */
  1345. void Configlist_sortbasis(void){
  1346. basis = (struct config*)msort((char*)current,(char**)&(current->bp),
  1347. Configcmp);
  1348. basisend = 0;
  1349. return;
  1350. }
  1351. /* Return a pointer to the head of the configuration list and
  1352. ** reset the list */
  1353. struct config *Configlist_return(void){
  1354. struct config *old;
  1355. old = current;
  1356. current = 0;
  1357. currentend = 0;
  1358. return old;
  1359. }
  1360. /* Return a pointer to the head of the configuration list and
  1361. ** reset the list */
  1362. struct config *Configlist_basis(void){
  1363. struct config *old;
  1364. old = basis;
  1365. basis = 0;
  1366. basisend = 0;
  1367. return old;
  1368. }
  1369. /* Free all elements of the given configuration list */
  1370. void Configlist_eat(struct config *cfp)
  1371. {
  1372. struct config *nextcfp;
  1373. for(; cfp; cfp=nextcfp){
  1374. nextcfp = cfp->next;
  1375. assert( cfp->fplp==0 );
  1376. assert( cfp->bplp==0 );
  1377. if( cfp->fws ) SetFree(cfp->fws);
  1378. deleteconfig(cfp);
  1379. }
  1380. return;
  1381. }
  1382. /***************** From the file "error.c" *********************************/
  1383. /*
  1384. ** Code for printing error message.
  1385. */
  1386. void ErrorMsg(const char *filename, int lineno, const char *format, ...){
  1387. va_list ap;
  1388. fprintf(stderr, "%s:%d: ", filename, lineno);
  1389. va_start(ap, format);
  1390. vfprintf(stderr,format,ap);
  1391. va_end(ap);
  1392. fprintf(stderr, "\n");
  1393. }
  1394. /**************** From the file "main.c" ************************************/
  1395. /*
  1396. ** Main program file for the LEMON parser generator.
  1397. */
  1398. /* Report an out-of-memory condition and abort. This function
  1399. ** is used mostly by the "MemoryCheck" macro in struct.h
  1400. */
  1401. void memory_error(void){
  1402. fprintf(stderr,"Out of memory. Aborting...\n");
  1403. exit(1);
  1404. }
  1405. static int nDefine = 0; /* Number of -D options on the command line */
  1406. static char **azDefine = 0; /* Name of the -D macros */
  1407. /* This routine is called with the argument to each -D command-line option.
  1408. ** Add the macro defined to the azDefine array.
  1409. */
  1410. static void handle_D_option(char *z){
  1411. char **paz;
  1412. nDefine++;
  1413. azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
  1414. if( azDefine==0 ){
  1415. fprintf(stderr,"out of memory\n");
  1416. exit(1);
  1417. }
  1418. paz = &azDefine[nDefine-1];
  1419. *paz = (char *) malloc( lemonStrlen(z)+1 );
  1420. if( *paz==0 ){
  1421. fprintf(stderr,"out of memory\n");
  1422. exit(1);
  1423. }
  1424. lemon_strcpy(*paz, z);
  1425. for(z=*paz; *z && *z!='='; z++){}
  1426. *z = 0;
  1427. }
  1428. /* Rember the name of the output directory
  1429. */
  1430. static char *outputDir = NULL;
  1431. static void handle_d_option(char *z){
  1432. outputDir = (char *) malloc( lemonStrlen(z)+1 );
  1433. if( outputDir==0 ){
  1434. fprintf(stderr,"out of memory\n");
  1435. exit(1);
  1436. }
  1437. lemon_strcpy(outputDir, z);
  1438. }
  1439. static char *user_templatename = NULL;
  1440. static void handle_T_option(char *z){
  1441. user_templatename = (char *) malloc( lemonStrlen(z)+1 );
  1442. if( user_templatename==0 ){
  1443. memory_error();
  1444. }
  1445. lemon_strcpy(user_templatename, z);
  1446. }
  1447. /* Merge together to lists of rules ordered by rule.iRule */
  1448. static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
  1449. struct rule *pFirst = 0;
  1450. struct rule **ppPrev = &pFirst;
  1451. while( pA && pB ){
  1452. if( pA->iRule<pB->iRule ){
  1453. *ppPrev = pA;
  1454. ppPrev = &pA->next;
  1455. pA = pA->next;
  1456. }else{
  1457. *ppPrev = pB;
  1458. ppPrev = &pB->next;
  1459. pB = pB->next;
  1460. }
  1461. }
  1462. if( pA ){
  1463. *ppPrev = pA;
  1464. }else{
  1465. *ppPrev = pB;
  1466. }
  1467. return pFirst;
  1468. }
  1469. /*
  1470. ** Sort a list of rules in order of increasing iRule value
  1471. */
  1472. static struct rule *Rule_sort(struct rule *rp){
  1473. unsigned int i;
  1474. struct rule *pNext;
  1475. struct rule *x[32];
  1476. memset(x, 0, sizeof(x));
  1477. while( rp ){
  1478. pNext = rp->next;
  1479. rp->next = 0;
  1480. for(i=0; i<sizeof(x)/sizeof(x[0])-1 && x[i]; i++){
  1481. rp = Rule_merge(x[i], rp);
  1482. x[i] = 0;
  1483. }
  1484. x[i] = rp;
  1485. rp = pNext;
  1486. }
  1487. rp = 0;
  1488. for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
  1489. rp = Rule_merge(x[i], rp);
  1490. }
  1491. return rp;
  1492. }
  1493. /* forward reference */
  1494. static const char *minimum_size_type(int lwr, int upr, int *pnByte);
  1495. /* Print a single line of the "Parser Stats" output
  1496. */
  1497. static void stats_line(const char *zLabel, int iValue){
  1498. int nLabel = lemonStrlen(zLabel);
  1499. printf(" %s%.*s %5d\n", zLabel,
  1500. 35-nLabel, "................................",
  1501. iValue);
  1502. }
  1503. /* The main program. Parse the command line and do it... */
  1504. int main(int argc, char **argv){
  1505. static int version = 0;
  1506. static int rpflag = 0;
  1507. static int basisflag = 0;
  1508. static int compress = 0;
  1509. static int quiet = 0;
  1510. static int statistics = 0;
  1511. static int mhflag = 0;
  1512. static int nolinenosflag = 0;
  1513. static int noResort = 0;
  1514. static int sqlFlag = 0;
  1515. static int printPP = 0;
  1516. static struct s_options options[] = {
  1517. {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
  1518. {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
  1519. {OPT_FSTR, "d", (char*)&handle_d_option, "Output directory. Default '.'"},
  1520. {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
  1521. {OPT_FLAG, "E", (char*)&printPP, "Print input file after preprocessing."},
  1522. {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
  1523. {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
  1524. {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
  1525. {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
  1526. {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
  1527. {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
  1528. {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
  1529. "Show conflicts resolved by precedence rules"},
  1530. {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
  1531. {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
  1532. {OPT_FLAG, "s", (char*)&statistics,
  1533. "Print parser stats to standard output."},
  1534. {OPT_FLAG, "S", (char*)&sqlFlag,
  1535. "Generate the *.sql file describing the parser tables."},
  1536. {OPT_FLAG, "x", (char*)&version, "Print the version number."},
  1537. {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
  1538. {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
  1539. {OPT_FLAG,0,0,0}
  1540. };
  1541. int i;
  1542. int exitcode;
  1543. struct lemon lem;
  1544. struct rule *rp;
  1545. (void)argc;
  1546. OptInit(argv,options,stderr);
  1547. if( version ){
  1548. printf("Lemon version 1.0\n");
  1549. exit(0);
  1550. }
  1551. if( OptNArgs()!=1 ){
  1552. fprintf(stderr,"Exactly one filename argument is required.\n");
  1553. exit(1);
  1554. }
  1555. memset(&lem, 0, sizeof(lem));
  1556. lem.errorcnt = 0;
  1557. /* Initialize the machine */
  1558. Strsafe_init();
  1559. Symbol_init();
  1560. State_init();
  1561. lem.argv0 = argv[0];
  1562. lem.filename = OptArg(0);
  1563. lem.basisflag = basisflag;
  1564. lem.nolinenosflag = nolinenosflag;
  1565. lem.printPreprocessed = printPP;
  1566. Symbol_new("$");
  1567. /* Parse the input file */
  1568. Parse(&lem);
  1569. if( lem.printPreprocessed || lem.errorcnt ) exit(lem.errorcnt);
  1570. if( lem.nrule==0 ){
  1571. fprintf(stderr,"Empty grammar.\n");
  1572. exit(1);
  1573. }
  1574. lem.errsym = Symbol_find("error");
  1575. /* Count and index the symbols of the grammar */
  1576. Symbol_new("{default}");
  1577. lem.nsymbol = Symbol_count();
  1578. lem.symbols = Symbol_arrayof();
  1579. for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
  1580. qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
  1581. for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
  1582. while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
  1583. assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
  1584. lem.nsymbol = i - 1;
  1585. for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
  1586. lem.nterminal = i;
  1587. /* Assign sequential rule numbers. Start with 0. Put rules that have no
  1588. ** reduce action C-code associated with them last, so that the switch()
  1589. ** statement that selects reduction actions will have a smaller jump table.
  1590. */
  1591. for(i=0, rp=lem.rule; rp; rp=rp->next){
  1592. rp->iRule = rp->code ? i++ : -1;
  1593. }
  1594. lem.nruleWithAction = i;
  1595. for(rp=lem.rule; rp; rp=rp->next){
  1596. if( rp->iRule<0 ) rp->iRule = i++;
  1597. }
  1598. lem.startRule = lem.rule;
  1599. lem.rule = Rule_sort(lem.rule);
  1600. /* Generate a reprint of the grammar, if requested on the command line */
  1601. if( rpflag ){
  1602. Reprint(&lem);
  1603. }else{
  1604. /* Initialize the size for all follow and first sets */
  1605. SetSize(lem.nterminal+1);
  1606. /* Find the precedence for every production rule (that has one) */
  1607. FindRulePrecedences(&lem);
  1608. /* Compute the lambda-nonterminals and the first-sets for every
  1609. ** nonterminal */
  1610. FindFirstSets(&lem);
  1611. /* Compute all LR(0) states. Also record follow-set propagation
  1612. ** links so that the follow-set can be computed later */
  1613. lem.nstate = 0;
  1614. FindStates(&lem);
  1615. lem.sorted = State_arrayof();
  1616. /* Tie up loose ends on the propagation links */
  1617. FindLinks(&lem);
  1618. /* Compute the follow set of every reducible configuration */
  1619. FindFollowSets(&lem);
  1620. /* Compute the action tables */
  1621. FindActions(&lem);
  1622. /* Compress the action tables */
  1623. if( compress==0 ) CompressTables(&lem);
  1624. /* Reorder and renumber the states so that states with fewer choices
  1625. ** occur at the end. This is an optimization that helps make the
  1626. ** generated parser tables smaller. */
  1627. if( noResort==0 ) ResortStates(&lem);
  1628. /* Generate a report of the parser generated. (the "y.output" file) */
  1629. if( !quiet ) ReportOutput(&lem);
  1630. /* Generate the source code for the parser */
  1631. ReportTable(&lem, mhflag, sqlFlag);
  1632. /* Produce a header file for use by the scanner. (This step is
  1633. ** omitted if the "-m" option is used because makeheaders will
  1634. ** generate the file for us.) */
  1635. if( !mhflag ) ReportHeader(&lem);
  1636. }
  1637. if( statistics ){
  1638. printf("Parser statistics:\n");
  1639. stats_line("terminal symbols", lem.nterminal);
  1640. stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
  1641. stats_line("total symbols", lem.nsymbol);
  1642. stats_line("rules", lem.nrule);
  1643. stats_line("states", lem.nxstate);
  1644. stats_line("conflicts", lem.nconflict);
  1645. stats_line("action table entries", lem.nactiontab);
  1646. stats_line("lookahead table entries", lem.nlookaheadtab);
  1647. stats_line("total table size (bytes)", lem.tablesize);
  1648. }
  1649. if( lem.nconflict > 0 ){
  1650. fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
  1651. }
  1652. /* return 0 on success, 1 on failure. */
  1653. exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
  1654. exit(exitcode);
  1655. return (exitcode);
  1656. }
  1657. /******************** From the file "msort.c" *******************************/
  1658. /*
  1659. ** A generic merge-sort program.
  1660. **
  1661. ** USAGE:
  1662. ** Let "ptr" be a pointer to some structure which is at the head of
  1663. ** a null-terminated list. Then to sort the list call:
  1664. **
  1665. ** ptr = msort(ptr,&(ptr->next),cmpfnc);
  1666. **
  1667. ** In the above, "cmpfnc" is a pointer to a function which compares
  1668. ** two instances of the structure and returns an integer, as in
  1669. ** strcmp. The second argument is a pointer to the pointer to the
  1670. ** second element of the linked list. This address is used to compute
  1671. ** the offset to the "next" field within the structure. The offset to
  1672. ** the "next" field must be constant for all structures in the list.
  1673. **
  1674. ** The function returns a new pointer which is the head of the list
  1675. ** after sorting.
  1676. **
  1677. ** ALGORITHM:
  1678. ** Merge-sort.
  1679. */
  1680. /*
  1681. ** Return a pointer to the next structure in the linked list.
  1682. */
  1683. #define NEXT(A) (*(char**)(((char*)A)+offset))
  1684. /*
  1685. ** Inputs:
  1686. ** a: A sorted, null-terminated linked list. (May be null).
  1687. ** b: A sorted, null-terminated linked list. (May be null).
  1688. ** cmp: A pointer to the comparison function.
  1689. ** offset: Offset in the structure to the "next" field.
  1690. **
  1691. ** Return Value:
  1692. ** A pointer to the head of a sorted list containing the elements
  1693. ** of both a and b.
  1694. **
  1695. ** Side effects:
  1696. ** The "next" pointers for elements in the lists a and b are
  1697. ** changed.
  1698. */
  1699. static char *merge(
  1700. char *a,
  1701. char *b,
  1702. int (*cmp)(const char*,const char*),
  1703. int offset
  1704. ){
  1705. char *ptr, *head;
  1706. if( a==0 ){
  1707. head = b;
  1708. }else if( b==0 ){
  1709. head = a;
  1710. }else{
  1711. if( (*cmp)(a,b)<=0 ){
  1712. ptr = a;
  1713. a = NEXT(a);
  1714. }else{
  1715. ptr = b;
  1716. b = NEXT(b);
  1717. }
  1718. head = ptr;
  1719. while( a && b ){
  1720. if( (*cmp)(a,b)<=0 ){
  1721. NEXT(ptr) = a;
  1722. ptr = a;
  1723. a = NEXT(a);
  1724. }else{
  1725. NEXT(ptr) = b;
  1726. ptr = b;
  1727. b = NEXT(b);
  1728. }
  1729. }
  1730. if( a ) NEXT(ptr) = a;
  1731. else NEXT(ptr) = b;
  1732. }
  1733. return head;
  1734. }
  1735. /*
  1736. ** Inputs:
  1737. ** list: Pointer to a singly-linked list of structures.
  1738. ** next: Pointer to pointer to the second element of the list.
  1739. ** cmp: A comparison function.
  1740. **
  1741. ** Return Value:
  1742. ** A pointer to the head of a sorted list containing the elements
  1743. ** originally in list.
  1744. **
  1745. ** Side effects:
  1746. ** The "next" pointers for elements in list are changed.
  1747. */
  1748. #define LISTSIZE 30
  1749. static char *msort(
  1750. char *list,
  1751. char **next,
  1752. int (*cmp)(const char*,const char*)
  1753. ){
  1754. unsigned long offset;
  1755. char *ep;
  1756. char *set[LISTSIZE];
  1757. int i;
  1758. offset = (unsigned long)((char*)next - (char*)list);
  1759. for(i=0; i<LISTSIZE; i++) set[i] = 0;
  1760. while( list ){
  1761. ep = list;
  1762. list = NEXT(list);
  1763. NEXT(ep) = 0;
  1764. for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
  1765. ep = merge(ep,set[i],cmp,offset);
  1766. set[i] = 0;
  1767. }
  1768. set[i] = ep;
  1769. }
  1770. ep = 0;
  1771. for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
  1772. return ep;
  1773. }
  1774. /************************ From the file "option.c" **************************/
  1775. static char **g_argv;
  1776. static struct s_options *op;
  1777. static FILE *errstream;
  1778. #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
  1779. /*
  1780. ** Print the command line with a carrot pointing to the k-th character
  1781. ** of the n-th field.
  1782. */
  1783. static void errline(int n, int k, FILE *err)
  1784. {
  1785. int spcnt, i;
  1786. if( g_argv[0] ){
  1787. fprintf(err,"%s",g_argv[0]);
  1788. spcnt = lemonStrlen(g_argv[0]) + 1;
  1789. }else{
  1790. spcnt = 0;
  1791. }
  1792. for(i=1; i<n && g_argv[i]; i++){
  1793. fprintf(err," %s",g_argv[i]);
  1794. spcnt += lemonStrlen(g_argv[i])+1;
  1795. }
  1796. spcnt += k;
  1797. for(; g_argv[i]; i++) fprintf(err," %s",g_argv[i]);
  1798. if( spcnt<20 ){
  1799. fprintf(err,"\n%*s^-- here\n",spcnt,"");
  1800. }else{
  1801. fprintf(err,"\n%*shere --^\n",spcnt-7,"");
  1802. }
  1803. }
  1804. /*
  1805. ** Return the index of the N-th non-switch argument. Return -1
  1806. ** if N is out of range.
  1807. */
  1808. static int argindex(int n)
  1809. {
  1810. int i;
  1811. int dashdash = 0;
  1812. if( g_argv!=0 && *g_argv!=0 ){
  1813. for(i=1; g_argv[i]; i++){
  1814. if( dashdash || !ISOPT(g_argv[i]) ){
  1815. if( n==0 ) return i;
  1816. n--;
  1817. }
  1818. if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
  1819. }
  1820. }
  1821. return -1;
  1822. }
  1823. static char emsg[] = "Command line syntax error: ";
  1824. /*
  1825. ** Process a flag command line argument.
  1826. */
  1827. static int handleflags(int i, FILE *err)
  1828. {
  1829. int v;
  1830. int errcnt = 0;
  1831. int j;
  1832. for(j=0; op[j].label; j++){
  1833. if( strncmp(&g_argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
  1834. }
  1835. v = g_argv[i][0]=='-' ? 1 : 0;
  1836. if( op[j].label==0 ){
  1837. if( err ){
  1838. fprintf(err,"%sundefined option.\n",emsg);
  1839. errline(i,1,err);
  1840. }
  1841. errcnt++;
  1842. }else if( op[j].arg==0 ){
  1843. /* Ignore this option */
  1844. }else if( op[j].type==OPT_FLAG ){
  1845. *((int*)op[j].arg) = v;
  1846. }else if( op[j].type==OPT_FFLAG ){
  1847. (*(void(*)(int))(op[j].arg))(v);
  1848. }else if( op[j].type==OPT_FSTR ){
  1849. (*(void(*)(char *))(op[j].arg))(&g_argv[i][2]);
  1850. }else{
  1851. if( err ){
  1852. fprintf(err,"%smissing argument on switch.\n",emsg);
  1853. errline(i,1,err);
  1854. }
  1855. errcnt++;
  1856. }
  1857. return errcnt;
  1858. }
  1859. /*
  1860. ** Process a command line switch which has an argument.
  1861. */
  1862. static int handleswitch(int i, FILE *err)
  1863. {
  1864. int lv = 0;
  1865. double dv = 0.0;
  1866. char *sv = 0, *end;
  1867. char *cp;
  1868. int j;
  1869. int errcnt = 0;
  1870. cp = strchr(g_argv[i],'=');
  1871. assert( cp!=0 );
  1872. *cp = 0;
  1873. for(j=0; op[j].label; j++){
  1874. if( strcmp(g_argv[i],op[j].label)==0 ) break;
  1875. }
  1876. *cp = '=';
  1877. if( op[j].label==0 ){
  1878. if( err ){
  1879. fprintf(err,"%sundefined option.\n",emsg);
  1880. errline(i,0,err);
  1881. }
  1882. errcnt++;
  1883. }else{
  1884. cp++;
  1885. switch( op[j].type ){
  1886. case OPT_FLAG:
  1887. case OPT_FFLAG:
  1888. if( err ){
  1889. fprintf(err,"%soption requires an argument.\n",emsg);
  1890. errline(i,0,err);
  1891. }
  1892. errcnt++;
  1893. break;
  1894. case OPT_DBL:
  1895. case OPT_FDBL:
  1896. dv = strtod(cp,&end);
  1897. if( *end ){
  1898. if( err ){
  1899. fprintf(err,
  1900. "%sillegal character in floating-point argument.\n",emsg);
  1901. errline(i,(int)((char*)end-(char*)g_argv[i]),err);
  1902. }
  1903. errcnt++;
  1904. }
  1905. break;
  1906. case OPT_INT:
  1907. case OPT_FINT:
  1908. lv = strtol(cp,&end,0);
  1909. if( *end ){
  1910. if( err ){
  1911. fprintf(err,"%sillegal character in integer argument.\n",emsg);
  1912. errline(i,(int)((char*)end-(char*)g_argv[i]),err);
  1913. }
  1914. errcnt++;
  1915. }
  1916. break;
  1917. case OPT_STR:
  1918. case OPT_FSTR:
  1919. sv = cp;
  1920. break;
  1921. }
  1922. switch( op[j].type ){
  1923. case OPT_FLAG:
  1924. case OPT_FFLAG:
  1925. break;
  1926. case OPT_DBL:
  1927. *(double*)(op[j].arg) = dv;
  1928. break;
  1929. case OPT_FDBL:
  1930. (*(void(*)(double))(op[j].arg))(dv);
  1931. break;
  1932. case OPT_INT:
  1933. *(int*)(op[j].arg) = lv;
  1934. break;
  1935. case OPT_FINT:
  1936. (*(void(*)(int))(op[j].arg))((int)lv);
  1937. break;
  1938. case OPT_STR:
  1939. *(char**)(op[j].arg) = sv;
  1940. break;
  1941. case OPT_FSTR:
  1942. (*(void(*)(char *))(op[j].arg))(sv);
  1943. break;
  1944. }
  1945. }
  1946. return errcnt;
  1947. }
  1948. int OptInit(char **a, struct s_options *o, FILE *err)
  1949. {
  1950. int errcnt = 0;
  1951. g_argv = a;
  1952. op = o;
  1953. errstream = err;
  1954. if( g_argv && *g_argv && op ){
  1955. int i;
  1956. for(i=1; g_argv[i]; i++){
  1957. if( g_argv[i][0]=='+' || g_argv[i][0]=='-' ){
  1958. errcnt += handleflags(i,err);
  1959. }else if( strchr(g_argv[i],'=') ){
  1960. errcnt += handleswitch(i,err);
  1961. }
  1962. }
  1963. }
  1964. if( errcnt>0 ){
  1965. fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
  1966. OptPrint();
  1967. exit(1);
  1968. }
  1969. return 0;
  1970. }
  1971. int OptNArgs(void){
  1972. int cnt = 0;
  1973. int dashdash = 0;
  1974. int i;
  1975. if( g_argv!=0 && g_argv[0]!=0 ){
  1976. for(i=1; g_argv[i]; i++){
  1977. if( dashdash || !ISOPT(g_argv[i]) ) cnt++;
  1978. if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
  1979. }
  1980. }
  1981. return cnt;
  1982. }
  1983. char *OptArg(int n)
  1984. {
  1985. int i;
  1986. i = argindex(n);
  1987. return i>=0 ? g_argv[i] : 0;
  1988. }
  1989. void OptErr(int n)
  1990. {
  1991. int i;
  1992. i = argindex(n);
  1993. if( i>=0 ) errline(i,0,errstream);
  1994. }
  1995. void OptPrint(void){
  1996. int i;
  1997. int max, len;
  1998. max = 0;
  1999. for(i=0; op[i].label; i++){
  2000. len = lemonStrlen(op[i].label) + 1;
  2001. switch( op[i].type ){
  2002. case OPT_FLAG:
  2003. case OPT_FFLAG:
  2004. break;
  2005. case OPT_INT:
  2006. case OPT_FINT:
  2007. len += 9; /* length of "<integer>" */
  2008. break;
  2009. case OPT_DBL:
  2010. case OPT_FDBL:
  2011. len += 6; /* length of "<real>" */
  2012. break;
  2013. case OPT_STR:
  2014. case OPT_FSTR:
  2015. len += 8; /* length of "<string>" */
  2016. break;
  2017. }
  2018. if( len>max ) max = len;
  2019. }
  2020. for(i=0; op[i].label; i++){
  2021. switch( op[i].type ){
  2022. case OPT_FLAG:
  2023. case OPT_FFLAG:
  2024. fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
  2025. break;
  2026. case OPT_INT:
  2027. case OPT_FINT:
  2028. fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
  2029. (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
  2030. break;
  2031. case OPT_DBL:
  2032. case OPT_FDBL:
  2033. fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
  2034. (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
  2035. break;
  2036. case OPT_STR:
  2037. case OPT_FSTR:
  2038. fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
  2039. (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
  2040. break;
  2041. }
  2042. }
  2043. }
  2044. /*********************** From the file "parse.c" ****************************/
  2045. /*
  2046. ** Input file parser for the LEMON parser generator.
  2047. */
  2048. /* The state of the parser */
  2049. enum e_state {
  2050. INITIALIZE,
  2051. WAITING_FOR_DECL_OR_RULE,
  2052. WAITING_FOR_DECL_KEYWORD,
  2053. WAITING_FOR_DECL_ARG,
  2054. WAITING_FOR_PRECEDENCE_SYMBOL,
  2055. WAITING_FOR_ARROW,
  2056. IN_RHS,
  2057. LHS_ALIAS_1,
  2058. LHS_ALIAS_2,
  2059. LHS_ALIAS_3,
  2060. RHS_ALIAS_1,
  2061. RHS_ALIAS_2,
  2062. PRECEDENCE_MARK_1,
  2063. PRECEDENCE_MARK_2,
  2064. RESYNC_AFTER_RULE_ERROR,
  2065. RESYNC_AFTER_DECL_ERROR,
  2066. WAITING_FOR_DESTRUCTOR_SYMBOL,
  2067. WAITING_FOR_DATATYPE_SYMBOL,
  2068. WAITING_FOR_FALLBACK_ID,
  2069. WAITING_FOR_WILDCARD_ID,
  2070. WAITING_FOR_CLASS_ID,
  2071. WAITING_FOR_CLASS_TOKEN,
  2072. WAITING_FOR_TOKEN_NAME
  2073. };
  2074. struct pstate {
  2075. char *filename; /* Name of the input file */
  2076. int tokenlineno; /* Linenumber at which current token starts */
  2077. int errorcnt; /* Number of errors so far */
  2078. char *tokenstart; /* Text of current token */
  2079. struct lemon *gp; /* Global state vector */
  2080. enum e_state state; /* The state of the parser */
  2081. struct symbol *fallback; /* The fallback token */
  2082. struct symbol *tkclass; /* Token class symbol */
  2083. struct symbol *lhs; /* Left-hand side of current rule */
  2084. const char *lhsalias; /* Alias for the LHS */
  2085. int nrhs; /* Number of right-hand side symbols seen */
  2086. struct symbol *rhs[MAXRHS]; /* RHS symbols */
  2087. const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
  2088. struct rule *prevrule; /* Previous rule parsed */
  2089. const char *declkeyword; /* Keyword of a declaration */
  2090. char **declargslot; /* Where the declaration argument should be put */
  2091. int insertLineMacro; /* Add #line before declaration insert */
  2092. int *decllinenoslot; /* Where to write declaration line number */
  2093. enum e_assoc declassoc; /* Assign this association to decl arguments */
  2094. int preccounter; /* Assign this precedence to decl arguments */
  2095. struct rule *firstrule; /* Pointer to first rule in the grammar */
  2096. struct rule *lastrule; /* Pointer to the most recently parsed rule */
  2097. };
  2098. /* Parse a single token */
  2099. static void parseonetoken(struct pstate *psp)
  2100. {
  2101. const char *x;
  2102. x = Strsafe(psp->tokenstart); /* Save the token permanently */
  2103. #if 0
  2104. printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
  2105. x,psp->state);
  2106. #endif
  2107. switch( psp->state ){
  2108. case INITIALIZE:
  2109. psp->prevrule = 0;
  2110. psp->preccounter = 0;
  2111. psp->firstrule = psp->lastrule = 0;
  2112. psp->gp->nrule = 0;
  2113. /* fall through */
  2114. case WAITING_FOR_DECL_OR_RULE:
  2115. if( x[0]=='%' ){
  2116. psp->state = WAITING_FOR_DECL_KEYWORD;
  2117. }else if( ISLOWER(x[0]) ){
  2118. psp->lhs = Symbol_new(x);
  2119. psp->nrhs = 0;
  2120. psp->lhsalias = 0;
  2121. psp->state = WAITING_FOR_ARROW;
  2122. }else if( x[0]=='{' ){
  2123. if( psp->prevrule==0 ){
  2124. ErrorMsg(psp->filename,psp->tokenlineno,
  2125. "There is no prior rule upon which to attach the code "
  2126. "fragment which begins on this line.");
  2127. psp->errorcnt++;
  2128. }else if( psp->prevrule->code!=0 ){
  2129. ErrorMsg(psp->filename,psp->tokenlineno,
  2130. "Code fragment beginning on this line is not the first "
  2131. "to follow the previous rule.");
  2132. psp->errorcnt++;
  2133. }else if( strcmp(x, "{NEVER-REDUCE")==0 ){
  2134. psp->prevrule->neverReduce = 1;
  2135. }else{
  2136. psp->prevrule->line = psp->tokenlineno;
  2137. psp->prevrule->code = &x[1];
  2138. psp->prevrule->noCode = 0;
  2139. }
  2140. }else if( x[0]=='[' ){
  2141. psp->state = PRECEDENCE_MARK_1;
  2142. }else{
  2143. ErrorMsg(psp->filename,psp->tokenlineno,
  2144. "Token \"%s\" should be either \"%%\" or a nonterminal name.",
  2145. x);
  2146. psp->errorcnt++;
  2147. }
  2148. break;
  2149. case PRECEDENCE_MARK_1:
  2150. if( !ISUPPER(x[0]) ){
  2151. ErrorMsg(psp->filename,psp->tokenlineno,
  2152. "The precedence symbol must be a terminal.");
  2153. psp->errorcnt++;
  2154. }else if( psp->prevrule==0 ){
  2155. ErrorMsg(psp->filename,psp->tokenlineno,
  2156. "There is no prior rule to assign precedence \"[%s]\".",x);
  2157. psp->errorcnt++;
  2158. }else if( psp->prevrule->precsym!=0 ){
  2159. ErrorMsg(psp->filename,psp->tokenlineno,
  2160. "Precedence mark on this line is not the first "
  2161. "to follow the previous rule.");
  2162. psp->errorcnt++;
  2163. }else{
  2164. psp->prevrule->precsym = Symbol_new(x);
  2165. }
  2166. psp->state = PRECEDENCE_MARK_2;
  2167. break;
  2168. case PRECEDENCE_MARK_2:
  2169. if( x[0]!=']' ){
  2170. ErrorMsg(psp->filename,psp->tokenlineno,
  2171. "Missing \"]\" on precedence mark.");
  2172. psp->errorcnt++;
  2173. }
  2174. psp->state = WAITING_FOR_DECL_OR_RULE;
  2175. break;
  2176. case WAITING_FOR_ARROW:
  2177. if( x[0]==':' && x[1]==':' && x[2]=='=' ){
  2178. psp->state = IN_RHS;
  2179. }else if( x[0]=='(' ){
  2180. psp->state = LHS_ALIAS_1;
  2181. }else{
  2182. ErrorMsg(psp->filename,psp->tokenlineno,
  2183. "Expected to see a \":\" following the LHS symbol \"%s\".",
  2184. psp->lhs->name);
  2185. psp->errorcnt++;
  2186. psp->state = RESYNC_AFTER_RULE_ERROR;
  2187. }
  2188. break;
  2189. case LHS_ALIAS_1:
  2190. if( ISALPHA(x[0]) ){
  2191. psp->lhsalias = x;
  2192. psp->state = LHS_ALIAS_2;
  2193. }else{
  2194. ErrorMsg(psp->filename,psp->tokenlineno,
  2195. "\"%s\" is not a valid alias for the LHS \"%s\"\n",
  2196. x,psp->lhs->name);
  2197. psp->errorcnt++;
  2198. psp->state = RESYNC_AFTER_RULE_ERROR;
  2199. }
  2200. break;
  2201. case LHS_ALIAS_2:
  2202. if( x[0]==')' ){
  2203. psp->state = LHS_ALIAS_3;
  2204. }else{
  2205. ErrorMsg(psp->filename,psp->tokenlineno,
  2206. "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
  2207. psp->errorcnt++;
  2208. psp->state = RESYNC_AFTER_RULE_ERROR;
  2209. }
  2210. break;
  2211. case LHS_ALIAS_3:
  2212. if( x[0]==':' && x[1]==':' && x[2]=='=' ){
  2213. psp->state = IN_RHS;
  2214. }else{
  2215. ErrorMsg(psp->filename,psp->tokenlineno,
  2216. "Missing \"->\" following: \"%s(%s)\".",
  2217. psp->lhs->name,psp->lhsalias);
  2218. psp->errorcnt++;
  2219. psp->state = RESYNC_AFTER_RULE_ERROR;
  2220. }
  2221. break;
  2222. case IN_RHS:
  2223. if( x[0]=='.' ){
  2224. struct rule *rp;
  2225. rp = (struct rule *)calloc( sizeof(struct rule) +
  2226. sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
  2227. if( rp==0 ){
  2228. ErrorMsg(psp->filename,psp->tokenlineno,
  2229. "Can't allocate enough memory for this rule.");
  2230. psp->errorcnt++;
  2231. psp->prevrule = 0;
  2232. }else{
  2233. int i;
  2234. rp->ruleline = psp->tokenlineno;
  2235. rp->rhs = (struct symbol**)&rp[1];
  2236. rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
  2237. for(i=0; i<psp->nrhs; i++){
  2238. rp->rhs[i] = psp->rhs[i];
  2239. rp->rhsalias[i] = psp->alias[i];
  2240. if( rp->rhsalias[i]!=0 ){ rp->rhs[i]->bContent = 1; }
  2241. }
  2242. rp->lhs = psp->lhs;
  2243. rp->lhsalias = psp->lhsalias;
  2244. rp->nrhs = psp->nrhs;
  2245. rp->code = 0;
  2246. rp->noCode = 1;
  2247. rp->precsym = 0;
  2248. rp->index = psp->gp->nrule++;
  2249. rp->nextlhs = rp->lhs->rule;
  2250. rp->lhs->rule = rp;
  2251. rp->next = 0;
  2252. if( psp->firstrule==0 ){
  2253. psp->firstrule = psp->lastrule = rp;
  2254. }else{
  2255. psp->lastrule->next = rp;
  2256. psp->lastrule = rp;
  2257. }
  2258. psp->prevrule = rp;
  2259. }
  2260. psp->state = WAITING_FOR_DECL_OR_RULE;
  2261. }else if( ISALPHA(x[0]) ){
  2262. if( psp->nrhs>=MAXRHS ){
  2263. ErrorMsg(psp->filename,psp->tokenlineno,
  2264. "Too many symbols on RHS of rule beginning at \"%s\".",
  2265. x);
  2266. psp->errorcnt++;
  2267. psp->state = RESYNC_AFTER_RULE_ERROR;
  2268. }else{
  2269. psp->rhs[psp->nrhs] = Symbol_new(x);
  2270. psp->alias[psp->nrhs] = 0;
  2271. psp->nrhs++;
  2272. }
  2273. }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 && ISUPPER(x[1]) ){
  2274. struct symbol *msp = psp->rhs[psp->nrhs-1];
  2275. if( msp->type!=MULTITERMINAL ){
  2276. struct symbol *origsp = msp;
  2277. msp = (struct symbol *) calloc(1,sizeof(*msp));
  2278. memset(msp, 0, sizeof(*msp));
  2279. msp->type = MULTITERMINAL;
  2280. msp->nsubsym = 1;
  2281. msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
  2282. msp->subsym[0] = origsp;
  2283. msp->name = origsp->name;
  2284. psp->rhs[psp->nrhs-1] = msp;
  2285. }
  2286. msp->nsubsym++;
  2287. msp->subsym = (struct symbol **) realloc(msp->subsym,
  2288. sizeof(struct symbol*)*msp->nsubsym);
  2289. msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
  2290. if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
  2291. ErrorMsg(psp->filename,psp->tokenlineno,
  2292. "Cannot form a compound containing a non-terminal");
  2293. psp->errorcnt++;
  2294. }
  2295. }else if( x[0]=='(' && psp->nrhs>0 ){
  2296. psp->state = RHS_ALIAS_1;
  2297. }else{
  2298. ErrorMsg(psp->filename,psp->tokenlineno,
  2299. "Illegal character on RHS of rule: \"%s\".",x);
  2300. psp->errorcnt++;
  2301. psp->state = RESYNC_AFTER_RULE_ERROR;
  2302. }
  2303. break;
  2304. case RHS_ALIAS_1:
  2305. if( ISALPHA(x[0]) ){
  2306. psp->alias[psp->nrhs-1] = x;
  2307. psp->state = RHS_ALIAS_2;
  2308. }else{
  2309. ErrorMsg(psp->filename,psp->tokenlineno,
  2310. "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
  2311. x,psp->rhs[psp->nrhs-1]->name);
  2312. psp->errorcnt++;
  2313. psp->state = RESYNC_AFTER_RULE_ERROR;
  2314. }
  2315. break;
  2316. case RHS_ALIAS_2:
  2317. if( x[0]==')' ){
  2318. psp->state = IN_RHS;
  2319. }else{
  2320. ErrorMsg(psp->filename,psp->tokenlineno,
  2321. "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
  2322. psp->errorcnt++;
  2323. psp->state = RESYNC_AFTER_RULE_ERROR;
  2324. }
  2325. break;
  2326. case WAITING_FOR_DECL_KEYWORD:
  2327. if( ISALPHA(x[0]) ){
  2328. psp->declkeyword = x;
  2329. psp->declargslot = 0;
  2330. psp->decllinenoslot = 0;
  2331. psp->insertLineMacro = 1;
  2332. psp->state = WAITING_FOR_DECL_ARG;
  2333. if( strcmp(x,"name")==0 ){
  2334. psp->declargslot = &(psp->gp->name);
  2335. psp->insertLineMacro = 0;
  2336. }else if( strcmp(x,"include")==0 ){
  2337. psp->declargslot = &(psp->gp->include);
  2338. }else if( strcmp(x,"code")==0 ){
  2339. psp->declargslot = &(psp->gp->extracode);
  2340. }else if( strcmp(x,"token_destructor")==0 ){
  2341. psp->declargslot = &psp->gp->tokendest;
  2342. }else if( strcmp(x,"default_destructor")==0 ){
  2343. psp->declargslot = &psp->gp->vardest;
  2344. }else if( strcmp(x,"token_prefix")==0 ){
  2345. psp->declargslot = &psp->gp->tokenprefix;
  2346. psp->insertLineMacro = 0;
  2347. }else if( strcmp(x,"syntax_error")==0 ){
  2348. psp->declargslot = &(psp->gp->error);
  2349. }else if( strcmp(x,"parse_accept")==0 ){
  2350. psp->declargslot = &(psp->gp->accept);
  2351. }else if( strcmp(x,"parse_failure")==0 ){
  2352. psp->declargslot = &(psp->gp->failure);
  2353. }else if( strcmp(x,"stack_overflow")==0 ){
  2354. psp->declargslot = &(psp->gp->overflow);
  2355. }else if( strcmp(x,"extra_argument")==0 ){
  2356. psp->declargslot = &(psp->gp->arg);
  2357. psp->insertLineMacro = 0;
  2358. }else if( strcmp(x,"extra_context")==0 ){
  2359. psp->declargslot = &(psp->gp->ctx);
  2360. psp->insertLineMacro = 0;
  2361. }else if( strcmp(x,"token_type")==0 ){
  2362. psp->declargslot = &(psp->gp->tokentype);
  2363. psp->insertLineMacro = 0;
  2364. }else if( strcmp(x,"default_type")==0 ){
  2365. psp->declargslot = &(psp->gp->vartype);
  2366. psp->insertLineMacro = 0;
  2367. }else if( strcmp(x,"stack_size")==0 ){
  2368. psp->declargslot = &(psp->gp->stacksize);
  2369. psp->insertLineMacro = 0;
  2370. }else if( strcmp(x,"start_symbol")==0 ){
  2371. psp->declargslot = &(psp->gp->start);
  2372. psp->insertLineMacro = 0;
  2373. }else if( strcmp(x,"left")==0 ){
  2374. psp->preccounter++;
  2375. psp->declassoc = LEFT;
  2376. psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
  2377. }else if( strcmp(x,"right")==0 ){
  2378. psp->preccounter++;
  2379. psp->declassoc = RIGHT;
  2380. psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
  2381. }else if( strcmp(x,"nonassoc")==0 ){
  2382. psp->preccounter++;
  2383. psp->declassoc = NONE;
  2384. psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
  2385. }else if( strcmp(x,"destructor")==0 ){
  2386. psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
  2387. }else if( strcmp(x,"type")==0 ){
  2388. psp->state = WAITING_FOR_DATATYPE_SYMBOL;
  2389. }else if( strcmp(x,"fallback")==0 ){
  2390. psp->fallback = 0;
  2391. psp->state = WAITING_FOR_FALLBACK_ID;
  2392. }else if( strcmp(x,"token")==0 ){
  2393. psp->state = WAITING_FOR_TOKEN_NAME;
  2394. }else if( strcmp(x,"wildcard")==0 ){
  2395. psp->state = WAITING_FOR_WILDCARD_ID;
  2396. }else if( strcmp(x,"token_class")==0 ){
  2397. psp->state = WAITING_FOR_CLASS_ID;
  2398. }else{
  2399. ErrorMsg(psp->filename,psp->tokenlineno,
  2400. "Unknown declaration keyword: \"%%%s\".",x);
  2401. psp->errorcnt++;
  2402. psp->state = RESYNC_AFTER_DECL_ERROR;
  2403. }
  2404. }else{
  2405. ErrorMsg(psp->filename,psp->tokenlineno,
  2406. "Illegal declaration keyword: \"%s\".",x);
  2407. psp->errorcnt++;
  2408. psp->state = RESYNC_AFTER_DECL_ERROR;
  2409. }
  2410. break;
  2411. case WAITING_FOR_DESTRUCTOR_SYMBOL:
  2412. if( !ISALPHA(x[0]) ){
  2413. ErrorMsg(psp->filename,psp->tokenlineno,
  2414. "Symbol name missing after %%destructor keyword");
  2415. psp->errorcnt++;
  2416. psp->state = RESYNC_AFTER_DECL_ERROR;
  2417. }else{
  2418. struct symbol *sp = Symbol_new(x);
  2419. psp->declargslot = &sp->destructor;
  2420. psp->decllinenoslot = &sp->destLineno;
  2421. psp->insertLineMacro = 1;
  2422. psp->state = WAITING_FOR_DECL_ARG;
  2423. }
  2424. break;
  2425. case WAITING_FOR_DATATYPE_SYMBOL:
  2426. if( !ISALPHA(x[0]) ){
  2427. ErrorMsg(psp->filename,psp->tokenlineno,
  2428. "Symbol name missing after %%type keyword");
  2429. psp->errorcnt++;
  2430. psp->state = RESYNC_AFTER_DECL_ERROR;
  2431. }else{
  2432. struct symbol *sp = Symbol_find(x);
  2433. if((sp) && (sp->datatype)){
  2434. ErrorMsg(psp->filename,psp->tokenlineno,
  2435. "Symbol %%type \"%s\" already defined", x);
  2436. psp->errorcnt++;
  2437. psp->state = RESYNC_AFTER_DECL_ERROR;
  2438. }else{
  2439. if (!sp){
  2440. sp = Symbol_new(x);
  2441. }
  2442. psp->declargslot = &sp->datatype;
  2443. psp->insertLineMacro = 0;
  2444. psp->state = WAITING_FOR_DECL_ARG;
  2445. }
  2446. }
  2447. break;
  2448. case WAITING_FOR_PRECEDENCE_SYMBOL:
  2449. if( x[0]=='.' ){
  2450. psp->state = WAITING_FOR_DECL_OR_RULE;
  2451. }else if( ISUPPER(x[0]) ){
  2452. struct symbol *sp;
  2453. sp = Symbol_new(x);
  2454. if( sp->prec>=0 ){
  2455. ErrorMsg(psp->filename,psp->tokenlineno,
  2456. "Symbol \"%s\" has already be given a precedence.",x);
  2457. psp->errorcnt++;
  2458. }else{
  2459. sp->prec = psp->preccounter;
  2460. sp->assoc = psp->declassoc;
  2461. }
  2462. }else{
  2463. ErrorMsg(psp->filename,psp->tokenlineno,
  2464. "Can't assign a precedence to \"%s\".",x);
  2465. psp->errorcnt++;
  2466. }
  2467. break;
  2468. case WAITING_FOR_DECL_ARG:
  2469. if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
  2470. const char *zOld, *zNew;
  2471. char *zBuf, *z;
  2472. int nOld, n, nLine = 0, nNew, nBack;
  2473. int addLineMacro;
  2474. char zLine[50];
  2475. zNew = x;
  2476. if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
  2477. nNew = lemonStrlen(zNew);
  2478. if( *psp->declargslot ){
  2479. zOld = *psp->declargslot;
  2480. }else{
  2481. zOld = "";
  2482. }
  2483. nOld = lemonStrlen(zOld);
  2484. n = nOld + nNew + 20;
  2485. addLineMacro = !psp->gp->nolinenosflag
  2486. && psp->insertLineMacro
  2487. && psp->tokenlineno>1
  2488. && (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
  2489. if( addLineMacro ){
  2490. for(z=psp->filename, nBack=0; *z; z++){
  2491. if( *z=='\\' ) nBack++;
  2492. }
  2493. lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
  2494. nLine = lemonStrlen(zLine);
  2495. n += nLine + lemonStrlen(psp->filename) + nBack;
  2496. }
  2497. *psp->declargslot = (char *) realloc(*psp->declargslot, n);
  2498. zBuf = *psp->declargslot + nOld;
  2499. if( addLineMacro ){
  2500. if( nOld && zBuf[-1]!='\n' ){
  2501. *(zBuf++) = '\n';
  2502. }
  2503. memcpy(zBuf, zLine, nLine);
  2504. zBuf += nLine;
  2505. *(zBuf++) = '"';
  2506. for(z=psp->filename; *z; z++){
  2507. if( *z=='\\' ){
  2508. *(zBuf++) = '\\';
  2509. }
  2510. *(zBuf++) = *z;
  2511. }
  2512. *(zBuf++) = '"';
  2513. *(zBuf++) = '\n';
  2514. }
  2515. if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
  2516. psp->decllinenoslot[0] = psp->tokenlineno;
  2517. }
  2518. memcpy(zBuf, zNew, nNew);
  2519. zBuf += nNew;
  2520. *zBuf = 0;
  2521. psp->state = WAITING_FOR_DECL_OR_RULE;
  2522. }else{
  2523. ErrorMsg(psp->filename,psp->tokenlineno,
  2524. "Illegal argument to %%%s: %s",psp->declkeyword,x);
  2525. psp->errorcnt++;
  2526. psp->state = RESYNC_AFTER_DECL_ERROR;
  2527. }
  2528. break;
  2529. case WAITING_FOR_FALLBACK_ID:
  2530. if( x[0]=='.' ){
  2531. psp->state = WAITING_FOR_DECL_OR_RULE;
  2532. }else if( !ISUPPER(x[0]) ){
  2533. ErrorMsg(psp->filename, psp->tokenlineno,
  2534. "%%fallback argument \"%s\" should be a token", x);
  2535. psp->errorcnt++;
  2536. }else{
  2537. struct symbol *sp = Symbol_new(x);
  2538. if( psp->fallback==0 ){
  2539. psp->fallback = sp;
  2540. }else if( sp->fallback ){
  2541. ErrorMsg(psp->filename, psp->tokenlineno,
  2542. "More than one fallback assigned to token %s", x);
  2543. psp->errorcnt++;
  2544. }else{
  2545. sp->fallback = psp->fallback;
  2546. psp->gp->has_fallback = 1;
  2547. }
  2548. }
  2549. break;
  2550. case WAITING_FOR_TOKEN_NAME:
  2551. /* Tokens do not have to be declared before use. But they can be
  2552. ** in order to control their assigned integer number. The number for
  2553. ** each token is assigned when it is first seen. So by including
  2554. **
  2555. ** %token ONE TWO THREE.
  2556. **
  2557. ** early in the grammar file, that assigns small consecutive values
  2558. ** to each of the tokens ONE TWO and THREE.
  2559. */
  2560. if( x[0]=='.' ){
  2561. psp->state = WAITING_FOR_DECL_OR_RULE;
  2562. }else if( !ISUPPER(x[0]) ){
  2563. ErrorMsg(psp->filename, psp->tokenlineno,
  2564. "%%token argument \"%s\" should be a token", x);
  2565. psp->errorcnt++;
  2566. }else{
  2567. (void)Symbol_new(x);
  2568. }
  2569. break;
  2570. case WAITING_FOR_WILDCARD_ID:
  2571. if( x[0]=='.' ){
  2572. psp->state = WAITING_FOR_DECL_OR_RULE;
  2573. }else if( !ISUPPER(x[0]) ){
  2574. ErrorMsg(psp->filename, psp->tokenlineno,
  2575. "%%wildcard argument \"%s\" should be a token", x);
  2576. psp->errorcnt++;
  2577. }else{
  2578. struct symbol *sp = Symbol_new(x);
  2579. if( psp->gp->wildcard==0 ){
  2580. psp->gp->wildcard = sp;
  2581. }else{
  2582. ErrorMsg(psp->filename, psp->tokenlineno,
  2583. "Extra wildcard to token: %s", x);
  2584. psp->errorcnt++;
  2585. }
  2586. }
  2587. break;
  2588. case WAITING_FOR_CLASS_ID:
  2589. if( !ISLOWER(x[0]) ){
  2590. ErrorMsg(psp->filename, psp->tokenlineno,
  2591. "%%token_class must be followed by an identifier: %s", x);
  2592. psp->errorcnt++;
  2593. psp->state = RESYNC_AFTER_DECL_ERROR;
  2594. }else if( Symbol_find(x) ){
  2595. ErrorMsg(psp->filename, psp->tokenlineno,
  2596. "Symbol \"%s\" already used", x);
  2597. psp->errorcnt++;
  2598. psp->state = RESYNC_AFTER_DECL_ERROR;
  2599. }else{
  2600. psp->tkclass = Symbol_new(x);
  2601. psp->tkclass->type = MULTITERMINAL;
  2602. psp->state = WAITING_FOR_CLASS_TOKEN;
  2603. }
  2604. break;
  2605. case WAITING_FOR_CLASS_TOKEN:
  2606. if( x[0]=='.' ){
  2607. psp->state = WAITING_FOR_DECL_OR_RULE;
  2608. }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
  2609. struct symbol *msp = psp->tkclass;
  2610. msp->nsubsym++;
  2611. msp->subsym = (struct symbol **) realloc(msp->subsym,
  2612. sizeof(struct symbol*)*msp->nsubsym);
  2613. if( !ISUPPER(x[0]) ) x++;
  2614. msp->subsym[msp->nsubsym-1] = Symbol_new(x);
  2615. }else{
  2616. ErrorMsg(psp->filename, psp->tokenlineno,
  2617. "%%token_class argument \"%s\" should be a token", x);
  2618. psp->errorcnt++;
  2619. psp->state = RESYNC_AFTER_DECL_ERROR;
  2620. }
  2621. break;
  2622. case RESYNC_AFTER_RULE_ERROR:
  2623. /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
  2624. ** break; */
  2625. case RESYNC_AFTER_DECL_ERROR:
  2626. if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
  2627. if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
  2628. break;
  2629. }
  2630. }
  2631. /* The text in the input is part of the argument to an %ifdef or %ifndef.
  2632. ** Evaluate the text as a boolean expression. Return true or false.
  2633. */
  2634. static int eval_preprocessor_boolean(char *z, int lineno){
  2635. int neg = 0;
  2636. int res = 0;
  2637. int okTerm = 1;
  2638. int i;
  2639. for(i=0; z[i]!=0; i++){
  2640. if( ISSPACE(z[i]) ) continue;
  2641. if( z[i]=='!' ){
  2642. if( !okTerm ) goto pp_syntax_error;
  2643. neg = !neg;
  2644. continue;
  2645. }
  2646. if( z[i]=='|' && z[i+1]=='|' ){
  2647. if( okTerm ) goto pp_syntax_error;
  2648. if( res ) return 1;
  2649. i++;
  2650. okTerm = 1;
  2651. continue;
  2652. }
  2653. if( z[i]=='&' && z[i+1]=='&' ){
  2654. if( okTerm ) goto pp_syntax_error;
  2655. if( !res ) return 0;
  2656. i++;
  2657. okTerm = 1;
  2658. continue;
  2659. }
  2660. if( z[i]=='(' ){
  2661. int k;
  2662. int n = 1;
  2663. if( !okTerm ) goto pp_syntax_error;
  2664. for(k=i+1; z[k]; k++){
  2665. if( z[k]==')' ){
  2666. n--;
  2667. if( n==0 ){
  2668. z[k] = 0;
  2669. res = eval_preprocessor_boolean(&z[i+1], -1);
  2670. z[k] = ')';
  2671. if( res<0 ){
  2672. i = i-res;
  2673. goto pp_syntax_error;
  2674. }
  2675. i = k;
  2676. break;
  2677. }
  2678. }else if( z[k]=='(' ){
  2679. n++;
  2680. }else if( z[k]==0 ){
  2681. i = k;
  2682. goto pp_syntax_error;
  2683. }
  2684. }
  2685. if( neg ){
  2686. res = !res;
  2687. neg = 0;
  2688. }
  2689. okTerm = 0;
  2690. continue;
  2691. }
  2692. if( ISALPHA(z[i]) ){
  2693. int j, k, n;
  2694. if( !okTerm ) goto pp_syntax_error;
  2695. for(k=i+1; ISALNUM(z[k]) || z[k]=='_'; k++){}
  2696. n = k - i;
  2697. res = 0;
  2698. for(j=0; j<nDefine; j++){
  2699. if( strncmp(azDefine[j],&z[i],n)==0 && azDefine[j][n]==0 ){
  2700. res = 1;
  2701. break;
  2702. }
  2703. }
  2704. i = k-1;
  2705. if( neg ){
  2706. res = !res;
  2707. neg = 0;
  2708. }
  2709. okTerm = 0;
  2710. continue;
  2711. }
  2712. goto pp_syntax_error;
  2713. }
  2714. return res;
  2715. pp_syntax_error:
  2716. if( lineno>0 ){
  2717. fprintf(stderr, "%%if syntax error on line %d.\n", lineno);
  2718. fprintf(stderr, " %.*s <-- syntax error here\n", i+1, z);
  2719. exit(1);
  2720. }else{
  2721. return -(i+1);
  2722. }
  2723. }
  2724. /* Run the preprocessor over the input file text. The global variables
  2725. ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
  2726. ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
  2727. ** comments them out. Text in between is also commented out as appropriate.
  2728. */
  2729. static void preprocess_input(char *z){
  2730. int i, j, k;
  2731. int exclude = 0;
  2732. int start = 0;
  2733. int lineno = 1;
  2734. int start_lineno = 1;
  2735. for(i=0; z[i]; i++){
  2736. if( z[i]=='\n' ) lineno++;
  2737. if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
  2738. if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
  2739. if( exclude ){
  2740. exclude--;
  2741. if( exclude==0 ){
  2742. for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
  2743. }
  2744. }
  2745. for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
  2746. }else if( strncmp(&z[i],"%else",5)==0 && ISSPACE(z[i+5]) ){
  2747. if( exclude==1){
  2748. exclude = 0;
  2749. for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
  2750. }else if( exclude==0 ){
  2751. exclude = 1;
  2752. start = i;
  2753. start_lineno = lineno;
  2754. }
  2755. for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
  2756. }else if( strncmp(&z[i],"%ifdef ",7)==0
  2757. || strncmp(&z[i],"%if ",4)==0
  2758. || strncmp(&z[i],"%ifndef ",8)==0 ){
  2759. if( exclude ){
  2760. exclude++;
  2761. }else{
  2762. int isNot;
  2763. int iBool;
  2764. for(j=i; z[j] && !ISSPACE(z[j]); j++){}
  2765. iBool = j;
  2766. isNot = (j==i+7);
  2767. while( z[j] && z[j]!='\n' ){ j++; }
  2768. k = z[j];
  2769. z[j] = 0;
  2770. exclude = eval_preprocessor_boolean(&z[iBool], lineno);
  2771. z[j] = k;
  2772. if( !isNot ) exclude = !exclude;
  2773. if( exclude ){
  2774. start = i;
  2775. start_lineno = lineno;
  2776. }
  2777. }
  2778. for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
  2779. }
  2780. }
  2781. if( exclude ){
  2782. fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
  2783. exit(1);
  2784. }
  2785. }
  2786. /* In spite of its name, this function is really a scanner. It read
  2787. ** in the entire input file (all at once) then tokenizes it. Each
  2788. ** token is passed to the function "parseonetoken" which builds all
  2789. ** the appropriate data structures in the global state vector "gp".
  2790. */
  2791. void Parse(struct lemon *gp)
  2792. {
  2793. struct pstate ps;
  2794. FILE *fp;
  2795. char *filebuf;
  2796. unsigned int filesize;
  2797. int lineno;
  2798. int c;
  2799. char *cp, *nextcp;
  2800. int startline = 0;
  2801. memset(&ps, '\0', sizeof(ps));
  2802. ps.gp = gp;
  2803. ps.filename = gp->filename;
  2804. ps.errorcnt = 0;
  2805. ps.state = INITIALIZE;
  2806. /* Begin by reading the input file */
  2807. fp = fopen(ps.filename,"rb");
  2808. if( fp==0 ){
  2809. ErrorMsg(ps.filename,0,"Can't open this file for reading.");
  2810. gp->errorcnt++;
  2811. return;
  2812. }
  2813. fseek(fp,0,2);
  2814. filesize = ftell(fp);
  2815. rewind(fp);
  2816. filebuf = (char *)malloc( filesize+1 );
  2817. if( filesize>100000000 || filebuf==0 ){
  2818. ErrorMsg(ps.filename,0,"Input file too large.");
  2819. free(filebuf);
  2820. gp->errorcnt++;
  2821. fclose(fp);
  2822. return;
  2823. }
  2824. if( fread(filebuf,1,filesize,fp)!=filesize ){
  2825. ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
  2826. filesize);
  2827. free(filebuf);
  2828. gp->errorcnt++;
  2829. fclose(fp);
  2830. return;
  2831. }
  2832. fclose(fp);
  2833. filebuf[filesize] = 0;
  2834. /* Make an initial pass through the file to handle %ifdef and %ifndef */
  2835. preprocess_input(filebuf);
  2836. if( gp->printPreprocessed ){
  2837. printf("%s\n", filebuf);
  2838. return;
  2839. }
  2840. /* Now scan the text of the input file */
  2841. lineno = 1;
  2842. for(cp=filebuf; (c= *cp)!=0; ){
  2843. if( c=='\n' ) lineno++; /* Keep track of the line number */
  2844. if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
  2845. if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
  2846. cp+=2;
  2847. while( (c= *cp)!=0 && c!='\n' ) cp++;
  2848. continue;
  2849. }
  2850. if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
  2851. cp+=2;
  2852. if( (*cp)=='/' ) cp++;
  2853. while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
  2854. if( c=='\n' ) lineno++;
  2855. cp++;
  2856. }
  2857. if( c ) cp++;
  2858. continue;
  2859. }
  2860. ps.tokenstart = cp; /* Mark the beginning of the token */
  2861. ps.tokenlineno = lineno; /* Linenumber on which token begins */
  2862. if( c=='\"' ){ /* String literals */
  2863. cp++;
  2864. while( (c= *cp)!=0 && c!='\"' ){
  2865. if( c=='\n' ) lineno++;
  2866. cp++;
  2867. }
  2868. if( c==0 ){
  2869. ErrorMsg(ps.filename,startline,
  2870. "String starting on this line is not terminated before "
  2871. "the end of the file.");
  2872. ps.errorcnt++;
  2873. nextcp = cp;
  2874. }else{
  2875. nextcp = cp+1;
  2876. }
  2877. }else if( c=='{' ){ /* A block of C code */
  2878. int level;
  2879. cp++;
  2880. for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
  2881. if( c=='\n' ) lineno++;
  2882. else if( c=='{' ) level++;
  2883. else if( c=='}' ) level--;
  2884. else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
  2885. int prevc;
  2886. cp = &cp[2];
  2887. prevc = 0;
  2888. while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
  2889. if( c=='\n' ) lineno++;
  2890. prevc = c;
  2891. cp++;
  2892. }
  2893. }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
  2894. cp = &cp[2];
  2895. while( (c= *cp)!=0 && c!='\n' ) cp++;
  2896. if( c ) lineno++;
  2897. }else if( c=='\'' || c=='\"' ){ /* String a character literals */
  2898. int startchar, prevc;
  2899. startchar = c;
  2900. prevc = 0;
  2901. for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
  2902. if( c=='\n' ) lineno++;
  2903. if( prevc=='\\' ) prevc = 0;
  2904. else prevc = c;
  2905. }
  2906. }
  2907. }
  2908. if( c==0 ){
  2909. ErrorMsg(ps.filename,ps.tokenlineno,
  2910. "C code starting on this line is not terminated before "
  2911. "the end of the file.");
  2912. ps.errorcnt++;
  2913. nextcp = cp;
  2914. }else{
  2915. nextcp = cp+1;
  2916. }
  2917. }else if( ISALNUM(c) ){ /* Identifiers */
  2918. while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
  2919. nextcp = cp;
  2920. }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
  2921. cp += 3;
  2922. nextcp = cp;
  2923. }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
  2924. cp += 2;
  2925. while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
  2926. nextcp = cp;
  2927. }else{ /* All other (one character) operators */
  2928. cp++;
  2929. nextcp = cp;
  2930. }
  2931. c = *cp;
  2932. *cp = 0; /* Null terminate the token */
  2933. parseonetoken(&ps); /* Parse the token */
  2934. *cp = (char)c; /* Restore the buffer */
  2935. cp = nextcp;
  2936. }
  2937. free(filebuf); /* Release the buffer after parsing */
  2938. gp->rule = ps.firstrule;
  2939. gp->errorcnt = ps.errorcnt;
  2940. }
  2941. /*************************** From the file "plink.c" *********************/
  2942. /*
  2943. ** Routines processing configuration follow-set propagation links
  2944. ** in the LEMON parser generator.
  2945. */
  2946. static struct plink *plink_freelist = 0;
  2947. /* Allocate a new plink */
  2948. struct plink *Plink_new(void){
  2949. struct plink *newlink;
  2950. if( plink_freelist==0 ){
  2951. int i;
  2952. int amt = 100;
  2953. plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
  2954. if( plink_freelist==0 ){
  2955. fprintf(stderr,
  2956. "Unable to allocate memory for a new follow-set propagation link.\n");
  2957. exit(1);
  2958. }
  2959. for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
  2960. plink_freelist[amt-1].next = 0;
  2961. }
  2962. newlink = plink_freelist;
  2963. plink_freelist = plink_freelist->next;
  2964. return newlink;
  2965. }
  2966. /* Add a plink to a plink list */
  2967. void Plink_add(struct plink **plpp, struct config *cfp)
  2968. {
  2969. struct plink *newlink;
  2970. newlink = Plink_new();
  2971. newlink->next = *plpp;
  2972. *plpp = newlink;
  2973. newlink->cfp = cfp;
  2974. }
  2975. /* Transfer every plink on the list "from" to the list "to" */
  2976. void Plink_copy(struct plink **to, struct plink *from)
  2977. {
  2978. struct plink *nextpl;
  2979. while( from ){
  2980. nextpl = from->next;
  2981. from->next = *to;
  2982. *to = from;
  2983. from = nextpl;
  2984. }
  2985. }
  2986. /* Delete every plink on the list */
  2987. void Plink_delete(struct plink *plp)
  2988. {
  2989. struct plink *nextpl;
  2990. while( plp ){
  2991. nextpl = plp->next;
  2992. plp->next = plink_freelist;
  2993. plink_freelist = plp;
  2994. plp = nextpl;
  2995. }
  2996. }
  2997. /*********************** From the file "report.c" **************************/
  2998. /*
  2999. ** Procedures for generating reports and tables in the LEMON parser generator.
  3000. */
  3001. /* Generate a filename with the given suffix. Space to hold the
  3002. ** name comes from malloc() and must be freed by the calling
  3003. ** function.
  3004. */
  3005. PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
  3006. {
  3007. char *name;
  3008. char *cp;
  3009. char *filename = lemp->filename;
  3010. int sz;
  3011. if( outputDir ){
  3012. cp = strrchr(filename, '/');
  3013. if( cp ) filename = cp + 1;
  3014. }
  3015. sz = lemonStrlen(filename);
  3016. sz += lemonStrlen(suffix);
  3017. if( outputDir ) sz += lemonStrlen(outputDir) + 1;
  3018. sz += 5;
  3019. name = (char*)malloc( sz );
  3020. if( name==0 ){
  3021. fprintf(stderr,"Can't allocate space for a filename.\n");
  3022. exit(1);
  3023. }
  3024. name[0] = 0;
  3025. if( outputDir ){
  3026. lemon_strcpy(name, outputDir);
  3027. lemon_strcat(name, "/");
  3028. }
  3029. lemon_strcat(name,filename);
  3030. cp = strrchr(name,'.');
  3031. if( cp ) *cp = 0;
  3032. lemon_strcat(name,suffix);
  3033. return name;
  3034. }
  3035. /* Open a file with a name based on the name of the input file,
  3036. ** but with a different (specified) suffix, and return a pointer
  3037. ** to the stream */
  3038. PRIVATE FILE *file_open(
  3039. struct lemon *lemp,
  3040. const char *suffix,
  3041. const char *mode
  3042. ){
  3043. FILE *fp;
  3044. if( lemp->outname ) free(lemp->outname);
  3045. lemp->outname = file_makename(lemp, suffix);
  3046. fp = fopen(lemp->outname,mode);
  3047. if( fp==0 && *mode=='w' ){
  3048. fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
  3049. lemp->errorcnt++;
  3050. return 0;
  3051. }
  3052. return fp;
  3053. }
  3054. /* Print the text of a rule
  3055. */
  3056. void rule_print(FILE *out, struct rule *rp){
  3057. int i, j;
  3058. fprintf(out, "%s",rp->lhs->name);
  3059. /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
  3060. fprintf(out," ::=");
  3061. for(i=0; i<rp->nrhs; i++){
  3062. struct symbol *sp = rp->rhs[i];
  3063. if( sp->type==MULTITERMINAL ){
  3064. fprintf(out," %s", sp->subsym[0]->name);
  3065. for(j=1; j<sp->nsubsym; j++){
  3066. fprintf(out,"|%s", sp->subsym[j]->name);
  3067. }
  3068. }else{
  3069. fprintf(out," %s", sp->name);
  3070. }
  3071. /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
  3072. }
  3073. }
  3074. /* Duplicate the input file without comments and without actions
  3075. ** on rules */
  3076. void Reprint(struct lemon *lemp)
  3077. {
  3078. struct rule *rp;
  3079. struct symbol *sp;
  3080. int i, j, maxlen, len, ncolumns, skip;
  3081. printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
  3082. maxlen = 10;
  3083. for(i=0; i<lemp->nsymbol; i++){
  3084. sp = lemp->symbols[i];
  3085. len = lemonStrlen(sp->name);
  3086. if( len>maxlen ) maxlen = len;
  3087. }
  3088. ncolumns = 76/(maxlen+5);
  3089. if( ncolumns<1 ) ncolumns = 1;
  3090. skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
  3091. for(i=0; i<skip; i++){
  3092. printf("//");
  3093. for(j=i; j<lemp->nsymbol; j+=skip){
  3094. sp = lemp->symbols[j];
  3095. assert( sp->index==j );
  3096. printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
  3097. }
  3098. printf("\n");
  3099. }
  3100. for(rp=lemp->rule; rp; rp=rp->next){
  3101. rule_print(stdout, rp);
  3102. printf(".");
  3103. if( rp->precsym ) printf(" [%s]",rp->precsym->name);
  3104. /* if( rp->code ) printf("\n %s",rp->code); */
  3105. printf("\n");
  3106. }
  3107. }
  3108. /* Print a single rule.
  3109. */
  3110. void RulePrint(FILE *fp, struct rule *rp, int iCursor){
  3111. struct symbol *sp;
  3112. int i, j;
  3113. fprintf(fp,"%s ::=",rp->lhs->name);
  3114. for(i=0; i<=rp->nrhs; i++){
  3115. if( i==iCursor ) fprintf(fp," *");
  3116. if( i==rp->nrhs ) break;
  3117. sp = rp->rhs[i];
  3118. if( sp->type==MULTITERMINAL ){
  3119. fprintf(fp," %s", sp->subsym[0]->name);
  3120. for(j=1; j<sp->nsubsym; j++){
  3121. fprintf(fp,"|%s",sp->subsym[j]->name);
  3122. }
  3123. }else{
  3124. fprintf(fp," %s", sp->name);
  3125. }
  3126. }
  3127. }
  3128. /* Print the rule for a configuration.
  3129. */
  3130. void ConfigPrint(FILE *fp, struct config *cfp){
  3131. RulePrint(fp, cfp->rp, cfp->dot);
  3132. }
  3133. /* #define TEST */
  3134. #if 0
  3135. /* Print a set */
  3136. PRIVATE void SetPrint(out,set,lemp)
  3137. FILE *out;
  3138. char *set;
  3139. struct lemon *lemp;
  3140. {
  3141. int i;
  3142. char *spacer;
  3143. spacer = "";
  3144. fprintf(out,"%12s[","");
  3145. for(i=0; i<lemp->nterminal; i++){
  3146. if( SetFind(set,i) ){
  3147. fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
  3148. spacer = " ";
  3149. }
  3150. }
  3151. fprintf(out,"]\n");
  3152. }
  3153. /* Print a plink chain */
  3154. PRIVATE void PlinkPrint(out,plp,tag)
  3155. FILE *out;
  3156. struct plink *plp;
  3157. char *tag;
  3158. {
  3159. while( plp ){
  3160. fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
  3161. ConfigPrint(out,plp->cfp);
  3162. fprintf(out,"\n");
  3163. plp = plp->next;
  3164. }
  3165. }
  3166. #endif
  3167. /* Print an action to the given file descriptor. Return FALSE if
  3168. ** nothing was actually printed.
  3169. */
  3170. int PrintAction(
  3171. struct action *ap, /* The action to print */
  3172. FILE *fp, /* Print the action here */
  3173. int indent /* Indent by this amount */
  3174. ){
  3175. int result = 1;
  3176. switch( ap->type ){
  3177. case SHIFT: {
  3178. struct state *stp = ap->x.stp;
  3179. fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
  3180. break;
  3181. }
  3182. case REDUCE: {
  3183. struct rule *rp = ap->x.rp;
  3184. fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
  3185. RulePrint(fp, rp, -1);
  3186. break;
  3187. }
  3188. case SHIFTREDUCE: {
  3189. struct rule *rp = ap->x.rp;
  3190. fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
  3191. RulePrint(fp, rp, -1);
  3192. break;
  3193. }
  3194. case ACCEPT:
  3195. fprintf(fp,"%*s accept",indent,ap->sp->name);
  3196. break;
  3197. case ERROR:
  3198. fprintf(fp,"%*s error",indent,ap->sp->name);
  3199. break;
  3200. case SRCONFLICT:
  3201. case RRCONFLICT:
  3202. fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
  3203. indent,ap->sp->name,ap->x.rp->iRule);
  3204. break;
  3205. case SSCONFLICT:
  3206. fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
  3207. indent,ap->sp->name,ap->x.stp->statenum);
  3208. break;
  3209. case SH_RESOLVED:
  3210. if( showPrecedenceConflict ){
  3211. fprintf(fp,"%*s shift %-7d -- dropped by precedence",
  3212. indent,ap->sp->name,ap->x.stp->statenum);
  3213. }else{
  3214. result = 0;
  3215. }
  3216. break;
  3217. case RD_RESOLVED:
  3218. if( showPrecedenceConflict ){
  3219. fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
  3220. indent,ap->sp->name,ap->x.rp->iRule);
  3221. }else{
  3222. result = 0;
  3223. }
  3224. break;
  3225. case NOT_USED:
  3226. result = 0;
  3227. break;
  3228. }
  3229. if( result && ap->spOpt ){
  3230. fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
  3231. }
  3232. return result;
  3233. }
  3234. /* Generate the "*.out" log file */
  3235. void ReportOutput(struct lemon *lemp)
  3236. {
  3237. int i, n;
  3238. struct state *stp;
  3239. struct config *cfp;
  3240. struct action *ap;
  3241. struct rule *rp;
  3242. FILE *fp;
  3243. fp = file_open(lemp,".out","wb");
  3244. if( fp==0 ) return;
  3245. for(i=0; i<lemp->nxstate; i++){
  3246. stp = lemp->sorted[i];
  3247. fprintf(fp,"State %d:\n",stp->statenum);
  3248. if( lemp->basisflag ) cfp=stp->bp;
  3249. else cfp=stp->cfp;
  3250. while( cfp ){
  3251. char buf[20];
  3252. if( cfp->dot==cfp->rp->nrhs ){
  3253. lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
  3254. fprintf(fp," %5s ",buf);
  3255. }else{
  3256. fprintf(fp," ");
  3257. }
  3258. ConfigPrint(fp,cfp);
  3259. fprintf(fp,"\n");
  3260. #if 0
  3261. SetPrint(fp,cfp->fws,lemp);
  3262. PlinkPrint(fp,cfp->fplp,"To ");
  3263. PlinkPrint(fp,cfp->bplp,"From");
  3264. #endif
  3265. if( lemp->basisflag ) cfp=cfp->bp;
  3266. else cfp=cfp->next;
  3267. }
  3268. fprintf(fp,"\n");
  3269. for(ap=stp->ap; ap; ap=ap->next){
  3270. if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
  3271. }
  3272. fprintf(fp,"\n");
  3273. }
  3274. fprintf(fp, "----------------------------------------------------\n");
  3275. fprintf(fp, "Symbols:\n");
  3276. fprintf(fp, "The first-set of non-terminals is shown after the name.\n\n");
  3277. for(i=0; i<lemp->nsymbol; i++){
  3278. int j;
  3279. struct symbol *sp;
  3280. sp = lemp->symbols[i];
  3281. fprintf(fp, " %3d: %s", i, sp->name);
  3282. if( sp->type==NONTERMINAL ){
  3283. fprintf(fp, ":");
  3284. if( sp->lambda ){
  3285. fprintf(fp, " <lambda>");
  3286. }
  3287. for(j=0; j<lemp->nterminal; j++){
  3288. if( sp->firstset && SetFind(sp->firstset, j) ){
  3289. fprintf(fp, " %s", lemp->symbols[j]->name);
  3290. }
  3291. }
  3292. }
  3293. if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
  3294. fprintf(fp, "\n");
  3295. }
  3296. fprintf(fp, "----------------------------------------------------\n");
  3297. fprintf(fp, "Syntax-only Symbols:\n");
  3298. fprintf(fp, "The following symbols never carry semantic content.\n\n");
  3299. for(i=n=0; i<lemp->nsymbol; i++){
  3300. int w;
  3301. struct symbol *sp = lemp->symbols[i];
  3302. if( sp->bContent ) continue;
  3303. w = (int)strlen(sp->name);
  3304. if( n>0 && n+w>75 ){
  3305. fprintf(fp,"\n");
  3306. n = 0;
  3307. }
  3308. if( n>0 ){
  3309. fprintf(fp, " ");
  3310. n++;
  3311. }
  3312. fprintf(fp, "%s", sp->name);
  3313. n += w;
  3314. }
  3315. if( n>0 ) fprintf(fp, "\n");
  3316. fprintf(fp, "----------------------------------------------------\n");
  3317. fprintf(fp, "Rules:\n");
  3318. for(rp=lemp->rule; rp; rp=rp->next){
  3319. fprintf(fp, "%4d: ", rp->iRule);
  3320. rule_print(fp, rp);
  3321. fprintf(fp,".");
  3322. if( rp->precsym ){
  3323. fprintf(fp," [%s precedence=%d]",
  3324. rp->precsym->name, rp->precsym->prec);
  3325. }
  3326. fprintf(fp,"\n");
  3327. }
  3328. fclose(fp);
  3329. return;
  3330. }
  3331. /* Search for the file "name" which is in the same directory as
  3332. ** the executable */
  3333. PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
  3334. {
  3335. const char *pathlist;
  3336. char *pathbufptr = 0;
  3337. char *pathbuf = 0;
  3338. char *path,*cp;
  3339. char c;
  3340. #ifdef __WIN32__
  3341. cp = strrchr(argv0,'\\');
  3342. #else
  3343. cp = strrchr(argv0,'/');
  3344. #endif
  3345. if( cp ){
  3346. c = *cp;
  3347. *cp = 0;
  3348. path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
  3349. if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
  3350. *cp = c;
  3351. }else{
  3352. pathlist = getenv("PATH");
  3353. if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
  3354. pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
  3355. path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
  3356. if( (pathbuf != 0) && (path!=0) ){
  3357. pathbufptr = pathbuf;
  3358. lemon_strcpy(pathbuf, pathlist);
  3359. while( *pathbuf ){
  3360. cp = strchr(pathbuf,':');
  3361. if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
  3362. c = *cp;
  3363. *cp = 0;
  3364. lemon_sprintf(path,"%s/%s",pathbuf,name);
  3365. *cp = c;
  3366. if( c==0 ) pathbuf[0] = 0;
  3367. else pathbuf = &cp[1];
  3368. if( access(path,modemask)==0 ) break;
  3369. }
  3370. }
  3371. free(pathbufptr);
  3372. }
  3373. return path;
  3374. }
  3375. /* Given an action, compute the integer value for that action
  3376. ** which is to be put in the action table of the generated machine.
  3377. ** Return negative if no action should be generated.
  3378. */
  3379. PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
  3380. {
  3381. int act;
  3382. switch( ap->type ){
  3383. case SHIFT: act = ap->x.stp->statenum; break;
  3384. case SHIFTREDUCE: {
  3385. /* Since a SHIFT is inherient after a prior REDUCE, convert any
  3386. ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
  3387. ** REDUCE action: */
  3388. if( ap->sp->index>=lemp->nterminal
  3389. && (lemp->errsym==0 || ap->sp->index!=lemp->errsym->index)
  3390. ){
  3391. act = lemp->minReduce + ap->x.rp->iRule;
  3392. }else{
  3393. act = lemp->minShiftReduce + ap->x.rp->iRule;
  3394. }
  3395. break;
  3396. }
  3397. case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
  3398. case ERROR: act = lemp->errAction; break;
  3399. case ACCEPT: act = lemp->accAction; break;
  3400. default: act = -1; break;
  3401. }
  3402. return act;
  3403. }
  3404. #define LINESIZE 1000
  3405. /* The next cluster of routines are for reading the template file
  3406. ** and writing the results to the generated parser */
  3407. /* The first function transfers data from "in" to "out" until
  3408. ** a line is seen which begins with "%%". The line number is
  3409. ** tracked.
  3410. **
  3411. ** if name!=0, then any word that begin with "Parse" is changed to
  3412. ** begin with *name instead.
  3413. */
  3414. PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
  3415. {
  3416. int i, iStart;
  3417. char line[LINESIZE];
  3418. while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
  3419. (*lineno)++;
  3420. iStart = 0;
  3421. if( name ){
  3422. for(i=0; line[i]; i++){
  3423. if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
  3424. && (i==0 || !ISALPHA(line[i-1]))
  3425. ){
  3426. if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
  3427. fprintf(out,"%s",name);
  3428. i += 4;
  3429. iStart = i+1;
  3430. }
  3431. }
  3432. }
  3433. fprintf(out,"%s",&line[iStart]);
  3434. }
  3435. }
  3436. /* Skip forward past the header of the template file to the first "%%"
  3437. */
  3438. PRIVATE void tplt_skip_header(FILE *in, int *lineno)
  3439. {
  3440. char line[LINESIZE];
  3441. while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
  3442. (*lineno)++;
  3443. }
  3444. }
  3445. /* The next function finds the template file and opens it, returning
  3446. ** a pointer to the opened file. */
  3447. PRIVATE FILE *tplt_open(struct lemon *lemp)
  3448. {
  3449. static char templatename[] = "lempar.c";
  3450. char buf[1000];
  3451. FILE *in;
  3452. char *tpltname;
  3453. char *toFree = 0;
  3454. char *cp;
  3455. /* first, see if user specified a template filename on the command line. */
  3456. if (user_templatename != 0) {
  3457. if( access(user_templatename,004)==-1 ){
  3458. fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
  3459. user_templatename);
  3460. lemp->errorcnt++;
  3461. return 0;
  3462. }
  3463. in = fopen(user_templatename,"rb");
  3464. if( in==0 ){
  3465. fprintf(stderr,"Can't open the template file \"%s\".\n",
  3466. user_templatename);
  3467. lemp->errorcnt++;
  3468. return 0;
  3469. }
  3470. return in;
  3471. }
  3472. cp = strrchr(lemp->filename,'.');
  3473. if( cp ){
  3474. lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
  3475. }else{
  3476. lemon_sprintf(buf,"%s.lt",lemp->filename);
  3477. }
  3478. if( access(buf,004)==0 ){
  3479. tpltname = buf;
  3480. }else if( access(templatename,004)==0 ){
  3481. tpltname = templatename;
  3482. }else{
  3483. toFree = tpltname = pathsearch(lemp->argv0,templatename,0);
  3484. }
  3485. if( tpltname==0 ){
  3486. fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
  3487. templatename);
  3488. lemp->errorcnt++;
  3489. return 0;
  3490. }
  3491. in = fopen(tpltname,"rb");
  3492. if( in==0 ){
  3493. fprintf(stderr,"Can't open the template file \"%s\".\n",tpltname);
  3494. lemp->errorcnt++;
  3495. }
  3496. free(toFree);
  3497. return in;
  3498. }
  3499. /* Print a #line directive line to the output file. */
  3500. PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
  3501. {
  3502. fprintf(out,"#line %d \"",lineno);
  3503. while( *filename ){
  3504. if( *filename == '\\' ) putc('\\',out);
  3505. putc(*filename,out);
  3506. filename++;
  3507. }
  3508. fprintf(out,"\"\n");
  3509. }
  3510. /* Print a string to the file and keep the linenumber up to date */
  3511. PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
  3512. {
  3513. if( str==0 ) return;
  3514. while( *str ){
  3515. putc(*str,out);
  3516. if( *str=='\n' ) (*lineno)++;
  3517. str++;
  3518. }
  3519. if( str[-1]!='\n' ){
  3520. putc('\n',out);
  3521. (*lineno)++;
  3522. }
  3523. if (!lemp->nolinenosflag) {
  3524. (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
  3525. }
  3526. return;
  3527. }
  3528. /*
  3529. ** The following routine emits code for the destructor for the
  3530. ** symbol sp
  3531. */
  3532. void emit_destructor_code(
  3533. FILE *out,
  3534. struct symbol *sp,
  3535. struct lemon *lemp,
  3536. int *lineno
  3537. ){
  3538. char *cp = 0;
  3539. if( sp->type==TERMINAL ){
  3540. cp = lemp->tokendest;
  3541. if( cp==0 ) return;
  3542. fprintf(out,"{\n"); (*lineno)++;
  3543. }else if( sp->destructor ){
  3544. cp = sp->destructor;
  3545. fprintf(out,"{\n"); (*lineno)++;
  3546. if( !lemp->nolinenosflag ){
  3547. (*lineno)++;
  3548. tplt_linedir(out,sp->destLineno,lemp->filename);
  3549. }
  3550. }else if( lemp->vardest ){
  3551. cp = lemp->vardest;
  3552. if( cp==0 ) return;
  3553. fprintf(out,"{\n"); (*lineno)++;
  3554. }else{
  3555. assert( 0 ); /* Cannot happen */
  3556. }
  3557. for(; *cp; cp++){
  3558. if( *cp=='$' && cp[1]=='$' ){
  3559. fprintf(out,"(yypminor->yy%d)",sp->dtnum);
  3560. cp++;
  3561. continue;
  3562. }
  3563. if( *cp=='\n' ) (*lineno)++;
  3564. fputc(*cp,out);
  3565. }
  3566. fprintf(out,"\n"); (*lineno)++;
  3567. if (!lemp->nolinenosflag) {
  3568. (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
  3569. }
  3570. fprintf(out,"}\n"); (*lineno)++;
  3571. return;
  3572. }
  3573. /*
  3574. ** Return TRUE (non-zero) if the given symbol has a destructor.
  3575. */
  3576. int has_destructor(struct symbol *sp, struct lemon *lemp)
  3577. {
  3578. int ret;
  3579. if( sp->type==TERMINAL ){
  3580. ret = lemp->tokendest!=0;
  3581. }else{
  3582. ret = lemp->vardest!=0 || sp->destructor!=0;
  3583. }
  3584. return ret;
  3585. }
  3586. /*
  3587. ** Append text to a dynamically allocated string. If zText is 0 then
  3588. ** reset the string to be empty again. Always return the complete text
  3589. ** of the string (which is overwritten with each call).
  3590. **
  3591. ** n bytes of zText are stored. If n==0 then all of zText up to the first
  3592. ** \000 terminator is stored. zText can contain up to two instances of
  3593. ** %d. The values of p1 and p2 are written into the first and second
  3594. ** %d.
  3595. **
  3596. ** If n==-1, then the previous character is overwritten.
  3597. */
  3598. PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
  3599. static char empty[1] = { 0 };
  3600. static char *z = 0;
  3601. static int alloced = 0;
  3602. static int used = 0;
  3603. int c;
  3604. char zInt[40];
  3605. if( zText==0 ){
  3606. if( used==0 && z!=0 ) z[0] = 0;
  3607. used = 0;
  3608. return z;
  3609. }
  3610. if( n<=0 ){
  3611. if( n<0 ){
  3612. used += n;
  3613. assert( used>=0 );
  3614. }
  3615. n = lemonStrlen(zText);
  3616. }
  3617. if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
  3618. alloced = n + sizeof(zInt)*2 + used + 200;
  3619. z = (char *) realloc(z, alloced);
  3620. }
  3621. if( z==0 ) return empty;
  3622. while( n-- > 0 ){
  3623. c = *(zText++);
  3624. if( c=='%' && n>0 && zText[0]=='d' ){
  3625. lemon_sprintf(zInt, "%d", p1);
  3626. p1 = p2;
  3627. lemon_strcpy(&z[used], zInt);
  3628. used += lemonStrlen(&z[used]);
  3629. zText++;
  3630. n--;
  3631. }else{
  3632. z[used++] = (char)c;
  3633. }
  3634. }
  3635. z[used] = 0;
  3636. return z;
  3637. }
  3638. /*
  3639. ** Write and transform the rp->code string so that symbols are expanded.
  3640. ** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
  3641. **
  3642. ** Return 1 if the expanded code requires that "yylhsminor" local variable
  3643. ** to be defined.
  3644. */
  3645. PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
  3646. char *cp, *xp;
  3647. int i;
  3648. int rc = 0; /* True if yylhsminor is used */
  3649. int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
  3650. const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
  3651. char lhsused = 0; /* True if the LHS element has been used */
  3652. char lhsdirect; /* True if LHS writes directly into stack */
  3653. char used[MAXRHS]; /* True for each RHS element which is used */
  3654. char zLhs[50]; /* Convert the LHS symbol into this string */
  3655. char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
  3656. for(i=0; i<rp->nrhs; i++) used[i] = 0;
  3657. lhsused = 0;
  3658. if( rp->code==0 ){
  3659. static char newlinestr[2] = { '\n', '\0' };
  3660. rp->code = newlinestr;
  3661. rp->line = rp->ruleline;
  3662. rp->noCode = 1;
  3663. }else{
  3664. rp->noCode = 0;
  3665. }
  3666. if( rp->nrhs==0 ){
  3667. /* If there are no RHS symbols, then writing directly to the LHS is ok */
  3668. lhsdirect = 1;
  3669. }else if( rp->rhsalias[0]==0 ){
  3670. /* The left-most RHS symbol has no value. LHS direct is ok. But
  3671. ** we have to call the destructor on the RHS symbol first. */
  3672. lhsdirect = 1;
  3673. if( has_destructor(rp->rhs[0],lemp) ){
  3674. append_str(0,0,0,0);
  3675. append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
  3676. rp->rhs[0]->index,1-rp->nrhs);
  3677. rp->codePrefix = Strsafe(append_str(0,0,0,0));
  3678. rp->noCode = 0;
  3679. }
  3680. }else if( rp->lhsalias==0 ){
  3681. /* There is no LHS value symbol. */
  3682. lhsdirect = 1;
  3683. }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
  3684. /* The LHS symbol and the left-most RHS symbol are the same, so
  3685. ** direct writing is allowed */
  3686. lhsdirect = 1;
  3687. lhsused = 1;
  3688. used[0] = 1;
  3689. if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
  3690. ErrorMsg(lemp->filename,rp->ruleline,
  3691. "%s(%s) and %s(%s) share the same label but have "
  3692. "different datatypes.",
  3693. rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
  3694. lemp->errorcnt++;
  3695. }
  3696. }else{
  3697. lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
  3698. rp->lhsalias, rp->rhsalias[0]);
  3699. zSkip = strstr(rp->code, zOvwrt);
  3700. if( zSkip!=0 ){
  3701. /* The code contains a special comment that indicates that it is safe
  3702. ** for the LHS label to overwrite left-most RHS label. */
  3703. lhsdirect = 1;
  3704. }else{
  3705. lhsdirect = 0;
  3706. }
  3707. }
  3708. if( lhsdirect ){
  3709. sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
  3710. }else{
  3711. rc = 1;
  3712. sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
  3713. }
  3714. append_str(0,0,0,0);
  3715. /* This const cast is wrong but harmless, if we're careful. */
  3716. for(cp=(char *)rp->code; *cp; cp++){
  3717. if( cp==zSkip ){
  3718. append_str(zOvwrt,0,0,0);
  3719. cp += lemonStrlen(zOvwrt)-1;
  3720. dontUseRhs0 = 1;
  3721. continue;
  3722. }
  3723. if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
  3724. char saved;
  3725. for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
  3726. saved = *xp;
  3727. *xp = 0;
  3728. if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
  3729. append_str(zLhs,0,0,0);
  3730. cp = xp;
  3731. lhsused = 1;
  3732. }else{
  3733. for(i=0; i<rp->nrhs; i++){
  3734. if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
  3735. if( i==0 && dontUseRhs0 ){
  3736. ErrorMsg(lemp->filename,rp->ruleline,
  3737. "Label %s used after '%s'.",
  3738. rp->rhsalias[0], zOvwrt);
  3739. lemp->errorcnt++;
  3740. }else if( cp!=rp->code && cp[-1]=='@' ){
  3741. /* If the argument is of the form @X then substituted
  3742. ** the token number of X, not the value of X */
  3743. append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
  3744. }else{
  3745. struct symbol *sp = rp->rhs[i];
  3746. int dtnum;
  3747. if( sp->type==MULTITERMINAL ){
  3748. dtnum = sp->subsym[0]->dtnum;
  3749. }else{
  3750. dtnum = sp->dtnum;
  3751. }
  3752. append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
  3753. }
  3754. cp = xp;
  3755. used[i] = 1;
  3756. break;
  3757. }
  3758. }
  3759. }
  3760. *xp = saved;
  3761. }
  3762. append_str(cp, 1, 0, 0);
  3763. } /* End loop */
  3764. /* Main code generation completed */
  3765. cp = append_str(0,0,0,0);
  3766. if( cp && cp[0] ) rp->code = Strsafe(cp);
  3767. append_str(0,0,0,0);
  3768. /* Check to make sure the LHS has been used */
  3769. if( rp->lhsalias && !lhsused ){
  3770. ErrorMsg(lemp->filename,rp->ruleline,
  3771. "Label \"%s\" for \"%s(%s)\" is never used.",
  3772. rp->lhsalias,rp->lhs->name,rp->lhsalias);
  3773. lemp->errorcnt++;
  3774. }
  3775. /* Generate destructor code for RHS minor values which are not referenced.
  3776. ** Generate error messages for unused labels and duplicate labels.
  3777. */
  3778. for(i=0; i<rp->nrhs; i++){
  3779. if( rp->rhsalias[i] ){
  3780. if( i>0 ){
  3781. int j;
  3782. if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
  3783. ErrorMsg(lemp->filename,rp->ruleline,
  3784. "%s(%s) has the same label as the LHS but is not the left-most "
  3785. "symbol on the RHS.",
  3786. rp->rhs[i]->name, rp->rhsalias[i]);
  3787. lemp->errorcnt++;
  3788. }
  3789. for(j=0; j<i; j++){
  3790. if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
  3791. ErrorMsg(lemp->filename,rp->ruleline,
  3792. "Label %s used for multiple symbols on the RHS of a rule.",
  3793. rp->rhsalias[i]);
  3794. lemp->errorcnt++;
  3795. break;
  3796. }
  3797. }
  3798. }
  3799. if( !used[i] ){
  3800. ErrorMsg(lemp->filename,rp->ruleline,
  3801. "Label %s for \"%s(%s)\" is never used.",
  3802. rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
  3803. lemp->errorcnt++;
  3804. }
  3805. }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
  3806. append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
  3807. rp->rhs[i]->index,i-rp->nrhs+1);
  3808. }
  3809. }
  3810. /* If unable to write LHS values directly into the stack, write the
  3811. ** saved LHS value now. */
  3812. if( lhsdirect==0 ){
  3813. append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
  3814. append_str(zLhs, 0, 0, 0);
  3815. append_str(";\n", 0, 0, 0);
  3816. }
  3817. /* Suffix code generation complete */
  3818. cp = append_str(0,0,0,0);
  3819. if( cp && cp[0] ){
  3820. rp->codeSuffix = Strsafe(cp);
  3821. rp->noCode = 0;
  3822. }
  3823. return rc;
  3824. }
  3825. /*
  3826. ** Generate code which executes when the rule "rp" is reduced. Write
  3827. ** the code to "out". Make sure lineno stays up-to-date.
  3828. */
  3829. PRIVATE void emit_code(
  3830. FILE *out,
  3831. struct rule *rp,
  3832. struct lemon *lemp,
  3833. int *lineno
  3834. ){
  3835. const char *cp;
  3836. /* Setup code prior to the #line directive */
  3837. if( rp->codePrefix && rp->codePrefix[0] ){
  3838. fprintf(out, "{%s", rp->codePrefix);
  3839. for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
  3840. }
  3841. /* Generate code to do the reduce action */
  3842. if( rp->code ){
  3843. if( !lemp->nolinenosflag ){
  3844. (*lineno)++;
  3845. tplt_linedir(out,rp->line,lemp->filename);
  3846. }
  3847. fprintf(out,"{%s",rp->code);
  3848. for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
  3849. fprintf(out,"}\n"); (*lineno)++;
  3850. if( !lemp->nolinenosflag ){
  3851. (*lineno)++;
  3852. tplt_linedir(out,*lineno,lemp->outname);
  3853. }
  3854. }
  3855. /* Generate breakdown code that occurs after the #line directive */
  3856. if( rp->codeSuffix && rp->codeSuffix[0] ){
  3857. fprintf(out, "%s", rp->codeSuffix);
  3858. for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
  3859. }
  3860. if( rp->codePrefix ){
  3861. fprintf(out, "}\n"); (*lineno)++;
  3862. }
  3863. return;
  3864. }
  3865. /*
  3866. ** Print the definition of the union used for the parser's data stack.
  3867. ** This union contains fields for every possible data type for tokens
  3868. ** and nonterminals. In the process of computing and printing this
  3869. ** union, also set the ".dtnum" field of every terminal and nonterminal
  3870. ** symbol.
  3871. */
  3872. void print_stack_union(
  3873. FILE *out, /* The output stream */
  3874. struct lemon *lemp, /* The main info structure for this parser */
  3875. int *plineno, /* Pointer to the line number */
  3876. int mhflag /* True if generating makeheaders output */
  3877. ){
  3878. int lineno; /* The line number of the output */
  3879. char **types; /* A hash table of datatypes */
  3880. int arraysize; /* Size of the "types" array */
  3881. int maxdtlength; /* Maximum length of any ".datatype" field. */
  3882. char *stddt; /* Standardized name for a datatype */
  3883. int i,j; /* Loop counters */
  3884. unsigned hash; /* For hashing the name of a type */
  3885. const char *name; /* Name of the parser */
  3886. /* Allocate and initialize types[] and allocate stddt[] */
  3887. arraysize = lemp->nsymbol * 2;
  3888. types = (char**)calloc( arraysize, sizeof(char*) );
  3889. if( types==0 ){
  3890. fprintf(stderr,"Out of memory.\n");
  3891. exit(1);
  3892. }
  3893. for(i=0; i<arraysize; i++) types[i] = 0;
  3894. maxdtlength = 0;
  3895. if( lemp->vartype ){
  3896. maxdtlength = lemonStrlen(lemp->vartype);
  3897. }
  3898. for(i=0; i<lemp->nsymbol; i++){
  3899. int len;
  3900. struct symbol *sp = lemp->symbols[i];
  3901. if( sp->datatype==0 ) continue;
  3902. len = lemonStrlen(sp->datatype);
  3903. if( len>maxdtlength ) maxdtlength = len;
  3904. }
  3905. stddt = (char*)malloc( maxdtlength*2 + 1 );
  3906. if( stddt==0 ){
  3907. fprintf(stderr,"Out of memory.\n");
  3908. exit(1);
  3909. }
  3910. /* Build a hash table of datatypes. The ".dtnum" field of each symbol
  3911. ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
  3912. ** used for terminal symbols. If there is no %default_type defined then
  3913. ** 0 is also used as the .dtnum value for nonterminals which do not specify
  3914. ** a datatype using the %type directive.
  3915. */
  3916. for(i=0; i<lemp->nsymbol; i++){
  3917. struct symbol *sp = lemp->symbols[i];
  3918. char *cp;
  3919. if( sp==lemp->errsym ){
  3920. sp->dtnum = arraysize+1;
  3921. continue;
  3922. }
  3923. if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
  3924. sp->dtnum = 0;
  3925. continue;
  3926. }
  3927. cp = sp->datatype;
  3928. if( cp==0 ) cp = lemp->vartype;
  3929. j = 0;
  3930. while( ISSPACE(*cp) ) cp++;
  3931. while( *cp ) stddt[j++] = *cp++;
  3932. while( j>0 && ISSPACE(stddt[j-1]) ) j--;
  3933. stddt[j] = 0;
  3934. if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
  3935. sp->dtnum = 0;
  3936. continue;
  3937. }
  3938. hash = 0;
  3939. for(j=0; stddt[j]; j++){
  3940. hash = hash*53 + stddt[j];
  3941. }
  3942. hash = (hash & 0x7fffffff)%arraysize;
  3943. while( types[hash] ){
  3944. if( strcmp(types[hash],stddt)==0 ){
  3945. sp->dtnum = hash + 1;
  3946. break;
  3947. }
  3948. hash++;
  3949. if( hash>=(unsigned)arraysize ) hash = 0;
  3950. }
  3951. if( types[hash]==0 ){
  3952. sp->dtnum = hash + 1;
  3953. types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
  3954. if( types[hash]==0 ){
  3955. fprintf(stderr,"Out of memory.\n");
  3956. exit(1);
  3957. }
  3958. lemon_strcpy(types[hash],stddt);
  3959. }
  3960. }
  3961. /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
  3962. name = lemp->name ? lemp->name : "Parse";
  3963. lineno = *plineno;
  3964. if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
  3965. fprintf(out,"#define %sTOKENTYPE %s\n",name,
  3966. lemp->tokentype?lemp->tokentype:"void*"); lineno++;
  3967. if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
  3968. fprintf(out,"typedef union {\n"); lineno++;
  3969. fprintf(out," int yyinit;\n"); lineno++;
  3970. fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
  3971. for(i=0; i<arraysize; i++){
  3972. if( types[i]==0 ) continue;
  3973. fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
  3974. free(types[i]);
  3975. }
  3976. if( lemp->errsym && lemp->errsym->useCnt ){
  3977. fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
  3978. }
  3979. free(stddt);
  3980. free(types);
  3981. fprintf(out,"} YYMINORTYPE;\n"); lineno++;
  3982. *plineno = lineno;
  3983. }
  3984. /*
  3985. ** Return the name of a C datatype able to represent values between
  3986. ** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
  3987. ** for that type (1, 2, or 4) into *pnByte.
  3988. */
  3989. static const char *minimum_size_type(int lwr, int upr, int *pnByte){
  3990. const char *zType = "int";
  3991. int nByte = 4;
  3992. if( lwr>=0 ){
  3993. if( upr<=255 ){
  3994. zType = "unsigned char";
  3995. nByte = 1;
  3996. }else if( upr<65535 ){
  3997. zType = "unsigned short int";
  3998. nByte = 2;
  3999. }else{
  4000. zType = "unsigned int";
  4001. nByte = 4;
  4002. }
  4003. }else if( lwr>=-127 && upr<=127 ){
  4004. zType = "signed char";
  4005. nByte = 1;
  4006. }else if( lwr>=-32767 && upr<32767 ){
  4007. zType = "short";
  4008. nByte = 2;
  4009. }
  4010. if( pnByte ) *pnByte = nByte;
  4011. return zType;
  4012. }
  4013. /*
  4014. ** Each state contains a set of token transaction and a set of
  4015. ** nonterminal transactions. Each of these sets makes an instance
  4016. ** of the following structure. An array of these structures is used
  4017. ** to order the creation of entries in the yy_action[] table.
  4018. */
  4019. struct axset {
  4020. struct state *stp; /* A pointer to a state */
  4021. int isTkn; /* True to use tokens. False for non-terminals */
  4022. int nAction; /* Number of actions */
  4023. int iOrder; /* Original order of action sets */
  4024. };
  4025. /*
  4026. ** Compare to axset structures for sorting purposes
  4027. */
  4028. static int axset_compare(const void *a, const void *b){
  4029. struct axset *p1 = (struct axset*)a;
  4030. struct axset *p2 = (struct axset*)b;
  4031. int c;
  4032. c = p2->nAction - p1->nAction;
  4033. if( c==0 ){
  4034. c = p1->iOrder - p2->iOrder;
  4035. }
  4036. assert( c!=0 || p1==p2 );
  4037. return c;
  4038. }
  4039. /*
  4040. ** Write text on "out" that describes the rule "rp".
  4041. */
  4042. static void writeRuleText(FILE *out, struct rule *rp){
  4043. int j;
  4044. fprintf(out,"%s ::=", rp->lhs->name);
  4045. for(j=0; j<rp->nrhs; j++){
  4046. struct symbol *sp = rp->rhs[j];
  4047. if( sp->type!=MULTITERMINAL ){
  4048. fprintf(out," %s", sp->name);
  4049. }else{
  4050. int k;
  4051. fprintf(out," %s", sp->subsym[0]->name);
  4052. for(k=1; k<sp->nsubsym; k++){
  4053. fprintf(out,"|%s",sp->subsym[k]->name);
  4054. }
  4055. }
  4056. }
  4057. }
  4058. /* Generate C source code for the parser */
  4059. void ReportTable(
  4060. struct lemon *lemp,
  4061. int mhflag, /* Output in makeheaders format if true */
  4062. int sqlFlag /* Generate the *.sql file too */
  4063. ){
  4064. FILE *out, *in, *sql;
  4065. int lineno;
  4066. struct state *stp;
  4067. struct action *ap;
  4068. struct rule *rp;
  4069. struct acttab *pActtab;
  4070. int i, j, n, sz;
  4071. int nLookAhead;
  4072. int szActionType; /* sizeof(YYACTIONTYPE) */
  4073. int szCodeType; /* sizeof(YYCODETYPE) */
  4074. const char *name;
  4075. int mnTknOfst, mxTknOfst;
  4076. int mnNtOfst, mxNtOfst;
  4077. struct axset *ax;
  4078. char *prefix;
  4079. lemp->minShiftReduce = lemp->nstate;
  4080. lemp->errAction = lemp->minShiftReduce + lemp->nrule;
  4081. lemp->accAction = lemp->errAction + 1;
  4082. lemp->noAction = lemp->accAction + 1;
  4083. lemp->minReduce = lemp->noAction + 1;
  4084. lemp->maxAction = lemp->minReduce + lemp->nrule;
  4085. in = tplt_open(lemp);
  4086. if( in==0 ) return;
  4087. out = file_open(lemp,".c","wb");
  4088. if( out==0 ){
  4089. fclose(in);
  4090. return;
  4091. }
  4092. if( sqlFlag==0 ){
  4093. sql = 0;
  4094. }else{
  4095. sql = file_open(lemp, ".sql", "wb");
  4096. if( sql==0 ){
  4097. fclose(in);
  4098. fclose(out);
  4099. return;
  4100. }
  4101. fprintf(sql,
  4102. "BEGIN;\n"
  4103. "CREATE TABLE symbol(\n"
  4104. " id INTEGER PRIMARY KEY,\n"
  4105. " name TEXT NOT NULL,\n"
  4106. " isTerminal BOOLEAN NOT NULL,\n"
  4107. " fallback INTEGER REFERENCES symbol"
  4108. " DEFERRABLE INITIALLY DEFERRED\n"
  4109. ");\n"
  4110. );
  4111. for(i=0; i<lemp->nsymbol; i++){
  4112. fprintf(sql,
  4113. "INSERT INTO symbol(id,name,isTerminal,fallback)"
  4114. "VALUES(%d,'%s',%s",
  4115. i, lemp->symbols[i]->name,
  4116. i<lemp->nterminal ? "TRUE" : "FALSE"
  4117. );
  4118. if( lemp->symbols[i]->fallback ){
  4119. fprintf(sql, ",%d);\n", lemp->symbols[i]->fallback->index);
  4120. }else{
  4121. fprintf(sql, ",NULL);\n");
  4122. }
  4123. }
  4124. fprintf(sql,
  4125. "CREATE TABLE rule(\n"
  4126. " ruleid INTEGER PRIMARY KEY,\n"
  4127. " lhs INTEGER REFERENCES symbol(id),\n"
  4128. " txt TEXT\n"
  4129. ");\n"
  4130. "CREATE TABLE rulerhs(\n"
  4131. " ruleid INTEGER REFERENCES rule(ruleid),\n"
  4132. " pos INTEGER,\n"
  4133. " sym INTEGER REFERENCES symbol(id)\n"
  4134. ");\n"
  4135. );
  4136. for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
  4137. assert( i==rp->iRule );
  4138. fprintf(sql,
  4139. "INSERT INTO rule(ruleid,lhs,txt)VALUES(%d,%d,'",
  4140. rp->iRule, rp->lhs->index
  4141. );
  4142. writeRuleText(sql, rp);
  4143. fprintf(sql,"');\n");
  4144. for(j=0; j<rp->nrhs; j++){
  4145. struct symbol *sp = rp->rhs[j];
  4146. if( sp->type!=MULTITERMINAL ){
  4147. fprintf(sql,
  4148. "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
  4149. i,j,sp->index
  4150. );
  4151. }else{
  4152. int k;
  4153. for(k=0; k<sp->nsubsym; k++){
  4154. fprintf(sql,
  4155. "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
  4156. i,j,sp->subsym[k]->index
  4157. );
  4158. }
  4159. }
  4160. }
  4161. }
  4162. fprintf(sql, "COMMIT;\n");
  4163. }
  4164. lineno = 1;
  4165. fprintf(out,
  4166. "/* This file is automatically generated by Lemon from input grammar\n"
  4167. "** source file \"%s\". */\n", lemp->filename); lineno += 2;
  4168. /* The first %include directive begins with a C-language comment,
  4169. ** then skip over the header comment of the template file
  4170. */
  4171. if( lemp->include==0 ) lemp->include = "";
  4172. for(i=0; ISSPACE(lemp->include[i]); i++){
  4173. if( lemp->include[i]=='\n' ){
  4174. lemp->include += i+1;
  4175. i = -1;
  4176. }
  4177. }
  4178. if( lemp->include[0]=='/' ){
  4179. tplt_skip_header(in,&lineno);
  4180. }else{
  4181. tplt_xfer(lemp->name,in,out,&lineno);
  4182. }
  4183. /* Generate the include code, if any */
  4184. tplt_print(out,lemp,lemp->include,&lineno);
  4185. if( mhflag ){
  4186. char *incName = file_makename(lemp, ".h");
  4187. fprintf(out,"#include \"%s\"\n", incName); lineno++;
  4188. free(incName);
  4189. }
  4190. tplt_xfer(lemp->name,in,out,&lineno);
  4191. /* Generate #defines for all tokens */
  4192. if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
  4193. else prefix = "";
  4194. if( mhflag ){
  4195. fprintf(out,"#if INTERFACE\n"); lineno++;
  4196. }else{
  4197. fprintf(out,"#ifndef %s%s\n", prefix, lemp->symbols[1]->name);
  4198. }
  4199. for(i=1; i<lemp->nterminal; i++){
  4200. fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
  4201. lineno++;
  4202. }
  4203. fprintf(out,"#endif\n"); lineno++;
  4204. tplt_xfer(lemp->name,in,out,&lineno);
  4205. /* Generate the defines */
  4206. fprintf(out,"#define YYCODETYPE %s\n",
  4207. minimum_size_type(0, lemp->nsymbol, &szCodeType)); lineno++;
  4208. fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol); lineno++;
  4209. fprintf(out,"#define YYACTIONTYPE %s\n",
  4210. minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
  4211. if( lemp->wildcard ){
  4212. fprintf(out,"#define YYWILDCARD %d\n",
  4213. lemp->wildcard->index); lineno++;
  4214. }
  4215. print_stack_union(out,lemp,&lineno,mhflag);
  4216. fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
  4217. if( lemp->stacksize ){
  4218. fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
  4219. }else{
  4220. fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
  4221. }
  4222. fprintf(out, "#endif\n"); lineno++;
  4223. if( mhflag ){
  4224. fprintf(out,"#if INTERFACE\n"); lineno++;
  4225. }
  4226. name = lemp->name ? lemp->name : "Parse";
  4227. if( lemp->arg && lemp->arg[0] ){
  4228. i = lemonStrlen(lemp->arg);
  4229. while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
  4230. while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
  4231. fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
  4232. fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
  4233. fprintf(out,"#define %sARG_PARAM ,%s\n",name,&lemp->arg[i]); lineno++;
  4234. fprintf(out,"#define %sARG_FETCH %s=yypParser->%s;\n",
  4235. name,lemp->arg,&lemp->arg[i]); lineno++;
  4236. fprintf(out,"#define %sARG_STORE yypParser->%s=%s;\n",
  4237. name,&lemp->arg[i],&lemp->arg[i]); lineno++;
  4238. }else{
  4239. fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
  4240. fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
  4241. fprintf(out,"#define %sARG_PARAM\n",name); lineno++;
  4242. fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
  4243. fprintf(out,"#define %sARG_STORE\n",name); lineno++;
  4244. }
  4245. if( lemp->ctx && lemp->ctx[0] ){
  4246. i = lemonStrlen(lemp->ctx);
  4247. while( i>=1 && ISSPACE(lemp->ctx[i-1]) ) i--;
  4248. while( i>=1 && (ISALNUM(lemp->ctx[i-1]) || lemp->ctx[i-1]=='_') ) i--;
  4249. fprintf(out,"#define %sCTX_SDECL %s;\n",name,lemp->ctx); lineno++;
  4250. fprintf(out,"#define %sCTX_PDECL ,%s\n",name,lemp->ctx); lineno++;
  4251. fprintf(out,"#define %sCTX_PARAM ,%s\n",name,&lemp->ctx[i]); lineno++;
  4252. fprintf(out,"#define %sCTX_FETCH %s=yypParser->%s;\n",
  4253. name,lemp->ctx,&lemp->ctx[i]); lineno++;
  4254. fprintf(out,"#define %sCTX_STORE yypParser->%s=%s;\n",
  4255. name,&lemp->ctx[i],&lemp->ctx[i]); lineno++;
  4256. }else{
  4257. fprintf(out,"#define %sCTX_SDECL\n",name); lineno++;
  4258. fprintf(out,"#define %sCTX_PDECL\n",name); lineno++;
  4259. fprintf(out,"#define %sCTX_PARAM\n",name); lineno++;
  4260. fprintf(out,"#define %sCTX_FETCH\n",name); lineno++;
  4261. fprintf(out,"#define %sCTX_STORE\n",name); lineno++;
  4262. }
  4263. if( mhflag ){
  4264. fprintf(out,"#endif\n"); lineno++;
  4265. }
  4266. if( lemp->errsym && lemp->errsym->useCnt ){
  4267. fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
  4268. fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
  4269. }
  4270. if( lemp->has_fallback ){
  4271. fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
  4272. }
  4273. /* Compute the action table, but do not output it yet. The action
  4274. ** table must be computed before generating the YYNSTATE macro because
  4275. ** we need to know how many states can be eliminated.
  4276. */
  4277. ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
  4278. if( ax==0 ){
  4279. fprintf(stderr,"malloc failed\n");
  4280. exit(1);
  4281. }
  4282. for(i=0; i<lemp->nxstate; i++){
  4283. stp = lemp->sorted[i];
  4284. ax[i*2].stp = stp;
  4285. ax[i*2].isTkn = 1;
  4286. ax[i*2].nAction = stp->nTknAct;
  4287. ax[i*2+1].stp = stp;
  4288. ax[i*2+1].isTkn = 0;
  4289. ax[i*2+1].nAction = stp->nNtAct;
  4290. }
  4291. mxTknOfst = mnTknOfst = 0;
  4292. mxNtOfst = mnNtOfst = 0;
  4293. /* In an effort to minimize the action table size, use the heuristic
  4294. ** of placing the largest action sets first */
  4295. for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
  4296. qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
  4297. pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal);
  4298. for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
  4299. stp = ax[i].stp;
  4300. if( ax[i].isTkn ){
  4301. for(ap=stp->ap; ap; ap=ap->next){
  4302. int action;
  4303. if( ap->sp->index>=lemp->nterminal ) continue;
  4304. action = compute_action(lemp, ap);
  4305. if( action<0 ) continue;
  4306. acttab_action(pActtab, ap->sp->index, action);
  4307. }
  4308. stp->iTknOfst = acttab_insert(pActtab, 1);
  4309. if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
  4310. if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
  4311. }else{
  4312. for(ap=stp->ap; ap; ap=ap->next){
  4313. int action;
  4314. if( ap->sp->index<lemp->nterminal ) continue;
  4315. if( ap->sp->index==lemp->nsymbol ) continue;
  4316. action = compute_action(lemp, ap);
  4317. if( action<0 ) continue;
  4318. acttab_action(pActtab, ap->sp->index, action);
  4319. }
  4320. stp->iNtOfst = acttab_insert(pActtab, 0);
  4321. if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
  4322. if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
  4323. }
  4324. #if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
  4325. { int jj, nn;
  4326. for(jj=nn=0; jj<pActtab->nAction; jj++){
  4327. if( pActtab->aAction[jj].action<0 ) nn++;
  4328. }
  4329. printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
  4330. i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
  4331. ax[i].nAction, pActtab->nAction, nn);
  4332. }
  4333. #endif
  4334. }
  4335. free(ax);
  4336. /* Mark rules that are actually used for reduce actions after all
  4337. ** optimizations have been applied
  4338. */
  4339. for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
  4340. for(i=0; i<lemp->nxstate; i++){
  4341. for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
  4342. if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
  4343. ap->x.rp->doesReduce = 1;
  4344. }
  4345. }
  4346. }
  4347. /* Finish rendering the constants now that the action table has
  4348. ** been computed */
  4349. fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
  4350. fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
  4351. fprintf(out,"#define YYNRULE_WITH_ACTION %d\n",lemp->nruleWithAction);
  4352. lineno++;
  4353. fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++;
  4354. fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
  4355. i = lemp->minShiftReduce;
  4356. fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++;
  4357. i += lemp->nrule;
  4358. fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
  4359. fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
  4360. fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
  4361. fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
  4362. fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
  4363. i = lemp->minReduce + lemp->nrule;
  4364. fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
  4365. tplt_xfer(lemp->name,in,out,&lineno);
  4366. /* Now output the action table and its associates:
  4367. **
  4368. ** yy_action[] A single table containing all actions.
  4369. ** yy_lookahead[] A table containing the lookahead for each entry in
  4370. ** yy_action. Used to detect hash collisions.
  4371. ** yy_shift_ofst[] For each state, the offset into yy_action for
  4372. ** shifting terminals.
  4373. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  4374. ** shifting non-terminals after a reduce.
  4375. ** yy_default[] Default action for each state.
  4376. */
  4377. /* Output the yy_action table */
  4378. lemp->nactiontab = n = acttab_action_size(pActtab);
  4379. lemp->tablesize += n*szActionType;
  4380. fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
  4381. fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
  4382. for(i=j=0; i<n; i++){
  4383. int action = acttab_yyaction(pActtab, i);
  4384. if( action<0 ) action = lemp->noAction;
  4385. if( j==0 ) fprintf(out," /* %5d */ ", i);
  4386. fprintf(out, " %4d,", action);
  4387. if( j==9 || i==n-1 ){
  4388. fprintf(out, "\n"); lineno++;
  4389. j = 0;
  4390. }else{
  4391. j++;
  4392. }
  4393. }
  4394. fprintf(out, "};\n"); lineno++;
  4395. /* Output the yy_lookahead table */
  4396. lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab);
  4397. lemp->tablesize += n*szCodeType;
  4398. fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
  4399. for(i=j=0; i<n; i++){
  4400. int la = acttab_yylookahead(pActtab, i);
  4401. if( la<0 ) la = lemp->nsymbol;
  4402. if( j==0 ) fprintf(out," /* %5d */ ", i);
  4403. fprintf(out, " %4d,", la);
  4404. if( j==9 ){
  4405. fprintf(out, "\n"); lineno++;
  4406. j = 0;
  4407. }else{
  4408. j++;
  4409. }
  4410. }
  4411. /* Add extra entries to the end of the yy_lookahead[] table so that
  4412. ** yy_shift_ofst[]+iToken will always be a valid index into the array,
  4413. ** even for the largest possible value of yy_shift_ofst[] and iToken. */
  4414. nLookAhead = lemp->nterminal + lemp->nactiontab;
  4415. while( i<nLookAhead ){
  4416. if( j==0 ) fprintf(out," /* %5d */ ", i);
  4417. fprintf(out, " %4d,", lemp->nterminal);
  4418. if( j==9 ){
  4419. fprintf(out, "\n"); lineno++;
  4420. j = 0;
  4421. }else{
  4422. j++;
  4423. }
  4424. i++;
  4425. }
  4426. if( j>0 ){ fprintf(out, "\n"); lineno++; }
  4427. fprintf(out, "};\n"); lineno++;
  4428. /* Output the yy_shift_ofst[] table */
  4429. n = lemp->nxstate;
  4430. while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
  4431. fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
  4432. fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
  4433. fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
  4434. fprintf(out, "static const %s yy_shift_ofst[] = {\n",
  4435. minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
  4436. lineno++;
  4437. lemp->tablesize += n*sz;
  4438. for(i=j=0; i<n; i++){
  4439. int ofst;
  4440. stp = lemp->sorted[i];
  4441. ofst = stp->iTknOfst;
  4442. if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
  4443. if( j==0 ) fprintf(out," /* %5d */ ", i);
  4444. fprintf(out, " %4d,", ofst);
  4445. if( j==9 || i==n-1 ){
  4446. fprintf(out, "\n"); lineno++;
  4447. j = 0;
  4448. }else{
  4449. j++;
  4450. }
  4451. }
  4452. fprintf(out, "};\n"); lineno++;
  4453. /* Output the yy_reduce_ofst[] table */
  4454. n = lemp->nxstate;
  4455. while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
  4456. fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
  4457. fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
  4458. fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
  4459. fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
  4460. minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
  4461. lemp->tablesize += n*sz;
  4462. for(i=j=0; i<n; i++){
  4463. int ofst;
  4464. stp = lemp->sorted[i];
  4465. ofst = stp->iNtOfst;
  4466. if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
  4467. if( j==0 ) fprintf(out," /* %5d */ ", i);
  4468. fprintf(out, " %4d,", ofst);
  4469. if( j==9 || i==n-1 ){
  4470. fprintf(out, "\n"); lineno++;
  4471. j = 0;
  4472. }else{
  4473. j++;
  4474. }
  4475. }
  4476. fprintf(out, "};\n"); lineno++;
  4477. /* Output the default action table */
  4478. fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
  4479. n = lemp->nxstate;
  4480. lemp->tablesize += n*szActionType;
  4481. for(i=j=0; i<n; i++){
  4482. stp = lemp->sorted[i];
  4483. if( j==0 ) fprintf(out," /* %5d */ ", i);
  4484. if( stp->iDfltReduce<0 ){
  4485. fprintf(out, " %4d,", lemp->errAction);
  4486. }else{
  4487. fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
  4488. }
  4489. if( j==9 || i==n-1 ){
  4490. fprintf(out, "\n"); lineno++;
  4491. j = 0;
  4492. }else{
  4493. j++;
  4494. }
  4495. }
  4496. fprintf(out, "};\n"); lineno++;
  4497. tplt_xfer(lemp->name,in,out,&lineno);
  4498. /* Generate the table of fallback tokens.
  4499. */
  4500. if( lemp->has_fallback ){
  4501. int mx = lemp->nterminal - 1;
  4502. /* 2019-08-28: Generate fallback entries for every token to avoid
  4503. ** having to do a range check on the index */
  4504. /* while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } */
  4505. lemp->tablesize += (mx+1)*szCodeType;
  4506. for(i=0; i<=mx; i++){
  4507. struct symbol *p = lemp->symbols[i];
  4508. if( p->fallback==0 ){
  4509. fprintf(out, " 0, /* %10s => nothing */\n", p->name);
  4510. }else{
  4511. fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
  4512. p->name, p->fallback->name);
  4513. }
  4514. lineno++;
  4515. }
  4516. }
  4517. tplt_xfer(lemp->name, in, out, &lineno);
  4518. /* Generate a table containing the symbolic name of every symbol
  4519. */
  4520. for(i=0; i<lemp->nsymbol; i++){
  4521. fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++;
  4522. }
  4523. tplt_xfer(lemp->name,in,out,&lineno);
  4524. /* Generate a table containing a text string that describes every
  4525. ** rule in the rule set of the grammar. This information is used
  4526. ** when tracing REDUCE actions.
  4527. */
  4528. for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
  4529. assert( rp->iRule==i );
  4530. fprintf(out," /* %3d */ \"", i);
  4531. writeRuleText(out, rp);
  4532. fprintf(out,"\",\n"); lineno++;
  4533. }
  4534. tplt_xfer(lemp->name,in,out,&lineno);
  4535. /* Generate code which executes every time a symbol is popped from
  4536. ** the stack while processing errors or while destroying the parser.
  4537. ** (In other words, generate the %destructor actions)
  4538. */
  4539. if( lemp->tokendest ){
  4540. int once = 1;
  4541. for(i=0; i<lemp->nsymbol; i++){
  4542. struct symbol *sp = lemp->symbols[i];
  4543. if( sp==0 || sp->type!=TERMINAL ) continue;
  4544. if( once ){
  4545. fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
  4546. once = 0;
  4547. }
  4548. fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
  4549. }
  4550. for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
  4551. if( i<lemp->nsymbol ){
  4552. emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
  4553. fprintf(out," break;\n"); lineno++;
  4554. }
  4555. }
  4556. if( lemp->vardest ){
  4557. struct symbol *dflt_sp = 0;
  4558. int once = 1;
  4559. for(i=0; i<lemp->nsymbol; i++){
  4560. struct symbol *sp = lemp->symbols[i];
  4561. if( sp==0 || sp->type==TERMINAL ||
  4562. sp->index<=0 || sp->destructor!=0 ) continue;
  4563. if( once ){
  4564. fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
  4565. once = 0;
  4566. }
  4567. fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
  4568. dflt_sp = sp;
  4569. }
  4570. if( dflt_sp!=0 ){
  4571. emit_destructor_code(out,dflt_sp,lemp,&lineno);
  4572. }
  4573. fprintf(out," break;\n"); lineno++;
  4574. }
  4575. for(i=0; i<lemp->nsymbol; i++){
  4576. struct symbol *sp = lemp->symbols[i];
  4577. if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
  4578. if( sp->destLineno<0 ) continue; /* Already emitted */
  4579. fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
  4580. /* Combine duplicate destructors into a single case */
  4581. for(j=i+1; j<lemp->nsymbol; j++){
  4582. struct symbol *sp2 = lemp->symbols[j];
  4583. if( sp2 && sp2->type!=TERMINAL && sp2->destructor
  4584. && sp2->dtnum==sp->dtnum
  4585. && strcmp(sp->destructor,sp2->destructor)==0 ){
  4586. fprintf(out," case %d: /* %s */\n",
  4587. sp2->index, sp2->name); lineno++;
  4588. sp2->destLineno = -1; /* Avoid emitting this destructor again */
  4589. }
  4590. }
  4591. emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
  4592. fprintf(out," break;\n"); lineno++;
  4593. }
  4594. tplt_xfer(lemp->name,in,out,&lineno);
  4595. /* Generate code which executes whenever the parser stack overflows */
  4596. tplt_print(out,lemp,lemp->overflow,&lineno);
  4597. tplt_xfer(lemp->name,in,out,&lineno);
  4598. /* Generate the tables of rule information. yyRuleInfoLhs[] and
  4599. ** yyRuleInfoNRhs[].
  4600. **
  4601. ** Note: This code depends on the fact that rules are number
  4602. ** sequentially beginning with 0.
  4603. */
  4604. for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
  4605. fprintf(out," %4d, /* (%d) ", rp->lhs->index, i);
  4606. rule_print(out, rp);
  4607. fprintf(out," */\n"); lineno++;
  4608. }
  4609. tplt_xfer(lemp->name,in,out,&lineno);
  4610. for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
  4611. fprintf(out," %3d, /* (%d) ", -rp->nrhs, i);
  4612. rule_print(out, rp);
  4613. fprintf(out," */\n"); lineno++;
  4614. }
  4615. tplt_xfer(lemp->name,in,out,&lineno);
  4616. /* Generate code which execution during each REDUCE action */
  4617. i = 0;
  4618. for(rp=lemp->rule; rp; rp=rp->next){
  4619. i += translate_code(lemp, rp);
  4620. }
  4621. if( i ){
  4622. fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
  4623. }
  4624. /* First output rules other than the default: rule */
  4625. for(rp=lemp->rule; rp; rp=rp->next){
  4626. struct rule *rp2; /* Other rules with the same action */
  4627. if( rp->codeEmitted ) continue;
  4628. if( rp->noCode ){
  4629. /* No C code actions, so this will be part of the "default:" rule */
  4630. continue;
  4631. }
  4632. fprintf(out," case %d: /* ", rp->iRule);
  4633. writeRuleText(out, rp);
  4634. fprintf(out, " */\n"); lineno++;
  4635. for(rp2=rp->next; rp2; rp2=rp2->next){
  4636. if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
  4637. && rp2->codeSuffix==rp->codeSuffix ){
  4638. fprintf(out," case %d: /* ", rp2->iRule);
  4639. writeRuleText(out, rp2);
  4640. fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
  4641. rp2->codeEmitted = 1;
  4642. }
  4643. }
  4644. emit_code(out,rp,lemp,&lineno);
  4645. fprintf(out," break;\n"); lineno++;
  4646. rp->codeEmitted = 1;
  4647. }
  4648. /* Finally, output the default: rule. We choose as the default: all
  4649. ** empty actions. */
  4650. fprintf(out," default:\n"); lineno++;
  4651. for(rp=lemp->rule; rp; rp=rp->next){
  4652. if( rp->codeEmitted ) continue;
  4653. assert( rp->noCode );
  4654. fprintf(out," /* (%d) ", rp->iRule);
  4655. writeRuleText(out, rp);
  4656. if( rp->neverReduce ){
  4657. fprintf(out, " (NEVER REDUCES) */ assert(yyruleno!=%d);\n",
  4658. rp->iRule); lineno++;
  4659. }else if( rp->doesReduce ){
  4660. fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
  4661. }else{
  4662. fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
  4663. rp->iRule); lineno++;
  4664. }
  4665. }
  4666. fprintf(out," break;\n"); lineno++;
  4667. tplt_xfer(lemp->name,in,out,&lineno);
  4668. /* Generate code which executes if a parse fails */
  4669. tplt_print(out,lemp,lemp->failure,&lineno);
  4670. tplt_xfer(lemp->name,in,out,&lineno);
  4671. /* Generate code which executes when a syntax error occurs */
  4672. tplt_print(out,lemp,lemp->error,&lineno);
  4673. tplt_xfer(lemp->name,in,out,&lineno);
  4674. /* Generate code which executes when the parser accepts its input */
  4675. tplt_print(out,lemp,lemp->accept,&lineno);
  4676. tplt_xfer(lemp->name,in,out,&lineno);
  4677. /* Append any addition code the user desires */
  4678. tplt_print(out,lemp,lemp->extracode,&lineno);
  4679. acttab_free(pActtab);
  4680. fclose(in);
  4681. fclose(out);
  4682. if( sql ) fclose(sql);
  4683. return;
  4684. }
  4685. /* Generate a header file for the parser */
  4686. void ReportHeader(struct lemon *lemp)
  4687. {
  4688. FILE *out, *in;
  4689. const char *prefix;
  4690. char line[LINESIZE];
  4691. char pattern[LINESIZE];
  4692. int i;
  4693. if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
  4694. else prefix = "";
  4695. in = file_open(lemp,".h","rb");
  4696. if( in ){
  4697. int nextChar;
  4698. for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
  4699. lemon_sprintf(pattern,"#define %s%-30s %3d\n",
  4700. prefix,lemp->symbols[i]->name,i);
  4701. if( strcmp(line,pattern) ) break;
  4702. }
  4703. nextChar = fgetc(in);
  4704. fclose(in);
  4705. if( i==lemp->nterminal && nextChar==EOF ){
  4706. /* No change in the file. Don't rewrite it. */
  4707. return;
  4708. }
  4709. }
  4710. out = file_open(lemp,".h","wb");
  4711. if( out ){
  4712. for(i=1; i<lemp->nterminal; i++){
  4713. fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
  4714. }
  4715. fclose(out);
  4716. }
  4717. return;
  4718. }
  4719. /* Reduce the size of the action tables, if possible, by making use
  4720. ** of defaults.
  4721. **
  4722. ** In this version, we take the most frequent REDUCE action and make
  4723. ** it the default. Except, there is no default if the wildcard token
  4724. ** is a possible look-ahead.
  4725. */
  4726. void CompressTables(struct lemon *lemp)
  4727. {
  4728. struct state *stp;
  4729. struct action *ap, *ap2, *nextap;
  4730. struct rule *rp, *rp2, *rbest;
  4731. int nbest, n;
  4732. int i;
  4733. int usesWildcard;
  4734. for(i=0; i<lemp->nstate; i++){
  4735. stp = lemp->sorted[i];
  4736. nbest = 0;
  4737. rbest = 0;
  4738. usesWildcard = 0;
  4739. for(ap=stp->ap; ap; ap=ap->next){
  4740. if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
  4741. usesWildcard = 1;
  4742. }
  4743. if( ap->type!=REDUCE ) continue;
  4744. rp = ap->x.rp;
  4745. if( rp->lhsStart ) continue;
  4746. if( rp==rbest ) continue;
  4747. n = 1;
  4748. for(ap2=ap->next; ap2; ap2=ap2->next){
  4749. if( ap2->type!=REDUCE ) continue;
  4750. rp2 = ap2->x.rp;
  4751. if( rp2==rbest ) continue;
  4752. if( rp2==rp ) n++;
  4753. }
  4754. if( n>nbest ){
  4755. nbest = n;
  4756. rbest = rp;
  4757. }
  4758. }
  4759. /* Do not make a default if the number of rules to default
  4760. ** is not at least 1 or if the wildcard token is a possible
  4761. ** lookahead.
  4762. */
  4763. if( nbest<1 || usesWildcard ) continue;
  4764. /* Combine matching REDUCE actions into a single default */
  4765. for(ap=stp->ap; ap; ap=ap->next){
  4766. if( ap->type==REDUCE && ap->x.rp==rbest ) break;
  4767. }
  4768. assert( ap );
  4769. ap->sp = Symbol_new("{default}");
  4770. for(ap=ap->next; ap; ap=ap->next){
  4771. if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
  4772. }
  4773. stp->ap = Action_sort(stp->ap);
  4774. for(ap=stp->ap; ap; ap=ap->next){
  4775. if( ap->type==SHIFT ) break;
  4776. if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
  4777. }
  4778. if( ap==0 ){
  4779. stp->autoReduce = 1;
  4780. stp->pDfltReduce = rbest;
  4781. }
  4782. }
  4783. /* Make a second pass over all states and actions. Convert
  4784. ** every action that is a SHIFT to an autoReduce state into
  4785. ** a SHIFTREDUCE action.
  4786. */
  4787. for(i=0; i<lemp->nstate; i++){
  4788. stp = lemp->sorted[i];
  4789. for(ap=stp->ap; ap; ap=ap->next){
  4790. struct state *pNextState;
  4791. if( ap->type!=SHIFT ) continue;
  4792. pNextState = ap->x.stp;
  4793. if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
  4794. ap->type = SHIFTREDUCE;
  4795. ap->x.rp = pNextState->pDfltReduce;
  4796. }
  4797. }
  4798. }
  4799. /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
  4800. ** (meaning that the SHIFTREDUCE will land back in the state where it
  4801. ** started) and if there is no C-code associated with the reduce action,
  4802. ** then we can go ahead and convert the action to be the same as the
  4803. ** action for the RHS of the rule.
  4804. */
  4805. for(i=0; i<lemp->nstate; i++){
  4806. stp = lemp->sorted[i];
  4807. for(ap=stp->ap; ap; ap=nextap){
  4808. nextap = ap->next;
  4809. if( ap->type!=SHIFTREDUCE ) continue;
  4810. rp = ap->x.rp;
  4811. if( rp->noCode==0 ) continue;
  4812. if( rp->nrhs!=1 ) continue;
  4813. #if 1
  4814. /* Only apply this optimization to non-terminals. It would be OK to
  4815. ** apply it to terminal symbols too, but that makes the parser tables
  4816. ** larger. */
  4817. if( ap->sp->index<lemp->nterminal ) continue;
  4818. #endif
  4819. /* If we reach this point, it means the optimization can be applied */
  4820. nextap = ap;
  4821. for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
  4822. assert( ap2!=0 );
  4823. ap->spOpt = ap2->sp;
  4824. ap->type = ap2->type;
  4825. ap->x = ap2->x;
  4826. }
  4827. }
  4828. }
  4829. /*
  4830. ** Compare two states for sorting purposes. The smaller state is the
  4831. ** one with the most non-terminal actions. If they have the same number
  4832. ** of non-terminal actions, then the smaller is the one with the most
  4833. ** token actions.
  4834. */
  4835. static int stateResortCompare(const void *a, const void *b){
  4836. const struct state *pA = *(const struct state**)a;
  4837. const struct state *pB = *(const struct state**)b;
  4838. int n;
  4839. n = pB->nNtAct - pA->nNtAct;
  4840. if( n==0 ){
  4841. n = pB->nTknAct - pA->nTknAct;
  4842. if( n==0 ){
  4843. n = pB->statenum - pA->statenum;
  4844. }
  4845. }
  4846. assert( n!=0 );
  4847. return n;
  4848. }
  4849. /*
  4850. ** Renumber and resort states so that states with fewer choices
  4851. ** occur at the end. Except, keep state 0 as the first state.
  4852. */
  4853. void ResortStates(struct lemon *lemp)
  4854. {
  4855. int i;
  4856. struct state *stp;
  4857. struct action *ap;
  4858. for(i=0; i<lemp->nstate; i++){
  4859. stp = lemp->sorted[i];
  4860. stp->nTknAct = stp->nNtAct = 0;
  4861. stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */
  4862. stp->iTknOfst = NO_OFFSET;
  4863. stp->iNtOfst = NO_OFFSET;
  4864. for(ap=stp->ap; ap; ap=ap->next){
  4865. int iAction = compute_action(lemp,ap);
  4866. if( iAction>=0 ){
  4867. if( ap->sp->index<lemp->nterminal ){
  4868. stp->nTknAct++;
  4869. }else if( ap->sp->index<lemp->nsymbol ){
  4870. stp->nNtAct++;
  4871. }else{
  4872. assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
  4873. stp->iDfltReduce = iAction;
  4874. }
  4875. }
  4876. }
  4877. }
  4878. qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
  4879. stateResortCompare);
  4880. for(i=0; i<lemp->nstate; i++){
  4881. lemp->sorted[i]->statenum = i;
  4882. }
  4883. lemp->nxstate = lemp->nstate;
  4884. while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
  4885. lemp->nxstate--;
  4886. }
  4887. }
  4888. /***************** From the file "set.c" ************************************/
  4889. /*
  4890. ** Set manipulation routines for the LEMON parser generator.
  4891. */
  4892. static int size = 0;
  4893. /* Set the set size */
  4894. void SetSize(int n)
  4895. {
  4896. size = n+1;
  4897. }
  4898. /* Allocate a new set */
  4899. char *SetNew(void){
  4900. char *s;
  4901. s = (char*)calloc( size, 1);
  4902. if( s==0 ){
  4903. memory_error();
  4904. }
  4905. return s;
  4906. }
  4907. /* Deallocate a set */
  4908. void SetFree(char *s)
  4909. {
  4910. free(s);
  4911. }
  4912. /* Add a new element to the set. Return TRUE if the element was added
  4913. ** and FALSE if it was already there. */
  4914. int SetAdd(char *s, int e)
  4915. {
  4916. int rv;
  4917. assert( e>=0 && e<size );
  4918. rv = s[e];
  4919. s[e] = 1;
  4920. return !rv;
  4921. }
  4922. /* Add every element of s2 to s1. Return TRUE if s1 changes. */
  4923. int SetUnion(char *s1, char *s2)
  4924. {
  4925. int i, progress;
  4926. progress = 0;
  4927. for(i=0; i<size; i++){
  4928. if( s2[i]==0 ) continue;
  4929. if( s1[i]==0 ){
  4930. progress = 1;
  4931. s1[i] = 1;
  4932. }
  4933. }
  4934. return progress;
  4935. }
  4936. /********************** From the file "table.c" ****************************/
  4937. /*
  4938. ** All code in this file has been automatically generated
  4939. ** from a specification in the file
  4940. ** "table.q"
  4941. ** by the associative array code building program "aagen".
  4942. ** Do not edit this file! Instead, edit the specification
  4943. ** file, then rerun aagen.
  4944. */
  4945. /*
  4946. ** Code for processing tables in the LEMON parser generator.
  4947. */
  4948. PRIVATE unsigned strhash(const char *x)
  4949. {
  4950. unsigned h = 0;
  4951. while( *x ) h = h*13 + *(x++);
  4952. return h;
  4953. }
  4954. /* Works like strdup, sort of. Save a string in malloced memory, but
  4955. ** keep strings in a table so that the same string is not in more
  4956. ** than one place.
  4957. */
  4958. const char *Strsafe(const char *y)
  4959. {
  4960. const char *z;
  4961. char *cpy;
  4962. if( y==0 ) return 0;
  4963. z = Strsafe_find(y);
  4964. if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
  4965. lemon_strcpy(cpy,y);
  4966. z = cpy;
  4967. Strsafe_insert(z);
  4968. }
  4969. MemoryCheck(z);
  4970. return z;
  4971. }
  4972. /* There is one instance of the following structure for each
  4973. ** associative array of type "x1".
  4974. */
  4975. struct s_x1 {
  4976. int size; /* The number of available slots. */
  4977. /* Must be a power of 2 greater than or */
  4978. /* equal to 1 */
  4979. int count; /* Number of currently slots filled */
  4980. struct s_x1node *tbl; /* The data stored here */
  4981. struct s_x1node **ht; /* Hash table for lookups */
  4982. };
  4983. /* There is one instance of this structure for every data element
  4984. ** in an associative array of type "x1".
  4985. */
  4986. typedef struct s_x1node {
  4987. const char *data; /* The data */
  4988. struct s_x1node *next; /* Next entry with the same hash */
  4989. struct s_x1node **from; /* Previous link */
  4990. } x1node;
  4991. /* There is only one instance of the array, which is the following */
  4992. static struct s_x1 *x1a;
  4993. /* Allocate a new associative array */
  4994. void Strsafe_init(void){
  4995. if( x1a ) return;
  4996. x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
  4997. if( x1a ){
  4998. x1a->size = 1024;
  4999. x1a->count = 0;
  5000. x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
  5001. if( x1a->tbl==0 ){
  5002. free(x1a);
  5003. x1a = 0;
  5004. }else{
  5005. int i;
  5006. x1a->ht = (x1node**)&(x1a->tbl[1024]);
  5007. for(i=0; i<1024; i++) x1a->ht[i] = 0;
  5008. }
  5009. }
  5010. }
  5011. /* Insert a new record into the array. Return TRUE if successful.
  5012. ** Prior data with the same key is NOT overwritten */
  5013. int Strsafe_insert(const char *data)
  5014. {
  5015. x1node *np;
  5016. unsigned h;
  5017. unsigned ph;
  5018. if( x1a==0 ) return 0;
  5019. ph = strhash(data);
  5020. h = ph & (x1a->size-1);
  5021. np = x1a->ht[h];
  5022. while( np ){
  5023. if( strcmp(np->data,data)==0 ){
  5024. /* An existing entry with the same key is found. */
  5025. /* Fail because overwrite is not allows. */
  5026. return 0;
  5027. }
  5028. np = np->next;
  5029. }
  5030. if( x1a->count>=x1a->size ){
  5031. /* Need to make the hash table bigger */
  5032. int i,arrSize;
  5033. struct s_x1 array;
  5034. array.size = arrSize = x1a->size*2;
  5035. array.count = x1a->count;
  5036. array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
  5037. if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
  5038. array.ht = (x1node**)&(array.tbl[arrSize]);
  5039. for(i=0; i<arrSize; i++) array.ht[i] = 0;
  5040. for(i=0; i<x1a->count; i++){
  5041. x1node *oldnp, *newnp;
  5042. oldnp = &(x1a->tbl[i]);
  5043. h = strhash(oldnp->data) & (arrSize-1);
  5044. newnp = &(array.tbl[i]);
  5045. if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
  5046. newnp->next = array.ht[h];
  5047. newnp->data = oldnp->data;
  5048. newnp->from = &(array.ht[h]);
  5049. array.ht[h] = newnp;
  5050. }
  5051. /* free(x1a->tbl); // This program was originally for 16-bit machines.
  5052. ** Don't worry about freeing memory on modern platforms. */
  5053. *x1a = array;
  5054. }
  5055. /* Insert the new data */
  5056. h = ph & (x1a->size-1);
  5057. np = &(x1a->tbl[x1a->count++]);
  5058. np->data = data;
  5059. if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
  5060. np->next = x1a->ht[h];
  5061. x1a->ht[h] = np;
  5062. np->from = &(x1a->ht[h]);
  5063. return 1;
  5064. }
  5065. /* Return a pointer to data assigned to the given key. Return NULL
  5066. ** if no such key. */
  5067. const char *Strsafe_find(const char *key)
  5068. {
  5069. unsigned h;
  5070. x1node *np;
  5071. if( x1a==0 ) return 0;
  5072. h = strhash(key) & (x1a->size-1);
  5073. np = x1a->ht[h];
  5074. while( np ){
  5075. if( strcmp(np->data,key)==0 ) break;
  5076. np = np->next;
  5077. }
  5078. return np ? np->data : 0;
  5079. }
  5080. /* Return a pointer to the (terminal or nonterminal) symbol "x".
  5081. ** Create a new symbol if this is the first time "x" has been seen.
  5082. */
  5083. struct symbol *Symbol_new(const char *x)
  5084. {
  5085. struct symbol *sp;
  5086. sp = Symbol_find(x);
  5087. if( sp==0 ){
  5088. sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
  5089. MemoryCheck(sp);
  5090. sp->name = Strsafe(x);
  5091. sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
  5092. sp->rule = 0;
  5093. sp->fallback = 0;
  5094. sp->prec = -1;
  5095. sp->assoc = UNK;
  5096. sp->firstset = 0;
  5097. sp->lambda = LEMON_FALSE;
  5098. sp->destructor = 0;
  5099. sp->destLineno = 0;
  5100. sp->datatype = 0;
  5101. sp->useCnt = 0;
  5102. Symbol_insert(sp,sp->name);
  5103. }
  5104. sp->useCnt++;
  5105. return sp;
  5106. }
  5107. /* Compare two symbols for sorting purposes. Return negative,
  5108. ** zero, or positive if a is less then, equal to, or greater
  5109. ** than b.
  5110. **
  5111. ** Symbols that begin with upper case letters (terminals or tokens)
  5112. ** must sort before symbols that begin with lower case letters
  5113. ** (non-terminals). And MULTITERMINAL symbols (created using the
  5114. ** %token_class directive) must sort at the very end. Other than
  5115. ** that, the order does not matter.
  5116. **
  5117. ** We find experimentally that leaving the symbols in their original
  5118. ** order (the order they appeared in the grammar file) gives the
  5119. ** smallest parser tables in SQLite.
  5120. */
  5121. int Symbolcmpp(const void *_a, const void *_b)
  5122. {
  5123. const struct symbol *a = *(const struct symbol **) _a;
  5124. const struct symbol *b = *(const struct symbol **) _b;
  5125. int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
  5126. int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
  5127. return i1==i2 ? a->index - b->index : i1 - i2;
  5128. }
  5129. /* There is one instance of the following structure for each
  5130. ** associative array of type "x2".
  5131. */
  5132. struct s_x2 {
  5133. int size; /* The number of available slots. */
  5134. /* Must be a power of 2 greater than or */
  5135. /* equal to 1 */
  5136. int count; /* Number of currently slots filled */
  5137. struct s_x2node *tbl; /* The data stored here */
  5138. struct s_x2node **ht; /* Hash table for lookups */
  5139. };
  5140. /* There is one instance of this structure for every data element
  5141. ** in an associative array of type "x2".
  5142. */
  5143. typedef struct s_x2node {
  5144. struct symbol *data; /* The data */
  5145. const char *key; /* The key */
  5146. struct s_x2node *next; /* Next entry with the same hash */
  5147. struct s_x2node **from; /* Previous link */
  5148. } x2node;
  5149. /* There is only one instance of the array, which is the following */
  5150. static struct s_x2 *x2a;
  5151. /* Allocate a new associative array */
  5152. void Symbol_init(void){
  5153. if( x2a ) return;
  5154. x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
  5155. if( x2a ){
  5156. x2a->size = 128;
  5157. x2a->count = 0;
  5158. x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
  5159. if( x2a->tbl==0 ){
  5160. free(x2a);
  5161. x2a = 0;
  5162. }else{
  5163. int i;
  5164. x2a->ht = (x2node**)&(x2a->tbl[128]);
  5165. for(i=0; i<128; i++) x2a->ht[i] = 0;
  5166. }
  5167. }
  5168. }
  5169. /* Insert a new record into the array. Return TRUE if successful.
  5170. ** Prior data with the same key is NOT overwritten */
  5171. int Symbol_insert(struct symbol *data, const char *key)
  5172. {
  5173. x2node *np;
  5174. unsigned h;
  5175. unsigned ph;
  5176. if( x2a==0 ) return 0;
  5177. ph = strhash(key);
  5178. h = ph & (x2a->size-1);
  5179. np = x2a->ht[h];
  5180. while( np ){
  5181. if( strcmp(np->key,key)==0 ){
  5182. /* An existing entry with the same key is found. */
  5183. /* Fail because overwrite is not allows. */
  5184. return 0;
  5185. }
  5186. np = np->next;
  5187. }
  5188. if( x2a->count>=x2a->size ){
  5189. /* Need to make the hash table bigger */
  5190. int i,arrSize;
  5191. struct s_x2 array;
  5192. array.size = arrSize = x2a->size*2;
  5193. array.count = x2a->count;
  5194. array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
  5195. if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
  5196. array.ht = (x2node**)&(array.tbl[arrSize]);
  5197. for(i=0; i<arrSize; i++) array.ht[i] = 0;
  5198. for(i=0; i<x2a->count; i++){
  5199. x2node *oldnp, *newnp;
  5200. oldnp = &(x2a->tbl[i]);
  5201. h = strhash(oldnp->key) & (arrSize-1);
  5202. newnp = &(array.tbl[i]);
  5203. if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
  5204. newnp->next = array.ht[h];
  5205. newnp->key = oldnp->key;
  5206. newnp->data = oldnp->data;
  5207. newnp->from = &(array.ht[h]);
  5208. array.ht[h] = newnp;
  5209. }
  5210. /* free(x2a->tbl); // This program was originally written for 16-bit
  5211. ** machines. Don't worry about freeing this trivial amount of memory
  5212. ** on modern platforms. Just leak it. */
  5213. *x2a = array;
  5214. }
  5215. /* Insert the new data */
  5216. h = ph & (x2a->size-1);
  5217. np = &(x2a->tbl[x2a->count++]);
  5218. np->key = key;
  5219. np->data = data;
  5220. if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
  5221. np->next = x2a->ht[h];
  5222. x2a->ht[h] = np;
  5223. np->from = &(x2a->ht[h]);
  5224. return 1;
  5225. }
  5226. /* Return a pointer to data assigned to the given key. Return NULL
  5227. ** if no such key. */
  5228. struct symbol *Symbol_find(const char *key)
  5229. {
  5230. unsigned h;
  5231. x2node *np;
  5232. if( x2a==0 ) return 0;
  5233. h = strhash(key) & (x2a->size-1);
  5234. np = x2a->ht[h];
  5235. while( np ){
  5236. if( strcmp(np->key,key)==0 ) break;
  5237. np = np->next;
  5238. }
  5239. return np ? np->data : 0;
  5240. }
  5241. /* Return the n-th data. Return NULL if n is out of range. */
  5242. struct symbol *Symbol_Nth(int n)
  5243. {
  5244. struct symbol *data;
  5245. if( x2a && n>0 && n<=x2a->count ){
  5246. data = x2a->tbl[n-1].data;
  5247. }else{
  5248. data = 0;
  5249. }
  5250. return data;
  5251. }
  5252. /* Return the size of the array */
  5253. int Symbol_count()
  5254. {
  5255. return x2a ? x2a->count : 0;
  5256. }
  5257. /* Return an array of pointers to all data in the table.
  5258. ** The array is obtained from malloc. Return NULL if memory allocation
  5259. ** problems, or if the array is empty. */
  5260. struct symbol **Symbol_arrayof()
  5261. {
  5262. struct symbol **array;
  5263. int i,arrSize;
  5264. if( x2a==0 ) return 0;
  5265. arrSize = x2a->count;
  5266. array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
  5267. if( array ){
  5268. for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
  5269. }
  5270. return array;
  5271. }
  5272. /* Compare two configurations */
  5273. int Configcmp(const char *_a,const char *_b)
  5274. {
  5275. const struct config *a = (struct config *) _a;
  5276. const struct config *b = (struct config *) _b;
  5277. int x;
  5278. x = a->rp->index - b->rp->index;
  5279. if( x==0 ) x = a->dot - b->dot;
  5280. return x;
  5281. }
  5282. /* Compare two states */
  5283. PRIVATE int statecmp(struct config *a, struct config *b)
  5284. {
  5285. int rc;
  5286. for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
  5287. rc = a->rp->index - b->rp->index;
  5288. if( rc==0 ) rc = a->dot - b->dot;
  5289. }
  5290. if( rc==0 ){
  5291. if( a ) rc = 1;
  5292. if( b ) rc = -1;
  5293. }
  5294. return rc;
  5295. }
  5296. /* Hash a state */
  5297. PRIVATE unsigned statehash(struct config *a)
  5298. {
  5299. unsigned h=0;
  5300. while( a ){
  5301. h = h*571 + a->rp->index*37 + a->dot;
  5302. a = a->bp;
  5303. }
  5304. return h;
  5305. }
  5306. /* Allocate a new state structure */
  5307. struct state *State_new()
  5308. {
  5309. struct state *newstate;
  5310. newstate = (struct state *)calloc(1, sizeof(struct state) );
  5311. MemoryCheck(newstate);
  5312. return newstate;
  5313. }
  5314. /* There is one instance of the following structure for each
  5315. ** associative array of type "x3".
  5316. */
  5317. struct s_x3 {
  5318. int size; /* The number of available slots. */
  5319. /* Must be a power of 2 greater than or */
  5320. /* equal to 1 */
  5321. int count; /* Number of currently slots filled */
  5322. struct s_x3node *tbl; /* The data stored here */
  5323. struct s_x3node **ht; /* Hash table for lookups */
  5324. };
  5325. /* There is one instance of this structure for every data element
  5326. ** in an associative array of type "x3".
  5327. */
  5328. typedef struct s_x3node {
  5329. struct state *data; /* The data */
  5330. struct config *key; /* The key */
  5331. struct s_x3node *next; /* Next entry with the same hash */
  5332. struct s_x3node **from; /* Previous link */
  5333. } x3node;
  5334. /* There is only one instance of the array, which is the following */
  5335. static struct s_x3 *x3a;
  5336. /* Allocate a new associative array */
  5337. void State_init(void){
  5338. if( x3a ) return;
  5339. x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
  5340. if( x3a ){
  5341. x3a->size = 128;
  5342. x3a->count = 0;
  5343. x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
  5344. if( x3a->tbl==0 ){
  5345. free(x3a);
  5346. x3a = 0;
  5347. }else{
  5348. int i;
  5349. x3a->ht = (x3node**)&(x3a->tbl[128]);
  5350. for(i=0; i<128; i++) x3a->ht[i] = 0;
  5351. }
  5352. }
  5353. }
  5354. /* Insert a new record into the array. Return TRUE if successful.
  5355. ** Prior data with the same key is NOT overwritten */
  5356. int State_insert(struct state *data, struct config *key)
  5357. {
  5358. x3node *np;
  5359. unsigned h;
  5360. unsigned ph;
  5361. if( x3a==0 ) return 0;
  5362. ph = statehash(key);
  5363. h = ph & (x3a->size-1);
  5364. np = x3a->ht[h];
  5365. while( np ){
  5366. if( statecmp(np->key,key)==0 ){
  5367. /* An existing entry with the same key is found. */
  5368. /* Fail because overwrite is not allows. */
  5369. return 0;
  5370. }
  5371. np = np->next;
  5372. }
  5373. if( x3a->count>=x3a->size ){
  5374. /* Need to make the hash table bigger */
  5375. int i,arrSize;
  5376. struct s_x3 array;
  5377. array.size = arrSize = x3a->size*2;
  5378. array.count = x3a->count;
  5379. array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
  5380. if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
  5381. array.ht = (x3node**)&(array.tbl[arrSize]);
  5382. for(i=0; i<arrSize; i++) array.ht[i] = 0;
  5383. for(i=0; i<x3a->count; i++){
  5384. x3node *oldnp, *newnp;
  5385. oldnp = &(x3a->tbl[i]);
  5386. h = statehash(oldnp->key) & (arrSize-1);
  5387. newnp = &(array.tbl[i]);
  5388. if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
  5389. newnp->next = array.ht[h];
  5390. newnp->key = oldnp->key;
  5391. newnp->data = oldnp->data;
  5392. newnp->from = &(array.ht[h]);
  5393. array.ht[h] = newnp;
  5394. }
  5395. free(x3a->tbl);
  5396. *x3a = array;
  5397. }
  5398. /* Insert the new data */
  5399. h = ph & (x3a->size-1);
  5400. np = &(x3a->tbl[x3a->count++]);
  5401. np->key = key;
  5402. np->data = data;
  5403. if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
  5404. np->next = x3a->ht[h];
  5405. x3a->ht[h] = np;
  5406. np->from = &(x3a->ht[h]);
  5407. return 1;
  5408. }
  5409. /* Return a pointer to data assigned to the given key. Return NULL
  5410. ** if no such key. */
  5411. struct state *State_find(struct config *key)
  5412. {
  5413. unsigned h;
  5414. x3node *np;
  5415. if( x3a==0 ) return 0;
  5416. h = statehash(key) & (x3a->size-1);
  5417. np = x3a->ht[h];
  5418. while( np ){
  5419. if( statecmp(np->key,key)==0 ) break;
  5420. np = np->next;
  5421. }
  5422. return np ? np->data : 0;
  5423. }
  5424. /* Return an array of pointers to all data in the table.
  5425. ** The array is obtained from malloc. Return NULL if memory allocation
  5426. ** problems, or if the array is empty. */
  5427. struct state **State_arrayof(void)
  5428. {
  5429. struct state **array;
  5430. int i,arrSize;
  5431. if( x3a==0 ) return 0;
  5432. arrSize = x3a->count;
  5433. array = (struct state **)calloc(arrSize, sizeof(struct state *));
  5434. if( array ){
  5435. for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
  5436. }
  5437. return array;
  5438. }
  5439. /* Hash a configuration */
  5440. PRIVATE unsigned confighash(struct config *a)
  5441. {
  5442. unsigned h=0;
  5443. h = h*571 + a->rp->index*37 + a->dot;
  5444. return h;
  5445. }
  5446. /* There is one instance of the following structure for each
  5447. ** associative array of type "x4".
  5448. */
  5449. struct s_x4 {
  5450. int size; /* The number of available slots. */
  5451. /* Must be a power of 2 greater than or */
  5452. /* equal to 1 */
  5453. int count; /* Number of currently slots filled */
  5454. struct s_x4node *tbl; /* The data stored here */
  5455. struct s_x4node **ht; /* Hash table for lookups */
  5456. };
  5457. /* There is one instance of this structure for every data element
  5458. ** in an associative array of type "x4".
  5459. */
  5460. typedef struct s_x4node {
  5461. struct config *data; /* The data */
  5462. struct s_x4node *next; /* Next entry with the same hash */
  5463. struct s_x4node **from; /* Previous link */
  5464. } x4node;
  5465. /* There is only one instance of the array, which is the following */
  5466. static struct s_x4 *x4a;
  5467. /* Allocate a new associative array */
  5468. void Configtable_init(void){
  5469. if( x4a ) return;
  5470. x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
  5471. if( x4a ){
  5472. x4a->size = 64;
  5473. x4a->count = 0;
  5474. x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
  5475. if( x4a->tbl==0 ){
  5476. free(x4a);
  5477. x4a = 0;
  5478. }else{
  5479. int i;
  5480. x4a->ht = (x4node**)&(x4a->tbl[64]);
  5481. for(i=0; i<64; i++) x4a->ht[i] = 0;
  5482. }
  5483. }
  5484. }
  5485. /* Insert a new record into the array. Return TRUE if successful.
  5486. ** Prior data with the same key is NOT overwritten */
  5487. int Configtable_insert(struct config *data)
  5488. {
  5489. x4node *np;
  5490. unsigned h;
  5491. unsigned ph;
  5492. if( x4a==0 ) return 0;
  5493. ph = confighash(data);
  5494. h = ph & (x4a->size-1);
  5495. np = x4a->ht[h];
  5496. while( np ){
  5497. if( Configcmp((const char *) np->data,(const char *) data)==0 ){
  5498. /* An existing entry with the same key is found. */
  5499. /* Fail because overwrite is not allows. */
  5500. return 0;
  5501. }
  5502. np = np->next;
  5503. }
  5504. if( x4a->count>=x4a->size ){
  5505. /* Need to make the hash table bigger */
  5506. int i,arrSize;
  5507. struct s_x4 array;
  5508. array.size = arrSize = x4a->size*2;
  5509. array.count = x4a->count;
  5510. array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
  5511. if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
  5512. array.ht = (x4node**)&(array.tbl[arrSize]);
  5513. for(i=0; i<arrSize; i++) array.ht[i] = 0;
  5514. for(i=0; i<x4a->count; i++){
  5515. x4node *oldnp, *newnp;
  5516. oldnp = &(x4a->tbl[i]);
  5517. h = confighash(oldnp->data) & (arrSize-1);
  5518. newnp = &(array.tbl[i]);
  5519. if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
  5520. newnp->next = array.ht[h];
  5521. newnp->data = oldnp->data;
  5522. newnp->from = &(array.ht[h]);
  5523. array.ht[h] = newnp;
  5524. }
  5525. /* free(x4a->tbl); // This code was originall written for 16-bit machines.
  5526. ** on modern machines, don't worry about freeing this trival amount of
  5527. ** memory. */
  5528. *x4a = array;
  5529. }
  5530. /* Insert the new data */
  5531. h = ph & (x4a->size-1);
  5532. np = &(x4a->tbl[x4a->count++]);
  5533. np->data = data;
  5534. if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
  5535. np->next = x4a->ht[h];
  5536. x4a->ht[h] = np;
  5537. np->from = &(x4a->ht[h]);
  5538. return 1;
  5539. }
  5540. /* Return a pointer to data assigned to the given key. Return NULL
  5541. ** if no such key. */
  5542. struct config *Configtable_find(struct config *key)
  5543. {
  5544. int h;
  5545. x4node *np;
  5546. if( x4a==0 ) return 0;
  5547. h = confighash(key) & (x4a->size-1);
  5548. np = x4a->ht[h];
  5549. while( np ){
  5550. if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
  5551. np = np->next;
  5552. }
  5553. return np ? np->data : 0;
  5554. }
  5555. /* Remove all data from the table. Pass each data to the function "f"
  5556. ** as it is removed. ("f" may be null to avoid this step.) */
  5557. void Configtable_clear(int(*f)(struct config *))
  5558. {
  5559. int i;
  5560. if( x4a==0 || x4a->count==0 ) return;
  5561. if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
  5562. for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
  5563. x4a->count = 0;
  5564. return;
  5565. }