1
0

lemon.c 144 KB

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