boot-9.scm 171 KB

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