boot-9.scm 143 KB

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