boot-9.scm 143 KB

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