boot-9.scm 136 KB

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