boot-9.scm 165 KB

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