boot-9.scm 143 KB

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