boot-9.scm 169 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791
  1. ;;; -*- mode: scheme; coding: utf-8; -*-
  2. ;;;; Copyright (C) 1995-2014, 2016-2025 Free Software Foundation, Inc.
  3. ;;;;
  4. ;;;; This library is free software; you can redistribute it and/or
  5. ;;;; modify it under the terms of the GNU Lesser General Public
  6. ;;;; License as published by the Free Software Foundation; either
  7. ;;;; version 3 of the License, or (at your option) any later version.
  8. ;;;;
  9. ;;;; This library is distributed in the hope that it will be useful,
  10. ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. ;;;; Lesser General Public License for more details.
  13. ;;;;
  14. ;;;; You should have received a copy of the GNU Lesser General Public
  15. ;;;; License along with this library; if not, write to the Free Software
  16. ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. ;;;;
  18. ;;; Commentary:
  19. ;;; This file is the first thing loaded into Guile. It adds many mundane
  20. ;;; definitions and a few that are interesting.
  21. ;;;
  22. ;;; The module system (hence the hierarchical namespace) are defined in this
  23. ;;; file.
  24. ;;;
  25. ;;; Code:
  26. ;; Before compiling, make sure any symbols are resolved in the (guile)
  27. ;; module, the primary location of those symbols, rather than in
  28. ;; (guile-user), the default module that we compile in.
  29. (eval-when (compile)
  30. (set-current-module (resolve-module '(guile))))
  31. ;; Prevent this file being loaded more than once in a session. Just
  32. ;; doesn't make sense!
  33. (if (current-module)
  34. (error "re-loading ice-9/boot-9.scm not allowed"))
  35. ;;; {Language primitives}
  36. ;;;
  37. ;; These are are the procedural wrappers around the primitives of
  38. ;; Guile's language: apply, call-with-current-continuation, etc.
  39. ;;
  40. ;; Usually, a call to a primitive is compiled specially. The compiler
  41. ;; knows about all these kinds of expressions. But the primitives may
  42. ;; be referenced not only as operators, but as values as well. These
  43. ;; stub procedures are the "values" of apply, dynamic-wind, and other
  44. ;; such primitives.
  45. ;;
  46. (define apply
  47. (case-lambda
  48. ((fun args)
  49. ((@@ primitive apply) fun args))
  50. ((fun arg1 . args)
  51. (letrec ((append* (lambda (tail)
  52. (let ((tail (car tail))
  53. (tail* (cdr tail)))
  54. (if (null? tail*)
  55. tail
  56. (cons tail (append* tail*)))))))
  57. (apply fun (cons arg1 (append* args)))))))
  58. (define (call-with-current-continuation proc)
  59. ((@@ primitive call-with-current-continuation) proc))
  60. (define (call-with-values producer consumer)
  61. ((@@ primitive call-with-values) producer consumer))
  62. (define (dynamic-wind in thunk out)
  63. "All three arguments must be 0-argument procedures.
  64. Guard @var{in} is called, then @var{thunk}, then
  65. guard @var{out}.
  66. If, any time during the execution of @var{thunk}, the
  67. continuation of the @code{dynamic_wind} expression is escaped
  68. non-locally, @var{out} is called. If the continuation of
  69. the dynamic-wind is re-entered, @var{in} is called. Thus
  70. @var{in} and @var{out} may be called any number of
  71. times.
  72. @lisp
  73. (define x 'normal-binding)
  74. @result{} x
  75. (define a-cont
  76. (call-with-current-continuation
  77. (lambda (escape)
  78. (let ((old-x x))
  79. (dynamic-wind
  80. ;; in-guard:
  81. ;;
  82. (lambda () (set! x 'special-binding))
  83. ;; thunk
  84. ;;
  85. (lambda () (display x) (newline)
  86. (call-with-current-continuation escape)
  87. (display x) (newline)
  88. x)
  89. ;; out-guard:
  90. ;;
  91. (lambda () (set! x old-x)))))))
  92. ;; Prints:
  93. special-binding
  94. ;; Evaluates to:
  95. @result{} a-cont
  96. x
  97. @result{} normal-binding
  98. (a-cont #f)
  99. ;; Prints:
  100. special-binding
  101. ;; Evaluates to:
  102. @result{} a-cont ;; the value of the (define a-cont...)
  103. x
  104. @result{} normal-binding
  105. a-cont
  106. @result{} special-binding
  107. @end lisp"
  108. ;; FIXME: Here we don't check that the out procedure is a thunk before
  109. ;; calling the in-guard, as dynamic-wind is called as part of loading
  110. ;; modules, but thunk? requires loading (system vm debug). This is in
  111. ;; contrast to the open-coded version of dynamic-wind, which does
  112. ;; currently insert an eager thunk? check (but often optimizes it
  113. ;; out). Not sure what the right thing to do is here -- make thunk?
  114. ;; callable before modules are loaded, live with this inconsistency,
  115. ;; or remove the thunk? check from the compiler? Questions,
  116. ;; questions.
  117. #;
  118. (unless (thunk? out)
  119. (scm-error 'wrong-type-arg "dynamic-wind" "Not a thunk: ~S"
  120. (list out) #f))
  121. (in)
  122. ((@@ primitive wind) in out)
  123. (call-with-values thunk
  124. (lambda vals
  125. ((@@ primitive unwind))
  126. (out)
  127. (apply values vals))))
  128. (define (with-fluid* fluid val thunk)
  129. "Set @var{fluid} to @var{value} temporarily, and call @var{thunk}.
  130. @var{thunk} must be a procedure of no arguments."
  131. ((@@ primitive push-fluid) fluid val)
  132. (call-with-values thunk
  133. (lambda vals
  134. ((@@ primitive pop-fluid))
  135. (apply values vals))))
  136. (define (with-dynamic-state state thunk)
  137. "Call @var{proc} while @var{state} is the current dynamic state object.
  138. @var{thunk} must be a procedure of no arguments."
  139. ((@@ primitive push-dynamic-state) state)
  140. (call-with-values thunk
  141. (lambda vals
  142. ((@@ primitive pop-dynamic-state))
  143. (apply values vals))))
  144. ;;; {Simple Debugging Tools}
  145. ;;;
  146. (define (peek . stuff)
  147. "Write arguments to the current output port, and return the last argument.
  148. This is handy for tracing function calls, e.g.:
  149. (+ 10 (troublesome-fn))
  150. => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))"
  151. (newline)
  152. (display ";;; ")
  153. (write stuff)
  154. (newline)
  155. (car (last-pair stuff)))
  156. (define pk peek)
  157. (define (warn . stuff)
  158. (newline (current-warning-port))
  159. (display ";;; WARNING " (current-warning-port))
  160. (display stuff (current-warning-port))
  161. (newline (current-warning-port))
  162. (car (last-pair stuff)))
  163. (define (info . stuff)
  164. (newline (current-info-port))
  165. (display ";;; INFO " (current-info-port))
  166. (display stuff (current-info-port))
  167. (newline (current-info-port))
  168. (car (last-pair stuff)))
  169. ;;; {Features}
  170. ;;;
  171. (define (provide sym)
  172. (if (not (memq sym *features*))
  173. (set! *features* (cons sym *features*))))
  174. ;; In SLIB, provided? also checks to see if the module is available. We
  175. ;; should do that too, but don't.
  176. (define (provided? feature)
  177. "Return #t iff FEATURE is available to this Guile interpreter."
  178. (and (memq feature *features*) #t))
  179. ;;; {map and for-each}
  180. ;;;
  181. (define map
  182. (case-lambda
  183. ((f l)
  184. (if (not (list? l))
  185. (scm-error 'wrong-type-arg "map" "Not a list: ~S"
  186. (list l) #f))
  187. (let map1 ((l l))
  188. (if (pair? l)
  189. (cons (f (car l)) (map1 (cdr l)))
  190. '())))
  191. ((f l1 l2)
  192. (if (not (= (length l1) (length l2)))
  193. (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
  194. (list l2) #f))
  195. (let map2 ((l1 l1) (l2 l2))
  196. (if (pair? l1)
  197. (cons (f (car l1) (car l2))
  198. (map2 (cdr l1) (cdr l2)))
  199. '())))
  200. ((f l1 . rest)
  201. (let ((len (length l1)))
  202. (let mapn ((rest rest))
  203. (or (null? rest)
  204. (if (= (length (car rest)) len)
  205. (mapn (cdr rest))
  206. (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
  207. (list (car rest)) #f)))))
  208. (let mapn ((l1 l1) (rest rest))
  209. (if (pair? l1)
  210. (cons (apply f (car l1) (map car rest))
  211. (mapn (cdr l1) (map cdr rest)))
  212. '())))))
  213. (define map-in-order map)
  214. (define for-each
  215. (case-lambda
  216. ((f l)
  217. (if (not (list? l))
  218. (scm-error 'wrong-type-arg "for-each" "Not a list: ~S" (list l) #f))
  219. (let for-each1 ((l l))
  220. (if (not (null? l))
  221. (begin
  222. (f (car l))
  223. (for-each1 (cdr l))))))
  224. ((f l1 l2)
  225. (if (not (= (length l1) (length l2)))
  226. (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
  227. (list l2) #f))
  228. (let for-each2 ((l1 l1) (l2 l2))
  229. (if (not (null? l1))
  230. (begin
  231. (f (car l1) (car l2))
  232. (for-each2 (cdr l1) (cdr l2))))))
  233. ((f l1 . rest)
  234. (let ((len (length l1)))
  235. (let for-eachn ((rest rest))
  236. (or (null? rest)
  237. (if (= (length (car rest)) len)
  238. (for-eachn (cdr rest))
  239. (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
  240. (list (car rest)) #f)))))
  241. (let for-eachn ((l1 l1) (rest rest))
  242. (if (pair? l1)
  243. (begin
  244. (apply f (car l1) (map car rest))
  245. (for-eachn (cdr l1) (map cdr rest))))))))
  246. ;; Temporary definitions used by `include'; replaced later.
  247. (define (absolute-file-name? file-name) #t)
  248. (define (open-input-file str) (open-file str "r"))
  249. ;;; {and-map and or-map}
  250. ;;;
  251. ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
  252. ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
  253. ;;;
  254. (define (and-map f lst)
  255. "Apply F to successive elements of LST until exhaustion or F returns #f.
  256. If returning early, return #f. Otherwise, return the last value returned
  257. by F. If F has never been called because LST is empty, return #t."
  258. (let loop ((result #t)
  259. (l lst))
  260. (and result
  261. (or (and (null? l)
  262. result)
  263. (loop (f (car l)) (cdr l))))))
  264. (define (or-map f lst)
  265. "Apply F to successive elements of LST until exhaustion or while F returns #f.
  266. If returning early, return the return value of F."
  267. (let loop ((result #f)
  268. (l lst))
  269. (or result
  270. (and (not (null? l))
  271. (loop (f (car l)) (cdr l))))))
  272. ;; let format alias simple-format until the more complete version is loaded
  273. (define format simple-format)
  274. ;; this is scheme wrapping the C code so the final pred call is a tail call,
  275. ;; per SRFI-13 spec
  276. (define string-any
  277. (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
  278. (if (and (procedure? char_pred)
  279. (> end start)
  280. (<= end (string-length s))) ;; let c-code handle range error
  281. (or (string-any-c-code char_pred s start (1- end))
  282. (char_pred (string-ref s (1- end))))
  283. (string-any-c-code char_pred s start end))))
  284. ;; this is scheme wrapping the C code so the final pred call is a tail call,
  285. ;; per SRFI-13 spec
  286. (define string-every
  287. (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
  288. (if (and (procedure? char_pred)
  289. (> end start)
  290. (<= end (string-length s))) ;; let c-code handle range error
  291. (and (string-every-c-code char_pred s start (1- end))
  292. (char_pred (string-ref s (1- end))))
  293. (string-every-c-code char_pred s start end))))
  294. (define (substring-fill! str start end fill)
  295. "A variant of string-fill! that we keep for compatibility."
  296. (string-fill! str fill start end))
  297. ;; Define a minimal stub of the module API for psyntax, before modules
  298. ;; have booted.
  299. (define (module-name x)
  300. '(guile))
  301. (define (module-add! module sym var)
  302. (hashq-set! (%get-pre-modules-obarray) sym var))
  303. (define (module-define! module sym val)
  304. (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
  305. (if v
  306. (variable-set! v val)
  307. (module-add! module sym (make-variable val)))))
  308. (define (module-ref module sym)
  309. (let ((v (module-variable module sym)))
  310. (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
  311. (define module-generate-unique-id!
  312. (let ((next-id 0))
  313. (lambda (m)
  314. (let ((i next-id))
  315. (set! next-id (+ i 1))
  316. i))))
  317. (define module-gensym gensym)
  318. (define (resolve-module . args)
  319. #f)
  320. ;; The definition of "include" needs read-syntax. Replaced later.
  321. (define (read-syntax port)
  322. (let ((datum (read port)))
  323. (if (eof-object? datum)
  324. datum
  325. (datum->syntax #f datum))))
  326. ;; API provided by psyntax
  327. (define syntax-violation #f)
  328. (define datum->syntax #f)
  329. (define syntax->datum #f)
  330. (define identifier? #f)
  331. (define generate-temporaries #f)
  332. (define bound-identifier=? #f)
  333. (define free-identifier=? #f)
  334. ;; $sc-dispatch is an implementation detail of psyntax. It is used by
  335. ;; expanded macros, to dispatch an input against a set of patterns.
  336. (define $sc-dispatch #f)
  337. ;; Load it up!
  338. (primitive-load-path "ice-9/psyntax-pp")
  339. ;; The binding for `macroexpand' has now been overridden, making psyntax the
  340. ;; expander now.
  341. (define-syntax and
  342. (syntax-rules ()
  343. ((_) #t)
  344. ((_ x) x)
  345. ;; Avoid ellipsis, which would lead to quadratic expansion time.
  346. ((_ x . y) (if x (and . y) #f))))
  347. (define-syntax or
  348. (syntax-rules ()
  349. ((_) #f)
  350. ((_ x) x)
  351. ;; Avoid ellipsis, which would lead to quadratic expansion time.
  352. ((_ x . y) (let ((t x)) (if t t (or . y))))))
  353. (include-from-path "ice-9/quasisyntax")
  354. (define-syntax-rule (when test stmt stmt* ...)
  355. (if test (let () stmt stmt* ...)))
  356. (define-syntax-rule (unless test stmt stmt* ...)
  357. (if (not test) (let () stmt stmt* ...)))
  358. (define-syntax else
  359. (lambda (x)
  360. (syntax-violation 'else "bad use of 'else' syntactic keyword" x x)))
  361. (define-syntax =>
  362. (lambda (x)
  363. (syntax-violation '=> "bad use of '=>' syntactic keyword" x x)))
  364. (define-syntax ...
  365. (lambda (x)
  366. (syntax-violation '... "bad use of '...' syntactic keyword" x x)))
  367. (define-syntax _
  368. (lambda (x)
  369. (syntax-violation '_ "bad use of '_' syntactic keyword" x x)))
  370. (define-syntax cond
  371. (lambda (whole-expr)
  372. (define (fold f seed xs)
  373. (let loop ((xs xs) (seed seed))
  374. (if (null? xs) seed
  375. (loop (cdr xs) (f (car xs) seed)))))
  376. (define (reverse-map f xs)
  377. (fold (lambda (x seed) (cons (f x) seed))
  378. '() xs))
  379. (syntax-case whole-expr ()
  380. ((_ clause clauses ...)
  381. #`(begin
  382. #,@(fold (lambda (clause-builder tail)
  383. (clause-builder tail))
  384. #'()
  385. (reverse-map
  386. (lambda (clause)
  387. (define* (bad-clause #:optional (msg "invalid clause"))
  388. (syntax-violation 'cond msg whole-expr clause))
  389. (syntax-case clause (=> else)
  390. ((else e e* ...)
  391. (lambda (tail)
  392. (if (null? tail)
  393. #'((let () e e* ...))
  394. (bad-clause "else must be the last clause"))))
  395. ((else . _) (bad-clause))
  396. ((test => receiver)
  397. (lambda (tail)
  398. #`((let ((t test))
  399. (if t
  400. (receiver t)
  401. #,@tail)))))
  402. ((test => receiver ...)
  403. (bad-clause "wrong number of receiver expressions"))
  404. ((generator guard => receiver)
  405. (lambda (tail)
  406. #`((call-with-values (lambda () generator)
  407. (lambda vals
  408. (if (apply guard vals)
  409. (apply receiver vals)
  410. #,@tail))))))
  411. ((generator guard => receiver ...)
  412. (bad-clause "wrong number of receiver expressions"))
  413. ((test)
  414. (lambda (tail)
  415. #`((let ((t test))
  416. (if t t #,@tail)))))
  417. ((test e e* ...)
  418. (lambda (tail)
  419. #`((if test
  420. (let () e e* ...)
  421. #,@tail))))
  422. (_ (bad-clause))))
  423. #'(clause clauses ...))))))))
  424. (define-syntax case
  425. (lambda (whole-expr)
  426. (define (fold f seed xs)
  427. (let loop ((xs xs) (seed seed))
  428. (if (null? xs) seed
  429. (loop (cdr xs) (f (car xs) seed)))))
  430. (define (fold2 f a b xs)
  431. (let loop ((xs xs) (a a) (b b))
  432. (if (null? xs) (values a b)
  433. (call-with-values
  434. (lambda () (f (car xs) a b))
  435. (lambda (a b)
  436. (loop (cdr xs) a b))))))
  437. (define (reverse-map-with-seed f seed xs)
  438. (fold2 (lambda (x ys seed)
  439. (call-with-values
  440. (lambda () (f x seed))
  441. (lambda (y seed)
  442. (values (cons y ys) seed))))
  443. '() seed xs))
  444. (syntax-case whole-expr ()
  445. ((_ expr clause clauses ...)
  446. (with-syntax ((key #'key))
  447. #`(let ((key expr))
  448. #,@(fold
  449. (lambda (clause-builder tail)
  450. (clause-builder tail))
  451. #'()
  452. (reverse-map-with-seed
  453. (lambda (clause seen)
  454. (define* (bad-clause #:optional (msg "invalid clause"))
  455. (syntax-violation 'case msg whole-expr clause))
  456. (syntax-case clause ()
  457. ((test . rest)
  458. (with-syntax
  459. ((clause-expr
  460. (syntax-case #'rest (=>)
  461. ((=> receiver) #'(receiver key))
  462. ((=> receiver ...)
  463. (bad-clause
  464. "wrong number of receiver expressions"))
  465. ((e e* ...) #'(let () e e* ...))
  466. (_ (bad-clause)))))
  467. (syntax-case #'test (else)
  468. ((datums ...)
  469. (let ((seen
  470. (fold
  471. (lambda (datum seen)
  472. (define (warn-datum type)
  473. ((@ (system base message)
  474. warning)
  475. type
  476. (append (source-properties datum)
  477. (source-properties
  478. (syntax->datum #'test)))
  479. datum
  480. (syntax->datum clause)
  481. (syntax->datum whole-expr)))
  482. (when (memv datum seen)
  483. (warn-datum 'duplicate-case-datum))
  484. (when (or (pair? datum) (array? datum))
  485. (warn-datum 'bad-case-datum))
  486. (cons datum seen))
  487. seen
  488. (map syntax->datum #'(datums ...)))))
  489. (values (lambda (tail)
  490. #`((if (memv key '(datums ...))
  491. clause-expr
  492. #,@tail)))
  493. seen)))
  494. (else (values (lambda (tail)
  495. (if (null? tail)
  496. #'(clause-expr)
  497. (bad-clause
  498. "else must be the last clause")))
  499. seen))
  500. (_ (bad-clause)))))
  501. (_ (bad-clause))))
  502. '() #'(clause clauses ...)))))))))
  503. (define-syntax do
  504. (syntax-rules ()
  505. ((do ((var init step ...) ...)
  506. (test expr ...)
  507. command ...)
  508. (letrec
  509. ((loop
  510. (lambda (var ...)
  511. (if test
  512. (begin
  513. (if #f #f)
  514. expr ...)
  515. (begin
  516. command
  517. ...
  518. (loop (do "step" var step ...)
  519. ...))))))
  520. (loop init ...)))
  521. ((do "step" x)
  522. x)
  523. ((do "step" x y)
  524. y)))
  525. (define-syntax define-values
  526. (lambda (orig-form)
  527. (syntax-case orig-form ()
  528. ((_ () expr)
  529. ;; XXX Work around the lack of hygienic top-level identifiers
  530. (with-syntax (((dummy) (generate-temporaries '(dummy))))
  531. #`(define dummy
  532. (call-with-values (lambda () expr)
  533. (lambda () #f)))))
  534. ((_ (var) expr)
  535. (identifier? #'var)
  536. #`(define var
  537. (call-with-values (lambda () expr)
  538. (lambda (v) v))))
  539. ((_ (var0 ... varn) expr)
  540. (and-map identifier? #'(var0 ... varn))
  541. ;; XXX Work around the lack of hygienic toplevel identifiers
  542. (with-syntax (((dummy) (generate-temporaries '(dummy))))
  543. #`(begin
  544. ;; Avoid mutating the user-visible variables
  545. (define dummy
  546. (call-with-values (lambda () expr)
  547. (lambda (var0 ... varn)
  548. (list var0 ... varn))))
  549. (define var0
  550. (let ((v (car dummy)))
  551. (set! dummy (cdr dummy))
  552. v))
  553. ...
  554. (define varn
  555. (let ((v (car dummy)))
  556. (set! dummy #f) ; blackhole dummy
  557. v)))))
  558. ((_ var expr)
  559. (identifier? #'var)
  560. #'(define var
  561. (call-with-values (lambda () expr)
  562. list)))
  563. ((_ (var0 ... . varn) expr)
  564. (and-map identifier? #'(var0 ... varn))
  565. ;; XXX Work around the lack of hygienic toplevel identifiers
  566. (with-syntax (((dummy) (generate-temporaries '(dummy))))
  567. #`(begin
  568. ;; Avoid mutating the user-visible variables
  569. (define dummy
  570. (call-with-values (lambda () expr)
  571. (lambda (var0 ... . varn)
  572. (list var0 ... varn))))
  573. (define var0
  574. (let ((v (car dummy)))
  575. (set! dummy (cdr dummy))
  576. v))
  577. ...
  578. (define varn
  579. (let ((v (car dummy)))
  580. (set! dummy #f) ; blackhole dummy
  581. v))))))))
  582. (define-syntax-rule (delay exp)
  583. (make-promise (lambda () exp)))
  584. (define-syntax with-fluids
  585. (lambda (stx)
  586. (define (emit-with-fluids bindings body)
  587. (syntax-case bindings ()
  588. (()
  589. body)
  590. (((f v) . bindings)
  591. #`(with-fluid* f v
  592. (lambda ()
  593. #,(emit-with-fluids #'bindings body))))))
  594. (syntax-case stx ()
  595. ((_ ((fluid val) ...) exp exp* ...)
  596. (with-syntax (((fluid-tmp ...) (generate-temporaries #'(fluid ...)))
  597. ((val-tmp ...) (generate-temporaries #'(val ...))))
  598. #`(let ((fluid-tmp fluid) ...)
  599. (let ((val-tmp val) ...)
  600. #,(emit-with-fluids #'((fluid-tmp val-tmp) ...)
  601. #'(let () exp exp* ...)))))))))
  602. (define-syntax current-source-location
  603. (lambda (x)
  604. (syntax-case x ()
  605. ((_)
  606. (with-syntax ((s (datum->syntax x (syntax-source x))))
  607. #''s)))))
  608. ;; We provide this accessor out of convenience. current-line and
  609. ;; current-column aren't so interesting, because they distort what they
  610. ;; are measuring; better to use syntax-source from a macro.
  611. ;;
  612. (define-syntax current-filename
  613. (lambda (x)
  614. "A macro that expands to the current filename: the filename that
  615. the (current-filename) form appears in. Expands to #f if this
  616. information is unavailable."
  617. (false-if-exception
  618. (canonicalize-path (assq-ref (syntax-source x) 'filename)))))
  619. (define-syntax-rule (define-once sym val)
  620. (define sym
  621. (if (module-locally-bound? (current-module) 'sym) sym val)))
  622. ;;; {Error handling}
  623. ;;;
  624. ;; Define delimited continuation operators, and implement catch and throw in
  625. ;; terms of them.
  626. (define make-prompt-tag
  627. (lambda* (#:optional (stem "prompt"))
  628. ;; The only property that prompt tags need have is uniqueness in the
  629. ;; sense of eq?. A one-element list will serve nicely.
  630. (list stem)))
  631. (define default-prompt-tag
  632. ;; Redefined later to be a parameter.
  633. (let ((%default-prompt-tag (make-prompt-tag)))
  634. (lambda ()
  635. %default-prompt-tag)))
  636. (define (call-with-prompt tag thunk handler)
  637. ((@@ primitive call-with-prompt) tag thunk handler))
  638. (define (abort-to-prompt tag . args)
  639. (abort-to-prompt* tag args))
  640. ;;; {Defmacros}
  641. ;;;
  642. (define-syntax define-macro
  643. (lambda (x)
  644. "Define a defmacro."
  645. (syntax-case x ()
  646. ((_ (macro . args) doc body1 body ...)
  647. (string? (syntax->datum #'doc))
  648. #'(define-macro macro doc (lambda args body1 body ...)))
  649. ((_ (macro . args) body ...)
  650. #'(define-macro macro #f (lambda args body ...)))
  651. ((_ macro transformer)
  652. #'(define-macro macro #f transformer))
  653. ((_ macro doc transformer)
  654. (or (string? (syntax->datum #'doc))
  655. (not (syntax->datum #'doc)))
  656. #'(define-syntax macro
  657. (lambda (y)
  658. doc
  659. #((macro-type . defmacro)
  660. (defmacro-args args))
  661. (syntax-case y ()
  662. ((_ . args)
  663. (let ((v (syntax->datum #'args)))
  664. (datum->syntax y (apply transformer v)))))))))))
  665. (define-syntax defmacro
  666. (lambda (x)
  667. "Define a defmacro, with the old lispy defun syntax."
  668. (syntax-case x ()
  669. ((_ macro args doc body1 body ...)
  670. (string? (syntax->datum #'doc))
  671. #'(define-macro macro doc (lambda args body1 body ...)))
  672. ((_ macro args body ...)
  673. #'(define-macro macro #f (lambda args body ...))))))
  674. (provide 'defmacro)
  675. ;;; {Deprecation}
  676. ;;;
  677. (define-syntax begin-deprecated
  678. (lambda (x)
  679. (syntax-case x ()
  680. ((_ form form* ...)
  681. (if (include-deprecated-features)
  682. #'(begin form form* ...)
  683. #'(begin))))))
  684. ;;; {Trivial Functions}
  685. ;;;
  686. (define (identity x) x)
  687. (define (compose proc . rest)
  688. "Compose PROC with the procedures in REST, such that the last one in
  689. REST is applied first and PROC last, and return the resulting procedure.
  690. The given procedures must have compatible arity."
  691. (if (null? rest)
  692. proc
  693. (let ((g (apply compose rest)))
  694. (lambda args
  695. (call-with-values (lambda () (apply g args)) proc)))))
  696. (define (negate proc)
  697. "Return a procedure with the same arity as PROC that returns the `not'
  698. of PROC's result."
  699. (lambda args
  700. (not (apply proc args))))
  701. (define (const value)
  702. "Return a procedure that accepts any number of arguments and returns
  703. VALUE."
  704. (lambda _
  705. value))
  706. (define (and=> value procedure)
  707. "When VALUE is #f, return #f. Otherwise, return (PROC VALUE)."
  708. (and value (procedure value)))
  709. (define call/cc call-with-current-continuation)
  710. ;;; {General Properties}
  711. ;;;
  712. ;; Properties are a lispy way to associate random info with random objects.
  713. ;; Traditionally properties are implemented as an alist or a plist actually
  714. ;; pertaining to the object in question.
  715. ;;
  716. ;; These "object properties" have the advantage that they can be associated with
  717. ;; any object, even if the object has no plist. Object properties are good when
  718. ;; you are extending pre-existing objects in unexpected ways. They also present
  719. ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
  720. ;; type that always has properties, it's often still best to store those
  721. ;; properties within the object itself.
  722. (define (make-object-property)
  723. ;; Weak tables are thread-safe.
  724. (let ((prop (make-weak-key-hash-table)))
  725. (make-procedure-with-setter
  726. (lambda (obj) (hashq-ref prop obj))
  727. (lambda (obj val) (hashq-set! prop obj val)))))
  728. ;;; {Symbol Properties}
  729. ;;;
  730. ;;; Symbol properties are something you see in old Lisp code. In most current
  731. ;;; Guile code, symbols are not used as a data structure -- they are used as
  732. ;;; keys into other data structures.
  733. (define (symbol-property sym prop)
  734. (let ((pair (assoc prop (symbol-pref sym))))
  735. (and pair (cdr pair))))
  736. (define (set-symbol-property! sym prop val)
  737. (let ((pair (assoc prop (symbol-pref sym))))
  738. (if pair
  739. (set-cdr! pair val)
  740. (symbol-pset! sym (acons prop val (symbol-pref sym))))))
  741. (define (symbol-property-remove! sym prop)
  742. (let ((pair (assoc prop (symbol-pref sym))))
  743. (if pair
  744. (symbol-pset! sym (delq! pair (symbol-pref sym))))))
  745. ;;; {Arrays}
  746. ;;;
  747. (define (array-shape array)
  748. "Return a list as long as the rank of @var{array}, where each element
  749. is a two-element list containing the lower and upper bounds of the
  750. corresponding dimension.
  751. @lisp
  752. (array-dimensions (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) (0 5))
  753. @end lisp
  754. See also: @code{array-dimensions}, @code{array-rank}."
  755. (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
  756. (array-dimensions array)))
  757. ;;; {Keywords}
  758. ;;;
  759. ;;; It's much better if you can use lambda* / define*, of course.
  760. (define (kw-arg-ref args kw)
  761. (let ((rem (member kw args)))
  762. (and rem (pair? (cdr rem)) (cadr rem))))
  763. ;;; {IOTA functions: generating lists of numbers}
  764. ;;;
  765. ;;; Compatible with srfi-1 so it can just be reused there.
  766. (define* (iota count #:optional (start 0) (step 1))
  767. (unless (and (integer? count) (>= count 0))
  768. (throw 'wrong-type-arg count))
  769. (let loop ((n (- count 1)) (result '()))
  770. (if (negative? n)
  771. result
  772. (loop (- n 1) (cons (+ start (* n step)) result)))))
  773. ;;; {Structs}
  774. ;;;
  775. (define (struct-layout s)
  776. (struct-ref (struct-vtable s) vtable-index-layout))
  777. ;;; {Records}
  778. ;;;
  779. ;; Printing records: by default, records are printed as
  780. ;;
  781. ;; #<type-name field1: val1 field2: val2 ...>
  782. ;;
  783. ;; You can change that by giving a custom printing function to
  784. ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
  785. ;; will be called like
  786. ;;
  787. ;; (<printer> object port)
  788. ;;
  789. ;; It should print OBJECT to PORT.
  790. ;; 0: type-name, 1: fields, 2: constructor, 3: flags, 4: parents 5: mutable bitmask
  791. (define record-type-vtable
  792. (let ((s (make-vtable (string-append standard-vtable-fields
  793. "pwpwpwpwpwpw")
  794. (lambda (s p)
  795. (display "#<record-type " p)
  796. (display (record-type-name s) p)
  797. (display ">" p)))))
  798. (set-struct-vtable-name! s 'record-type)
  799. s))
  800. (define (record-type? obj)
  801. (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
  802. (define (record-type-name rtd)
  803. (unless (record-type? rtd)
  804. (error 'not-a-record-type rtd))
  805. (struct-ref rtd vtable-offset-user))
  806. (define (record-type-fields rtd)
  807. (unless (record-type? rtd)
  808. (error 'not-a-record-type rtd))
  809. (struct-ref rtd (+ 1 vtable-offset-user)))
  810. (define (record-type-constructor rtd)
  811. (unless (record-type? rtd)
  812. (error 'not-a-record-type rtd))
  813. (struct-ref rtd (+ 2 vtable-offset-user)))
  814. (define (record-type-properties rtd)
  815. (unless (record-type? rtd)
  816. (error 'not-a-record-type rtd))
  817. (struct-ref rtd (+ 3 vtable-offset-user)))
  818. (define (record-type-extensible? rtd)
  819. (assq-ref (record-type-properties rtd) 'extensible?))
  820. (define (record-type-opaque? rtd)
  821. (assq-ref (record-type-properties rtd) 'opaque?))
  822. (define (record-type-uid rtd)
  823. (assq-ref (record-type-properties rtd) 'uid))
  824. (define (record-type-parents rtd)
  825. (unless (record-type? rtd)
  826. (error 'not-a-record-type rtd))
  827. (struct-ref rtd (+ 4 vtable-offset-user)))
  828. (define (record-type-parent rtd)
  829. (let* ((parents (record-type-parents rtd))
  830. (nparents (vector-length parents)))
  831. (and (not (zero? nparents))
  832. (vector-ref parents (1- nparents)))))
  833. (define (record-type-has-parent? rtd parent)
  834. (or (eq? rtd parent)
  835. (let ((parents (record-type-parents rtd))
  836. (nparents (vector-length (record-type-parents parent))))
  837. (and (< nparents (vector-length parents))
  838. (eq? (vector-ref parents nparents) parent)))))
  839. (define (record-type-mutable-fields rtd)
  840. (unless (record-type? rtd)
  841. (error 'not-a-record-type rtd))
  842. (struct-ref rtd (+ 5 vtable-offset-user)))
  843. (define prefab-record-types
  844. (make-hash-table))
  845. (define* (make-record-type type-name fields #:optional printer #:key
  846. parent uid extensible? allow-duplicate-field-names?
  847. (opaque? (and=> parent record-type-opaque?)))
  848. ;; Pre-generate constructors for nfields < 20.
  849. (define-syntax make-constructor
  850. (lambda (x)
  851. (define *max-static-argument-count* 20)
  852. (define (make-formals n)
  853. (let lp ((i 0))
  854. (if (< i n)
  855. (cons (datum->syntax
  856. x
  857. (string->symbol
  858. (string (integer->char (+ (char->integer #\a) i)))))
  859. (lp (1+ i)))
  860. '())))
  861. (syntax-case x ()
  862. ((_ rtd exp) (not (identifier? #'exp))
  863. #'(let ((n exp))
  864. (make-constructor rtd n)))
  865. ((_ rtd nfields)
  866. #`(case nfields
  867. #,@(let lp ((n 0))
  868. (if (< n *max-static-argument-count*)
  869. (cons (with-syntax (((formal ...) (make-formals n))
  870. (n n))
  871. #'((n)
  872. (lambda (formal ...)
  873. (make-struct/simple rtd formal ...))))
  874. (lp (1+ n)))
  875. '()))
  876. (else
  877. (lambda args
  878. (if (= (length args) nfields)
  879. (apply make-struct/no-tail rtd args)
  880. (scm-error 'wrong-number-of-args
  881. (format #f "make-~a" type-name)
  882. "Wrong number of arguments" '() #f)))))))))
  883. (define (default-record-printer s p)
  884. (display "#<" p)
  885. (display (record-type-name (record-type-descriptor s)) p)
  886. (let loop ((fields (record-type-fields (record-type-descriptor s)))
  887. (off 0))
  888. (cond
  889. ((not (null? fields))
  890. (display " " p)
  891. (display (car fields) p)
  892. (display ": " p)
  893. (write (struct-ref s off) p)
  894. (loop (cdr fields) (+ 1 off)))))
  895. (display ">" p))
  896. (define parents
  897. (cond
  898. ((record-type? parent)
  899. (unless (record-type-extensible? parent)
  900. (error "parent type is final"))
  901. (when (and (record-type-opaque? parent) (not opaque?))
  902. (error "can't make non-opaque subtype of opaque type"))
  903. (let* ((parent-parents (record-type-parents parent))
  904. (parent-nparents (vector-length parent-parents))
  905. (parents (make-vector (1+ parent-nparents))))
  906. (vector-move-left! parent-parents 0 parent-nparents parents 0)
  907. (vector-set! parents parent-nparents parent)
  908. parents))
  909. (parent
  910. (error "expected parent to be a record type" parent))
  911. (else
  912. #())))
  913. (define (check-fields fields)
  914. (unless (null? fields)
  915. (let ((field (car fields))
  916. (fields (cdr fields)))
  917. (unless (symbol? field)
  918. (error "expected field to be a symbol" field))
  919. (when (and (not allow-duplicate-field-names?) (memq field fields))
  920. (error "duplicate field" field))
  921. (check-fields fields))))
  922. (define (append-fields head tail)
  923. (if (null? head)
  924. tail
  925. (let ((field (car head))
  926. (tail (append-fields (cdr head) tail)))
  927. (when (and (not allow-duplicate-field-names?) (memq field tail))
  928. (error "duplicate field" field))
  929. (cons field tail))))
  930. (define computed-fields
  931. (let ((fields (map (lambda (field)
  932. (cond
  933. ((symbol? field) field)
  934. (else
  935. (unless (and (pair? field)
  936. (memq (car field) '(mutable immutable))
  937. (pair? (cdr field))
  938. (null? (cddr field)))
  939. (error "bad field declaration" field))
  940. (cadr field))))
  941. fields)))
  942. (check-fields fields)
  943. (if parent
  944. (append-fields (record-type-fields parent) fields)
  945. fields)))
  946. (define mutable-fields
  947. (let lp ((fields fields)
  948. (i (if parent (length (record-type-fields parent)) 0))
  949. (mutable (if parent (record-type-mutable-fields parent) 0)))
  950. (if (null? fields)
  951. mutable
  952. (let ((field (car fields)))
  953. (lp (cdr fields)
  954. (1+ i)
  955. (if (or (not (pair? field))
  956. (eq? (car field) 'mutable))
  957. (logior mutable (ash 1 i))
  958. mutable))))))
  959. (define name-sym
  960. (cond
  961. ((symbol? type-name) type-name)
  962. ((string? type-name)
  963. (issue-deprecation-warning
  964. "Passing a string as a type-name to make-record-type is deprecated."
  965. " Pass a symbol instead.")
  966. (string->symbol type-name))
  967. (else
  968. (error "expected a symbol for record type name" type-name))))
  969. (define properties
  970. (let ((maybe-acons (lambda (k v tail)
  971. (if v (acons k v tail) tail))))
  972. (maybe-acons 'extensible? extensible?
  973. (maybe-acons 'opaque? opaque?
  974. (maybe-acons 'uid uid
  975. '())))))
  976. (cond
  977. ((and uid (hashq-ref prefab-record-types uid))
  978. => (lambda (rtd)
  979. (unless (and (equal? (record-type-name rtd) name-sym)
  980. (equal? (record-type-fields rtd) computed-fields)
  981. (not printer)
  982. (equal? (record-type-properties rtd) properties)
  983. (equal? (record-type-parents rtd) parents)
  984. (equal? (record-type-mutable-fields rtd) mutable-fields))
  985. (error "prefab record type declaration incompatible with previous"
  986. rtd))
  987. rtd))
  988. (else
  989. (let ((rtd (make-struct/no-tail
  990. record-type-vtable
  991. (make-struct-layout
  992. (apply string-append
  993. (map (lambda (f) "pw") computed-fields)))
  994. (or printer default-record-printer)
  995. name-sym
  996. computed-fields
  997. #f ; Constructor initialized below.
  998. properties
  999. parents
  1000. mutable-fields)))
  1001. (struct-set! rtd (+ vtable-offset-user 2)
  1002. (make-constructor rtd (length computed-fields)))
  1003. ;; Temporary solution: Associate a name to the record type
  1004. ;; descriptor so that the object system can create a wrapper
  1005. ;; class for it.
  1006. (set-struct-vtable-name! rtd name-sym)
  1007. (when uid
  1008. (unless (symbol? uid)
  1009. (error "UID for prefab record type should be a symbol" uid))
  1010. (hashq-set! prefab-record-types uid rtd))
  1011. rtd))))
  1012. (define record-constructor
  1013. (case-lambda
  1014. ((rtd)
  1015. (record-type-constructor rtd))
  1016. ((rtd field-names)
  1017. (issue-deprecation-warning
  1018. "Calling `record-constructor' with two arguments (the record type"
  1019. " and a list of field names) is deprecated. Instead, call with just"
  1020. " one argument, and provide a wrapper around that constructor if"
  1021. " needed.")
  1022. (primitive-eval
  1023. `(lambda ,field-names
  1024. (make-struct/no-tail ',rtd
  1025. ,@(map (lambda (f)
  1026. (if (memq f field-names)
  1027. f
  1028. #f))
  1029. (record-type-fields rtd))))))))
  1030. (define (record-predicate rtd)
  1031. (unless (record-type? rtd)
  1032. (error 'not-a-record-type rtd))
  1033. (if (record-type-extensible? rtd)
  1034. (let ((pos (vector-length (record-type-parents rtd))))
  1035. ;; Extensible record types form a forest of DAGs, with each
  1036. ;; record type recording an ordered vector of its ancestors. If
  1037. ;; A is a subtype of B, and B has N parents, then A.parents[N]
  1038. ;; will be B.
  1039. (lambda (obj)
  1040. (and (struct? obj)
  1041. (let* ((v (struct-vtable obj)))
  1042. (or (eq? v rtd)
  1043. (let ((parents (record-type-parents v)))
  1044. (and (< pos (vector-length parents))
  1045. (eq? (vector-ref parents pos) rtd))))))))
  1046. (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj))))))
  1047. (define (record-accessor rtd field-name-or-idx)
  1048. (define vtable-index-size 5) ; FIXME: pull from struct.h
  1049. (define (record-nfields rtd)
  1050. (struct-ref/unboxed rtd vtable-index-size))
  1051. (let ((type-name (record-type-name rtd))
  1052. (pos (cond
  1053. ((and (exact-integer? field-name-or-idx)
  1054. (<= 0 field-name-or-idx (record-nfields rtd)))
  1055. field-name-or-idx)
  1056. ((list-index (record-type-fields rtd) field-name-or-idx))
  1057. (else (error 'no-such-field field-name-or-idx))))
  1058. (pred (record-predicate rtd)))
  1059. (lambda (obj)
  1060. (unless (pred obj)
  1061. (scm-error 'wrong-type-arg "record-accessor"
  1062. "Wrong type argument (want `~S'): ~S"
  1063. (list type-name obj)
  1064. #f))
  1065. (struct-ref obj pos))))
  1066. (define (record-modifier rtd field-name-or-idx)
  1067. (define vtable-index-size 5) ; FIXME: pull from struct.h
  1068. (define (record-nfields rtd)
  1069. (struct-ref/unboxed rtd vtable-index-size))
  1070. (let ((type-name (record-type-name rtd))
  1071. (pos (cond
  1072. ((and (exact-integer? field-name-or-idx)
  1073. (<= 0 field-name-or-idx (record-nfields rtd)))
  1074. field-name-or-idx)
  1075. ((list-index (record-type-fields rtd) field-name-or-idx))
  1076. (else (error 'no-such-field field-name-or-idx))))
  1077. (pred (record-predicate rtd)))
  1078. (unless (logbit? pos (record-type-mutable-fields rtd))
  1079. (error "field is immutable" rtd field-name-or-idx))
  1080. (lambda (obj val)
  1081. (unless (pred obj)
  1082. (scm-error 'wrong-type-arg "record-modifier"
  1083. "Wrong type argument (want `~S'): ~S"
  1084. (list type-name obj)
  1085. #f))
  1086. (struct-set! obj pos val))))
  1087. (define (record? obj)
  1088. (and (struct? obj) (record-type? (struct-vtable obj))))
  1089. (define (record-type-descriptor obj)
  1090. (if (record? obj)
  1091. (struct-vtable obj)
  1092. (error 'not-a-record obj)))
  1093. (provide 'record)
  1094. ;;; {Parameters}
  1095. ;;;
  1096. (define <parameter>
  1097. ;; Three fields: the procedure itself, the fluid, and the converter.
  1098. (make-struct/no-tail <applicable-struct-vtable> 'pwpwpw))
  1099. (set-struct-vtable-name! <parameter> '<parameter>)
  1100. (define* (make-parameter init #:optional (conv (lambda (x) x)))
  1101. "Make a new parameter.
  1102. A parameter is a dynamically bound value, accessed through a procedure.
  1103. To access the current value, apply the procedure with no arguments:
  1104. (define p (make-parameter 10))
  1105. (p) => 10
  1106. To provide a new value for the parameter in a dynamic extent, use
  1107. `parameterize':
  1108. (parameterize ((p 20))
  1109. (p)) => 20
  1110. (p) => 10
  1111. The value outside of the dynamic extent of the body is unaffected. To
  1112. update the current value, apply it to one argument:
  1113. (p 20) => 10
  1114. (p) => 20
  1115. As you can see, the call that updates a parameter returns its previous
  1116. value.
  1117. All values for the parameter are first run through the CONV procedure,
  1118. including INIT, the initial value. The default CONV procedure is the
  1119. identity procedure. CONV is commonly used to ensure some set of
  1120. invariants on the values that a parameter may have."
  1121. (let ((fluid (make-fluid (conv init))))
  1122. (make-struct/no-tail
  1123. <parameter>
  1124. (case-lambda
  1125. (() (fluid-ref fluid))
  1126. ((x) (let ((prev (fluid-ref fluid)))
  1127. (fluid-set! fluid (conv x))
  1128. prev)))
  1129. fluid conv)))
  1130. (define (parameter? x)
  1131. (and (struct? x) (eq? (struct-vtable x) <parameter>)))
  1132. (define (parameter-fluid p)
  1133. (if (parameter? p)
  1134. (struct-ref p 1)
  1135. (scm-error 'wrong-type-arg "parameter-fluid"
  1136. "Not a parameter: ~S" (list p) #f)))
  1137. (define (parameter-converter p)
  1138. (if (parameter? p)
  1139. (struct-ref p 2)
  1140. (scm-error 'wrong-type-arg "parameter-fluid"
  1141. "Not a parameter: ~S" (list p) #f)))
  1142. (define-syntax parameterize
  1143. (lambda (x)
  1144. (syntax-case x ()
  1145. ((_ ((param value) ...) body body* ...)
  1146. (with-syntax (((p ...) (generate-temporaries #'(param ...))))
  1147. #'(let ((p param) ...)
  1148. (if (not (parameter? p))
  1149. (scm-error 'wrong-type-arg "parameterize"
  1150. "Not a parameter: ~S" (list p) #f))
  1151. ...
  1152. (with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
  1153. ...)
  1154. body body* ...)))))))
  1155. (define* (fluid->parameter fluid #:optional (conv (lambda (x) x)))
  1156. "Make a parameter that wraps a fluid.
  1157. The value of the parameter will be the same as the value of the fluid.
  1158. If the parameter is rebound in some dynamic extent, perhaps via
  1159. `parameterize', the new value will be run through the optional CONV
  1160. procedure, as with any parameter. Note that unlike `make-parameter',
  1161. CONV is not applied to the initial value."
  1162. (make-struct/no-tail
  1163. <parameter>
  1164. (case-lambda
  1165. (() (fluid-ref fluid))
  1166. ((x) (let ((prev (fluid-ref fluid)))
  1167. (fluid-set! fluid (conv x))
  1168. prev)))
  1169. fluid conv))
  1170. ;;; Once parameters have booted, define the default prompt tag as being
  1171. ;;; a parameter, and make allow-legacy-syntax-objects? a parameter.
  1172. ;;;
  1173. (set! default-prompt-tag (make-parameter (default-prompt-tag)))
  1174. ;;; {Languages}
  1175. ;;;
  1176. ;; The language can be a symbolic name or a <language> object from
  1177. ;; (system base language).
  1178. ;;
  1179. (define current-language (make-parameter 'scheme))
  1180. ;;; {High-Level Port Routines}
  1181. ;;;
  1182. (define (call-with-output-string proc)
  1183. "Calls the one-argument procedure @var{proc} with a newly created output
  1184. port. When the function returns, the string composed of the characters
  1185. written into the port is returned."
  1186. (let ((port (open-output-string)))
  1187. (proc port)
  1188. (get-output-string port)))
  1189. ;;; {Booleans}
  1190. ;;;
  1191. (define (->bool x) (not (not x)))
  1192. ;;; {Symbols}
  1193. ;;;
  1194. (define (symbol-append . args)
  1195. (string->symbol (apply string-append (map symbol->string args))))
  1196. (define (list->symbol . args)
  1197. (string->symbol (apply list->string args)))
  1198. (define (symbol . args)
  1199. (string->symbol (apply string args)))
  1200. ;;; {Lists}
  1201. ;;;
  1202. (define (list-index l k)
  1203. (let loop ((n 0)
  1204. (l l))
  1205. (and (not (null? l))
  1206. (if (eq? (car l) k)
  1207. n
  1208. (loop (+ n 1) (cdr l))))))
  1209. ;;; {Exceptions}
  1210. ;;;
  1211. (let-syntax ((define-values* (syntax-rules ()
  1212. ((_ (id ...) body ...)
  1213. (define-values (id ...)
  1214. (let ()
  1215. body ...
  1216. (values id ...)))))))
  1217. (define-values* (&exception
  1218. &compound-exception
  1219. simple-exceptions
  1220. make-exception
  1221. exception?
  1222. exception-type?
  1223. make-exception-type
  1224. exception-predicate
  1225. exception-accessor)
  1226. (define &exception (make-record-type '&exception '() #:extensible? #t))
  1227. (define simple-exception? (record-predicate &exception))
  1228. (define &compound-exception (make-record-type '&compound-exception
  1229. '((immutable components))))
  1230. (define compound-exception? (record-predicate &compound-exception))
  1231. (define make-compound-exception (record-constructor &compound-exception))
  1232. (define compound-exception-components
  1233. (record-accessor &compound-exception 'components))
  1234. (define (simple-exceptions exception)
  1235. "Return a list of the simple exceptions that compose the exception
  1236. object @var{exception}."
  1237. (cond ((compound-exception? exception)
  1238. (compound-exception-components exception))
  1239. ((simple-exception? exception)
  1240. (list exception))
  1241. (else
  1242. (error "not a exception" exception))))
  1243. (define (make-exception . exceptions)
  1244. "Return an exception object composed of @var{exceptions}."
  1245. (define (flatten exceptions)
  1246. (if (null? exceptions)
  1247. '()
  1248. (append (simple-exceptions (car exceptions))
  1249. (flatten (cdr exceptions)))))
  1250. (let ((simple (flatten exceptions)))
  1251. (if (and (pair? simple) (null? (cdr simple)))
  1252. (car simple)
  1253. (make-compound-exception simple))))
  1254. (define (exception? obj)
  1255. "Return true if @var{obj} is an exception object."
  1256. (or (compound-exception? obj) (simple-exception? obj)))
  1257. (define (exception-type? obj)
  1258. "Return true if OBJ is an exception type."
  1259. (and (record-type? obj)
  1260. (record-type-has-parent? obj &exception)))
  1261. (define (make-exception-type id parent field-names)
  1262. "Return a new exception type named @var{id}, inheriting from
  1263. @var{parent}, and with the fields whose names are listed in
  1264. @var{field-names}. @var{field-names} must be a list of symbols and must
  1265. not contain names already used by @var{parent} or one of its
  1266. supertypes."
  1267. (unless (exception-type? parent)
  1268. (error "parent is not a exception type" parent))
  1269. (unless (and-map symbol? field-names)
  1270. (error "field names should be a list of symbols" field-names))
  1271. (make-record-type id field-names #:parent parent #:extensible? #t))
  1272. (define (exception-predicate rtd)
  1273. "Return a procedure that will return true if its argument is a
  1274. simple exception that is an instance of @var{rtd}, or a compound
  1275. exception composed of such an instance."
  1276. (let ((rtd-predicate (record-predicate rtd)))
  1277. (lambda (obj)
  1278. (cond ((compound-exception? obj)
  1279. (or-map rtd-predicate (simple-exceptions obj)))
  1280. (else (rtd-predicate obj))))))
  1281. (define (exception-accessor rtd proc)
  1282. "Return a procedure that will call @var{proc} on an instance of
  1283. the exception type @var{rtd}, or on the component of a compound
  1284. exception that is an instance of @var{rtd}."
  1285. (let ((rtd-predicate (record-predicate rtd)))
  1286. (lambda (obj)
  1287. (if (rtd-predicate obj)
  1288. (proc obj)
  1289. (let lp ((exceptions (if (compound-exception? obj)
  1290. (simple-exceptions obj)
  1291. '())))
  1292. (when (null? exceptions)
  1293. (error "object is not an exception of the right type"
  1294. obj rtd)) (if (rtd-predicate (car exceptions))
  1295. (proc (car exceptions))
  1296. (lp (cdr exceptions)))))))))
  1297. ;; Exceptionally, these exception types are built with
  1298. ;; make-record-type, in order to be able to mark them as sealed. This
  1299. ;; allows boot definitions of
  1300. (define &exception-with-kind-and-args
  1301. (make-record-type '&exception-with-kind-and-args
  1302. '((immutable kind) (immutable args))
  1303. #:parent &exception #:extensible? #f))
  1304. (define &quit-exception
  1305. (make-record-type '&quit-exception
  1306. '((immutable code))
  1307. #:parent &exception #:extensible? #f))
  1308. (define &error
  1309. (make-exception-type '&error &exception '()))
  1310. (define &programming-error
  1311. (make-exception-type '&programming-error &error '()))
  1312. (define &non-continuable
  1313. (make-exception-type '&non-continuable &programming-error '()))
  1314. ;; Boot definition; overridden later.
  1315. (define-values* (make-exception-from-throw)
  1316. (define make-exception-with-kind-and-args
  1317. (record-constructor &exception-with-kind-and-args))
  1318. (define make-quit-exception
  1319. (record-constructor &quit-exception))
  1320. (define (make-exception-from-throw key args)
  1321. (let ((exn (make-exception-with-kind-and-args key args)))
  1322. (case key
  1323. ((quit)
  1324. (let ((code (cond
  1325. ((not (pair? args)) 0)
  1326. ((integer? (car args)) (car args))
  1327. ((not (car args)) 1)
  1328. (else 0))))
  1329. (make-exception (make-quit-exception code)
  1330. exn)))
  1331. (else
  1332. exn)))))
  1333. (define-values* (exception-kind
  1334. exception-args
  1335. raise-exception
  1336. with-exception-handler
  1337. catch
  1338. with-throw-handler
  1339. throw)
  1340. (define (steal-binding! sym)
  1341. (let ((val (module-ref (current-module) sym)))
  1342. (hashq-remove! (%get-pre-modules-obarray) sym)
  1343. val))
  1344. (define %exception-handler (steal-binding! '%exception-handler))
  1345. (define %exception-epoch (steal-binding! '%exception-epoch))
  1346. (define %init-exceptions! (steal-binding! '%init-exceptions!))
  1347. (%init-exceptions! &compound-exception
  1348. &exception-with-kind-and-args
  1349. &quit-exception)
  1350. (define exception-with-kind-and-args?
  1351. (exception-predicate &exception-with-kind-and-args))
  1352. (define %exception-kind
  1353. (exception-accessor &exception-with-kind-and-args
  1354. (record-accessor &exception-with-kind-and-args 'kind)))
  1355. (define %exception-args
  1356. (exception-accessor &exception-with-kind-and-args
  1357. (record-accessor &exception-with-kind-and-args 'args)))
  1358. (define (exception-kind obj)
  1359. (if (exception-with-kind-and-args? obj)
  1360. (%exception-kind obj)
  1361. '%exception))
  1362. (define (exception-args obj)
  1363. (if (exception-with-kind-and-args? obj)
  1364. (%exception-args obj)
  1365. (list obj)))
  1366. (define quit-exception?
  1367. (exception-predicate &quit-exception))
  1368. (define quit-exception-code
  1369. (exception-accessor &quit-exception
  1370. (record-accessor &quit-exception 'code)))
  1371. (define (fallback-exception-handler exn)
  1372. (cond
  1373. ((quit-exception? exn)
  1374. (primitive-exit (quit-exception-code exn)))
  1375. (else
  1376. (display "guile: uncaught exception:\n" (current-error-port))
  1377. (print-exception (current-error-port) #f
  1378. (exception-kind exn) (exception-args exn))
  1379. (primitive-exit 1))))
  1380. (define* (raise-exception exn #:key (continuable? #f))
  1381. "Raise an exception by invoking the current exception handler on
  1382. @var{exn}. The handler is called with a continuation whose dynamic
  1383. environment is that of the call to @code{raise}, except that the current
  1384. exception handler is the one that was in place when the handler being
  1385. called was installed.
  1386. If @var{continuable?} is true, the handler is invoked in tail position
  1387. relative to the @code{raise-exception} call. Otherwise if the handler
  1388. returns, a non-continuable exception of type @code{&non-continuable} is
  1389. raised in the same dynamic environment as the handler."
  1390. (define (exception-has-type? exn type)
  1391. (cond
  1392. ((eq? type #t)
  1393. #t)
  1394. ((symbol? type)
  1395. (eq? (exception-kind exn) type))
  1396. ((exception-type? type)
  1397. (and (exception? exn)
  1398. ((exception-predicate type) exn)))
  1399. (else #f)))
  1400. (let ((current-epoch (fluid-ref %exception-epoch)))
  1401. (let lp ((depth 0))
  1402. ;; FIXME: fluid-ref* takes time proportional to depth, which
  1403. ;; makes this loop quadratic.
  1404. (let ((val (fluid-ref* %exception-handler depth)))
  1405. ;; There are two types of exception handlers: unwinding handlers
  1406. ;; and pre-unwind handlers. Although you can implement unwinding
  1407. ;; handlers with pre-unwind handlers, it's better to separate them
  1408. ;; because it allows for emergency situations like "stack
  1409. ;; overflow" or "out of memory" to unwind the stack before calling
  1410. ;; a handler.
  1411. (cond
  1412. ((not val)
  1413. ;; No exception handlers bound; use fallback.
  1414. (fallback-exception-handler exn))
  1415. ((fluid? (car val))
  1416. (let ((epoch (car val))
  1417. (handler (cdr val)))
  1418. (cond
  1419. ((< (fluid-ref epoch) current-epoch)
  1420. (with-fluids ((epoch current-epoch))
  1421. (cond
  1422. (continuable?
  1423. (handler exn))
  1424. (else
  1425. (handler exn)
  1426. (raise-exception
  1427. ((record-constructor &non-continuable)))))))
  1428. (else
  1429. (lp (1+ depth))))))
  1430. (else
  1431. (let ((prompt-tag (car val))
  1432. (type (cdr val)))
  1433. (cond
  1434. ((exception-has-type? exn type)
  1435. (abort-to-prompt prompt-tag exn)
  1436. (error "unreachable"))
  1437. (else
  1438. (lp (1+ depth)))))))))))
  1439. (define* (with-exception-handler handler thunk #:key (unwind? #f)
  1440. (unwind-for-type #t))
  1441. "Establish @var{handler}, a procedure of one argument, as the
  1442. current exception handler during the dynamic extent of invoking
  1443. @var{thunk}.
  1444. If @code{raise-exception} is called during the dynamic extent of
  1445. invoking @var{thunk}, @var{handler} will be invoked on the argument of
  1446. @code{raise-exception}.
  1447. There are two kinds of exception handlers: unwinding and non-unwinding.
  1448. By default, exception handlers are non-unwinding. If @var{unwind?} is
  1449. false, @var{handler} will be invoked within the continuation of the
  1450. error, without unwinding the stack. Its dynamic environment will be
  1451. that of the @code{raise-exception} call, with the exception that the
  1452. current exception handler won't be @var{handler}, but rather the
  1453. \"outer\" handler (the one that was in place when
  1454. @code{with-exception-handler} was called).
  1455. However, it's often the case that one would like to handle an exception
  1456. by unwinding the computation to an earlier state and running the error
  1457. handler there. After all, unless the @code{raise-exception} call is
  1458. continuable, the exception handler needs to abort the continuation. To
  1459. support this use case, if @var{unwind?} is true, @code{raise-exception}
  1460. will first unwind the stack by invoking an @dfn{escape
  1461. continuation} (@pxref{Prompt Primitives, @code{call/ec}}), and then
  1462. invoke the handler with the continuation of the
  1463. @code{with-exception-handler} call.
  1464. Finally, one more wrinkle: for unwinding exception handlers, it can be
  1465. useful to determine whether an exception handler would indeed handle a
  1466. particular exception or not. This is especially the case for exceptions
  1467. raised in resource-exhaustion scenarios like @code{stack-overflow} or
  1468. @code{out-of-memory}, where you want to immediately shrink the
  1469. continuation before recovering. @xref{Stack Overflow}. For this
  1470. purpose, the @var{unwind-for-type} parameter allows users to specify the
  1471. kind of exception handled by an exception handler; if @code{#t}, all
  1472. exceptions will be handled; if an exception type object, only exceptions
  1473. of that type will be handled; otherwise if a symbol, only that
  1474. exceptions with the given @code{exception-kind} will be handled."
  1475. (unless (procedure? handler)
  1476. (scm-error 'wrong-type-arg "with-exception-handler"
  1477. "Wrong type argument in position ~a: ~a"
  1478. (list 1 handler) (list handler)))
  1479. (cond
  1480. (unwind?
  1481. (unless (or (eq? unwind-for-type #t)
  1482. (symbol? unwind-for-type)
  1483. (exception-type? unwind-for-type))
  1484. (scm-error 'wrong-type-arg "with-exception-handler"
  1485. "Wrong type argument for #:unwind-for-type: ~a"
  1486. (list unwind-for-type) (list unwind-for-type)))
  1487. (let ((tag (make-prompt-tag "exception handler")))
  1488. (call-with-prompt
  1489. tag
  1490. (lambda ()
  1491. (with-fluids ((%exception-handler (cons tag unwind-for-type)))
  1492. (thunk)))
  1493. (lambda (k exn)
  1494. (handler exn)))))
  1495. (else
  1496. (let ((epoch (make-fluid 0)))
  1497. (with-fluids ((%exception-handler (cons epoch handler)))
  1498. (thunk))))))
  1499. (define (throw key . args)
  1500. "Invoke the catch form matching @var{key}, passing @var{args} to the
  1501. @var{handler}.
  1502. @var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
  1503. If there is no handler at all, Guile prints an error and then exits."
  1504. (unless (symbol? key)
  1505. (throw 'wrong-type-arg "throw" "Wrong type argument in position ~a: ~a"
  1506. (list 1 key) (list key)))
  1507. (raise-exception (make-exception-from-throw key args)))
  1508. (define (with-throw-handler k thunk pre-unwind-handler)
  1509. "Add @var{handler} to the dynamic context as a throw handler
  1510. for key @var{k}, then invoke @var{thunk}."
  1511. (unless (or (symbol? k) (eq? k #t))
  1512. (scm-error 'wrong-type-arg "with-throw-handler"
  1513. "Wrong type argument in position ~a: ~a"
  1514. (list 1 k) (list k)))
  1515. (define running? (make-fluid))
  1516. ;; Throw handlers have two semantic oddities.
  1517. ;;
  1518. ;; One is that throw handlers are not re-entrant: if one is
  1519. ;; already active in the current continuation, it won't handle
  1520. ;; exceptions thrown within that continuation. It's a restrictive
  1521. ;; choice, but it does ensure progress. We ensure this property
  1522. ;; by having a running? fluid associated with each
  1523. ;; with-throw-handler.
  1524. ;;
  1525. ;; The other oddity is that any exception thrown within a throw
  1526. ;; handler starts the whole raise-exception dispatch procedure
  1527. ;; again from the top. This can have its uses if you want to have
  1528. ;; handlers for multiple specific keys active at the same time,
  1529. ;; without specifying an order between them. But, it's weird. We
  1530. ;; ensure this property by having a %exception-epoch fluid and
  1531. ;; also associating an epoch with each pre-unwind handler; a
  1532. ;; handler is active if its epoch is less than the current
  1533. ;; %exception-epoch. We increment the epoch with the extent of
  1534. ;; the throw handler.
  1535. (with-exception-handler
  1536. (lambda (exn)
  1537. (when (and (or (eq? k #t) (eq? k (exception-kind exn)))
  1538. (not (fluid-ref running?)))
  1539. (with-fluids ((%exception-epoch (1+ (fluid-ref %exception-epoch)))
  1540. (running? #t))
  1541. (apply pre-unwind-handler (exception-kind exn)
  1542. (exception-args exn))))
  1543. (raise-exception exn))
  1544. thunk))
  1545. (define* (catch k thunk handler #:optional pre-unwind-handler)
  1546. "Invoke @var{thunk} in the dynamic context of @var{handler} for
  1547. exceptions matching @var{key}. If thunk throws to the symbol
  1548. @var{key}, then @var{handler} is invoked this way:
  1549. @lisp
  1550. (handler key args ...)
  1551. @end lisp
  1552. @var{key} is a symbol or @code{#t}.
  1553. @var{thunk} takes no arguments. If @var{thunk} returns
  1554. normally, that is the return value of @code{catch}.
  1555. Handler is invoked outside the scope of its own @code{catch}.
  1556. If @var{handler} again throws to the same key, a new handler
  1557. from further up the call chain is invoked.
  1558. If the key is @code{#t}, then a throw to @emph{any} symbol will
  1559. match this call to @code{catch}.
  1560. If a @var{pre-unwind-handler} is given and @var{thunk} throws
  1561. an exception that matches @var{key}, Guile calls the
  1562. @var{pre-unwind-handler} before unwinding the dynamic state and
  1563. invoking the main @var{handler}. @var{pre-unwind-handler} should
  1564. be a procedure with the same signature as @var{handler}, that
  1565. is @code{(lambda (key . args))}. It is typically used to save
  1566. the stack at the point where the exception occurred, but can also
  1567. query other parts of the dynamic state at that point, such as
  1568. fluid values.
  1569. A @var{pre-unwind-handler} can exit either normally or non-locally.
  1570. If it exits normally, Guile unwinds the stack and dynamic context
  1571. and then calls the normal (third argument) handler. If it exits
  1572. non-locally, that exit determines the continuation."
  1573. (define (wrong-type-arg n val)
  1574. (scm-error 'wrong-type-arg "catch"
  1575. "Wrong type argument in position ~a: ~a"
  1576. (list n val) (list val)))
  1577. (unless (or (symbol? k) (eq? k #t))
  1578. (wrong-type-arg 2 k))
  1579. (unless (procedure? handler)
  1580. (wrong-type-arg 3 handler))
  1581. (unless (or (not pre-unwind-handler) (procedure? pre-unwind-handler))
  1582. (wrong-type-arg 4 pre-unwind-handler))
  1583. (with-exception-handler
  1584. (lambda (exn)
  1585. (apply handler (exception-kind exn) (exception-args exn)))
  1586. (if pre-unwind-handler
  1587. (lambda ()
  1588. (with-throw-handler k thunk pre-unwind-handler))
  1589. thunk)
  1590. #:unwind? #t
  1591. #:unwind-for-type k))))
  1592. ;;;
  1593. ;;; Extensible exception printing.
  1594. ;;;
  1595. (define set-exception-printer! #f)
  1596. ;; There is already a definition of print-exception from backtrace.c
  1597. ;; that we will override.
  1598. (let ((exception-printers '()))
  1599. (define (print-location frame port)
  1600. (let ((source (and=> frame frame-source)))
  1601. ;; source := (addr . (filename . (line . column)))
  1602. (if source
  1603. (let ((filename (or (cadr source) "<unnamed port>"))
  1604. (line (caddr source))
  1605. (col (cdddr source)))
  1606. (format port "~a:~a:~a: " filename (1+ line) col))
  1607. (format port "ERROR: "))))
  1608. (set! set-exception-printer!
  1609. (lambda (key proc)
  1610. (set! exception-printers (acons key proc exception-printers))))
  1611. (set! print-exception
  1612. (lambda (port frame key args)
  1613. (define (default-printer)
  1614. (format port "Throw to key `~a' with args `~s'." key args))
  1615. (when frame
  1616. (print-location frame port)
  1617. ;; When booting, false-if-exception isn't defined yet.
  1618. (let ((name (catch #t
  1619. (lambda () (frame-procedure-name frame))
  1620. (lambda _ #f))))
  1621. (when name
  1622. (format port "In procedure ~a:\n" name))))
  1623. (catch #t
  1624. (lambda ()
  1625. (let ((printer (assq-ref exception-printers key)))
  1626. (if printer
  1627. (printer port key args default-printer)
  1628. (default-printer))))
  1629. (lambda (k . args)
  1630. (format port "Error while printing exception.")))
  1631. (newline port)
  1632. (force-output port))))
  1633. ;;;
  1634. ;;; Printers for those keys thrown by Guile.
  1635. ;;;
  1636. (let ()
  1637. (define (scm-error-printer port key args default-printer)
  1638. ;; Abuse case-lambda as a pattern matcher, given that we don't have
  1639. ;; ice-9 match at this point.
  1640. (apply (case-lambda
  1641. ((subr msg args . rest)
  1642. (if subr
  1643. (format port "In procedure ~a: " subr))
  1644. (apply format port msg (or args '())))
  1645. (_ (default-printer)))
  1646. args))
  1647. (define (syntax-error-printer port key args default-printer)
  1648. (apply (case-lambda
  1649. ((who what where form subform . extra)
  1650. (format port "Syntax error:\n")
  1651. (if where
  1652. (let ((file (or (assq-ref where 'filename) "unknown file"))
  1653. (line (and=> (assq-ref where 'line) 1+))
  1654. (col (assq-ref where 'column)))
  1655. (format port "~a:~a:~a: " file line col))
  1656. (format port "unknown location: "))
  1657. (if who
  1658. (format port "~a: " who))
  1659. (format port "~a" what)
  1660. (if subform
  1661. (format port " in subform ~s of ~s" subform form)
  1662. (if form
  1663. (format port " in form ~s" form))))
  1664. (_ (default-printer)))
  1665. args))
  1666. (define (keyword-error-printer port key args default-printer)
  1667. (let ((message (cadr args))
  1668. (faulty (car (cadddr args)))) ; I won't do it again, I promise.
  1669. (format port "~a: ~s" message faulty)))
  1670. (define (getaddrinfo-error-printer port key args default-printer)
  1671. (format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
  1672. (set-exception-printer! 'goops-error scm-error-printer)
  1673. (set-exception-printer! 'host-not-found scm-error-printer)
  1674. (set-exception-printer! 'keyword-argument-error keyword-error-printer)
  1675. (set-exception-printer! 'misc-error scm-error-printer)
  1676. (set-exception-printer! 'no-data scm-error-printer)
  1677. (set-exception-printer! 'no-recovery scm-error-printer)
  1678. (set-exception-printer! 'null-pointer-error scm-error-printer)
  1679. (set-exception-printer! 'out-of-memory scm-error-printer)
  1680. (set-exception-printer! 'out-of-range scm-error-printer)
  1681. (set-exception-printer! 'program-error scm-error-printer)
  1682. (set-exception-printer! 'read-error scm-error-printer)
  1683. (set-exception-printer! 'regular-expression-syntax scm-error-printer)
  1684. (set-exception-printer! 'signal scm-error-printer)
  1685. (set-exception-printer! 'stack-overflow scm-error-printer)
  1686. (set-exception-printer! 'system-error scm-error-printer)
  1687. (set-exception-printer! 'try-again scm-error-printer)
  1688. (set-exception-printer! 'unbound-variable scm-error-printer)
  1689. (set-exception-printer! 'wrong-number-of-args scm-error-printer)
  1690. (set-exception-printer! 'wrong-type-arg scm-error-printer)
  1691. (set-exception-printer! 'syntax-error syntax-error-printer)
  1692. (set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
  1693. ;; Load `posix.scm' even when not (provided? 'posix) so that we get the
  1694. ;; `stat' accessors.
  1695. (primitive-load-path "ice-9/posix")
  1696. (if (provided? 'socket)
  1697. (primitive-load-path "ice-9/networking"))
  1698. ;; For reference, Emacs file-exists-p uses stat in this same way.
  1699. (define file-exists?
  1700. (if (provided? 'posix)
  1701. (lambda (str)
  1702. (->bool (stat str #f)))
  1703. (lambda (str)
  1704. (let ((port (catch 'system-error (lambda () (open-input-file str))
  1705. (lambda args #f))))
  1706. (if port (begin (close-port port) #t)
  1707. #f)))))
  1708. (define file-is-directory?
  1709. (if (provided? 'posix)
  1710. (lambda (str)
  1711. (eq? (stat:type (stat str)) 'directory))
  1712. (lambda (str)
  1713. (let ((port (catch 'system-error
  1714. (lambda ()
  1715. (open-input-file (string-append str "/.")))
  1716. (lambda args #f))))
  1717. (if port (begin (close-port port) #t)
  1718. #f)))))
  1719. (define (system-error-errno args)
  1720. (if (eq? (car args) 'system-error)
  1721. (car (list-ref args 4))
  1722. #f))
  1723. ;;; {Error Handling}
  1724. ;;;
  1725. (define error
  1726. (case-lambda
  1727. (()
  1728. (scm-error 'misc-error #f "?" #f #f))
  1729. ((message . args)
  1730. (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
  1731. (scm-error 'misc-error #f msg (cons message args) #f)))))
  1732. ;;; {Time Structures}
  1733. ;;;
  1734. (define (tm:sec obj) (vector-ref obj 0))
  1735. (define (tm:min obj) (vector-ref obj 1))
  1736. (define (tm:hour obj) (vector-ref obj 2))
  1737. (define (tm:mday obj) (vector-ref obj 3))
  1738. (define (tm:mon obj) (vector-ref obj 4))
  1739. (define (tm:year obj) (vector-ref obj 5))
  1740. (define (tm:wday obj) (vector-ref obj 6))
  1741. (define (tm:yday obj) (vector-ref obj 7))
  1742. (define (tm:isdst obj) (vector-ref obj 8))
  1743. (define (tm:gmtoff obj) (vector-ref obj 9))
  1744. (define (tm:zone obj) (vector-ref obj 10))
  1745. (define (set-tm:sec obj val) (vector-set! obj 0 val))
  1746. (define (set-tm:min obj val) (vector-set! obj 1 val))
  1747. (define (set-tm:hour obj val) (vector-set! obj 2 val))
  1748. (define (set-tm:mday obj val) (vector-set! obj 3 val))
  1749. (define (set-tm:mon obj val) (vector-set! obj 4 val))
  1750. (define (set-tm:year obj val) (vector-set! obj 5 val))
  1751. (define (set-tm:wday obj val) (vector-set! obj 6 val))
  1752. (define (set-tm:yday obj val) (vector-set! obj 7 val))
  1753. (define (set-tm:isdst obj val) (vector-set! obj 8 val))
  1754. (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
  1755. (define (set-tm:zone obj val) (vector-set! obj 10 val))
  1756. (define (tms:clock obj) (vector-ref obj 0))
  1757. (define (tms:utime obj) (vector-ref obj 1))
  1758. (define (tms:stime obj) (vector-ref obj 2))
  1759. (define (tms:cutime obj) (vector-ref obj 3))
  1760. (define (tms:cstime obj) (vector-ref obj 4))
  1761. ;;; {C Environment}
  1762. ;;;
  1763. (define (setenv name value)
  1764. (if value
  1765. (putenv (string-append name "=" value))
  1766. (putenv name)))
  1767. (define (unsetenv name)
  1768. "Remove the entry for NAME from the environment."
  1769. (putenv name))
  1770. ;;; {Load Paths}
  1771. ;;;
  1772. (let-syntax ((compile-time-case
  1773. (lambda (stx)
  1774. (syntax-case stx ()
  1775. ((_ exp clauses ...)
  1776. (let ((val (primitive-eval (syntax->datum #'exp))))
  1777. (let next-clause ((clauses #'(clauses ...)))
  1778. (syntax-case clauses (else)
  1779. (()
  1780. (syntax-violation 'compile-time-case
  1781. "all clauses failed to match" stx))
  1782. (((else form ...))
  1783. #'(begin form ...))
  1784. ((((k ...) form ...) clauses ...)
  1785. (if (memv val (syntax->datum #'(k ...)))
  1786. #'(begin form ...)
  1787. (next-clause #'(clauses ...))))))))))))
  1788. ;; emacs: (put 'compile-time-case 'scheme-indent-function 1)
  1789. (compile-time-case (system-file-name-convention)
  1790. ((posix)
  1791. (define (file-name-separator? c)
  1792. (char=? c #\/))
  1793. (define file-name-separator-string "/")
  1794. (define (absolute-file-name? file-name)
  1795. (string-prefix? "/" file-name)))
  1796. ((windows)
  1797. (define (file-name-separator? c)
  1798. (or (char=? c #\/)
  1799. (char=? c #\\)))
  1800. (define file-name-separator-string "/")
  1801. (define (absolute-file-name? file-name)
  1802. (define (file-name-separator-at-index? idx)
  1803. (and (> (string-length file-name) idx)
  1804. (file-name-separator? (string-ref file-name idx))))
  1805. (define (unc-file-name?)
  1806. ;; Universal Naming Convention (UNC) file-names start with \\,
  1807. ;; and are always absolute. See:
  1808. ;; http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#fully_qualified_vs._relative_paths
  1809. (and (file-name-separator-at-index? 0)
  1810. (file-name-separator-at-index? 1)))
  1811. (define (has-drive-specifier?)
  1812. (and (>= (string-length file-name) 2)
  1813. (let ((drive (string-ref file-name 0)))
  1814. (or (char<=? #\a drive #\z)
  1815. (char<=? #\A drive #\Z)))
  1816. (eqv? (string-ref file-name 1) #\:)))
  1817. (or (unc-file-name?)
  1818. (if (has-drive-specifier?)
  1819. (file-name-separator-at-index? 2)
  1820. (file-name-separator-at-index? 0)))))))
  1821. (define (in-vicinity directory file)
  1822. "Concatenate @var{directory} and @var{file}, adding
  1823. @code{file-name-separator-string} (by default slash) in between if it is
  1824. not already present. This helps create file names."
  1825. (let ((tail (let ((len (string-length directory)))
  1826. (if (zero? len)
  1827. #f
  1828. (string-ref directory (- len 1))))))
  1829. (string-append directory
  1830. (if (or (not tail) (file-name-separator? tail))
  1831. ""
  1832. file-name-separator-string)
  1833. file)))
  1834. ;;; {Exception-handling helpers}
  1835. (define-syntax false-if-exception
  1836. (syntax-rules ()
  1837. ((false-if-exception expr)
  1838. (catch #t
  1839. (lambda () expr)
  1840. (lambda args #f)))
  1841. ((false-if-exception expr #:warning template arg ...)
  1842. (catch #t
  1843. (lambda () expr)
  1844. (lambda (key . args)
  1845. (for-each (lambda (s)
  1846. (if (not (string-null? s))
  1847. (format (current-warning-port) ";;; ~a\n" s)))
  1848. (string-split
  1849. (call-with-output-string
  1850. (lambda (port)
  1851. (format port template arg ...)
  1852. (print-exception port #f key args)))
  1853. #\newline))
  1854. #f)))))
  1855. ;;; {Help for scm_shell}
  1856. ;;;
  1857. ;;; The argument-processing code used by Guile-based shells generates
  1858. ;;; Scheme code based on the argument list. This page contains help
  1859. ;;; functions for the code it generates.
  1860. ;;;
  1861. (define (command-line) (program-arguments))
  1862. ;; This is mostly for the internal use of the code generated by
  1863. ;; scm_compile_shell_switches.
  1864. (define (load-user-init)
  1865. (let* ((home (or (getenv "HOME")
  1866. (false-if-exception (passwd:dir (getpwuid (getuid))))
  1867. file-name-separator-string)) ;; fallback for cygwin etc.
  1868. (init-file (in-vicinity home ".guile")))
  1869. (if (file-exists? init-file)
  1870. (primitive-load init-file))))
  1871. ;;; {The interpreter stack}
  1872. ;;;
  1873. ;; %stacks defined in stacks.c
  1874. (define (%start-stack tag thunk)
  1875. (let ((prompt-tag (make-prompt-tag "start-stack")))
  1876. (call-with-prompt
  1877. prompt-tag
  1878. (lambda ()
  1879. (with-fluids ((%stacks (cons tag prompt-tag)))
  1880. (thunk)))
  1881. (lambda (k . args)
  1882. (%start-stack tag (lambda () (apply k args)))))))
  1883. (define-syntax-rule (start-stack tag exp)
  1884. (%start-stack tag (lambda () exp)))
  1885. ;;; {Loading by paths}
  1886. ;;;
  1887. (define (load-from-path name)
  1888. "Load a Scheme source file named NAME, searching for it in the
  1889. directories listed in %load-path, and applying each of the file
  1890. name extensions listed in %load-extensions."
  1891. (start-stack 'load-stack
  1892. (primitive-load-path name)))
  1893. (define-syntax-rule (add-to-load-path elt)
  1894. "Add ELT to Guile's load path, at compile-time and at run-time."
  1895. (eval-when (expand load eval)
  1896. (set! %load-path (cons elt (delete elt %load-path)))))
  1897. (define %load-verbosely #f)
  1898. (define (assert-load-verbosity v) (set! %load-verbosely v))
  1899. (define (%load-announce file)
  1900. (if %load-verbosely
  1901. (with-output-to-port (current-warning-port)
  1902. (lambda ()
  1903. (display ";;; ")
  1904. (display "loading ")
  1905. (display file)
  1906. (newline)
  1907. (force-output)))))
  1908. (set! %load-hook %load-announce)
  1909. ;;; {Reader Extensions}
  1910. ;;;
  1911. ;;; Reader code for various "#c" forms.
  1912. ;;;
  1913. (define read-hash-procedures
  1914. (fluid->parameter %read-hash-procedures))
  1915. (define (read-hash-procedure ch)
  1916. (assq-ref (read-hash-procedures) ch))
  1917. (define (read-hash-extend ch proc)
  1918. (let ((alist (read-hash-procedures)))
  1919. (read-hash-procedures
  1920. (if proc
  1921. (assq-set! alist ch proc)
  1922. (assq-remove! alist ch)))))
  1923. (define read-eval? (make-fluid #f))
  1924. (read-hash-extend #\.
  1925. (lambda (c port)
  1926. (if (fluid-ref read-eval?)
  1927. (eval (read port) (interaction-environment))
  1928. (error
  1929. "#. read expansion found and read-eval? is #f."))))
  1930. ;;; {Low Level Modules}
  1931. ;;;
  1932. ;;; These are the low level data structures for modules.
  1933. ;;;
  1934. ;;; Every module object is of the type 'module-type', which is a record
  1935. ;;; consisting of the following members:
  1936. ;;;
  1937. ;;; - declarative?: a boolean flag indicating whether this module's
  1938. ;;; singly-defined bindings are used in a declarative way.
  1939. ;;; Declarative definitions can be better optimized by the compiler.
  1940. ;;; See "Declarative Modules" in the manual, for more.
  1941. ;;;
  1942. ;;; - obarray: a hash table that maps symbols to variable objects. In this
  1943. ;;; hash table, the definitions are found that are local to the module (that
  1944. ;;; is, not imported from other modules). When looking up bindings in the
  1945. ;;; module, this hash table is searched first.
  1946. ;;;
  1947. ;;; - binder: either #f or a function taking a module and a symbol argument.
  1948. ;;; If it is a function it is called after the obarray has been
  1949. ;;; unsuccessfully searched for a binding. It then can provide bindings
  1950. ;;; that would otherwise not be found locally in the module.
  1951. ;;;
  1952. ;;; - uses: a list of modules from which non-local bindings can be inherited.
  1953. ;;; These modules are the third place queried for bindings after the obarray
  1954. ;;; has been unsuccessfully searched and the binder function did not deliver
  1955. ;;; a result either.
  1956. ;;;
  1957. ;;; - transformer: either #f or a function taking a scheme expression as
  1958. ;;; delivered by read. If it is a function, it will be called to perform
  1959. ;;; syntax transformations (e. g. makro expansion) on the given scheme
  1960. ;;; expression. The output of the transformer function will then be passed
  1961. ;;; to Guile's internal memoizer. This means that the output must be valid
  1962. ;;; scheme code. The only exception is, that the output may make use of the
  1963. ;;; syntax extensions provided to identify the modules that a binding
  1964. ;;; belongs to.
  1965. ;;;
  1966. ;;; - name: the name of the module. This is used for all kinds of printing
  1967. ;;; outputs. In certain places the module name also serves as a way of
  1968. ;;; identification. When adding a module to the uses list of another
  1969. ;;; module, it is made sure that the new uses list will not contain two
  1970. ;;; modules of the same name.
  1971. ;;;
  1972. ;;; - kind: classification of the kind of module. The value is (currently?)
  1973. ;;; only used for printing. It has no influence on how a module is treated.
  1974. ;;; Currently the following values are used when setting the module kind:
  1975. ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
  1976. ;;; is set, it defaults to 'module.
  1977. ;;;
  1978. ;;; - duplicates-handlers: a list of procedures that get called to make a
  1979. ;;; choice between two duplicate bindings when name clashes occur. See the
  1980. ;;; `duplicate-handlers' global variable below.
  1981. ;;;
  1982. ;;; - observers: a list of procedures that get called when the module is
  1983. ;;; modified.
  1984. ;;;
  1985. ;;; - weak-observers: a weak-key hash table of procedures that get called
  1986. ;;; when the module is modified. See `module-observe-weak' for details.
  1987. ;;;
  1988. ;;; In addition, the module may (must?) contain a binding for
  1989. ;;; `%module-public-interface'. This variable should be bound to a module
  1990. ;;; representing the exported interface of a module. See the
  1991. ;;; `module-public-interface' and `module-export!' procedures.
  1992. ;;;
  1993. ;;; !!! warning: The interface to lazy binder procedures is going
  1994. ;;; to be changed in an incompatible way to permit all the basic
  1995. ;;; module ops to be virtualized.
  1996. ;;;
  1997. ;;; (make-module size use-list lazy-binding-proc) => module
  1998. ;;; module-{obarray,uses,binder}[|-set!]
  1999. ;;; (module? obj) => [#t|#f]
  2000. ;;; (module-locally-bound? module symbol) => [#t|#f]
  2001. ;;; (module-bound? module symbol) => [#t|#f]
  2002. ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
  2003. ;;; (module-symbol-interned? module symbol) => [#t|#f]
  2004. ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
  2005. ;;; (module-variable module symbol) => [#<variable ...> | #f]
  2006. ;;; (module-symbol-binding module symbol opt-value)
  2007. ;;; => [ <obj> | opt-value | an error occurs ]
  2008. ;;; (module-make-local-var! module symbol) => #<variable...>
  2009. ;;; (module-add! module symbol var) => unspecified
  2010. ;;; (module-remove! module symbol) => unspecified
  2011. ;;; (module-for-each proc module) => unspecified
  2012. ;;; (make-scm-module) => module ; a lazy copy of the symhash module
  2013. ;;; (set-current-module module) => unspecified
  2014. ;;; (current-module) => #<module...>
  2015. ;;;
  2016. ;;;
  2017. ;;; {Printing Modules}
  2018. ;;;
  2019. ;; This is how modules are printed. You can re-define it.
  2020. (define (%print-module mod port)
  2021. (display "#<" port)
  2022. (display (or (module-kind mod) "module") port)
  2023. (display " " port)
  2024. (display (module-name mod) port)
  2025. (display " " port)
  2026. (display (number->string (object-address mod) 16) port)
  2027. (display ">" port))
  2028. (letrec-syntax
  2029. ;; Locally extend the syntax to allow record accessors to be defined at
  2030. ;; compile-time. Cache the rtd locally to the constructor, the getters and
  2031. ;; the setters, in order to allow for redefinition of the record type; not
  2032. ;; relevant in the case of modules, but perhaps if we make this public, it
  2033. ;; could matter.
  2034. ((define-record-type
  2035. (lambda (x)
  2036. (define (make-id scope . fragments)
  2037. (datum->syntax scope
  2038. (apply symbol-append
  2039. (map (lambda (x)
  2040. (if (symbol? x) x (syntax->datum x)))
  2041. fragments))))
  2042. (define (getter rtd type-name field slot)
  2043. (define id (make-id rtd type-name '- field))
  2044. #`(define #,id
  2045. (let ((rtd #,rtd))
  2046. (lambda (#,type-name)
  2047. (unless (eq? (struct-vtable #,type-name) rtd)
  2048. (scm-error 'wrong-type-arg
  2049. #,(symbol->string (syntax->datum id))
  2050. "Wrong type argument (want `~S'): ~S"
  2051. (list '#,type-name #,type-name)
  2052. #f))
  2053. (struct-ref #,type-name #,slot)))))
  2054. (define (setter rtd type-name field slot)
  2055. (define id (make-id rtd 'set- type-name '- field '!))
  2056. #`(define #,id
  2057. (let ((rtd #,rtd))
  2058. (lambda (#,type-name val)
  2059. (unless (eq? (struct-vtable #,type-name) rtd)
  2060. (scm-error 'wrong-type-arg
  2061. #,(symbol->string (syntax->datum id))
  2062. "Wrong type argument (want `~S'): ~S"
  2063. (list '#,type-name #,type-name)
  2064. #f))
  2065. (struct-set! #,type-name #,slot val)))))
  2066. (define (accessors rtd type-name fields n exp)
  2067. (syntax-case fields ()
  2068. (() exp)
  2069. (((field #:no-accessors) field* ...) (identifier? #'field)
  2070. (accessors rtd type-name #'(field* ...) (1+ n)
  2071. exp))
  2072. (((field #:no-setter) field* ...) (identifier? #'field)
  2073. (accessors rtd type-name #'(field* ...) (1+ n)
  2074. #`(begin #,exp
  2075. #,(getter rtd type-name #'field n))))
  2076. (((field #:no-getter) field* ...) (identifier? #'field)
  2077. (accessors rtd type-name #'(field* ...) (1+ n)
  2078. #`(begin #,exp
  2079. #,(setter rtd type-name #'field n))))
  2080. ((field field* ...) (identifier? #'field)
  2081. (accessors rtd type-name #'(field* ...) (1+ n)
  2082. #`(begin #,exp
  2083. #,(getter rtd type-name #'field n)
  2084. #,(setter rtd type-name #'field n))))))
  2085. (define (predicate rtd type-name fields exp)
  2086. (accessors
  2087. rtd type-name fields 0
  2088. #`(begin
  2089. #,exp
  2090. (define (#,(make-id rtd type-name '?) obj)
  2091. (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
  2092. (define (field-list fields)
  2093. (syntax-case fields ()
  2094. (() '())
  2095. (((f . opts) . rest) (identifier? #'f)
  2096. (cons #'f (field-list #'rest)))
  2097. ((f . rest) (identifier? #'f)
  2098. (cons #'f (field-list #'rest)))))
  2099. (define (constructor rtd type-name fields exp)
  2100. (let* ((ctor (make-id rtd type-name '-constructor))
  2101. (args (field-list fields))
  2102. (n (length fields))
  2103. (slots (iota n)))
  2104. (predicate rtd type-name fields
  2105. #`(begin #,exp
  2106. (define #,ctor
  2107. (let ((rtd #,rtd))
  2108. (lambda #,args
  2109. (make-struct/simple rtd #,@args))))
  2110. (struct-set! #,rtd (+ vtable-offset-user 2)
  2111. #,ctor)))))
  2112. (define (type type-name printer fields)
  2113. (define (make-layout)
  2114. (let lp ((fields fields) (slots '()))
  2115. (syntax-case fields ()
  2116. (() (datum->syntax #'here
  2117. (make-struct-layout
  2118. (apply string-append slots))))
  2119. ((_ . rest) (lp #'rest (cons "pw" slots))))))
  2120. (let ((rtd (make-id type-name type-name '-type)))
  2121. (constructor rtd type-name fields
  2122. #`(begin
  2123. (define #,rtd
  2124. (make-struct/no-tail
  2125. record-type-vtable
  2126. '#,(make-layout)
  2127. #,printer
  2128. '#,type-name
  2129. '#,(field-list fields)
  2130. #f ; constructor; set later
  2131. '() ; properties
  2132. #())) ; parents
  2133. (set-struct-vtable-name! #,rtd '#,type-name)))))
  2134. (syntax-case x ()
  2135. ((_ type-name printer (field ...))
  2136. (type #'type-name #'printer #'(field ...)))))))
  2137. ;; module-type
  2138. ;;
  2139. ;; A module is characterized by an obarray in which local symbols
  2140. ;; are interned, a list of modules, "uses", from which non-local
  2141. ;; bindings can be inherited, and an optional lazy-binder which
  2142. ;; is a (CLOSURE module symbol) which, as a last resort, can provide
  2143. ;; bindings that would otherwise not be found locally in the module.
  2144. ;;
  2145. ;; NOTE: If you change the set of fields or their order, you also need to
  2146. ;; change the constants in libguile/modules.h.
  2147. ;;
  2148. ;; NOTE: The getter `module-transformer' is defined libguile/modules.c.
  2149. ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
  2150. ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
  2151. ;;
  2152. (define-record-type module
  2153. (lambda (obj port) (%print-module obj port))
  2154. (obarray
  2155. uses
  2156. binder
  2157. declarative?
  2158. (transformer #:no-getter)
  2159. (name #:no-getter)
  2160. kind
  2161. duplicates-handlers
  2162. (import-obarray #:no-setter)
  2163. observers
  2164. (weak-observers #:no-setter)
  2165. version
  2166. submodules
  2167. submodule-binder
  2168. public-interface
  2169. filename
  2170. next-unique-id
  2171. (replacements #:no-setter)
  2172. inlinable-exports)))
  2173. ;; make-module &opt size uses binder
  2174. ;;
  2175. (define* (make-module #:optional (size 0) (uses '()) (binder #f))
  2176. "Create a new module, perhaps with a particular size of obarray,
  2177. initial uses list, or binding procedure."
  2178. (unless (integer? size)
  2179. (error "Illegal size to make-module." size))
  2180. (unless (zero? size)
  2181. (issue-deprecation-warning
  2182. "Passing a non-zero size argument to `make-module' is deprecated. "
  2183. "Omit the argument or pass zero instead."))
  2184. (unless (and (list? uses) (and-map module? uses))
  2185. (error "Incorrect use list." uses))
  2186. (when (and binder (not (procedure? binder)))
  2187. (error "Lazy-binder expected to be a procedure or #f." binder))
  2188. (module-constructor (make-hash-table size)
  2189. uses binder #f macroexpand
  2190. #f #f #f
  2191. (make-hash-table)
  2192. '()
  2193. (make-weak-key-hash-table) #f
  2194. (make-hash-table) #f #f #f 0
  2195. (make-hash-table) #f))
  2196. ;;; {Observer protocol}
  2197. ;;;
  2198. (define (module-observe module proc)
  2199. (set-module-observers! module (cons proc (module-observers module)))
  2200. (cons module proc))
  2201. (define* (module-observe-weak module observer-id #:optional (proc observer-id))
  2202. "Register PROC as an observer of MODULE under name OBSERVER-ID (which can
  2203. be any Scheme object). PROC is invoked and passed MODULE any time
  2204. MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
  2205. (thus, it is never unregistered if OBSERVER-ID is an immediate value,
  2206. for instance).
  2207. The two-argument version is kept for backward compatibility: when called
  2208. with two arguments, the observer gets unregistered when closure PROC
  2209. gets GC'd (making it impossible to use an anonymous lambda for PROC)."
  2210. (hashq-set! (module-weak-observers module) observer-id proc))
  2211. (define (module-unobserve token)
  2212. (let ((module (car token))
  2213. (id (cdr token)))
  2214. (if (integer? id)
  2215. (hash-remove! (module-weak-observers module) id)
  2216. (set-module-observers! module (delq1! id (module-observers module)))))
  2217. *unspecified*)
  2218. ;; Hash table of module -> #t indicating modules that changed while
  2219. ;; observers were deferred, or #f if observers are not being deferred.
  2220. (define module-defer-observers (make-parameter #f))
  2221. (define (module-modified m)
  2222. (cond
  2223. ((module-defer-observers) => (lambda (tab) (hashq-set! tab m #t)))
  2224. (else (module-call-observers m))))
  2225. ;;; This function can be used to delay calls to observers so that they
  2226. ;;; can be called once only in the face of massive updating of modules.
  2227. ;;;
  2228. (define (call-with-deferred-observers thunk)
  2229. (cond
  2230. ((module-defer-observers) (thunk))
  2231. (else
  2232. (let ((modules (make-hash-table)))
  2233. (dynamic-wind (lambda () #t)
  2234. (lambda ()
  2235. (parameterize ((module-defer-observers modules))
  2236. (thunk)))
  2237. (lambda ()
  2238. (let ((changed (hash-map->list cons modules)))
  2239. (hash-clear! modules)
  2240. (for-each (lambda (pair)
  2241. (module-call-observers (car pair)))
  2242. changed))))))))
  2243. (define (module-call-observers m)
  2244. (for-each (lambda (proc) (proc m)) (module-observers m))
  2245. ;; We assume that weak observers don't (un)register themselves as they are
  2246. ;; called since this would preclude proper iteration over the hash table
  2247. ;; elements.
  2248. (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
  2249. ;;; {Module Searching in General}
  2250. ;;;
  2251. ;;; We sometimes want to look for properties of a symbol
  2252. ;;; just within the obarray of one module. If the property
  2253. ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
  2254. ;;; DISPLAY is locally rebound in the module `safe-guile'.''
  2255. ;;;
  2256. ;;;
  2257. ;;; Other times, we want to test for a symbol property in the obarray
  2258. ;;; of M and, if it is not found there, try each of the modules in the
  2259. ;;; uses list of M. This is the normal way of testing for some
  2260. ;;; property, so we state these properties without qualification as
  2261. ;;; in: ``The symbol 'fnord is interned in module M because it is
  2262. ;;; interned locally in module M2 which is a member of the uses list
  2263. ;;; of M.''
  2264. ;;;
  2265. (define (module-search fn m v)
  2266. "Return the first non-#f result of FN applied to M and then to
  2267. the modules in the uses of M, and so on recursively. If all applications
  2268. return #f, then so does this function."
  2269. (define (loop pos)
  2270. (and (pair? pos)
  2271. (or (module-search fn (car pos) v)
  2272. (loop (cdr pos)))))
  2273. (or (fn m v)
  2274. (loop (module-uses m))))
  2275. ;;; {Is a symbol bound in a module?}
  2276. ;;;
  2277. ;;; Symbol S in Module M is bound if S is interned in M and if the binding
  2278. ;;; of S in M has been set to some well-defined value.
  2279. ;;;
  2280. (define (module-locally-bound? m v)
  2281. "Is symbol V bound (interned and defined) locally in module M?"
  2282. (let ((var (module-local-variable m v)))
  2283. (and var
  2284. (variable-bound? var))))
  2285. (define (module-bound? m v)
  2286. "Is symbol V bound (interned and defined) anywhere in module M or its
  2287. uses?"
  2288. (let ((var (module-variable m v)))
  2289. (and var
  2290. (variable-bound? var))))
  2291. ;;; {Is a symbol interned in a module?}
  2292. ;;;
  2293. ;;; Symbol S in Module M is interned if S occurs in
  2294. ;;; of S in M has been set to some well-defined value.
  2295. ;;;
  2296. ;;; It is possible to intern a symbol in a module without providing
  2297. ;;; an initial binding for the corresponding variable. This is done
  2298. ;;; with:
  2299. ;;; (module-add! module symbol (make-undefined-variable))
  2300. ;;;
  2301. ;;; In that case, the symbol is interned in the module, but not
  2302. ;;; bound there. The unbound symbol shadows any binding for that
  2303. ;;; symbol that might otherwise be inherited from a member of the uses list.
  2304. ;;;
  2305. (define (module-obarray-get-handle ob key)
  2306. ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
  2307. (define (module-obarray-ref ob key)
  2308. ((if (symbol? key) hashq-ref hash-ref) ob key))
  2309. (define (module-obarray-set! ob key val)
  2310. ((if (symbol? key) hashq-set! hash-set!) ob key val))
  2311. (define (module-obarray-remove! ob key)
  2312. ((if (symbol? key) hashq-remove! hash-remove!) ob key))
  2313. (define (module-symbol-locally-interned? m v)
  2314. "Is symbol V interned (not neccessarily defined) locally in module M
  2315. or its uses? Interned symbols shadow inherited bindings even if they
  2316. are not themselves bound to a defined value."
  2317. (not (not (module-obarray-get-handle (module-obarray m) v))))
  2318. (define (module-symbol-interned? m v)
  2319. "Is symbol V interned (not neccessarily defined) anywhere in module M
  2320. or its uses? Interned symbols shadow inherited bindings even if they
  2321. are not themselves bound to a defined value."
  2322. (module-search module-symbol-locally-interned? m v))
  2323. ;;; {Mapping modules x symbols --> variables}
  2324. ;;;
  2325. ;; module-local-variable module symbol
  2326. ;; return the local variable associated with a MODULE and SYMBOL.
  2327. ;;
  2328. ;;; This function is very important. It is the only function that can
  2329. ;;; return a variable from a module other than the mutators that store
  2330. ;;; new variables in modules. Therefore, this function is the location
  2331. ;;; of the "lazy binder" hack.
  2332. ;;;
  2333. ;;; If symbol is defined in MODULE, and if the definition binds symbol
  2334. ;;; to a variable, return that variable object.
  2335. ;;;
  2336. ;;; If the symbols is not found at first, but the module has a lazy binder,
  2337. ;;; then try the binder.
  2338. ;;;
  2339. ;;; If the symbol is not found at all, return #f.
  2340. ;;;
  2341. ;;; (This is now written in C, see `modules.c'.)
  2342. ;;;
  2343. ;;; {Mapping modules x symbols --> bindings}
  2344. ;;;
  2345. ;;; These are similar to the mapping to variables, except that the
  2346. ;;; variable is dereferenced.
  2347. ;;;
  2348. (define (module-symbol-local-binding m v . opt-val)
  2349. "Return the binding of variable V specified by name within module M,
  2350. signaling an error if the variable is unbound. If the OPT-VALUE is
  2351. passed, then instead of signaling an error, return OPT-VALUE."
  2352. (let ((var (module-local-variable m v)))
  2353. (if (and var (variable-bound? var))
  2354. (variable-ref var)
  2355. (if (not (null? opt-val))
  2356. (car opt-val)
  2357. (error "Locally unbound variable." v)))))
  2358. (define (module-symbol-binding m v . opt-val)
  2359. "Return the binding of variable V specified by name within module M,
  2360. signaling an error if the variable is unbound. If the OPT-VALUE is
  2361. passed, then instead of signaling an error, return OPT-VALUE."
  2362. (let ((var (module-variable m v)))
  2363. (if (and var (variable-bound? var))
  2364. (variable-ref var)
  2365. (if (not (null? opt-val))
  2366. (car opt-val)
  2367. (error "Unbound variable." v)))))
  2368. ;;; {Adding Variables to Modules}
  2369. ;;;
  2370. ;; This function is used in modules.c.
  2371. ;;
  2372. (define (module-make-local-var! m v)
  2373. "Ensure a variable for V in the local namespace of M.
  2374. If no variable was already there, then create a new and uninitialized
  2375. variable."
  2376. (or (let ((b (module-obarray-ref (module-obarray m) v)))
  2377. (and (variable? b)
  2378. (begin
  2379. ;; Mark as modified since this function is called when
  2380. ;; the standard eval closure defines a binding
  2381. (module-modified m)
  2382. b)))
  2383. ;; Create a new local variable.
  2384. (let ((local-var (make-undefined-variable)))
  2385. (module-add! m v local-var)
  2386. local-var)))
  2387. (define (module-ensure-local-variable! module symbol)
  2388. "Ensure that there is a local variable in MODULE for SYMBOL. If
  2389. there is no binding for SYMBOL, create a new uninitialized
  2390. variable. Return the local variable."
  2391. (or (module-local-variable module symbol)
  2392. (let ((var (make-undefined-variable)))
  2393. (module-add! module symbol var)
  2394. var)))
  2395. ;; module-add! module symbol var
  2396. ;;
  2397. (define (module-add! m v var)
  2398. "Ensure a particular variable for V in the local namespace of M."
  2399. (if (not (variable? var))
  2400. (error "Bad variable to module-add!" var))
  2401. (if (not (symbol? v))
  2402. (error "Bad symbol to module-add!" v))
  2403. (module-obarray-set! (module-obarray m) v var)
  2404. (module-modified m))
  2405. (define (module-remove! m v)
  2406. "Make sure that symbol V is undefined in the local namespace of M."
  2407. (module-obarray-remove! (module-obarray m) v)
  2408. (module-modified m))
  2409. (define (module-clear! m)
  2410. (hash-clear! (module-obarray m))
  2411. (module-modified m))
  2412. ;; MODULE-FOR-EACH -- exported
  2413. ;;
  2414. (define (module-for-each proc module)
  2415. "Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE)."
  2416. (hash-for-each proc (module-obarray module)))
  2417. (define (module-map proc module)
  2418. (hash-map->list proc (module-obarray module)))
  2419. ;; Submodules
  2420. ;;
  2421. ;; Modules exist in a separate namespace from values, because you generally do
  2422. ;; not want the name of a submodule, which you might not even use, to collide
  2423. ;; with local variables that happen to be named the same as the submodule.
  2424. ;;
  2425. (define (module-ref-submodule module name)
  2426. (or (hashq-ref (module-submodules module) name)
  2427. (and (module-submodule-binder module)
  2428. ((module-submodule-binder module) module name))))
  2429. (define (module-define-submodule! module name submodule)
  2430. (hashq-set! (module-submodules module) name submodule))
  2431. ;;; {Module-based Loading}
  2432. ;;;
  2433. (define (save-module-excursion thunk)
  2434. (let ((inner-module (current-module))
  2435. (outer-module #f))
  2436. (dynamic-wind (lambda ()
  2437. (set! outer-module (current-module))
  2438. (set-current-module inner-module)
  2439. (set! inner-module #f))
  2440. thunk
  2441. (lambda ()
  2442. (set! inner-module (current-module))
  2443. (set-current-module outer-module)
  2444. (set! outer-module #f)))))
  2445. ;;; {MODULE-REF -- exported}
  2446. ;;;
  2447. (define (module-ref module name . rest)
  2448. "Returns the value of a variable called NAME in MODULE or any of its
  2449. used modules. If there is no such variable, then if the optional third
  2450. argument DEFAULT is present, it is returned; otherwise an error is signaled."
  2451. (let ((variable (module-variable module name)))
  2452. (if (and variable (variable-bound? variable))
  2453. (variable-ref variable)
  2454. (if (null? rest)
  2455. (error "No variable named" name 'in module)
  2456. (car rest) ; default value
  2457. ))))
  2458. ;; MODULE-SET! -- exported
  2459. ;;
  2460. (define (module-set! module name value)
  2461. "Sets the variable called NAME in MODULE (or in a module that MODULE uses)
  2462. to VALUE; if there is no such variable, an error is signaled."
  2463. (let ((variable (module-variable module name)))
  2464. (if variable
  2465. (variable-set! variable value)
  2466. (error "No variable named" name 'in module))))
  2467. ;; MODULE-DEFINE! -- exported
  2468. ;;
  2469. (define (module-define! module name value)
  2470. "Sets the variable called NAME in MODULE to VALUE; if there is no such
  2471. variable, it is added first."
  2472. (let ((variable (module-local-variable module name)))
  2473. (if variable
  2474. (begin
  2475. (variable-set! variable value)
  2476. (module-modified module))
  2477. (let ((variable (make-variable value)))
  2478. (module-add! module name variable)))))
  2479. ;; MODULE-DEFINED? -- exported
  2480. ;;
  2481. (define (module-defined? module name)
  2482. "Return #t iff NAME is defined in MODULE (or in a module that MODULE
  2483. uses)."
  2484. (let ((variable (module-variable module name)))
  2485. (and variable (variable-bound? variable))))
  2486. (define (module-use! module interface)
  2487. "Add INTERFACE to the list of interfaces used by MODULE."
  2488. (if (not (or (eq? module interface)
  2489. (memq interface (module-uses module))))
  2490. (begin
  2491. ;; Newly used modules must be appended rather than consed, so that
  2492. ;; `module-variable' traverses the use list starting from the first
  2493. ;; used module.
  2494. (set-module-uses! module (append (module-uses module)
  2495. (list interface)))
  2496. (hash-clear! (module-import-obarray module))
  2497. (module-modified module))))
  2498. (define (module-use-interfaces! module interfaces)
  2499. "Same as MODULE-USE!, but only notifies module observers after all
  2500. interfaces are added to the inports list."
  2501. (let* ((cur (module-uses module))
  2502. (new (let lp ((in interfaces) (out '()))
  2503. (if (null? in)
  2504. (reverse out)
  2505. (lp (cdr in)
  2506. (let ((iface (car in)))
  2507. (if (or (memq iface cur) (memq iface out))
  2508. out
  2509. (cons iface out))))))))
  2510. (set-module-uses! module (append cur new))
  2511. (hash-clear! (module-import-obarray module))
  2512. (module-modified module)))
  2513. ;;; {Recursive Namespaces}
  2514. ;;;
  2515. ;;; A hierarchical namespace emerges if we consider some module to be
  2516. ;;; root, and submodules of that module to be nested namespaces.
  2517. ;;;
  2518. ;;; The routines here manage variable names in hierarchical namespace.
  2519. ;;; Each variable name is a list of elements, looked up in successively nested
  2520. ;;; modules.
  2521. ;;;
  2522. ;;; (nested-ref some-root-module '(foo bar baz))
  2523. ;;; => <value of a variable named baz in the submodule bar of
  2524. ;;; the submodule foo of some-root-module>
  2525. ;;;
  2526. ;;;
  2527. ;;; There are:
  2528. ;;;
  2529. ;;; ;; a-root is a module
  2530. ;;; ;; name is a list of symbols
  2531. ;;;
  2532. ;;; nested-ref a-root name
  2533. ;;; nested-set! a-root name val
  2534. ;;; nested-define! a-root name val
  2535. ;;; nested-remove! a-root name
  2536. ;;;
  2537. ;;; These functions manipulate values in namespaces. For referencing the
  2538. ;;; namespaces themselves, use the following:
  2539. ;;;
  2540. ;;; nested-ref-module a-root name
  2541. ;;; nested-define-module! a-root name mod
  2542. ;;;
  2543. ;;; (current-module) is a natural choice for a root so for convenience there are
  2544. ;;; also:
  2545. ;;;
  2546. ;;; local-ref name == nested-ref (current-module) name
  2547. ;;; local-set! name val == nested-set! (current-module) name val
  2548. ;;; local-define name val == nested-define! (current-module) name val
  2549. ;;; local-remove name == nested-remove! (current-module) name
  2550. ;;; local-ref-module name == nested-ref-module (current-module) name
  2551. ;;; local-define-module! name m == nested-define-module! (current-module) name m
  2552. ;;;
  2553. (define (nested-ref root names)
  2554. (if (null? names)
  2555. root
  2556. (let loop ((cur root)
  2557. (head (car names))
  2558. (tail (cdr names)))
  2559. (if (null? tail)
  2560. (module-ref cur head #f)
  2561. (let ((cur (module-ref-submodule cur head)))
  2562. (and cur
  2563. (loop cur (car tail) (cdr tail))))))))
  2564. (define (nested-set! root names val)
  2565. (let loop ((cur root)
  2566. (head (car names))
  2567. (tail (cdr names)))
  2568. (if (null? tail)
  2569. (module-set! cur head val)
  2570. (let ((cur (module-ref-submodule cur head)))
  2571. (if (not cur)
  2572. (error "failed to resolve module" names)
  2573. (loop cur (car tail) (cdr tail)))))))
  2574. (define (nested-define! root names val)
  2575. (let loop ((cur root)
  2576. (head (car names))
  2577. (tail (cdr names)))
  2578. (if (null? tail)
  2579. (module-define! cur head val)
  2580. (let ((cur (module-ref-submodule cur head)))
  2581. (if (not cur)
  2582. (error "failed to resolve module" names)
  2583. (loop cur (car tail) (cdr tail)))))))
  2584. (define (nested-remove! root names)
  2585. (let loop ((cur root)
  2586. (head (car names))
  2587. (tail (cdr names)))
  2588. (if (null? tail)
  2589. (module-remove! cur head)
  2590. (let ((cur (module-ref-submodule cur head)))
  2591. (if (not cur)
  2592. (error "failed to resolve module" names)
  2593. (loop cur (car tail) (cdr tail)))))))
  2594. (define (nested-ref-module root names)
  2595. (let loop ((cur root)
  2596. (names names))
  2597. (if (null? names)
  2598. cur
  2599. (let ((cur (module-ref-submodule cur (car names))))
  2600. (and cur
  2601. (loop cur (cdr names)))))))
  2602. (define (nested-define-module! root names module)
  2603. (if (null? names)
  2604. (error "can't redefine root module" root module)
  2605. (let loop ((cur root)
  2606. (head (car names))
  2607. (tail (cdr names)))
  2608. (if (null? tail)
  2609. (module-define-submodule! cur head module)
  2610. (let ((cur (or (module-ref-submodule cur head)
  2611. (let ((m (make-module)))
  2612. (set-module-kind! m 'directory)
  2613. (set-module-name! m (append (module-name cur)
  2614. (list head)))
  2615. (module-define-submodule! cur head m)
  2616. m))))
  2617. (loop cur (car tail) (cdr tail)))))))
  2618. (define (local-ref names)
  2619. (nested-ref (current-module) names))
  2620. (define (local-set! names val)
  2621. (nested-set! (current-module) names val))
  2622. (define (local-define names val)
  2623. (nested-define! (current-module) names val))
  2624. (define (local-remove names)
  2625. (nested-remove! (current-module) names))
  2626. (define (local-ref-module names)
  2627. (nested-ref-module (current-module) names))
  2628. (define (local-define-module names mod)
  2629. (nested-define-module! (current-module) names mod))
  2630. ;;; {The (guile) module}
  2631. ;;;
  2632. ;;; The standard module, which has the core Guile bindings. Also called the
  2633. ;;; "root module", as it is imported by many other modules, but it is not
  2634. ;;; necessarily the root of anything; and indeed, the module named '() might be
  2635. ;;; better thought of as a root.
  2636. ;;;
  2637. ;; The root module uses the pre-modules-obarray as its obarray. This
  2638. ;; special obarray accumulates all bindings that have been established
  2639. ;; before the module system is fully booted.
  2640. ;;
  2641. ;; (The obarray continues to be used by code that has been closed over
  2642. ;; before the module system has been booted.)
  2643. ;;
  2644. (define the-root-module
  2645. (let ((m (make-module 0)))
  2646. (set-module-obarray! m (%get-pre-modules-obarray))
  2647. (set-module-name! m '(guile))
  2648. ;; Inherit next-unique-id from preliminary stub of
  2649. ;; %module-get-next-unique-id! defined above.
  2650. (set-module-next-unique-id! m (module-generate-unique-id! #f))
  2651. m))
  2652. ;; The root interface is a module that uses the same obarray as the
  2653. ;; root module. It does not allow new definitions, tho.
  2654. ;;
  2655. (define the-scm-module
  2656. (let ((m (make-module 0)))
  2657. (set-module-obarray! m (%get-pre-modules-obarray))
  2658. (set-module-name! m '(guile))
  2659. (set-module-kind! m 'interface)
  2660. ;; In Guile 1.8 and earlier M was its own public interface.
  2661. (set-module-public-interface! m m)
  2662. m))
  2663. (set-module-public-interface! the-root-module the-scm-module)
  2664. ;; Now that we have a root module, even though modules aren't fully booted,
  2665. ;; expand the definition of resolve-module.
  2666. ;;
  2667. (define (resolve-module name . args)
  2668. (if (equal? name '(guile))
  2669. the-root-module
  2670. (error "unexpected module to resolve during module boot" name)))
  2671. (define (module-generate-unique-id! m)
  2672. (let ((i (module-next-unique-id m)))
  2673. (set-module-next-unique-id! m (+ i 1))
  2674. i))
  2675. ;; Cheat. These bindings are needed by modules.c, but we don't want
  2676. ;; to move their real definition here because that would be unnatural.
  2677. ;;
  2678. (define define-module* #f)
  2679. (define process-use-modules #f)
  2680. (define module-export! #f)
  2681. (define default-duplicate-binding-procedures #f)
  2682. ;; This boots the module system. All bindings needed by modules.c
  2683. ;; must have been defined by now.
  2684. ;;
  2685. (set-current-module the-root-module)
  2686. (define (call-with-module-autoload-lock thunk)
  2687. ;; This binding is overridden when (ice-9 threads) is available to
  2688. ;; implement a critical section around the call to THUNK. It must be
  2689. ;; used anytime 'autoloads-done' and related variables are accessed
  2690. ;; and whenever submodules are accessed (via the 'nested-'
  2691. ;; procedures.)
  2692. (thunk))
  2693. ;; Now that modules are booted, give module-name its final definition.
  2694. ;;
  2695. (define module-name
  2696. (let ((accessor (record-accessor module-type 'name)))
  2697. (lambda (mod)
  2698. (or (accessor mod)
  2699. (let ((name (list (gensym))))
  2700. ;; Name MOD and bind it in the module root so that it's visible to
  2701. ;; `resolve-module'. This is important as `psyntax' stores module
  2702. ;; names and relies on being able to `resolve-module' them.
  2703. (set-module-name! mod name)
  2704. (call-with-module-autoload-lock
  2705. (lambda ()
  2706. (nested-define-module! (resolve-module '() #f) name mod)))
  2707. (accessor mod))))))
  2708. (define* (module-gensym #:optional (id " mg") (m (current-module)))
  2709. "Return a fresh symbol in the context of module M, based on ID (a
  2710. string or symbol). As long as M is a valid module, this procedure is
  2711. deterministic."
  2712. (define (->string number)
  2713. (number->string number 16))
  2714. (if m
  2715. (string->symbol
  2716. (string-append id "-"
  2717. (->string (hash (module-name m) most-positive-fixnum))
  2718. "-"
  2719. (->string (module-generate-unique-id! m))))
  2720. (gensym id)))
  2721. (define (make-modules-in module name)
  2722. (or (nested-ref-module module name)
  2723. (let ((m (make-module)))
  2724. (set-module-kind! m 'directory)
  2725. (set-module-name! m (append (module-name module) name))
  2726. (nested-define-module! module name m)
  2727. m)))
  2728. (define user-modules-declarative? (make-parameter #t))
  2729. (define (beautify-user-module! module)
  2730. (let ((interface (module-public-interface module)))
  2731. (if (or (not interface)
  2732. (eq? interface module))
  2733. (let ((interface (make-module)))
  2734. (set-module-name! interface (module-name module))
  2735. (set-module-version! interface (module-version module))
  2736. (set-module-kind! interface 'interface)
  2737. (set-module-public-interface! module interface))))
  2738. (if (and (not (memq the-scm-module (module-uses module)))
  2739. (not (eq? module the-root-module)))
  2740. ;; Import the default set of bindings (from the SCM module) in MODULE.
  2741. (module-use! module the-scm-module)))
  2742. (define (version-matches? version-ref target)
  2743. (define (sub-versions-match? v-refs t)
  2744. (define (sub-version-matches? v-ref t)
  2745. (let ((matches? (lambda (v) (sub-version-matches? v t))))
  2746. (cond
  2747. ((number? v-ref) (eqv? v-ref t))
  2748. ((list? v-ref)
  2749. (case (car v-ref)
  2750. ((>=) (>= t (cadr v-ref)))
  2751. ((<=) (<= t (cadr v-ref)))
  2752. ((and) (and-map matches? (cdr v-ref)))
  2753. ((or) (or-map matches? (cdr v-ref)))
  2754. ((not) (not (matches? (cadr v-ref))))
  2755. (else (error "Invalid sub-version reference" v-ref))))
  2756. (else (error "Invalid sub-version reference" v-ref)))))
  2757. (or (null? v-refs)
  2758. (and (not (null? t))
  2759. (sub-version-matches? (car v-refs) (car t))
  2760. (sub-versions-match? (cdr v-refs) (cdr t)))))
  2761. (let ((matches? (lambda (v) (version-matches? v target))))
  2762. (or (null? version-ref)
  2763. (case (car version-ref)
  2764. ((and) (and-map matches? (cdr version-ref)))
  2765. ((or) (or-map matches? (cdr version-ref)))
  2766. ((not) (not (matches? (cadr version-ref))))
  2767. (else (sub-versions-match? version-ref target))))))
  2768. (define (make-fresh-user-module)
  2769. (let ((m (make-module)))
  2770. (beautify-user-module! m)
  2771. (set-module-declarative?! m (user-modules-declarative?))
  2772. m))
  2773. ;; NOTE: This binding is used in libguile/modules.c.
  2774. ;;
  2775. (define resolve-module
  2776. (let ((root (make-module)))
  2777. (set-module-name! root '())
  2778. ;; Define the-root-module as '(guile).
  2779. (module-define-submodule! root 'guile the-root-module)
  2780. (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
  2781. (call-with-module-autoload-lock
  2782. (lambda ()
  2783. (let ((already (nested-ref-module root name)))
  2784. (cond
  2785. ((and already
  2786. (or (not autoload) (module-public-interface already)))
  2787. ;; A hit, a palpable hit.
  2788. (if (and version
  2789. (not (version-matches? version (module-version already))))
  2790. (error "incompatible module version already loaded" name))
  2791. already)
  2792. (autoload
  2793. ;; Try to autoload the module, and recurse.
  2794. (try-load-module name version)
  2795. (resolve-module name #f #:ensure ensure))
  2796. (else
  2797. ;; No module found (or if one was, it had no public interface), and
  2798. ;; we're not autoloading. Make an empty module if #:ensure is true.
  2799. (or already
  2800. (and ensure
  2801. (make-modules-in root name)))))))))))
  2802. (define (try-load-module name version)
  2803. (try-module-autoload name version))
  2804. (define (reload-module m)
  2805. "Revisit the source file corresponding to the module @var{m}."
  2806. (let ((f (module-filename m)))
  2807. (if f
  2808. (save-module-excursion
  2809. (lambda ()
  2810. ;; Re-set the initial environment, as in try-module-autoload.
  2811. (set-current-module (make-fresh-user-module))
  2812. (primitive-load-path f)
  2813. m))
  2814. ;; Though we could guess, we *should* know it.
  2815. (error "unknown file name for module" m))))
  2816. (define (purify-module! module)
  2817. "Removes bindings in MODULE which are inherited from the (guile) module."
  2818. (let ((use-list (module-uses module)))
  2819. (if (and (pair? use-list)
  2820. (eq? (car (last-pair use-list)) the-scm-module))
  2821. (set-module-uses! module (reverse (cdr (reverse use-list)))))))
  2822. (define* (resolve-interface name #:key
  2823. (select #f)
  2824. (hide '())
  2825. (prefix #f)
  2826. (renamer (if prefix
  2827. (symbol-prefix-proc prefix)
  2828. identity))
  2829. version)
  2830. "Return a module that is an interface to the module designated by
  2831. NAME.
  2832. `resolve-interface' takes four keyword arguments:
  2833. #:select SELECTION
  2834. SELECTION is a list of binding-specs to be imported; A binding-spec
  2835. is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
  2836. is the name in the used module and SEEN is the name in the using
  2837. module. Note that SEEN is also passed through RENAMER, below. The
  2838. default is to select all bindings. If you specify no selection but
  2839. a renamer, only the bindings that already exist in the used module
  2840. are made available in the interface. Bindings that are added later
  2841. are not picked up.
  2842. #:hide BINDINGS
  2843. BINDINGS is a list of bindings which should not be imported.
  2844. #:prefix PREFIX
  2845. PREFIX is a symbol that will be appended to each exported name.
  2846. The default is to not perform any renaming.
  2847. #:renamer RENAMER
  2848. RENAMER is a procedure that takes a symbol and returns its new
  2849. name. The default is not perform any renaming.
  2850. Signal \"no code for module\" error if module name is not resolvable
  2851. or its public interface is not available. Signal \"no binding\"
  2852. error if selected binding does not exist in the used module."
  2853. (let* ((module (resolve-module name #t version #:ensure #f))
  2854. (public-i (and module (module-public-interface module))))
  2855. (unless public-i
  2856. (error "no code for module" name))
  2857. (if (and (not select) (null? hide) (eq? renamer identity))
  2858. public-i
  2859. (let ((custom-i (make-module)))
  2860. (set-module-kind! custom-i 'custom-interface)
  2861. (set-module-name! custom-i name)
  2862. ;; Check that we are not hiding bindings which don't exist
  2863. (for-each (lambda (binding)
  2864. (unless (module-local-variable public-i binding)
  2865. (error
  2866. (simple-format
  2867. #f "no binding `~A' to hide in module ~A"
  2868. binding name))))
  2869. hide)
  2870. (define (maybe-export! src dst var)
  2871. (unless (memq src hide)
  2872. (let ((name (renamer dst)))
  2873. (when (hashq-ref (module-replacements public-i) src)
  2874. (hashq-set! (module-replacements custom-i) name #t))
  2875. (module-add! custom-i name var))))
  2876. (cond
  2877. (select
  2878. (for-each
  2879. (lambda (bspec)
  2880. (let* ((direct? (symbol? bspec))
  2881. (orig (if direct? bspec (car bspec)))
  2882. (seen (if direct? bspec (cdr bspec)))
  2883. (var (module-local-variable public-i orig)))
  2884. (unless var
  2885. (scm-error 'unbound-variable "resolve-interface"
  2886. "no binding `~A' in module ~A" (list orig name)
  2887. #f))
  2888. (maybe-export! orig seen var)))
  2889. select))
  2890. (else
  2891. ;; FIXME: Use a lazy binder so that changes to the used
  2892. ;; module are picked up automatically.
  2893. (module-for-each (lambda (sym var)
  2894. (maybe-export! sym sym var))
  2895. public-i)))
  2896. custom-i))))
  2897. (define (symbol-prefix-proc prefix)
  2898. (lambda (symbol)
  2899. (symbol-append prefix symbol)))
  2900. ;; This function is called from "modules.c". If you change it, be
  2901. ;; sure to update "modules.c" as well.
  2902. (define* (define-module* name
  2903. #:key filename pure version (imports '()) (exports '())
  2904. (replacements '()) (re-exports '()) (re-export-replacements '())
  2905. (autoloads '()) (duplicates #f) transformer declarative?
  2906. inlinable-exports)
  2907. (define (list-of pred l)
  2908. (or (null? l)
  2909. (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
  2910. (define (valid-import? x)
  2911. (list? x))
  2912. (define (valid-export? x)
  2913. (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
  2914. (define (valid-autoload? x)
  2915. (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
  2916. ;; We could add a #:no-check arg, set by the define-module macro, if
  2917. ;; these checks are taking too much time.
  2918. ;;
  2919. (let ((module (resolve-module name #f)))
  2920. (beautify-user-module! module)
  2921. (set-module-declarative?! module declarative?)
  2922. (when filename
  2923. (set-module-filename! module filename))
  2924. (when pure
  2925. (purify-module! module))
  2926. (when version
  2927. (unless (list-of integer? version)
  2928. (error "expected list of integers for version"))
  2929. (set-module-version! module version)
  2930. (set-module-version! (module-public-interface module) version))
  2931. (call-with-deferred-observers
  2932. (lambda ()
  2933. (unless (list-of valid-import? imports)
  2934. (error "expected imports to be a list of import specifications"))
  2935. (unless (list-of valid-export? exports)
  2936. (error "expected exports to be a list of symbols or symbol pairs"))
  2937. (unless (list-of valid-export? replacements)
  2938. (error "expected replacements to be a list of symbols or symbol pairs"))
  2939. (unless (list-of valid-export? re-exports)
  2940. (error "expected re-exports to be a list of symbols or symbol pairs"))
  2941. (module-export! module exports)
  2942. (module-replace! module replacements)
  2943. (unless (null? imports)
  2944. (let ((imports (map (lambda (import-spec)
  2945. (apply resolve-interface import-spec))
  2946. imports)))
  2947. (module-use-interfaces! module imports)))
  2948. (module-re-export! module re-exports)
  2949. (module-re-export! module re-export-replacements #:replace? #t)
  2950. ;; FIXME: Avoid use of `apply'.
  2951. (apply module-autoload! module autoloads)
  2952. (let ((duplicates (or duplicates
  2953. ;; Avoid stomping a previously installed
  2954. ;; duplicates handlers if possible.
  2955. (and (not (module-duplicates-handlers module))
  2956. ;; Note: If you change this default,
  2957. ;; change it also in
  2958. ;; `default-duplicate-binding-procedures'.
  2959. '(replace warn-override-core warn last)))))
  2960. (when duplicates
  2961. (let ((handlers (lookup-duplicates-handlers duplicates)))
  2962. (set-module-duplicates-handlers! module handlers))))))
  2963. (when transformer
  2964. (unless (and (pair? transformer) (list-of symbol? transformer))
  2965. (error "expected transformer to be a module name" transformer))
  2966. (let ((iface (resolve-interface transformer))
  2967. (sym (car (last-pair transformer))))
  2968. (set-module-transformer! module (module-ref iface sym))))
  2969. (when inlinable-exports
  2970. (unless (procedure? inlinable-exports)
  2971. (error "expected inlinable-exports to be a procedure" inlinable-exports))
  2972. (set-module-inlinable-exports! (module-public-interface module)
  2973. inlinable-exports))
  2974. (run-hook module-defined-hook module)
  2975. module))
  2976. ;; `module-defined-hook' is a hook that is run whenever a new module
  2977. ;; is defined. Its members are called with one argument, the new
  2978. ;; module.
  2979. (define module-defined-hook (make-hook 1))
  2980. ;;; {Autoload}
  2981. ;;;
  2982. (define (make-autoload-interface module name bindings)
  2983. (let ((b (lambda (a sym definep)
  2984. (false-if-exception
  2985. (and (memq sym bindings)
  2986. (let ((i (resolve-interface name #:select bindings)))
  2987. (unless i
  2988. (error "missing interface for module" name))
  2989. (let ((uses (memq a (module-uses module))))
  2990. (when uses
  2991. ;; Replace autoload-interface with actual
  2992. ;; interface.
  2993. (set-car! uses i)))
  2994. (for-each
  2995. (lambda (name)
  2996. (when (hashq-ref (module-replacements i) name)
  2997. (hashq-set! (module-replacements a) name #t)))
  2998. bindings)
  2999. (or (module-local-variable i sym)
  3000. (error "binding not presentin module" name sym))))
  3001. #:warning "Failed to autoload ~a in ~a:\n" sym name))))
  3002. (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
  3003. (make-hash-table 0) '() (make-weak-value-hash-table) #f
  3004. (make-hash-table 0) #f #f #f 0 (make-hash-table 0) #f)))
  3005. (define (module-autoload! module . args)
  3006. "Have @var{module} automatically load the module named @var{name} when one
  3007. of the symbols listed in @var{bindings} is looked up. @var{args} should be a
  3008. list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
  3009. module '(ice-9 q) '(make-q q-length))}."
  3010. (let loop ((args args))
  3011. (cond ((null? args)
  3012. #t)
  3013. ((null? (cdr args))
  3014. (error "invalid name+binding autoload list" args))
  3015. (else
  3016. (let ((name (car args))
  3017. (bindings (cadr args)))
  3018. (module-use! module (make-autoload-interface module
  3019. name bindings))
  3020. (loop (cddr args)))))))
  3021. ;;; {Autoloading modules}
  3022. ;;;
  3023. (define autoloads-in-progress '())
  3024. ;; This function is called from scm_load_scheme_module in
  3025. ;; "deprecated.c". Please do not change its interface.
  3026. ;;
  3027. (define* (try-module-autoload module-name #:optional version)
  3028. "Try to load a module of the given name. If it is not found, return
  3029. #f. Otherwise return #t. May raise an exception if a file is found,
  3030. but it fails to load."
  3031. (let* ((reverse-name (reverse module-name))
  3032. (name (symbol->string (car reverse-name)))
  3033. (dir-hint-module-name (reverse (cdr reverse-name)))
  3034. (dir-hint (apply string-append
  3035. (map (lambda (elt)
  3036. (string-append (symbol->string elt)
  3037. file-name-separator-string))
  3038. dir-hint-module-name))))
  3039. (resolve-module dir-hint-module-name #f)
  3040. (call-with-module-autoload-lock
  3041. (lambda ()
  3042. (and (not (autoload-done-or-in-progress? dir-hint name))
  3043. (let ((didit #f))
  3044. (dynamic-wind
  3045. (lambda () (autoload-in-progress! dir-hint name))
  3046. (lambda ()
  3047. (with-fluids ((current-reader #f))
  3048. (save-module-excursion
  3049. (lambda ()
  3050. (define (call/ec proc)
  3051. (let ((tag (make-prompt-tag)))
  3052. (call-with-prompt
  3053. tag
  3054. (lambda ()
  3055. (proc (lambda () (abort-to-prompt tag))))
  3056. (lambda (k) (values)))))
  3057. ;; The initial environment when loading a module is a fresh
  3058. ;; user module.
  3059. (set-current-module (make-fresh-user-module))
  3060. ;; Here we could allow some other search strategy (other than
  3061. ;; primitive-load-path), for example using versions encoded
  3062. ;; into the file system -- but then we would have to figure
  3063. ;; out how to locate the compiled file, do auto-compilation,
  3064. ;; etc. Punt for now, and don't use versions when locating
  3065. ;; the file.
  3066. (call/ec
  3067. (lambda (abort)
  3068. (primitive-load-path (in-vicinity dir-hint name)
  3069. abort)
  3070. (set! didit #t)))))))
  3071. (lambda () (set-autoloaded! dir-hint name didit)))
  3072. didit))))))
  3073. ;;; {Dynamic linking of modules}
  3074. ;;;
  3075. (define autoloads-done '((guile . guile)))
  3076. (define (autoload-done-or-in-progress? p m)
  3077. (let ((n (cons p m)))
  3078. (->bool (or (member n autoloads-done)
  3079. (member n autoloads-in-progress)))))
  3080. (define (autoload-done! p m)
  3081. (let ((n (cons p m)))
  3082. (set! autoloads-in-progress
  3083. (delete! n autoloads-in-progress))
  3084. (or (member n autoloads-done)
  3085. (set! autoloads-done (cons n autoloads-done)))))
  3086. (define (autoload-in-progress! p m)
  3087. (let ((n (cons p m)))
  3088. (set! autoloads-done
  3089. (delete! n autoloads-done))
  3090. (set! autoloads-in-progress (cons n autoloads-in-progress))))
  3091. (define (set-autoloaded! p m done?)
  3092. (if done?
  3093. (autoload-done! p m)
  3094. (let ((n (cons p m)))
  3095. (set! autoloads-done (delete! n autoloads-done))
  3096. (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
  3097. ;;; {Run-time options}
  3098. ;;;
  3099. (define-syntax define-option-interface
  3100. (syntax-rules ()
  3101. ((_ (interface (options enable disable) (option-set!)))
  3102. (begin
  3103. (define options
  3104. (case-lambda
  3105. (() (interface))
  3106. ((arg)
  3107. (if (list? arg)
  3108. (begin (interface arg) (interface))
  3109. (for-each
  3110. (lambda (option)
  3111. (apply (lambda (name value documentation)
  3112. (display name)
  3113. (let ((len (string-length (symbol->string name))))
  3114. (when (< len 16)
  3115. (display #\tab)
  3116. (when (< len 8)
  3117. (display #\tab))))
  3118. (display #\tab)
  3119. (display value)
  3120. (display #\tab)
  3121. (display documentation)
  3122. (newline))
  3123. option))
  3124. (interface #t))))))
  3125. (define (enable . flags)
  3126. (interface (append flags (interface)))
  3127. (interface))
  3128. (define (disable . flags)
  3129. (let ((options (interface)))
  3130. (for-each (lambda (flag) (set! options (delq! flag options)))
  3131. flags)
  3132. (interface options)
  3133. (interface)))
  3134. (define-syntax-rule (option-set! opt val)
  3135. (eval-when (expand load eval)
  3136. (options (append (options) (list 'opt val)))))))))
  3137. (define-option-interface
  3138. (debug-options-interface
  3139. (debug-options debug-enable debug-disable)
  3140. (debug-set!)))
  3141. (define-option-interface
  3142. (read-options-interface
  3143. (read-options read-enable read-disable)
  3144. (read-set!)))
  3145. (define-option-interface
  3146. (print-options-interface
  3147. (print-options print-enable print-disable)
  3148. (print-set!)))
  3149. ;;; {The Unspecified Value}
  3150. ;;;
  3151. ;;; Currently Guile represents unspecified values via one particular value,
  3152. ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
  3153. ;;; future if we could replace this with a return of 0 values, though.
  3154. ;;;
  3155. (define-syntax *unspecified*
  3156. (identifier-syntax (if #f #f)))
  3157. (define (unspecified? v) (eq? v *unspecified*))
  3158. ;;; {Running Repls}
  3159. ;;;
  3160. (define *repl-stack* (make-fluid '()))
  3161. ;; Programs can call `batch-mode?' to see if they are running as part of a
  3162. ;; script or if they are running interactively. REPL implementations ensure that
  3163. ;; `batch-mode?' returns #f during their extent.
  3164. ;;
  3165. (define (batch-mode?)
  3166. (null? (fluid-ref *repl-stack*)))
  3167. ;; Programs can re-enter batch mode, for example after a fork, by calling
  3168. ;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
  3169. ;; to abort to the outermost prompt, and call a thunk there.
  3170. ;;
  3171. (define (ensure-batch-mode!)
  3172. (set! batch-mode? (lambda () #t)))
  3173. (define (quit . args)
  3174. (apply throw 'quit args))
  3175. (define exit quit)
  3176. (define (gc-run-time)
  3177. (cdr (assq 'gc-time-taken (gc-stats))))
  3178. (define abort-hook (make-hook))
  3179. (define before-error-hook (make-hook))
  3180. (define after-error-hook (make-hook))
  3181. (define before-backtrace-hook (make-hook))
  3182. (define after-backtrace-hook (make-hook))
  3183. (define before-read-hook (make-hook))
  3184. (define after-read-hook (make-hook))
  3185. (define before-eval-hook (make-hook 1))
  3186. (define after-eval-hook (make-hook 1))
  3187. (define before-print-hook (make-hook 1))
  3188. (define after-print-hook (make-hook 1))
  3189. ;;; This hook is run at the very end of an interactive session.
  3190. ;;;
  3191. (define exit-hook (make-hook))
  3192. ;;; The default repl-reader function. We may override this if we've
  3193. ;;; the readline library.
  3194. (define repl-reader
  3195. (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
  3196. (if (not (char-ready?))
  3197. (begin
  3198. (display (if (string? prompt) prompt (prompt)))
  3199. ;; An interesting situation. The printer resets the column to
  3200. ;; 0 by printing a newline, but we then advance it by printing
  3201. ;; the prompt. However the port-column of the output port
  3202. ;; does not typically correspond with the actual column on the
  3203. ;; screen, because the input is echoed back! Since the
  3204. ;; input is line-buffered and thus ends with a newline, the
  3205. ;; output will really start on column zero. So, here we zero
  3206. ;; it out. See bug 9664.
  3207. ;;
  3208. ;; Note that for similar reasons, the output-line will not
  3209. ;; reflect the actual line on the screen. But given the
  3210. ;; possibility of multiline input, the fix is not as
  3211. ;; straightforward, so we don't bother.
  3212. ;;
  3213. ;; Also note that the readline implementation papers over
  3214. ;; these concerns, because it's readline itself printing the
  3215. ;; prompt, and not Guile.
  3216. (set-port-column! (current-output-port) 0)))
  3217. (force-output)
  3218. (run-hook before-read-hook)
  3219. ((or reader read) (current-input-port))))
  3220. ;;; {While}
  3221. ;;;
  3222. ;;; with `continue' and `break'.
  3223. ;;;
  3224. ;; The inliner will remove the prompts at compile-time if it finds that
  3225. ;; `continue' or `break' are not used.
  3226. ;;
  3227. (define-syntax while
  3228. (lambda (x)
  3229. (syntax-case x ()
  3230. ((while cond body ...)
  3231. #`(let ((break-tag (make-prompt-tag "break"))
  3232. (continue-tag (make-prompt-tag "continue")))
  3233. (call-with-prompt
  3234. break-tag
  3235. (lambda ()
  3236. (define-syntax #,(datum->syntax #'while 'break)
  3237. (lambda (x)
  3238. (syntax-case x ()
  3239. ((_ arg (... ...))
  3240. #'(abort-to-prompt break-tag arg (... ...)))
  3241. (_
  3242. #'(lambda args
  3243. (apply abort-to-prompt break-tag args))))))
  3244. (let lp ()
  3245. (call-with-prompt
  3246. continue-tag
  3247. (lambda ()
  3248. (define-syntax #,(datum->syntax #'while 'continue)
  3249. (lambda (x)
  3250. (syntax-case x ()
  3251. ((_)
  3252. #'(abort-to-prompt continue-tag))
  3253. ((_ . args)
  3254. (syntax-violation 'continue "too many arguments" x))
  3255. (_
  3256. #'(lambda ()
  3257. (abort-to-prompt continue-tag))))))
  3258. (do () ((not cond) #f) body ...))
  3259. (lambda (k) (lp)))))
  3260. (lambda (k . args)
  3261. (if (null? args)
  3262. #t
  3263. (apply values args)))))))))
  3264. ;;; {Module System Macros}
  3265. ;;;
  3266. ;; Return a list of expressions that evaluate to the appropriate
  3267. ;; arguments for resolve-interface according to SPEC.
  3268. (eval-when (expand)
  3269. (if (memq 'prefix (read-options))
  3270. (error "boot-9 must be compiled with #:kw, not :kw")))
  3271. (define (keyword-like-symbol->keyword sym)
  3272. (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
  3273. (define-syntax define-module
  3274. (lambda (x)
  3275. (define (keyword-like? stx)
  3276. (let ((dat (syntax->datum stx)))
  3277. (and (symbol? dat)
  3278. (eqv? (string-ref (symbol->string dat) 0) #\:))))
  3279. (define (->keyword sym)
  3280. (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
  3281. (define (parse-iface args)
  3282. (let loop ((in args) (out '()))
  3283. (syntax-case in ()
  3284. (() (reverse! out))
  3285. ;; The user wanted #:foo, but wrote :foo. Fix it.
  3286. ((sym . in) (keyword-like? #'sym)
  3287. (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
  3288. ((kw . in) (not (keyword? (syntax->datum #'kw)))
  3289. (syntax-violation 'define-module "expected keyword arg" x #'kw))
  3290. ((#:renamer renamer . in)
  3291. (loop #'in (cons* #',renamer #:renamer out)))
  3292. ((kw val . in)
  3293. (loop #'in (cons* #'val #'kw out))))))
  3294. (define (parse args imp exp rex rep rxp aut dec)
  3295. ;; Just quote everything except #:use-module and #:use-syntax. We
  3296. ;; need to know about all arguments regardless since we want to turn
  3297. ;; symbols that look like keywords into real keywords, and the
  3298. ;; keyword args in a define-module form are not regular
  3299. ;; (i.e. no-backtrace doesn't take a value).
  3300. (syntax-case args ()
  3301. (()
  3302. (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
  3303. (exp (if (null? exp) '() #`(#:exports '#,exp)))
  3304. (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
  3305. (rep (if (null? rep) '() #`(#:replacements '#,rep)))
  3306. (rxp (if (null? rxp) '() #`(#:re-export-replacements '#,rxp)))
  3307. (aut (if (null? aut) '() #`(#:autoloads '#,aut)))
  3308. (dec (if dec '() #`(#:declarative?
  3309. #,(user-modules-declarative?)))))
  3310. #`(#,@imp #,@exp #,@rex #,@rep #,@rxp #,@aut #,@dec)))
  3311. ;; The user wanted #:foo, but wrote :foo. Fix it.
  3312. ((sym . args) (keyword-like? #'sym)
  3313. (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
  3314. imp exp rex rep rxp aut dec))
  3315. ((kw . args) (not (keyword? (syntax->datum #'kw)))
  3316. (syntax-violation 'define-module "expected keyword arg" x #'kw))
  3317. ((#:no-backtrace . args)
  3318. ;; Ignore this one.
  3319. (parse #'args imp exp rex rep rxp aut dec))
  3320. ((#:pure . args)
  3321. #`(#:pure #t . #,(parse #'args imp exp rex rep rxp aut dec)))
  3322. ((kw)
  3323. (syntax-violation 'define-module "keyword arg without value" x #'kw))
  3324. ((#:version (v ...) . args)
  3325. #`(#:version '(v ...) . #,(parse #'args imp exp rex rep rxp aut dec)))
  3326. ((#:duplicates (d ...) . args)
  3327. #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep rxp aut dec)))
  3328. ((#:filename f . args)
  3329. #`(#:filename 'f . #,(parse #'args imp exp rex rep rxp aut dec)))
  3330. ((#:declarative? d . args)
  3331. #`(#:declarative? 'd . #,(parse #'args imp exp rex rep rxp aut #t)))
  3332. ((#:use-module (name name* ...) . args)
  3333. (and (and-map symbol? (syntax->datum #'(name name* ...))))
  3334. (parse #'args #`(#,@imp ((name name* ...))) exp rex rep rxp aut dec))
  3335. ((#:use-syntax (name name* ...) . args)
  3336. (and (and-map symbol? (syntax->datum #'(name name* ...))))
  3337. #`(#:transformer '(name name* ...)
  3338. . #,(parse #'args #`(#,@imp ((name name* ...))) exp rex
  3339. rep rxp aut dec)))
  3340. ((#:use-module ((name name* ...) arg ...) . args)
  3341. (and (and-map symbol? (syntax->datum #'(name name* ...))))
  3342. (parse #'args
  3343. #`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
  3344. exp rex rep rxp aut dec))
  3345. ((#:export (ex ...) . args)
  3346. (parse #'args imp #`(#,@exp ex ...) rex rep rxp aut dec))
  3347. ((#:export-syntax (ex ...) . args)
  3348. (parse #'args imp #`(#,@exp ex ...) rex rep rxp aut dec))
  3349. ((#:re-export (re ...) . args)
  3350. (parse #'args imp exp #`(#,@rex re ...) rep rxp aut dec))
  3351. ((#:re-export-syntax (re ...) . args)
  3352. (parse #'args imp exp #`(#,@rex re ...) rep rxp aut dec))
  3353. ((#:replace (r ...) . args)
  3354. (parse #'args imp exp rex #`(#,@rep r ...) rxp aut dec))
  3355. ((#:replace-syntax (r ...) . args)
  3356. (parse #'args imp exp rex #`(#,@rep r ...) rxp aut dec))
  3357. ((#:re-export-and-replace (r ...) . args)
  3358. (parse #'args imp exp rex rep #`(#,@rxp r ...) aut dec))
  3359. ((#:autoload name bindings . args)
  3360. (parse #'args imp exp rex rep rxp #`(#,@aut name bindings) dec))
  3361. ((kw val . args)
  3362. (syntax-violation 'define-module "unknown keyword or bad argument"
  3363. #'kw #'val))))
  3364. (syntax-case x ()
  3365. ((_ (name name* ...) arg ...)
  3366. (and-map symbol? (syntax->datum #'(name name* ...)))
  3367. (with-syntax (((quoted-arg ...)
  3368. (parse #'(arg ...) '() '() '() '() '() '() #f))
  3369. ;; Ideally the filename is either a string or #f;
  3370. ;; this hack is to work around a case in which
  3371. ;; port-filename returns a symbol (`socket') for
  3372. ;; sockets.
  3373. (filename (let ((f (assq-ref (or (syntax-source x) '())
  3374. 'filename)))
  3375. (and (string? f) f))))
  3376. #'(eval-when (expand load eval)
  3377. (let ((m (define-module* '(name name* ...)
  3378. #:filename filename quoted-arg ...)))
  3379. (set-current-module m)
  3380. m)))))))
  3381. ;; The guts of the use-modules macro. Add the interfaces of the named
  3382. ;; modules to the use-list of the current module, in order.
  3383. ;; This function is called by "modules.c". If you change it, be sure
  3384. ;; to change scm_c_use_module as well.
  3385. (define (process-use-modules module-interface-args)
  3386. (let ((interfaces (map (lambda (mif-args)
  3387. (or (apply resolve-interface mif-args)
  3388. (error "no such module" mif-args)))
  3389. module-interface-args)))
  3390. (call-with-deferred-observers
  3391. (lambda ()
  3392. (module-use-interfaces! (current-module) interfaces)))))
  3393. (define-syntax use-modules
  3394. (lambda (x)
  3395. (define (keyword-like? stx)
  3396. (let ((dat (syntax->datum stx)))
  3397. (and (symbol? dat)
  3398. (eqv? (string-ref (symbol->string dat) 0) #\:))))
  3399. (define (->keyword sym)
  3400. (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
  3401. (define (quotify-iface args)
  3402. (let loop ((in args) (out '()))
  3403. (syntax-case in ()
  3404. (() (reverse! out))
  3405. ;; The user wanted #:foo, but wrote :foo. Fix it.
  3406. ((sym . in) (keyword-like? #'sym)
  3407. (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
  3408. ((kw . in) (not (keyword? (syntax->datum #'kw)))
  3409. (syntax-violation 'define-module "expected keyword arg" x #'kw))
  3410. ((#:renamer renamer . in)
  3411. (loop #'in (cons* #'renamer #:renamer out)))
  3412. ((kw val . in)
  3413. (loop #'in (cons* #''val #'kw out))))))
  3414. (define (quotify specs)
  3415. (let lp ((in specs) (out '()))
  3416. (syntax-case in ()
  3417. (() (reverse out))
  3418. (((name name* ...) . in)
  3419. (and-map symbol? (syntax->datum #'(name name* ...)))
  3420. (lp #'in (cons #''((name name* ...)) out)))
  3421. ((((name name* ...) arg ...) . in)
  3422. (and-map symbol? (syntax->datum #'(name name* ...)))
  3423. (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
  3424. (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
  3425. out)))))))
  3426. (syntax-case x ()
  3427. ((_ spec ...)
  3428. (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
  3429. #'(eval-when (expand load eval)
  3430. (process-use-modules (list quoted-args ...))
  3431. *unspecified*))))))
  3432. (include-from-path "ice-9/r6rs-libraries")
  3433. (include-from-path "ice-9/r7rs-libraries")
  3434. (define-syntax-rule (define-private foo bar)
  3435. (define foo bar))
  3436. (define-syntax define-public
  3437. (syntax-rules ()
  3438. ((_ (name . args) . body)
  3439. (begin
  3440. (define (name . args) . body)
  3441. (export name)))
  3442. ((_ name val)
  3443. (begin
  3444. (define name val)
  3445. (export name)))))
  3446. (define-syntax-rule (defmacro-public name args body ...)
  3447. (begin
  3448. (defmacro name args body ...)
  3449. (export-syntax name)))
  3450. ;; And now for the most important macro.
  3451. (define-syntax-rule (λ formals body ...)
  3452. (lambda formals body ...))
  3453. ;; This function is called from "modules.c". If you change it, be
  3454. ;; sure to update "modules.c" as well.
  3455. (define* (module-export! m names #:key replace?)
  3456. "Export a local variable."
  3457. (let ((public-i (module-public-interface m)))
  3458. (for-each (lambda (name)
  3459. (let* ((internal-name (if (pair? name) (car name) name))
  3460. (external-name (if (pair? name) (cdr name) name))
  3461. (var (module-ensure-local-variable! m internal-name)))
  3462. (when replace?
  3463. (hashq-set! (module-replacements public-i) external-name #t))
  3464. (module-add! public-i external-name var)))
  3465. names)))
  3466. (define (module-replace! m names)
  3467. (module-export! m names #:replace? #t))
  3468. (define (module-export-all! mod)
  3469. "Export all local variables from a module."
  3470. (define (fresh-interface!)
  3471. (let ((iface (make-module)))
  3472. (set-module-name! iface (module-name mod))
  3473. (set-module-version! iface (module-version mod))
  3474. (set-module-kind! iface 'interface)
  3475. (set-module-public-interface! mod iface)
  3476. iface))
  3477. (let ((iface (or (module-public-interface mod)
  3478. (fresh-interface!))))
  3479. (set-module-obarray! iface (module-obarray mod))))
  3480. (define* (module-re-export! m names #:key replace?)
  3481. "Re-export an imported variable."
  3482. (let ((public-i (module-public-interface m)))
  3483. (for-each
  3484. (lambda (name)
  3485. (let* ((internal-name (if (pair? name) (car name) name))
  3486. (external-name (if (pair? name) (cdr name) name))
  3487. (var (module-variable m internal-name)))
  3488. (cond
  3489. ((not var)
  3490. (error "Undefined variable:" internal-name))
  3491. ((eq? var (module-local-variable m internal-name))
  3492. (error "re-exporting local variable:" internal-name))
  3493. (else
  3494. (when replace?
  3495. (hashq-set! (module-replacements public-i) external-name #t))
  3496. (module-add! public-i external-name var)))))
  3497. names)))
  3498. (define-syntax-rule (export name ...)
  3499. (eval-when (expand load eval)
  3500. (call-with-deferred-observers
  3501. (lambda ()
  3502. (module-export! (current-module) '(name ...))))))
  3503. (define-syntax-rule (re-export name ...)
  3504. (eval-when (expand load eval)
  3505. (call-with-deferred-observers
  3506. (lambda ()
  3507. (module-re-export! (current-module) '(name ...))))))
  3508. (define-syntax-rule (export! name ...)
  3509. (eval-when (expand load eval)
  3510. (call-with-deferred-observers
  3511. (lambda ()
  3512. (module-replace! (current-module) '(name ...))))))
  3513. (define-syntax-rule (export-syntax name ...)
  3514. (export name ...))
  3515. (define-syntax-rule (re-export-syntax name ...)
  3516. (re-export name ...))
  3517. ;;; {Parameters}
  3518. ;;;
  3519. (define* (make-mutable-parameter init #:optional (converter identity))
  3520. (let ((fluid (make-fluid (converter init))))
  3521. (case-lambda
  3522. (() (fluid-ref fluid))
  3523. ((val) (fluid-set! fluid (converter val))))))
  3524. ;;; {Handling of duplicate imported bindings}
  3525. ;;;
  3526. ;; Duplicate handlers take the following arguments:
  3527. ;;
  3528. ;; module importing module
  3529. ;; name conflicting name
  3530. ;; int1 old interface where name occurs
  3531. ;; val1 value of binding in old interface
  3532. ;; int2 new interface where name occurs
  3533. ;; val2 value of binding in new interface
  3534. ;; var previous resolution or #f
  3535. ;; val value of previous resolution
  3536. ;;
  3537. ;; A duplicate handler can take three alternative actions:
  3538. ;;
  3539. ;; 1. return #f => leave responsibility to next handler
  3540. ;; 2. exit with an error
  3541. ;; 3. return a variable resolving the conflict
  3542. ;;
  3543. (define duplicate-handlers
  3544. (let ((m (make-module)))
  3545. (define (check module name int1 val1 int2 val2 var val)
  3546. (scm-error 'misc-error
  3547. #f
  3548. "~A: `~A' imported from both ~A and ~A"
  3549. (list (module-name module)
  3550. name
  3551. (module-name int1)
  3552. (module-name int2))
  3553. #f))
  3554. (define (warn module name int1 val1 int2 val2 var val)
  3555. (format (current-warning-port)
  3556. "WARNING: ~A: `~A' imported from both ~A and ~A\n"
  3557. (module-name module)
  3558. name
  3559. (module-name int1)
  3560. (module-name int2))
  3561. #f)
  3562. (define (replace module name int1 val1 int2 val2 var val)
  3563. (let* ((replace1 (hashq-ref (module-replacements int1) name))
  3564. (replace2 (hashq-ref (module-replacements int2) name))
  3565. (old (or (and replace1 var)
  3566. (module-variable int1 name)))
  3567. (new (module-variable int2 name)))
  3568. (if replace1
  3569. (and (or (eq? old new) (not replace2))
  3570. old)
  3571. (and replace2 new))))
  3572. (define (warn-override-core module name int1 val1 int2 val2 var val)
  3573. (and (eq? int1 the-scm-module)
  3574. (begin
  3575. (format (current-warning-port)
  3576. "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
  3577. (module-name module)
  3578. (module-name int2)
  3579. name)
  3580. (module-variable int2 name))))
  3581. (define (first module name int1 val1 int2 val2 var val)
  3582. (or var (module-variable int1 name)))
  3583. (define (last module name int1 val1 int2 val2 var val)
  3584. (module-variable int2 name))
  3585. (define (noop module name int1 val1 int2 val2 var val)
  3586. #f)
  3587. (set-module-name! m 'duplicate-handlers)
  3588. (set-module-kind! m 'interface)
  3589. (module-define! m 'check check)
  3590. (module-define! m 'warn warn)
  3591. (module-define! m 'replace replace)
  3592. (module-define! m 'warn-override-core warn-override-core)
  3593. (module-define! m 'first first)
  3594. (module-define! m 'last last)
  3595. (module-define! m 'merge-generics noop)
  3596. (module-define! m 'merge-accessors noop)
  3597. m))
  3598. (define (lookup-duplicates-handlers handler-names)
  3599. (and handler-names
  3600. (map (lambda (handler-name)
  3601. (or (module-symbol-local-binding
  3602. duplicate-handlers handler-name #f)
  3603. (error "invalid duplicate handler name:"
  3604. handler-name)))
  3605. (if (list? handler-names)
  3606. handler-names
  3607. (list handler-names)))))
  3608. (define default-duplicate-binding-procedures
  3609. (case-lambda
  3610. (()
  3611. (or (module-duplicates-handlers (current-module))
  3612. ;; Note: If you change this default, change it also in
  3613. ;; `define-module*'.
  3614. (lookup-duplicates-handlers
  3615. '(replace warn-override-core warn last))))
  3616. ((procs)
  3617. (set-module-duplicates-handlers! (current-module) procs))))
  3618. (define default-duplicate-binding-handler
  3619. (case-lambda
  3620. (()
  3621. (map procedure-name (default-duplicate-binding-procedures)))
  3622. ((handlers)
  3623. (default-duplicate-binding-procedures
  3624. (lookup-duplicates-handlers handlers)))))
  3625. ;;; {`load'.}
  3626. ;;;
  3627. ;;; Load is tricky when combined with relative file names, compilation,
  3628. ;;; and the file system. If a file name is relative, what is it
  3629. ;;; relative to? The name of the source file at the time it was
  3630. ;;; compiled? The name of the compiled file? What if both or either
  3631. ;;; were installed? And how do you get that information? Tricky, I
  3632. ;;; say.
  3633. ;;;
  3634. ;;; To get around all of this, we're going to do something nasty, and
  3635. ;;; turn `load' into a macro. That way it can know the name of the
  3636. ;;; source file with respect to which it was invoked, so it can resolve
  3637. ;;; relative file names with respect to the original source file.
  3638. ;;;
  3639. ;;; There is an exception, and that is that if the source file was in
  3640. ;;; the load path when it was compiled, instead of looking up against
  3641. ;;; the absolute source location, we load-from-path against the relative
  3642. ;;; source location.
  3643. ;;;
  3644. (define %auto-compilation-options
  3645. ;; Default `compile-file' option when auto-compiling.
  3646. '(#:warnings (shadowed-toplevel use-before-definition arity-mismatch
  3647. format duplicate-case-datum bad-case-datum
  3648. non-idempotent-definition)))
  3649. (define* (load-in-vicinity dir file-name #:optional reader)
  3650. "Load source file FILE-NAME in vicinity of directory DIR. Use a
  3651. pre-compiled version of FILE-NAME when available, and auto-compile one
  3652. when none is available, reading FILE-NAME with READER."
  3653. ;; The auto-compilation code will residualize a .go file in the cache
  3654. ;; dir: by default, $HOME/.cache/guile/2.0/ccache/PATH.go. This
  3655. ;; function determines the PATH to use as a key into the compilation
  3656. ;; cache.
  3657. (define (canonical->suffix canon)
  3658. (cond
  3659. ((and (not (string-null? canon))
  3660. (file-name-separator? (string-ref canon 0)))
  3661. canon)
  3662. ((and (eq? (system-file-name-convention) 'windows)
  3663. (absolute-file-name? canon))
  3664. ;; An absolute file name that doesn't start with a separator
  3665. ;; starts with a drive component. Transform the drive component
  3666. ;; to a file name element: c:\foo -> \c\foo.
  3667. (string-append file-name-separator-string
  3668. (substring canon 0 1)
  3669. (substring canon 2)))
  3670. (else canon)))
  3671. (define compiled-extension
  3672. ;; File name extension of compiled files.
  3673. (cond ((or (null? %load-compiled-extensions)
  3674. (string-null? (car %load-compiled-extensions)))
  3675. (warn "invalid %load-compiled-extensions"
  3676. %load-compiled-extensions)
  3677. ".go")
  3678. (else (car %load-compiled-extensions))))
  3679. (define (more-recent? stat1 stat2)
  3680. ;; Return #t when STAT1 has an mtime greater than that of STAT2.
  3681. (or (> (stat:mtime stat1) (stat:mtime stat2))
  3682. (and (= (stat:mtime stat1) (stat:mtime stat2))
  3683. (>= (stat:mtimensec stat1)
  3684. (stat:mtimensec stat2)))))
  3685. (define (fallback-file-name canon-file-name)
  3686. ;; Return the in-cache compiled file name for source file
  3687. ;; CANON-FILE-NAME.
  3688. ;; FIXME: would probably be better just to append
  3689. ;; SHA1(canon-file-name) to the %compile-fallback-path, to avoid
  3690. ;; deep directory stats.
  3691. (and %compile-fallback-path
  3692. (string-append %compile-fallback-path
  3693. (canonical->suffix canon-file-name)
  3694. compiled-extension)))
  3695. (define (compile file)
  3696. ;; Compile source FILE, lazily loading the compiler.
  3697. ((module-ref (resolve-interface '(system base compile))
  3698. 'compile-file)
  3699. file
  3700. #:opts %auto-compilation-options
  3701. #:env (current-module)))
  3702. (define (load-thunk-from-file file)
  3703. (let ((loader (resolve-interface '(system vm loader))))
  3704. ((module-ref loader 'load-thunk-from-file) file)))
  3705. ;; Returns a thunk loaded from the .go file corresponding to `name'.
  3706. ;; Does not search load paths, only the fallback path. If the .go
  3707. ;; file is missing or out of date, and auto-compilation is enabled,
  3708. ;; will try auto-compilation, just as primitive-load-path does
  3709. ;; internally. primitive-load is unaffected. Returns #f if
  3710. ;; auto-compilation failed or was disabled.
  3711. ;;
  3712. ;; NB: Unless we need to compile the file, this function should not
  3713. ;; cause (system base compile) to be loaded up. For that reason
  3714. ;; compiled-file-name partially duplicates functionality from (system
  3715. ;; base compile).
  3716. (define (fresh-compiled-thunk name scmstat go-file-name)
  3717. ;; Return GO-FILE-NAME after making sure that it contains a freshly
  3718. ;; compiled version of source file NAME with stat SCMSTAT; return #f
  3719. ;; on failure.
  3720. (false-if-exception
  3721. (let ((gostat (and (not %fresh-auto-compile)
  3722. (stat go-file-name #f))))
  3723. (if (and gostat (more-recent? gostat scmstat))
  3724. (load-thunk-from-file go-file-name)
  3725. (begin
  3726. (when gostat
  3727. (format (current-info-port)
  3728. ";;; note: source file ~a\n;;; newer than compiled ~a\n"
  3729. name go-file-name))
  3730. (cond
  3731. (%load-should-auto-compile
  3732. (%warn-auto-compilation-enabled)
  3733. (format (current-info-port) ";;; compiling ~a\n" name)
  3734. (let ((cfn (compile name)))
  3735. (format (current-info-port) ";;; compiled ~a\n" cfn)
  3736. (load-thunk-from-file cfn)))
  3737. (else #f)))))
  3738. #:warning "WARNING: compilation of ~a failed:\n" name))
  3739. (define (sans-extension file)
  3740. (let ((dot (string-rindex file #\.)))
  3741. (if dot
  3742. (substring file 0 dot)
  3743. file)))
  3744. (define (load-absolute abs-file-name)
  3745. ;; Load from ABS-FILE-NAME, using a compiled file or auto-compiling
  3746. ;; if needed.
  3747. (define scmstat
  3748. (false-if-exception
  3749. (stat abs-file-name)
  3750. #:warning "Stat of ~a failed:\n" abs-file-name))
  3751. (define (pre-compiled)
  3752. (or-map
  3753. (lambda (dir)
  3754. (or-map
  3755. (lambda (ext)
  3756. (let ((candidate (string-append (in-vicinity dir file-name) ext)))
  3757. (let ((gostat (stat candidate #f)))
  3758. (and gostat
  3759. (more-recent? gostat scmstat)
  3760. (false-if-exception
  3761. (load-thunk-from-file candidate)
  3762. #:warning "WARNING: failed to load compiled file ~a:\n"
  3763. candidate)))))
  3764. %load-compiled-extensions))
  3765. %load-compiled-path))
  3766. (define (fallback)
  3767. (and=> (false-if-exception (canonicalize-path abs-file-name))
  3768. (lambda (canon)
  3769. (and=> (fallback-file-name canon)
  3770. (lambda (go-file-name)
  3771. (fresh-compiled-thunk abs-file-name
  3772. scmstat
  3773. go-file-name))))))
  3774. (let ((compiled (and scmstat (or (pre-compiled) (fallback)))))
  3775. (if compiled
  3776. (begin
  3777. (if %load-hook
  3778. (%load-hook abs-file-name))
  3779. (compiled))
  3780. (start-stack 'load-stack
  3781. (primitive-load abs-file-name)))))
  3782. (save-module-excursion
  3783. (lambda ()
  3784. (with-fluids ((current-reader reader)
  3785. (%file-port-name-canonicalization 'relative))
  3786. (cond
  3787. ((absolute-file-name? file-name)
  3788. (load-absolute file-name))
  3789. ((absolute-file-name? dir)
  3790. (load-absolute (in-vicinity dir file-name)))
  3791. (else
  3792. (load-from-path (in-vicinity dir file-name))))))))
  3793. (define-syntax load
  3794. (make-variable-transformer
  3795. (lambda (x)
  3796. (let* ((src (syntax-source x))
  3797. (file (and src (assq-ref src 'filename)))
  3798. (dir (and (string? file) (dirname file))))
  3799. ;; A module that uses `load' is not declarative.
  3800. (when (module-declarative? (current-module))
  3801. (format (current-warning-port)
  3802. "WARNING: Use of `load' in declarative module ~A. ~A\n"
  3803. (module-name (current-module))
  3804. "Add #:declarative? #f to your define-module invocation.")
  3805. (set-module-declarative?! (current-module) #f))
  3806. (syntax-case x ()
  3807. ((_ arg ...)
  3808. #`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
  3809. (id
  3810. (identifier? #'id)
  3811. #`(lambda args
  3812. (apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
  3813. ;;; {`cond-expand' for SRFI-0 support.}
  3814. ;;;
  3815. ;;; This syntactic form expands into different commands or
  3816. ;;; definitions, depending on the features provided by the Scheme
  3817. ;;; implementation.
  3818. ;;;
  3819. ;;; Syntax:
  3820. ;;;
  3821. ;;; <cond-expand>
  3822. ;;; --> (cond-expand <cond-expand-clause>+)
  3823. ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
  3824. ;;; <cond-expand-clause>
  3825. ;;; --> (<feature-requirement> <command-or-definition>*)
  3826. ;;; <feature-requirement>
  3827. ;;; --> <feature-identifier>
  3828. ;;; | (and <feature-requirement>*)
  3829. ;;; | (or <feature-requirement>*)
  3830. ;;; | (not <feature-requirement>)
  3831. ;;; <feature-identifier>
  3832. ;;; --> <a symbol which is the name or alias of a SRFI>
  3833. ;;;
  3834. ;;; Additionally, this implementation provides the
  3835. ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
  3836. ;;; determine the implementation type and the supported standard.
  3837. ;;;
  3838. ;;; Remember to update the features list when adding more SRFIs.
  3839. ;;;
  3840. (define %cond-expand-features
  3841. ;; This should contain only features that are present in core Guile,
  3842. ;; before loading any modules. Modular features are handled by
  3843. ;; placing 'cond-expand-provide' in the relevant module.
  3844. '(guile
  3845. guile-2
  3846. guile-2.2
  3847. guile-3
  3848. guile-3.0
  3849. r5rs
  3850. r6rs
  3851. r7rs
  3852. exact-closed ieee-float full-unicode ratios ;; R7RS features.
  3853. srfi-0 ;; cond-expand itself
  3854. srfi-4 ;; homogeneous numeric vectors
  3855. srfi-6 ;; string ports
  3856. srfi-13 ;; string library
  3857. srfi-14 ;; character sets
  3858. srfi-16 ;; case-lambda
  3859. srfi-23 ;; `error` procedure
  3860. srfi-30 ;; nested multi-line comments
  3861. srfi-39 ;; parameterize
  3862. srfi-46 ;; basic syntax-rules extensions
  3863. srfi-55 ;; require-extension
  3864. srfi-61 ;; general cond clause
  3865. srfi-62 ;; s-expression comments
  3866. srfi-87 ;; => in case clauses
  3867. srfi-105 ;; curly infix expressions
  3868. ))
  3869. ;; This table maps module public interfaces to the list of features.
  3870. ;;
  3871. (define %cond-expand-table (make-hash-table))
  3872. ;; Add one or more features to the `cond-expand' feature list of the
  3873. ;; module `module'.
  3874. ;;
  3875. (define (cond-expand-provide module features)
  3876. (let ((mod (module-public-interface module)))
  3877. (and mod
  3878. (hashq-set! %cond-expand-table mod
  3879. (append (hashq-ref %cond-expand-table mod '())
  3880. features)))))
  3881. (define-syntax cond-expand
  3882. (lambda (x)
  3883. (define (module-has-feature? mod sym)
  3884. (or-map (lambda (mod)
  3885. (memq sym (hashq-ref %cond-expand-table mod '())))
  3886. (module-uses mod)))
  3887. (define (condition-matches? condition)
  3888. (syntax-case condition (and or not)
  3889. ((and c ...)
  3890. (and-map condition-matches? #'(c ...)))
  3891. ((or c ...)
  3892. (or-map condition-matches? #'(c ...)))
  3893. ((not c)
  3894. (if (condition-matches? #'c) #f #t))
  3895. (c
  3896. (identifier? #'c)
  3897. (let ((sym (syntax->datum #'c)))
  3898. (if (memq sym %cond-expand-features)
  3899. #t
  3900. (module-has-feature? (current-module) sym))))))
  3901. (define (match clauses alternate)
  3902. (syntax-case clauses ()
  3903. (((condition form ...) . rest)
  3904. (if (condition-matches? #'condition)
  3905. #'(begin form ...)
  3906. (match #'rest alternate)))
  3907. (() (alternate))))
  3908. (syntax-case x (else)
  3909. ((_ clause ... (else form ...))
  3910. (match #'(clause ...)
  3911. (lambda ()
  3912. #'(begin form ...))))
  3913. ((_ clause ...)
  3914. (match #'(clause ...)
  3915. (lambda ()
  3916. (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
  3917. ;; This procedure gets called from the startup code with a list of
  3918. ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
  3919. ;;
  3920. (define (use-srfis srfis)
  3921. (process-use-modules
  3922. (map (lambda (num)
  3923. (list (list 'srfi (string->symbol
  3924. (string-append "srfi-" (number->string num))))))
  3925. srfis)))
  3926. ;;; srfi-55: require-extension
  3927. ;;;
  3928. (define-syntax require-extension
  3929. (lambda (x)
  3930. (syntax-case x (srfi)
  3931. ((_ (srfi n ...))
  3932. (and-map integer? (syntax->datum #'(n ...)))
  3933. (with-syntax
  3934. (((srfi-n ...)
  3935. (map (lambda (n)
  3936. (datum->syntax x (symbol-append 'srfi- n)))
  3937. (map string->symbol
  3938. (map number->string (syntax->datum #'(n ...)))))))
  3939. #'(use-modules (srfi srfi-n) ...)))
  3940. ((_ (type arg ...))
  3941. (identifier? #'type)
  3942. (syntax-violation 'require-extension "Not a recognized extension type"
  3943. x)))))
  3944. ;;; Defining transparently inlinable procedures
  3945. ;;;
  3946. (define-syntax define-inlinable
  3947. ;; Define a macro and a procedure such that direct calls are inlined, via
  3948. ;; the macro expansion, whereas references in non-call contexts refer to
  3949. ;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
  3950. (lambda (x)
  3951. ;; Use a space in the prefix to avoid potential -Wunused-toplevel
  3952. ;; warning
  3953. (define prefix (string->symbol "% "))
  3954. (define (make-procedure-name name)
  3955. (datum->syntax name
  3956. (symbol-append prefix (syntax->datum name)
  3957. '-procedure)))
  3958. (syntax-case x ()
  3959. ((_ (name formals ...) body0 body ...)
  3960. (identifier? #'name)
  3961. (with-syntax ((proc-name (make-procedure-name #'name))
  3962. ((args ...) (generate-temporaries #'(formals ...))))
  3963. #`(begin
  3964. (define (proc-name formals ...)
  3965. #((maybe-unused))
  3966. (syntax-parameterize ((name (identifier-syntax proc-name)))
  3967. body0 body ...))
  3968. (define-syntax-parameter name
  3969. (lambda (x)
  3970. (syntax-case x ()
  3971. ((_ args ...)
  3972. #'((syntax-parameterize ((name (identifier-syntax proc-name)))
  3973. (lambda (formals ...)
  3974. body0 body ...))
  3975. args ...))
  3976. ((_ a (... ...))
  3977. (syntax-violation 'name "Wrong number of arguments" x))
  3978. (_
  3979. (identifier? x)
  3980. #'proc-name))))))))))
  3981. (define using-readline?
  3982. (let ((using-readline? (make-fluid)))
  3983. (make-procedure-with-setter
  3984. (lambda () (fluid-ref using-readline?))
  3985. (lambda (v) (fluid-set! using-readline? v)))))
  3986. ;;; {R6RS and R7RS}
  3987. ;;;
  3988. (define (install-r6rs!)
  3989. "Make changes to the default environment to better conform to the
  3990. R6RS. @xref{R6RS Incompatibilities} in the manual."
  3991. (set! %load-extensions
  3992. (cons* ".guile.sls" ".sls"
  3993. (delete ".guile.sls" (delete ".sls" %load-extensions))))
  3994. (read-enable 'r6rs-hex-escapes)
  3995. (read-enable 'hungry-eol-escapes))
  3996. (define (install-r7rs!)
  3997. "Make changes to the default environment to better conform to the
  3998. R7RS."
  3999. (install-r6rs!)
  4000. (set! %load-extensions
  4001. (cons* ".guile.sld" ".sld"
  4002. (delete ".guile.sld" (delete ".sld" (delete ".guile.sls" (delete ".sls" %load-extensions))))))
  4003. (read-enable 'r7rs-symbols))
  4004. ;;; {Deprecated stuff}
  4005. ;;;
  4006. (begin-deprecated
  4007. (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
  4008. ;;; {Ports}
  4009. ;;;
  4010. ;; Allow code in (guile) to use port bindings.
  4011. (module-use! the-root-module (resolve-interface '(ice-9 ports)))
  4012. ;; Allow users of (guile) to see port bindings.
  4013. (module-use! the-scm-module (resolve-interface '(ice-9 ports)))
  4014. ;;; {`read' implementation in Scheme.}
  4015. ;;;
  4016. ;;;
  4017. (call-with-values (lambda ()
  4018. ;; Capture syntax? binding, later removed from root
  4019. ;; module.
  4020. (let ((syntax? syntax?))
  4021. (include-from-path "ice-9/read.scm")
  4022. (values read read-syntax)))
  4023. (lambda (read* read-syntax*)
  4024. (set! read read*)
  4025. (set! read-syntax read-syntax*)))
  4026. ;;; {Threads}
  4027. ;;;
  4028. ;; Load (ice-9 threads), initializing some internal data structures.
  4029. (resolve-interface '(ice-9 threads))
  4030. ;;; {Exceptions}
  4031. ;;;
  4032. ;; Load (ice-9 exceptions), initializing some internal data structures.
  4033. (resolve-interface '(ice-9 exceptions))
  4034. ;;; SRFI-4 in the default environment. FIXME: we should figure out how
  4035. ;;; to deprecate this.
  4036. ;;;
  4037. ;; FIXME:
  4038. (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
  4039. ;;; make-soft-port in the default environment. FIXME: Deprecate, make
  4040. ;;; callers import (ice-9 soft-port).
  4041. ;;;
  4042. (define (make-soft-port pv modes)
  4043. ((module-ref (resolve-interface '(ice-9 soft-ports))
  4044. 'deprecated-make-soft-port)
  4045. pv modes))
  4046. ;;; A few identifiers that need to be defined in this file are really
  4047. ;;; internal implementation details. We shove them off into internal
  4048. ;;; modules, removing them from the (guile) module.
  4049. ;;;
  4050. (define-module (system syntax internal))
  4051. (let ()
  4052. (define (steal-bindings! from to ids)
  4053. (for-each
  4054. (lambda (sym)
  4055. (let ((v (module-local-variable from sym)))
  4056. (module-remove! from sym)
  4057. (module-add! to sym v)))
  4058. ids)
  4059. (module-export! to ids))
  4060. (steal-bindings! the-root-module (resolve-module '(system syntax internal))
  4061. '(syntax?
  4062. syntax-local-binding
  4063. %syntax-module
  4064. syntax-locally-bound-identifiers
  4065. syntax-session-id
  4066. make-syntax
  4067. syntax-expression
  4068. syntax-wrap
  4069. syntax-module
  4070. syntax-sourcev)))
  4071. ;;; Place the user in the guile-user module.
  4072. ;;;
  4073. ;; Set filename to #f to prevent reload.
  4074. (define-module (guile-user)
  4075. #:autoload (system base compile) (compile compile-file)
  4076. #:filename #f
  4077. #:declarative? #f)
  4078. ;; Remain in the `(guile)' module at compilation-time so that the
  4079. ;; `-Wunused-toplevel' warning works as expected.
  4080. (eval-when (compile) (set-current-module the-root-module))
  4081. ;;; boot-9.scm ends here