scheme48.info-1 295 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807
  1. This is scheme48.info, produced by makeinfo version 6.7 from
  2. scheme48.texi.
  3. This manual is for Scheme48 version 1.3.
  4. Copyright (C) 2004, 2005, 2006 Taylor Campbell. All rights reserved.
  5. This manual includes material derived from works bearing the
  6. following notice:
  7. Copyright (C) 1993-2005 Richard Kelsey, Jonathan Rees, and Mike
  8. Sperber. All rights reserved.
  9. Redistribution and use in source and binary forms, with or without
  10. modification, are permitted provided that the following conditions
  11. are met:
  12. * Redistributions of source code must retain the above copyright
  13. notice, this list of conditions and the following disclaimer.
  14. * Redistributions in binary form must reproduce the above
  15. copyright notice, this list of conditions and the following
  16. disclaimer in the documentation and/or other materials
  17. provided with the distribution.
  18. * The name of the authors may not be used to endorse or promote
  19. products derived from this software without specific prior
  20. written permission.
  21. THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR
  22. IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  23. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  24. DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT,
  25. INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  26. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  27. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  28. HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  29. STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  30. ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  31. POSSIBILITY OF SUCH DAMAGE.
  32. INFO-DIR-SECTION The Algorithmic Language Scheme
  33. START-INFO-DIR-ENTRY
  34. * Scheme48: (scheme48). Nearly complete reference manual for version 1.3
  35. END-INFO-DIR-ENTRY
  36. 
  37. File: scheme48.info, Node: Top, Next: Introduction & acknowledgements, Up: (dir)
  38. The Nearly Complete Scheme48 Reference Manual
  39. *********************************************
  40. This manual is for Scheme48 version 1.3.
  41. Copyright (C) 2004, 2005, 2006 Taylor Campbell. All rights reserved.
  42. This manual includes material derived from works bearing the
  43. following notice:
  44. Copyright (C) 1993-2005 Richard Kelsey, Jonathan Rees, and Mike
  45. Sperber. All rights reserved.
  46. Redistribution and use in source and binary forms, with or without
  47. modification, are permitted provided that the following conditions
  48. are met:
  49. * Redistributions of source code must retain the above copyright
  50. notice, this list of conditions and the following disclaimer.
  51. * Redistributions in binary form must reproduce the above
  52. copyright notice, this list of conditions and the following
  53. disclaimer in the documentation and/or other materials
  54. provided with the distribution.
  55. * The name of the authors may not be used to endorse or promote
  56. products derived from this software without specific prior
  57. written permission.
  58. THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR
  59. IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  60. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  61. DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT,
  62. INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  63. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  64. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  65. HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  66. STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  67. ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  68. POSSIBILITY OF SUCH DAMAGE.
  69. * Menu:
  70. * Introduction & acknowledgements::
  71. * User environment::
  72. * Module system::
  73. * System facilities::
  74. * Multithreading::
  75. * Libraries::
  76. * C interface::
  77. * POSIX interface::
  78. * Pre-Scheme:: A low-level dialect of Scheme
  79. * References::
  80. * Concept index::
  81. * Binding index::
  82. * Structure index::
  83. -- The Detailed Node Listing --
  84. * Introduction & acknowledgements::
  85. User environment
  86. * Running Scheme48::
  87. * Emacs integration::
  88. * Using the module system::
  89. * Command processor::
  90. Module system
  91. * Module system architecture::
  92. * Module configuration language:: Language of the module system
  93. * Macros in concert with modules::
  94. * Static type system::
  95. System facilities
  96. * System features::
  97. * Condition system::
  98. * Bitwise manipulation::
  99. * Generic dispatch system::
  100. * I/O system::
  101. * Reader & writer::
  102. * Records::
  103. * Suspending and resuming heap images::
  104. Multithreading
  105. * Basic thread operations::
  106. * Optimistic concurrency::
  107. * Higher-level synchronization::
  108. * Concurrent ML:: High-level event synchronization
  109. * Pessimistic concurrency:: Mutual exclusion/locking
  110. * Custom thread synchronization::
  111. Libraries
  112. * Boxed bitwise-integer masks::
  113. * Enumerated/finite types and sets::
  114. * Macros for writing loops::
  115. * Library data structures::
  116. * I/O extensions::
  117. * TCP & UDP sockets::
  118. * Common-Lisp-style formatting::
  119. * Library utilities::
  120. C interface
  121. * Shared bindings between Scheme and C::
  122. * Calling C functions from Scheme::
  123. * Dynamic loading of C modules::
  124. * Accessing Scheme data from C::
  125. * Calling Scheme procedures from C::
  126. * Interacting with the Scheme heap in C::
  127. * Using Scheme records in C::
  128. * Raising exceptions from C::
  129. * Unsafe C macros::
  130. POSIX interface
  131. * POSIX processes::
  132. * POSIX signals::
  133. * POSIX process environment::
  134. * POSIX users and groups::
  135. * POSIX host OS and machine identification::
  136. * POSIX file system access::
  137. * POSIX time::
  138. * POSIX I/O utilities::
  139. * POSIX regular expressions::
  140. * POSIX C to Scheme correspondence::
  141. Pre-Scheme
  142. * Differences between Pre-Scheme & Scheme::
  143. * Pre-Scheme type specifiers::
  144. * Standard Pre-Scheme environment::
  145. * More Pre-Scheme packages::
  146. * Invoking the Pre-Scheme compiler::
  147. * Example Pre-Scheme compiler usage::
  148. * Running Pre-Scheme as Scheme::
  149. 
  150. File: scheme48.info, Node: Introduction & acknowledgements, Next: User environment, Prev: Top, Up: Top
  151. 1 Introduction
  152. **************
  153. Scheme48 is an implementation of Scheme based on a byte-code virtual
  154. machine with design goals of simplicity and cleanliness. To briefly
  155. enumerate some interesting aspects of it, Scheme48 features:
  156. * an advanced module system based on Jonathan Rees's W7 security
  157. kernel with well-integrated interaction between macros and modules;
  158. * a virtual machine written in a dialect of Scheme itself,
  159. Pre-Scheme, for which a compiler is written with Scheme48;
  160. * a sophisticated, user-level, preëmptive multithreading system with
  161. numerous high-level concurrency abstractions;
  162. * a composable, lock-free shared-memory thread synchronization
  163. mechanism known as "optimistic concurrency"; and
  164. * an advanced user environment that is well-integrated with the
  165. module and thread systems to facilitate very rapid development of
  166. software systems scaling from small to large and single-threaded to
  167. multi-threaded.
  168. It was originally written by Jonathan Rees and Richard Kelsey in 1986
  169. in response to the fact that so many Lisp implementations had started
  170. out simple and grown to be complex monsters of projects. It has been
  171. used in a number of research areas, including:
  172. * mobile robots at Cornell [Donald 92];
  173. * a multi-user collaboration system, sometimes known as a 'MUD'
  174. ('multi-user dungeon') or 'MUSE' ('multi-user simulation
  175. environment'), as well as general research in capability-based
  176. security [Museme; Rees 96]; and
  177. * advanced distributed computing with higher-order mobile agents at
  178. NEC's Princeton research lab [Cejtin et al. 95].
  179. The system is tied together in a modular fashion by a configuration
  180. language that permits quite easy mixing and matching of components, so
  181. much so that Scheme48 can be used essentially as its own OS, as it was
  182. in Cornell's mobile robots program, or just as easily within another, as
  183. the standard distribution is. The standard distribution is quite
  184. portable and needs only a 32-bit byte-addressed POSIX system.
  185. The name 'Scheme48' commemorates the time it took Jonathan Rees and
  186. Richard Kelsey to originally write Scheme48 on August 6th & 7th, 1986:
  187. forty-eight hours. (It has been joked that the system has expanded to
  188. such a size now that it requires forty-eight hours to _read_ the
  189. source.)
  190. 1.1 This manual
  191. ===============
  192. This manual begins in the form of an introduction to the usage of
  193. Scheme48, suitable for those new to the system, after which it is
  194. primarily a reference material, organized by subject. Included in the
  195. manual is also a complete reference manual for Pre-Scheme, a low-level
  196. dialect of Scheme for systems programming and in which the Scheme48
  197. virtual machine is written; *note Pre-Scheme::.
  198. This manual is, except for some sections pilfered and noted as such
  199. from the official but incomplete Scheme48 reference manual, solely the
  200. work of Taylor Campbell, on whom all responsibility for the content of
  201. the manual lies. The authors of Scheme48 do not endorse this manual.
  202. 1.2 Acknowledgements
  203. ====================
  204. Thanks to Jonathan Rees and Richard Kelsey for having decided so many
  205. years ago to make a simple Scheme implementation with a clean design in
  206. the first place, and for having worked on it so hard for so many years
  207. (almost twenty!); to Martin Gasbichler and Mike Sperber, for having
  208. picked up Scheme48 in the past couple years when Richard and Jonathan
  209. were unable to work actively on it; to Jeremy Fincher for having asked
  210. numerous questions about Scheme48 as he gathered knowledge from which he
  211. intended to build an implementation of his own Lisp dialect, thereby
  212. inducing me to decide to write the manual in the first place; to Jorgen
  213. Schäfer, for having also asked so many questions, proofread various
  214. drafts, and made innumerable suggestions to the manual.
  215. 
  216. File: scheme48.info, Node: User environment, Next: Module system, Prev: Introduction & acknowledgements, Up: Top
  217. 2 User environment
  218. ******************
  219. * Menu:
  220. * Running Scheme48::
  221. * Emacs integration::
  222. * Using the module system::
  223. * Command processor::
  224. 
  225. File: scheme48.info, Node: Running Scheme48, Next: Emacs integration, Up: User environment
  226. 2.1 Running Scheme48
  227. ====================
  228. Scheme48 is run by invoking its virtual machine on a dumped heap image
  229. to resume a saved system state. The common case of invoking the default
  230. image, 'scheme48.image', which contains the usual command processor,
  231. run-time system, &c., is what the 'scheme48' script that is installed
  232. does. The actual virtual machine executable itself, 'scheme48vm', is
  233. typically not installed into an executable directory such as
  234. '/usr/local/bin/' on Unix, but in the Scheme48 library directory, which
  235. is, by default on Unix installations of Scheme48, '/usr/local/lib/'.
  236. However, both 'scheme48' and 'scheme48vm' share the following
  237. command-line options; the only difference is that 'scheme48' has a
  238. default '-i' argument.
  239. '-h HEAP-SIZE'
  240. The size of Scheme48's heap, in cells. By default, the heap size
  241. is 3 megacells, or 12 megabytes, permitting 6 megabytes per
  242. semispace -- Scheme48 uses a simple stop & copy garbage
  243. collector.(1) Since the current garbage collector cannot resize
  244. the heap dynamically if it becomes consistently too full, users on
  245. machines with much RAM may be more comfortable with liberally
  246. increasing this option.
  247. '-s STACK-SIZE'
  248. The stack size, in cells. The default stack size is 10000 bytes,
  249. or 2500 cells. Note that this is only the size of the stack cache
  250. segment of memory for fast stack frame storage. When this
  251. overflows, there is no error; instead, Scheme48 simply copies the
  252. contents of the stack cache into the heap, until the frames it
  253. copied into the heap are needed later, at which point they are
  254. copied back into the stack cache. The '-s' option therefore
  255. affects only performance, not the probability of fatal stack
  256. overflow errors.
  257. '-i IMAGE-FILENAME'
  258. The filename of the suspended heap image to resume. When running
  259. the 'scheme48' executable, the default is the regular Scheme48
  260. image; when running the virtual machine directly, this option must
  261. be passed explicitly. For information on creating custom heap
  262. images, *note Image-building commands::, and also *note Suspending
  263. and resuming heap images::.
  264. '-a ARGUMENT ...'
  265. Command-line arguments to pass to the heap image's resumer, rather
  266. than being parsed by the virtual machine. In the usual Scheme48
  267. command processor image, these arguments are put in a list of
  268. strings that will be the initial focus value (*note Focus value::).
  269. '-u'
  270. Muffles warnings on startup about undefined imported foreign
  271. bindings.
  272. The usual Scheme48 image may accept an argument of 'batch', using the
  273. '-a' switch to the virtual machine. This enters Scheme48 in batch mode,
  274. which displays no welcoming banner, prints no prompt for inputs, and
  275. exits when an EOF is read. This may be used to run scripts from the
  276. command-line, often in the exec language (*note Command programs::), by
  277. sending text to Scheme48 through Unix pipes or shell heredocs. For
  278. example, this Unix shell command will load the command program in the
  279. file 'foo.scm' into the exec language environment and exit Scheme48 when
  280. the program returns:
  281. echo ,exec ,load foo.scm | scheme48 -a batch
  282. This Unix shell command will load 'packages.scm' into the module
  283. language environment, open the 'tests' structure into the user
  284. environment, and call the procedure 'run-tests' with zero arguments:
  285. scheme48 -a batch <<END
  286. ,config ,load packages.scm
  287. ,open tests
  288. (run-tests)
  289. END
  290. Scheme48 also supports [SRFI 22] and [SRFI 7] by providing R5RS and
  291. [SRFI 7] script interpreters in the location where Scheme48 binaries are
  292. kept as 'scheme-r5rs' and 'scheme-srfi-7'. See the [SRFI 22] and [SRFI
  293. 7] documents for more details. Scheme48's command processor also has
  294. commands for loading [SRFI 7] programs, with or without a [SRFI 22]
  295. script header; *note SRFI 7::.
  296. 2.1.1 Command processor introduction
  297. ------------------------------------
  298. The Scheme48 command processor is started up on resumption of the usual
  299. Scheme48 image. This is by default what the 'scheme48' script installed
  300. by Scheme48 does. It will first print out a banner that contains some
  301. general information about the system, which will typically look
  302. something like this:
  303. Welcome to Scheme 48 1.3 (made by root on Sun Jul 10 10:57:03 EDT 2005)
  304. Copyright (c) 1993-2005 by Richard Kelsey and Jonathan Rees.
  305. Please report bugs to scheme-48-bugs@s48.org.
  306. Get more information at http://www.s48.org/.
  307. Type ,? (comma question-mark) for help.
  308. After the banner, it will initiate a REPL (read-eval-print loop). At
  309. first, there should be a simple '>' prompt. The command processor
  310. interprets Scheme code as well as "commands". Commands operate the
  311. system at a level above or outside Scheme. They begin with a comma, and
  312. they continue until the end of the line, unless they expect a Scheme
  313. expression argument, which may continue as many lines as desired. Here
  314. is an example of a command invocation:
  315. > ,set load-noisily on
  316. This will set the 'load-noisily' switch (*note Command processor
  317. switches::) on.
  318. *Note:* If a command accepts a Scheme expression argument that is
  319. followed by more arguments, all of the arguments after the Scheme
  320. expression must be put on the same line as the last line of the Scheme
  321. expression.
  322. Certain operations, such as breakpoints and errors, result in a
  323. recursive command processor to be invoked. This is known as "pushing a
  324. command level". *Note Command levels::. Also, the command processor
  325. supports an "object inspector", an interactive program for inspecting
  326. the components of objects, including continuation or stack frame
  327. objects; the debugger is little more than the inspector, working on
  328. continuations. *Note Inspector::.
  329. Evaluation of code takes place in the "interaction environment".
  330. (This is what R5RS's 'interaction-environment' returns.) Initially,
  331. this is the "user environment", which by default is a normal R5RS Scheme
  332. environment. There are commands that set the interaction environment
  333. and evaluate code in other environments, too; *note Module commands::.
  334. The command processor's prompt has a variety of forms. As above, it
  335. starts out with as a simple '>'. Several factors can affect the prompt.
  336. The complete form of the prompt is as follows:
  337. * It begins with an optional command level (*note Command levels::)
  338. number: at the top level, there is no command level number; as
  339. command levels are pushed, the number is incremented, starting at
  340. 1.
  341. * Optionally, the name of the interaction environment follows the
  342. command level number: if the interaction environment is the user
  343. environment, there is no name printed here; named environments are
  344. printed with their names; unnamed environments (usually created
  345. using the ',new-package' command; *note Module commands::) are
  346. printed with their numeric identifiers. If a command level number
  347. preceded an environment name, a space is printed between them.
  348. * If the command processor is in the regular REPL mode, it ends with
  349. a '>' and a space before the user input area; if it is in inspector
  350. mode (*note Inspector::), it ends with a ':' and a space before the
  351. user input area.
  352. For example, this prompt denotes that the user is in inspector mode
  353. at command level 3 and that the interaction environment is an
  354. environment named 'frobozz':
  355. 3 frobozz:
  356. This prompt shows that the user is in the regular REPL mode at the
  357. top level, but in the environment for module descriptions (*note Module
  358. commands::):
  359. config>
  360. For a complete listing of all the commands in the command processor,
  361. *note Command processor::.
  362. ---------- Footnotes ----------
  363. (1) The Scheme48 team is also working on a new, generational garbage
  364. collector, but it is not in the standard distribution of Scheme48 yet.
  365. 
  366. File: scheme48.info, Node: Emacs integration, Next: Using the module system, Prev: Running Scheme48, Up: User environment
  367. 2.2 Emacs integration
  368. =====================
  369. Emacs is the canonical development environment for Scheme48. The
  370. 'scheme.el' and 'cmuscheme.el' packages provide support for editing
  371. Scheme code and running inferior Scheme processes, respectively. Also,
  372. the 'scheme48.el' package provides more support for integrating directly
  373. with Scheme48.(1) 'scheme.el' and 'cmuscheme.el' come with GNU Emacs;
  374. 'scheme48.el' is available separately from
  375. <http://www.emacswiki.org/cgi-bin/wiki/download/scheme48.el>.
  376. To load 'scheme48.el' if it is in the directory EMACS-DIR, add these
  377. lines to your '.emacs':
  378. (add-to-list 'load-path "EMACS-DIR/")
  379. (autoload 'scheme48-mode "scheme48"
  380. "Major mode for improved Scheme48 integration."
  381. t)
  382. (add-hook 'hack-local-variables-hook
  383. (lambda ()
  384. (if (and (boundp 'scheme48-package)
  385. scheme48-package)
  386. (progn (scheme48-mode)
  387. (hack-local-variables-prop-line)))))
  388. The 'add-hook' call sets Emacs up so that any file with a
  389. 'scheme48-package' local variable specified in the file's '-*-' line or
  390. 'Local Variables' section will be entered in Scheme48 mode. Files
  391. should use the 'scheme48-package' variable to enable Scheme48 mode; they
  392. should not specify Scheme48 mode explicitly, since this would fail in
  393. Emacs instances without 'scheme48.el'. That is, put this at the tops of
  394. files:
  395. ;;; -*- Mode: Scheme; scheme48-package: ... -*-
  396. Avoid this at the tops of files:
  397. ;;; -*- Mode: Scheme48 -*-
  398. There is also SLIME48, the Superior Lisp Interaction Mode for Emacs
  399. with Scheme48. It provides a considerably higher level of integration
  400. the other Emacs packages do, although it is less mature. It is at
  401. <http://mumble.net/~campbell/scheme/slime48.tar.gz>;
  402. there is also a Darcs repository(2) at
  403. <http://mumble.net/~campbell/darcs/slime48/>.
  404. Finally, 'paredit.el' implements pseudo-structural editing facilities
  405. for S-expressions: it automatically balances parentheses and provides a
  406. number of high-level operations on S-expressions. 'Paredit.el' is
  407. available on the web at
  408. <http://mumble.net/~campbell/emacs/paredit.el>.
  409. 'cmuscheme.el' defines these:
  410. -- Emacs command: run-scheme [scheme-prog]
  411. Starts an inferior Scheme process or switches to a running one.
  412. With no argument, this uses the value of 'scheme-program-name' to
  413. run the inferior Scheme system; with a prefix argument SCHEME-PROG,
  414. this invokes SCHEME-PROG.
  415. -- Emacs variable: scheme-program-name
  416. The Scheme program to invoke for inferior Scheme processes.
  417. Under 'scheme48-mode' with 'scheme.el', 'cmuscheme.el', and
  418. 'scheme48.el', these keys are defined:
  419. 'C-M-f' -- 'forward-sexp'
  420. 'C-M-b' -- 'backward-sexp'
  421. 'C-M-k' -- 'kill-sexp'
  422. '<ESC> C-<DEL>' (_not_ 'C-M-<DEL>') -- 'backward-kill-sexp'
  423. 'C-M-q' -- 'indent-sexp'
  424. 'C-M-@' -- 'mark-sexp'
  425. 'C-M-<SPC>' -- 'mark-sexp'
  426. S-expression manipulation commands. 'C-M-f' moves forward by one
  427. S-expression; 'C-M-b' moves backward by one. 'C-M-k' kills the
  428. S-expression following the point; '<ESC> C-<DEL>' kills the
  429. S-expression preceding the point. 'C-M-q' indents the S-expression
  430. following the point. 'C-M-@' & 'C-M-<SPC>', equivalent to one
  431. another, mark the S-expression following the point.
  432. 'C-c z' -- 'switch-to-scheme'
  433. Switches to the inferior Scheme process buffer.
  434. 'C-c C-l' -- 'scheme48-load-file'
  435. Loads the file corresponding with the current buffer into Scheme48.
  436. If that file was not previously loaded into Scheme48 with 'C-c
  437. C-l', Scheme48 records the current interaction environment in place
  438. as it loads the file; if the file was previously recorded, it is
  439. loaded into the recorded environment. *Note Emacs integration
  440. commands::.
  441. 'C-c C-r' -- 'scheme48-send-region'
  442. 'C-c M-r' -- 'scheme48-send-region-and-go'
  443. 'C-c C-r' sends the currently selected region to the current
  444. inferior Scheme process. The file of the current buffer is
  445. recorded as in the 'C-c C-l' command, and code is evaluated in the
  446. recorded package. 'C-c M-r' does similarly, but subsequently also
  447. switches to the inferior Scheme process buffer.
  448. 'C-M-x' -- 'scheme48-send-definition'
  449. 'C-c C-e' -- 'scheme48-send-definition'
  450. 'C-c M-e' -- 'scheme48-send-definition-and-go'
  451. 'C-M-x' (GNU convention) and 'C-c C-e' send the top-level
  452. definition that the current point is within to the current inferior
  453. Scheme process. 'C-c M-e' does similarly, but subsequently also
  454. switches to the inferior Scheme process buffer. 'C-c C-e' and 'C-c
  455. M-e' also respect Scheme48's file/environment mapping.
  456. 'C-x C-e' -- 'scheme48-send-last-sexp'
  457. Sends the S-expression preceding the point to the inferior Scheme
  458. process. This also respects Scheme48's file/environment mapping.
  459. ---------- Footnotes ----------
  460. (1) 'scheme48.el' is based on the older 'cmuscheme48.el', which is
  461. bundled with Scheme48 in the 'emacs/' directory. Since 'cmuscheme48.el'
  462. is older and less developed, it is not documented here.
  463. (2) Darcs is a revision control system; see
  464. <http://www.darcs.net/>
  465. for more details.
  466. 
  467. File: scheme48.info, Node: Using the module system, Next: Command processor, Prev: Emacs integration, Up: User environment
  468. 2.3 Using the module system
  469. ===========================
  470. Scheme48 is deeply integrated with an advanced module system. For
  471. complete detail of its module system, *note Module system::. Briefly,
  472. however:
  473. * "Packages" are top-level environments suitable for evaluating
  474. expressions and definitions, either interactively, from files
  475. loaded on-the-fly, or as the bodies of modules. They can also
  476. access bindings exported by structures by "opening" the structures.
  477. * "Structures" are libraries, or implementations of interfaces,
  478. exporting sets of bindings that packages can access. Underlying
  479. structures are usually packages, in which the user can, in some
  480. cases, interactively evaluate code during development.
  481. Scheme48's usual development system, the command processor, provides
  482. a number of commands for working with the module system. For complete
  483. details, *note Module commands::. Chief among these commands are
  484. ',open' and ',in'. ',open STRUCT ...' makes all of the bindings from
  485. each of STRUCT ... available in the interaction environment. Many of
  486. the sections in this manual describe one or more structures with the
  487. name they are given. For example, in order to use, or open, the
  488. multi-dimensional array library in the current interaction environment,
  489. one would enter
  490. ,open arrays
  491. to the command processor. ',in STRUCT' sets the interaction environment
  492. to be the package underlying STRUCT. For instance, if, during
  493. development, the user decides that the package of the existing structure
  494. 'foo' should open the structure 'bar', he might type
  495. ,in foo
  496. ,open bar
  497. The initial interaction environment is known as the "user package";
  498. the interaction environment may be reverted to the user package with the
  499. ',user' command.
  500. Module descriptions, or code in the module configuration language
  501. (*note Module configuration language::) should be loaded into the
  502. special environment for that language with the ',config' command (*note
  503. Module commands::). E.g., if 'packages.scm' contains a set of module
  504. descriptions that the user wishes to load, among which is the definition
  505. of a structure 'frobozz' which he wishes to open, he will typically send
  506. the following to the command processor prompt:
  507. ,config ,load packages.scm
  508. ,open frobozz
  509. *Note:* These are commands for the interactive command processor,
  510. _not_ special directives to store in files to work with the module
  511. system. The module language is disjoint from Scheme; for complete
  512. detail on it, *note Module system::.
  513. 2.3.1 Configuration mutation
  514. ----------------------------
  515. (This section was derived from work copyrighted (C) 1993-2005 by Richard
  516. Kelsey, Jonathan Rees, and Mike Sperber.)
  517. During program development, it is often desirable to make changes to
  518. packages and interfaces. In static languages, it is usually necessary
  519. to re-compile and re-link a program in order for such changes to be
  520. reflected in a running system. Even in interactive Common Lisp systems,
  521. a change to a package's exports often requires reloading clients that
  522. have already mentioned names whose bindings change. In those systems,
  523. once 'read' resolves a use of a name to a symbol, that resolution is
  524. fixed, so a change in the way that a name resolves to a symbol can be
  525. reflected only by re-'read'ing all such references.
  526. The Scheme48 development environment supports rapid turnaround in
  527. modular program development by allowing mutations to a program's
  528. configuration and giving a clear semantics to such mutation. The rule
  529. is that variable bindings in a running program are always resolved
  530. according to the current structure and interface bindings, even when
  531. these bindings change as a result of edits to the configuration. For
  532. example, consider the following:
  533. (define-interface foo-interface (export a c))
  534. (define-structure foo foo-interface
  535. (open scheme)
  536. (begin (define a 1)
  537. (define (b x) (+ a x))
  538. (define (c y) (* (b a) y))))
  539. (define-structure bar (export d)
  540. (open scheme foo)
  541. (begin (define (d w) (+ (b w) a))))
  542. This program has a bug. The variable named 'b', which is free in the
  543. definition of 'd', has no binding in 'bar''s package. Suppose that 'b'
  544. was intended to be exported by 'foo', but was mistakenly omitted. It is
  545. not necessary to re-process 'bar' or any of 'foo''s other clients at
  546. this point. One need only change 'foo-interface' and inform the
  547. development system of that change (using, say, an appropriate Emacs
  548. command), and 'foo''s binding of 'b' will be found when the procedure
  549. 'd' is called and its reference to 'b' actually evaluated.
  550. Similarly, it is possible to replace a structure; clients of the old
  551. structure will be modified so that they see bindings from the new one.
  552. Shadowing is also supported in the same way. Suppose that a client
  553. package C opens a structure 'mumble' that exports a name 'x', and
  554. 'mumble''s implementation obtains the binding of 'x' from some other
  555. structure 'frotz'. C will see the binding from 'frotz'. If one then
  556. alters 'mumble' so that it shadows 'bar''s binding of 'x' with a
  557. definition of its own, procedures in C that refer to 'x' will
  558. subsequently automatically see 'mumble''s definition instead of the one
  559. from 'frotz' that they saw earlier.
  560. This semantics might appear to require a large amount of computation
  561. on every variable reference: the specified behaviour appears to require
  562. scanning the package's list of opened structures and examining their
  563. interfaces -- on every variable reference evaluated, not just at
  564. compile-time. However, the development environment uses caching with
  565. cache invalidation to make variable references fast, and most of the
  566. code is invoked only when the virtual machine traps due to a reference
  567. to an undefined variable.
  568. 2.3.2 Listing interfaces
  569. ------------------------
  570. The 'list-interfaces' structure provides a utility for examining
  571. interfaces. It is usually opened into the config package with ',config
  572. ,open list-interfaces' in order to have access to the structures &
  573. interfaces easily.
  574. -- procedure: list-interface struct-or-interface --> unspecified
  575. Lists all of the bindings exported by STRUCT-OR-INTERFACE along
  576. with their static types (*note Static type system::). For example,
  577. > ,config ,open list-interfaces
  578. > ,config (list-interface condvars)
  579. condvar-has-value? (proc (:condvar) :value)
  580. condvar-value (proc (:condvar) :value)
  581. condvar? (proc (:value) :boolean)
  582. make-condvar (proc (&rest :value) :condvar)
  583. maybe-commit-and-set-condvar! (proc (:condvar :value) :boolean)
  584. maybe-commit-and-wait-for-condvar (proc (:condvar) :boolean)
  585. set-condvar-has-value?! (proc (:condvar :value) :unspecific)
  586. set-condvar-value! (proc (:condvar :value) :unspecific)
  587. 
  588. File: scheme48.info, Node: Command processor, Prev: Using the module system, Up: User environment
  589. 2.4 Command processor
  590. =====================
  591. The Scheme48 command processor is the main development environment. It
  592. incorporates a read-eval-print loop as well as an interactive inspector
  593. and debugger. It is well-integrated with the module system for rapid
  594. dynamic development, which is made even more convenient with the Emacs
  595. interface, 'scheme48.el'; *note Emacs integration::.
  596. * Menu:
  597. * Basic commands::
  598. * Command processor switches::
  599. * Emacs integration commands::
  600. * Focus value::
  601. * Command levels::
  602. * Module commands::
  603. * SRFI 7::
  604. * Debugging commands::
  605. * Inspector::
  606. * Command programs::
  607. * Image-building commands::
  608. * Resource statistics and control::
  609. 
  610. File: scheme48.info, Node: Basic commands, Next: Command processor switches, Up: Command processor
  611. 2.4.1 Basic commands
  612. --------------------
  613. There are several generally useful commands built-in, along with many
  614. others described in subsequent sections:
  615. -- command: ,help
  616. -- command: ,help command
  617. -- command: ,?
  618. -- command: ,? command
  619. Requests help on commands. ',?' is an alias for ',help'. Plain
  620. ',help' lists a synopsis of all commands available, as well as all
  621. switches (*note Command processor switches::). ',help COMMAND'
  622. requests help on the particular command COMMAND.
  623. -- command: ,exit
  624. -- command: ,exit status
  625. -- command: ,exit-when-done
  626. -- command: ,exit-when-done status
  627. Exits the command processor. ',exit' immediately exits with an
  628. exit status of 0. ',exit STATUS' exits with the status that
  629. evaluating the expression STATUS in the interaction environment
  630. produces. ',exit-when-done' is like ',exit', but it waits until
  631. all threads complete before exiting.
  632. -- command: ,go expression
  633. ',go' is like ',exit', except that it requires an argument, and it
  634. evaluates EXPRESSION in the interaction environment in a _tail
  635. context_ with respect to the command processor. This means that
  636. the command processor may no longer be reachable by the garbage
  637. collector, and may be collected as garbage during the evaluation of
  638. EXPRESSION. For example, the full Scheme48 command processor is
  639. bootstrapped from a minimal one that supports the ',go' command.
  640. The full command processor is initiated in an argument to the
  641. command, but the minimal one is no longer reachable, so it may be
  642. collected as garbage, leaving only the full one.
  643. -- command: ,run expression
  644. Evaluates EXPRESSION in the interaction environment. Alone, this
  645. command is not very useful, but it is required in situations such
  646. as the inspector (*note Inspector::) and command programs (*note
  647. Command programs::).
  648. -- command: ,undefine name
  649. Removes the binding for NAME in the interaction environment.
  650. -- command: ,load filename ...
  651. Loads the contents each FILENAME as Scheme source code into the
  652. interaction environment. Each FILENAME is translated first (*note
  653. Filenames::). The given filenames may be surrounded or not by
  654. double-quotes; however, if a filename contains spaces, it must be
  655. surrounded by double-quotes. The differences between the ',load'
  656. command and Scheme's 'load' procedure are that ',load' does not
  657. require its arguments to be quoted, allows arbitrarily many
  658. arguments while the 'load' procedure accepts only one filename (and
  659. an optional environment), and works even in environments in which
  660. 'load' is not bound.
  661. -- command: ,translate from to
  662. A convenience for registering a filename translation without
  663. needing to open the 'filenames' structure. For more details on
  664. filename translations, *note Filenames::; this command corresponds
  665. with the 'filename' structure's 'set-translation!' procedure. As
  666. with ',load', each of the filenames FROM and TO may be surrounded
  667. or not by double-quotes, unless there is a space in the filenames,
  668. in which case it must be surrounded by double-quotes.
  669. Note that in the exec language (*note Command programs::),
  670. 'translate' is the same as the 'filenames' structure's
  671. 'set-translation!' procedure, _not_ the procedure named 'translate'
  672. from the 'filenames' structure.
  673. 
  674. File: scheme48.info, Node: Command processor switches, Next: Emacs integration commands, Prev: Basic commands, Up: Command processor
  675. 2.4.2 Switches
  676. --------------
  677. The Scheme48 command processor keeps track of a set of "switches",
  678. user-settable configurations.
  679. -- command: ,set switch
  680. -- command: ,set switch {on|off|?}
  681. -- command: ,unset switch
  682. -- command: ,set ?
  683. ',set SWITCH' & ',set SWITCH on' set the switch SWITCH on. ',unset
  684. SWITCH' & ',set SWITCH off' turn SWITCH off. ',set SWITCH ?' gives
  685. a brief description of SWITCH's current status. ',set ?' gives
  686. information about all the available switches and their current
  687. state.
  688. The following switches are defined. Each switch is listed with its
  689. name and its default status.
  690. 'ask-before-loading' _(off)_
  691. If this is on, Scheme48 will prompt the user before loading
  692. modules' code. If it is off, it will quietly just load it.
  693. 'batch' _(off)_
  694. Batch mode is intended for automated uses of the command processor.
  695. With batch mode on, errors cause the command processor to exit, and
  696. the prompt is not printed.
  697. 'break-on-warnings' _(off)_
  698. If the 'break-on-warnings' switch is on, warnings (*note Condition
  699. system::) signalled that reach the command processor's handler will
  700. cause a command level (*note Command levels::) to be pushed,
  701. similarly to breakpoints and errors.
  702. 'inline-values' _(off)_
  703. 'Inline-values' tells whether or not certain procedures may be
  704. integrated in-line.
  705. 'levels' _(on)_
  706. Errors will push a new command level (*note Command levels::) if
  707. this switch is on, or they will just reset back to the top level if
  708. 'levels' is off.
  709. 'load-noisily' _(off)_
  710. Loading source files will cause messages to be printed if
  711. 'load-noisily' is on; otherwise they will be suppressed.
  712. 
  713. File: scheme48.info, Node: Emacs integration commands, Next: Focus value, Prev: Command processor switches, Up: Command processor
  714. 2.4.3 Emacs integration commands
  715. --------------------------------
  716. There are several commands that exist mostly for Emacs integration
  717. (*note Emacs integration::); although they may be used elsewhere, they
  718. are not very useful or convenient without 'scheme48.el'.
  719. -- command: ,from-file filename
  720. -- command: ,end
  721. ',from-file FILENAME' proclaims that the code following the
  722. command, until an ',end' command, comes from FILENAME -- for
  723. example, this may be due to an appropriate Emacs command, such as
  724. 'C-c C-l' in 'scheme48.el' --; if this is the first time the
  725. command processor has seen code from FILENAME, it is registered to
  726. correspond with the interaction environment wherein the
  727. ',from-file' command was used. If it is not the first time, the
  728. code is evaluated within the package that was registered for
  729. FILENAME.
  730. -- command: ,forget filename
  731. Clears the command processor's memory of the package to which
  732. FILENAME corresponds.
  733. 
  734. File: scheme48.info, Node: Focus value, Next: Command levels, Prev: Emacs integration commands, Up: Command processor
  735. 2.4.4 Focus value
  736. -----------------
  737. The Scheme48 command processor maintains a current "focus value". This
  738. is typically the value that the last expression evaluated to, or a list
  739. of values if it returned multiple values. If it evaluated to either
  740. zero values or Scheme48's 'unspecific' token (*note System features::),
  741. the focus value is unchanged. At the initial startup of Scheme48, the
  742. focus value is set to the arguments passed to Scheme48's virtual machine
  743. after the '-a' argument on the command-line (*note Running Scheme48::).
  744. The focus value is accessed through the '##' syntax; the reader
  745. substitutes a special quotation (special so that the compiler will not
  746. generate warnings about a regular 'quote' expression containing a weird
  747. value) for occurrences of '##'. Several commands, such as ',inspect'
  748. and ',dis', either accept an argument or use the current focus value.
  749. Also, in the inspector (*note Inspector::), the focus object is the
  750. object that is currently being inspected.
  751. > (cons 1 2)
  752. '(1 . 2)
  753. > ##
  754. '(1 . 2)
  755. > (begin (display "Hello, world!") (newline))
  756. Hello, world!
  757. > ##
  758. '(1 . 2)
  759. > (cdr ##)
  760. 2
  761. > (define x 5)
  762. ; no values returned
  763. > (+ ## x)
  764. 7
  765. > (values 1 2 3)
  766. ; 3 values returned
  767. 1
  768. 2
  769. 3
  770. > ##
  771. '(1 2 3)
  772. 
  773. File: scheme48.info, Node: Command levels, Next: Module commands, Prev: Focus value, Up: Command processor
  774. 2.4.5 Command levels
  775. --------------------
  776. The Scheme48 command processor maintains a stack of "command levels", or
  777. recursive invocations of the command processor. Each command level
  778. retains information about the point from the previous command level at
  779. which it was pushed: the threads that were running -- which the command
  780. processor suspends --, including the thread of that command level
  781. itself; the continuation of what pushed the level; and, if applicable,
  782. the condition (*note Condition system::) that caused the command level
  783. to be pushed. Each command level has its own thread scheduler, which
  784. controls all threads running at that level, including those threads'
  785. children.
  786. Some beginning users may find command levels confusing, particularly
  787. those who are new to Scheme or who are familiar with the more simplistic
  788. interaction methods of other Scheme systems. These users may disable
  789. the command level system with the 'levels' switch (*note Command
  790. processor switches::) by writing the command ',set levels off'.
  791. -- command: ,push
  792. -- command: ,pop
  793. -- command: ,resume
  794. -- command: ,resume level
  795. -- command: ,reset
  796. -- command: ,reset level
  797. ',push' pushes a new command level. ',pop' pops the current
  798. command level. 'C-d'/'^D', or EOF, has the same effect as the
  799. ',pop' command. Popping the top command level inquires the user
  800. whether to exit or to return to the top level. ',resume LEVEL'
  801. pops all command levels down to LEVEL and resumes all threads that
  802. were running at LEVEL when it was suspended to push another command
  803. level. ',reset LEVEL' resets the command processor to LEVEL,
  804. terminating all threads at that level but the command reader
  805. thread. ',resume' & ',reset' with no argument use the top command
  806. level.
  807. -- command: ,condition
  808. -- command: ,threads
  809. ',condition' sets the focus value to the condition that caused the
  810. command level to be pushed, or prints 'no condition' if there was
  811. no relevant condition. ',threads' invokes the inspector on the
  812. list of threads of the previous command level, or on nothing if the
  813. current command level is the top one.
  814. > ,push
  815. 1> ,push
  816. 2> ,pop
  817. 1> ,reset
  818. Top level
  819. > ,open threads formats
  820. > ,push
  821. 1> ,push
  822. 2> (spawn (lambda ()
  823. (let loop ()
  824. (sleep 10000) ; Sleep for ten seconds.
  825. (format #t "~&foo~%")
  826. (loop)))
  827. 'my-thread)
  828. 2>
  829. foo
  830. ,push
  831. 3> ,threads
  832. ; 2 values returned
  833. [0] '#{Thread 4 my-thread}
  834. [1] '#{Thread 3 command-loop}
  835. 3: q
  836. '(#{Thread 4 my-thread} #{Thread 3 command-loop})
  837. 3> ,resume 1
  838. foo
  839. 2>
  840. foo
  841. ,push
  842. 3> ,reset 1
  843. Back to 1> ,pop
  844. >
  845. 
  846. File: scheme48.info, Node: Module commands, Next: SRFI 7, Prev: Command levels, Up: Command processor
  847. 2.4.6 Module commands
  848. ---------------------
  849. Scheme48's command processor is well-integrated with its module system
  850. (*note Module system::). It has several dedicated environments,
  851. including the user package and the config package, and can be used to
  852. evaluate code within most packages in the Scheme48 image during program
  853. development. The config package includes bindings for Scheme48's
  854. configuration language; structure & interface definitions may be
  855. evaluated in it. The command processor also has provisions to support
  856. rapid development and module reloading by automatically updating
  857. references to redefined variables in compiled code without having to
  858. reload all of that code.
  859. -- command: ,open struct ...
  860. Opens each STRUCT into the interaction environment, making all of
  861. its exported bindings available. This may have the consequence of
  862. loading code to implement those bindings. If there was code
  863. evaluated in the interaction environment that referred to a
  864. previously undefined variable for whose name a binding was exported
  865. by one of these structures, a message is printed to the effect that
  866. that binding is now available, and the code that referred to that
  867. undefined variable will be modified to subsequently refer to the
  868. newly available binding.
  869. -- command: ,load-package struct
  870. -- command: ,reload-package struct
  871. ',load-package' and ',reload-package' both load the code associated
  872. with the package underlying STRUCT, after ensuring that all of the
  873. other structures opened by that package are loaded as well.
  874. ',load-package' loads the code only if has not already been loaded;
  875. ',reload-package' unconditionally loads it.
  876. -- command: ,user
  877. -- command: ,user command-or-exp
  878. -- command: ,config
  879. -- command: ,config command-or-exp
  880. -- command: ,for-syntax
  881. -- command: ,for-syntax command-or-exp
  882. -- command: ,new-package
  883. -- command: ,in structure
  884. -- command: ,in structure command-or-exp
  885. These all operate on the interaction environment. ',user' sets it
  886. to the user package, which is the default at initial startup.
  887. ',user COMMAND-OR-EXP' temporarily sets the interaction environment
  888. to the user package, processes COMMAND-OR-EXP, and reverts the
  889. interaction environment to what it was before ',user' was invoked.
  890. The ',config' & ',for-syntax' commands are similar, except that
  891. they operate on the config package and the package used for the
  892. user package's macros (*note Macros in concert with modules::).
  893. ',new-package' creates a temporary, unnamed package with a vanilla
  894. R5RS environment and sets the interaction environment to it. That
  895. new package is not accessible in any way except to the user of the
  896. command processor, and it is destroyed after the user switches to
  897. another environment (unless the user uses the ',structure' command;
  898. see below). ',in STRUCTURE' sets the interaction environment to be
  899. STRUCTURE's package; STRUCTURE is a name whose value is extracted
  900. from the config package. ',in STRUCTURE COMMAND-OR-EXP' sets the
  901. interaction environment to STRUCTURE temporarily to process
  902. COMMAND-OR-EXP and then reverts it to what it was before the use of
  903. ',in'. Note that, within a structure, the bindings available are
  904. exactly those bindings that would be available within the
  905. structure's static code, i.e. code in the structure's 'begin'
  906. package clauses or code in files referred to by 'files' package
  907. clauses.
  908. -- command: ,user-package-is struct
  909. -- command: ,config-package-is struct
  910. ',user-package-is' & ',config-package-is' set the user & config
  911. packages, respectively, to be STRUCT's package. STRUCT is a name
  912. whose value is accessed from the current config package.
  913. -- command: ,structure name interface
  914. This defines a structure named NAME in the config package that is a
  915. view of INTERFACE on the current interaction environment.
  916. 
  917. File: scheme48.info, Node: SRFI 7, Next: Debugging commands, Prev: Module commands, Up: Command processor
  918. 2.4.7 SRFI 7
  919. ------------
  920. Scheme48 supports [SRFI 7] after loading the 'srfi-7' structure by
  921. providing two commands for loading [SRFI 7] programs:
  922. -- command: ,load-srfi-7-program name filename
  923. -- command: ,load-srfi-7-script name filename
  924. These load [SRFI 7] a program into a newly constructed structure,
  925. named NAME, which opens whatever other structures are needed by
  926. features specified in the program. ',load-srfi-7-program' loads a
  927. simple [SRFI 7] program; ',load-srfi-7-script' skips the first
  928. line, intended for [SRFI 22] Unix scripts.
  929. 
  930. File: scheme48.info, Node: Debugging commands, Next: Inspector, Prev: SRFI 7, Up: Command processor
  931. 2.4.8 Debugging commands
  932. ------------------------
  933. There are a number of commands useful for debugging, along with a
  934. continuation inspector, all of which composes a convenient debugger.
  935. -- command: ,bound? name
  936. -- command: ,where
  937. -- command: ,where procedure
  938. ',bound?' prints out binding information about NAME, if it is bound
  939. in the interaction environment, or 'Not bound' if NAME is unbound.
  940. ',where' prints out information about what file and package its
  941. procedure argument was created in. If PROCEDURE is not passed,
  942. ',where' uses the focus value. If ',where''s argument is not a
  943. procedure, it informs the user of this fact. If ',where' cannot
  944. find the location of its argument's creation, it prints 'Source
  945. file not recorded.'
  946. -- command: ,expand
  947. -- command: ,expand exp
  948. -- command: ,dis
  949. -- command: ,dis proc
  950. ',expand' prints out a macro-expansion of EXP, or the focus value
  951. if EXP is not provided. The expression to be expanded should be an
  952. ordinary S-expression. The expansion may contain 'generated names'
  953. and 'qualified names.' These merely contain lexical context
  954. information that allow one to differentiate between identifiers
  955. with the same name. Generated names look like '#{Generated NAME
  956. UNIQUE-NUMERIC-ID}'. Qualified names appear to be vectors; they
  957. look like '#(>> INTRODUCER-MACRO NAME UNIQUE-NUMERIC-ID)', where
  958. INTRODUCER-MACRO is the macro that introduced the name.
  959. ',dis' prints out a disassembly of its procedure, continuation, or
  960. template argument. If PROC is passed, it is evaluated in the
  961. interaction environment; if not, ',dis' disassembles the focus
  962. value. The disassembly is of Scheme48's virtual machine's byte
  963. code.(1)
  964. -- command: ,condition
  965. -- command: ,threads
  966. For the descriptions of these commands, *note Command levels::.
  967. These are mentioned here because they are relevant in the context
  968. of debugging.
  969. -- command: ,trace
  970. -- command: ,trace name ...
  971. -- command: ,untrace
  972. -- command: ,untrace name ...
  973. Traced procedures will print out information about when they are
  974. entered and when they exit. ',trace' lists all of the traced
  975. procedures' bindings. ',trace NAME ...' sets each NAME in the
  976. interaction environment, which should be bound to a procedure, to
  977. be a traced procedure over the original procedure. ',untrace'
  978. resets all traced procedures to their original, untraced
  979. procedures. ',untrace NAME ...' untraces each individual traced
  980. procedure of NAME ... in the interaction environment.
  981. -- command: ,preview
  982. Prints a trace of the previous command level's suspended
  983. continuation. This is analogous with stack traces in many
  984. debuggers.
  985. -- command: ,debug
  986. Invokes the debugger: runs the inspector on the previous command
  987. level's saved continuation. For more details, *note Inspector::.
  988. -- command: ,proceed
  989. -- command: ,proceed exp
  990. Returns to the continuation of the condition signalling of the
  991. previous command level. Only certain kinds of conditions will push
  992. a new command level, however -- breakpoints, errors, and
  993. interrupts, and, if the 'break-on-warnings' switch is on, warnings
  994. --; also, certain kinds of errors that do push new command levels
  995. do not permit being proceeded from. In particular, only with a few
  996. VM primitives may the ',proceed' command be used. If EXP is
  997. passed, it is evaluated in the interaction environment to produce
  998. the values to return; if it is not passed, zero values are
  999. returned.
  1000. ---------- Footnotes ----------
  1001. (1) A description of the byte code is forthcoming, although it does
  1002. not have much priority to this manual's author. For now, users can read
  1003. the rudimentary descriptions of the Scheme48 virtual machine's byte code
  1004. instruction set in 'vm/interp/arch.scm' of Scheme48's Scheme source.
  1005. 
  1006. File: scheme48.info, Node: Inspector, Next: Command programs, Prev: Debugging commands, Up: Command processor
  1007. 2.4.9 Inspector
  1008. ---------------
  1009. Scheme48 provides a simple interactive object inspector. The command
  1010. processor's prompt's end changes from '>' to ':' when in inspection
  1011. mode. The inspector is the basis of the debugger, which is, for the
  1012. most part, merely an inspector of continuations. In the debugger, the
  1013. prompt is 'debug:'. In the inspector, objects are printed followed by
  1014. menus of their components. Entries in the menu are printed with the
  1015. index, which optionally includes a symbolic name, and the value of the
  1016. component. For example, a pair whose car is the symbol 'a' and whose
  1017. cdr is the symbol 'b' would be printed by the inspector like this:
  1018. '(a . b)
  1019. [0: car] 'a
  1020. [1: cdr] 'b
  1021. The inspector maintains a stack of the focus objects it previously
  1022. inspected. Selecting a new focus object pushes the current one onto the
  1023. stack; the 'u' command pops the stack.
  1024. -- command: ,inspect
  1025. -- command: ,inspect exp
  1026. Invokes the inspector. If EXP is present, it is evaluated in the
  1027. user package and its result is inspected (or a list of results, if
  1028. it returned multiple values, is inspected). If EXP is absent, the
  1029. current focus value is inspected.
  1030. The inspector operates with its own set of commands, separate from
  1031. the regular interaction commands, although regular commands may be
  1032. invoked from the inspector as normal. Inspector commands are entered
  1033. with or without a preceding comma at the inspector prompt. Multiple
  1034. inspector commands may be entered on one line; an input may also consist
  1035. of an expression to be evaluated. If an expression is evaluated, its
  1036. value is selected as the focus object. Note, however, that, since
  1037. inspector commands are symbols, variables cannot be evaluated just by
  1038. entering their names; one must use either the ',run' command or wrap the
  1039. variables in a 'begin'.
  1040. These inspector commands are defined:
  1041. -- inspector command: menu
  1042. -- inspector command: m
  1043. 'Menu' prints a menu for the focus object. 'M' moves forward in
  1044. the current menu if there are more than sixteen items to be
  1045. displayed.
  1046. -- inspector command: u
  1047. Pops the stack of focus objects, discarding the current one and
  1048. setting the focus object to the current top of the stack.
  1049. -- inspector command: q
  1050. Quits the inspector, going back into the read-eval-print loop.
  1051. -- inspector command: template
  1052. Attempts to coerce the focus object into a template. If
  1053. successful, this selects it as the new focus object; if not, this
  1054. prints an error to that effect. Templates are the static
  1055. components of closures and continuations: they contain the code for
  1056. the procedure, the top-level references made by the procedure,
  1057. literal constants used in the code, and any inferior templates of
  1058. closures that may be constructed by the code.
  1059. -- inspector command: d
  1060. Goes down to the parent of the continuation being inspected. This
  1061. command is valid only in the debugger mode, i.e. when the focus
  1062. object is a continuation.
  1063. 
  1064. File: scheme48.info, Node: Command programs, Next: Image-building commands, Prev: Inspector, Up: Command processor
  1065. 2.4.10 Command programs
  1066. -----------------------
  1067. The Scheme48 command processor can be controlled programmatically by
  1068. "command programs", programs written in the "exec language". This
  1069. language is essentially a mirror of the commands but in a syntax using
  1070. S-expressions. The language also includes all of Scheme. The exec
  1071. language is defined as part of the "exec package".
  1072. -- command: ,exec
  1073. -- command: ,exec command
  1074. Sets the interaction environment to be the exec package. If an
  1075. argument is passed, it is set temporarily, only to run the given
  1076. command.
  1077. Commands in the exec language are invoked as procedures in Scheme.
  1078. Arguments should be passed as follows:
  1079. * Identifiers, such as those of structure names in the config
  1080. package, should be passed as literal symbols. For instance, the
  1081. command ',in frobbotz' would become in the exec language '(in
  1082. 'frobbotz)'.
  1083. * Filenames should be passed as strings; e.g., ',dump frob.image'
  1084. becomes '(dump "frob.image")'.
  1085. * Commands should be represented in list values with the car being
  1086. the command name and the cdr being the arguments. Note that when
  1087. applying a command an argument that is a command invocation is
  1088. often quoted to produce a list, but the list should not include any
  1089. quotation; for instance, ',in mumble ,undefine frobnicate' would
  1090. become '(in 'mumble '(undefine frobnicate))', even though simply
  1091. ',undefine frobnicate' would become '(undefine 'frobnicate)'.
  1092. The reason for this is that the command invocation in the exec
  1093. language is different from a list that represents a command
  1094. invocation passed as an argument to another command; since commands
  1095. in the exec language are ordinary procedures, the arguments must be
  1096. quoted, but the quoted arguments are not themselves evaluated: they
  1097. are applied as commands.
  1098. An argument to a command that expects a command invocation can also
  1099. be a procedure, which would simply be called with zero arguments.
  1100. For instance, '(config (lambda () (display
  1101. (interaction-environment)) (newline)))' will call the given
  1102. procedure with the interaction environment set to the config
  1103. package.
  1104. * Expressions must be passed using the 'run' command. For example,
  1105. the equivalent of ',user (+ 1 2)' in the exec language would be
  1106. '(user '(run (+ 1 2)))'.
  1107. Command programs can be loaded by running the ',load' command in the
  1108. exec package. Scripts to load application bundles are usually written
  1109. in the exec language and loaded into the exec package. For example,
  1110. this command program, when loaded into the exec package, will load
  1111. 'foo.scm' into the config package, ensure that the package 'frobbotzim'
  1112. is loaded, and open the 'quuxim' structure in the user package:
  1113. (config '(load "foo.scm"))
  1114. (load-package 'frobbotzim)
  1115. (user '(open quuxim))
  1116. 
  1117. File: scheme48.info, Node: Image-building commands, Next: Resource statistics and control, Prev: Command programs, Up: Command processor
  1118. 2.4.11 Image-building commands
  1119. ------------------------------
  1120. Since Scheme48's operation revolves about an image-based model, these
  1121. commands provide a way to save heap images on the file system, which may
  1122. be resumed by invoking the Scheme48 virtual machine on them as in *note
  1123. Running Scheme48::.
  1124. -- command: ,build resumer filename
  1125. -- command: ,dump filename
  1126. -- command: ,dump filename message
  1127. ',build' evaluates RESUMER, whose value should be a unary
  1128. procedure, and builds a heap image in FILENAME that, when resumed
  1129. by the virtual machine, will pass the resumer all of the
  1130. command-line arguments after the '-a' argument to the virtual
  1131. machine. The run-time system will have been initialized as with
  1132. usual resumers (*note Suspending and resuming heap images::), and a
  1133. basic condition handler will have been installed by the time that
  1134. the resumer is called. On Unix, RESUMER must return an integer
  1135. exit status for the process. ',dump' dumps the Scheme48 command
  1136. processor, including all of the current settings, to FILENAME. If
  1137. MESSAGE is passed, it should be a string delimited by
  1138. double-quotes, and it will be printed as part of the welcome banner
  1139. on startup; its default value, if it is not present, is
  1140. '"(suspended image)"'.
  1141. 
  1142. File: scheme48.info, Node: Resource statistics and control, Prev: Image-building commands, Up: Command processor
  1143. 2.4.12 Resource statistics and control
  1144. --------------------------------------
  1145. Scheme48 provides several devices for querying statistics about various
  1146. resources and controlling resources, both in the command processor and
  1147. programmatically.
  1148. -- command: ,collect
  1149. Forces a garbage collection and prints the amount of space in the
  1150. heap before and after the collection.
  1151. -- command: ,time expression
  1152. Evaluates EXPRESSION and prints how long it took. Three numbers
  1153. are printed: run time, GC time, and real time. The run time is the
  1154. amount of time in Scheme code; the GC time is the amount of time
  1155. spent in the garbage collector; and the real time is the actual
  1156. amount of time that passed during the expression's evaluation.
  1157. -- command: ,keep
  1158. -- command: ,keep kind ...
  1159. -- command: ,flush
  1160. -- command: ,flush kind ...
  1161. Scheme48 maintains several different kinds of information used for
  1162. debugging information. ',keep' with no arguments shows what kinds
  1163. of debugging data are preserved and what kinds are not. ',keep
  1164. KIND ...' requests that the debugging data of the given kinds
  1165. should be kept; the ',flush' command requests the opposite.
  1166. ',flush' with no arguments flushes location names and resets the
  1167. debug data table. The following are the kinds of debugging data:
  1168. 'names'
  1169. procedure names
  1170. 'maps'
  1171. environment maps used by the debugger to show local variable
  1172. names
  1173. 'files'
  1174. filenames where procedures were defined
  1175. 'source'
  1176. source code surrounding continuations, printed by the debugger
  1177. 'tabulate'
  1178. if true, will store debug data records in a global table that
  1179. can be easily flushed; if false, will store directly in
  1180. compiled code
  1181. ',flush' can also accept 'location-names', which will flush the
  1182. table of top-level variables' names (printed, for example, by the
  1183. ',bound?' command); 'file-packages', which will flush the table
  1184. that maps filenames to packages in which code from those files
  1185. should be evaluated; or 'table', in which case the table of debug
  1186. data is flushed.
  1187. Removing much debug data can significantly reduce the size of
  1188. Scheme48 heap images, but it can also make error messages and
  1189. debugging much more difficult. Usually, all debug data is
  1190. retained; only for images that must be small and that do not need
  1191. to be debuggable should the debugging data flags be turned off.
  1192. The 'spatial' structure exports these utilities for displaying
  1193. various statistics about the heap:
  1194. -- procedure: space --> unspecified
  1195. -- procedure: vector-space [predicate] --> unspecified
  1196. -- procedure: record-space [predicate] --> unspecified
  1197. 'Space' prints out a list of the numbers of all objects and the
  1198. number of bytes allocated for those objects on the heap,
  1199. partitioned by the objects' primitive types and whether or not they
  1200. are immutable (pure) or mutable (impure). 'Vector-space' prints
  1201. the number of vectors and the number of bytes used to store those
  1202. vectors of several different varieties, based on certain heuristics
  1203. about their form. If the predicate argument is passed, it gathers
  1204. only vectors that satisfy that predicate. 'Record-space' prints
  1205. out, for each record type in the heap, both the number of all
  1206. instances of that record type and the number of bytes used to store
  1207. all of those instances. Like 'vector-space', if the predicate
  1208. argument is passed, 'record-space' will consider only those records
  1209. that satisfy the predicate.
  1210. All of these three procedures first invoke the garbage collector
  1211. before gathering statistics.
  1212. The 'traverse' structure provides a simple utility for finding paths
  1213. by which objects refer to one another.
  1214. -- procedure: traverse-breadth-first object --> unspecified
  1215. -- procedure: traverse-depth-first object --> unspecified
  1216. These traverse the heap, starting at OBJECT, recording all objects
  1217. transitively referred to. 'Traverse-breadth-first' uses a
  1218. FIFO-queue-directed breadth-first graph traversal, while
  1219. 'traverse-depth-first' uses a LIFO-stack-directed depth-first graph
  1220. traversal. The traversal halts at any leaves in the graph, which
  1221. are distinguished by an internal "leaf predicate" in the module.
  1222. See below on 'set-leaf-predicate!' on how to customize this and
  1223. what the default is.
  1224. The traversal information is recorded in a global resource; it is
  1225. not thread-safe, and intended only for interactive usage. The
  1226. record can be reset by passing some simple object with no
  1227. references to either 'traverse-breadth-first' or
  1228. 'traverse-depth-first'; e.g., '(traverse-depth-first #f)'.
  1229. -- procedure: trail object --> unspecified
  1230. After traversing the heap from an initial object, '(trail OBJECT)'
  1231. prints the path of references and intermediate objects by which the
  1232. initial object holds a transitive reference to OBJECT.
  1233. -- procedure: set-leaf-predicate! predicate --> unspecified
  1234. -- procedure: usual-leaf-predicate object --> boolean
  1235. 'Set-leaf-predicate!' sets the current leaf predicate to be
  1236. PREDICATE. 'Usual-leaf-predicate' is the default leaf predicate;
  1237. it considers simple numbers (integers and flonums), strings, byte
  1238. vectors, characters, and immediate objects (true, false, nil, and
  1239. the unspecific object) to be leaves, and everything else to be
  1240. branches.
  1241. 
  1242. File: scheme48.info, Node: Module system, Next: System facilities, Prev: User environment, Up: Top
  1243. 3 Module system
  1244. ***************
  1245. Scheme48 has an advanced module system that is designed to interact well
  1246. with macros, incremental compilation, and the interactive development
  1247. environment's (*note User environment::) code reloading facilities for
  1248. rapid program development. For details on the integration of the module
  1249. system and the user environment for rapid code reloading, *note Using
  1250. the module system::.
  1251. * Menu:
  1252. * Module system architecture::
  1253. * Module configuration language:: Language of the module system
  1254. * Macros in concert with modules::
  1255. * Static type system::
  1256. 
  1257. File: scheme48.info, Node: Module system architecture, Next: Module configuration language, Up: Module system
  1258. 3.1 Module system architecture
  1259. ==============================
  1260. The fundamental mechanism by which Scheme code is evaluated is the
  1261. lexical environment. Scheme48's module system revolves around this
  1262. fundamental concept. Its purpose is to control the denotation of names
  1263. in code(1) in a structured, modular manner. The module system is
  1264. manipulated by a static "configuration language", described in the next
  1265. section; this section describes the concepts in the architecture of the
  1266. module system.
  1267. The "package" is the entity internal to the module system that maps a
  1268. set of names to denotations. For example, the package that represents
  1269. the Scheme language maps 'lambda' to a descriptor for the special form
  1270. that the compiler interprets to construct a procedure, 'car' to the
  1271. procedure that accesses the car of a pair, &c. Packages are not
  1272. explicitly manipulated by the configuration language, but they lie
  1273. underneath structures, which are described below. A package also
  1274. contains the code of a module and controls the visibility of names
  1275. within that code. It also includes some further information, such as
  1276. optimizer switches. A "structure" is a view on a package; that is, it
  1277. contains a package and an "interface" that lists all of the names it
  1278. exports to the outside. Multiple structures may be constructed atop a
  1279. single package; this mechanism is often used to offer multiple
  1280. abstraction levels to the outside. A "module" is an abstract entity: it
  1281. consists of some code, the namespace visible to the code, and the set of
  1282. abstractions or views upon that code.
  1283. A package contains a list of the structures whose bindings should be
  1284. available in the code of that package. If a structure is referred to in
  1285. a such a list of a package, the package is said to "open" that
  1286. structure. It is illegal for a package to open two structures whose
  1287. interfaces contain the same name.(2) Packages may also modify the names
  1288. of the bindings that they import. They may import only selected
  1289. bindings, exclude certain bindings from structures, rename imported
  1290. bindings, create alias bindings, and add prefixes to names.
  1291. Most packages will open the standard 'scheme' structure, although it
  1292. is not implicitly opened, and the module system allows not opening
  1293. 'scheme'. It may seem to be not very useful to not open it, but this is
  1294. necessary if some bindings from it are intended to be shadowed by
  1295. another structure, and it allows for entirely different languages from
  1296. Scheme to be used in a package's code. For example, Scheme48's byte
  1297. code interpreter virtual machine is implemented in a subset of Scheme
  1298. called Pre-Scheme, which is described in a later chapter in this manual.
  1299. The modules that compose the VM all open not the 'scheme' structure but
  1300. the _'prescheme'_ structure. The configuration language itself is
  1301. controlled by the module system, too. In another example, from Scsh,
  1302. the Scheme shell, there is a structure 'scsh' that contains all of the
  1303. Unix shell programming facilities. However, the 'scsh' structure
  1304. necessarily modifies some of the bindings related to I/O that the
  1305. 'scheme' structure exports. Modules could not open both 'scheme' and
  1306. 'scsh', because they both provide several bindings with the same names,
  1307. so Scsh defines a more convenient 'scheme-with-scsh' structure that
  1308. opens both 'scheme', but with all of the shadowed bindings excluded, and
  1309. 'scsh'; modules that use Scsh would open neither 'scsh' nor 'scheme':
  1310. they instead open just 'scheme-with-scsh'.
  1311. Interfaces are separated from structures in order that they may be
  1312. reüsed and combined. For example, several different modules may
  1313. implement the same abstractions differently. The structures that they
  1314. include would, in such cases, reüse the same interfaces. Also, it is
  1315. sometimes desirable to combine several interfaces into a "compound
  1316. interface"; see the 'compound-interface' form in the next section.
  1317. Furthermore, during interactive development, interface definitions may
  1318. be reloaded, and the structures that use them will automatically begin
  1319. using the new interfaces; *note Using the module system::.
  1320. Scheme48's module system also supports "parameterized modules".
  1321. Parameterized modules, sometimes known as "generic modules",
  1322. "higher-order modules" or "functors", are essentially functions at the
  1323. module system level that map structures to structures. They may be
  1324. instantiated or applied arbitrarily many times, and they may accept and
  1325. return arbitrarily many structures. Parameterized modules may also
  1326. accept and return other parameterized modules.
  1327. ---------- Footnotes ----------
  1328. (1) This is in contrast to, for example, Common Lisp's package
  1329. system, which controls the mapping from strings to names.
  1330. (2) The current implementation, however, does not detect this.
  1331. Instead it uses the left-most structure in the list of a package's
  1332. 'open' clause; see the next section for details on this.
  1333. 
  1334. File: scheme48.info, Node: Module configuration language, Next: Macros in concert with modules, Prev: Module system architecture, Up: Module system
  1335. 3.2 Module configuration language
  1336. =================================
  1337. Scheme48's module system is used through a "module configuration
  1338. language". _The configuration language is entirely separate from
  1339. Scheme._ Typically, in one configuration, or set of components that
  1340. compose a program, there is an 'interfaces.scm' file that defines all of
  1341. the interfaces used by the configuration, and there is also a
  1342. 'packages.scm' file that defines all of the packages & structures that
  1343. compose it. Note that modules are not necessarily divided into files or
  1344. restricted to one file: modules may include arbitrarily many files, and
  1345. modules' code may also be written in-line to structure expressions (see
  1346. the 'begin' package clause below), although that is usually only for
  1347. expository purposes and trivial modules.
  1348. Structures are always created with corresponding "package clauses".
  1349. Each clause specifies an attribute of the package that underlies the
  1350. structure or structures created using the clauses. There are several
  1351. different types of clauses:
  1352. -- package clause: open structure ...
  1353. -- package clause: access structure ...
  1354. 'Open' specifies that the package should open each of the listed
  1355. structures, whose packages will be loaded if necessary. 'Access'
  1356. specifies that each listed structure should be accessible using the
  1357. '(structure-ref STRUCTURE IDENTIFIER)' special form, which
  1358. evaluates to the value of IDENTIFIER exported by the accessed
  1359. structure STRUCTURE. 'Structure-ref' is available from the
  1360. 'structure-refs' structure. Each STRUCTURE passed to 'access' is
  1361. not opened, however; the bindings exported thereby are available
  1362. only using 'structure-ref'. While the qualified 'structure-ref'
  1363. mechanism is no longer useful in the presence of modified
  1364. structures (see below on 'modify', 'subset', & 'with-prefix'), some
  1365. old code still uses it, and 'access' is also useful to force that
  1366. the listed structures' packages be loaded without cluttering the
  1367. namespace of the package whose clauses the 'access' clause is
  1368. among.
  1369. -- package clause: for-syntax package-clause ...
  1370. Specifies a set of package clauses for the next floor of the
  1371. reflective tower; *note Macros in concert with modules::.
  1372. -- package clause: files file-specifier ...
  1373. -- package clause: begin code ...
  1374. 'Files' and 'begin' specify the package's code. 'Files' takes a
  1375. sequence of namelists for the filenames of files that contain code;
  1376. *note Filenames::. 'Begin' accepts in-line program code.
  1377. -- package clause: optimize optimizer-specifier ...
  1378. -- package clause: integrate [on?]
  1379. 'Optimize' clauses request that specified compiler optimizers be
  1380. applied to the code. (Actually, 'optimizer' is a misnomer. The
  1381. 'optimize' clause may specify arbitrary passes that the compiler
  1382. can be extended with.) 'Integrate' clauses specify whether or not
  1383. integrable procedures from other modules, most notably Scheme
  1384. primitives such as 'car' or 'vector-ref', should actually be
  1385. integrated in this package. This is by default on. Most modules
  1386. should leave it on for any reasonable performance; only a select
  1387. few, into which code is intended to be dynamically loaded
  1388. frequently and in which redefinition of imported procedures is
  1389. common, need turn this off. The value of the argument to
  1390. 'integrate' clauses should be a literal boolean, i.e. '#t' or '#f';
  1391. if no argument is supplied, integration is enabled by default.
  1392. Currently, the only optimizer built-in to Scheme48 is the automatic
  1393. procedure integrator, or 'auto-integrate', which attempts stronger
  1394. type reconstruction than is attempted with most code (*note Static
  1395. type system::) and selects procedures below a certain size to be
  1396. made integrable (so that the body will be compiled in-line in all
  1397. known call sites). Older versions of Scheme48 also provided
  1398. another optimizer, 'flat-environments', which would flatten certain
  1399. lexical closure environments, rather than using a nested
  1400. environment structure. Now, however, Scheme48's byte code compiler
  1401. always flattens environments; specifying 'flat-environments' in an
  1402. 'optimize' clause does nothing.
  1403. A configuration is a sequence of definitions. There are definition
  1404. forms for only structures and interfaces.
  1405. -- configuration form: define-structure name interface package-clause
  1406. ...
  1407. -- configuration form: define-structures ((name interface) ...)
  1408. package-clause ...
  1409. 'Define-structure' creates a package with the given package clauses
  1410. and defines NAME to be the single view atop it, with the interface
  1411. INTERFACE. 'Define-structures' also creates a package with the
  1412. given package clauses; upon that package, it defines each NAME to
  1413. be a view on it with the corresponding interface.
  1414. -- configuration form: define-module (name parameter ...) definition
  1415. ... result
  1416. -- configuration form: def name ... (parameterized-module argument ...)
  1417. 'Define-module' defines NAME to be a parameterized module that
  1418. accepts the given parameters.
  1419. -- configuration form: define-interface name interface
  1420. Defines NAME to be the interface that INTERFACE evaluates to.
  1421. INTERFACE may either be an interface constructor application or
  1422. simply a name defined to be an interface by some prior
  1423. 'define-interface' form.
  1424. -- interface constructor: export export-specifier ...
  1425. 'Export' constructs a simple interface with the given export
  1426. specifiers. The export specifiers specify names to export and
  1427. their corresponding static types. Each EXPORT-SPECIFIER should
  1428. have one of the following forms:
  1429. 'SYMBOL'
  1430. in which case SYMBOL is exported with the most general value
  1431. type;
  1432. '(SYMBOL TYPE)'
  1433. in which case SYMBOL is exported with the given type; or
  1434. '((SYMBOL ...) TYPE)'
  1435. in which case each SYMBOL is exported with the same given type
  1436. For details on the valid forms of TYPE, *note Static type system::.
  1437. *Note:* All macros listed in interfaces _must_ be explicitly
  1438. annotated with the type ':syntax'; otherwise they would be exported
  1439. with a Scheme value type, which would confuse the compiler, because
  1440. it would not realize that they are macros: it would instead treat
  1441. them as ordinary variables that have regular run-time values.
  1442. -- interface constructor: compound-interface interface ...
  1443. This constructs an interface that contains all of the export
  1444. specifiers from each INTERFACE.
  1445. Structures may also be constructed anonymously; this is typically
  1446. most useful in passing them to or returning them from parameterized
  1447. modules.
  1448. -- structure constructor: structure interface package-clauses
  1449. -- structure constructor: structures (interface ...) package-clauses
  1450. 'Structure' creates a package with the given clauses and evaluates
  1451. to a structure over it with the given interface. 'Structures' does
  1452. similarly, but it evaluates to a number of structures, each with
  1453. the corresponding INTERFACE.
  1454. -- structure constructor: subset structure (name ...)
  1455. -- structure constructor: with-prefix structure name
  1456. -- structure constructor: modify structure modifier ...
  1457. These modify the interface of STRUCTURE. 'Subset' evaluates to a
  1458. structure that exports only NAME ..., excluding any other names
  1459. that STRUCTURE exported. 'With-prefix' adds a prefix NAME to every
  1460. name listed in STRUCTURE's interface. Both 'subset' and
  1461. 'with-prefix' are syntactic sugar for the more general 'modify',
  1462. which applies the modifier commands in a strictly right-to-left or
  1463. last-to-first order. *Note:* These all _denote new structures with
  1464. new interfaces_; they do not destructively modify existing
  1465. structures' interfaces.
  1466. -- modifier command: prefix name
  1467. -- modifier command: expose name ...
  1468. -- modifier command: hide name ...
  1469. -- modifier command: alias (from to) ...
  1470. -- modifier command: rename (from to) ...
  1471. 'Prefix' adds the prefix NAME to every exported name in the
  1472. structure's interface. 'Expose' exposes only NAME ...; any other
  1473. names are hidden. 'Hide' hides NAME .... 'Alias' exports each TO
  1474. as though it were the corresponding FROM, as well as each FROM.
  1475. 'Rename' exports each TO as if it were the corresponding FROM, but
  1476. it also hides the corresponding FROM.
  1477. Examples:
  1478. (modify STRUCTURE
  1479. (prefix foo:)
  1480. (expose bar baz quux))
  1481. makes only 'foo:bar', 'foo:baz', and 'foo:quux', available.
  1482. (modify STRUCTURE
  1483. (hide baz:quux)
  1484. (prefix baz:)
  1485. (rename (foo bar)
  1486. (mumble frotz))
  1487. (alias (gargle mumph)))
  1488. exports 'baz:gargle' as what was originally 'mumble', 'baz:mumph'
  1489. as an alias for what was originally 'gargle', 'baz:frotz' as what
  1490. was originally 'mumble', 'baz:bar' as what was originally 'foo',
  1491. _not_ 'baz:quux' -- what was originally simply 'quux' --, and
  1492. everything else that STRUCTURE exported, but with a prefix of
  1493. 'baz:'.
  1494. There are several simple utilities for binding variables to
  1495. structures locally and returning multiple structures not necessarily
  1496. over the same package (i.e. not with 'structures'). These are all valid
  1497. in the bodies of 'define-module' and 'def' forms, and in the arguments
  1498. to parameterized modules and 'open' package clauses.
  1499. -- syntax: begin body
  1500. -- syntax: let ((name value) ...) body
  1501. -- syntax: receive (name ...) producer body
  1502. -- syntax: values value ...
  1503. These are all as in ordinary Scheme. Note, however, that there is
  1504. no reasonable way by which to use 'values' except to call it, so it
  1505. is considered a syntax; also note that 'receive' may not receive a
  1506. variable number of values -- i.e. there are no 'rest lists' --,
  1507. because list values in the configuration language are nonsensical.
  1508. Finally, the configuration language also supports syntactic
  1509. extensions, or macros, as in Scheme.
  1510. -- configuration form: define-syntax name transformer-specifier
  1511. Defines the syntax transformer NAME to be the transformer specified
  1512. by TRANSFORMER-SPECIFIER. TRANSFORMER-SPECIFIER is exactly the
  1513. same as in Scheme code; it is evaluated as ordinary Scheme.
  1514. 
  1515. File: scheme48.info, Node: Macros in concert with modules, Next: Static type system, Prev: Module configuration language, Up: Module system
  1516. 3.3 Macros in concert with modules
  1517. ==================================
  1518. One reason that the standard Scheme language does not support a module
  1519. system yet is the issue of macros and modularity. There are several
  1520. issues to deal with:
  1521. * that compilation of code that uses macros requires presence of
  1522. those macros' definitions, which prevents true separate
  1523. compilation, because those macros may be from other modules;
  1524. * that a macro's expansion must preserve referential transparency and
  1525. hygiene, for example in cases where it refers to names from within
  1526. the module in which it was defined, even if those names weren't
  1527. exported; and
  1528. * that a macro's code may be arbitrary Scheme code, which in turn can
  1529. use other modules, so one module's compile-time, when macros are
  1530. expanded, is another's run-time, when the code used in macros is
  1531. executed by the expander: this makes a tower of phases of code
  1532. evaluation over which some coherent control must be provided.
  1533. Scheme48's module system tries to address all of these issues coherently
  1534. and comprehensively. Although it cannot offer _total_ separate
  1535. compilation, it can offer incremental compilation, and compiled modules
  1536. can be dumped to the file system & restored in the process of
  1537. incremental compilation.(1)
  1538. Scheme48's module system is also very careful to preserve non-local
  1539. module references from a macro's expansion. Macros in Scheme48 are
  1540. required to perform hygienic renaming in order for this preservation,
  1541. however; *note Explicit renaming macros::. For a brief example,
  1542. consider the 'delay' syntax for lazy evaluation. It expands to a simple
  1543. procedure call:
  1544. (delay EXPRESSION)
  1545. ==> (make-promise (lambda () EXPRESSION))
  1546. However, 'make-promise' is not exported from the 'scheme' structure.
  1547. The expansion works correctly due to the hygienic renaming performed by
  1548. the 'delay' macro transformer: when it hygienically renames
  1549. 'make-promise', the output contains not the symbol but a special token
  1550. that refers exactly to the binding of 'make-promise' from the
  1551. environment in which the 'delay' macro transformer was defined. Special
  1552. care is taken to preserve this information. Had 'delay' expanded to a
  1553. simple S-expression with simple symbols, it would have generated a free
  1554. reference to 'make-promise', which would cause run-time undefined
  1555. variable errors, or, if the module in which 'delay' was used had its
  1556. _own_ binding of or imported a binding of the name 'make-promise',
  1557. 'delay''s expansion would refer to the wrong binding, and there could
  1558. potentially be drastic and entirely unintended impact upon its
  1559. semantics.
  1560. Finally, Scheme48's module system has a special design for the tower
  1561. of phases, called a "reflective tower".(2) Every storey represents the
  1562. environment available at successive macro levels. That is, when the
  1563. right-hand side of a macro definition or binding is evaluated in an
  1564. environment, the next storey in that environment's reflective tower is
  1565. used to evaluate that macro binding. For example, in this code, there
  1566. are two storeys used in the tower:
  1567. (define (foo ...bar...)
  1568. (let-syntax ((baz ...quux...))
  1569. ...zot...))
  1570. In order to evaluate code in one storey of the reflective tower, it is
  1571. necessary to expand all macros first. Most of the code in this example
  1572. will eventually be evaluated in the first storey of the reflective tower
  1573. (assuming it is an ordinary top-level definition), but, in order to
  1574. expand macros in that code, the 'let-syntax' must be expanded. This
  1575. causes '...quux...' to be evaluated in the _second_ storey of the tower,
  1576. after which macro expansion can proceed, and long after which the
  1577. enclosing program can be evaluated.
  1578. The module system provides a simple way to manipulate the reflective
  1579. tower. There is a package clause, 'for-syntax', that simply contains
  1580. package clauses for the next storey in the tower. For example, a
  1581. package with the following clauses:
  1582. (open scheme foo bar)
  1583. (for-syntax (open scheme baz quux))
  1584. has all the bindings of 'scheme', 'foo', & 'bar', at the ground storey;
  1585. and the environment in which macros' definitions are evaluated provides
  1586. everything from 'scheme', 'baz', & 'quux'.
  1587. With no 'for-syntax' clauses, the 'scheme' structure is implicitly
  1588. opened; however, if there are 'for-syntax' clauses, 'scheme' must be
  1589. explicitly opened.(3) Also, 'for-syntax' clauses may be arbitrarily
  1590. nested: reflective towers are theoretically infinite in height. (They
  1591. are internally implemented lazily, so they grow exactly as high as they
  1592. need to be.)
  1593. Here is a simple, though contrived, example of using 'for-syntax'.
  1594. The 'while-loops' structure exports 'while', a macro similar to C's
  1595. 'while' loop. 'While''s transformer unhygienically binds the name
  1596. 'exit' to a procedure that exits from the loop. It necessarily,
  1597. therefore, uses explicit renaming macros (*note Explicit renaming
  1598. macros::) in order to break hygiene; it also, in the macro transformer,
  1599. uses the 'destructure' macro to destructure the input form (*note
  1600. Library utilities::, in particular, the structure 'destructuring' for
  1601. destructuring S-expressions).
  1602. (define-structure while-loops (export while)
  1603. (open scheme)
  1604. (for-syntax (open scheme destructuring))
  1605. (begin
  1606. (define-syntax while
  1607. (lambda (form r compare)
  1608. (destructure (((WHILE test . body) form))
  1609. `(,(r 'CALL-WITH-CURRENT-CONTINUATION)
  1610. (,(r 'LAMBDA) (EXIT)
  1611. (,(r 'LET) (r 'LOOP) ()
  1612. (,(r 'IF) ,test
  1613. (,(r 'BEGIN)
  1614. ,@body
  1615. (,(r 'LOOP)))))))))
  1616. (CALL-WITH-CURRENT-CONTINUATION LAMBDA LET IF BEGIN))))
  1617. This next 'while-example' structure defines an example procedure
  1618. 'foo' that uses 'while'. Since 'while-example' has no macro
  1619. definitions, there is no need for any 'for-syntax' clauses; it imports
  1620. 'while' from the 'while-loops' structure only at the ground storey,
  1621. because it has no macro bindings to evaluate the transformer expressions
  1622. of:
  1623. (define-structure while-example (export foo)
  1624. (open scheme while-loops)
  1625. (begin
  1626. (define (foo x)
  1627. (while (> x 9)
  1628. (if (integer? (sqrt x))
  1629. (exit (expt x 2))
  1630. (set! x (- x 1)))))))
  1631. ---------- Footnotes ----------
  1632. (1) While such facilities are not built-in to Scheme48, there is a
  1633. package to do this, which will probably be integrated at some point soon
  1634. into Scheme48.
  1635. (2) This would be more accurately named 'syntactic tower,' as it has
  1636. nothing to do with reflection.
  1637. (3) This is actually only in the default config package of the
  1638. default development environment. The full mechanism is very general.
  1639. 
  1640. File: scheme48.info, Node: Static type system, Prev: Macros in concert with modules, Up: Module system
  1641. 3.4 Static type system
  1642. ======================
  1643. Scheme48 supports a rudimentary static type system. It is intended
  1644. mainly to catch some classes of type and arity mismatch errors early, at
  1645. compile-time. By default, there is only _extremely_ basic analysis,
  1646. which is typically only good enough to catch arity errors and the really
  1647. egregious type errors. The full reconstructor, which is still not very
  1648. sophisticated, is enabled by specifying an optimizer pass that invokes
  1649. the code usage analyzer. The only optimizer pass built-in to Scheme48,
  1650. the automatic procedure integrator, named 'auto-integrate', does so.
  1651. The type reconstructor attempts to assign the most specific type it
  1652. can to program terms, signalling warnings for terms that are certain to
  1653. be invalid by Scheme's dynamic semantics. Since the reconstructor is
  1654. not very sophisticated, it frequently gives up and assigns very general
  1655. types to many terms. Note, however, that it is very lenient in that it
  1656. only assigns more general types: it will _never_ signal a warning
  1657. because it could not reconstruct a very specific type. For example, the
  1658. following program will produce no warnings:
  1659. (define (foo x y) (if x (+ y 1) (car y)))
  1660. Calls to 'foo' that are clearly invalid, such as '(foo #t 'a)', could
  1661. cause the type analyzer to signal warnings, but it is not sophisticated
  1662. enough to determine that 'foo''s second argument must be either a number
  1663. or a pair; it simply assigns a general value type (see below).
  1664. There are some tricky cases that depend on the order by which
  1665. arguments are evaluated in a combination, because that order is not
  1666. specified in Scheme. In these cases, the relevant types are narrowed to
  1667. the most specific ones that could not possibly cause errors at run-time
  1668. for any order. For example,
  1669. (lambda (x) (+ (begin (set! x '(3)) 5) (car x)))
  1670. will be assigned the type '(proc (:pair) :number)', because, if the
  1671. arguments are evaluated right-to-left, and 'x' is not a pair, there will
  1672. be a run-time type error.
  1673. The type reconstructor presumes that all code is potentially
  1674. reachable, so it may signal warnings for code that the most trivial
  1675. control flow analyzer could decide unreachable. For example, it would
  1676. signal a warning for '(if #t 3 (car 7))'. Furthermore, it does not
  1677. account for continuation throws; for example, though it is a perfectly
  1678. valid Scheme program, the type analyzer might signal a warning for this
  1679. code:
  1680. (call-with-current-continuation
  1681. (lambda (k) (0 (k))))
  1682. The type system is based on a type lattice. There are several
  1683. maximum or 'top' elements, such as ':values', ':syntax', and
  1684. ':structure'; and one minimum or 'bottom' element, ':error'. This
  1685. description of the type system makes use of the following notations: 'E
  1686. : T' means that the term E has the type, or some compatible subtype of,
  1687. T; and 'T--_{A} <= T--_{B}' means that T-_{A} is a compatible subtype of
  1688. T-_{B} -- that is, any term whose static type is T-_{A} is valid in any
  1689. context that expects the type T-_{B} --.
  1690. Note that the previous text has used the word 'term,' not
  1691. 'expression,' because static types are assigned to not only Scheme
  1692. expressions. For example, 'cond' macro has the type ':syntax'.
  1693. Structures in the configuration language also have static types: their
  1694. interfaces. (Actually, they really have the type ':structure', but this
  1695. is a deficiency in the current implementation's design.) Types, in
  1696. fact, have their own type: ':type'. Here are some examples of values,
  1697. first-class or otherwise, and their types:
  1698. cond : :syntax
  1699. (values 1 'foo '(x . y))
  1700. : (some-values :exact-integer :symbol :pair)
  1701. :syntax : :type
  1702. 3 : :exact-integer
  1703. (define-structure foo (export a b) ...)
  1704. foo : (export a b)
  1705. One notable deficiency of the type system is the absence of any sort
  1706. of parametric polymorphism.
  1707. -- type constructor: join type ...
  1708. -- type constructor: meet type ...
  1709. 'Join' and 'meet' construct the supremum and infimum elements in
  1710. the type lattice of the given types. That is, for any two disjoint
  1711. types T-_{A} and T-_{B}, let T-_{J} be '(join T--_{A} T--_{B})' and
  1712. T-_{M} be '(meet T--_{A} T--_{B})':
  1713. * T-_{J} <= T-_{A} and T-_{J} <= T-_{B}
  1714. * T-_{A} <= T-_{M} and T-_{B} <= T-_{M}
  1715. For example, '(join :pair :null)' allows either pairs or nil, i.e.
  1716. lists, and '(meet :integer :exact)' accepts only integers that are
  1717. also exact.
  1718. (More complete definitions of supremum, infimum, and other elements
  1719. of lattice theory, may be found elsewhere.)
  1720. -- type: :error
  1721. This is the minimal, or 'bottom,' element in the type lattice. It
  1722. is the type of, for example, calls to 'error'.
  1723. -- type: :values
  1724. -- type: :arguments
  1725. All Scheme _expressions_ have the type ':values'. They may have
  1726. more specific types as well, but all expressions' types are
  1727. compatible subtypes of ':values'. ':Values' is a maximal element
  1728. of the type lattice. ':Arguments' is synonymous with ':values'.
  1729. -- type: :value
  1730. Scheme expressions that have a single result have the type
  1731. ':value', or some compatible subtype thereof; it is itself a
  1732. compatible subtype of ':values'.
  1733. -- type constructor: some-values type ...
  1734. 'Some-values' is used to denote the types of expressions that have
  1735. multiple results: if 'E_{1} ... E_{N}' have the types 'T_{1} ...
  1736. T_{N}', then the Scheme expression '(values E_{1} ... E_{N})' has
  1737. the type '(some-values T_{1} ... T_{N})'.
  1738. 'Some-values'-constructed types are compatible subtypes of
  1739. ':values'.
  1740. 'Some-values' also accepts 'optional' and 'rest' types, similarly
  1741. to Common Lisp's 'optional' and 'rest' formal parameters. The
  1742. sequence of types may contain a '&opt' token, followed by which is
  1743. any number of further types, which are considered to be optional.
  1744. For example, 'make-vector''s domain is '(some-values :exact-integer
  1745. &opt :value)'. There may also be a '&rest' token, which must
  1746. follow the '&opt' token if there is one. Following the '&rest'
  1747. token is one more type, which the rest of the sequents in a
  1748. sequence after the required or optional sequents must satisfy. For
  1749. example, 'map''s domain is '(some-values :procedure (join :pair
  1750. :null) &rest (join :pair :null))': it accepts one procedure and at
  1751. least one list (pair or null) argument.
  1752. -- type constructor: procedure domain codomain
  1753. -- type constructor: proc (arg-type ...) result-type
  1754. Procedure type constructors. Procedure types are always compatible
  1755. subtypes of ':value'. 'Procedure' is a simple constructor from a
  1756. specific domain and codomain; DOMAIN and CODOMAIN must be
  1757. compatible subtypes of ':values'. 'Proc' is a more convenient
  1758. constructor. It is equivalent to '(procedure (some-values ARG-TYPE
  1759. ...) RESULT-TYPE)'.
  1760. -- type: :boolean
  1761. -- type: :char
  1762. -- type: :null
  1763. -- type: :unspecific
  1764. -- type: :pair
  1765. -- type: :string
  1766. -- type: :symbol
  1767. -- type: :vector
  1768. -- type: :procedure
  1769. -- type: :input-port
  1770. -- type: :output-port
  1771. Types that represent standard Scheme data. These are all
  1772. compatible subtypes of ':value'. ':Procedure' is the general type
  1773. for all procedures; see 'proc' and 'procedure' for procedure types
  1774. with specific domains and codomains.
  1775. -- type: :number
  1776. -- type: :complex
  1777. -- type: :real
  1778. -- type: :rational
  1779. -- type: :integer
  1780. Types of the Scheme numeric tower. ':integer <= :rational <= :real
  1781. <= :complex <= :number'
  1782. -- type: :exact
  1783. -- type: :inexact
  1784. -- type: :exact-integer
  1785. -- type: :inexact-real
  1786. ':Exact' and ':inexact' are the types of exact and inexact numbers,
  1787. respectively. They are typically met with one of the types in the
  1788. numeric tower above; ':exact-integer' and ':inexact-real' are two
  1789. conveniences for the most common meets.
  1790. -- type: :other
  1791. ':Other' is for types that do not fall into any of the previous
  1792. value categories. (':other <= :value') All new types introduced,
  1793. for example by 'loophole' (*note Type annotations::), are
  1794. compatible subtypes of ':other'.
  1795. -- type constructor: variable type
  1796. This is the type of all assignable variables, where 'TYPE <=
  1797. :value'. Assignment to variables whose types are value types, not
  1798. assignable variable types, is invalid.
  1799. -- type: :syntax
  1800. -- type: :structure
  1801. ':Syntax' and ':structure' are two other maximal elements of the
  1802. type lattice, along with ':values'. ':Syntax' is the type of
  1803. macros or syntax transformers. ':Structure' is the general type of
  1804. all structures.
  1805. 3.4.1 Types in the configuration language
  1806. -----------------------------------------
  1807. Scheme48's configuration language has several places in which to write
  1808. types. However, due to the definitions of certain elements of the
  1809. configuration language, notably the 'export' syntax, the allowable type
  1810. syntax is far more limited than the above. Only the following are
  1811. provided:
  1812. -- type: :values
  1813. -- type: :value
  1814. -- type: :arguments
  1815. -- type: :syntax
  1816. -- type: :structure
  1817. All of the built-in maximal elements of the type lattice are
  1818. provided, as well as the simple compatible subtype ':values',
  1819. ':value'.
  1820. -- type: :boolean
  1821. -- type: :char
  1822. -- type: :null
  1823. -- type: :unspecific
  1824. -- type: :pair
  1825. -- type: :string
  1826. -- type: :symbol
  1827. -- type: :vector
  1828. -- type: :procedure
  1829. -- type: :input-port
  1830. -- type: :output-port
  1831. -- type: :number
  1832. -- type: :complex
  1833. -- type: :real
  1834. -- type: :rational
  1835. -- type: :integer
  1836. -- type: :exact-integer
  1837. These are the only value types provided in the configuration
  1838. language. Note the conspicuous absence of ':exact', ':inexact',
  1839. and ':inexact-real'.
  1840. -- type constructor: procedure domain codomain
  1841. -- type constructor: proc (arg-type ...) result-type
  1842. These two are the only type constructors available. Note here the
  1843. conspicuous absence of 'some-values', so procedure types that are
  1844. constructed by 'procedure' can accept only one argument (or use the
  1845. overly general ':values' type) & return only one result (or, again,
  1846. use ':values' for the codomain), and procedure types that are
  1847. constructed by 'proc' are similar in the result type.
  1848. 
  1849. File: scheme48.info, Node: System facilities, Next: Multithreading, Prev: Module system, Up: Top
  1850. 4 System facilities
  1851. *******************
  1852. This chapter details many facilities that the Scheme48 run-time system
  1853. provides.
  1854. * Menu:
  1855. * System features::
  1856. * Condition system::
  1857. * Bitwise manipulation::
  1858. * Generic dispatch system::
  1859. * I/O system::
  1860. * Reader & writer::
  1861. * Records::
  1862. * Suspending and resuming heap images::
  1863. 
  1864. File: scheme48.info, Node: System features, Next: Condition system, Up: System facilities
  1865. 4.1 System features
  1866. ===================
  1867. Scheme48 provides a variety of miscellaneous features built-in to the
  1868. system.
  1869. * Menu:
  1870. * Miscellaneous features::
  1871. * Various utilities::
  1872. * Filenames::
  1873. * Fluid/dynamic bindings::
  1874. * ASCII character encoding::
  1875. * Integer enumerations::
  1876. * Cells::
  1877. * Queues::
  1878. * Hash tables::
  1879. * Weak references::
  1880. * Type annotations::
  1881. * Explicit renaming macros::
  1882. 
  1883. File: scheme48.info, Node: Miscellaneous features, Next: Various utilities, Up: System features
  1884. 4.1.1 Miscellaneous features
  1885. ----------------------------
  1886. The structure 'features' provides some very miscellaneous features in
  1887. Scheme48.
  1888. -- procedure: immutable? object --> boolean
  1889. -- procedure: make-immutable! object --> object
  1890. All Scheme objects in Scheme48 have a flag determining whether or
  1891. not they may be mutated. All immediate Scheme objects ('()', '#f',
  1892. &c.) are immutable; all fixnums (small integers) are immutable; and
  1893. all stored objects -- vectors, pairs, &c. -- may be mutable.
  1894. 'Immutable?' returns '#t' if OBJECT may not be mutated, and
  1895. 'make-immutable!', a bit ironically, modifies OBJECT so that it may
  1896. not be mutated, if it was not already immutable, and returns it.
  1897. (immutable? #t) => #t
  1898. (define p (cons 1 2))
  1899. (immutable? p) => #f
  1900. (car p) => 1
  1901. (set-car! p 5)
  1902. (car p) => 5
  1903. (define q (make-immutable! p))
  1904. (eq? p q) => #t
  1905. (car p) => 5
  1906. (immutable? q) => #t
  1907. (set-car! p 6) error-> immutable pair
  1908. -- procedure: string-hash string --> integer-hash-code
  1909. Computes a basic but fast hash of STRING.
  1910. (string-hash "Hello, world!") => 1161
  1911. -- procedure: force-output port --> unspecified
  1912. Forces all buffered output to be sent out of PORT.
  1913. This is identical to the binding of the same name exported by the
  1914. 'i/o' structure (*note Ports::).
  1915. -- procedure: current-noise-port --> output-port
  1916. The current noise port is a port for sending noise messages that
  1917. are inessential to the operation of a program.
  1918. The 'silly' structure exports a single procedure, implemented as a VM
  1919. primitive for the silly reason of efficiency, hence the name of the
  1920. structure.(1) It is used in an inner loop of the reader.
  1921. -- procedure: reverse-list->string char-list count --> string
  1922. Returns a string of the first COUNT characters in CHAR-LIST, in
  1923. reverse. It is a serious error if CHAR-LIST is not a list whose
  1924. length is at least COUNT; the error is not detected by the VM, so
  1925. bogus pointers may be involved as a result. Use this routine with
  1926. care in inner loops.
  1927. The 'debug-messages' structure exports a procedure for emitting very
  1928. basic debugging messages for low-level problems.
  1929. -- procedure: debug-message item ... --> unspecified
  1930. Prints ITEM ... directly to an error port,(2) eliding buffering and
  1931. thread synchronization on the Scheme side. Objects are printed as
  1932. follows:
  1933. * Fixnums (small integers) are written in decimal.
  1934. * Characters are written literally with a '#\' prefix. No
  1935. naming translation is performed, so the space and newline
  1936. characters are written literally, not as '#\space' or
  1937. '#\newline'.
  1938. * Records are written as #{TYPE-NAME}, where TYPE-NAME is the
  1939. name of the record's type.
  1940. * Strings and symbols are written literally.
  1941. * Booleans and the empty list are written normally, i.e. as
  1942. '#t', '#f', or '()'.
  1943. * Pairs are written as '(...)'.
  1944. * Vectors are written as '#(...)'.
  1945. * Objects of certain primitive types are written as #{TYPE}:
  1946. procedures, templates, locations, code (byte) vectors, and
  1947. continuations.(3)
  1948. * Everything else is printed as #{???}.
  1949. The 'code-quote' structure exports a variant of 'quote' that is
  1950. useful in some sophisticated macros.
  1951. -- special form: code-quote object --> object
  1952. Evaluates to the literal value of OBJECT. This is semantically
  1953. identical to 'quote', but OBJECT may be anything, and the compiler
  1954. will not signal any warnings regarding its value, while such
  1955. warnings would be signalled for 'quote' expressions that do not
  1956. wrap readable S-expressions: arbitrary, compound, unreadable data
  1957. may be stored in 'code-quote'. Values computed at compile-time may
  1958. thus be transmitted to run-time code. However, care should be
  1959. taken in doing this.
  1960. ---------- Footnotes ----------
  1961. (1) The author of this manual is not at fault for this nomenclature.
  1962. (2) On Unix, this is 'stderr', the standard I/O error output file.
  1963. (3) Continuations here are in the sense of VM stack frames, not
  1964. escape procedures as obtained using 'call-with-current-continuation'.
  1965. 
  1966. File: scheme48.info, Node: Various utilities, Next: Filenames, Prev: Miscellaneous features, Up: System features
  1967. 4.1.2 Various utilities
  1968. -----------------------
  1969. The 'util' structure contains some miscellaneous utility routines
  1970. extensively used internally in the run-time system. While they are not
  1971. meant to compose a comprehensive library (such as, for example, [SRFI
  1972. 1]), they were found useful in building the run-time system without
  1973. introducing massive libraries into the core of the system.
  1974. -- procedure: unspecific --> unspecific
  1975. Returns Scheme48's "unspecific" token, which is used wherever R5RS
  1976. uses the term 'unspecific' or 'unspecified.' In this manual, the
  1977. term 'unspecified' is used to mean that the values returned by a
  1978. particular procedure are not specified and may be anything,
  1979. including a varying number of values, whereas 'unspecific' refers
  1980. to Scheme48's specific 'unspecific' value that the 'unspecific'
  1981. procedure returns.
  1982. -- procedure: reduce kons knil list --> final-knil
  1983. Reduces LIST by repeatedly applying KONS to elements of LIST and
  1984. the current KNIL value. This is the fundamental list recursion
  1985. operator.
  1986. (reduce KONS KNIL
  1987. (cons ELT_{1}
  1988. (cons ELT_{2}
  1989. (...(cons ELT_{N} '())...))))
  1990. ==
  1991. (KONS ELT_{1}
  1992. (KONS ELT_{2}
  1993. (...(KONS ELT_{N} KNIL)...)))
  1994. Example:
  1995. (reduce append '() '((1 2 3) (4 5 6) (7 8 9)))
  1996. => (1 2 3 4 5 6 7 8 9)
  1997. (append '(1 2 3)
  1998. (append '(4 5 6)
  1999. (append '(7 8 9) '())))
  2000. => (1 2 3 4 5 6 7 8 9)
  2001. -- procedure: fold combiner list accumulator --> final-accumulator
  2002. Folds LIST into an accumulator by repeatedly combining each element
  2003. into an accumulator with COMBINER. This is the fundamental list
  2004. iteration operator.
  2005. (fold COMBINER
  2006. (list ELT_{1} ELT_{2} ... ELT_{N})
  2007. ACCUMULATOR)
  2008. ==
  2009. (let* ((accum_{1} (COMBINER ELT_{1} ACCUMULATOR))
  2010. (accum_{2} (COMBINER ELT_{2} accum_{1}))
  2011. ...
  2012. (accum_{N} (COMBINER ELT_{N} accum_{N-1})))
  2013. accum_{N})
  2014. Example:
  2015. (fold cons '() '(a b c d))
  2016. => (d c b a)
  2017. (cons 'd (cons 'c (cons 'b (cons 'a '()))))
  2018. => (d c b a)
  2019. -- procedure: fold->2 combiner list accumulator_{1} accumulator_{2} -->
  2020. [final-accumulator_{1} final-accumulator_{2}]
  2021. -- procedure: fold->3 combiner list accumulator_{1} accumulator_{2}
  2022. accumulator_{3} --> [final-accumulator_{1}
  2023. final-accumulator_{2} final-accumulator_{3}]
  2024. Variants of 'fold' for two and three accumulators, respectively.
  2025. ;;; Partition LIST by elements that satisfy PRED? and those
  2026. ;;; that do not.
  2027. (fold->2 (lambda (elt satisfied unsatisfied)
  2028. (if (PRED? elt)
  2029. (values (cons elt satisfied) unsatisfied)
  2030. (values satisfied (cons elt unsatisfied))))
  2031. LIST
  2032. '() '())
  2033. -- procedure: filter predicate list --> filtered-list
  2034. Returns a list of all elements in LIST that satisfy PREDICATE.
  2035. (filter odd? '(3 1 4 1 5 9 2 6 5 3 5))
  2036. => (3 1 1 5 9 5 3 5)
  2037. -- procedure: posq object list --> integer or '#f'
  2038. -- procedure: posv object list --> integer or '#f'
  2039. -- procedure: position object list --> integer or '#f'
  2040. These find the position of the first element equal to OBJECT in
  2041. LIST. 'Posq' compares elements by 'eq?'; 'posv' compares by
  2042. 'eqv?'; 'position' compares by 'equal?'.
  2043. (posq 'c '(a b c d e f))
  2044. => 2
  2045. (posv 1/2 '(1 1/2 2 3/2))
  2046. => 1
  2047. (position '(d . e) '((a . b) (b . c) (c . d) (d . e) (e . f)))
  2048. => 3
  2049. -- procedure: any predicate list --> value or '#f'
  2050. -- procedure: every predicate list --> boolean
  2051. 'Any' returns the value that PREDICATE returns for the first
  2052. element in LIST for which PREDICATE returns a true value; if no
  2053. element of LIST satisfied PREDICATE, 'any' returns '#f'. 'Every'
  2054. returns '#t' if every element of LIST satisfies PREDICATE, or '#f'
  2055. if there exist any that do not.
  2056. (any (lambda (x) (and (even? x) (sqrt x)))
  2057. '(0 1 4 9 16))
  2058. => 2
  2059. (every odd? '(1 3 5 7 9))
  2060. => #t
  2061. -- procedure: sublist list start end --> list
  2062. Returns a list of the elements in LIST including & after that at
  2063. the index START and before the index END.
  2064. (sublist '(a b c d e f g h i) 3 6) => (d e f)
  2065. -- procedure: last list --> value
  2066. Returns the last element in LIST. 'Last''s effect is undefined if
  2067. LIST is empty.
  2068. (last '(a b c)) => c
  2069. -- procedure: insert object list elt< --> list
  2070. Inserts OBJECT into the sorted list LIST, comparing the order of
  2071. OBJECT and each element by ELT<.
  2072. (insert 3 '(0 1 2 4 5) <) => (0 1 2 3 4 5)
  2073. 
  2074. File: scheme48.info, Node: Filenames, Next: Fluid/dynamic bindings, Prev: Various utilities, Up: System features
  2075. 4.1.3 Filenames
  2076. ---------------
  2077. There are some basic filename manipulation facilities exported by the
  2078. 'filenames' structure.(1)
  2079. -- constant: *scheme-file-type* --> symbol
  2080. -- constant: *load-file-type* --> symbol
  2081. '*Scheme-file-type*' is a symbol denoting the file extension that
  2082. Scheme48 assumes for Scheme source files; any other extension, for
  2083. instance in the filename list of a structure definition, must be
  2084. written explicitly. '*Load-file-type*' is a symbol denoting the
  2085. preferable file extension to load files from. ('*Load-file-type*'
  2086. was used mostly in bootstrapping Scheme48 from Pseudoscheme or T
  2087. long ago and is no longer very useful.)
  2088. -- procedure: file-name-directory filename --> string
  2089. -- procedure: file-name-nondirectory filename --> string
  2090. 'File-name-directory' returns the directory component of the
  2091. filename denoted by the string FILENAME, including a trailing
  2092. separator (on Unix, '/'). 'File-name-nondirectory' returns
  2093. everything but the directory component of the filename denoted by
  2094. the string FILENAME, including the extension.
  2095. (file-name-directory "/usr/local/lib/scheme48/scheme48.image")
  2096. => "/usr/local/lib/scheme48/"
  2097. (file-name-nondirectory "/usr/local/lib/scheme48/scheme48.image")
  2098. => "scheme48.image"
  2099. (file-name-directory "scheme48.image")
  2100. => ""
  2101. (file-name-nondirectory "scheme48.image")
  2102. => "scheme48.image"
  2103. "Namelists" are platform-independent means by which to name files.
  2104. They are represented as readable S-expressions of any of the following
  2105. forms:
  2106. 'BASENAME'
  2107. represents a filename with only a basename and no directory or file
  2108. type/extension;
  2109. '(DIRECTORY BASENAME [TYPE])'
  2110. represents a filename with a single preceding directory component
  2111. and an optional file type/extension; and
  2112. '((DIRECTORY ...) BASENAME [TYPE])'
  2113. represents a filename with a sequence of directory components, a
  2114. basename, and an optional file type/extension.
  2115. Each atomic component -- that is, the basename, the type/extension,
  2116. and each individual directory component -- may be either a string or a
  2117. symbol. Symbols are converted to the canonical case of the host
  2118. operating system by 'namestring' (on Unix, lowercase); the case of
  2119. string components is not touched.
  2120. -- procedure: namestring namelist directory default-type --> string
  2121. Converts NAMELIST to a string in the format required by the host
  2122. operating system.(2) If NAMELIST did not have a directory
  2123. component, DIRECTORY, a string in the underlying operating system's
  2124. format for directory prefixes, is added to the resulting
  2125. namestring; and, if NAMELIST did not have a type/extension,
  2126. DEFAULT-TYPE, which may be a string or a symbol and which should
  2127. _not_ already contain the host operating system's delimiter
  2128. (usually a dot), is appended to the resulting namestring.
  2129. DIRECTORY or DEFAULT-TYPE may be '#f', in which case they are not
  2130. prefixed or appended to the resulting filename.
  2131. (namestring 'foo #f #f) => "foo"
  2132. (namestring 'foo "bar" 'baz) => "bar/foo.baz"
  2133. (namestring '(rts defenum) "scheme" 'scm)
  2134. => "scheme/rts/defenum.scm"
  2135. (namestring '((foo bar) baz quux) "zot" #f)
  2136. => "zot/foo/bar/baz.quux"
  2137. (namestring "zot/foo/bar/baz.quux" #f "mumble")
  2138. => "zot/foo/bar/baz.quux.mumble"
  2139. 4.1.3.1 Filename translations
  2140. .............................
  2141. Scheme48 keeps a registry of "filename translations", translations from
  2142. filename prefixes to the real prefixes. This allows abstraction of
  2143. actual directory prefixes without necessitating running Scheme code to
  2144. construct directory pathnames (for example, in configuration files).
  2145. Interactively, in the usual command processor, users can set filename
  2146. translations with the ',translate'; *note Basic commands::.
  2147. -- procedure: translations --> string/string-alist
  2148. Returns the alist of filename translations.
  2149. -- procedure: set-translation! from to --> unspecified
  2150. Adds a filename prefix translation, overwriting an existing one if
  2151. one already existed.
  2152. -- procedure: translate filename --> translated-filename
  2153. Translates the first prefix of FILENAME found in the registry of
  2154. translations and returns the translated filename.
  2155. (set-translation! "s48" "/home/me/scheme/scheme48/scheme")
  2156. (translate (namestring '(bcomp frame) "s48" 'scm))
  2157. => "/home/me/scheme/scheme48/scheme/bcomp/frame.scm"
  2158. (translate (namestring "comp-packages" "s48" 'scm))
  2159. => "/home/me/scheme/scheme48/scheme/comp-packages.scm"
  2160. (translate "s48/frobozz")
  2161. => "/home/me/scheme/scheme48/scheme/frobozz"
  2162. (set-translation! "scheme48" "s48")
  2163. (translate (namestring '((scheme48 big) filename) #f 'scm))
  2164. => scheme48/big/filename.scm
  2165. (translate (translate (namestring '((scheme48 big) filename) #f 'scm)))
  2166. => "/home/me/scheme/scheme48/scheme/big/filename.scm"
  2167. One filename translation is built-in, mapping '=scheme48/' to the
  2168. directory of system files in a Scheme48 installation, which on Unix is
  2169. typically a directory in '/usr/local/lib'.
  2170. (translate "=scheme48/scheme48.image")
  2171. => /usr/local/scheme48/scheme48.image
  2172. ---------- Footnotes ----------
  2173. (1) The facilities Scheme48 provides are very rudimentary, and they
  2174. are not intended to act as a coherent and comprehensive pathname or
  2175. logical name facility such as that of Common Lisp. However, they served
  2176. the basic needs of Scheme48's build process when they were originally
  2177. created.
  2178. (2) However, the current standard distribution of Scheme48 is
  2179. specific to Unix: the current code implements only Unix filename
  2180. facilities.
  2181. 
  2182. File: scheme48.info, Node: Fluid/dynamic bindings, Next: ASCII character encoding, Prev: Filenames, Up: System features
  2183. 4.1.4 Fluid/dynamic bindings
  2184. ----------------------------
  2185. The 'fluids' structure provides a facility for dynamically bound
  2186. resources, like special variables in Common Lisp, but with first-class,
  2187. unforgeable objects.
  2188. Every thread (*note Multithreading::) in Scheme48 maintains a "fluid
  2189. or dynamic environment". It maps "fluid descriptors" to their values,
  2190. much like a lexical environment maps names to their values. The dynamic
  2191. environment is implemented by deep binding and dynamically scoped.
  2192. Fluid variables are represented as first-class objects for which there
  2193. is a top-level value and possibly a binding in the current dynamic
  2194. environment. Escape procedures, as created with Scheme's
  2195. 'call-with-current-continuation', also store & preserve the dynamic
  2196. environment at the time of their continuation's capture and restore it
  2197. when invoked.
  2198. The convention for naming variables that are bound to fluid objects
  2199. is to add a prefix of '$' (dollar sign); e.g., '$foo'.
  2200. -- procedure: make-fluid top-level-value --> fluid
  2201. Fluid constructor.
  2202. -- procedure: fluid fl --> value
  2203. -- procedure: set-fluid! fl value --> unspecified
  2204. -- procedure: fluid-cell-ref fluid-cell --> value
  2205. -- procedure: fluid-cell-set! fluid-cell value --> unspecified
  2206. 'Fluid' returns the value that the current dynamic environment
  2207. associates with FL, if it has an association; if not, it returns
  2208. FL's top-level value, as passed to 'make-fluid' to create FL.
  2209. 'Set-fluid!' assigns the value of the association in the current
  2210. dynamic environment for FL to VALUE, or, if there is no such
  2211. association, it assigns the top-level value of FL to VALUE. Direct
  2212. assignment of fluids is deprecated, however, and may be removed in
  2213. a later release; instead, programmers should use fluids that are
  2214. bound to mutable cells (*note Cells::). 'Fluid-cell-ref' and
  2215. 'fluid-cell-set!' are conveniences for this; they simply call the
  2216. corresponding cell operations after fetching the cell that the
  2217. fluid refers to by using 'fluid'.
  2218. -- procedure: let-fluid fluid value thunk --> values
  2219. -- procedure: let-fluids fluid_{0} value_{0} fluid_{1} value_{1} ...
  2220. thunk --> values
  2221. These dynamically bind their fluid arguments to the corresponding
  2222. value arguments and apply THUNK with the new dynamic environment,
  2223. restoring the old one after THUNK returns and returning the value
  2224. it returns.
  2225. (define $mumble (make-fluid 0))
  2226. (let ((a (fluid $mumble))
  2227. (b (let-fluid $mumble 1
  2228. (lambda () (fluid $mumble))))
  2229. (c (fluid $mumble))
  2230. (d (let-fluid $mumble 2
  2231. (lambda ()
  2232. (let-fluid $mumble 3
  2233. (lambda () (fluid $mumble)))))))
  2234. (list a b c d))
  2235. => (0 1 0 3)
  2236. (let ((note (lambda (when)
  2237. (display when)
  2238. (display ": ")
  2239. (write (fluid $mumble))
  2240. (newline))))
  2241. (note 'initial)
  2242. (let-fluid $mumble 1 (lambda () (note 'let-fluid)))
  2243. (note 'after-let-fluid)
  2244. (let-fluid $mumble 1
  2245. (lambda ()
  2246. (note 'outer-let-fluid)
  2247. (let-fluid $mumble 2 (lambda () (note 'inner-let-fluid)))))
  2248. (note 'after-inner-let-fluid)
  2249. ((call-with-current-continuation
  2250. (lambda (k)
  2251. (lambda ()
  2252. (let-fluid $mumble 1
  2253. (lambda ()
  2254. (note 'let-fluid-within-cont)
  2255. (let-fluid $mumble 2
  2256. (lambda () (note 'inner-let-fluid-within-cont)))
  2257. (k (lambda () (note 'let-fluid-thrown)))))))))
  2258. (note 'after-throw))
  2259. -| initial: 0
  2260. -| let-fluid: 1
  2261. -| after-let-fluid: 0
  2262. -| outer-let-fluid: 1
  2263. -| inner-let-fluid: 2
  2264. -| let-fluid-within-cont: 1
  2265. -| inner-let-fluid-within-cont: 2
  2266. -| let-fluid-thrown: 0
  2267. -| after-throw: 0
  2268. 
  2269. File: scheme48.info, Node: ASCII character encoding, Next: Integer enumerations, Prev: Fluid/dynamic bindings, Up: System features
  2270. 4.1.5 ASCII character encoding
  2271. ------------------------------
  2272. These names are exported by the 'ascii' structure.
  2273. -- procedure: char->ascii char --> ascii-integer
  2274. -- procedure: ascii->char ascii-integer --> character
  2275. These convert characters to and from their integer ASCII encodings.
  2276. 'Char->ascii' and 'ascii->char' are similar to R5RS's
  2277. 'char->integer' and 'integer->char', but they are guaranteed to use
  2278. the ASCII encoding. Scheme48's 'integer->char' and 'char->integer'
  2279. deliberately do not use the ASCII encoding to encourage programmers
  2280. to make use of only what R5RS guarantees.
  2281. (char->ascii #\a) => 97
  2282. (ascii->char 97) => #\a
  2283. -- constant: ascii-limit --> integer
  2284. -- constant: ascii-whitespaces --> ascii-integer-list
  2285. 'Ascii-limit' is an integer that is one greater than the highest
  2286. number that 'char->ascii' may return or 'ascii->char' will accept.
  2287. 'Ascii-whitespaces' is a list of the integer encodings of all
  2288. characters that are considered whitespace: space (32), horizontal
  2289. tab (9), line-feed/newline (10), vertical tab (11), form-feed/page
  2290. (12), and carriage return (13).
  2291. 
  2292. File: scheme48.info, Node: Integer enumerations, Next: Cells, Prev: ASCII character encoding, Up: System features
  2293. 4.1.6 Integer enumerations
  2294. --------------------------
  2295. Scheme48 provides a facility for "integer enumerations", somewhat akin
  2296. to C enums. The names described in this section are exported by the
  2297. 'enumerated' structure.
  2298. *Note:* These enumerations are _not_ compatible with the
  2299. enumerated/finite type facility (*note Enumerated/finite types and
  2300. sets::).
  2301. -- syntax: define-enumeration enumeration-name (enumerand-name ...)
  2302. Defines ENUMERATION-NAME to be a static enumeration. (Note that it
  2303. is _not_ a regular variable. It is actually a macro, though its
  2304. exact syntax is not exposed; it must be exported with the ':syntax'
  2305. type (*note Static type system::).) ENUMERATION-NAME thereafter
  2306. may be used with the enumeration operators described below.
  2307. -- syntax: enum enumeration-name enumerand-name --> enumerand-integer
  2308. -- syntax: components enumeration-name --> component-vector
  2309. 'Enum' expands to the integer value represented symbolically by
  2310. ENUMERAND-NAME in the enumeration ENUMERATION-NAME as defined by
  2311. 'define-enumeration'. 'Components' expands to a literal vector of
  2312. the components in ENUMERATION-NAME as defined by
  2313. 'define-enumeration'. In both cases, ENUMERAND-NAME must be
  2314. written literally as the name of the enumerand; see
  2315. 'name->enumerand' for extracting an enumerand's integer given a
  2316. run-time symbol naming an enumerand.
  2317. -- syntax: enumerand->name enumerand-integer enumeration-name -->
  2318. symbol
  2319. -- syntax: name->enumerand enumerand-name enumeration-name -->
  2320. integer-enumerand
  2321. 'Enumerand->name' expands to a form that evaluates to the symbolic
  2322. name that the integer value of the expression ENUMERAND-INTEGER is
  2323. mapped to by ENUMERATION-NAME as defined by 'define-enumeration'.
  2324. 'Name->enumerand' expands to a form that evaluates to the integer
  2325. value of the enumerand in ENUMERATION-NAME that is represented
  2326. symbolically by the value of the expression ENUMERAND-NAME.
  2327. The 'enum-case' structure provides a handy utility of the same name
  2328. for dispatching on enumerands.
  2329. -- syntax: enum-case
  2330. (enum-case ENUMERATION-NAME KEY
  2331. ((ENUMERAND-NAME ...) BODY)
  2332. ...
  2333. [(else ELSE-BODY)])
  2334. Matches KEY with the clause one of whose names maps in
  2335. ENUMERATION-NAME to the integer value of KEY. KEY must be an
  2336. exact, non-negative integer. If no matching clause is found, and
  2337. ELSE-BODY is present, 'enum-case' will evaluate ELSE-BODY; if
  2338. ELSE-BODY is not present, 'enum-case' will return an unspecific
  2339. value.
  2340. Examples:
  2341. (define-enumeration foo
  2342. (bar
  2343. baz))
  2344. (enum foo bar) => 0
  2345. (enum foo baz) => 1
  2346. (enum-case foo (enum foo bar)
  2347. ((baz) 'x)
  2348. (else 'y))
  2349. => y
  2350. (enum-case foo (enum foo baz)
  2351. ((bar) 'a)
  2352. ((baz) 'b))
  2353. => b
  2354. (enumerand->name 1 foo) => baz
  2355. (name->enumerand 'bar foo) => 0
  2356. (components foo) => #(bar baz)
  2357. 
  2358. File: scheme48.info, Node: Cells, Next: Queues, Prev: Integer enumerations, Up: System features
  2359. 4.1.7 Cells
  2360. -----------
  2361. Scheme48 also provides a simple mutable cell data type from the 'cells'
  2362. structure. It uses them internally for local, lexical variables that
  2363. are assigned, but cells are available still to the rest of the system
  2364. for general use.
  2365. -- procedure: make-cell contents --> cell
  2366. -- procedure: cell? object --> boolean
  2367. -- procedure: cell-ref cell --> value
  2368. -- procedure: cell-set! cell value --> unspecified
  2369. 'Make-cell' creates a new cell with the given contents. 'Cell?' is
  2370. the disjoint type predicate for cells. 'Cell-ref' returns the
  2371. current contents of CELL. 'Cell-set!' assigns the contents of CELL
  2372. to VALUE.
  2373. Examples:
  2374. (define cell (make-cell 42))
  2375. (cell-ref cell) => 42
  2376. (cell? cell) => #t
  2377. (cell-set! cell 'frobozz)
  2378. (cell-ref cell) => frobozz
  2379. 
  2380. File: scheme48.info, Node: Queues, Next: Hash tables, Prev: Cells, Up: System features
  2381. 4.1.8 Queues
  2382. ------------
  2383. The 'queues' structure exports names for procedures that operate on
  2384. simple first-in, first-out queues.
  2385. -- procedure: make-queue --> queue
  2386. -- procedure: queue? object --> boolean
  2387. 'Make-queue' constructs an empty queue. 'Queue?' is the disjoint
  2388. type predicate for queues.
  2389. -- procedure: queue-empty? queue --> boolean
  2390. -- procedure: empty-queue! queue --> unspecified
  2391. 'Queue-empty?' returns '#t' if QUEUE contains zero elements or '#f'
  2392. if it contains some. 'Empty-queue!' removes all elements from
  2393. QUEUE.
  2394. -- procedure: enqueue! queue object --> unspecified
  2395. -- procedure: dequeue! queue --> value
  2396. -- procedure: maybe-dequeue! queue --> value or '#f'
  2397. -- procedure: queue-head queue --> value
  2398. 'Enqueue!' adds OBJECT to QUEUE. 'Dequeue!' removes & returns the
  2399. next object available from QUEUE; if QUEUE is empty, 'dequeue!'
  2400. signals an error. 'Maybe-dequeue!' is like 'dequeue!', but it
  2401. returns '#f' in the case of an absence of any element, rather than
  2402. signalling an error. 'Queue-head' returns the next element
  2403. available from QUEUE without removing it, or it signals an error if
  2404. QUEUE is empty.
  2405. -- procedure: queue-length queue --> integer
  2406. Returns the number of objects in QUEUE.
  2407. -- procedure: on-queue? queue object --> boolean
  2408. -- procedure: delete-from-queue! queue object --> unspecified
  2409. 'On-queue?' returns true if QUEUE contains OBJECT or '#f' if not.
  2410. 'Delete-from-queue!' removes the first occurrence of OBJECT from
  2411. QUEUE that would be dequeued.
  2412. -- procedure: queue->list queue --> list
  2413. -- procedure: list->queue list --> queue
  2414. These convert queues to and from lists of their elements.
  2415. 'Queue->list' returns a list in the order in which its elements
  2416. were added to the queue. 'List->queue' returns a queue that will
  2417. produce elements starting at the head of the list.
  2418. Examples:
  2419. (define q (make-queue))
  2420. (enqueue! q 'foo)
  2421. (enqueue! q 'bar)
  2422. (queue->list q) => (foo bar)
  2423. (on-queue? q 'bar) => #t
  2424. (dequeue! q) => 'foo
  2425. (queue-empty? q) => #f
  2426. (delete-from-queue! queue 'bar)
  2427. (queue-empty? q) => #t
  2428. (enqueue! q 'frobozz)
  2429. (empty-queue! q)
  2430. (queue-empty? q) => #t
  2431. (dequeue! q) error-> empty queue
  2432. Queues are integrated with Scheme48's optimistic concurrency (*note
  2433. Optimistic concurrency::) facilities, in that every procedure exported
  2434. except for 'queue->list' ensures fusible atomicity in operation -- that
  2435. is, every operation except for 'queue->list' ensures that the
  2436. transaction it performs is atomic, and that it may be fused within
  2437. larger atomic transactions, as transactions wrapped within
  2438. 'call-ensuring-atomicity' &c. may be.
  2439. 
  2440. File: scheme48.info, Node: Hash tables, Next: Weak references, Prev: Queues, Up: System features
  2441. 4.1.9 Hash tables
  2442. -----------------
  2443. Scheme48 provides a simple hash table facility in the structure
  2444. 'tables'.
  2445. -- procedure: make-table [hasher] --> table
  2446. -- procedure: make-string-table --> string-table
  2447. -- procedure: make-symbol-table --> symbol-table
  2448. -- procedure: make-integer-table --> integer-table
  2449. Hash table constructors. 'Make-table' creates a table that hashes
  2450. keys either with HASHER, if it is passed to 'make-table', or
  2451. 'default-hash-function', and it compares keys for equality with
  2452. 'eq?', unless they are numbers, in which case it compares with
  2453. 'eqv?'. 'Make-string-table' makes a table whose hash function is
  2454. 'string-hash' and that compares the equality of keys with
  2455. 'string=?'. 'Make-symbol-table' constructs a table that hashes
  2456. symbol keys by converting them to strings and hashing them with
  2457. 'string-hash'; it compares keys' equality by 'eq?'. Tables made by
  2458. 'make-integer-table' hash keys by taking their absolute value, and
  2459. test for key equality with the '=' procedure.
  2460. -- procedure: make-table-maker comparator hasher --> table-maker
  2461. Customized table constructor constructor: this returns a nullary
  2462. procedure that creates a new table that uses COMPARATOR to compare
  2463. keys for equality and HASHER to hash keys.
  2464. -- procedure: table? object --> boolean
  2465. Hash table disjoint type predicate.
  2466. -- procedure: table-ref table key --> value or '#f'
  2467. -- procedure: table-set! table key value --> unspecified
  2468. 'Table-ref' returns the value associated with KEY in TABLE, or '#f'
  2469. if there is no such association. If VALUE is '#f', 'table-set!'
  2470. ensures that there is no longer an association with KEY in TABLE;
  2471. if VALUE is any other value, 'table-set!' creates a new association
  2472. or assigns an existing one in TABLE whose key is KEY and whose
  2473. associated value is VALUE.
  2474. -- procedure: table-walk proc table --> unspecified
  2475. 'Table-walk' applies PROC to the key & value, in that order of
  2476. arguments, of every association in TABLE.
  2477. -- procedure: make-table-immutable! table --> table
  2478. This makes the structure of TABLE immutable, though not its
  2479. contents. 'Table-set!' may not be used with tables that have been
  2480. made immutable.
  2481. -- procedure: default-hash-function value --> integer-hash-code
  2482. -- procedure: string-hash string --> integer-hash-code
  2483. Two built-in hashing functions. 'Default-hash-function' can hash
  2484. any Scheme value that could usefully be used in a 'case' clause.
  2485. 'String-hash' is likely to be fast, as it is implemented as a VM
  2486. primitive. 'String-hash' is the same as what the 'features'
  2487. structure exports under the same name.
  2488. 
  2489. File: scheme48.info, Node: Weak references, Next: Type annotations, Prev: Hash tables, Up: System features
  2490. 4.1.10 Weak references
  2491. ----------------------
  2492. Scheme48 provides an interface to weakly held references in basic weak
  2493. pointers and "populations", or sets whose elements are weakly held. The
  2494. facility is in the structure 'weak'.
  2495. 4.1.10.1 Weak pointers
  2496. ......................
  2497. -- procedure: make-weak-pointer contents --> weak-pointer
  2498. -- procedure: weak-pointer? object --> boolean
  2499. -- procedure: weak-pointer-ref weak-pointer --> value or '#f'
  2500. 'Make-weak-pointer' creates a weak pointer that points to CONTENTS.
  2501. 'Weak-pointer?' is the weak pointer disjoint type predicate.
  2502. 'Weak-pointer-ref' accesses the value contained within
  2503. 'weak-pointer', or returns '#f' if there were no strong references
  2504. to the contents and a garbage collection occurred. Weak pointers
  2505. resemble cells (*note Cells::), except that they are immutable and
  2506. hold their contents weakly, not strongly.
  2507. 4.1.10.2 Populations (weak sets)
  2508. ................................
  2509. -- procedure: make-population --> population
  2510. -- procedure: add-to-population! object population --> unspecified
  2511. -- procedure: population->list population --> list
  2512. -- procedure: walk-population proc population --> unspecified
  2513. 'Make-population' constructs an empty population.
  2514. 'Add-to-population!' adds OBJECT to the population POPULATION.
  2515. 'Population->list' returns a list of the elements of POPULATION.
  2516. Note, though, that this can be dangerous in that it can create
  2517. strong references to the population's contents and potentially leak
  2518. space because of this. 'Walk-population' applies PROC to every
  2519. element in POPULATION.
  2520. 
  2521. File: scheme48.info, Node: Type annotations, Next: Explicit renaming macros, Prev: Weak references, Up: System features
  2522. 4.1.11 Type annotations
  2523. -----------------------
  2524. Scheme48 allows optional type annotations with the 'loophole' special
  2525. form from the 'loopholes' structure.
  2526. -- syntax: loophole type expression --> values
  2527. This is exactly equivalent in semantics to EXPRESSION, except the
  2528. static type analyzer is informed that the whole expression has the
  2529. type TYPE. For details on the form of TYPE, *note Static type
  2530. system::.
  2531. Type annotations can be used for several different purposes:
  2532. * simply to give more information to the static type analyzer;
  2533. * to work as a simple abstract data type facility: passing a type
  2534. name that does not already exist creates a new disjoint value type;
  2535. and
  2536. * to prevent the type system from generating warnings in the rare
  2537. cases where it would do so incorrectly, such as in the
  2538. 'primitive-cwcc', 'primitive-catch', and 'with-continuation'
  2539. devices (to be documented in a later edition of this manual).
  2540. To see an example of the second use, see 'rts/jar-defrecord.scm' in
  2541. Scheme48's source tree.
  2542. *Note:* Type annotations do _not_ damage the safety of Scheme's type
  2543. system. They affect only the static type analyzer, which does not
  2544. change run-time object representations; it only checks type soundness of
  2545. code and generates warnings for programs that would cause run-time type
  2546. errors.
  2547. 
  2548. File: scheme48.info, Node: Explicit renaming macros, Prev: Type annotations, Up: System features
  2549. 4.1.12 Explicit renaming macros
  2550. -------------------------------
  2551. Scheme48 supports a simple low-level macro system based on explicitly
  2552. renaming identifiers to preserve hygiene. The macro system is
  2553. well-integrated with the module system; *note Macros in concert with
  2554. modules::.
  2555. "Explicit renaming" macro transformers operate on simple
  2556. S-expressions extended with "identifiers", which are like symbols but
  2557. contain more information about lexical context. In order to preserve
  2558. that lexical context, transformers must explicitly call a "renamer"
  2559. procedure to produce an identifier with the proper scope. To test
  2560. whether identifiers have the same denotation, transformers are also
  2561. given an identifier comparator.
  2562. The facility provided by Scheme48 is almost identical to the explicit
  2563. renaming macro facility described in [Clinger 91].(1) It differs only
  2564. by the 'transformer' keyword, which is described in the paper but not
  2565. used by Scheme48, and in the annotation of auxiliary names.
  2566. -- syntax: define-syntax name transformer [aux-names]
  2567. Introduces a derived syntax NAME with the given transformer, which
  2568. may be an explicit renaming transformer procedure, a pair whose car
  2569. is such a procedure and whose cdr is a list of auxiliary
  2570. identifiers, or the value of a 'syntax-rules' expression. In the
  2571. first case, the added operand AUX-NAMES may, and usually should
  2572. except in the case of local (non-exported) syntactic bindings, be a
  2573. list of all of the auxiliary top-level identifiers used by the
  2574. macro.
  2575. Explicit renaming transformer procedures are procedures of three
  2576. arguments: an input form, an identifier renamer procedure, and an
  2577. identifier comparator procedure. The input form is the whole form of
  2578. the macro's invocation (including, at the car, the identifier whose
  2579. denotation was the syntactic binding). The identifier renamer accepts
  2580. an identifier as an argument and returns an identifier that is
  2581. hygienically renamed to refer absolutely to the identifier's denotation
  2582. in the environment of the macro's definition, not in the environment of
  2583. the macro's usage. In order to preserve hygiene of syntactic
  2584. transformations, macro transformers must call this renamer procedure for
  2585. any literal identifiers in the output. The renamer procedure is
  2586. referentially transparent; that is, two invocations of it with the same
  2587. arguments in terms of 'eq?' will produce the same results in the sense
  2588. of 'eq?'.
  2589. For example, this simple transformer for a 'swap!' macro is
  2590. incorrect:
  2591. (define-syntax swap!
  2592. (lambda (form rename compare)
  2593. (let ((a (cadr form))
  2594. (b (caddr form)))
  2595. `(LET ((TEMP ,a))
  2596. (SET! ,a ,b)
  2597. (SET! ,b TEMP)))))
  2598. The introduction of the literal identifier 'temp' into the output may
  2599. conflict with one of the input variables if it were to also be named
  2600. 'temp': '(swap! temp foo)' or '(swap! bar temp)' would produce the wrong
  2601. result. Also, the macro would fail in another very strange way if the
  2602. user were to have a local variable named 'let' or 'set!', or it would
  2603. simply produce invalid output if there were no binding of 'let' or
  2604. 'set!' in the environment in which the macro was used. These are basic
  2605. problems of abstraction: the user of the macro should not need to know
  2606. how the macro is internally implemented, notably with a 'temp' variable
  2607. and using the 'let' and 'set!' special forms.
  2608. Instead, the macro must hygienically rename these identifiers using
  2609. the renamer procedure it is given, and it should list the top-level
  2610. identifiers it renames (which cannot otherwise be extracted
  2611. automatically from the macro's definition):
  2612. (define-syntax swap!
  2613. (lambda (form rename compare)
  2614. (let ((a (cadr form))
  2615. (b (caddr form)))
  2616. `(,(rename 'LET) ((,(rename 'TEMP) ,a))
  2617. (,(rename 'SET!) ,a ,b)
  2618. (,(rename 'SET!) ,b ,(rename 'TEMP)))))
  2619. (LET SET!))
  2620. However, some macros are unhygienic by design, i.e. they insert
  2621. identifiers into the output intended to be used in the environment of
  2622. the macro's usage. For example, consider a 'loop' macro that loops
  2623. endlessly, but binds a variable named 'exit' to an escape procedure to
  2624. the continuation of the 'loop' expression, with which the user of the
  2625. macro can escape the loop:
  2626. (define-syntax loop
  2627. (lambda (form rename compare)
  2628. (let ((body (cdr form)))
  2629. `(,(rename 'CALL-WITH-CURRENT-CONTINUATION)
  2630. (,(rename 'LAMBDA) (EXIT) ; Literal, unrenamed EXIT.
  2631. (,(rename 'LET) ,(rename 'LOOP) ()
  2632. ,@body
  2633. (,(rename 'LOOP)))))))
  2634. (CALL-WITH-CURRENT-CONTINUATION LAMBDA LET))
  2635. Note that macros that expand to 'loop' must also be unhygienic; for
  2636. instance, this naïve definition of a 'loop-while' macro is incorrect,
  2637. because it hygienically renames 'exit' automatically by of the
  2638. definition of 'syntax-rules', so the identifier it refers to is not the
  2639. one introduced unhygienically by 'loop':
  2640. (define-syntax loop-while
  2641. (syntax-rules ()
  2642. ((LOOP-WHILE test body ...)
  2643. (LOOP (IF (NOT test)
  2644. (EXIT)) ; Hygienically renamed.
  2645. body ...))))
  2646. Instead, a transformer must be written to not hygienically rename 'exit'
  2647. in the output:
  2648. (define-syntax loop-while
  2649. (lambda (form rename compare)
  2650. (let ((test (cadr form))
  2651. (body (cddr form)))
  2652. `(,(rename 'LOOP)
  2653. (,(rename 'IF) (,(rename 'NOT) ,test)
  2654. (EXIT)) ; Not hygienically renamed.
  2655. ,@body)))
  2656. (LOOP IF NOT))
  2657. To understand the necessity of annotating macros with the list of
  2658. auxiliary names they use, consider the following definition of the
  2659. 'delay' form, which transforms '(delay EXP)' into '(make-promise (lambda
  2660. () EXP))', where 'make-promise' is some non-exported procedure defined
  2661. in the same module as the 'delay' macro:
  2662. (define-syntax delay
  2663. (lambda (form rename compare)
  2664. (let ((exp (cadr form)))
  2665. `(,(rename 'MAKE-PROMISE) (,(rename 'LAMBDA) () ,exp)))))
  2666. This preserves hygiene as necessary, but, while the compiler can know
  2667. whether 'make-promise' is _exported_ or not, it cannot in general
  2668. determine whether 'make-promise' is _local_, i.e. not accessible in any
  2669. way whatsoever, even in macro output, from any other modules. In this
  2670. case, 'make-promise' is _not_ local, but the compiler cannot in general
  2671. know this, and it would be an unnecessarily heavy burden on the
  2672. compiler, the linker, and related code-processing systems to assume that
  2673. all bindings are not local. It is therefore better(2) to annotate such
  2674. definitions with the list of auxiliary names used by the transformer:
  2675. (define-syntax delay
  2676. (lambda (form rename compare)
  2677. (let ((exp (cadr form)))
  2678. `(,(rename 'MAKE-PROMISE) (,(rename 'LAMBDA) () ,exp))))
  2679. (MAKE-PROMISE LAMBDA))
  2680. ---------- Footnotes ----------
  2681. (1) For the sake of avoiding any potential copyright issues, the
  2682. paper is not duplicated here, and instead the author of this manual has
  2683. written the entirety of this section.
  2684. (2) However, the current compiler in Scheme48 does not require this,
  2685. though the static linker does.
  2686. 
  2687. File: scheme48.info, Node: Condition system, Next: Bitwise manipulation, Prev: System features, Up: System facilities
  2688. 4.2 Condition system
  2689. ====================
  2690. As of version 1.3 (different from all older versions), Scheme48 supports
  2691. two different condition systems. One of them, the original one, is a
  2692. simple system where conditions are represented as tagged lists. This
  2693. section documents the original one. The new condition system is [SRFI
  2694. 34, 35], and there is a complicated translation layer between the old
  2695. one, employed by the run-time system, and the new one, which is
  2696. implemented in a layer high above that as a library, but a library which
  2697. is always loaded in the usual development environment. See the [SRFI
  2698. 34, 35] documents for documentation of the new condition system. [SRFI
  2699. 34] is available from the 'exceptions' structure; SRFI 35, from the
  2700. 'conditions' structure.
  2701. *Note:* The condition system changed in Scheme48 version 1.3. While
  2702. the old one is still available, the names of the structures that
  2703. implement it changed. 'Signals' is now 'simple-signals', and
  2704. 'conditions' is now 'simple-conditions'. The structure that 'signals'
  2705. _now_ names implements the same interface, but with [SRFI 34, 35]
  2706. underlying it. The structure that the name 'conditions' _now_
  2707. identifies [SRFI 35]. You will have to update all old code that relied
  2708. on the old 'signals' and 'conditions' structure either by using those
  2709. structures' new names or by invasively modifying all code to use [SRFI
  2710. 34, 35]. Also, the only way to completely elide the use of the SRFIs is
  2711. to evaluate this in an environment with the 'exceptions-internal' and
  2712. 'vm-exceptions' structure open:
  2713. (begin (initialize-vm-exceptions! really-signal-condition)
  2714. ;; INITIALIZE-VM-EXCEPTIONS! returns a very large object,
  2715. ;; which we probably don't want printed at the REPL.
  2716. #t)
  2717. 4.2.1 Signalling, handling, and representing conditions
  2718. -------------------------------------------------------
  2719. Scheme48 provides a simple condition system.(1) "Conditions" are
  2720. objects that describe exceptional situations. Scheme48 keeps a registry
  2721. of "condition types", which just have references to their supertypes.
  2722. Conditions are simple objects that contain only two fields, the type and
  2723. the type-specific data (the "stuff"). Accessor procedures should be
  2724. defined for particular condition types to extract the data contained
  2725. within the 'stuff' fields of instances of of those condition types.
  2726. Condition types are represented as symbols. "Condition handlers" are
  2727. part of the system's dynamic context; they are used to handle
  2728. exceptional situations when conditions are signalled that describe such
  2729. exceptional situations. "Signalling" a condition signals that an
  2730. exceptional situation occurred and invokes the current condition handler
  2731. on the condition.
  2732. Scheme48's condition system is split up into three structures:
  2733. 'simple-signals'
  2734. Exports procedures to signal conditions and construct conditions,
  2735. as well as some utilities for common kinds of conditions.
  2736. 'handle'
  2737. Exports facilities for handling signalled conditions.
  2738. 'simple-conditions'
  2739. The system of representing conditions as objects.
  2740. The 'simple-signals' structure exports these procedures:
  2741. -- procedure: make-condition type-name stuff --> condition
  2742. The condition object constructor.
  2743. -- procedure: signal-condition condition --> values (may not return)
  2744. -- procedure: signal type-name stuff ... --> values (may not return)
  2745. 'Signal-condition' signals the given condition. 'Signal' is a
  2746. convenience atop the common conjunction of 'signal-condition' and
  2747. 'make-condition': it constructs a condition with the given type
  2748. name and stuff, whereafter it signals that condition with
  2749. 'signal-condition'.
  2750. -- procedure: error message irritant ... --> values (may not return)
  2751. -- procedure: warn message irritant ... --> values (may not return)
  2752. -- procedure: syntax-error message irritant ... --> expression (may not
  2753. return)
  2754. -- procedure: call-error message irritant ... --> values (may not
  2755. return)
  2756. -- procedure: note message irritant ... --> values (may not return)
  2757. Conveniences for signalling standard condition types. These
  2758. procedures generally either do not return or return an unspecified
  2759. value, unless specified to by a user of the debugger.
  2760. 'Syntax-error' returns the expression '(quote syntax-error)', if
  2761. the condition handler returns to 'syntax-error' in the first place.
  2762. By convention, the message should be lowercased (i.e. the first
  2763. word should not be capitalized), and it should not end with
  2764. punctuation. The message is typically not a complete sentence.
  2765. For example, these all follow Scheme48's convention:
  2766. argument type error
  2767. wrong number of arguments
  2768. invalid syntax
  2769. ill-typed right-hand side
  2770. out of memory, unable to continue
  2771. These, on the other hand, do not follow the convention and should
  2772. be avoided:
  2773. Argument type error:
  2774. An argument of the wrong type was passed.
  2775. possible type mismatch:
  2776. Luser is an idiot!
  2777. Elaboration on a message is performed usually by wrapping an
  2778. irritant in a descriptive list. For example, one might write:
  2779. (error "invalid argument"
  2780. '(not a pair)
  2781. `(while calling ,frobbotz)
  2782. `(received ,object))
  2783. This might be printed as:
  2784. Error: invalid argument
  2785. (not a pair)
  2786. (while calling #{Procedure 123 (frobbotz in ...)})
  2787. (received #(a b c d))
  2788. The 'handle' structure exports the following procedures:
  2789. -- procedure: with-handler handler thunk --> values
  2790. Sets up HANDLER as the condition handler for the dynamic extent of
  2791. THUNK. HANDLER should be a procedure of two arguments: the
  2792. condition that was signalled and a procedure of zero arguments that
  2793. propagates the condition up to the next dynamically enclosing
  2794. handler. When a condition is signalled, HANDLER is tail-called
  2795. from the point that the condition was signalled at. Note that,
  2796. because HANDLER is tail-called at that point, it will _return_ to
  2797. that point also.
  2798. *Warning:* 'With-handler' is potentially very dangerous. If an
  2799. exception occurs and a condition is raised in the handler, the
  2800. handler itself will be called with that new condition!
  2801. Furthermore, the handler may accidentally return to an unexpecting
  2802. signaller, which can cause very confusing errors. Be careful with
  2803. 'with-handler'; to be perfectly safe, it might be a good idea to
  2804. throw back out to where the handler was initially installed before
  2805. doing anything:
  2806. ((call-with-current-continuation
  2807. (lambda (k)
  2808. (lambda ()
  2809. (with-handler (lambda (c propagate)
  2810. (k (lambda () HANDLER BODY)))
  2811. (lambda () BODY))))))
  2812. -- procedure: ignore-errors thunk --> values or condition
  2813. -- procedure: report-errors-as-warnings thunk message irritant ... -->
  2814. values
  2815. 'Ignore-errors' sets up a condition handler that will return error
  2816. conditions to the point where 'ignore-errors' was called, and
  2817. propagate all other conditions. If no condition is signalled
  2818. during the dynamic extent of THUNK, 'ignore-errors' simply returns
  2819. whatever THUNK returned. 'Report-errors-as-warnings' downgrades
  2820. errors to warnings while executing THUNK. If an error occurs, a
  2821. warning is signalled with the given message, and a list of
  2822. irritants constructed by adding the error condition to the end of
  2823. the list IRRITANT ....
  2824. Finally, the 'simple-conditions' structure defines the condition type
  2825. system. (Note that conditions themselves are constructed only by
  2826. 'make-condition' (and 'signal') from the 'simple-signals' structure.)
  2827. Conditions are very basic values that have only two universally defined
  2828. fields: the type and the stuff. The type is a symbol denoting a
  2829. condition type. The type is specified in the first argument to
  2830. 'make-condition' or 'signal'. The stuff field contains whatever a
  2831. particular condition type stores in conditions of that type. The stuff
  2832. field is always a list; it is created from the arguments after the first
  2833. to 'make-condition' or 'signal'. Condition types are denoted by
  2834. symbols, kept in a global registry that maps condition type names to
  2835. their supertype names.
  2836. -- procedure: define-condition-type name supertype-names -->
  2837. unspecified
  2838. Registers the symbol NAME as a condition type. Its supertypes are
  2839. named in the list SUPERTYPE-NAMES.
  2840. -- procedure: condition-predicate ctype-name --> predicate
  2841. Returns a procedure of one argument that returns '#t' if that
  2842. argument is a condition whose type's name is CTYPE-NAME or '#f' if
  2843. not.
  2844. -- procedure: condition-type condition --> type-name
  2845. -- procedure: condition-stuff condition --> list
  2846. Accessors for the two immutable fields of conditions.
  2847. -- procedure: error? condition --> boolean
  2848. -- procedure: warning? condition --> boolean
  2849. -- procedure: note? condition --> boolean
  2850. -- procedure: syntax-error? condition --> boolean
  2851. -- procedure: call-error? condition --> boolean
  2852. -- procedure: read-error? condition --> boolean
  2853. -- procedure: interrupt? condition --> boolean
  2854. Condition predicates for built-in condition types.
  2855. -- procedure: make-exception opcode reason arguments --> exception
  2856. -- procedure: exception? condition --> boolean
  2857. -- procedure: exception-opcode exception --> integer-opcode
  2858. -- procedure: exception-reason exception --> symbol
  2859. -- procedure: exception-arguments exception --> list
  2860. "Exceptions" represent run-time errors in the Scheme48 VM. They
  2861. contain information about what opcode the VM was executing when it
  2862. happened, what the reason for the exception occurring was, and the
  2863. relevant arguments.
  2864. 4.2.2 Displaying conditions
  2865. ---------------------------
  2866. The 'display-conditions' structure is also relevant in this section.
  2867. -- procedure: display-condition condition port --> unspecified
  2868. Prints CONDITION to PORT for a user to read. For example:
  2869. (display-condition (make-condition 'error
  2870. "Foo bar baz"
  2871. 'quux
  2872. '(zot mumble: frotz))
  2873. (current-output-port))
  2874. -| Error: Foo bar baz
  2875. -| quux
  2876. -| (zot mumble: frotz)
  2877. -- method table: &disclose-condition condition --> disclosed
  2878. Method table (*note Generic dispatch system::) for a generic
  2879. procedure (not exposed) used to translate a condition object into a
  2880. more readable format. *Note Writer::.
  2881. -- procedure: limited-write object port max-depth max-length -->
  2882. unspecified
  2883. A utility for avoiding excessive output: prints OBJECT to PORT, but
  2884. will never print more than MAX-LENGTH of a subobject's components,
  2885. leaving a '---' after the last component, and won't recur further
  2886. down the object graph from the vertex OBJECT beyond MAX-DEPTH,
  2887. instead printing an octothorpe ('#').
  2888. (let ((x (cons #f #f)))
  2889. (set-car! x x)
  2890. (set-cdr! x x)
  2891. (limited-write x (current-output-port) 2 2))
  2892. -| ((# # ---) (# # ---) ---)
  2893. ---------- Footnotes ----------
  2894. (1) Note, however, that Scheme48's condition system is likely to be
  2895. superseded in the near future by [SRFI 34, SRFI 35].
  2896. 
  2897. File: scheme48.info, Node: Bitwise manipulation, Next: Generic dispatch system, Prev: Condition system, Up: System facilities
  2898. 4.3 Bitwise manipulation
  2899. ========================
  2900. Scheme48 provides two structures for bit manipulation: bitwise integer
  2901. operations, the 'bitwise' structure, and homogeneous vectors of bytes
  2902. (integers between 0 and 255, inclusive), the 'byte-vectors' structure.
  2903. 4.3.1 Bitwise integer operations
  2904. --------------------------------
  2905. The 'bitwise' structure exports these procedures:
  2906. -- procedure: bitwise-and integer ... --> integer
  2907. -- procedure: bitwise-ior integer ... --> integer
  2908. -- procedure: bitwise-xor integer ... --> integer
  2909. -- procedure: bitwise-not integer --> integer
  2910. Basic twos-complement bitwise boolean logic operations.
  2911. -- procedure: arithmetic-shift integer count --> integer
  2912. Shifts INTEGER by the given bit count. If COUNT is positive, the
  2913. shift is a left shift; otherwise, it is a right shift.
  2914. 'Arithmetic-shift' preserves INTEGER's sign.
  2915. -- procedure: bit-count integer --> integer
  2916. Returns the number of bits that are set in INTEGER. If INTEGER is
  2917. negative, it is flipped by the bitwise NOT operation before
  2918. counting.
  2919. (bit-count #b11010010) => 4
  2920. 4.3.2 Byte vectors
  2921. ------------------
  2922. The structure 'byte-vectors' exports analogues of regular vector
  2923. procedures for "byte vectors", homogeneous vectors of bytes:
  2924. -- procedure: make-byte-vector length fill --> byte-vector
  2925. -- procedure: byte-vector byte ... --> byte-vector
  2926. -- procedure: byte-vector? object --> boolean
  2927. -- procedure: byte-vector-length byte-vector --> integer
  2928. -- procedure: byte-vector-ref byte-vector index --> byte
  2929. -- procedure: byte-vector-set! byte-vector index byte --> unspecified
  2930. FILL and each BYTE must be bytes, i.e. integers within the
  2931. inclusive range 0 to 255. Note that 'make-byte-vector' is not an
  2932. exact analogue of 'make-vector', because the FILL parameter is
  2933. required.
  2934. Old versions of Scheme48 referred to byte vectors as 'code vectors'
  2935. (since they were used to denote byte code). The 'code-vectors'
  2936. structure exports 'make-code-vector', 'code-vector?',
  2937. 'code-vector-length', 'code-vector-ref', and 'code-vector-set!',
  2938. identical to the analogously named byte vector operations.
  2939. 
  2940. File: scheme48.info, Node: Generic dispatch system, Next: I/O system, Prev: Bitwise manipulation, Up: System facilities
  2941. 4.4 Generic dispatch system
  2942. ===========================
  2943. Scheme48 supports a CLOS-style generic procedure dispatch system, based
  2944. on type predicates. The main interface is exported by 'methods'. The
  2945. internals of the system are exposed by the 'meta-methods' structure, but
  2946. they are not documented here. The generic dispatch system is used in
  2947. Scheme48's writer (*note Writer::) and numeric system.
  2948. "Types" in Scheme48's generic dispatch system are represented using
  2949. type predicates, rather than having every object have a single,
  2950. well-defined 'class.' The naming convention for simple types is to
  2951. prefix the type name with a colon. The types support multiple
  2952. inheritance. Method specificity is determined based on descending order
  2953. of argument importance. That is, given two methods, M & N, such that
  2954. they are both applicable to a given sequence of arguments, and an index
  2955. I into that sequence, such that I is the first index in M's & N's lists
  2956. of argument type specifiers, from left to right, where the type differs:
  2957. if the type for M's argument at I is more specific than the
  2958. corresponding type in N's specifiers, M is considered to be more
  2959. specific than N, even if the remaining argument type specifiers in N are
  2960. more specific.
  2961. -- syntax: define-simple-type name (supertype ...) predicate
  2962. Defines NAME to be a "simple type" with the given predicate and the
  2963. given supertypes.
  2964. -- procedure: singleton value --> simple-type
  2965. Creates a "singleton type" that matches only VALUE.
  2966. -- syntax: define-generic proc-name method-table-name [prototype]
  2967. Defines PROC-NAME to be a "generic procedure" that, when invoked,
  2968. will dispatch on its arguments via the "method table" that
  2969. METHOD-TABLE-NAME is defined to be and apply the most specific
  2970. method it can determine defined in the METHOD-TABLE-NAME method
  2971. table to its arguments. The convention for naming variables that
  2972. will be bound to method tables is to add an ampersand to the front
  2973. of the name. PROTOTYPE is a suggestion for what method prototypes
  2974. should follow the shape of, but it is currently ignored.
  2975. -- syntax: define-method method-table prototype body
  2976. Adds a "method" to METHOD-TABLE, which is usually one defined by
  2977. 'define-generic'.(1) PROTOTYPE should be a list whose elements may
  2978. be either identifiers, in which case that parameter is not used for
  2979. dispatching, or lists of two elements, the 'car' of which is the
  2980. parameter name and the 'cadr' of which should evaluate to the type
  2981. on which to dispatch. As in many generic dispatch systems of
  2982. similar designs, methods may invoke the next-most-specific method.
  2983. By default, the name 'next-method' is bound in BODY to a nullary
  2984. procedure that calls the next-most-specific method. The name of
  2985. this procedure may be specified by the user by putting the sequence
  2986. '"next" NEXT-METHOD-NAME' in PROTOTYPE, in which case it will be
  2987. NEXT-METHOD-NAME that is bound to that procedure. For example:
  2988. (define-method &frob ((foo :bar) "next" frobozz)
  2989. (if (mumble? foo)
  2990. (frobozz) ; Invoke the next method.
  2991. (yargh blargle foo)))
  2992. A number of simple types are already defined & exported by the
  2993. 'methods' structure. Entries are listed as 'TYPE-NAME <- (SUPERTYPE
  2994. ...), PREDICATE'
  2995. * ':values <- (), (lambda (x) #t)' -- Abstract supertype of all
  2996. run-time values
  2997. * ':value <- (:values), (lambda (x) #t)' -- Abstract supertype of all
  2998. first-class values
  2999. * ':zero <- (:values), (lambda (x) #f)' -- Type that no objects
  3000. satisfy
  3001. * ':number <- (:value), number?'
  3002. * ':complex <- (:number), complex?' -- (This happens to be equivalent
  3003. to ':number'.)
  3004. * ':real <- (:complex), real?'
  3005. * ':rational <- (:real), rational?'
  3006. * ':integer <- (:rational), integer?'
  3007. * ':exact-integer <- (:integer), (lambda (x) (and (integer? x)
  3008. (exact? x)))'
  3009. * ':boolean <- (:value), boolean?'
  3010. * ':symbol <- (:value), symbol?'
  3011. * ':char <- (:value), char?'
  3012. * ':null <- (:value), null?'
  3013. * ':pair <- (:value), pair?'
  3014. * ':vector <- (:value), vector?'
  3015. * ':string <- (:value), string?'
  3016. * ':procedure <- (:value), procedure?'
  3017. * ':input-port <- (:value), input-port?'
  3018. * ':output-port <- (:value), output-port?'
  3019. * ':eof-object <- (:value), eof-object?'
  3020. * ':record <- (:value), record?'
  3021. ---------- Footnotes ----------
  3022. (1) There is an internal interface, a sort of meta-object protocol,
  3023. to the method dispatch system, but it is not yet documented.
  3024. 
  3025. File: scheme48.info, Node: I/O system, Next: Reader & writer, Prev: Generic dispatch system, Up: System facilities
  3026. 4.5 I/O system
  3027. ==============
  3028. Scheme48 supports a sophisticated, non-blocking, user-extensible I/O
  3029. system untied to any particular operating system's I/O facilities. It
  3030. is based in three levels: channels, ports, and the facilities already
  3031. built with both ports and channels in Scheme48, such as buffering.
  3032. * Menu:
  3033. * Ports:: Abstract & generalized I/O objects.
  3034. * Programmatic ports:: Designing custom ports.
  3035. * Miscellaneous I/O internals:: Various internal I/O system routines.
  3036. * Channels:: Low-level interface to OS facilities.
  3037. * Channel ports:: Ports built upon channels.
  3038. 
  3039. File: scheme48.info, Node: Ports, Next: Programmatic ports, Up: I/O system
  3040. 4.5.1 Ports
  3041. -----------
  3042. While channels provide the low-level interface directly to the OS's I/O
  3043. facilities, "ports" provide a more abstract & generalized mechanism for
  3044. I/O transmission. Rather than being specific to channels or being
  3045. themselves primitive I/O devices, ports are functionally parameterized.
  3046. This section describes the usual I/O operations on ports. The next
  3047. section describes the programmatic port parameterization mechanism, and
  3048. the section following that describes the most commonly used built-in
  3049. port abstraction, ports atop channels.
  3050. 4.5.1.1 Port operations
  3051. .......................
  3052. The following names are exported by the 'i/o' structure.
  3053. -- procedure: input-port? value --> boolean
  3054. -- procedure: output-port? value --> boolean
  3055. These return '#t' if their argument is both a port and either an
  3056. input port or output port, respectively, or '#f' if neither
  3057. condition is true.
  3058. -- procedure: close-input-port port --> unspecified
  3059. -- procedure: close-output-port port --> unspecified
  3060. Closes PORT, which must be an input port or an output port,
  3061. respectively.
  3062. -- procedure: char-ready? [port] --> boolean
  3063. -- procedure: output-port-ready? port --> boolean
  3064. 'Char-ready?' returns a true value if there is a character ready to
  3065. be read from PORT and '#f' if there is no character ready. PORT
  3066. defaults to the current input port if absent; see below on current
  3067. ports. 'Output-port-ready?' returns a true value if PORT is ready
  3068. to receive a single written character and '#f' if not.
  3069. -- procedure: read-block block start count port [wait?] --> count-read
  3070. or EOF
  3071. -- procedure: write-block block start count port --> count-written
  3072. -- procedure: write-string string port --> char-count-written
  3073. 'Read-block' attempts to read COUNT elements from PORT into BLOCK,
  3074. which may be a string or a byte vector, starting at START. If
  3075. fewer than COUNT characters or bytes are available to read from
  3076. PORT, and WAIT? is a true value or absent, 'read-block' will wait
  3077. until COUNT characters are available and read into BLOCK; if WAIT?
  3078. is '#f', 'read-block' immediately returns. 'Read-block' returns
  3079. the number of elements read into BLOCK, or an end of file object if
  3080. the stream's end is immediately encountered. 'Write-block' writes
  3081. COUNT elements from BLOCK, which may be a string or a byte vector,
  3082. starting at START to PORT. 'Write-string' is a convenience atop
  3083. 'write-block' for writing the entirety of a string to a port.
  3084. -- procedure: newline [port] --> unspecified
  3085. Writes a newline character or character sequence to the output port
  3086. PORT. PORT defaults to the current output port; see below on
  3087. current ports.
  3088. -- procedure: disclose-port port --> disclosed
  3089. Returns a disclosed representation of PORT; *note Writer::.
  3090. -- procedure: force-output port --> unspecified
  3091. Forces all buffered output in the output port PORT to be sent.
  3092. -- procedure: make-null-output-port --> output-port
  3093. Returns an output port that will ignore any output it receives.
  3094. 4.5.1.2 Current ports
  3095. .....................
  3096. Scheme48 keeps in its dynamic environment (*note Fluid/dynamic
  3097. bindings::) a set of 'current' ports. These include R5RS's current
  3098. input and output ports, as well as ports for general noise produced by
  3099. the system, and ports for where error messages are printed. These
  3100. procedures are exported by the 'i/o' structure.
  3101. -- procedure: current-input-port --> input-port
  3102. -- procedure: current-output-port --> output-port
  3103. -- procedure: current-noise-port --> output-port
  3104. -- procedure: current-error-port --> output-port
  3105. These return the values in the current dynamic environment of the
  3106. respective ports. 'Current-input-port' and 'current-output-port'
  3107. are also exported by the 'scheme' structure.
  3108. -- procedure: input-port-option arguments --> input-port
  3109. -- procedure: output-port-option arguments --> output-port
  3110. These are utilities for retrieving optional input and output port
  3111. arguments from rest argument lists, defaulting to the current input
  3112. or output ports. For example, assuming the newline character
  3113. sequence is simply '#\newline', 'newline' might be written as:
  3114. (define (newline . maybe-port)
  3115. (write-char #\newline (output-port-option maybe-port)))
  3116. -- procedure: silently thunk --> values
  3117. This stifles output from the current noise port in the dynamic
  3118. extent of THUNK, which is applied to zero arguments. 'Silently'
  3119. returns the values that THUNK returns.
  3120. -- procedure: with-current-ports input output error thunk --> values
  3121. 'With-current-ports' dynamically binds the current input, output,
  3122. and error ports to INPUT, OUTPUT, and ERROR, respectively, in the
  3123. dynamic extent of THUNK, which is applied to zero arguments. The
  3124. current noise port is also bound to ERROR. 'With-current-ports'
  3125. returns the values that THUNK returns.
  3126. Similarly to 'with-current-ports', the 'i/o-internal' structure also
  3127. exports these procedures:
  3128. -- procedure: call-with-current-input-port port thunk --> values
  3129. -- procedure: call-with-current-output-port port thunk --> values
  3130. -- procedure: call-with-current-noise-port port thunk --> values
  3131. These bind individual current ports for the dynamic extent of each
  3132. THUNK, which is applied to zero arguments. These all return the
  3133. values that THUNK returns.
  3134. 
  3135. File: scheme48.info, Node: Programmatic ports, Next: Miscellaneous I/O internals, Prev: Ports, Up: I/O system
  3136. 4.5.2 Programmatic ports
  3137. ------------------------
  3138. Ports are user-extensible; all primitive port operations on them --
  3139. 'read-char', 'write-block', &c. -- are completely generalized.
  3140. Abstractions for buffered ports are also available.
  3141. * Menu:
  3142. * Port data type::
  3143. * Port handlers::
  3144. * Buffered ports & handlers::
  3145. 
  3146. File: scheme48.info, Node: Port data type, Next: Port handlers, Up: Programmatic ports
  3147. 4.5.2.1 Port data type
  3148. ......................
  3149. The 'ports' structure defines the basis of the port data type and
  3150. exports the following procedures.
  3151. -- procedure: make-port handler status lock data buffer index limit
  3152. pending-eof? --> port
  3153. Port constructor. The arguments are all the fields of ports, which
  3154. are described below. Note that 'make-port' is rarely called
  3155. directly; usually one will use one of the buffered port
  3156. constructors instead.
  3157. -- procedure: port-handler port --> port-handler
  3158. -- procedure: port-buffer port --> buffer or '#f'
  3159. -- procedure: port-lock port --> value
  3160. -- procedure: port-status port --> integer-status
  3161. -- procedure: port-data port --> value
  3162. -- procedure: port-index port --> integer or '#f'
  3163. -- procedure: port-limit port --> integer or '#f'
  3164. -- procedure: port-pending-eof? port --> boolean
  3165. Accessors for the port fields:
  3166. 'handler'
  3167. The handler is the functional parameterization mechanism: it
  3168. provides all the port's operations, such as reading/writing
  3169. blocks, disclosing (*note Writer::) the port, closing the
  3170. port, &c. *Note Port handlers::.
  3171. 'buffer'
  3172. The buffer is used for buffered ports, where it is a byte
  3173. vector (*note Bitwise manipulation::). It may be any value
  3174. for unbuffered ports.
  3175. 'lock'
  3176. This misnamed field was originally used for a mutual exclusion
  3177. lock, before optimistic concurrency was made the native
  3178. synchronization mechanism in Scheme48. It is now used as a
  3179. 'timestamp' for buffered ports: it is provisionally written to
  3180. with a unique value when a thread resets the 'index' to reüse
  3181. the buffer, and it is provisionally read from when reading
  3182. from the buffer. In this way, if the buffer is reset while
  3183. another thread is reading from it, the other thread's proposal
  3184. is invalidated by the different value in memory than what was
  3185. there when it logged the old timestamp in its proposal.
  3186. 'status'
  3187. A mask from the 'port-status-options' enumeration; *note
  3188. Miscellaneous I/O internals::.
  3189. 'data'
  3190. Arbitrary data for particular kinds of ports. For example,
  3191. for a port that tracks line & column information (*note I/O
  3192. extensions::), this might be a record containing the
  3193. underlying port, the line number, and the column number.
  3194. 'index'
  3195. The current index into a buffered port's buffer. If the port
  3196. is not buffered, this is '#f'.
  3197. 'limit'
  3198. The limit of the 'index' field for a buffered port's buffer.
  3199. When the 'index' field is equal to the 'limit' field, the
  3200. buffer is full. If the port is not buffered, this is '#f'.
  3201. 'pending-eof?'
  3202. For output ports, this is a boolean flag indicating whether
  3203. the buffer has been forced to output recently. For input
  3204. ports, this is a boolean flag indicating whether an end of
  3205. file is pending after reading through the current buffer.
  3206. -- procedure: set-port-lock! port value --> unspecified
  3207. -- procedure: set-port-status! port status --> unspecified
  3208. -- procedure: set-port-data! port data --> unspecified
  3209. -- procedure: set-port-index! port index --> unspecified
  3210. -- procedure: set-port-limit! port index --> unspecified
  3211. -- procedure: set-port-pending-eof?! port pending-eof? --> unspecified
  3212. These assign respective fields of ports. The 'buffer' and
  3213. 'handler' fields, however, are immutable.
  3214. -- procedure: provisional-port-handler port --> port-handler
  3215. -- procedure: provisional-port-lock port --> value
  3216. -- procedure: provisional-port-status port --> integer-status
  3217. -- procedure: provisional-port-data port --> value
  3218. -- procedure: provisional-port-index port --> integer or '#f'
  3219. -- procedure: provisional-port-limit port --> integer or '#f'
  3220. -- procedure: provisional-port-pending-eof? port --> boolean
  3221. -- procedure: provisional-set-port-lock! port value --> unspecified
  3222. -- procedure: provisional-set-port-status! port status --> unspecified
  3223. -- procedure: provisional-set-port-data! port data --> unspecified
  3224. -- procedure: provisional-set-port-index! port index --> unspecified
  3225. -- procedure: provisional-set-port-limit! port index --> unspecified
  3226. -- procedure: provisional-set-port-pending-eof?! port pending-eof? -->
  3227. unspecified
  3228. Provisional versions of the above port accessors & modifiers; that
  3229. is, accessors & modifiers that log in the current proposal, if
  3230. there is one.
  3231. 
  3232. File: scheme48.info, Node: Port handlers, Next: Buffered ports & handlers, Prev: Port data type, Up: Programmatic ports
  3233. 4.5.2.2 Port handlers
  3234. .....................
  3235. "Port handlers" store a port's specific operations for the general port
  3236. operations, such as block reads and writes, buffer flushing, &c. Port
  3237. handler constructors, including 'make-port-handler' & the buffered port
  3238. handlers in the next section, are available from the 'i/o-internal'
  3239. structure.
  3240. -- procedure: make-port-handler discloser closer char-reader/writer
  3241. block-reader/writer readiness-tester buffer-forcer -->
  3242. port-handler
  3243. Basic port handler constructor. The arguments are used for the
  3244. port handler fields. Each field contains a procedure. The
  3245. expected semantics of each procedure depend on whether the port is
  3246. for input or output. Input ports do not use the 'buffer-forcer'
  3247. field. The first two fields are independent of the type of port:
  3248. discloser port -> disclosed
  3249. Returns a disclosed representation of the port, i.e. a list
  3250. whose 'car' is the 'type name' of this handler (usually with a
  3251. suffix of either '-input-port' or '-output-port') followed by
  3252. a list of all of the components to be printed; *note Writer::.
  3253. closer port -> ignored
  3254. Closes PORT. This operation corresponds with the
  3255. 'close-input-port' & 'close-output-port' procedures.
  3256. For input ports, the remaining fields are:
  3257. char-reader port consume? -> char
  3258. Reads a single character from PORT. If CONSUME? is true, the
  3259. character should be consumed from PORT; if CONSUME? is '#f',
  3260. however, the character should be left in PORT's input stream.
  3261. If CONSUME? is true, this operation corresponds with
  3262. 'read-char'; if it is '#f', this operation corresponds with
  3263. 'peek-char'.
  3264. block-reader port block start count wait? -> count-written or EOF
  3265. Attempts to read COUNT characters from PORT's input stream
  3266. into the string or byte vector BLOCK, starting at START. In
  3267. the case that an insufficient number of characters is
  3268. available, if WAIT? is true, the procedure should wait until
  3269. all of the wanted characters are available; otherwise, if
  3270. WAIT? is '#f', the block reader should immediately return. In
  3271. either case, it returns the number of characters that were
  3272. read into BLOCK, or an end of file object if it immediately
  3273. reached the end of the stream. Buffered ports will typically
  3274. just copy elements from the buffer into BLOCK, rather than
  3275. reading from any internal I/O channel in PORT. This operation
  3276. corresponds with 'read-block'.
  3277. readiness-tester port -> boolean
  3278. Returns a true value if there is a character available to be
  3279. read in PORT or '#f' if not. This operation corresponds with
  3280. the 'char-ready?' procedure.
  3281. For output ports, the remaining fields are:
  3282. char-writer port char -> ignored
  3283. Writes the single character CHAR to PORT. This operation
  3284. corresponds with 'write-char'.
  3285. block-writer port block start count -> count-written
  3286. Writes COUNT characters to PORT from BLOCK, starting at START.
  3287. BLOCK may be a string or a byte vector. This will usually
  3288. involve copying contents of BLOCK to PORT's buffer, if it is
  3289. buffered. This operation corresponds with 'write-block'.
  3290. readiness-tester port -> boolean
  3291. Returns a true value if PORT is ready to receive a character
  3292. and '#f' if not.
  3293. buffer-forcer port necessary? -> ignored
  3294. For buffered ports, this is intended to force all buffered
  3295. output to the actual internal I/O channel of PORT. NECESSARY?
  3296. tells whether or not it is absolutely necessary to force all
  3297. the output immediately; if it is '#t', the buffer forcer is
  3298. required to force all output in the buffer before it returns.
  3299. If NECESSARY? is '#f', not only may it just register an I/O
  3300. transaction without waiting for it to complete, but it also
  3301. should _not_ signal an error if PORT is already closed. For
  3302. unbuffered ports, this operation need not do anything at all.
  3303. 
  3304. File: scheme48.info, Node: Buffered ports & handlers, Prev: Port handlers, Up: Programmatic ports
  3305. 4.5.2.3 Buffered ports & handlers
  3306. .................................
  3307. Along with bare port handlers, Scheme48 provides conveniences for many
  3308. patterns of buffered ports & port handlers. These names are exported by
  3309. the 'i/o-internal' structure. Buffered ports are integrated with
  3310. Scheme48's optimistic concurrency (*note Optimistic concurrency::)
  3311. facilities.
  3312. *Note:* Although internally buffered ports are integrated with
  3313. optimistic concurrency, operations on buffered ports, like operations on
  3314. channels, cannot be reliably fusibly atomic.
  3315. -- procedure: make-buffered-input-port handler data buffer index limit
  3316. --> input-port
  3317. -- procedure: make-buffered-output-port handler data buffer index limit
  3318. --> output-port
  3319. Constructors for buffered ports. HANDLER is the port's handler,
  3320. which is usually constructed with one of the buffered port handler
  3321. constructors (see below). DATA is arbitrary data to go in the
  3322. port's 'data' field. BUFFER is a byte vector whose length is
  3323. greater than or equal to both INDEX & LIMIT. INDEX is the initial
  3324. index into BUFFER to go in the port's 'index' field. LIMIT is the
  3325. limit in the port's buffer, to go into the port's 'limit' field;
  3326. nothing will be written into BUFFER at or past LIMIT.
  3327. -- procedure: make-unbuffered-input-port handler data --> input-port
  3328. -- procedure: make-unbuffered-output-port handler data --> output-port
  3329. Conveniences for ports that are explicitly _not_ buffered. Only
  3330. the relevant fields are passed; all fields pertaining to buffering
  3331. are initialized with '#f'.
  3332. -- procedure: make-buffered-input-port-handler discloser closer
  3333. buffer-filler readiness-tester --> port-handler
  3334. This creates a port handler for buffered input ports. The
  3335. arguments are as follows:
  3336. discloser port-data -> disclosed
  3337. closer port-data -> ignored
  3338. DISCLOSER & CLOSER are like the similarly named regular port
  3339. handler fields, but they are applied directly to the port's
  3340. data, not to the port itself.
  3341. buffer-filler port wait? -> committed?
  3342. Used to fill PORT's buffer when it no longer has contents from
  3343. which to read in its current buffer. WAIT? is a boolean flag,
  3344. '#t' if the operation should wait until the I/O transaction
  3345. necessary to fill the buffer completes, or '#f' if it may
  3346. simply initiate an I/O transaction but not wait until it
  3347. completes (e.g., use 'channel-maybe-commit-and-read', but not
  3348. wait on the condition variable passed to
  3349. 'channel-maybe-commit-and-read'). BUFFER-FILLER is called
  3350. with a fresh proposal in place, and it is the responsibility
  3351. of BUFFER-FILLER to commit it. It returns a boolean flag
  3352. denoting whether the proposal was committed. The last call in
  3353. BUFFER-FILLER is usually either '(maybe-commit)' or a call to
  3354. a procedure that causes that effect (e.g., one of the
  3355. operation on condition variables that commits the current
  3356. proposal. *Note condition variables: Higher-level
  3357. synchronization.)
  3358. readiness-tester port -> [committed? ready?]
  3359. Called when 'char-ready?' is applied to PORT and the buffer of
  3360. PORT is empty. Like BUFFER-FILLER, READINESS-TESTER is
  3361. applied with a fresh proposal in place, which it should
  3362. attempt to commit. READINESS-TESTER should return two values,
  3363. each a boolean flag: the first denotes whether or not the
  3364. current proposal was successfully committed, and, if it was
  3365. successful, whether or not a character is ready.
  3366. -- procedure: make-buffered-output-port-handler discloser
  3367. buffer-emptier readiness-tester --> port-handler
  3368. This creates a port handler for buffered output ports. DISCLOSER &
  3369. CLOSER are as with buffered input ports. The remaining fields are
  3370. as follows:
  3371. buffer-emptier port necessary? -> committed?
  3372. BUFFER-EMPTIER is used when PORT's buffer is full and needs to
  3373. be emptied. It is called with a fresh proposal in place. It
  3374. should reset PORT's 'index' field, call 'note-buffer-reuse!'
  3375. to invalidate other threads' transactions on the recycled
  3376. buffer, and attempt to commit the new proposal installed. It
  3377. returns a boolean flag indicating whether or not the commit
  3378. succeeded.
  3379. readiness-tester port -> [committed? ready?]
  3380. READINESS-TESTER is applied to PORT when its buffer is full
  3381. (i.e. its 'index' & 'limit' fields are equal) and
  3382. 'output-port-ready?' is applied to PORT. After performing the
  3383. test, it should attempt to commit the current proposal and
  3384. then return two values: whether it succeeded in committing the
  3385. current proposal, and, if it was successful, whether or not a
  3386. character is ready to be outputted.
  3387. -- constant: default-buffer-size --> integer
  3388. The default size for port buffers. This happens to be 4096 in the
  3389. current version of Scheme48.
  3390. -- procedure: note-buffer-reuse! port --> unspecified
  3391. -- procedure: check-buffer-timestamp! port --> unspecified
  3392. These are used to signal the resetting of a buffer between multiple
  3393. threads. 'Note-buffer-reuse!' is called -- in the case of an
  3394. output port -- when a buffer fills up, is emptied, and flushed; or
  3395. -- in the case of an input port -- when a buffer is emptied and
  3396. needs to be refilled. 'Note-buffer-reuse!' logs in the current
  3397. proposal a fresh value to store in PORT. When that proposal is
  3398. committed, this fresh value is stored in the port. Other threads
  3399. that were using PORT's buffer call 'check-buffer-timestamp!', which
  3400. logs a read in the current proposal. If another thread commits a
  3401. buffer reüse to memory, that read will be invalidated, invalidating
  3402. the whole transaction.
  3403. 
  3404. File: scheme48.info, Node: Miscellaneous I/O internals, Next: Channels, Prev: Programmatic ports, Up: I/O system
  3405. 4.5.3 Miscellaneous I/O internals
  3406. ---------------------------------
  3407. All of these but 'port-status-options' are exported by the
  3408. 'i/o-internal' structure; the 'port-status-options' enumeration is
  3409. exported by the 'architecture' structure, but it deserves mention in
  3410. this section.
  3411. -- enumeration: port-status-options
  3412. (define-enumeration port-status-options
  3413. (input
  3414. output
  3415. open-for-input
  3416. open-for-output))
  3417. Enumeration of indices into a port's 'status' field bit set.
  3418. -- procedure: open-input-port? port --> boolean
  3419. -- procedure: open-output-port? port --> boolean
  3420. These return true values if PORT is both an input or output port,
  3421. respectively, and open.
  3422. -- constant: open-input-port-status --> integer-status
  3423. -- constant: open-output-port-status --> integer-status
  3424. The bitwise masks of enumerands from the 'port-status-options'
  3425. enumeration signifying an open input or output port, respectively.
  3426. -- procedure: make-input-port-closed! port --> unspecified
  3427. -- procedure: make-output-port-closed! port --> unspecified
  3428. These set the status of PORT, which must be an input or output
  3429. port, respectively, to indicate that it is closed.
  3430. -- procedure: eof-object --> eof-object
  3431. Returns the EOF object token. This is the only value that will
  3432. answer true to R5RS's 'eof-object?' predicate.
  3433. -- procedure: force-output-if-open port --> unspecified
  3434. This forces PORT's output if it is an open output port, and does
  3435. not block.
  3436. -- procedure: periodically-force-output! port --> unspecified
  3437. -- procedure: periodically-flushed-ports --> port-list
  3438. 'Periodically-force-output!' registers PORT to be forced
  3439. periodically. Only a weak reference to PORT in this registry is
  3440. held, however, so this cannot cause accidental space leaks.
  3441. 'Periodically-flushed-ports' returns a list of all ports in this
  3442. registry. Note that the returned list holds strong references to
  3443. all of its elements. 'Periodically-flushed-ports' does not permit
  3444. thread context switches, or interrupts of any sort, while it runs.
  3445. 
  3446. File: scheme48.info, Node: Channels, Next: Channel ports, Prev: Miscellaneous I/O internals, Up: I/O system
  3447. 4.5.4 Channels
  3448. --------------
  3449. "Channels" represent the OS's native I/O transmission channels. On
  3450. Unix, channels are essentially boxed file descriptors, for example. The
  3451. only operations on channels are block reads & writes. Blocks in this
  3452. sense may be either strings or byte vectors (*note Bitwise
  3453. manipulation::).
  3454. 4.5.4.1 Low-level channel operations
  3455. ....................................
  3456. The low-level base of the interface to channels described here is
  3457. exported from the 'channels' structure.
  3458. -- procedure: channel? --> boolean
  3459. Disjoint type predicate for channels.
  3460. -- procedure: channel-id channel --> value
  3461. -- procedure: channel-status channel --> integer-enumerand
  3462. -- procedure: channel-os-index channel --> integer
  3463. 'Channel-id' returns CHANNEL's id. The id is some identifying
  3464. characteristic of channels. For example, file channels' ids are
  3465. usually the corresponding filenames; channels such as the standard
  3466. input, output, or error output channels have names like '"standard
  3467. input"' and '"standard output"'. 'Channel-status' returns the
  3468. current status of CHANNEL; see the 'channel-status-option'
  3469. enumeration below. 'Channel-os-index' returns the OS-specific
  3470. integer index of CHANNEL. On Unix, for example, this is the
  3471. channel's file descriptor.
  3472. -- procedure: open-channel filename option close-silently? --> channel
  3473. 'Open-channel' opens a channel for a file given its filename.
  3474. OPTION specifies what type of channel this is; see the
  3475. 'channel-status-option' enumeration below. CLOSE-SILENTLY? is a
  3476. boolean that specifies whether a message should be printed (on
  3477. Unix, to 'stderr') when the resulting channel is closed after a
  3478. garbage collector finds it unreachable.
  3479. -- procedure: close-channel channel --> unspecified
  3480. Closes CHANNEL after aborting any potential pending I/O
  3481. transactions it may have been involved with.
  3482. -- procedure: channel-ready? channel --> boolean
  3483. If CHANNEL is an input channel: returns '#t' if there is input
  3484. ready to be read from CHANNEL or '#f' if not; if CHANNEL is an
  3485. output channel: returns '#t' if a write would immediately take
  3486. place upon calling 'channel-maybe-write', i.e.
  3487. 'channel-maybe-write' would not return '#f', or '#f' if not.
  3488. -- procedure: channel-maybe-read channel buffer start-index octet-count
  3489. wait? --> octet count read, error status cell, EOF object, or
  3490. '#f'
  3491. -- procedure: channel-maybe-write channel buffer start-index
  3492. octet-count --> octet count written, error status cell, or
  3493. '#f'
  3494. -- procedure: channel-abort channel --> unspecified
  3495. 'Channel-maybe-read' attempts to read OCTET-COUNT octets from
  3496. CHANNEL into BUFFER, starting at START-INDEX. If a low-level I/O
  3497. error occurs, it returns a cell containing a token given by the
  3498. operating system indicating what kind of error occurred. If WAIT?
  3499. is '#t', and CHANNEL is not ready to be read from, CHANNEL is
  3500. registered for the VM's event polling mechanism, and
  3501. 'channel-maybe-read' returns '#f'. Otherwise, it returns either
  3502. the number of octets read, or an EOF object if CHANNEL was was at
  3503. the end.
  3504. 'Channel-maybe-write' attempts to write OCTET-COUNT octets to
  3505. CHANNEL from BUFFER, starting at START-INDEX. If a low-level I/O
  3506. error occurs, it returns a cell indicating a token given by the
  3507. operating system indicating what kind of error occurred. If no
  3508. such low-level error occurs, it registers CHANNEL for the VM's
  3509. event polling mechanism and returns '#f' iff zero octets were
  3510. immediately written or the number of octets immediately written if
  3511. any were.
  3512. 'Channel-abort' aborts any pending operation registered for the
  3513. VM's event polling mechanism.
  3514. -- procedure: open-channels-list --> channel-list
  3515. Returns a list of all open channels in order of the 'os-index'
  3516. field.
  3517. -- enumeration: channel-status-option
  3518. (define-enumeration channel-status-option
  3519. (closed
  3520. input
  3521. output
  3522. special-input
  3523. special-output))
  3524. Enumeration for a channel's status. The 'closed' enumerand is used
  3525. only after a channel has been closed. Note that this is _not_
  3526. suitable for a bit mask; that is, one may choose exactly one of the
  3527. enumerands, not use a bit mask of status options. For example, to
  3528. open a file 'frob' for input that one wishes the garbage collector
  3529. to be silent about on closing it:
  3530. (open-channel "frob"
  3531. (enum channel-status-option input)
  3532. #t)
  3533. => #{Input-channel "frob"}
  3534. 4.5.4.2 Higher-level channel operations
  3535. .......................................
  3536. More convenient abstractions for operating on channels, based on
  3537. condition variables (*note Higher-level synchronization::), are provided
  3538. from the 'channel-i/o' structure. They are integrated with Scheme48's
  3539. optimistic concurrency (*note Optimistic concurrency::) facilities.
  3540. *Note:* Transactions on channels can _not_ be atomic in the sense of
  3541. optimistic concurrency. Since they involve communication with the
  3542. outside world, they are irrevocable transactions, and thus an
  3543. invalidated proposal cannot retract the transaction on the channel.
  3544. -- procedure: channel-maybe-commit-and-read channel buffer start-index
  3545. octet-count condvar wait? --> committed?
  3546. -- procedure: channel-maybe-commit-and-write channel buffer start-index
  3547. octet-count condvar --> committed?
  3548. These attempt to commit the current proposal. If they fail, they
  3549. immediately return '#f'; otherwise, they proceed, and return '#t'.
  3550. If the commit succeeded, these procedures attempt an I/O
  3551. transaction, without blocking. 'Channel-maybe-commit-and-read'
  3552. attempts to read OCTET-COUNT octets into BUFFER, starting at
  3553. START-INDEX, from CHANNEL. 'Channel-maybe-commit-and-write'
  3554. attempts to write OCTET-COUNT octets from BUFFER, starting at
  3555. START-INDEX, to CHANNEL. CONDVAR is noted as waiting for the
  3556. completion of the I/O transaction. When the I/O transaction
  3557. finally completes -- in the case of a read, there are octets ready
  3558. to be read into BUFFER from CHANNEL or the end of the file was
  3559. struck; in the case of a write, CHANNEL is ready to receive some
  3560. octets --, CONDVAR is set to the result of the I/O transaction: the
  3561. number of octets read, an I/O error condition, or an EOF object,
  3562. for reads; and the number of octets written or an I/O error
  3563. condition, for writes.
  3564. -- procedure: channel-maybe-commit-and-close channel closer -->
  3565. committed?
  3566. Attempts to commit the current proposal; if successful, this aborts
  3567. any wait on CHANNEL, sets the result of any condvars waiting on
  3568. CHANNEL to the EOF object, closes CHANNEL by applying CLOSER to
  3569. CHANNEL (in theory, CLOSER could be anything; usually, however, it
  3570. is 'close-channel' from the 'channels' structure or some wrapper
  3571. around it), and returns '#t'. If the commit failed,
  3572. 'channel-maybe-commit-and-close' immediately returns '#f'.
  3573. -- procedure: channel-write channel buffer start-index octet-count -->
  3574. octet-count-written
  3575. Atomically attempts to write OCTET-COUNT octets to CHANNEL from
  3576. BUFFER, starting at START-INDEX in BUFFER. If no I/O transaction
  3577. immediately occurs -- what would result in 'channel-maybe-write'
  3578. returning '#f' --, 'channel-write' blocks until something does
  3579. happen. It returns the number of octets written to CHANNEL.
  3580. -- procedure: wait-for-channel channel condvar --> unspecified
  3581. Registers CONDVAR so that it will be set to the result of some
  3582. prior I/O transaction when some I/O event regarding CHANNEL occurs.
  3583. (Contrary to the name, this does not actually wait or block. One
  3584. must still use 'maybe-commit-and-wait-for-condvar' on CONDVAR;
  3585. *note condition variables: Higher-level synchronization.) This is
  3586. useful primarily in conjunction with calling foreign I/O routines
  3587. that register channels with the VM's event polling system.
  3588. *Note:* 'wait-for-channel' must be called with interrupts disabled.
  3589. 
  3590. File: scheme48.info, Node: Channel ports, Prev: Channels, Up: I/O system
  3591. 4.5.5 Channel ports
  3592. -------------------
  3593. Built-in to Scheme48 are ports made atop channels. These are what are
  3594. created by R5RS's standard file operations. The following names are
  3595. exported by the 'channel-ports' structure.
  3596. -- procedure: call-with-input-file filename receiver --> values
  3597. -- procedure: call-with-output-file filename receiver --> values
  3598. -- procedure: with-input-from-file filename thunk --> values
  3599. -- procedure: with-output-to-file filename thunk --> values
  3600. -- procedure: open-input-file filename --> input-port
  3601. -- procedure: open-output-file filename --> output-port
  3602. Standard R5RS file I/O operations. (These are also exported by the
  3603. 'scheme' structure.) The 'call-with-...put-file' operations open
  3604. the specified type of port and apply RECEIVER to it; after RECEIVER
  3605. returns normally (i.e. nothing is done if there is a throw out of
  3606. RECEIVER), they close the port and return the values that RECEIVER
  3607. returned. 'With-input-from-file' & 'with-output-to-file' do
  3608. similarly, but, rather than applying THUNK to the port, they
  3609. dynamically bind the current input & output ports, respectively, to
  3610. the newly opened ports. 'Call-with-input-file',
  3611. 'call-with-output-file', 'with-input-from-file', and
  3612. 'with-output-to-file' return the values that THUNK returns.
  3613. 'Open-input-file' & 'open-output-file' just open input & output
  3614. ports; users of these operations must close them manually.
  3615. -- procedure: input-channel->port channel [buffer-size] --> port
  3616. -- procedure: output-channel->port channel [buffer-size] --> port
  3617. These create input & output ports atop the given channels and
  3618. optional buffer sizes. The default buffer size is 4096 bytes.
  3619. -- procedure: input-channel+closer->port channel closer [buffer-size]
  3620. --> port
  3621. -- procedure: output-channel+closer->port channel closer [buffer-size]
  3622. --> port
  3623. Similarly, these create input & output ports atop the given
  3624. channels and optional buffer sizes, but they allow for extra
  3625. cleanup when the resulting ports are closed.
  3626. -- procedure: port->channel port --> channel or '#f'
  3627. If PORT is a port created by the system's channel ports facility,
  3628. 'port->channel' returns the channel it was created atop; otherwise
  3629. 'port->channel' returns '#f'.
  3630. -- procedure: force-channel-output-ports! --> unspecified
  3631. This attempts to force as much output as possible from all of the
  3632. ports based on channels. This is used by Scheme48's POSIX
  3633. libraries before forking the current process.
  3634. 
  3635. File: scheme48.info, Node: Reader & writer, Next: Records, Prev: I/O system, Up: System facilities
  3636. 4.6 Reader & writer
  3637. ===================
  3638. Scheme48 has simple S-expression reader & writer libraries, with some
  3639. facilities beyond R5RS's 'read' & 'write' procedures.
  3640. * Menu:
  3641. * Reader::
  3642. * Writer::
  3643. 
  3644. File: scheme48.info, Node: Reader, Next: Writer, Up: Reader & writer
  3645. 4.6.1 Reader
  3646. ------------
  3647. Scheme48's reader facility is exported by the 'reading' structure. The
  3648. 'read' binding thereby exported is identical to that of the 'scheme'
  3649. structure, which is the binding that R5RS specifies under the name
  3650. 'read'.
  3651. -- procedure: read [port] --> readable-value
  3652. Reads a single S-expression from PORT, whose default value is the
  3653. current input port. If the end of the stream is encountered before
  3654. the beginning of an S-expression, 'read' will return an EOF object.
  3655. It will signal a read error if text read from PORT does not
  3656. constitute a complete, well-formed S-expression.
  3657. -- procedure: define-sharp-macro char proc --> unspecified
  3658. Defines a sharp/pound/hash/octothorpe ('#') reader macro. The next
  3659. time the reader is invoked, if it encounters an octothorpe/sharp
  3660. followed by CHAR, it applies PROC to CHAR and the input port being
  3661. read from. CHAR is _not_ consumed in the input port. If CHAR is
  3662. alphabetic, it should be lowercase; otherwise the reader will not
  3663. recognize it, since the reader converts the character following
  3664. octothorpes to lowercase.
  3665. -- procedure: reading-error port message irritant ... --> unspecified
  3666. Signals an error while reading, for custom sharp macros. It is not
  3667. likely that calls to 'reading-error' will return.
  3668. -- procedure: gobble-line port --> unspecified
  3669. Reads until a newline from PORT. The newline character sequence is
  3670. consumed.
  3671. 
  3672. File: scheme48.info, Node: Writer, Prev: Reader, Up: Reader & writer
  3673. 4.6.2 Writer
  3674. ------------
  3675. Scheme48's 'writing' structure exports its writer facility. The 'write'
  3676. and 'display' bindings from it are identical to those from the 'scheme'
  3677. structure, which are the same bindings that R5RS specifies.
  3678. -- procedure: write object [port] --> unspecified
  3679. Writes OBJECT to PORT, which defaults to the current output port,
  3680. in a machine-readable manner. Strings are written with double-
  3681. quotes; characters are prefixed by '#\'. Any object that is
  3682. unreadable -- anything that does not have a written representation
  3683. as an S-expression -- is written based on its "disclosed"
  3684. representation. Such unreadable objects are converted to a
  3685. disclosed representation by the 'disclose' generic procedure (see
  3686. below).
  3687. -- procedure: display object [port] --> unspecified
  3688. Displays OBJECT to PORT, which defaults to the value of the current
  3689. output port, in a more human-readable manner. Strings are written
  3690. without surrounding double-quotes; characters are written as
  3691. themselves with no prefix.
  3692. -- procedure: recurring-write object port recur --> unspecified
  3693. Writes OBJECT to PORT. Every time this recurs upon a new object,
  3694. rather than calling itself or its own looping procedure, it calls
  3695. RECUR. This allows customized printing routines that still take
  3696. advantage of the existence of Scheme48's writer. For example,
  3697. 'display' simply calls 'recurring-write' with a recurring procedure
  3698. that prints strings and characters specially and lets
  3699. 'recurring-write' handle everything else.
  3700. -- procedure: display-type-name name port --> unspecified
  3701. If NAME is a symbol with an alphabetic initial character, this
  3702. writes NAME to PORT with the first character uppercased and the
  3703. remaining character lowercased; otherwise, 'display-type-name'
  3704. simply writes NAME to PORT with 'display'.
  3705. (display-type-name 'foo)
  3706. -| Foo
  3707. (display-type-name (string->symbol "42foo"))
  3708. -| 42foo
  3709. (display-type-name (cons "foo" "bar"))
  3710. -| (foo . bar)
  3711. (display-type-name (string->symbol "fOo-BaR"))
  3712. -| Foo-bar
  3713. This is used when printing disclosed representations (see below).
  3714. 4.6.2.1 Object disclosure
  3715. .........................
  3716. The 'methods' structure (*note Generic dispatch system::) exports the
  3717. generic procedure 'disclose' and its method table '&disclose'. When
  3718. 'recurring-write' encounters an object it is unable to write in a
  3719. rereadable manner, it applies 'disclose' to the unreadable object to
  3720. acquire a "disclosed representation." (If 'disclose' returns '#f', i.e.
  3721. the object has no disclosed representation, the writer will write
  3722. '#{Random object}'.) After converting a value to its disclosed
  3723. representation, e.g. a list consisting of the symbol 'foo', the symbol
  3724. 'bar', a byte vector, and a pair '(1 . 2)', the writer will write '#{Foo
  3725. #{Byte-vector} bar (1 . 2)}'. That is: contents of the list are
  3726. surrounded by '#{' and '}', the first element of the list (the 'type
  3727. name') is written with 'display-type-name', and then the remaining
  3728. elements of the list are recursively printed out with the RECUR
  3729. argument.
  3730. Typically, when a programmer creates an abstract data type by using
  3731. Scheme48's record facility, he will not add methods to '&disclose' but
  3732. instead define the record type's discloser with the
  3733. 'define-record-discloser' procedure; *note Records::.
  3734. Example:
  3735. (define-record-type pare rtd/pare
  3736. (kons a d)
  3737. pare?
  3738. (a kar set-kar!)
  3739. (d kdr set-kdr!))
  3740. (define-record-discloser rtd/pare
  3741. (lambda (pare)
  3742. `(pare ,(kar pare) *dot* ,(kdr pare))))
  3743. (write (kons (kons 5 3) (kons 'a 'b)))
  3744. -| #{Pare #{Pare 5 *dot* 3} *dot* #{Pare a *dot* b}}
  3745. 
  3746. File: scheme48.info, Node: Records, Next: Suspending and resuming heap images, Prev: Reader & writer, Up: System facilities
  3747. 4.7 Records
  3748. ===========
  3749. Scheme48 provides several different levels of a record facility. Most
  3750. programmers will probably not care about the two lower levels; the
  3751. syntactic record type definers are sufficient for abstract data types.
  3752. At the highest level, there are two different record type definition
  3753. macros. Richard Kelsey's is exported from the 'defrecord' structure;
  3754. Jonathan Rees's is exported from 'define-record-types'. They both
  3755. export a 'define-record-type' macro and the same
  3756. 'define-record-discloser' procedure; however, the macros are
  3757. dramatically different. Scheme48 also provides [SRFI 9], which is
  3758. essentially Jonathan Rees's record type definition macro with a slight
  3759. syntactic difference, in the 'srfi-9' structure. Note, however, that
  3760. 'srfi-9' does not export 'define-record-discloser'. The difference
  3761. between Jonathan Rees's and Richard Kelsey's record type definition
  3762. macros is merely syntactic convenience; Jonathan Rees's more
  3763. conveniently allows for arbitrary naming of the generated variables,
  3764. whereas Richard Kelsey's is more convenient if the naming scheme varies
  3765. little.
  3766. 4.7.1 Jonathan Rees's 'define-record-type' macro
  3767. ------------------------------------------------
  3768. -- syntax: define-record-type
  3769. (define-record-type RECORD-TYPE-NAME RECORD-TYPE-VARIABLE
  3770. (CONSTRUCTOR CONSTRUCTOR-ARGUMENT ...)
  3771. [PREDICATE]
  3772. (FIELD-TAG FIELD-ACCESSOR [FIELD-MODIFIER])
  3773. ...)
  3774. This defines RECORD-TYPE-VARIABLE to be a record type descriptor.
  3775. CONSTRUCTOR is defined to be a procedure that accepts the listed
  3776. field arguments and creates a record of the newly defined type with
  3777. those fields initialized to the corresponding arguments.
  3778. PREDICATE, if present, is defined to be the disjoint (as long as
  3779. abstraction is not violated by the lower-level record interface)
  3780. type predicate for the new record type. Each FIELD-ACCESSOR is
  3781. defined to be a unary procedure that accepts a record type and
  3782. returns the value of the field named by the corresponding
  3783. FIELD-TAG. Each FIELD-MODIFIER, if present, is defined to be a
  3784. binary procedure that accepts a record of the new type and a value,
  3785. which it assigns the field named by the corresponding FIELD-TAG to.
  3786. Every CONSTRUCTOR-ARGUMENT must have a corresponding FIELD-TAG,
  3787. though FIELD-TAGs that are not used as arguments to the record
  3788. type's constructor are simply uninitialized when created. They
  3789. should have modifiers: otherwise they will never be initialized.
  3790. It is worth noting that Jonathan Rees's 'define-record-type' macro
  3791. does not introduce identifiers that were not in the original
  3792. macro's input form.
  3793. For example:
  3794. (define-record-type pare rtd/pare
  3795. (kons a d)
  3796. pare?
  3797. (a kar)
  3798. (d kdr set-kdr!))
  3799. (kar (kons 5 3))
  3800. => 5
  3801. (let ((p (kons 'a 'c)))
  3802. (set-kdr! p 'b)
  3803. (kdr p))
  3804. => b
  3805. (pare? (kons 1 2))
  3806. => #t
  3807. (pare? (cons 1 2))
  3808. => #f
  3809. There is also a variant of Jonathan Rees's 'define-record-type' macro
  3810. for defining record types with fields whose accessors and modifiers
  3811. respect optimistic concurrency (*note Optimistic concurrency::) by
  3812. logging in the current proposal.
  3813. 4.7.2 Richard Kelsey's 'define-record-type' macro
  3814. -------------------------------------------------
  3815. -- syntax: define-record-type
  3816. (define-record-type TYPE-NAME
  3817. (ARGUMENT-FIELD-SPECIFIER ...)
  3818. (NONARGUMENT-FIELD-SPECIFIER ...))
  3819. ARGUMENT-FIELD-SPECIFIER -->
  3820. FIELD-TAG Immutable field
  3821. | (FIELD-TAG) Mutable field
  3822. NONARGUMENT-FIELD-SPECIFIER -->
  3823. FIELD-TAG Uninitialized field
  3824. | (FIELD-TAG EXP) Initialized with EXP's value
  3825. This defines 'type/TYPE-NAME' to be a record type descriptor for
  3826. the newly defined record type, 'TYPE-NAME-maker' to be a
  3827. constructor for the new record type that accepts arguments for
  3828. every field in the argument field specifier list, 'TYPE-NAME?' to
  3829. be the disjoint type predicate for the new record type, accessors
  3830. for each field tag FIELD-TAG by constructing an identifier
  3831. 'TYPE-NAME-FIELD-TAG', and modifiers for each argument field tag
  3832. that was specified to be mutable as well as each nonargument field
  3833. tag. The name of the modifier for a field tag FIELD-TAG is
  3834. constructed to be 'set-TYPE-NAME-FIELD-TAG!'.
  3835. Note that Richard Kelsey's 'define-record-type' macro _does_
  3836. concatenate & introduce new identifiers, unlike Jonathan Rees's.
  3837. For example, a use of Richard Kelsey's 'define-record-type' macro
  3838. (define-record-type pare
  3839. (kar
  3840. (kdr))
  3841. (frob
  3842. (mumble 5)))
  3843. is equivalent to the following use of Jonathan Rees's macro
  3844. (define-record-type pare type/pare
  3845. (%pare-maker kar kdr mumble)
  3846. pare?
  3847. (kar pare-kar)
  3848. (kdr pare-kdr set-pare-kdr!)
  3849. (frob pare-frob set-pare-frob!)
  3850. (mumble pare-mumble set-pare-mumble!))
  3851. (define (pare-maker kar kdr)
  3852. (%pare-maker kar kdr 5))
  3853. 4.7.3 Record types
  3854. ------------------
  3855. Along with two general record type definition facilities, there are
  3856. operations directly on the record type descriptors themselves, exported
  3857. by the 'record-types' structure. (Record type descriptors are actually
  3858. records themselves.)
  3859. -- procedure: make-record-type name field-tags -->
  3860. record-type-descriptor
  3861. -- procedure: record-type? object --> boolean
  3862. 'Make-record-type' makes a record type descriptor with the given
  3863. name and field tags. 'Record-type?' is the disjoint type predicate
  3864. for record types.
  3865. -- procedure: record-type-name rtype-descriptor --> symbol
  3866. -- procedure: record-type-field-names rtype-descriptor --> symbol-list
  3867. Accessors for the two record type descriptor fields.
  3868. -- procedure: record-constructor rtype-descriptor argument-field-tags
  3869. --> constructor-procedure
  3870. -- procedure: record-predicate rtype-descriptor --> predicate-procedure
  3871. -- procedure: record-accessor rtype-descriptor field-tag -->
  3872. accessor-procedure
  3873. -- procedure: record-modifier rtype-descriptor field-tag -->
  3874. modifier-procedure
  3875. Constructors for the various procedures relating to record types.
  3876. 'Record-constructor' returns a procedure that accepts arguments for
  3877. each field in ARGUMENT-FIELD-TAGS and constructs a record whose
  3878. record type descriptor is RTYPE-DESCRIPTOR, initialized with its
  3879. arguments. 'Record-predicate' returns a disjoint type predicate
  3880. for records whose record type descriptor is RTYPE-DESCRIPTOR.
  3881. 'Record-accessor' and 'record-modifier' return accessors and
  3882. modifiers for records whose record type descriptor is
  3883. RTYPE-DESCRIPTOR for the given fields.
  3884. -- procedure: define-record-discloser rtype-descriptor discloser -->
  3885. unspecific
  3886. Defines the method by which records of type RTYPE-DESCRIPTOR are
  3887. disclosed (*note Writer::). This is also exported by
  3888. 'define-record-types' and 'defrecord'.
  3889. -- procedure: define-record-resumer rtype-descriptor resumer -->
  3890. unspecified
  3891. Sets RTYPE-DESCRIPTOR's record resumer to be RESUMER. If RESUMER
  3892. is '#t' (the default), records of this type require no particular
  3893. reinitialization when found in dumped heap images (*note Suspending
  3894. and resuming heap images::); if RESUMER is '#f', records of the
  3895. type RTYPE-DESCRIPTOR may not be dumped in heap images; finally, if
  3896. it is a procedure, and the heap image is resumed with the usual
  3897. image resumer (*note Suspending and resuming heap images::), it is
  3898. applied to each record whose record type descriptor is
  3899. RTYPE-DESCRIPTOR after the run-time system has been initialized and
  3900. before the argument to 'usual-resumer' is called.
  3901. The 'records-internal' structure also exports these:
  3902. -- record type: :record-type
  3903. The record type of record types.
  3904. -- procedure: disclose-record record --> disclosed
  3905. This applies RECORD's record type descriptor's discloser procedure
  3906. to RECORD to acquire a disclosed representation; *note Writer::.
  3907. For expository purposes, the record type record type might have been
  3908. defined like so with Jonathan Rees's 'define-record-type' macro:
  3909. (define-record-type record-type :record-type
  3910. (make-record-type name field-names)
  3911. record-type?
  3912. (name record-type-name)
  3913. (field-names record-type-field-names))
  3914. or like so with Richard Kelsey's 'define-record-type' macro:
  3915. (define-record-type record-type
  3916. (name field-names)
  3917. ())
  3918. Of course, in reality, these definitions would have severe problems with
  3919. circularity of definition.
  3920. 4.7.4 Low-level record manipulation
  3921. -----------------------------------
  3922. Internally, records are represented very similarly to vectors, and as
  3923. such have low-level operations on them similar to vectors, exported by
  3924. the 'records' structure. Records usually reserve the slot at index 0
  3925. for their record type descriptor.
  3926. *Warning:* The procedures described here can be very easily misused
  3927. to horribly break abstractions. Use them very carefully, only in very
  3928. limited & extreme circumstances!
  3929. -- procedure: make-record length init --> record
  3930. -- procedure: record elt ... --> record
  3931. -- procedure: record? object --> boolean
  3932. -- procedure: record-length record --> integer
  3933. -- procedure: record-ref record index --> value
  3934. -- procedure: record-set! record index object --> unspecified
  3935. Exact analogues of similarly named vector operation procedures.
  3936. -- procedure: record-type record --> value
  3937. This returns the record type descriptor of RECORD, i.e. the value
  3938. of the slot at index 0 in RECORD.
  3939. 
  3940. File: scheme48.info, Node: Suspending and resuming heap images, Prev: Records, Up: System facilities
  3941. 4.8 Suspending and resuming heap images
  3942. =======================================
  3943. Scheme48's virtual machine operates by loading a heap image into memory
  3944. and calling the initialization procedure specified in the image dump.
  3945. Heap images can be produced in several different ways: programmatically
  3946. with 'write-image', using the command processor's facilities (*note
  3947. Image-building commands::), or with the static linker. This section
  3948. describes only 'write-image' and the related system resumption &
  3949. initialization.
  3950. Heap image dumps begin with a sequence of characters terminated by an
  3951. ASCII form-feed/page character (codepoint 12). This content may be
  3952. anything; for example, it might be a Unix '#!' line that invokes
  3953. 'scheme48vm' on the file, or it might be a silly message to whomever
  3954. reads the top of the heap image dump file. (The command processor's
  3955. ',dump' & ',build' commands (*note Image-building commands::) write a
  3956. blank line at the top; the static linker puts a message stating that the
  3957. image was built by the static linker.)
  3958. 'Write-image' is exported by the 'write-images' structure.
  3959. -- procedure: write-image filename startup-proc message --> unspecified
  3960. Writes a heap image whose startup procedure is STARTUP-PROC and
  3961. that consists of every object accessible in some way from
  3962. STARTUP-PROC. MESSAGE is put at the start of the heap image file
  3963. before the ASCII form-feed/page character. When the image is
  3964. resumed, STARTUP-PROC is passed a vector of program arguments, an
  3965. input channel for standard input, an output channel for standard
  3966. output, an output channel for standard error, and a vector of
  3967. records to be resumed. This is typically simplified by
  3968. 'usual-resumer' (see below). On Unix, STARTUP-PROC must return an
  3969. integer exit code; otherwise the program will crash and burn with a
  3970. very low-level VM error message when STARTUP-PROC returns.
  3971. 4.8.1 System initialization
  3972. ---------------------------
  3973. When suspended heap images are resumed by the VM, the startup procedure
  3974. specified in the heap image is applied to five arguments: a vector of
  3975. command-line arguments (passed after the '-a' argument to the VM), an
  3976. input channel for standard input, an output channel for standard output,
  3977. an output channel for standard error, and a vector of records to be
  3978. resumed. The startup procedure is responsible for performing any
  3979. initialization necessary -- including initializing the Scheme48 run-time
  3980. system -- as well as simply running the program. Typically, this
  3981. procedure is not written manually: resumers are ordinarily created using
  3982. the "usual resumer" abstraction, exported from the structure
  3983. 'usual-resumer'.
  3984. -- procedure: usual-resumer startup-proc --> resumer-proc
  3985. This returns a procedure that is suitable as a heap image resumer
  3986. procedure. When the heap image is resumed, it initializes the
  3987. run-time system -- it resumes all the records, initializes the
  3988. thread system, the dynamic state, the interrupt system, I/O system,
  3989. &c. -- and applies STARTUP-PROC to a list (not a vector) of the
  3990. command-line arguments.
  3991. Some records may contain machine-, OS-, or other session-specific
  3992. data. When suspended in heap images and later resumed, this data may be
  3993. invalidated, and it may be necessary to reinitialize this data upon
  3994. resumption of suspended heap images. For this reason Scheme48 provides
  3995. "record resumers"; see 'define-record-resumer' from the 'record-types'
  3996. structure (*note Records::).
  3997. 4.8.2 Manual system initialization
  3998. ----------------------------------
  3999. If a programmer chooses not to use 'usual-resumer' -- which is _not_ a
  4000. very common thing to do --, he is responsible for manual initialization
  4001. of the run-time system, including the I/O system, resumption of records,
  4002. the thread system and the root thread scheduler, the interrupt system,
  4003. and the condition system.
  4004. *Warning:* Manual initialization of the run-time system is a _very_
  4005. delicate operation. Although one can potentially vastly decrease the
  4006. size of dumped heap images by doing it manually, (1) it is very
  4007. error-prone and difficult to do without exercising great care, which is
  4008. why the usual resumer facility exists. Unless you _*really*_ know what
  4009. you are doing, you should just use the usual resumer.
  4010. At the present, documentation of manual system initialization is
  4011. absent. However, if the reader knows enough about what he is doing that
  4012. he desires to manually initialize the run-time system, he is probably
  4013. sufficiently familiar with it already to be able to find the necessary
  4014. information directly from Scheme48's source code and module
  4015. descriptions.
  4016. ---------- Footnotes ----------
  4017. (1) For example, the author of this manual, merely out of curiosity,
  4018. compared the sizes of two images: one that used the usual resumer and
  4019. printed each of its command-line arguments, and one that performed _no_
  4020. run-time system initialization -- which eliminated the run-time system
  4021. in the image, because it was untraceable from the resumer -- and wrote
  4022. directly to the standard output channel. The difference was a factor of
  4023. about twenty. However, also note that the difference is constant; the
  4024. run-time system happened to account for nineteen twentieths of the
  4025. larger image.
  4026. 
  4027. File: scheme48.info, Node: Multithreading, Next: Libraries, Prev: System facilities, Up: Top
  4028. 5 Multithreading
  4029. ****************
  4030. This chapter describes Scheme48's fully preëmptive and sophisticated
  4031. user-level thread system. Scheme48 supports customized and nested
  4032. thread schedulers, user-designed synchronization mechanisms, optimistic
  4033. concurrency, useful thread synchronization libraries, a high-level event
  4034. algebra based on Reppy's Concurrent ML [Reppy 99], and common
  4035. pessimistic concurrency/mutual-exclusion-based thread synchronization
  4036. facilities.
  4037. * Menu:
  4038. * Basic thread operations::
  4039. * Optimistic concurrency::
  4040. * Higher-level synchronization::
  4041. * Concurrent ML:: High-level event synchronization
  4042. * Pessimistic concurrency:: Mutual exclusion/locking
  4043. * Custom thread synchronization::
  4044. 
  4045. File: scheme48.info, Node: Basic thread operations, Next: Optimistic concurrency, Up: Multithreading
  4046. 5.1 Basic thread operations
  4047. ===========================
  4048. This section describes the 'threads' structure.
  4049. -- procedure: spawn thunk [name] --> thread
  4050. 'Spawn' constructs a new thread and instructs the current thread
  4051. scheduler to commence running the new thread. NAME, if present, is
  4052. used for debugging. The new thread has a fresh dynamic environment
  4053. (*note Fluid/dynamic bindings::).
  4054. There are several miscellaneous facilities for thread operations.
  4055. -- procedure: relinquish-timeslice --> unspecified
  4056. -- procedure: sleep count --> unspecified
  4057. 'Relinquish-timeslice' relinquishes the remaining quantum that the
  4058. current thread has to run; this allows the current scheduler run
  4059. the next thread immediately. 'Sleep' suspends the current thread
  4060. for COUNT milliseconds.
  4061. -- procedure: terminate-current-thread --> (does not return)
  4062. Terminates the current thread, running all 'dynamic-wind' exit
  4063. points. 'Terminate-current-thread' obviously does not return.
  4064. Threads may be represented and manipulated in first-class thread
  4065. descriptor objects.
  4066. -- procedure: current-thread --> thread
  4067. -- procedure: thread? object --> boolean
  4068. -- procedure: thread-name thread --> value
  4069. -- procedure: thread-uid thread --> unique-integer-id
  4070. 'Current-thread' returns the thread descriptor for the currently
  4071. running thread. 'Thread?' is the thread descriptor disjoint type
  4072. predicate. 'Thread-name' returns the name that was passed to
  4073. 'spawn' when spawning THREAD, or '#f' if no name was passed.
  4074. 'Thread-uid' returns a thread descriptor's unique integer
  4075. identifier, assigned by the thread system.
  4076. 
  4077. File: scheme48.info, Node: Optimistic concurrency, Next: Higher-level synchronization, Prev: Basic thread operations, Up: Multithreading
  4078. 5.2 Optimistic concurrency
  4079. ==========================
  4080. Scheme48's fundamental thread synchronization mechanism is based on a
  4081. device often used in high-performance database systems: optimistic
  4082. concurrency. The basic principle of optimistic concurrency is that,
  4083. rather than mutually excluding other threads from data involved in one
  4084. thread's transaction, a thread keeps a log of its transaction, not
  4085. actually modifying the data involved, only touching the log. When the
  4086. thread is ready to commit its changes, it checks that all of the reads
  4087. from memory retained their integrity -- that is, all of the memory that
  4088. was read from during the transaction has remained the same, and is
  4089. consistent with what is there at the time of the commit. If, and only
  4090. if, all of the reads remained valid, the logged writes are committed;
  4091. otherwise, the transaction has been invalidated. While a thread is
  4092. transacting, any number of other threads may be also transacting on the
  4093. same resource. All that matters is that the values each transaction
  4094. read are consistent with every write that was committed during the
  4095. transaction. This synchronization mechanism allows for wait-free,
  4096. lockless systems that easily avoid confusing problems involving careful
  4097. sequences of readily deadlock-prone mutual exclusion.
  4098. In the Scheme48 system, every thread has its own log of transactions,
  4099. called a "proposal". There are variants of all data accessors &
  4100. modifiers that operate on the current thread's proposal, rather than
  4101. actual memory: after the initial read of a certain part of memory --
  4102. which _does_ perform a real read --, the value from that location in
  4103. memory is cached in the proposal, and thenceforth reads from that
  4104. location in memory will actually read the cache; modifications touch
  4105. only the proposal, until the proposal is committed.
  4106. All of the names described in this section are exported by the
  4107. 'proposals' structure.
  4108. 5.2.1 High-level optimistic concurrency
  4109. ---------------------------------------
  4110. There are several high-level operations that abstract the manipulation
  4111. of the current thread's proposal.
  4112. -- procedure: call-ensuring-atomicity thunk --> values
  4113. -- procedure: call-ensuring-atomicity! thunk --> unspecified
  4114. These ensure that the operation of THUNK is atomic. If there is
  4115. already a current proposal in place, these are equivalent to
  4116. calling THUNK. If there is not a current proposal in place, these
  4117. install a new proposal, call THUNK, and attempt to commit the new
  4118. proposal. If the commit succeeded, these return. If it failed,
  4119. these retry with a new proposal until they do succeed.
  4120. 'Call-ensuring-atomicity' returns the values that THUNK returned
  4121. when the commit succeeded; 'call-ensuring-atomicity!' returns zero
  4122. values -- it is intended for when THUNK is used for its effects
  4123. only.
  4124. -- procedure: call-atomically thunk --> values
  4125. -- procedure: call-atomically! thunk --> unspecified
  4126. These are like CALL-ENSURING-ATOMICITY and
  4127. CALL-ENSURING-ATOMICITY!, respectively, except that they always
  4128. install a new proposal (saving the old one and restoring it when
  4129. they are done).
  4130. -- syntax: ensure-atomicity body --> values
  4131. -- syntax: ensure-atomicity! body --> unspecified
  4132. -- syntax: atomically body --> values
  4133. -- syntax: atomically! body --> unspecified
  4134. These are syntactic sugar over 'call-ensuring-atomicity',
  4135. 'call-ensuring-atomicity!', 'call-atomically', and
  4136. 'call-atomically!', respectively.
  4137. Use these high-level optimistic concurrency operations to make the
  4138. body atomic. 'Call-ensuring-atomicity' &c. simply ensure that the
  4139. transaction will be atomic, and may 'fuse' it with an enclosing atomic
  4140. transaction if there already is one, i.e. use the proposal for that
  4141. transaction already in place, creating one only if there is not already
  4142. one. 'Call-atomically' &c. are for what might be called 'subatomic'
  4143. transactions, which cannot be fused with other atomic transactions, and
  4144. for which there is always created a new proposal.
  4145. However, code within 'call-ensuring-atomicity' &c. or
  4146. 'call-atomically' &c. should _not_ explicitly commit the current
  4147. proposal; those operations above _automatically_ commit the current
  4148. proposal when the atomic transaction is completed. (In the case of
  4149. 'call-atomically' &c., this is when the procedure passed returns; in the
  4150. case of 'call-ensuring-atomicity' &c., this is when the outermost
  4151. enclosing atomic transaction completes, or the same as 'call-atomically'
  4152. if there was no enclosing atomic transaction.) To explicitly commit the
  4153. current proposal -- for example, to perform some particular action if
  4154. the commit fails rather than just to repeatedly retry the transaction,
  4155. or to use operations from the customized thread synchronization (*note
  4156. Custom thread synchronization::) facilities that commit the current
  4157. proposal after their regular function, or the operations on condition
  4158. variables (*note Higher-level synchronization::) that operate on the
  4159. condition variable and then commit the current proposal --, one must use
  4160. the 'with-new-proposal' syntax as described below, not these operations.
  4161. 5.2.2 Logging variants of Scheme procedures
  4162. -------------------------------------------
  4163. -- procedure: provisional-car pair --> value
  4164. -- procedure: provisional-cdr pair --> value
  4165. -- procedure: provisional-set-car! pair value --> unspecified
  4166. -- procedure: provisional-set-cdr! pair value --> unspecified
  4167. -- procedure: provisional-cell-ref cell --> value
  4168. -- procedure: provisional-cell-set! cell value --> unspecified
  4169. -- procedure: provisional-vector-ref vector index --> value
  4170. -- procedure: provisional-vector-set! vector index value -->
  4171. unspecified
  4172. -- procedure: provisional-string-ref string index --> char
  4173. -- procedure: provisional-string-set! string index value -->
  4174. unspecified
  4175. -- procedure: provisional-byte-vector-ref byte-vector index --> char
  4176. -- procedure: provisional-byte-vector-set! byte-vector index byte -->
  4177. unspecified
  4178. -- procedure: attempt-copy-bytes! from fstart to tstart count -->
  4179. unspecified
  4180. These are variants of most basic Scheme memory accessors &
  4181. modifiers that log in the current proposal, rather than performing
  4182. the actual memory access/modification. All of these do perform the
  4183. actual memory access/modification, however, if there is no current
  4184. proposal in place when they are called. 'Attempt-copy-bytes!'
  4185. copies a sequence of COUNT bytes from the byte vector or string
  4186. FROM, starting at the index FSTART, to the byte vector or string
  4187. TO, starting at the index TSTART.
  4188. 5.2.3 Synchronized records
  4189. --------------------------
  4190. -- syntax: define-synchronized-record-type
  4191. (define-synchronized-record-type TAG TYPE-NAME
  4192. (CONSTRUCTOR-NAME PARAMETER-FIELD-TAG ...)
  4193. [(SYNC-FIELD-TAG ...)]
  4194. PREDICATE-NAME
  4195. (FIELD-TAG ACCESSOR-NAME [MODIFIER-NAME])
  4196. ...)
  4197. This is exactly like 'define-record-type' from the
  4198. 'define-record-types' structure, except that the accessors &
  4199. modifiers for each field in SYNC-FIELD-TAG ... are defined to be
  4200. provisional, i.e. to log in the current proposal. If the list of
  4201. synchronized fields is absent, all of the fields are synchronized,
  4202. i.e. it is as if all were specified in that list.
  4203. The 'proposals' structure also exports 'define-record-discloser'
  4204. (*note Records::). Moreover, the 'define-sync-record-types' structure,
  4205. too, exports 'define-synchronized-record-type', though it does not
  4206. export 'define-record-discloser'.
  4207. 5.2.4 Optimistic concurrency example
  4208. ------------------------------------
  4209. Here is a basic example of using optimistic concurrency to ensure the
  4210. synchronization of memory. We first present a simple mechanism for
  4211. counting integers by maintaining internal state, which is expressed
  4212. easily with closures:
  4213. (define (make-counter value)
  4214. (lambda ()
  4215. (let ((v value))
  4216. (set! value (+ v 1))
  4217. v)))
  4218. This has a problem: between obtaining the value of the closure's slot
  4219. for 'value' and updating that slot, another thread might be given
  4220. control and modify the counter, producing unpredictable results in
  4221. threads in the middle of working with the counter. To remedy this, we
  4222. might add a mutual exclusion lock to counters to prevent threads from
  4223. simultaneously accessing the cell:
  4224. (define (make-counter value)
  4225. (let ((lock (make-lock)))
  4226. (lambda ()
  4227. (dynamic-wind
  4228. (lambda () (obtain-lock lock))
  4229. (lambda ()
  4230. (let ((v value))
  4231. (set! value (+ v 1))
  4232. v))
  4233. (lambda () (release-lock lock))))))
  4234. This poses another problem, however. Suppose we wish to write an
  4235. atomic '(step-counters! COUNTER ...)' procedure that increments each of
  4236. the supplied counters by one; supplying a counter N times should have
  4237. the effect of incrementing it by N. The naïve definition of it is this:
  4238. (define (step-counters! . counters)
  4239. (for-each (lambda (counter) (counter))
  4240. counters))
  4241. Obviously, though, this is not atomic, because each individual
  4242. counter is locked when it is used, but not the whole iteration across
  4243. them. To work around this, we might use an obfuscated control structure
  4244. to allow nesting the locking of counters:
  4245. (define (make-counter value)
  4246. (let ((lock (make-lock)))
  4247. (lambda args
  4248. (dynamic-wind
  4249. (lambda () (obtain-lock lock))
  4250. (lambda ()
  4251. (if (null? args)
  4252. (let ((v value))
  4253. (set! value (+ v 1))
  4254. v)
  4255. ((car args))))
  4256. (lambda () (release-lock lock))))))
  4257. (define (step-counters! . counters)
  4258. (let loop ((cs counters))
  4259. (if (null? cs)
  4260. (for-each (lambda (counter) (counter))
  4261. counters)
  4262. ((car cs) (lambda () (loop (cdr cs)))))))
  4263. Aside from the obvious matter of the obfuscation of the control
  4264. structures used here, however, this has another problem: we cannot step
  4265. one counter multiple times atomically. Though different locks can be
  4266. nested, nesting is very dangerous, because accidentally obtaining a lock
  4267. that is already obtained can cause deadlock, and there is no modular,
  4268. transparent way to avoid this in the general case.
  4269. Instead, we can implement counters using optimistic concurrency to
  4270. synchronize the shared data. The state of counters is kept explicitly
  4271. in a cell (*note Cells::), in order to use a provisional accessor &
  4272. modifier, as is necessary to make use of optimistic concurrency, and we
  4273. surround with 'call-ensuring-atomicity' any regions we wish to be
  4274. atomic:
  4275. (define (make-counter initial)
  4276. (let ((cell (make-cell initial)))
  4277. (lambda ()
  4278. (call-ensuring-atomicity
  4279. (lambda ()
  4280. (let ((value (provisional-cell-ref cell)))
  4281. (provisional-cell-set! cell (+ value 1))
  4282. value))))))
  4283. (define (step-counters! . counters)
  4284. (call-ensuring-atomicity!
  4285. (lambda ()
  4286. (for-each (lambda (counter) (counter))
  4287. counters))))
  4288. This approach has a number of advantages:
  4289. * The original control structure is preserved, only with provisional
  4290. operators for shared memory access that we explicitly wish to be
  4291. synchronized and with 'call-ensuring-atomicity' wrapping the
  4292. portions of code that we explicitly want to be atomic.
  4293. * Composition of transactions is entirely transparent; it is
  4294. accomplished automatically simply by 'call-ensuring-atomicity'.
  4295. * Transactions can be nested arbitrarily deeply, and there is no
  4296. problem of accidentally locking the same resource again at a deeper
  4297. nesting level to induce deadlock.
  4298. * No explicit mutual exclusion or blocking is necessary. Threads
  4299. proceed without heed to others, but do not actually write data to
  4300. the shared memory until its validity is ensured. There is no
  4301. deadlock at all.
  4302. 5.2.5 Low-level optimistic concurrency
  4303. --------------------------------------
  4304. Along with the higher-level operations described above, there are some
  4305. lower-level primitives for finer control over optimistic concurrency.
  4306. -- procedure: make-proposal --> proposal
  4307. -- procedure: current-proposal --> proposal
  4308. -- procedure: set-current-proposal! proposal --> unspecified
  4309. -- procedure: remove-current-proposal! --> unspecified
  4310. 'Make-proposal' creates a fresh proposal. 'Current-proposal'
  4311. returns the current thread's proposal. 'Set-current-proposal!'
  4312. sets the current thread's proposal to PROPOSAL.
  4313. 'Remove-current-proposal!' sets the current thread's proposal to
  4314. '#f'.
  4315. -- procedure: maybe-commit --> boolean
  4316. -- procedure: invalidate-current-proposal! --> unspecified
  4317. 'Maybe-commit' checks that the current thread's proposal is still
  4318. valid. If it is, the proposal's writes are committed, and
  4319. 'maybe-commit' returns '#t'; if not, the current thread's proposal
  4320. is set to '#f' and 'maybe-commit' returns '#f'.
  4321. 'Invalidate-current-proposal!' causes an inconsistency in the
  4322. current proposal by caching a read and then directly writing to the
  4323. place that read was from.
  4324. -- syntax: with-new-proposal (lose) body --> values
  4325. Convenience for repeating a transaction. 'With-new-proposal' saves
  4326. the current proposal and will reinstates it when everything is
  4327. finished. After saving the current proposal, it binds LOSE to a
  4328. nullary procedure that installs a fresh proposal and that evaluates
  4329. BODY; it then calls LOSE. Typically, the last thing, or close to
  4330. last thing, that BODY will do is attempt to commit the current
  4331. proposal, and, if that fails, call LOSE to retry.
  4332. 'With-new-proposal' expands to a form that returns the values that
  4333. BODY returns.
  4334. This 'retry-at-most' example tries running the transaction of
  4335. THUNK, and, if it fails to commit, retries at most N times. If the
  4336. transaction is successfully committed before N repeated attempts,
  4337. it returns true; otherwise, it returns false.
  4338. (define (retry-at-most n thunk)
  4339. (with-new-proposal (lose)
  4340. (thunk)
  4341. (cond ((maybe-commit) #t)
  4342. ((zero? n) #f)
  4343. (else (set! n (- n 1))
  4344. (lose)))))
  4345. 
  4346. File: scheme48.info, Node: Higher-level synchronization, Next: Concurrent ML, Prev: Optimistic concurrency, Up: Multithreading
  4347. 5.3 Higher-level synchronization
  4348. ================================
  4349. This section details the various higher-level thread synchronization
  4350. devices that Scheme48 provides.
  4351. 5.3.1 Condition variables
  4352. -------------------------
  4353. "Condition variables" are multiple-assignment cells on which readers
  4354. block. Threads may wait on condition variables; when some other thread
  4355. assigns a condition variable, all threads waiting on it are revived.
  4356. The 'condvars' structure exports all of these condition-variable-related
  4357. names.
  4358. In many concurrency systems, condition variables are operated in
  4359. conjunction with mutual exclusion locks. On the other hand, in
  4360. Scheme48, they are used in conjunction with its optimistic concurrency
  4361. devices.
  4362. -- procedure: make-condvar [id] --> condvar
  4363. -- procedure: condvar? object --> boolean
  4364. Condition variable constructor & disjoint type predicate. ID is
  4365. used purely for debugging.
  4366. -- procedure: maybe-commit-and-wait-for-condvar condvar --> boolean
  4367. -- procedure: maybe-commit-and-set-condvar! condvar value --> boolean
  4368. 'Maybe-commit-and-wait-for-condvar' attempts to commit the current
  4369. proposal. If the commit succeeded, the current thread is blocked
  4370. on CONDVAR, and when the current thread is woken up,
  4371. 'maybe-commit-and-wait-for-condvar' returns '#t'. If the commit
  4372. did not succeed, 'maybe-commit-and-wait-for-condvar' immediately
  4373. returns '#f'. 'Maybe-commit-and-set-condvar!' attempts to commit
  4374. the current proposal as well. If it succeeds, it is noted that
  4375. CONDVAR has a value, CONDVAR's value is set to be VALUE, and all
  4376. threads waiting on CONDVAR are woken up.
  4377. *Note:* Do not use these in atomic transactions as delimited by
  4378. 'call-ensuring-atomicity' &c.; see the note in *note Optimistic
  4379. concurrency:: on this matter for details.
  4380. -- procedure: condvar-has-value? condvar --> boolean
  4381. -- procedure: condvar-value condvar --> value
  4382. 'Condvar-has-value?' tells whether or not CONDVAR has been
  4383. assigned. If it has been assigned, 'condvar-value' accesses the
  4384. value to which it was assigned.
  4385. -- procedure: set-condvar-has-value?! condvar boolean --> unspecified
  4386. -- procedure: set-condvar-value! condvar value --> unspecified
  4387. 'Set-condvar-has-value?!' is used to tell whether or not CONDVAR is
  4388. assigned. 'Set-condvar-value!' sets CONDVAR's value.
  4389. *Note:* 'Set-condvar-has-value?!' should be used only with a second
  4390. argument of '#f'. 'Set-condvar-value!' is a very dangerous
  4391. routine, and 'maybe-commit-and-set-condvar!' is what one should
  4392. almost always use, except if one wishes to clean up after
  4393. unassigning a condition variable.
  4394. 5.3.2 Placeholders
  4395. ------------------
  4396. "Placeholders" are similar to condition variables, except that they may
  4397. be assigned only once; they are in general a much simpler mechanism for
  4398. throw-away temporary synchronization devices. They are provided by the
  4399. 'placeholders' structure.
  4400. -- procedure: make-placeholder [id] --> placeholder
  4401. -- procedure: placeholder? object --> boolean
  4402. Placeholder constructor & disjoint type predicate. ID is used only
  4403. for debugging purposes when printing placeholders.
  4404. -- procedure: placeholder-value placeholder --> value
  4405. -- procedure: placeholder-set! placeholder value --> unspecified
  4406. 'Placeholder-value' blocks until PLACEHOLDER is assigned, at which
  4407. point it returns the value assigned. 'Placeholder-set!' assigns
  4408. PLACEHOLDER's value to VALUE, awakening all threads waiting for
  4409. PLACEHOLDER. It is an error to assign a placeholder with
  4410. 'placeholder-set!' that has already been assigned.
  4411. 5.3.3 Value pipes
  4412. -----------------
  4413. "Value pipes" are asynchronous communication pipes between threads. The
  4414. 'value-pipes' structure exports these value pipe operations.
  4415. -- procedure: make-pipe [size [id]] --> value-pipe
  4416. -- procedure: pipe? object --> boolean
  4417. 'Make-pipe' is the value pipe constructor. SIZE is a limit on the
  4418. number of elements the pipe can hold at one time. ID is used for
  4419. debugging purposes only in printing pipes. 'Pipe?' is the disjoint
  4420. type predicate for value pipes.
  4421. -- procedure: empty-pipe? pipe --> boolean
  4422. -- procedure: empty-pipe! pipe --> unspecified
  4423. 'Empty-pipe?' returns '#t' if PIPE has no elements in it and '#f'
  4424. if not. 'Empty-pipe!' removes all elements from 'pipe'.
  4425. -- procedure: pipe-read! pipe --> value
  4426. -- procedure: pipe-maybe-read! pipe --> value or '#f'
  4427. -- procedure: pipe-maybe-read?! pipe --> [boolean value]
  4428. 'Pipe-read!' reads a value from PIPE, removing it from the queue.
  4429. It blocks if there are no elements available in the queue.
  4430. 'Pipe-maybe-read!' attempts to read & return a single value from
  4431. PIPE; if no elements are available in its queue, it instead returns
  4432. '#f'. 'Pipe-maybe-read?!' does similarly, but it returns two
  4433. values: a boolean, signifying whether or not a value was read; and
  4434. the value, or '#f' if no value was read. 'Pipe-maybe-read?!' is
  4435. useful when PIPE may contain the value '#f'.
  4436. -- procedure: pipe-write! pipe value --> unspecified
  4437. -- procedure: pipe-push! pipe value --> unspecified
  4438. -- procedure: pipe-maybe-write! pipe value --> boolean
  4439. 'Pipe-write!' attempts to add VALUE to PIPE's queue. If PIPE's
  4440. maximum size, as passed to 'make-pipe' when constructing the pipe,
  4441. is either '#f' or greater than the number of elements in PIPE's
  4442. queue, 'pipe-write!' will not block; otherwise it will block until
  4443. a space has been made available in the pipe's queue by another
  4444. thread reading from it. 'Pipe-push!' does similarly, but, in the
  4445. case where the pipe is full, it pushes the first element to be read
  4446. out of the pipe. 'Pipe-maybe-write!' is also similar to
  4447. 'pipe-write!', but it returns '#t' if the pipe was not full, and it
  4448. _immediately_ returns '#f' if the pipe was full.
  4449. 
  4450. File: scheme48.info, Node: Concurrent ML, Next: Pessimistic concurrency, Prev: Higher-level synchronization, Up: Multithreading
  4451. 5.4 Concurrent ML
  4452. =================
  4453. Scheme48 provides a high-level event synchronization facility based on
  4454. on Reppy's "Concurrent ML" [Reppy 99]. The primary object in CML is the
  4455. "rendezvous"(1), which represents a point of process synchronization. A
  4456. rich library for manipulating rendezvous and several useful, high-level
  4457. synchronization abstractions are built atop rendezvous.
  4458. * Menu:
  4459. * Rendezvous concepts::
  4460. * Rendezvous base combinators::
  4461. * Rendezvous communication channels::
  4462. * Rendezvous-synchronized cells::
  4463. * Concurrent ML to Scheme correspondence::
  4464. ---------- Footnotes ----------
  4465. (1) In the original CML, these were called "events", but that term
  4466. was deemed too overloaded and confusing when Scheme48's library was
  4467. developed.
  4468. 
  4469. File: scheme48.info, Node: Rendezvous concepts, Next: Rendezvous base combinators, Up: Concurrent ML
  4470. 5.4.1 Rendezvous concepts
  4471. -------------------------
  4472. When access to a resource must be synchronized between multiple
  4473. processes, for example to transmit information from one process to
  4474. another over some sort of communication channel, the resource provides a
  4475. "rendezvous" to accomplish this, which represents a potential point of
  4476. synchronization between processes. The use of rendezvous occurs in two
  4477. stages: "synchronization" and "enablement". Note that creation of
  4478. rendezvous is an unrelated matter, and it does not (or should not)
  4479. itself result in any communication or synchronization between processes.
  4480. When a process requires an external resource for which it has a
  4481. rendezvous, it "synchronizes" that rendezvous. This first polls whether
  4482. the resource is immediately available; if so, the rendezvous is already
  4483. "enabled", and a value from the resource is immediately produced from
  4484. the synchronization. Otherwise, the synchronization of the rendezvous
  4485. is recorded somehow externally, and the process is blocked until the
  4486. rendezvous is enabled by an external entity, usually one that made the
  4487. resource available. Rendezvous may be reüsed arbitrarily many times;
  4488. the value produced by an enabled, synchronized rendezvous is not cached.
  4489. Note, however, that the construction of a rendezvous does not (or should
  4490. not) have destructive effect, such as sending a message to a remote
  4491. server or locking a mutex; the only destructive effects should be
  4492. incurred at synchronization or enablement time. For effecting
  4493. initialization prior to the synchronization of a rendezvous, see below
  4494. on "delayed rendezvous".
  4495. Rendezvous may consist of multiple rendezvous choices, any of which
  4496. may be taken when enabled but only one of which actually is. If, when a
  4497. composite rendezvous is initially synchronized, several components are
  4498. immediately enabled, each one has a particular numeric priority which is
  4499. used to choose among them. If several are tied for the highest
  4500. priority, a random one is chosen. If none is enabled when the choice is
  4501. synchronized, however, the synchronizer process is suspended until the
  4502. first one is enabled and revives the process. When this happens, any or
  4503. all of the other rendezvous components may receive a negative
  4504. acknowledgement; see below on "delayed rendezvous with negative
  4505. acknowledgement".
  4506. A rendezvous may also be a rendezvous "wrapped" with a procedure,
  4507. which means that, when the internal rendezvous becomes enabled, the
  4508. wrapper one also becomes enabled, and the value it produces is the
  4509. result of applying its procedure to the value that the internal
  4510. rendezvous produced. This allows the easy composition of complex
  4511. rendezvous from simpler ones, and it also provides a simple mechanism
  4512. for performing different actions following the enablement of different
  4513. rendezvous, rather than conflating the results of several possible
  4514. rendezvous choices into one value and operating on that (though this,
  4515. too, can be a useful operation).
  4516. 5.4.2 Delayed rendezvous
  4517. ------------------------
  4518. A rendezvous may be "delayed", which means that its synchronization
  4519. requires some processing that could not or would not be reasonable to
  4520. perform at its construction. It consists of a nullary procedure to
  4521. generate the actual rendezvous to synchronize when the delayed
  4522. rendezvous is itself synchronized.
  4523. For example, a rendezvous for generating unique identifiers, by
  4524. sending a request over a network to some server and waiting for a
  4525. response, could not be constructed by waiting for a response from the
  4526. server, because that may block, which should not occur until
  4527. synchronization. It also could not be constructed by first sending a
  4528. request to the server at all, because that would have a destructive
  4529. effect, which is not meant to happen when creating a rendezvous, only
  4530. when synchronizing or enabling one.
  4531. Instead, the unique identifier rendezvous would be implemented as a
  4532. delayed rendezvous that, when synchronized, would send a request to the
  4533. server and generate a rendezvous for the actual synchronization that
  4534. would become enabled on receiving the server's response.
  4535. 5.4.2.1 Negative acknowledgements
  4536. .................................
  4537. Delayed rendezvous may also receive negative acknowledgements. Rather
  4538. than a simple nullary procedure being used to generate the actual
  4539. rendezvous for synchronization, the procedure is unary, and it is passed
  4540. a "negative acknowledgement rendezvous", or "nack" for short. This nack
  4541. is enabled if the actual rendezvous was not chosen among a composite
  4542. group of rendezvous being synchronized. This allows not only delaying
  4543. initialization of rendezvous until necessary but also aborting or
  4544. rescinding initialized transactions if their rendezvous are unchosen and
  4545. therefore unused.
  4546. For example, a complex database query might be the object of some
  4547. rendezvous, but it is pointless to continue constructing the result if
  4548. that rendezvous is not chosen. A nack can be used to prematurely abort
  4549. the query to the database if another rendezvous was chosen in the stead
  4550. of that for the database query.
  4551. 
  4552. File: scheme48.info, Node: Rendezvous base combinators, Next: Rendezvous communication channels, Prev: Rendezvous concepts, Up: Concurrent ML
  4553. 5.4.3 Rendezvous combinators
  4554. ----------------------------
  4555. The 'rendezvous' structure exports several basic rendezvous combinators.
  4556. -- Constant: never-rv --> rendezvous
  4557. A rendezvous that is never enabled. If synchronized, this will
  4558. block the synchronizing thread indefinitely.
  4559. -- procedure: always-rv value --> rendezvous
  4560. Returns a rendezvous that is always enabled with the given value.
  4561. This rendezvous will never block the synchronizing thread.
  4562. -- procedure: guard rv-generator --> rendezvous
  4563. -- procedure: with-nack rv-generator --> rendezvous
  4564. 'Guard' returns a delayed rendezvous, generated by the given
  4565. procedure RV-GENERATOR, which is passed zero arguments whenever the
  4566. resultant rendezvous is synchronized. 'With-nack' returns a
  4567. delayed rendezvous for which a negative acknowledgement rendezvous
  4568. is constructed. If the resultant rendezvous is synchronized as a
  4569. part of a composite rendezvous, the procedure 'rv-generator' is
  4570. passed a nack for the synchronization, and it returns the
  4571. rendezvous to actually synchronize. If the delayed rendezvous was
  4572. synchronized as part of a composite group of rendezvous, and
  4573. another rendezvous among that group is enabled and chosen first,
  4574. the nack is enabled.
  4575. -- procedure: choose rendezvous ... --> composite-rendezvous
  4576. Returns a rendezvous that, when synchronized, synchronizes all of
  4577. the given components, and chooses only the first one to become
  4578. enabled, or the highest priority one if there are any that are
  4579. already enabled. If any of the rendezvous that were not chosen
  4580. when the composite became enabled were delayed rendezvous with
  4581. nacks, their nacks are enabled.
  4582. -- procedure: wrap rendezvous procedure --> rendezvous
  4583. Returns a rendezvous equivalent to RENDEZVOUS but wrapped with
  4584. PROCEDURE, so that, when the resultant rendezvous is synchronized,
  4585. RENDEZVOUS is transitively synchronized, and when RENDEZVOUS is
  4586. enabled, the resultant rendezvous is also enabled, with the value
  4587. that PROCEDURE returns when passed the value produced by
  4588. RENDEZVOUS.
  4589. (sync (wrap (always-rv 4)
  4590. (lambda (x) (* x x)))) --> 16
  4591. -- procedure: sync rendezvous --> value (may block)
  4592. -- procedure: select rendezvous ... --> value (may block)
  4593. 'Sync' and 'select' synchronize rendezvous. 'Sync' synchronizes a
  4594. single one; 'select' synchronizes any from the given set of them.
  4595. 'Select' is equivalent to '(sync (apply choose RENDEZVOUS ...))',
  4596. but it may be implemented more efficiently.
  4597. 5.4.3.1 Timing rendezvous
  4598. .........................
  4599. The 'rendezvous-time' structure exports two constructors for rendezvous
  4600. that become enabled only at a specific time or after a delay in time.
  4601. -- procedure: at-real-time-rv milliseconds --> rendezvous
  4602. -- procedure: after-time-rv milliseconds --> rendezvous
  4603. 'At-real-time-rv' returns a rendezvous that becomes enabled at the
  4604. time MILLISECONDS relative to the start of the Scheme program.
  4605. 'After-time-rv' returns a rendezvous that becomes enabled at least
  4606. MILLISECONDS after synchronization (_not_ construction).
  4607. 
  4608. File: scheme48.info, Node: Rendezvous communication channels, Next: Rendezvous-synchronized cells, Prev: Rendezvous base combinators, Up: Concurrent ML
  4609. 5.4.4 Rendezvous communication channels
  4610. ---------------------------------------
  4611. 5.4.4.1 Synchronous channels
  4612. ............................
  4613. The 'rendezvous-channels' structure provides a facility for "synchronous
  4614. channels": channels for communication between threads such that any
  4615. receiver blocks until another thread sends a message, or any sender
  4616. blocks until another thread receives the sent message. In CML,
  4617. synchronous channels are also called merely 'channels.'
  4618. -- procedure: make-channel --> channel
  4619. -- procedure: channel? object --> boolean
  4620. 'Make-channel' creates and returns a new channel. 'Channel?' is
  4621. the disjoint type predicate for channels.
  4622. -- procedure: send-rv channel message --> rendezvous
  4623. -- procedure: send channel message --> unspecified (may block)
  4624. 'Send-rv' returns a rendezvous that, when synchronized, becomes
  4625. enabled when a reception rendezvous for CHANNEL is synchronized, at
  4626. which point that reception rendezvous is enabled with a value of
  4627. MESSAGE. When enabled, the rendezvous returned by 'send-rv'
  4628. produces an unspecified value. 'Send' is like 'send-rv', but it
  4629. has the effect of immediately synchronizing the rendezvous, so it
  4630. therefore may block, and it does not return a rendezvous; '(send
  4631. CHANNEL MESSAGE)' is equivalent to '(sync (send-rv CHANNEL
  4632. MESSAGE))'.
  4633. -- procedure: receive-rv channel --> rendezvous
  4634. -- procedure: receive channel --> value (may block)
  4635. 'Receive-rv' returns a rendezvous that, when synchronized, and when
  4636. a sender rendezvous for CHANNEL with some message is synchronized,
  4637. becomes enabled with that message, at which point the sender
  4638. rendezvous is enabled with an unspecified value. 'Receive' is like
  4639. 'receive-rv', but it has the effect of immediately synchronizing
  4640. the reception rendezvous, so it therefore may block, and it does
  4641. not return the rendezvous but rather the message that was sent;
  4642. '(receive CHANNEL)' is equivalent to '(sync (receive-rv CHANNEL))'.
  4643. 5.4.4.2 Asynchronous channels
  4644. .............................
  4645. The 'rendezvous-async-channels' provides an "asynchronous channel"(1)
  4646. facility. Like synchronous channels, any attempts to read from an
  4647. asynchronous channel will block if there are no messages waiting to be
  4648. read. Unlike synchronous channels, however, sending a message will
  4649. never block. Instead, a queue of messages or a queue of recipients is
  4650. maintained: if a message is sent and there is a waiting recipient, the
  4651. message is delivered to that recipient; otherwise it is added to the
  4652. queue of messages. If a thread attempts to receive a message from an
  4653. asynchronous channel and there is a pending message, it receives that
  4654. message; otherwise it adds itself to the list of waiting recipients and
  4655. then blocks.
  4656. *Note:* Operations on synchronous channels from the structure
  4657. 'rendezvous-channels' do not work on asynchronous channels.
  4658. -- procedure: make-async-channel --> async-channel
  4659. -- procedure: async-channel? obj --> boolean
  4660. 'Make-async-channel' creates and returns an asynchronous channel.
  4661. 'Async-channel?' is the disjoint type predicate for asynchronous
  4662. channels.
  4663. -- procedure: receive-async-rv channel --> rendezvous
  4664. -- procedure: receive-async channel --> value (may block)
  4665. 'Receive-async-rv' returns a rendezvous that, when synchronized,
  4666. becomes enabled when a message is available in CHANNEL's queue of
  4667. messages. 'Receive-async' has the effect of immediately
  4668. synchronizing such a rendezvous and, when the rendezvous becomes
  4669. enabled, returning the value itself, rather than the rendezvous;
  4670. '(receive-async CHANNEL)' is equivalent to '(sync (receive-async-rv
  4671. CHANNEL))'.
  4672. -- procedure: send-async channel message --> unspecified
  4673. Sends a message to the asynchronous channel CHANNEL. Unlike the
  4674. synchronous channel 'send' operation, this procedure never blocks
  4675. arbitrarily long.(2) There is, therefore, no need for a
  4676. 'send-async-rv' like the 'send-rv' for synchronous channels. If
  4677. there is a waiting message recipient, the message is delivered to
  4678. that recipient; otherwise, it is added to the channel's message
  4679. queue.
  4680. ---------- Footnotes ----------
  4681. (1) Known as "mailboxes" in Reppy's original CML.
  4682. (2) However, asynchronous channels are implemented by a thread that
  4683. manages two synchronous channels (one for sends & one for receives), so
  4684. this may block briefly if the thread is busy receiving other send or
  4685. receive requests.
  4686. 
  4687. File: scheme48.info, Node: Rendezvous-synchronized cells, Next: Concurrent ML to Scheme correspondence, Prev: Rendezvous communication channels, Up: Concurrent ML
  4688. 5.4.5 Rendezvous-synchronized cells
  4689. -----------------------------------
  4690. 5.4.5.1 Placeholders: single-assignment cells
  4691. .............................................
  4692. "Placeholders"(1) are single-assignment cells on which readers block
  4693. until they are assigned.
  4694. *Note:* These placeholders are disjoint from and incompatible with
  4695. the placeholder mechanism provided in the 'placeholders' structure, and
  4696. attempts to apply operations on one to values of the other are errors.
  4697. -- procedure: make-placeholder [id] --> empty placeholder
  4698. -- procedure: placeholder? object --> boolean
  4699. 'Make-placeholder' creates and returns a new, empty placeholder.
  4700. ID is used only for debugging purposes; it is included in the
  4701. printed representation of the placeholder. 'Placeholder?' is the
  4702. disjoint type predicate for placeholders.
  4703. -- procedure: placeholder-value-rv placeholder --> rendezvous
  4704. -- procedure: placeholder-value placeholder --> value (may block)
  4705. 'Placeholder-value-rv' returns a rendezvous that, when
  4706. synchronized, becomes enabled when PLACEHOLDER has a value, with
  4707. that value. 'Placeholder-value' has the effect of immediately
  4708. synchronizing such a rendezvous, and it returns the value directly,
  4709. but possibly after blocking.
  4710. -- procedure: placeholder-set! placeholder value --> unspecified
  4711. Sets PLACEHOLDER's value to be VALUE, and enables all rendezvous
  4712. for PLACEHOLDER's value with that value. It is an error if
  4713. PLACEHOLDER has already been assigned.
  4714. 5.4.5.2 Jars: multiple-assignment cells
  4715. .......................................
  4716. "Jars"(2) are multiple-assignment cells on which readers block. Reading
  4717. from a full jar has the effect of emptying it, enabling the possibility
  4718. of subsequent assignment, unlike placeholders; and jars may be assigned
  4719. multiple times, but, like placeholders, only jars that are empty may be
  4720. assigned.
  4721. -- procedure: make-jar [id] --> empty jar
  4722. -- procedure: jar? object --> boolean
  4723. 'Make-jar' creates and returns a new, empty jar. ID is used only
  4724. for debugging purposes; it is included in the printed
  4725. representation of the jar. 'Jar?' is the disjoint type predicate
  4726. for jars.
  4727. -- procedure: jar-take-rv jar --> rendezvous
  4728. -- procedure: jar-take jar --> value (may block)
  4729. 'Jar-take-rv' returns a rendezvous that, when synchronized, becomes
  4730. enabled when JAR has a value, which is what value the rendezvous
  4731. becomes enabled with; when that rendezvous is enabled, it also
  4732. removes the value from JAR, putting the jar into an empty state.
  4733. 'Jar-take' has the effect of synchronizing such a rendezvous, may
  4734. block because of that, and returns the value of the jar directly,
  4735. not a rendezvous.
  4736. -- procedure: jar-put! jar value --> unspecified
  4737. 'Jar-put!' puts VALUE into the empty jar JAR. If any taker
  4738. rendezvous are waiting, the first is enabled with the value, and
  4739. the jar is returned to its empty state; otherwise, the jar is put
  4740. in the full state. 'Jar-put!' is an error if applied to a full
  4741. jar.
  4742. ---------- Footnotes ----------
  4743. (1) Called "I-variables" in Reppy's CML, and "I-structures" in ID-90.
  4744. (2) Termed "M-variables" in Reppy's CML.
  4745. 
  4746. File: scheme48.info, Node: Concurrent ML to Scheme correspondence, Prev: Rendezvous-synchronized cells, Up: Concurrent ML
  4747. 5.4.6 Concurrent ML to Scheme correspondence
  4748. --------------------------------------------
  4749. CML name Scheme name
  4750. structure 'CML' structure 'threads'
  4751. 'version' (no equivalent)
  4752. 'banner' (no equivalent)
  4753. 'spawnc' (no equivalent; use 'spawn' and 'lambda')
  4754. 'spawn' 'spawn'
  4755. 'yield' 'relinquish-timeslice'
  4756. 'exit' 'terminate-current-thread'
  4757. 'getTid' 'current-thread'
  4758. 'sameTid' 'eq?' (R5RS)
  4759. 'tidToString' (no equivalent; use the writer)
  4760. structure 'threads-internal'
  4761. 'hashTid' 'thread-uid'
  4762. structure 'rendezvous'
  4763. 'wrap' 'wrap'
  4764. 'guard' 'guard'
  4765. 'withNack' 'with-nack'
  4766. 'choose' 'choose'
  4767. 'sync' 'sync'
  4768. 'select' 'select'
  4769. 'never' 'never-rv'
  4770. 'alwaysEvt' 'always-rv'
  4771. 'joinEvt' (no equivalent)
  4772. structure 'rendezvous-channels'
  4773. 'channel' 'make-channel'
  4774. 'sameChannel' 'eq?' (R5RS)
  4775. 'send' 'send'
  4776. 'recv' 'receive'
  4777. 'sendEvt' 'send-rv'
  4778. 'recvEvt' 'receive-rv'
  4779. 'sendPoll' (no equivalent)
  4780. 'recvPoll' (no equivalent)
  4781. structure 'rendezvous-time'
  4782. 'timeOutEvt' 'after-time-rv'
  4783. 'atTimeEvt' 'at-real-time-rv'
  4784. structure 'SyncVar' structure 'rendezvous-placeholders'
  4785. exception 'Put' (no equivalent)
  4786. 'iVar' 'make-placeholder'
  4787. 'iPut' 'placeholder-set!'
  4788. 'iGet' 'placeholder-value'
  4789. 'iGetEvt' 'placeholder-value-rv'
  4790. 'iGetPoll' (no equivalent)
  4791. 'sameIVar' 'eq?' (R5RS)
  4792. structure 'jars'
  4793. 'mVar' 'make-jar'
  4794. 'mVarInit' (no equivalent)
  4795. 'mPut' 'jar-put!'
  4796. 'mTake' 'jar-take'
  4797. 'mTakeEvt' 'jar-take-rv'
  4798. 'mGet' (no equivalent)
  4799. 'mGetEvt' (no equivalent)
  4800. 'mTakePoll' (no equivalent)
  4801. 'mGetPoll' (no equivalent)
  4802. 'mSwap' (no equivalent)
  4803. 'mSwapEvt' (no equivalent)
  4804. 'sameMVar' 'eq?' (R5RS)
  4805. structure 'Mailbox' structure 'rendezvous-async-channels'
  4806. 'mailbox' 'make-async-channel'
  4807. 'sameMailbox' 'eq?' (R5RS)
  4808. 'send' 'send-async'
  4809. 'recv' 'receive-async'
  4810. 'recvEvt' 'receive-async-rv'
  4811. 'recvPoll' (no equivalent)
  4812. 
  4813. File: scheme48.info, Node: Pessimistic concurrency, Next: Custom thread synchronization, Prev: Concurrent ML, Up: Multithreading
  4814. 5.5 Pessimistic concurrency
  4815. ===========================
  4816. While Scheme48's primitive thread synchronization mechanisms revolve
  4817. around optimistic concurrency, Scheme48 still provides the more
  4818. well-known mechanism of pessimistic concurrency, or mutual exclusion,
  4819. with locks. Note that Scheme48's pessimistic concurrency facilities are
  4820. discouraged, and very little of the system uses them (at the time this
  4821. documentation was written, none of the system uses locks), and the
  4822. pessimistic concurrency libraries are limited to just locks; condition
  4823. variables are integrated only with optimistic concurrency. Except for
  4824. inherent applications of pessimistic concurrency, it is usually better
  4825. to use optimistic concurrency in Scheme48.
  4826. These names are exported by the 'locks' structure.
  4827. -- procedure: make-lock --> lock
  4828. -- procedure: lock? --> boolean
  4829. -- procedure: obtain-lock lock --> unspecified
  4830. -- procedure: maybe-obtain-lock lock --> boolean
  4831. -- procedure: release-lock lock --> unspecified
  4832. 'Make-lock' creates a new lock in the 'released' lock state.
  4833. 'Lock?' is the disjoint type predicate for locks. 'Obtain-lock'
  4834. atomically checks to see if LOCK is in the 'released' state: if it
  4835. is, LOCK is put into the 'obtained' lock state; otherwise,
  4836. 'obtain-lock' waits until LOCK is ready to be obtained, at which
  4837. point it is put into the 'obtained' lock state.
  4838. 'Maybe-obtain-lock' atomically checks to see if LOCK is in the
  4839. 'released' state: if it is, LOCK is put into the 'obtained' lock
  4840. state, and 'maybe-obtain-lock' returns '#t'; if it is in the
  4841. 'obtained' state, 'maybe-obtain-lock' immediately returns '#f'.
  4842. 'Release-lock' sets LOCK's state to be 'released,' letting the next
  4843. thread waiting to obtain it do so.
  4844. 
  4845. File: scheme48.info, Node: Custom thread synchronization, Prev: Pessimistic concurrency, Up: Multithreading
  4846. 5.6 Custom thread synchronization
  4847. =================================
  4848. Along with several useful thread synchronization abstraction facilities
  4849. built-in to Scheme48, there is also a simple and lower-level mechanism
  4850. for suspending & resuming threads. The following bindings are exported
  4851. from the 'threads-internal' structure.
  4852. Threads have a field for a cell (*note Cells::) that is used when the
  4853. thread is suspended. When it is ready to run, it is simply '#f'.
  4854. Suspending a thread involves setting its cell to a cell accessible
  4855. outside, so the thread can later be awoken. When the thread is awoken,
  4856. its cell field and the contents of the cell are both set to '#f'.
  4857. Often, objects involved in the synchronization of threads will have a
  4858. queue (*note Queues::) of thread cells. There are two specialized
  4859. operations on thread cell queues that simplify filtering out cells of
  4860. threads that have already been awoken.
  4861. -- procedure: maybe-commit-and-block cell --> boolean
  4862. -- procedure: maybe-commit-and-block-on-queue --> boolean
  4863. These attempt to commit the current proposal. If the commit fails,
  4864. they immediately return '#f'. Otherwise, they suspend the current
  4865. thread. 'Maybe-commit-and-block' first sets the current thread's
  4866. cell to CELL, which should contain the current thread.
  4867. 'Maybe-commit-and-block-on-queue' adds a cell containing the
  4868. current thread to QUEUE first. When the current thread is finally
  4869. resumed, these return '#t'.
  4870. -- procedure: maybe-commit-and-make-ready thread-or-queue --> boolean
  4871. Attempts to commit the current proposal. If the commit fails, this
  4872. returns '#f'. Otherwise, 'maybe-commit-and-make-ready' awakens the
  4873. specified thread[s] by clearing the thread/each thread's cell and
  4874. sending a message to the relevant scheduler[s] and returns '#t'.
  4875. If THREAD-OR-QUEUE is a thread, it simply awakens that; if it is a
  4876. queue, it empties the queue and awakens each thread in it.
  4877. -- procedure: maybe-dequeue-thread! thread-cell-queue --> thread or
  4878. boolean
  4879. -- procedure: thread-queue-empty? thread-cell-queue --> boolean
  4880. 'Maybe-dequeue-thread!' returns the next thread cell's contents in
  4881. the queue of thread cells THREAD-CELL-QUEUE. It removes cells that
  4882. have been emptied, i.e. whose threads have already been awoken.
  4883. 'Thread-queue-empty?' returns '#t' if there are no cells in
  4884. THREAD-CELL-QUEUE that contain threads, i.e. threads that are still
  4885. suspended. It too removes cells that have been emptied.
  4886. For example, the definition of placeholders (*note Higher-level
  4887. synchronization::) is presented here. Placeholders contain two fields:
  4888. the cached value (set when the placeholder is set) & a queue of threads
  4889. waiting (set to '#f' when the placeholder is assigned).
  4890. (define-synchronized-record-type placeholder :placeholder
  4891. (really-make-placeholder queue)
  4892. (value queue) ; synchronized fields
  4893. placeholder?
  4894. (queue placeholder-queue set-placeholder-queue!)
  4895. (value placeholder-real-value set-placeholder-value!))
  4896. (define (make-placeholder)
  4897. (really-make-placeholder (make-queue)))
  4898. (define (placeholder-value placeholder)
  4899. ;; Set up a new proposal for the transaction.
  4900. (with-new-proposal (lose)
  4901. (cond ((placeholder-queue placeholder)
  4902. ;; There's a queue of waiters. Attempt to commit the
  4903. ;; proposal and block. We'll be added to the queue if the
  4904. ;; commit succeeds; if it fails, retry.
  4905. => (lambda (queue)
  4906. (or (maybe-commit-and-block-on-queue queue)
  4907. (lose))))))
  4908. ;; Once our thread has been awoken, the placeholder will be set.
  4909. (placeholder-real-value placeholder))
  4910. (define (placeholder-set! placeholder value)
  4911. ;; Set up a new proposal for the transaction.
  4912. (with-new-proposal (lose)
  4913. (cond ((placeholder-queue placeholder)
  4914. => (lambda (queue)
  4915. ;; Clear the queue, set the value field.
  4916. (set-placeholder-queue! placeholder #f)
  4917. (set-placeholder-value! placeholder value)
  4918. ;; Attempt to commit our changes and awaken all of the
  4919. ;; waiting threads. If the commit fails, retry.
  4920. (if (not (maybe-commit-and-make-ready queue))
  4921. (lose))))
  4922. (else
  4923. ;; Someone assigned it first. Since placeholders are
  4924. ;; single-assignment cells, this is an error.
  4925. (error "placeholder is already assigned"
  4926. placeholder
  4927. (placeholder-real-value placeholder))))))
  4928. 
  4929. File: scheme48.info, Node: Libraries, Next: C interface, Prev: Multithreading, Up: Top
  4930. 6 Libraries
  4931. ***********
  4932. This chapter details a number of useful libraries built-in to Scheme48.
  4933. * Menu:
  4934. * Boxed bitwise-integer masks::
  4935. * Enumerated/finite types and sets::
  4936. * Macros for writing loops::
  4937. * Library data structures::
  4938. * I/O extensions::
  4939. * TCP & UDP sockets::
  4940. * Common-Lisp-style formatting::
  4941. * Library utilities::
  4942. 
  4943. File: scheme48.info, Node: Boxed bitwise-integer masks, Next: Enumerated/finite types and sets, Up: Libraries
  4944. 6.1 Boxed bitwise-integer masks
  4945. ===============================
  4946. Scheme48 provides a facility for generalized boxed bitwise-integer
  4947. masks. Masks represent sets of elements. An element is any arbitrary
  4948. object that represents an index into a bit mask; mask types are
  4949. parameterized by an isomorphism between elements and their integer
  4950. indices. Usual abstract set operations are available on masks. The
  4951. mask facility is divided into two parts: the 'mask-types' structure,
  4952. which provides the operations on the generalized mask type descriptors;
  4953. and the 'masks' structure, for the operations on masks themselves.
  4954. 6.1.1 Mask types
  4955. ----------------
  4956. -- procedure: make-mask-type name elt? index->elt elt->index size -->
  4957. mask-type
  4958. -- procedure: mask-type? object --> boolean
  4959. -- procedure: mask? object --> boolean
  4960. 'Make-mask-type' constructs a mask type with the given name.
  4961. Elements of this mask type must satisfy the predicate ELT?.
  4962. INTEGER->ELT is a unary procedure that maps bit mask indices to
  4963. possible set elements; ELT->INTEGER maps possible set elements to
  4964. bit mask indices. SIZE is the number of possible elements of masks
  4965. of the new type, i.e. the number of bits needed to represent the
  4966. internal bit mask. 'Mask?' is the disjoint type predicate for mask
  4967. objects.
  4968. -- procedure: mask-type mask --> mask-type
  4969. -- procedure: mask-has-type? mask type --> boolean
  4970. 'Mask-type' returns MASK's type. 'Mask-has-type?' returns '#t' if
  4971. MASK's type is the mask type TYPE or '#f' if not.
  4972. The 'mask-types' structure, not the 'masks' structure, exports
  4973. 'mask?' and 'mask-has-type?': it is expected that programmers who
  4974. implement mask types will define type predicates for masks of their type
  4975. based on 'mask?' and 'mask-has-type?', along with constructors &c. for
  4976. their masks.
  4977. -- procedure: integer->mask type integer --> mask
  4978. -- procedure: list->mask type elts --> mask
  4979. 'Integer->mask' returns a mask of type TYPE that contains all the
  4980. possible elements E of the type TYPE such that the bit at E's index
  4981. is set. 'List->mask' returns a mask whose type is TYPE containing
  4982. all of the elements in the list ELTS.
  4983. 6.1.2 Masks
  4984. -----------
  4985. -- procedure: mask->integer mask --> integer
  4986. -- procedure: mask->list mask --> element-list
  4987. 'Mask->integer' returns the integer bit set that MASK uses to
  4988. represent the element set. 'Mask->list' returns a list of all the
  4989. elements that MASK contains.
  4990. -- procedure: mask-member? mask elt --> boolean
  4991. -- procedure: mask-set mask elt ... --> mask
  4992. -- procedure: mask-clear mask elt ... --> mask
  4993. 'Mask-member?' returns true if ELT is a member of the mask MASK, or
  4994. '#f' if not. 'Mask-set' returns a mask with all the elements in
  4995. MASK as well as each ELT .... 'Mask-clear' returns a mask with all
  4996. the elements in MASK but with none of ELT ....
  4997. -- procedure: mask-union mask_{1} mask_{2} ... --> mask
  4998. -- procedure: mask-intersection mask_{1} mask_{2} ... --> mask
  4999. -- procedure: mask-subtract mask--_{a} mask--_{b} --> mask
  5000. -- procedure: mask-negate mask --> mask
  5001. Set operations on masks. 'Mask-union' returns a mask containing
  5002. every element that is a member of any one of its arguments.
  5003. 'Mask-intersection' returns a mask containing every element that is
  5004. a member of every one of its arguments. 'Mask-subtract' returns a
  5005. mask of every element that is in MASK-_{A} but not also in
  5006. MASK-_{B}. 'Mask-negate' returns a mask whose members are every
  5007. possible element of MASK's type that is not in MASK.
  5008. 
  5009. File: scheme48.info, Node: Enumerated/finite types and sets, Next: Macros for writing loops, Prev: Boxed bitwise-integer masks, Up: Libraries
  5010. 6.2 Enumerated/finite types and sets
  5011. ====================================
  5012. (This section was derived from work copyrighted (C) 1993-2005 by Richard
  5013. Kelsey, Jonathan Rees, and Mike Sperber.)
  5014. The structure 'finite-types' has two macros for defining "finite" or
  5015. "enumerated record types". These are record types for which there is a
  5016. fixed set of instances, all of which are created at the same time as the
  5017. record type itself. Also, the structure 'enum-sets' has several
  5018. utilities for building sets of the instances of those types, although it
  5019. is generalized beyond the built-in enumerated/finite type device. There
  5020. is considerable overlap between the boxed bitwise-integer mask library
  5021. (*note Boxed bitwise-integer masks::) and the enumerated set facility.
  5022. 6.2.1 Enumerated/finite types
  5023. -----------------------------
  5024. -- syntax: define-enumerated-type
  5025. (define-enumerated-type DISPATCHER TYPE
  5026. PREDICATE
  5027. INSTANCE-VECTOR
  5028. NAME-ACCESSOR
  5029. INDEX-ACCESSOR
  5030. (INSTANCE-NAME
  5031. ...))
  5032. This defines a new record type, to which TYPE is bound, with as
  5033. many instances as there are INSTANCE-NAMEs. PREDICATE is defined
  5034. to be the record type's predicate. INSTANCE-VECTOR is defined to
  5035. be a vector containing the instances of the type in the same order
  5036. as the INSTANCE-NAME list. DISPATCHER is defined to be a macro of
  5037. the form (DISPATCHER INSTANCE-NAME); it evaluates to the instance
  5038. with the given name, which is resolved at macro-expansion time.
  5039. NAME-ACCESSOR & INDEX-ACCESSOR are defined to be unary procedures
  5040. that return the symbolic name & index into the instance vector,
  5041. respectively, of the new record type's instances.
  5042. For example,
  5043. (define-enumerated-type colour :colour
  5044. colour?
  5045. colours
  5046. colour-name
  5047. colour-index
  5048. (black white purple maroon))
  5049. (colour-name (vector-ref colours 0)) => black
  5050. (colour-name (colour white)) => white
  5051. (colour-index (colour purple)) => 2
  5052. -- syntax: define-finite-type
  5053. (define-finite-type DISPATCHER TYPE
  5054. (FIELD-TAG ...)
  5055. PREDICATE
  5056. INSTANCE-VECTOR
  5057. NAME-ACCESSOR
  5058. INDEX-ACCESSOR
  5059. (FIELD-TAG ACCESSOR [MODIFIER])
  5060. ...
  5061. ((INSTANCE-NAME FIELD-VALUE ...)
  5062. ...))
  5063. This is like 'define-enumerated-type', but the instances can also
  5064. have added fields beyond the name and the accessor. The first list
  5065. of field tags lists the fields that each instance is constructed
  5066. with, and each instance is constructed by applying the unnamed
  5067. constructor to the initial field values listed. Fields not listed
  5068. in the first field tag list must be assigned later.
  5069. For example,
  5070. (define-finite-type colour :colour
  5071. (red green blue)
  5072. colour?
  5073. colours
  5074. colour-name
  5075. colour-index
  5076. (red colour-red)
  5077. (green colour-green)
  5078. (blue colour-blue)
  5079. ((black 0 0 0)
  5080. (white 255 255 255)
  5081. (purple 160 32 240)
  5082. (maroon 176 48 96)))
  5083. (colour-name (colour black)) => black
  5084. (colour-name (vector-ref colours 1)) => white
  5085. (colour-index (colour purple)) => 2
  5086. (colour-red (colour maroon)) => 176
  5087. 6.2.2 Sets over enumerated types
  5088. --------------------------------
  5089. -- syntax: define-enum-set-type
  5090. (define-enum-set-type SET-SYNTAX TYPE
  5091. PREDICATE
  5092. LIST->X-SET
  5093. ELEMENT-SYNTAX
  5094. ELEMENT-PREDICATE
  5095. ELEMENT-VECTOR
  5096. ELEMENT-INDEX)
  5097. This defines SET-SYNTAX to be a syntax for constructing sets, TYPE
  5098. to be an object that represents the type of enumerated sets,
  5099. PREDICATE to be a predicate for those sets, and LIST->X-SET to be a
  5100. procedure that converts a list of elements into a set of the new
  5101. type.
  5102. ELEMENT-SYNTAX must be the name of a macro for constructing set
  5103. elements from names (akin to the DISPATCHER argument to the
  5104. 'define-enumerated-type' & 'define-finite-type' forms).
  5105. ELEMENT-PREDICATE must be a predicate for the element type,
  5106. ELEMENT-VECTOR a vector of all values of the element type, and
  5107. ELEMENT-INDEX a procedure that returns the index of an element
  5108. within ELEMENT-VECTOR.
  5109. -- procedure: enum-set->list enum-set --> element list
  5110. -- procedure: enum-set-member? enum-set element --> boolean
  5111. -- procedure: enum-set=? enum-set--_{a} enum-set--_{b} --> boolean
  5112. -- procedure: enum-set-union enum-set--_{a} enum-set--_{b} --> enum-set
  5113. -- procedure: enum-set-intersection enum-set--_{a} enum-set--_{b} -->
  5114. enum-set
  5115. -- procedure: enum-set-negation enum-set --> enum-set
  5116. 'Enum-set->list' returns a list of elements within ENUM-SET.
  5117. 'Enum-set-member?' tests whether ELEMENT is a member of ENUM-SET.
  5118. 'Enum-set=?' tests whether two enumerated sets are equal, i.e.
  5119. contain all the same elements. The other procedures perform
  5120. standard set algebra operations on enumerated sets. It is an error
  5121. to pass an element that does not satisfy ENUM-SET's predicate to
  5122. 'enum-set-member?' or to pass two enumerated sets of different
  5123. types to 'enum-set=?' or the enumerated set algebra operators.
  5124. Here is a simple example of enumerated sets built atop the enumerated
  5125. types described in the previous section:
  5126. (define-enumerated-type colour :colour
  5127. colour?
  5128. colours
  5129. colour-name
  5130. colour-index
  5131. (red blue green))
  5132. (define-enum-set-type colour-set :colour-set
  5133. colour-set?
  5134. list->colour-set
  5135. colour colour? colours colour-index)
  5136. (enum-set->list (colour-set red blue))
  5137. => (#{Colour red} #{Colour blue})
  5138. (enum-set->list (enum-set-negation (colour-set red blue)))
  5139. => (#{Colour green})
  5140. (enum-set-member? (colour-set red blue) (colour blue))
  5141. => #t
  5142. 
  5143. File: scheme48.info, Node: Macros for writing loops, Next: Library data structures, Prev: Enumerated/finite types and sets, Up: Libraries
  5144. 6.3 Macros for writing loops
  5145. ============================
  5146. (This section was derived from work copyrighted (C) 1993-2005 by Richard
  5147. Kelsey, Jonathan Rees, and Mike Sperber.)
  5148. 'Iterate' & 'reduce' are extensions of named-'let' for writing loops
  5149. that walk down one or more sequences, such as the elements of a list or
  5150. vector, the characters read from a port, or an arithmetic series.
  5151. Additional sequences can be defined by the user. 'Iterate' & 'reduce'
  5152. are exported by the structure 'reduce'.
  5153. * Menu:
  5154. * Main looping macros::
  5155. * Sequence types::
  5156. * Synchronous sequences::
  5157. * Examples::
  5158. * Defining sequence types::
  5159. * Loop macro expansion::
  5160. 
  5161. File: scheme48.info, Node: Main looping macros, Next: Sequence types, Up: Macros for writing loops
  5162. 6.3.1 Main looping macros
  5163. -------------------------
  5164. -- syntax: iterate
  5165. (iterate LOOP-NAME ((SEQ-TYPE ELT-VAR ARG ...)
  5166. ...)
  5167. ((STATE-VAR INIT)
  5168. ...)
  5169. BODY
  5170. [TAIL-EXP])
  5171. 'Iterate' steps the ELT-VARs in parallel through the sequences,
  5172. while each STATE-VAR has the corresponding INIT for the first
  5173. iteration and later values supplied by the body. If any sequence
  5174. has reached the limit, the value of the 'iterate' expression is the
  5175. value of TAIL-EXP, if present, or the current values of the
  5176. STATE-VARs, returned as multiple values. If no sequence has
  5177. reached its limit, BODY is evaluated and either calls LOOP-NAME
  5178. with new values for the STATE-VARs or returns some other value(s).
  5179. The LOOP-NAME and the STATE-VARs & INITs behave exactly as in
  5180. named-'let', in that LOOP-NAME is bound only in the scope of BODY,
  5181. and each INIT is evaluated parallel in the enclosing scope of the
  5182. whole expression. Also, the arguments to the sequence constructors
  5183. will be evaluated in the enclosing scope of the whole expression,
  5184. or in an extension of that scope peculiar to the sequence type.
  5185. The named-'let' expression
  5186. (let LOOP-NAME ((STATE-VAR INIT) ...)
  5187. BODY
  5188. ...)
  5189. is equivalent to an iterate expression with no sequences (and with
  5190. an explicit 'let' wrapped around the body expressions to take care
  5191. of any internal definitions):
  5192. (iterate LOOP-NAME ()
  5193. ((STATE-VAR INIT) ...)
  5194. (let () BODY ...))
  5195. The SEQ-TYPEs are keywords (actually, macros of a particular form,
  5196. which makes it easy to add additional types of sequences; see
  5197. below). Examples are 'list*', which walks down the elements of a
  5198. list, and 'vector*', which does the same for vectors. For each
  5199. iteration, each ELT-VAR is bound to the next element of the
  5200. sequence. The ARGs are supplied to the sequence processors as
  5201. other inputs, such as the list or vector to walk down.
  5202. If there is a TAIL-EXP, it is evaluated when the end of one or more
  5203. sequences is reached. If the body does not call LOOP-NAME,
  5204. however, the TAIL-EXP is not evaluated. Unlike named-'let', the
  5205. behaviour of a non-tail-recursive call to LOOP-NAME is unspecified,
  5206. because iterating down a sequence may involve side effects, such as
  5207. reading characters from a port.
  5208. -- syntax: reduce
  5209. (reduce ((SEQ-TYPE ELT-VAR ARG ...)
  5210. ...)
  5211. ((STATE-VAR INIT)
  5212. ...)
  5213. BODY
  5214. [TAIL-EXP])
  5215. If an 'iterate' expression is not meant to terminate before a
  5216. sequence has reached its end, the body will always end with a tail
  5217. call to LOOP-NAME. 'Reduce' is a convenient macro that makes this
  5218. common case explicit. The syntax of 'reduce' is the same as that
  5219. of 'iterate', except that there is no LOOP-NAME, and the body
  5220. updates the state variables by returning multiple values in the
  5221. stead of passing the new values to LOOP-NAME: the body must return
  5222. as many values as there are state variables. By special
  5223. dispension, if there are no state variables, then the body may
  5224. return any number of values, all of which are ignored.
  5225. The value(s) returned by an instance of 'reduce' is (are) the
  5226. value(s) returned by the TAIL-EXP, if present, or the current
  5227. value(s) of the state variables when the end of one or more
  5228. sequences is reached.
  5229. A 'reduce' expression can be rewritten as an equivalent 'iterate'
  5230. expression by adding a LOOP-NAME and a wrapper for the body that
  5231. calls the LOOP-NAME:
  5232. (iterate loop ((SEQ-TYPE ELT-VAR ARG ...)
  5233. ...)
  5234. ((STATE-VAR INIT)
  5235. ...)
  5236. (call-with-values (lambda () BODY)
  5237. loop)
  5238. [TAIL-EXP])
  5239. 
  5240. File: scheme48.info, Node: Sequence types, Next: Synchronous sequences, Prev: Main looping macros, Up: Macros for writing loops
  5241. 6.3.2 Sequence types
  5242. --------------------
  5243. -- sequence type: list* elt-var list
  5244. -- sequence type: vector* elt-var vector
  5245. -- sequence type: string* elt-var string
  5246. -- sequence type: count* elt-var start [end [step]]
  5247. -- sequence type: input* elt-var input-port reader-proc
  5248. -- sequence type: stream* elt-var proc initial-seed
  5249. For lists, vectors, & strings, the ELT-VAR is bound to the
  5250. successive elements of the list or vector, or the successive
  5251. characters of the string.
  5252. For 'count*', the ELT-VAR is bound to the elements of the sequence
  5253. 'start, start + step, start + 2*step, ..., end', inclusive of START
  5254. and exclusive of END. The default STEP is '1', and the sequence
  5255. does not terminate if no END is given or if there is no N > 0 such
  5256. that END = START + NSTEP. ('=' is used to test for termination.)
  5257. For example, '(count* i 0 -1)' does not terminate because it begins
  5258. past the END value, and '(count* i 0 1 2)' does not terminate
  5259. because it skips over the END value.
  5260. For 'input*', the elements are the results of successive
  5261. applications of READER-PROC to INPUT-PORT. The sequence ends when
  5262. the READER-PROC returns an end-of-file object, i.e. a value that
  5263. satisfies 'eof-object?'.
  5264. For 'stream*', the PROC receives the current seed as an argument
  5265. and must return two values, the next value of the sequence & the
  5266. next seed. If the new seed is '#f', then the previous element was
  5267. the last one. For example, '(list* elt list)' is the same as
  5268. (stream* elt
  5269. (lambda (list)
  5270. (if (null? list)
  5271. (values 'ignored #f)
  5272. (values (car list) (cdr list))))
  5273. list)
  5274. 
  5275. File: scheme48.info, Node: Synchronous sequences, Next: Examples, Prev: Sequence types, Up: Macros for writing loops
  5276. 6.3.3 Synchronous sequences
  5277. ---------------------------
  5278. When using the sequence types described above, a loop terminates when
  5279. any of its sequences terminate. To help detect bugs, it is useful to
  5280. also have sequence types that check whether two or more sequences end on
  5281. the same iteration. For this purpose, there is a second set of sequence
  5282. types called "synchronous sequences". Synchronous sequences are like
  5283. ordinary asynchronous sequences in every respect except that they cause
  5284. an error to be signalled if a loop is terminated by a synchronous
  5285. sequence and some other synchronous sequence did not reach its end on
  5286. the same iteration.
  5287. Sequences are checked for termination in order from left to right,
  5288. and if a loop is terminated by an asynchronous sequence no further
  5289. checking is done.
  5290. -- synchronous sequence type: list% elt-var list
  5291. -- synchronous sequence type: vector% elt-var vector
  5292. -- synchronous sequence type: string% elt-var string
  5293. -- synchronous sequence type: count% elt-var start end [step]
  5294. -- synchronous sequence type: input% elt-var input-port reader-proc
  5295. -- synchronous sequence type: stream% elt-var proc initial-seed
  5296. These are all identical to their asynchronous equivalents above,
  5297. except that they are synchronous. Note that 'count%''s END
  5298. argument is required, unlike 'count*''s, because it would be
  5299. nonsensical to check for termination of a sequence that does not
  5300. terminate.
  5301. 
  5302. File: scheme48.info, Node: Examples, Next: Defining sequence types, Prev: Synchronous sequences, Up: Macros for writing loops
  5303. 6.3.4 Examples
  5304. --------------
  5305. Gathering the indices of list elements that answer true to some
  5306. predicate.
  5307. (define (select-matching-items list pred)
  5308. (reduce ((list* elt list)
  5309. (count* i 0))
  5310. ((hits '()))
  5311. (if (pred elt)
  5312. (cons i hits)
  5313. hits)
  5314. (reverse hits)))
  5315. Finding the index of an element of a list that satisfies a predicate.
  5316. (define (find-matching-item list pred)
  5317. (iterate loop ((list* elt list)
  5318. (count* i 0))
  5319. () ; no state variables
  5320. (if (pred elt)
  5321. i
  5322. (loop))))
  5323. Reading one line of text from an input port.
  5324. (define (read-line port)
  5325. (iterate loop ((input* c port read-char))
  5326. ((chars '()))
  5327. (if (char=? c #\newline)
  5328. (list->string (reverse chars))
  5329. (loop (cons c chars)))
  5330. (if (null? chars)
  5331. (eof-object) ; from the PRIMITIVES structure
  5332. (list->string (reverse chars)))))
  5333. Counting the lines in a file. This must be written in a way other
  5334. than with 'count*' because it needs the value of the count after the
  5335. loop has finished, but the count variable would not be bound then.
  5336. (define (line-count filename)
  5337. (call-with-input-file filename
  5338. (lambda (inport)
  5339. (reduce ((input* line inport read-line))
  5340. ((count 0))
  5341. (+ count 1)))))
  5342. 
  5343. File: scheme48.info, Node: Defining sequence types, Next: Loop macro expansion, Prev: Examples, Up: Macros for writing loops
  5344. 6.3.5 Defining sequence types
  5345. -----------------------------
  5346. The sequence types are object-oriented macros similar to enumerations.
  5347. An asynchronous sequence macro needs to supply three values: '#f' to
  5348. indicate that it is not synchronous, a list of state variables and their
  5349. initializers, and the code for one iteration. The first two methods are
  5350. written in continuation-passing style: they take another macro and
  5351. argument to which to pass their result. See [Friedman 00] for more
  5352. details on the theory behind how CPS macros work. The 'sync' method
  5353. receives no extra arguments. The 'state-vars' method is passed a list
  5354. of names that will be bound to the arguments of the sequence. The final
  5355. method, for stepping the sequence forward, is passed the list of names
  5356. bound to the arguments and the list of state variables. In addition,
  5357. there is a variable to be bound to the next element of the sequence, the
  5358. body expression for the loop, and an expression for terminating the
  5359. loop.
  5360. As an example, the definition of 'list*' is:
  5361. (define-syntax list*
  5362. (syntax-rules (SYNC STATE-VARS STEP)
  5363. ((LIST* SYNC (next more))
  5364. (next #F more))
  5365. ((LIST* STATE-VARS (start-list) (next more))
  5366. (next ((list-var start-list)) more))
  5367. ((LIST* STEP (start-list) (list-var) value-var loop-body tail-exp)
  5368. (IF (NULL? list-var)
  5369. tail-exp
  5370. (LET ((value-var (CAR list-var))
  5371. (list-var (CDR list-var)))
  5372. loop-body)))))
  5373. Synchronized sequences are similar, except that they need to provide
  5374. a termination test to be used when some other synchronized method
  5375. terminates the loop. To continue the example:
  5376. (define-syntax list%
  5377. (syntax-rules (SYNC DONE)
  5378. ((LIST% SYNC (next more))
  5379. (next #T more))
  5380. ((LIST% DONE (start-list) (list-var))
  5381. (NULL? list-var))
  5382. ((LIST% . anything-else)
  5383. (LIST* . anything-else))))
  5384. 
  5385. File: scheme48.info, Node: Loop macro expansion, Prev: Defining sequence types, Up: Macros for writing loops
  5386. 6.3.6 Loop macro expansion
  5387. --------------------------
  5388. Here is an example of the expansion of the 'reduce' macro:
  5389. (reduce ((list* x '(1 2 3)))
  5390. ((r '()))
  5391. (cons x r))
  5392. ==>
  5393. (let ((final (lambda (r) (values r)))
  5394. (list '(1 2 3))
  5395. (r '()))
  5396. (let loop ((list list) (r r))
  5397. (if (null? list)
  5398. (final r)
  5399. (let ((x (car list))
  5400. (list (cdr list)))
  5401. (let ((continue (lambda (r)
  5402. (loop list r))))
  5403. (continue (cons x r)))))))
  5404. The only mild inefficiencies in this code are the 'final' &
  5405. 'continue' procedures, both of which could trivially be substituted
  5406. in-line. The macro expander could easily perform the substitution for
  5407. 'continue' when there is no explicit proceed variable, as in this case,
  5408. but not in general.
  5409. 
  5410. File: scheme48.info, Node: Library data structures, Next: I/O extensions, Prev: Macros for writing loops, Up: Libraries
  5411. 6.4 Library data structures
  5412. ===========================
  5413. Scheme48 includes several libraries for a variety of data structures.
  5414. 6.4.1 Multi-dimensional arrays
  5415. ------------------------------
  5416. The 'arrays' structure exports a facility for multi-dimensional arrays,
  5417. based on Alan Bawden's interface.
  5418. -- procedure: make-array value dimension ... --> array
  5419. -- procedure: array dimensions element ... --> array
  5420. -- procedure: copy-array array ... --> array
  5421. Array constructors. 'Make-array' constructs an array with the
  5422. given dimensions, each of which must be an exact, non-negative
  5423. integer, and fills all of the elements with VALUE. 'Array' creates
  5424. an array with the given list of dimensions, which must be a list of
  5425. exact, non-negative integers, and fills it with the given elements
  5426. in row-major order. The number of elements must be equal to the
  5427. product of DIMENSIONS. 'Copy-array' constructs an array with the
  5428. same dimensions and contents as ARRAY.
  5429. -- procedure: array? object --> boolean
  5430. Disjoint type predicate for arrays.
  5431. -- procedure: array-shape array --> integer-list
  5432. Returns the list of dimensions of ARRAY.
  5433. -- procedure: array-ref array index ... --> value
  5434. -- procedure: array-set! array value index ... --> unspecified
  5435. Array element dereferencing and assignment. Each INDEX must be in
  5436. the half-open interval [0,D), where D is the respective dimension
  5437. of ARRAY corresponding with that index.
  5438. -- procedure: array->vector array --> vector
  5439. Creates a vector of the elements in ARRAY in row-major order.
  5440. -- procedure: make-shared-array array linear-map dimension ... -->
  5441. array
  5442. Creates a new array that shares storage with ARRAY and uses the
  5443. procedure LINEAR-MAP to map indices in the new array to indices in
  5444. ARRAY. LINEAR-MAP must accept as many arguments as DIMENSION ...,
  5445. each of which must be an exact, non-negative integer; and must
  5446. return a list of exact, non-negative integers equal in length to
  5447. the number of dimensions of ARRAY, and which must be valid indices
  5448. into ARRAY.
  5449. 6.4.2 Red/black search trees
  5450. ----------------------------
  5451. Along with hash tables for general object maps, Scheme48 also provides
  5452. red/black binary search trees generalized across key equality comparison
  5453. & ordering functions, as opposed to key equality comparison & hash
  5454. functions with hash tables. These names are exported by the
  5455. 'search-trees' structure.
  5456. -- procedure: make-search-tree key= key< --> search-tree
  5457. -- procedure: search-tree? object --> boolean
  5458. 'Make-search-tree' creates a new search tree with the given key
  5459. equality comparison & ordering functions. 'Search-tree?' is the
  5460. disjoint type predicate for red/black binary search trees.
  5461. -- procedure: search-tree-ref search-tree key --> value or '#f'
  5462. -- procedure: search-tree-set! search-tree key value --> unspecified
  5463. -- procedure: search-tree-modify! search-tree key modifier -->
  5464. unspecified
  5465. 'Search-tree-ref' returns the value associated with KEY in
  5466. SEARCH-TREE, or '#f' if no such association exists.
  5467. 'Search-tree-set!' assigns the value of an existing association in
  5468. SEARCH-TREE for KEY to be VALUE, if the association already exists;
  5469. or, if not, it creates a new association with the given key and
  5470. value. If VALUE is '#f', however, any association is removed.
  5471. 'Search-tree-modify!' modifies the association in SEARCH-TREE for
  5472. KEY by applying MODIFIER to the previous value of the association.
  5473. If no association previously existed, one is created whose key is
  5474. KEY and whose value is the result of applying MODIFIER to '#f'. If
  5475. MODIFIER returns '#f', the association is removed. This is
  5476. equivalent to '(search-tree-set! SEARCH-TREE KEY (MODIFIER
  5477. (search-tree-ref SEARCH-TREE KEY)))', but it is implemented more
  5478. efficiently.
  5479. -- procedure: search-tree-max search-tree --> value or '#f'
  5480. -- procedure: search-tree-min search-tree --> value or '#f'
  5481. -- procedure: pop-search-tree-max! search-tree --> value or '#f'
  5482. -- procedure: pop-search-tree-min! search-tree --> value or '#f'
  5483. These all return two values: the key & value for the association in
  5484. SEARCH-TREE whose key is the maximum or minimum of the tree.
  5485. 'Search-tree-max' and 'search-tree-min' do not remove the
  5486. association from SEARCH-TREE; 'pop-search-tree-max!' and
  5487. 'pop-search-tree-min!' do. If SEARCH-TREE is empty, these all
  5488. return the two values '#f' and '#f'.
  5489. -- procedure: walk-search-tree proc search-tree --> unspecified
  5490. This applies PROC to two arguments, the key & value, for every
  5491. association in SEARCH-TREE.
  5492. 6.4.3 Sparse vectors
  5493. --------------------
  5494. Sparse vectors, exported by the structure 'sparse-vectors', are vectors
  5495. that grow as large as necessary without leaving large, empty spaces in
  5496. the vector. They are implemented as trees of subvectors.
  5497. -- procedure: make-sparse-vector --> sparse-vector
  5498. Sparse vector constructor.
  5499. -- procedure: sparse-vector-ref sparse-vector index --> value or '#f'
  5500. -- procedure: sparse-vector-set! sparse-vector index value -->
  5501. unspecified
  5502. Sparse vector element accessor and modifier. In the case of
  5503. 'sparse-vector-ref', if INDEX is beyond the highest index that was
  5504. inserted into SPARSE-VECTOR, it returns '#f'; if
  5505. 'sparse-vector-set!' is passed an index beyond what was already
  5506. assigned, it simply extends the vector.
  5507. -- procedure: sparse-vector->list sparse-vector --> list
  5508. Creates a list of the elements in SPARSE-VECTOR. Elements that
  5509. uninitialized gaps comprise are denoted by '#f' in the list.
  5510. 
  5511. File: scheme48.info, Node: I/O extensions, Next: TCP & UDP sockets, Prev: Library data structures, Up: Libraries
  5512. 6.5 I/O extensions
  5513. ==================
  5514. These facilities are all exported from the 'extended-ports' structure.
  5515. Tracking ports track the line & column number that they are on.
  5516. -- procedure: make-tracking-input-port sub-port --> input-port
  5517. -- procedure: make-tracking-output-port sub-port --> output-port
  5518. Tracking port constructors. These simply create wrapper ports
  5519. around SUB-PORT that track the line & column numbers.
  5520. -- procedure: current-row port --> integer or '#f'
  5521. -- procedure: current-column port --> integer or '#f'
  5522. Accessors for line (row) & column number information. If PORT is a
  5523. not a tracking port, these simply return '#f'.
  5524. -- procedure: fresh-line port --> unspecified
  5525. This writes a newline to port with 'newline', unless it can be
  5526. determined that the previous character was a newline -- that is, if
  5527. '(current-column PORT)' does not evaluate to zero.
  5528. These are ports based on procedures that produce and consume single
  5529. characters at a time.
  5530. -- procedure: char-source->input-port char-producer [readiness-tester
  5531. closer] --> input-port
  5532. -- procedure: char-sink->output-port char-consumer --> output-port
  5533. 'Char-source->input-port' creates an input port that calls
  5534. CHAR-PRODUCER with zero arguments when a character is read from it.
  5535. If READINESS-TESTER is present, it is used for the 'char-ready?'
  5536. operation on the resulting port; likewise with CLOSER and
  5537. 'close-input-port'. 'Char-sink->output-port' creates an output
  5538. port that calls CHAR-CONSUMER for every character written to it.
  5539. Scheme48 also provides ports that collect and produce output to and
  5540. from strings.
  5541. -- procedure: make-string-input-port string --> input-port
  5542. Constructs an input port whose contents are read from STRING.
  5543. -- procedure: make-string-output-port --> output-port
  5544. -- procedure: string-output-port-output string-port --> string
  5545. -- procedure: call-with-string-output-port receiver --> string
  5546. 'Make-string-output-port' makes an output port that collects its
  5547. output in a string. 'String-output-port-output' returns the string
  5548. that STRING-PORT collected. 'Call-with-string-output-port' creates
  5549. a string output port, applies RECEIVER to it, and returns the
  5550. string that the string output port collected.
  5551. Finally, there is a facility for writing only a limited quantity of
  5552. output to a given port.
  5553. -- procedure: limit-output port count receiver --> unspecified
  5554. 'Limit-output' applies RECEIVER to a port that will write at most
  5555. COUNT characters to PORT.
  5556. 
  5557. File: scheme48.info, Node: TCP & UDP sockets, Next: Common-Lisp-style formatting, Prev: I/O extensions, Up: Libraries
  5558. 6.6 TCP & UDP sockets
  5559. =====================
  5560. Scheme48 provides a simple facility for TCP & UDP sockets. Both the
  5561. structures 'sockets' and 'udp-sockets' export several general
  5562. socket-related procedures:
  5563. -- procedure: close-socket socket --> unspecified
  5564. -- procedure: socket-port-number socket --> integer
  5565. -- procedure: get-host-name --> string
  5566. 'Close-socket' closes SOCKET, which may be any type of socket.
  5567. 'Socket-port-number' returns the port number through which SOCKET
  5568. is communicating. 'Get-host-name' returns the network name of the
  5569. current machine.
  5570. *Note:* Programmers should be wary of storing the result of a call
  5571. to 'get-host-name' in a dumped heap image, because the actual
  5572. machine's host name may vary from invocation to invocation of the
  5573. Scheme48 VM on that image, since heap images may be resumed on
  5574. multiple different machines.
  5575. 6.6.1 TCP sockets
  5576. -----------------
  5577. The 'sockets' structure provides simple TCP socket facilities.
  5578. -- procedure: open-socket [port-number] --> socket
  5579. -- procedure: socket-accept socket --> [input-port output-port]
  5580. The server interface. 'Open-socket' creates a socket that listens
  5581. on PORT-NUMBER, which defaults to a random number above 1024.
  5582. 'Socket-accept' blocks until there is a client waiting to be
  5583. accepted, at which point it returns two values: an input port & an
  5584. output port to send & receive data to & from the client.
  5585. -- procedure: socket-client host-name port-number --> [input-port
  5586. output-port]
  5587. Connects to the server at PORT-NUMBER denoted by the machine name
  5588. HOST-NAME and returns an input port and an output port for sending
  5589. & receiving data to & from the server. 'Socket-client' blocks the
  5590. current thread until the server accepts the connection request.
  5591. 6.6.2 UDP sockets
  5592. -----------------
  5593. The 'udp-sockets' structure defines a UDP socket facility.
  5594. -- procedure: open-udp-socket [port-number] --> socket
  5595. Opens a UDP socket on PORT-NUMBER, or a random port number if none
  5596. was passed. 'Open-udp-socket' returns two values: an input UDP
  5597. socket and an output UDP socket.
  5598. -- procedure: udp-send socket address buffer count --> count-sent
  5599. -- procedure: udp-receive socket buffer --> [count-received
  5600. remote-address]
  5601. 'Udp-send' attempts to send COUNT elements from the string or byte
  5602. vector BUFFER from the output UDP socket SOCKET to the UDP address
  5603. ADDRESS, and returns the number of octets it successfully sent.
  5604. 'Udp-receive' receives a UDP message from SOCKET, reading it into
  5605. BUFFER destructively. It returns two values: the number of octets
  5606. read into BUFFER and the address whence the octets came.
  5607. -- procedure: lookup-udp-address name port --> udp-address
  5608. -- procedure: udp-address? object --> boolean
  5609. -- procedure: udp-address-address address --> c-byte-vector
  5610. -- procedure: udp-address-port address --> port-number
  5611. -- procedure: udp-address-hostname address --> string-address
  5612. 'Lookup-udp-address' returns a UDP address for the machine name
  5613. NAME at the port number PORT. 'Udp-address?' is the disjoint type
  5614. predicate for UDP addresses. 'Udp-address-address' returns a byte
  5615. vector that contains the C representation of ADDRESS, suitable for
  5616. passing to C with Scheme48's C FFI. 'Udp-address-port' returns the
  5617. port number of ADDRESS. 'Udp-address-hostname' returns a string
  5618. representation of the IP address of ADDRESS.