boot-9.scm 152 KB

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